From 74ac431d87468a8f6f5b62b014867679e2c254c2 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Tue, 9 Dec 2025 15:02:22 +0000
Subject: [PATCH v1] Mark function arguments of type "T *" as "const T *" where
 possible

Several functions in the codebase accept "T *" parameters but do not modify
the pointed-to data.  These have been updated to take "const T *" instead,
improving type safety, making the interfaces clearer about their intent and may
enable additional optimizations.

This change helps the compiler catch accidental modifications and better documents
immutability of arguments.

This commit is the same idea as 8a27d418f8f but for any type of pointers.

To avoid any risks:

- cases that produce -Wdiscarded-qualifiers warnings have been discarded as
they would need more investigation.

- double pointers are excluded to keep the changes straightforward.

- cases that produce new -Wcast-qual warnings have been discarded.

As in 8a27d418f8f, no functional behavior is changed.
---
 contrib/bloom/blinsert.c                      |  2 +-
 contrib/dblink/dblink.c                       | 23 ++++--
 contrib/file_fdw/file_fdw.c                   |  8 +-
 contrib/fuzzystrmatch/dmetaphone.c            | 10 +--
 contrib/fuzzystrmatch/fuzzystrmatch.c         |  4 +-
 contrib/intarray/_int_bool.c                  |  2 +-
 contrib/isn/isn.c                             |  6 +-
 contrib/jsonb_plpython/jsonb_plpython.c       |  2 +-
 contrib/ltree/lquery_op.c                     |  2 +-
 contrib/pg_trgm/trgm_op.c                     |  8 +-
 contrib/pg_trgm/trgm_regexp.c                 | 19 +++--
 contrib/pg_walinspect/pg_walinspect.c         |  4 +-
 contrib/pgcrypto/pgp-info.c                   |  2 +-
 contrib/pgcrypto/pgp-pgsql.c                  |  2 +-
 contrib/pgcrypto/pgp-pubdec.c                 |  2 +-
 contrib/pgcrypto/pgp-pubkey.c                 |  4 +-
 contrib/seg/seg.c                             |  4 +-
 contrib/test_decoding/test_decoding.c         | 11 ++-
 contrib/xml2/xpath.c                          |  4 +-
 src/backend/access/brin/brin.c                |  6 +-
 src/backend/access/brin/brin_bloom.c          |  2 +-
 src/backend/access/brin/brin_tuple.c          |  7 +-
 src/backend/access/common/attmap.c            |  4 +-
 src/backend/access/common/printtup.c          |  2 +-
 src/backend/access/common/reloptions.c        |  4 +-
 src/backend/access/gin/ginentrypage.c         |  4 +-
 src/backend/access/gin/ginfast.c              |  2 +-
 src/backend/access/gin/ginscan.c              |  2 +-
 src/backend/access/gist/gistbuild.c           |  9 ++-
 src/backend/access/gist/gistproc.c            |  6 +-
 src/backend/access/gist/gistsplit.c           |  2 +-
 src/backend/access/hash/hashsearch.c          |  4 +-
 src/backend/access/heap/heapam.c              |  7 +-
 src/backend/access/heap/pruneheap.c           | 16 ++--
 src/backend/access/heap/vacuumlazy.c          |  8 +-
 src/backend/access/nbtree/nbtinsert.c         |  4 +-
 src/backend/access/nbtree/nbtreadpage.c       | 10 ++-
 src/backend/access/nbtree/nbtsort.c           |  4 +-
 src/backend/access/nbtree/nbtsplitloc.c       |  4 +-
 src/backend/access/rmgrdesc/xactdesc.c        |  7 +-
 src/backend/access/spgist/spgdoinsert.c       |  5 +-
 src/backend/access/spgist/spgkdtreeproc.c     |  2 +-
 src/backend/access/spgist/spgproc.c           |  2 +-
 src/backend/access/spgist/spgquadtreeproc.c   |  2 +-
 src/backend/access/spgist/spgscan.c           |  7 +-
 src/backend/access/spgist/spgutils.c          |  2 +-
 src/backend/access/transam/commit_ts.c        |  6 +-
 src/backend/access/transam/multixact.c        |  6 +-
 src/backend/access/transam/xlog.c             |  7 +-
 src/backend/access/transam/xlogprefetcher.c   |  4 +-
 src/backend/backup/backup_manifest.c          |  2 +-
 src/backend/backup/basebackup_copy.c          |  4 +-
 src/backend/catalog/aclchk.c                  | 20 ++---
 src/backend/catalog/dependency.c              | 11 +--
 src/backend/catalog/heap.c                    |  5 +-
 src/backend/catalog/namespace.c               |  2 +-
 src/backend/catalog/pg_enum.c                 |  5 +-
 src/backend/catalog/pg_publication.c          |  2 +-
 src/backend/commands/analyze.c                | 15 ++--
 src/backend/commands/cluster.c                |  4 +-
 src/backend/commands/copyfrom.c               | 15 ++--
 src/backend/commands/copyto.c                 |  5 +-
 src/backend/commands/createas.c               |  4 +-
 src/backend/commands/dropcmds.c               |  4 +-
 src/backend/commands/extension.c              |  8 +-
 src/backend/commands/foreigncmds.c            |  8 +-
 src/backend/commands/functioncmds.c           |  4 +-
 src/backend/commands/opclasscmds.c            | 28 ++++---
 src/backend/commands/prepare.c                |  4 +-
 src/backend/commands/sequence.c               |  5 +-
 src/backend/commands/statscmds.c              |  4 +-
 src/backend/commands/subscriptioncmds.c       | 26 ++++---
 src/backend/commands/trigger.c                | 17 +++--
 src/backend/commands/tsearchcmds.c            |  2 +-
 src/backend/commands/user.c                   |  4 +-
 src/backend/commands/vacuumparallel.c         |  7 +-
 src/backend/commands/view.c                   |  2 +-
 src/backend/executor/execCurrent.c            |  5 +-
 src/backend/executor/execExprInterp.c         | 49 +++++++-----
 src/backend/executor/execGrouping.c           | 11 ++-
 src/backend/executor/execParallel.c           |  8 +-
 src/backend/executor/execPartition.c          |  9 ++-
 src/backend/executor/execReplication.c        |  4 +-
 src/backend/executor/execTuples.c             |  2 +-
 src/backend/executor/execUtils.c              |  5 +-
 src/backend/executor/functions.c              | 12 +--
 src/backend/executor/instrument.c             |  4 +-
 src/backend/executor/nodeAgg.c                | 20 ++---
 src/backend/executor/nodeGatherMerge.c        |  9 ++-
 src/backend/executor/nodeIncrementalSort.c    |  3 +-
 src/backend/executor/nodeIndexonlyscan.c      |  5 +-
 src/backend/executor/nodeIndexscan.c          |  4 +-
 src/backend/executor/nodeLimit.c              |  4 +-
 src/backend/executor/nodeMemoize.c            | 12 +--
 src/backend/executor/nodeMergejoin.c          | 20 ++---
 src/backend/executor/nodeModifyTable.c        | 19 +++--
 src/backend/executor/nodeSetOp.c              |  4 +-
 src/backend/executor/nodeSubplan.c            |  2 +-
 src/backend/executor/nodeWindowAgg.c          |  8 +-
 src/backend/executor/nodeWorktablescan.c      |  4 +-
 src/backend/executor/spi.c                    |  4 +-
 src/backend/jit/llvm/llvmjit_expr.c           |  5 +-
 src/backend/lib/bipartite_match.c             |  4 +-
 src/backend/lib/dshash.c                      |  4 +-
 src/backend/lib/integerset.c                  | 15 ++--
 src/backend/lib/pairingheap.c                 |  2 +-
 src/backend/lib/rbtree.c                      |  2 +-
 src/backend/libpq/auth-scram.c                |  4 +-
 src/backend/libpq/auth.c                      |  2 +-
 src/backend/nodes/nodeFuncs.c                 |  4 +-
 src/backend/nodes/tidbitmap.c                 |  2 +-
 src/backend/optimizer/geqo/geqo_erx.c         | 10 ++-
 src/backend/optimizer/geqo/geqo_misc.c        |  2 +-
 src/backend/optimizer/path/costsize.c         | 29 ++++----
 src/backend/optimizer/path/equivclass.c       | 27 ++++---
 src/backend/optimizer/path/indxpath.c         | 46 ++++++------
 src/backend/optimizer/path/joinpath.c         | 11 +--
 src/backend/optimizer/path/pathkeys.c         | 31 ++++----
 src/backend/optimizer/path/tidpath.c          | 12 +--
 src/backend/optimizer/plan/analyzejoins.c     | 35 +++++----
 src/backend/optimizer/plan/createplan.c       | 57 +++++++-------
 src/backend/optimizer/plan/initsplan.c        | 22 +++---
 src/backend/optimizer/plan/planagg.c          |  4 +-
 src/backend/optimizer/plan/planner.c          | 74 ++++++++++---------
 src/backend/optimizer/plan/subselect.c        | 18 +++--
 src/backend/optimizer/prep/prepagg.c          |  8 +-
 src/backend/optimizer/prep/prepqual.c         |  8 +-
 src/backend/optimizer/prep/prepunion.c        | 31 ++++----
 src/backend/optimizer/util/clauses.c          | 13 ++--
 src/backend/optimizer/util/inherit.c          |  4 +-
 src/backend/optimizer/util/pathnode.c         |  9 ++-
 src/backend/optimizer/util/plancat.c          |  5 +-
 src/backend/optimizer/util/relnode.c          | 44 ++++++-----
 src/backend/optimizer/util/tlist.c            |  6 +-
 src/backend/parser/analyze.c                  | 10 ++-
 src/backend/parser/parse_collate.c            |  4 +-
 src/backend/parser/parse_expr.c               | 40 ++++++----
 src/backend/parser/parse_func.c               | 11 ++-
 src/backend/parser/parse_merge.c              | 10 ++-
 src/backend/parser/parse_relation.c           | 16 ++--
 src/backend/parser/parse_utilcmd.c            | 17 +++--
 src/backend/partitioning/partbounds.c         | 65 +++++++++-------
 src/backend/postmaster/autovacuum.c           |  4 +-
 src/backend/postmaster/postmaster.c           |  4 +-
 src/backend/regex/regprefix.c                 |  4 +-
 .../libpqwalreceiver/libpqwalreceiver.c       |  4 +-
 src/backend/replication/logical/launcher.c    |  2 +-
 src/backend/replication/logical/relation.c    | 11 ++-
 .../replication/logical/reorderbuffer.c       | 19 ++---
 .../replication/logical/sequencesync.c        |  2 +-
 src/backend/replication/logical/slotsync.c    |  3 +-
 src/backend/replication/logical/snapbuild.c   |  5 +-
 src/backend/replication/logical/tablesync.c   |  2 +-
 src/backend/replication/logical/worker.c      | 23 +++---
 src/backend/replication/pgoutput/pgoutput.c   | 16 ++--
 src/backend/replication/slot.c                |  2 +-
 src/backend/replication/syncrep.c             |  8 +-
 src/backend/replication/walsender.c           |  2 +-
 src/backend/rewrite/rewriteDefine.c           |  5 +-
 src/backend/rewrite/rowsecurity.c             | 16 ++--
 src/backend/statistics/dependencies.c         | 19 +++--
 src/backend/statistics/mvdistinct.c           | 11 ++-
 src/backend/storage/aio/aio.c                 |  5 +-
 src/backend/storage/aio/read_stream.c         |  2 +-
 src/backend/storage/buffer/bufmgr.c           |  6 +-
 src/backend/storage/ipc/procarray.c           |  4 +-
 src/backend/storage/ipc/waiteventset.c        | 16 ++--
 src/backend/storage/lmgr/lock.c               |  5 +-
 src/backend/storage/lmgr/lwlock.c             |  4 +-
 src/backend/tcop/fastpath.c                   |  5 +-
 src/backend/tcop/postgres.c                   |  8 +-
 src/backend/tsearch/dict_thesaurus.c          | 18 +++--
 src/backend/tsearch/ts_parse.c                |  2 +-
 src/backend/tsearch/wparser_def.c             |  6 +-
 src/backend/utils/activity/pgstat_backend.c   |  4 +-
 src/backend/utils/adt/array_userfuncs.c       |  4 +-
 src/backend/utils/adt/arrayfuncs.c            |  5 +-
 src/backend/utils/adt/ascii.c                 |  5 +-
 src/backend/utils/adt/date.c                  |  2 +-
 src/backend/utils/adt/formatting.c            | 10 ++-
 src/backend/utils/adt/geo_spgist.c            | 22 +++---
 src/backend/utils/adt/jsonb.c                 |  5 +-
 src/backend/utils/adt/jsonb_util.c            | 42 +++++++----
 src/backend/utils/adt/jsonfuncs.c             | 29 +++++---
 src/backend/utils/adt/jsonpath_exec.c         | 26 ++++---
 .../utils/adt/multirangetypes_selfuncs.c      |  5 +-
 src/backend/utils/adt/network_gist.c          |  3 +-
 src/backend/utils/adt/network_selfuncs.c      | 34 ++++++---
 src/backend/utils/adt/numeric.c               |  6 +-
 src/backend/utils/adt/pg_locale.c             |  2 +-
 src/backend/utils/adt/pgstatfuncs.c           |  2 +-
 src/backend/utils/adt/rangetypes.c            |  4 +-
 src/backend/utils/adt/rangetypes_gist.c       | 16 ++--
 src/backend/utils/adt/regexp.c                |  5 +-
 src/backend/utils/adt/selfuncs.c              | 36 +++++----
 src/backend/utils/adt/tsquery_util.c          |  2 +-
 src/backend/utils/adt/varlena.c               |  6 +-
 src/backend/utils/cache/catcache.c            |  2 +-
 src/backend/utils/cache/plancache.c           | 16 ++--
 src/backend/utils/cache/relcache.c            |  6 +-
 src/backend/utils/fmgr/funcapi.c              |  4 +-
 src/backend/utils/hash/dynahash.c             | 14 ++--
 src/backend/utils/misc/guc.c                  | 13 ++--
 src/backend/utils/mmgr/freepage.c             | 16 ++--
 src/backend/utils/mmgr/generation.c           |  4 +-
 src/backend/utils/mmgr/slab.c                 |  4 +-
 src/backend/utils/sort/sharedtuplestore.c     |  5 +-
 src/backend/utils/sort/tuplesort.c            |  4 +-
 src/bin/initdb/findtimezone.c                 |  6 +-
 src/bin/pg_basebackup/pg_basebackup.c         |  4 +-
 src/bin/pg_basebackup/receivelog.c            |  6 +-
 src/bin/pg_combinebackup/backup_label.c       |  5 +-
 src/bin/pg_combinebackup/pg_combinebackup.c   |  4 +-
 src/bin/pg_combinebackup/reconstruct.c        |  8 +-
 src/bin/pg_dump/common.c                      |  6 +-
 src/bin/pg_dump/compress_gzip.c               |  6 +-
 src/bin/pg_dump/compress_zstd.c               |  5 +-
 src/bin/pg_dump/parallel.c                    | 25 ++++---
 src/bin/pg_dump/pg_backup_archiver.c          | 46 ++++++------
 src/bin/pg_dump/pg_backup_custom.c            |  4 +-
 src/bin/pg_dump/pg_backup_directory.c         |  8 +-
 src/bin/pg_dump/pg_backup_tar.c               |  4 +-
 src/bin/pg_dump/pg_dumpall.c                  |  5 +-
 src/bin/pg_rewind/pg_rewind.c                 |  4 +-
 src/bin/pg_upgrade/info.c                     | 12 +--
 src/bin/pg_waldump/pg_waldump.c               |  2 +-
 src/bin/pg_walsummary/pg_walsummary.c         |  4 +-
 src/bin/pgbench/pgbench.c                     | 17 +++--
 src/bin/psql/crosstabview.c                   |  9 ++-
 src/bin/scripts/clusterdb.c                   |  5 +-
 src/bin/scripts/reindexdb.c                   |  5 +-
 src/bin/scripts/vacuuming.c                   |  4 +-
 src/common/parse_manifest.c                   |  4 +-
 src/common/pg_lzcompress.c                    |  2 +-
 src/interfaces/ecpg/ecpglib/execute.c         |  2 +-
 src/interfaces/ecpg/pgtypeslib/interval.c     |  2 +-
 src/interfaces/ecpg/pgtypeslib/numeric.c      |  2 +-
 src/interfaces/ecpg/preproc/type.c            |  9 ++-
 src/interfaces/libpq/fe-print.c               | 18 +++--
 src/pl/plperl/plperl.c                        |  2 +-
 src/pl/plpgsql/src/pl_exec.c                  | 35 ++++-----
 src/pl/plpgsql/src/pl_funcs.c                 | 10 +--
 src/pl/plpgsql/src/pl_scanner.c               |  5 +-
 src/pl/plpython/plpy_exec.c                   |  4 +-
 src/pl/plpython/plpy_typeio.c                 | 25 +++++--
 src/pl/tcl/pltcl.c                            |  4 +-
 .../injection_points/injection_points.c       |  2 +-
 .../modules/libpq_pipeline/libpq_pipeline.c   |  3 +-
 .../modules/test_radixtree/test_radixtree.c   |  2 +-
 src/test/modules/test_regex/test_regex.c      |  6 +-
 .../test_resowner/test_resowner_many.c        |  5 +-
 src/test/modules/test_shm_mq/setup.c          |  4 +-
 src/test/modules/test_shm_mq/test.c           |  7 +-
 src/test/regress/regress.c                    |  5 +-
 254 files changed, 1348 insertions(+), 1063 deletions(-)
   4.9% contrib/
   6.1% src/backend/access/
   6.4% src/backend/commands/
  10.2% src/backend/executor/
   6.4% src/backend/optimizer/path/
   8.7% src/backend/optimizer/plan/
   3.0% src/backend/optimizer/util/
   4.3% src/backend/parser/
   3.0% src/backend/replication/logical/
  10.7% src/backend/utils/adt/
   4.0% src/backend/utils/
  16.0% src/backend/
   4.8% src/bin/pg_dump/
   3.9% src/bin/
   3.8% src/pl/
   3.0% src/

diff --git a/contrib/bloom/blinsert.c b/contrib/bloom/blinsert.c
index c11e06c34ee..491cdde45c3 100644
--- a/contrib/bloom/blinsert.c
+++ b/contrib/bloom/blinsert.c
@@ -45,7 +45,7 @@ typedef struct
  * Flush page cached in BloomBuildState.
  */
 static void
-flushCachedPage(Relation index, BloomBuildState *buildstate)
+flushCachedPage(Relation index, const BloomBuildState *buildstate)
 {
 	Page		page;
 	Buffer		buffer = BloomNewBuffer(index);
diff --git a/contrib/dblink/dblink.c b/contrib/dblink/dblink.c
index 8bf8fc8ea2f..32d70d0a8c9 100644
--- a/contrib/dblink/dblink.c
+++ b/contrib/dblink/dblink.c
@@ -110,11 +110,14 @@ static void deleteConnection(const char *name);
 static char **get_pkey_attnames(Relation rel, int16 *indnkeyatts);
 static char **get_text_array_contents(ArrayType *array, int *numitems);
 static char *get_sql_insert(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals);
-static char *get_sql_delete(Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals);
+static char *get_sql_delete(Relation rel, const int *pkattnums, int pknumatts,
+							char **tgt_pkattvals);
 static char *get_sql_update(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals);
 static char *quote_ident_cstr(char *rawstr);
-static int	get_attnum_pk_pos(int *pkattnums, int pknumatts, int key);
-static HeapTuple get_tuple_of_interest(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals);
+static int	get_attnum_pk_pos(const int *pkattnums, int pknumatts,
+							  int key);
+static HeapTuple get_tuple_of_interest(Relation rel, const int *pkattnums,
+									   int pknumatts, char **src_pkattvals);
 static Relation get_rel_from_relname(text *relname_text, LOCKMODE lockmode, AclMode aclmode);
 static char *generate_relation_name(Relation rel);
 static void dblink_connstr_check(const char *connstr);
@@ -132,7 +135,8 @@ static bool is_valid_dblink_option(const PQconninfoOption *options,
 								   const char *option, Oid context);
 static int	applyRemoteGucs(PGconn *conn);
 static void restoreLocalGucs(int nestlevel);
-static bool UseScramPassthrough(ForeignServer *foreign_server, UserMapping *user);
+static bool UseScramPassthrough(const ForeignServer *foreign_server,
+								const UserMapping *user);
 static void appendSCRAMKeysInfo(StringInfo buf);
 static bool is_valid_dblink_fdw_option(const PQconninfoOption *options, const char *option,
 									   Oid context);
@@ -2197,7 +2201,8 @@ get_sql_insert(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals
 }
 
 static char *
-get_sql_delete(Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
+get_sql_delete(Relation rel, const int *pkattnums, int pknumatts,
+			   char **tgt_pkattvals)
 {
 	char	   *relname;
 	TupleDesc	tupdesc;
@@ -2340,7 +2345,7 @@ quote_ident_cstr(char *rawstr)
 }
 
 static int
-get_attnum_pk_pos(int *pkattnums, int pknumatts, int key)
+get_attnum_pk_pos(const int *pkattnums, int pknumatts, int key)
 {
 	int			i;
 
@@ -2355,7 +2360,8 @@ get_attnum_pk_pos(int *pkattnums, int pknumatts, int key)
 }
 
 static HeapTuple
-get_tuple_of_interest(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
+get_tuple_of_interest(Relation rel, const int *pkattnums, int pknumatts,
+					  char **src_pkattvals)
 {
 	char	   *relname;
 	TupleDesc	tupdesc;
@@ -3223,7 +3229,8 @@ appendSCRAMKeysInfo(StringInfo buf)
 
 
 static bool
-UseScramPassthrough(ForeignServer *foreign_server, UserMapping *user)
+UseScramPassthrough(const ForeignServer *foreign_server,
+					const UserMapping *user)
 {
 	ListCell   *cell;
 
diff --git a/contrib/file_fdw/file_fdw.c b/contrib/file_fdw/file_fdw.c
index e9cda3c47d1..01b949fc547 100644
--- a/contrib/file_fdw/file_fdw.c
+++ b/contrib/file_fdw/file_fdw.c
@@ -166,8 +166,8 @@ static bool check_selective_binary_conversion(RelOptInfo *baserel,
 											  List **columns);
 static void estimate_size(PlannerInfo *root, RelOptInfo *baserel,
 						  FileFdwPlanState *fdw_private);
-static void estimate_costs(PlannerInfo *root, RelOptInfo *baserel,
-						   FileFdwPlanState *fdw_private,
+static void estimate_costs(PlannerInfo *root, const RelOptInfo *baserel,
+						   const FileFdwPlanState *fdw_private,
 						   Cost *startup_cost, Cost *total_cost);
 static int	file_acquire_sample_rows(Relation onerel, int elevel,
 									 HeapTuple *rows, int targrows,
@@ -1139,8 +1139,8 @@ estimate_size(PlannerInfo *root, RelOptInfo *baserel,
  * Results are returned in *startup_cost and *total_cost.
  */
 static void
-estimate_costs(PlannerInfo *root, RelOptInfo *baserel,
-			   FileFdwPlanState *fdw_private,
+estimate_costs(PlannerInfo *root, const RelOptInfo *baserel,
+			   const FileFdwPlanState *fdw_private,
 			   Cost *startup_cost, Cost *total_cost)
 {
 	BlockNumber pages = fdw_private->pages;
diff --git a/contrib/fuzzystrmatch/dmetaphone.c b/contrib/fuzzystrmatch/dmetaphone.c
index 227d8b11ddc..903793addb1 100644
--- a/contrib/fuzzystrmatch/dmetaphone.c
+++ b/contrib/fuzzystrmatch/dmetaphone.c
@@ -279,7 +279,7 @@ IncreaseBuffer(metastring *s, int chars_needed)
 
 
 static void
-MakeUpper(metastring *s)
+MakeUpper(const metastring *s)
 {
 	char	   *i;
 
@@ -289,7 +289,7 @@ MakeUpper(metastring *s)
 
 
 static int
-IsVowel(metastring *s, int pos)
+IsVowel(const metastring *s, int pos)
 {
 	char		c;
 
@@ -322,7 +322,7 @@ SlavoGermanic(metastring *s)
 
 
 static char
-GetAt(metastring *s, int pos)
+GetAt(const metastring *s, int pos)
 {
 	if ((pos < 0) || (pos >= s->length))
 		return '\0';
@@ -332,7 +332,7 @@ GetAt(metastring *s, int pos)
 
 
 static void
-SetAt(metastring *s, int pos, char c)
+SetAt(const metastring *s, int pos, char c)
 {
 	if ((pos < 0) || (pos >= s->length))
 		return;
@@ -345,7 +345,7 @@ SetAt(metastring *s, int pos, char c)
    Caveats: the START value is 0 based
 */
 static int
-StringAt(metastring *s, int start, int length,...)
+StringAt(const metastring *s, int start, int length,...)
 {
 	char	   *test;
 	char	   *pos;
diff --git a/contrib/fuzzystrmatch/fuzzystrmatch.c b/contrib/fuzzystrmatch/fuzzystrmatch.c
index e7cc314b763..84648f9ae51 100644
--- a/contrib/fuzzystrmatch/fuzzystrmatch.c
+++ b/contrib/fuzzystrmatch/fuzzystrmatch.c
@@ -106,7 +106,7 @@ soundex_code(char letter)
 #define  SH		'X'
 #define  TH		'0'
 
-static char Lookahead(char *word, int how_far);
+static char Lookahead(const char *word, int how_far);
 static void _metaphone(char *word, int max_phonemes, char **phoned_word);
 
 /* Metachar.h ... little bits about characters for metaphone */
@@ -318,7 +318,7 @@ metaphone(PG_FUNCTION_ARGS)
 /* Allows us to safely look ahead an arbitrary # of letters */
 /* I probably could have just used strlen... */
 static char
-Lookahead(char *word, int how_far)
+Lookahead(const char *word, int how_far)
 {
 	char		letter_ahead = '\0';	/* null by default */
 	int			idx;
diff --git a/contrib/intarray/_int_bool.c b/contrib/intarray/_int_bool.c
index f45df86d60c..476d4252207 100644
--- a/contrib/intarray/_int_bool.c
+++ b/contrib/intarray/_int_bool.c
@@ -359,7 +359,7 @@ gin_bool_consistent(QUERYTYPE *query, bool *check)
 }
 
 static bool
-contains_required_value(ITEM *curitem)
+contains_required_value(const ITEM *curitem)
 {
 	/* since this function recurses, it could be driven to stack overflow */
 	check_stack_depth();
diff --git a/contrib/isn/isn.c b/contrib/isn/isn.c
index 3caa3af8b4c..5cfb308b624 100644
--- a/contrib/isn/isn.c
+++ b/contrib/isn/isn.c
@@ -144,7 +144,7 @@ invalidindex:
  *---------------------------------------------------------*/
 
 static unsigned
-dehyphenate(char *bufO, char *bufI)
+dehyphenate(char *bufO, const char *bufI)
 {
 	unsigned	ret = 0;
 
@@ -279,7 +279,7 @@ hyphenate(char *bufO, char *bufI, const char *(*TABLE)[2], const unsigned TABLE_
  * Returns the weight of the number (the check digit value, 0-10)
  */
 static unsigned
-weight_checkdig(char *isn, unsigned size)
+weight_checkdig(const char *isn, unsigned size)
 {
 	unsigned	weight = 0;
 
@@ -305,7 +305,7 @@ weight_checkdig(char *isn, unsigned size)
  * Returns the check digit value (0-9)
  */
 static unsigned
-checkdig(char *num, unsigned size)
+checkdig(const char *num, unsigned size)
 {
 	unsigned	check = 0,
 				check3 = 0;
diff --git a/contrib/jsonb_plpython/jsonb_plpython.c b/contrib/jsonb_plpython/jsonb_plpython.c
index 7e8e1d6674f..4fdf75993e7 100644
--- a/contrib/jsonb_plpython/jsonb_plpython.c
+++ b/contrib/jsonb_plpython/jsonb_plpython.c
@@ -66,7 +66,7 @@ _PG_init(void)
  * Transform string JsonbValue to Python string.
  */
 static PyObject *
-PLyUnicode_FromJsonbValue(JsonbValue *jbv)
+PLyUnicode_FromJsonbValue(const JsonbValue *jbv)
 {
 	Assert(jbv->type == jbvString);
 
diff --git a/contrib/ltree/lquery_op.c b/contrib/ltree/lquery_op.c
index a6466f575fd..e557b175e5a 100644
--- a/contrib/ltree/lquery_op.c
+++ b/contrib/ltree/lquery_op.c
@@ -22,7 +22,7 @@ PG_FUNCTION_INFO_V1(lt_q_rregex);
 #define NEXTVAL(x) ( (lquery*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
 
 static char *
-getlexeme(char *start, char *end, int *len)
+getlexeme(char *start, const char *end, int *len)
 {
 	char	   *ptr;
 
diff --git a/contrib/pg_trgm/trgm_op.c b/contrib/pg_trgm/trgm_op.c
index 29b39ec8a4c..645adca71e4 100644
--- a/contrib/pg_trgm/trgm_op.c
+++ b/contrib/pg_trgm/trgm_op.c
@@ -446,7 +446,7 @@ generate_trgm(char *str, int slen)
  * Returns concatenated trigram array.
  */
 static pos_trgm *
-make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
+make_positional_trgm(const trgm *trg1, int len1, const trgm *trg2, int len2)
 {
 	pos_trgm   *result;
 	int			i,
@@ -502,13 +502,13 @@ comp_ptrgm(const void *v1, const void *v2)
  * Returns word similarity.
  */
 static float4
-iterate_word_similarity(int *trg2indexes,
-						bool *found,
+iterate_word_similarity(const int *trg2indexes,
+						const bool *found,
 						int ulen1,
 						int len2,
 						int len,
 						uint8 flags,
-						TrgmBound *bounds)
+						const TrgmBound *bounds)
 {
 	int		   *lastpos,
 				i,
diff --git a/contrib/pg_trgm/trgm_regexp.c b/contrib/pg_trgm/trgm_regexp.c
index 1a76794c422..0142ef90b42 100644
--- a/contrib/pg_trgm/trgm_regexp.c
+++ b/contrib/pg_trgm/trgm_regexp.c
@@ -491,9 +491,10 @@ static void addKeyToQueue(TrgmNFA *trgmNFA, TrgmStateKey *key);
 static void addArcs(TrgmNFA *trgmNFA, TrgmState *state);
 static void addArc(TrgmNFA *trgmNFA, TrgmState *state, TrgmStateKey *key,
 				   TrgmColor co, TrgmStateKey *destKey);
-static bool validArcLabel(TrgmStateKey *key, TrgmColor co);
+static bool validArcLabel(const TrgmStateKey *key, TrgmColor co);
 static TrgmState *getState(TrgmNFA *trgmNFA, TrgmStateKey *key);
-static bool prefixContains(TrgmPrefix *prefix1, TrgmPrefix *prefix2);
+static bool prefixContains(const TrgmPrefix *prefix1,
+						   const TrgmPrefix *prefix2);
 static bool selectColorTrigrams(TrgmNFA *trgmNFA);
 static TRGM *expandColorTrigrams(TrgmNFA *trgmNFA, MemoryContext rcontext);
 static void fillTrgm(trgm *ptrgm, trgm_mb_char s[3]);
@@ -504,10 +505,12 @@ static TrgmPackedGraph *packGraph(TrgmNFA *trgmNFA, MemoryContext rcontext);
 static int	packArcInfoCmp(const void *a1, const void *a2);
 
 #ifdef TRGM_REGEXP_DEBUG
-static void printSourceNFA(regex_t *regex, TrgmColorInfo *colors, int ncolors);
+static void printSourceNFA(regex_t *regex, const TrgmColorInfo *colors,
+						   int ncolors);
 static void printTrgmNFA(TrgmNFA *trgmNFA);
 static void printTrgmColor(StringInfo buf, TrgmColor co);
-static void printTrgmPackedGraph(TrgmPackedGraph *packedGraph, TRGM *trigrams);
+static void printTrgmPackedGraph(const TrgmPackedGraph *packedGraph,
+								 TRGM *trigrams);
 #endif
 
 
@@ -1326,7 +1329,7 @@ addArc(TrgmNFA *trgmNFA, TrgmState *state, TrgmStateKey *key,
  * This is split out so that tests in addKey and addArc will stay in sync.
  */
 static bool
-validArcLabel(TrgmStateKey *key, TrgmColor co)
+validArcLabel(const TrgmStateKey *key, TrgmColor co)
 {
 	/*
 	 * We have to know full trigram in order to add outgoing arc.  So we can't
@@ -1412,7 +1415,7 @@ getState(TrgmNFA *trgmNFA, TrgmStateKey *key)
  * prefix2 also satisfies prefix1.
  */
 static bool
-prefixContains(TrgmPrefix *prefix1, TrgmPrefix *prefix2)
+prefixContains(const TrgmPrefix *prefix1, const TrgmPrefix *prefix2)
 {
 	if (prefix1->colors[1] == COLOR_UNKNOWN)
 	{
@@ -2122,7 +2125,7 @@ packArcInfoCmp(const void *a1, const void *a2)
  * Print initial NFA, in regexp library's representation
  */
 static void
-printSourceNFA(regex_t *regex, TrgmColorInfo *colors, int ncolors)
+printSourceNFA(regex_t *regex, const TrgmColorInfo *colors, int ncolors)
 {
 	StringInfoData buf;
 	int			nstates = pg_reg_getnumstates(regex);
@@ -2282,7 +2285,7 @@ printTrgmColor(StringInfo buf, TrgmColor co)
  * Print final packed representation of trigram-based expanded graph.
  */
 static void
-printTrgmPackedGraph(TrgmPackedGraph *packedGraph, TRGM *trigrams)
+printTrgmPackedGraph(const TrgmPackedGraph *packedGraph, TRGM *trigrams)
 {
 	StringInfoData buf;
 	trgm	   *p;
diff --git a/contrib/pg_walinspect/pg_walinspect.c b/contrib/pg_walinspect/pg_walinspect.c
index 6945bac1306..a89762161fd 100644
--- a/contrib/pg_walinspect/pg_walinspect.c
+++ b/contrib/pg_walinspect/pg_walinspect.c
@@ -51,7 +51,7 @@ static void GetWALRecordInfo(XLogReaderState *record, Datum *values,
 static void GetWALRecordsInfo(FunctionCallInfo fcinfo,
 							  XLogRecPtr start_lsn,
 							  XLogRecPtr end_lsn);
-static void GetXLogSummaryStats(XLogStats *stats, ReturnSetInfo *rsinfo,
+static void GetXLogSummaryStats(const XLogStats *stats, ReturnSetInfo *rsinfo,
 								Datum *values, bool *nulls, uint32 ncols,
 								bool stats_per_record);
 static void FillXLogStatsRow(const char *name, uint64 n, uint64 total_count,
@@ -650,7 +650,7 @@ FillXLogStatsRow(const char *name,
  * Get summary statistics about the records seen so far.
  */
 static void
-GetXLogSummaryStats(XLogStats *stats, ReturnSetInfo *rsinfo,
+GetXLogSummaryStats(const XLogStats *stats, ReturnSetInfo *rsinfo,
 					Datum *values, bool *nulls, uint32 ncols,
 					bool stats_per_record)
 {
diff --git a/contrib/pgcrypto/pgp-info.c b/contrib/pgcrypto/pgp-info.c
index 83dc60486bd..20c21b0d265 100644
--- a/contrib/pgcrypto/pgp-info.c
+++ b/contrib/pgcrypto/pgp-info.c
@@ -87,7 +87,7 @@ read_pubenc_keyid(PullFilter *pkt, uint8 *keyid_buf)
 static const char hextbl[] = "0123456789ABCDEF";
 
 static int
-print_key(uint8 *keyid, char *dst)
+print_key(const uint8 *keyid, char *dst)
 {
 	int			i;
 	unsigned	c;
diff --git a/contrib/pgcrypto/pgp-pgsql.c b/contrib/pgcrypto/pgp-pgsql.c
index 3e47b9364ab..1ed5f4fc199 100644
--- a/contrib/pgcrypto/pgp-pgsql.c
+++ b/contrib/pgcrypto/pgp-pgsql.c
@@ -144,7 +144,7 @@ fill_expect(struct debug_expect *ex, int text_mode)
 	} while (0)
 
 static void
-check_expect(PGP_Context *ctx, struct debug_expect *ex)
+check_expect(const PGP_Context *ctx, struct debug_expect *ex)
 {
 	EX_CHECK(cipher_algo);
 	EX_CHECK(s2k_mode);
diff --git a/contrib/pgcrypto/pgp-pubdec.c b/contrib/pgcrypto/pgp-pubdec.c
index a0a5738a40e..7201d7b5097 100644
--- a/contrib/pgcrypto/pgp-pubdec.c
+++ b/contrib/pgcrypto/pgp-pubdec.c
@@ -71,7 +71,7 @@ check_eme_pkcs1_v15(uint8 *data, int len)
  * ignore algo in cksum
  */
 static int
-control_cksum(uint8 *msg, int msglen)
+control_cksum(const uint8 *msg, int msglen)
 {
 	int			i;
 	unsigned	my_cksum,
diff --git a/contrib/pgcrypto/pgp-pubkey.c b/contrib/pgcrypto/pgp-pubkey.c
index 6f118865917..dd68e767257 100644
--- a/contrib/pgcrypto/pgp-pubkey.c
+++ b/contrib/pgcrypto/pgp-pubkey.c
@@ -250,7 +250,7 @@ out:
 #define HIDE_SHA1 254
 
 static int
-check_key_sha1(PullFilter *src, PGP_PubKey *pk)
+check_key_sha1(PullFilter *src, const PGP_PubKey *pk)
 {
 	int			res;
 	uint8		got_sha1[20];
@@ -296,7 +296,7 @@ err:
 }
 
 static int
-check_key_cksum(PullFilter *src, PGP_PubKey *pk)
+check_key_cksum(PullFilter *src, const PGP_PubKey *pk)
 {
 	int			res;
 	unsigned	got_cksum,
diff --git a/contrib/seg/seg.c b/contrib/seg/seg.c
index 2d3a048c73e..ee69e31813a 100644
--- a/contrib/seg/seg.c
+++ b/contrib/seg/seg.c
@@ -81,7 +81,7 @@ PG_FUNCTION_INFO_V1(seg_right);
 PG_FUNCTION_INFO_V1(seg_over_right);
 PG_FUNCTION_INFO_V1(seg_union);
 PG_FUNCTION_INFO_V1(seg_inter);
-static void rt_seg_size(SEG *a, float *size);
+static void rt_seg_size(const SEG *a, float *size);
 
 /*
 ** Various operators
@@ -706,7 +706,7 @@ seg_inter(PG_FUNCTION_ARGS)
 }
 
 static void
-rt_seg_size(SEG *a, float *size)
+rt_seg_size(const SEG *a, float *size)
 {
 	if (a == (SEG *) NULL || a->upper <= a->lower)
 		*size = 0.0;
diff --git a/contrib/test_decoding/test_decoding.c b/contrib/test_decoding/test_decoding.c
index 47094f86f5f..428c3b69ea9 100644
--- a/contrib/test_decoding/test_decoding.c
+++ b/contrib/test_decoding/test_decoding.c
@@ -57,7 +57,7 @@ static void pg_decode_shutdown(LogicalDecodingContext *ctx);
 static void pg_decode_begin_txn(LogicalDecodingContext *ctx,
 								ReorderBufferTXN *txn);
 static void pg_output_begin(LogicalDecodingContext *ctx,
-							TestDecodingData *data,
+							const TestDecodingData *data,
 							ReorderBufferTXN *txn,
 							bool last_write);
 static void pg_decode_commit_txn(LogicalDecodingContext *ctx,
@@ -93,7 +93,7 @@ static void pg_decode_rollback_prepared_txn(LogicalDecodingContext *ctx,
 static void pg_decode_stream_start(LogicalDecodingContext *ctx,
 								   ReorderBufferTXN *txn);
 static void pg_output_stream_start(LogicalDecodingContext *ctx,
-								   TestDecodingData *data,
+								   const TestDecodingData *data,
 								   ReorderBufferTXN *txn,
 								   bool last_write);
 static void pg_decode_stream_stop(LogicalDecodingContext *ctx,
@@ -307,7 +307,8 @@ pg_decode_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 }
 
 static void
-pg_output_begin(LogicalDecodingContext *ctx, TestDecodingData *data, ReorderBufferTXN *txn, bool last_write)
+pg_output_begin(LogicalDecodingContext *ctx, const TestDecodingData *data,
+				ReorderBufferTXN *txn, bool last_write)
 {
 	OutputPluginPrepareWrite(ctx, last_write);
 	if (data->include_xids)
@@ -790,7 +791,9 @@ pg_decode_stream_start(LogicalDecodingContext *ctx,
 }
 
 static void
-pg_output_stream_start(LogicalDecodingContext *ctx, TestDecodingData *data, ReorderBufferTXN *txn, bool last_write)
+pg_output_stream_start(LogicalDecodingContext *ctx,
+					   const TestDecodingData *data, ReorderBufferTXN *txn,
+					   bool last_write)
 {
 	OutputPluginPrepareWrite(ctx, last_write);
 	if (data->include_xids)
diff --git a/contrib/xml2/xpath.c b/contrib/xml2/xpath.c
index 662d7d02f27..138b866c580 100644
--- a/contrib/xml2/xpath.c
+++ b/contrib/xml2/xpath.c
@@ -44,7 +44,7 @@ typedef struct
 
 static xmlChar *pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
 								   xmlChar *toptagname, xmlChar *septagname,
-								   xmlChar *plainsep);
+								   const xmlChar *plainsep);
 
 static text *pgxml_result_to_text(xmlXPathObjectPtr res, xmlChar *toptag,
 								  xmlChar *septag, xmlChar *plainsep);
@@ -142,7 +142,7 @@ static xmlChar *
 pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
 				   xmlChar *toptagname,
 				   xmlChar *septagname,
-				   xmlChar *plainsep)
+				   const xmlChar *plainsep)
 {
 	volatile xmlBufferPtr buf = NULL;
 	xmlChar    *volatile result = NULL;
diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..c1d7c5b59a1 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -223,7 +223,8 @@ static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a,
 static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy);
 static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc,
 								BrinMemTuple *dtup, const Datum *values, const bool *nulls);
-static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys);
+static bool check_null_keys(const BrinValues *bval, const ScanKey *nullkeys,
+							int nnullkeys);
 static void brin_fill_empty_ranges(BrinBuildState *state,
 								   BlockNumber prevRange, BlockNumber nextRange);
 
@@ -2310,7 +2311,8 @@ add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup,
 }
 
 static bool
-check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
+check_null_keys(const BrinValues *bval, const ScanKey *nullkeys,
+				int nnullkeys)
 {
 	int			keyno;
 
diff --git a/src/backend/access/brin/brin_bloom.c b/src/backend/access/brin/brin_bloom.c
index 64dbb7b8532..7f87e87b4ad 100644
--- a/src/backend/access/brin/brin_bloom.c
+++ b/src/backend/access/brin/brin_bloom.c
@@ -405,7 +405,7 @@ bloom_add_value(BloomFilter *filter, uint32 value, bool *updated)
  * 		Check if the bloom filter contains a particular value.
  */
 static bool
-bloom_contains_value(BloomFilter *filter, uint32 value)
+bloom_contains_value(const BloomFilter *filter, uint32 value)
 {
 	int			i;
 	uint64		h1,
diff --git a/src/backend/access/brin/brin_tuple.c b/src/backend/access/brin/brin_tuple.c
index 861f397e6db..a2fe8959a81 100644
--- a/src/backend/access/brin/brin_tuple.c
+++ b/src/backend/access/brin/brin_tuple.c
@@ -50,7 +50,9 @@
 
 
 static inline void brin_deconstruct_tuple(BrinDesc *brdesc,
-										  char *tp, bits8 *nullbits, bool nulls,
+										  const char *tp,
+										  bits8 *nullbits,
+										  bool nulls,
 										  Datum *values, bool *allnulls, bool *hasnulls);
 
 
@@ -643,7 +645,8 @@ brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
  */
 static inline void
 brin_deconstruct_tuple(BrinDesc *brdesc,
-					   char *tp, bits8 *nullbits, bool nulls,
+					   const char *tp, bits8 *nullbits,
+					   bool nulls,
 					   Datum *values, bool *allnulls, bool *hasnulls)
 {
 	int			attnum;
diff --git a/src/backend/access/common/attmap.c b/src/backend/access/common/attmap.c
index 4901ebecef7..a4918504593 100644
--- a/src/backend/access/common/attmap.c
+++ b/src/backend/access/common/attmap.c
@@ -28,7 +28,7 @@
 
 static bool check_attrmap_match(TupleDesc indesc,
 								TupleDesc outdesc,
-								AttrMap *attrMap);
+								const AttrMap *attrMap);
 
 /*
  * make_attrmap
@@ -287,7 +287,7 @@ build_attrmap_by_name_if_req(TupleDesc indesc,
 static bool
 check_attrmap_match(TupleDesc indesc,
 					TupleDesc outdesc,
-					AttrMap *attrMap)
+					const AttrMap *attrMap)
 {
 	int			i;
 
diff --git a/src/backend/access/common/printtup.c b/src/backend/access/common/printtup.c
index 025fe75916f..d90a58a0044 100644
--- a/src/backend/access/common/printtup.c
+++ b/src/backend/access/common/printtup.c
@@ -423,7 +423,7 @@ printtup_destroy(DestReceiver *self)
 static void
 printatt(unsigned attributeId,
 		 Form_pg_attribute attributeP,
-		 char *value)
+		 const char *value)
 {
 	printf("\t%2d: %s%s%s%s\t(typeid = %u, len = %d, typmod = %d, byval = %c)\n",
 		   attributeId,
diff --git a/src/backend/access/common/reloptions.c b/src/backend/access/common/reloptions.c
index 9e288dfecbf..8fdeb0a7b31 100644
--- a/src/backend/access/common/reloptions.c
+++ b/src/backend/access/common/reloptions.c
@@ -578,7 +578,7 @@ static relopt_gen **custom_options = NULL;
 static bool need_initialization = true;
 
 static void initialize_reloptions(void);
-static void parse_one_reloption(relopt_value *option, char *text_str,
+static void parse_one_reloption(relopt_value *option, const char *text_str,
 								int text_len, bool validate);
 
 /*
@@ -1595,7 +1595,7 @@ parseLocalRelOptions(local_relopts *relopts, Datum options, bool validate)
  * value
  */
 static void
-parse_one_reloption(relopt_value *option, char *text_str, int text_len,
+parse_one_reloption(relopt_value *option, const char *text_str, int text_len,
 					bool validate)
 {
 	char	   *value;
diff --git a/src/backend/access/gin/ginentrypage.c b/src/backend/access/gin/ginentrypage.c
index 94f49d72a98..2944ed63757 100644
--- a/src/backend/access/gin/ginentrypage.c
+++ b/src/backend/access/gin/ginentrypage.c
@@ -20,7 +20,7 @@
 #include "utils/rel.h"
 
 static void entrySplitPage(GinBtree btree, Buffer origbuf,
-						   GinBtreeStack *stack,
+						   const GinBtreeStack *stack,
 						   GinBtreeEntryInsertData *insertData,
 						   BlockNumber updateblkno,
 						   Page *newlpage, Page *newrpage);
@@ -600,7 +600,7 @@ entryExecPlaceToPage(GinBtree btree, Buffer buf, GinBtreeStack *stack,
  */
 static void
 entrySplitPage(GinBtree btree, Buffer origbuf,
-			   GinBtreeStack *stack,
+			   const GinBtreeStack *stack,
 			   GinBtreeEntryInsertData *insertData,
 			   BlockNumber updateblkno,
 			   Page *newlpage, Page *newrpage)
diff --git a/src/backend/access/gin/ginfast.c b/src/backend/access/gin/ginfast.c
index 33816f8551f..97057d5b2eb 100644
--- a/src/backend/access/gin/ginfast.c
+++ b/src/backend/access/gin/ginfast.c
@@ -142,7 +142,7 @@ writeListPage(Relation index, Buffer buffer,
 }
 
 static void
-makeSublist(Relation index, IndexTuple *tuples, int32 ntuples,
+makeSublist(Relation index, const IndexTuple *tuples, int32 ntuples,
 			GinMetaPageData *res)
 {
 	Buffer		curBuffer = InvalidBuffer;
diff --git a/src/backend/access/gin/ginscan.c b/src/backend/access/gin/ginscan.c
index 26081693383..5169895586d 100644
--- a/src/backend/access/gin/ginscan.c
+++ b/src/backend/access/gin/ginscan.c
@@ -160,7 +160,7 @@ ginFillScanKey(GinScanOpaque so, OffsetNumber attnum,
 			   StrategyNumber strategy, int32 searchMode,
 			   Datum query, uint32 nQueryValues,
 			   Datum *queryValues, GinNullCategory *queryCategories,
-			   bool *partial_matches, Pointer *extra_data)
+			   const bool *partial_matches, Pointer *extra_data)
 {
 	GinScanKey	key = &(so->keys[so->nkeys++]);
 	GinState   *ginstate = &so->ginstate;
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..08bb4b3958a 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -141,7 +141,8 @@ static void gist_indexsortbuild_levelstate_flush(GISTBuildState *state,
 												 GistSortedBuildLevelState *levelstate);
 
 static void gistInitBuffering(GISTBuildState *buildstate);
-static int	calculatePagesPerBuffer(GISTBuildState *buildstate, int levelStep);
+static int	calculatePagesPerBuffer(const GISTBuildState *buildstate,
+									int levelStep);
 static void gistBuildCallback(Relation index,
 							  ItemPointer tid,
 							  Datum *values,
@@ -158,7 +159,7 @@ static BlockNumber gistbufferinginserttuples(GISTBuildState *buildstate,
 											 BlockNumber parentblk, OffsetNumber downlinkoffnum);
 static Buffer gistBufferingFindCorrectParent(GISTBuildState *buildstate,
 											 BlockNumber childblkno, int level,
-											 BlockNumber *parentblkno,
+											 const BlockNumber *parentblkno,
 											 OffsetNumber *downlinkoffnum);
 static void gistProcessEmptyingQueue(GISTBuildState *buildstate);
 static void gistEmptyAllBuffers(GISTBuildState *buildstate);
@@ -786,7 +787,7 @@ gistInitBuffering(GISTBuildState *buildstate)
  * at the next lower level.
  */
 static int
-calculatePagesPerBuffer(GISTBuildState *buildstate, int levelStep)
+calculatePagesPerBuffer(const GISTBuildState *buildstate, int levelStep)
 {
 	double		pagesPerBuffer;
 	double		avgIndexTuplesPerPage;
@@ -1224,7 +1225,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 static Buffer
 gistBufferingFindCorrectParent(GISTBuildState *buildstate,
 							   BlockNumber childblkno, int level,
-							   BlockNumber *parentblkno,
+							   const BlockNumber *parentblkno,
 							   OffsetNumber *downlinkoffnum)
 {
 	BlockNumber parent;
diff --git a/src/backend/access/gist/gistproc.c b/src/backend/access/gist/gistproc.c
index f2ec6cbe2e5..18a2ab76217 100644
--- a/src/backend/access/gist/gistproc.c
+++ b/src/backend/access/gist/gistproc.c
@@ -213,7 +213,7 @@ gist_box_penalty(PG_FUNCTION_ARGS)
  * and another half - to another
  */
 static void
-fallbackSplit(GistEntryVector *entryvec, GIST_SPLITVEC *v)
+fallbackSplit(const GistEntryVector *entryvec, GIST_SPLITVEC *v)
 {
 	OffsetNumber i,
 				maxoff;
@@ -1285,7 +1285,9 @@ computeDistance(bool isLeaf, BOX *box, Point *point)
 
 static bool
 gist_point_consistent_internal(StrategyNumber strategy,
-							   bool isLeaf, BOX *key, Point *query)
+							   bool isLeaf,
+							   const BOX *key,
+							   Point *query)
 {
 	bool		result = false;
 
diff --git a/src/backend/access/gist/gistsplit.c b/src/backend/access/gist/gistsplit.c
index 49838ceb07b..361e6116c9b 100644
--- a/src/backend/access/gist/gistsplit.c
+++ b/src/backend/access/gist/gistsplit.c
@@ -44,7 +44,7 @@ typedef struct
  * gistunionsubkey.
  */
 static void
-gistunionsubkeyvec(GISTSTATE *giststate, IndexTuple *itvec,
+gistunionsubkeyvec(GISTSTATE *giststate, const IndexTuple *itvec,
 				   GistSplitUnion *gsvp)
 {
 	IndexTuple *cleanedItVec;
diff --git a/src/backend/access/hash/hashsearch.c b/src/backend/access/hash/hashsearch.c
index 92c15a65be2..b8bdfe5435b 100644
--- a/src/backend/access/hash/hashsearch.c
+++ b/src/backend/access/hash/hashsearch.c
@@ -21,7 +21,7 @@
 #include "storage/predicate.h"
 #include "utils/rel.h"
 
-static bool _hash_readpage(IndexScanDesc scan, Buffer *bufP,
+static bool _hash_readpage(IndexScanDesc scan, const Buffer *bufP,
 						   ScanDirection dir);
 static int	_hash_load_qualified_items(IndexScanDesc scan, Page page,
 									   OffsetNumber offnum, ScanDirection dir);
@@ -445,7 +445,7 @@ _hash_first(IndexScanDesc scan, ScanDirection dir)
  *	Return true if any matching items are found else return false.
  */
 static bool
-_hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
+_hash_readpage(IndexScanDesc scan, const Buffer *bufP, ScanDirection dir)
 {
 	Relation	rel = scan->indexRelation;
 	HashScanOpaque so = (HashScanOpaque) scan->opaque;
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 4d382a04338..93c59aa57d4 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -100,7 +100,7 @@ static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 in
 static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
 									   uint16 infomask, Relation rel, int *remaining,
 									   bool logLockFailure);
-static void index_delete_sort(TM_IndexDeleteOp *delstate);
+static void index_delete_sort(const TM_IndexDeleteOp *delstate);
 static int	bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
 static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
 static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
@@ -2339,7 +2339,8 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
  * much the relation needs to be extended by.
  */
 static int
-heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
+heap_multi_insert_pages(const HeapTuple *heaptuples, int done, int ntuples,
+						Size saveFreeSpace)
 {
 	size_t		page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
 	int			npages = 1;
@@ -8486,7 +8487,7 @@ index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
  * (which are typical here).
  */
 static void
-index_delete_sort(TM_IndexDeleteOp *delstate)
+index_delete_sort(const TM_IndexDeleteOp *delstate)
 {
 	TM_IndexDelete *deltids = delstate->deltids;
 	int			ndeltids = delstate->ndeltids;
diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c
index ca44225a10e..bddac3ba90b 100644
--- a/src/backend/access/heap/pruneheap.c
+++ b/src/backend/access/heap/pruneheap.c
@@ -157,9 +157,9 @@ typedef struct
 } PruneState;
 
 /* Local functions */
-static void prune_freeze_setup(PruneFreezeParams *params,
-							   TransactionId *new_relfrozen_xid,
-							   MultiXactId *new_relmin_mxid,
+static void prune_freeze_setup(const PruneFreezeParams *params,
+							   const TransactionId *new_relfrozen_xid,
+							   const MultiXactId *new_relmin_mxid,
 							   const PruneFreezeResult *presult,
 							   PruneState *prstate);
 static void prune_freeze_plan(Oid reloid, Buffer buffer,
@@ -324,9 +324,9 @@ heap_page_prune_opt(Relation relation, Buffer buffer)
  * the provided parameters.
  */
 static void
-prune_freeze_setup(PruneFreezeParams *params,
-				   TransactionId *new_relfrozen_xid,
-				   MultiXactId *new_relmin_mxid,
+prune_freeze_setup(const PruneFreezeParams *params,
+				   const TransactionId *new_relfrozen_xid,
+				   const MultiXactId *new_relmin_mxid,
 				   const PruneFreezeResult *presult,
 				   PruneState *prstate)
 {
@@ -1993,7 +1993,7 @@ heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
  * caller's plan.
  */
 static inline bool
-heap_log_freeze_eq(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
+heap_log_freeze_eq(const xlhp_freeze_plan *plan, const HeapTupleFreeze *frz)
 {
 	if (plan->xmax == frz->xmax &&
 		plan->t_infomask2 == frz->t_infomask2 &&
@@ -2055,7 +2055,7 @@ heap_log_freeze_cmp(const void *arg1, const void *arg2)
  * will have steps required to freeze described by caller's plan during REDO.
  */
 static inline void
-heap_log_freeze_new_plan(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
+heap_log_freeze_new_plan(xlhp_freeze_plan *plan, const HeapTupleFreeze *frz)
 {
 	plan->xmax = frz->xmax;
 	plan->t_infomask2 = frz->t_infomask2;
diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 65bb0568a86..8d7cd3f172b 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -454,7 +454,7 @@ static IndexBulkDeleteResult *lazy_cleanup_one_index(Relation indrel,
 													 double reltuples,
 													 bool estimated_count,
 													 LVRelState *vacrel);
-static bool should_attempt_truncation(LVRelState *vacrel);
+static bool should_attempt_truncation(const LVRelState *vacrel);
 static void lazy_truncate_heap(LVRelState *vacrel);
 static BlockNumber count_nondeletable_pages(LVRelState *vacrel,
 											bool *lock_waiter_detected);
@@ -473,7 +473,7 @@ static bool heap_page_is_all_visible(Relation rel, Buffer buf,
 #endif
 static bool heap_page_would_be_all_visible(Relation rel, Buffer buf,
 										   TransactionId OldestXmin,
-										   OffsetNumber *deadoffsets,
+										   const OffsetNumber *deadoffsets,
 										   int ndeadoffsets,
 										   bool *all_frozen,
 										   TransactionId *visibility_cutoff_xid,
@@ -3221,7 +3221,7 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat,
  * we're called.
  */
 static bool
-should_attempt_truncation(LVRelState *vacrel)
+should_attempt_truncation(const LVRelState *vacrel)
 {
 	BlockNumber possibly_freeable;
 
@@ -3693,7 +3693,7 @@ heap_page_is_all_visible(Relation rel, Buffer buf,
 static bool
 heap_page_would_be_all_visible(Relation rel, Buffer buf,
 							   TransactionId OldestXmin,
-							   OffsetNumber *deadoffsets,
+							   const OffsetNumber *deadoffsets,
 							   int ndeadoffsets,
 							   bool *all_frozen,
 							   TransactionId *visibility_cutoff_xid,
diff --git a/src/backend/access/nbtree/nbtinsert.c b/src/backend/access/nbtree/nbtinsert.c
index 3a4b791f2ab..6cef5c6a908 100644
--- a/src/backend/access/nbtree/nbtinsert.c
+++ b/src/backend/access/nbtree/nbtinsert.c
@@ -72,7 +72,7 @@ static void _bt_simpledel_pass(Relation rel, Buffer buffer, Relation heapRel,
 							   OffsetNumber *deletable, int ndeletable,
 							   IndexTuple newitem, OffsetNumber minoff,
 							   OffsetNumber maxoff);
-static BlockNumber *_bt_deadblocks(Page page, OffsetNumber *deletable,
+static BlockNumber *_bt_deadblocks(Page page, const OffsetNumber *deletable,
 								   int ndeletable, IndexTuple newitem,
 								   int *nblocks);
 static inline int _bt_blk_cmp(const void *arg1, const void *arg2);
@@ -2948,7 +2948,7 @@ _bt_simpledel_pass(Relation rel, Buffer buffer, Relation heapRel,
  * Returns final array, and sets *nblocks to its final size for caller.
  */
 static BlockNumber *
-_bt_deadblocks(Page page, OffsetNumber *deletable, int ndeletable,
+_bt_deadblocks(Page page, const OffsetNumber *deletable, int ndeletable,
 			   IndexTuple newitem, int *nblocks)
 {
 	int			spacentids,
diff --git a/src/backend/access/nbtree/nbtreadpage.c b/src/backend/access/nbtree/nbtreadpage.c
index ac67b6f7a34..4401a4fa314 100644
--- a/src/backend/access/nbtree/nbtreadpage.c
+++ b/src/backend/access/nbtree/nbtreadpage.c
@@ -97,13 +97,14 @@ static void _bt_array_set_low_or_high(Relation rel, ScanKey skey,
 									  BTArrayKeyInfo *array, bool low_not_high);
 static void _bt_skiparray_set_element(Relation rel, ScanKey skey, BTArrayKeyInfo *array,
 									  int32 set_elem_result, Datum tupdatum, bool tupnull);
-static void _bt_skiparray_set_isnull(Relation rel, ScanKey skey, BTArrayKeyInfo *array);
+static void _bt_skiparray_set_isnull(Relation rel, ScanKey skey,
+									 const BTArrayKeyInfo *array);
 static inline int32 _bt_compare_array_skey(FmgrInfo *orderproc,
 										   Datum tupdatum, bool tupnull,
 										   Datum arrdatum, ScanKey cur);
 static void _bt_binsrch_skiparray_skey(bool cur_elem_trig, ScanDirection dir,
 									   Datum tupdatum, bool tupnull,
-									   BTArrayKeyInfo *array, ScanKey cur,
+									   const BTArrayKeyInfo *array, ScanKey cur,
 									   int32 *set_elem_result);
 #ifdef USE_ASSERT_CHECKING
 static bool _bt_verify_keys_with_arraykeys(IndexScanDesc scan);
@@ -3316,7 +3317,8 @@ _bt_skiparray_set_element(Relation rel, ScanKey skey, BTArrayKeyInfo *array,
  * _bt_skiparray_set_isnull() -- set skip array scan key to NULL
  */
 static void
-_bt_skiparray_set_isnull(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
+_bt_skiparray_set_isnull(Relation rel, ScanKey skey,
+						 const BTArrayKeyInfo *array)
 {
 	Assert(skey->sk_flags & SK_BT_SKIP);
 	Assert(skey->sk_flags & SK_SEARCHARRAY);
@@ -3579,7 +3581,7 @@ _bt_binsrch_array_skey(FmgrInfo *orderproc,
 static void
 _bt_binsrch_skiparray_skey(bool cur_elem_trig, ScanDirection dir,
 						   Datum tupdatum, bool tupnull,
-						   BTArrayKeyInfo *array, ScanKey cur,
+						   const BTArrayKeyInfo *array, ScanKey cur,
 						   int32 *set_elem_result)
 {
 	Assert(cur->sk_flags & SK_BT_SKIP);
diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtree/nbtsort.c
index 454adaee7dc..5caf4193b88 100644
--- a/src/backend/access/nbtree/nbtsort.c
+++ b/src/backend/access/nbtree/nbtsort.c
@@ -282,7 +282,7 @@ static void _bt_end_parallel(BTLeader *btleader);
 static Size _bt_parallel_estimate_shared(Relation heap, Snapshot snapshot);
 static double _bt_parallel_heapscan(BTBuildState *buildstate,
 									bool *brokenhotchain);
-static void _bt_leader_participate_as_worker(BTBuildState *buildstate);
+static void _bt_leader_participate_as_worker(const BTBuildState *buildstate);
 static void _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2,
 									   BTShared *btshared, Sharedsort *sharedsort,
 									   Sharedsort *sharedsort2, int sortmem,
@@ -1685,7 +1685,7 @@ _bt_parallel_heapscan(BTBuildState *buildstate, bool *brokenhotchain)
  * Within leader, participate as a parallel worker.
  */
 static void
-_bt_leader_participate_as_worker(BTBuildState *buildstate)
+_bt_leader_participate_as_worker(const BTBuildState *buildstate)
 {
 	BTLeader   *btleader = buildstate->btleader;
 	BTSpool    *leaderworker;
diff --git a/src/backend/access/nbtree/nbtsplitloc.c b/src/backend/access/nbtree/nbtsplitloc.c
index f0082f88c76..a82982f7a9b 100644
--- a/src/backend/access/nbtree/nbtsplitloc.c
+++ b/src/backend/access/nbtree/nbtsplitloc.c
@@ -72,7 +72,7 @@ static bool _bt_afternewitemoff(FindSplitData *state, OffsetNumber maxoff,
 static bool _bt_adjacenthtid(const ItemPointerData *lowhtid, const ItemPointerData *highhtid);
 static OffsetNumber _bt_bestsplitloc(FindSplitData *state, int perfectpenalty,
 									 bool *newitemonleft, FindSplitStrat strategy);
-static int	_bt_defaultinterval(FindSplitData *state);
+static int	_bt_defaultinterval(const FindSplitData *state);
 static int	_bt_strategy(FindSplitData *state, SplitPoint *leftpage,
 						 SplitPoint *rightpage, FindSplitStrat *strategy);
 static void _bt_interval_edges(FindSplitData *state,
@@ -874,7 +874,7 @@ _bt_bestsplitloc(FindSplitData *state, int perfectpenalty,
  * assumed to work in the paper.)
  */
 static int
-_bt_defaultinterval(FindSplitData *state)
+_bt_defaultinterval(const FindSplitData *state)
 {
 	SplitPoint *spaceoptimal;
 	int16		tolerance,
diff --git a/src/backend/access/rmgrdesc/xactdesc.c b/src/backend/access/rmgrdesc/xactdesc.c
index f0f696855b9..79e072c24b5 100644
--- a/src/backend/access/rmgrdesc/xactdesc.c
+++ b/src/backend/access/rmgrdesc/xactdesc.c
@@ -280,7 +280,7 @@ ParsePrepareRecord(uint8 info, xl_xact_prepare *xlrec, xl_xact_parsed_prepare *p
 
 static void
 xact_desc_relations(StringInfo buf, char *label, int nrels,
-					RelFileLocator *xlocators)
+					const RelFileLocator *xlocators)
 {
 	int			i;
 
@@ -296,7 +296,8 @@ xact_desc_relations(StringInfo buf, char *label, int nrels,
 }
 
 static void
-xact_desc_subxacts(StringInfo buf, int nsubxacts, TransactionId *subxacts)
+xact_desc_subxacts(StringInfo buf, int nsubxacts,
+				   const TransactionId *subxacts)
 {
 	int			i;
 
@@ -425,7 +426,7 @@ xact_desc_prepare(StringInfo buf, uint8 info, xl_xact_prepare *xlrec, RepOriginI
 }
 
 static void
-xact_desc_assignment(StringInfo buf, xl_xact_assignment *xlrec)
+xact_desc_assignment(StringInfo buf, const xl_xact_assignment *xlrec)
 {
 	int			i;
 
diff --git a/src/backend/access/spgist/spgdoinsert.c b/src/backend/access/spgist/spgdoinsert.c
index 4eadb518776..0a65ad73e13 100644
--- a/src/backend/access/spgist/spgdoinsert.c
+++ b/src/backend/access/spgist/spgdoinsert.c
@@ -592,7 +592,7 @@ setRedirectionTuple(SPPageDesc *current, OffsetNumber position,
  * fixes the problem even when there is only one old tuple.)
  */
 static bool
-checkAllTheSame(spgPickSplitIn *in, spgPickSplitOut *out, bool tooBig,
+checkAllTheSame(const spgPickSplitIn *in, spgPickSplitOut *out, bool tooBig,
 				bool *includeNew)
 {
 	int			theNode;
@@ -1710,7 +1710,8 @@ spgAddNodeAction(Relation index, SpGistState *state,
 static void
 spgSplitNodeAction(Relation index, SpGistState *state,
 				   SpGistInnerTuple innerTuple,
-				   SPPageDesc *current, spgChooseOut *out)
+				   SPPageDesc *current,
+				   const spgChooseOut *out)
 {
 	SpGistInnerTuple prefixTuple,
 				postfixTuple;
diff --git a/src/backend/access/spgist/spgkdtreeproc.c b/src/backend/access/spgist/spgkdtreeproc.c
index d6989759e5f..fd1740c1ca6 100644
--- a/src/backend/access/spgist/spgkdtreeproc.c
+++ b/src/backend/access/spgist/spgkdtreeproc.c
@@ -38,7 +38,7 @@ spg_kd_config(PG_FUNCTION_ARGS)
 }
 
 static int
-getSide(double coord, bool isX, Point *tst)
+getSide(double coord, bool isX, const Point *tst)
 {
 	double		tstcoord = (isX) ? tst->x : tst->y;
 
diff --git a/src/backend/access/spgist/spgproc.c b/src/backend/access/spgist/spgproc.c
index 722c17ce2e5..9894693daae 100644
--- a/src/backend/access/spgist/spgproc.c
+++ b/src/backend/access/spgist/spgproc.c
@@ -28,7 +28,7 @@
 
 /* Point-box distance in the assumption that box is aligned by axis */
 static double
-point_box_distance(Point *point, BOX *box)
+point_box_distance(Point *point, const BOX *box)
 {
 	double		dx,
 				dy;
diff --git a/src/backend/access/spgist/spgquadtreeproc.c b/src/backend/access/spgist/spgquadtreeproc.c
index 3e8cfa1709a..3bf32dbcc06 100644
--- a/src/backend/access/spgist/spgquadtreeproc.c
+++ b/src/backend/access/spgist/spgquadtreeproc.c
@@ -80,7 +80,7 @@ getQuadrant(Point *centroid, Point *tst)
 
 /* Returns bounding box of a given quadrant inside given bounding box */
 static BOX *
-getQuadrantArea(BOX *bbox, Point *centroid, int quadrant)
+getQuadrantArea(const BOX *bbox, const Point *centroid, int quadrant)
 {
 	BOX		   *result = (BOX *) palloc(sizeof(BOX));
 
diff --git a/src/backend/access/spgist/spgscan.c b/src/backend/access/spgist/spgscan.c
index 25893050c58..9068172a516 100644
--- a/src/backend/access/spgist/spgscan.c
+++ b/src/backend/access/spgist/spgscan.c
@@ -605,7 +605,7 @@ spgLeafTest(SpGistScanOpaque so, SpGistSearchItem *item,
 static void
 spgInitInnerConsistentIn(spgInnerConsistentIn *in,
 						 SpGistScanOpaque so,
-						 SpGistSearchItem *item,
+						 const SpGistSearchItem *item,
 						 SpGistInnerTuple innerTuple)
 {
 	in->scankeys = so->keyData;
@@ -627,9 +627,10 @@ spgInitInnerConsistentIn(spgInnerConsistentIn *in,
 
 static SpGistSearchItem *
 spgMakeInnerItem(SpGistScanOpaque so,
-				 SpGistSearchItem *parentItem,
+				 const SpGistSearchItem *parentItem,
 				 SpGistNodeTuple tuple,
-				 spgInnerConsistentOut *out, int i, bool isnull,
+				 const spgInnerConsistentOut *out, int i,
+				 bool isnull,
 				 double *distances)
 {
 	SpGistSearchItem *item = spgAllocSearchItem(so, isnull, distances);
diff --git a/src/backend/access/spgist/spgutils.c b/src/backend/access/spgist/spgutils.c
index 87c31da71a5..4b4cc179a94 100644
--- a/src/backend/access/spgist/spgutils.c
+++ b/src/backend/access/spgist/spgutils.c
@@ -794,7 +794,7 @@ SpGistGetInnerTypeSize(SpGistTypeDesc *att, Datum datum)
  * Copy the given non-null datum to *target, in the inner-tuple case
  */
 static void
-memcpyInnerDatum(void *target, SpGistTypeDesc *att, Datum datum)
+memcpyInnerDatum(void *target, const SpGistTypeDesc *att, Datum datum)
 {
 	unsigned int size;
 
diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c
index 370b38e048b..c7f8fbce36b 100644
--- a/src/backend/access/transam/commit_ts.c
+++ b/src/backend/access/transam/commit_ts.c
@@ -109,7 +109,8 @@ static CommitTimestampShared *commitTsShared;
 bool		track_commit_timestamp;
 
 static void SetXidCommitTsInPage(TransactionId xid, int nsubxids,
-								 TransactionId *subxids, TimestampTz ts,
+								 const TransactionId *subxids,
+								 TimestampTz ts,
 								 RepOriginId nodeid, int64 pageno);
 static void TransactionIdSetCommitTs(TransactionId xid, TimestampTz ts,
 									 RepOriginId nodeid, int slotno);
@@ -218,7 +219,8 @@ TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids,
  */
 static void
 SetXidCommitTsInPage(TransactionId xid, int nsubxids,
-					 TransactionId *subxids, TimestampTz ts,
+					 const TransactionId *subxids,
+					 TimestampTz ts,
 					 RepOriginId nodeid, int64 pageno)
 {
 	LWLock	   *lock = SimpleLruGetBankLock(CommitTsCtl, pageno);
diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c
index 72a4e50852a..f5b3c10b9a3 100644
--- a/src/backend/access/transam/multixact.c
+++ b/src/backend/access/transam/multixact.c
@@ -258,7 +258,8 @@ static MemoryContext MXactContext = NULL;
 /* internal MultiXactId management */
 static void MultiXactIdSetOldestVisible(void);
 static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
-							   int nmembers, MultiXactMember *members);
+							   int nmembers,
+							   const MultiXactMember *members);
 static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
 
 /* MultiXact cache management */
@@ -775,7 +776,8 @@ MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
  */
 static void
 RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
-				   int nmembers, MultiXactMember *members)
+				   int nmembers,
+				   const MultiXactMember *members)
 {
 	int64		pageno;
 	int64		prev_pageno;
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6ced1d57282..567f322937f 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -698,7 +698,7 @@ static char *str_time(pg_time_t tnow, char *buf, size_t bufsize);
 static int	get_sync_bit(int method);
 
 static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
-								XLogRecData *rdata,
+								const XLogRecData *rdata,
 								XLogRecPtr StartPos, XLogRecPtr EndPos,
 								TimeLineID tli);
 static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
@@ -1228,7 +1228,7 @@ ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
  * area in the WAL.
  */
 static void
-CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
+CopyXLogRecordToWAL(int write_len, bool isLogSwitch, const XLogRecData *rdata,
 					XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
 {
 	char	   *currpos;
@@ -7612,7 +7612,8 @@ CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
  * startup process.)
  */
 static void
-RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
+RecoveryRestartPoint(const CheckPoint *checkPoint,
+					 const XLogReaderState *record)
 {
 	/*
 	 * Also refrain from creating a restartpoint if we have seen any
diff --git a/src/backend/access/transam/xlogprefetcher.c b/src/backend/access/transam/xlogprefetcher.c
index ed3aacabc98..5516ab73a4e 100644
--- a/src/backend/access/transam/xlogprefetcher.c
+++ b/src/backend/access/transam/xlogprefetcher.c
@@ -230,13 +230,13 @@ lrq_free(LsnReadQueue *lrq)
 }
 
 static inline uint32
-lrq_inflight(LsnReadQueue *lrq)
+lrq_inflight(const LsnReadQueue *lrq)
 {
 	return lrq->inflight;
 }
 
 static inline uint32
-lrq_completed(LsnReadQueue *lrq)
+lrq_completed(const LsnReadQueue *lrq)
 {
 	return lrq->completed;
 }
diff --git a/src/backend/backup/backup_manifest.c b/src/backend/backup/backup_manifest.c
index dd76c9b0b63..9ba73dfc417 100644
--- a/src/backend/backup/backup_manifest.c
+++ b/src/backend/backup/backup_manifest.c
@@ -31,7 +31,7 @@ static void AppendStringToManifest(backup_manifest_info *manifest, const char *s
  * want a manifest, we set manifest->buffile to NULL.
  */
 static inline bool
-IsManifestEnabled(backup_manifest_info *manifest)
+IsManifestEnabled(const backup_manifest_info *manifest)
 {
 	return (manifest->buffile != NULL);
 }
diff --git a/src/backend/backup/basebackup_copy.c b/src/backend/backup/basebackup_copy.c
index eb45d3bcb66..6bbadb054d3 100644
--- a/src/backend/backup/basebackup_copy.c
+++ b/src/backend/backup/basebackup_copy.c
@@ -87,7 +87,7 @@ static void bbsink_copystream_cleanup(bbsink *sink);
 static void SendCopyOutResponse(void);
 static void SendCopyDone(void);
 static void SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli);
-static void SendTablespaceList(List *tablespaces);
+static void SendTablespaceList(const List *tablespaces);
 
 static const bbsink_ops bbsink_copystream_ops = {
 	.begin_backup = bbsink_copystream_begin_backup,
@@ -375,7 +375,7 @@ SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)
  * Send a result set via libpq describing the tablespace list.
  */
 static void
-SendTablespaceList(List *tablespaces)
+SendTablespaceList(const List *tablespaces)
 {
 	DestReceiver *dest;
 	TupOutputState *tstate;
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index 5b410ff14c9..991685cb57b 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -117,14 +117,15 @@ static void ExecGrant_Largeobject(InternalGrant *istmt);
 static void ExecGrant_Type_check(InternalGrant *istmt, HeapTuple tuple);
 static void ExecGrant_Parameter(InternalGrant *istmt);
 
-static void SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames);
+static void SetDefaultACLsInSchemas(InternalDefaultACL *iacls,
+									const List *nspnames);
 static void SetDefaultACL(InternalDefaultACL *iacls);
 
-static List *objectNamesToOids(ObjectType objtype, List *objnames,
+static List *objectNamesToOids(ObjectType objtype, const List *objnames,
 							   bool is_grant);
-static List *objectsInSchemaToOids(ObjectType objtype, List *nspnames);
+static List *objectsInSchemaToOids(ObjectType objtype, const List *nspnames);
 static List *getRelationsInNamespace(Oid namespaceId, char relkind);
-static void expand_col_privileges(List *colnames, Oid table_oid,
+static void expand_col_privileges(const List *colnames, Oid table_oid,
 								  AclMode this_privileges,
 								  AclMode *col_privileges,
 								  int num_col_privileges);
@@ -180,7 +181,8 @@ static void recordExtensionInitPrivWorker(Oid objoid, Oid classoid, int objsubid
 static Acl *
 merge_acl_with_grant(Acl *old_acl, bool is_grant,
 					 bool grant_option, DropBehavior behavior,
-					 List *grantees, AclMode privileges,
+					 const List *grantees,
+					 AclMode privileges,
 					 Oid grantorId, Oid ownerId)
 {
 	unsigned	modechg;
@@ -674,7 +676,7 @@ ExecGrantStmt_oids(InternalGrant *istmt)
  * consumption spikes.
  */
 static List *
-objectNamesToOids(ObjectType objtype, List *objnames, bool is_grant)
+objectNamesToOids(ObjectType objtype, const List *objnames, bool is_grant)
 {
 	List	   *objects = NIL;
 	ListCell   *cell;
@@ -786,7 +788,7 @@ objectNamesToOids(ObjectType objtype, List *objnames, bool is_grant)
  * no privilege checking on the individual objects here.
  */
 static List *
-objectsInSchemaToOids(ObjectType objtype, List *nspnames)
+objectsInSchemaToOids(ObjectType objtype, const List *nspnames)
 {
 	List	   *objects = NIL;
 	ListCell   *cell;
@@ -1102,7 +1104,7 @@ ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *s
  * All fields of *iacls except nspid were filled already
  */
 static void
-SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames)
+SetDefaultACLsInSchemas(InternalDefaultACL *iacls, const List *nspnames)
 {
 	if (nspnames == NIL)
 	{
@@ -1557,7 +1559,7 @@ RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
  * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
  */
 static void
-expand_col_privileges(List *colnames, Oid table_oid,
+expand_col_privileges(const List *colnames, Oid table_oid,
 					  AclMode this_privileges,
 					  AclMode *col_privileges,
 					  int num_col_privileges)
diff --git a/src/backend/catalog/dependency.c b/src/backend/catalog/dependency.c
index 8e70a85a3f7..a1be92de68c 100644
--- a/src/backend/catalog/dependency.c
+++ b/src/backend/catalog/dependency.c
@@ -160,7 +160,8 @@ static void deleteOneObject(const ObjectAddress *object,
 static void doDeletion(const ObjectAddress *object, int flags);
 static bool find_expr_references_walker(Node *node,
 										find_expr_references_context *context);
-static void process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum,
+static void process_function_rte_ref(const RangeTblEntry *rte,
+									 AttrNumber attnum,
 									 find_expr_references_context *context);
 static void eliminate_duplicate_dependencies(ObjectAddresses *addrs);
 static int	object_address_comparator(const void *a, const void *b);
@@ -171,7 +172,7 @@ static void add_exact_object_address_extra(const ObjectAddress *object,
 										   ObjectAddresses *addrs);
 static bool object_address_present_add_flags(const ObjectAddress *object,
 											 int flags,
-											 ObjectAddresses *addrs);
+											 const ObjectAddresses *addrs);
 static bool stack_address_present_add_flags(const ObjectAddress *object,
 											int flags,
 											ObjectAddressStack *stack);
@@ -183,7 +184,7 @@ static void DeleteInitPrivs(const ObjectAddress *object);
  * the actual deletion.
  */
 static void
-deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel,
+deleteObjectsInList(const ObjectAddresses *targetObjects, Relation *depRel,
 					int flags)
 {
 	int			i;
@@ -2377,7 +2378,7 @@ find_expr_references_walker(Node *node,
  * to an RTE_FUNCTION RTE
  */
 static void
-process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum,
+process_function_rte_ref(const RangeTblEntry *rte, AttrNumber attnum,
 						 find_expr_references_context *context)
 {
 	int			atts_done = 0;
@@ -2746,7 +2747,7 @@ object_address_present(const ObjectAddress *object,
 static bool
 object_address_present_add_flags(const ObjectAddress *object,
 								 int flags,
-								 ObjectAddresses *addrs)
+								 const ObjectAddresses *addrs)
 {
 	bool		result = false;
 	int			i;
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index fd6537567ea..206d91cee67 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -105,7 +105,7 @@ static void RelationRemoveInheritance(Oid relid);
 static Oid	StoreRelCheck(Relation rel, const char *ccname, Node *expr,
 						  bool is_enforced, bool is_validated, bool is_local,
 						  int16 inhcount, bool is_no_inherit, bool is_internal);
-static void StoreConstraints(Relation rel, List *cooked_constraints,
+static void StoreConstraints(Relation rel, const List *cooked_constraints,
 							 bool is_internal);
 static bool MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
 										bool allow_merge, bool is_local,
@@ -2307,7 +2307,8 @@ StoreRelNotNull(Relation rel, const char *nnname, AttrNumber attnum,
  * and StoreRelCheck (see AddRelationNewConstraints()).
  */
 static void
-StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
+StoreConstraints(Relation rel, const List *cooked_constraints,
+				 bool is_internal)
 {
 	int			numchecks = 0;
 	ListCell   *lc;
diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index d23474da4fb..1cd7c3479ad 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -4265,7 +4265,7 @@ preprocessNamespacePath(const char *searchPath, Oid roleid,
  * appears in the final list.
  */
 static List *
-finalNamespacePath(List *oidlist, Oid *firstNS)
+finalNamespacePath(const List *oidlist, Oid *firstNS)
 {
 	List	   *finalPath = NIL;
 	ListCell   *lc;
diff --git a/src/backend/catalog/pg_enum.c b/src/backend/catalog/pg_enum.c
index da9c2a46cfa..147e9b302d8 100644
--- a/src/backend/catalog/pg_enum.c
+++ b/src/backend/catalog/pg_enum.c
@@ -65,7 +65,8 @@ static HTAB *uncommitted_enum_values = NULL;
 static void init_uncommitted_enum_types(void);
 static void init_uncommitted_enum_values(void);
 static bool EnumTypeUncommitted(Oid typ_id);
-static void RenumberEnumType(Relation pg_enum, HeapTuple *existing, int nelems);
+static void RenumberEnumType(Relation pg_enum, const HeapTuple *existing,
+							 int nelems);
 static int	sort_order_cmp(const void *p1, const void *p2);
 
 
@@ -771,7 +772,7 @@ AtEOXact_Enum(void)
  * (for example, enum_in and enum_out do so).
  */
 static void
-RenumberEnumType(Relation pg_enum, HeapTuple *existing, int nelems)
+RenumberEnumType(Relation pg_enum, const HeapTuple *existing, int nelems)
 {
 	int			i;
 
diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c
index 0994220c53d..ca8e32e3af2 100644
--- a/src/backend/catalog/pg_publication.c
+++ b/src/backend/catalog/pg_publication.c
@@ -179,7 +179,7 @@ pg_relation_is_publishable(PG_FUNCTION_ARGS)
  * Otherwise, returns false.
  */
 static bool
-is_ancestor_member_tableinfos(Oid ancestor, List *table_infos)
+is_ancestor_member_tableinfos(Oid ancestor, const List *table_infos)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 25089fae3e0..52c0e142ad1 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -79,8 +79,10 @@ static void do_analyze_rel(Relation onerel,
 						   AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
 						   bool inh, bool in_outer_xact, int elevel);
 static void compute_index_stats(Relation onerel, double totalrows,
-								AnlIndexData *indexdata, int nindexes,
-								HeapTuple *rows, int numrows,
+								AnlIndexData *indexdata,
+								int nindexes,
+								const HeapTuple *rows,
+								int numrows,
 								MemoryContext col_context);
 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
 									   Node *index_expr);
@@ -863,8 +865,9 @@ do_analyze_rel(Relation onerel, const VacuumParams params,
  */
 static void
 compute_index_stats(Relation onerel, double totalrows,
-					AnlIndexData *indexdata, int nindexes,
-					HeapTuple *rows, int numrows,
+					AnlIndexData *indexdata,
+					int nindexes,
+					const HeapTuple *rows, int numrows,
 					MemoryContext col_context)
 {
 	MemoryContext ind_context,
@@ -1875,7 +1878,7 @@ static void compute_scalar_stats(VacAttrStatsP stats,
 								 double totalrows);
 static int	compare_scalars(const void *a, const void *b, void *arg);
 static int	compare_mcvs(const void *a, const void *b, void *arg);
-static int	analyze_mcv_list(int *mcv_counts,
+static int	analyze_mcv_list(const int *mcv_counts,
 							 int num_mcv,
 							 double stadistinct,
 							 double stanullfrac,
@@ -2976,7 +2979,7 @@ compare_mcvs(const void *a, const void *b, void *arg)
  * and which are therefore deemed worth storing in the table's MCV list.
  */
 static int
-analyze_mcv_list(int *mcv_counts,
+analyze_mcv_list(const int *mcv_counts,
 				 int num_mcv,
 				 double stadistinct,
 				 double stanullfrac,
diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index d1e772efb72..8e9e8c971cc 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -68,7 +68,7 @@ typedef struct
 } RelToCluster;
 
 
-static void cluster_multiple_rels(List *rtcs, ClusterParams *params);
+static void cluster_multiple_rels(const List *rtcs, ClusterParams *params);
 static void rebuild_relation(Relation OldHeap, Relation index, bool verbose);
 static void copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,
 							bool verbose, bool *pSwapToastByContent,
@@ -260,7 +260,7 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)
  * return.
  */
 static void
-cluster_multiple_rels(List *rtcs, ClusterParams *params)
+cluster_multiple_rels(const List *rtcs, ClusterParams *params)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 12781963b4f..20b7897971f 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -422,7 +422,7 @@ CopyMultiInsertInfoInit(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
  * Returns true if the buffers are full
  */
 static inline bool
-CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
+CopyMultiInsertInfoIsFull(const CopyMultiInsertInfo *miinfo)
 {
 	if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
 		miinfo->bufferedBytes >= MAX_BUFFERED_BYTES)
@@ -434,7 +434,7 @@ CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
  * Returns true if we have no buffered tuples
  */
 static inline bool
-CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
+CopyMultiInsertInfoIsEmpty(const CopyMultiInsertInfo *miinfo)
 {
 	return miinfo->bufferedTuples == 0;
 }
@@ -443,7 +443,7 @@ CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
  * Write the tuples stored in 'buffer' out to the table.
  */
 static inline void
-CopyMultiInsertBufferFlush(CopyMultiInsertInfo *miinfo,
+CopyMultiInsertBufferFlush(const CopyMultiInsertInfo *miinfo,
 						   CopyMultiInsertBuffer *buffer,
 						   int64 *processed)
 {
@@ -659,7 +659,8 @@ CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo,
  * 'curr_rri'.
  */
 static inline void
-CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri,
+CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo,
+						 const ResultRelInfo *curr_rri,
 						 int64 *processed)
 {
 	ListCell   *lc;
@@ -753,8 +754,10 @@ CopyMultiInsertInfoNextFreeSlot(CopyMultiInsertInfo *miinfo,
  * CopyMultiInsertInfoNextFreeSlot as being consumed.
  */
 static inline void
-CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
-						 TupleTableSlot *slot, int tuplen, uint64 lineno)
+CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo,
+						 const ResultRelInfo *rri,
+						 const TupleTableSlot *slot,
+						 int tuplen, uint64 lineno)
 {
 	CopyMultiInsertBuffer *buffer = rri->ri_CopyMultiInsertBuffer;
 
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index cef452584e5..853fc377e3b 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -127,7 +127,8 @@ static void CopyToTextLikeStart(CopyToState cstate, TupleDesc tupDesc);
 static void CopyToTextLikeOutFunc(CopyToState cstate, Oid atttypid, FmgrInfo *finfo);
 static void CopyToTextOneRow(CopyToState cstate, TupleTableSlot *slot);
 static void CopyToCSVOneRow(CopyToState cstate, TupleTableSlot *slot);
-static void CopyToTextLikeOneRow(CopyToState cstate, TupleTableSlot *slot,
+static void CopyToTextLikeOneRow(CopyToState cstate,
+								 const TupleTableSlot *slot,
 								 bool is_csv);
 static void CopyToTextLikeEnd(CopyToState cstate);
 static void CopyToBinaryStart(CopyToState cstate, TupleDesc tupDesc);
@@ -267,7 +268,7 @@ CopyToCSVOneRow(CopyToState cstate, TupleTableSlot *slot)
  */
 static pg_attribute_always_inline void
 CopyToTextLikeOneRow(CopyToState cstate,
-					 TupleTableSlot *slot,
+					 const TupleTableSlot *slot,
 					 bool is_csv)
 {
 	bool		need_delim = false;
diff --git a/src/backend/commands/createas.c b/src/backend/commands/createas.c
index 1ccc2e55c64..ec150b1b8c6 100644
--- a/src/backend/commands/createas.c
+++ b/src/backend/commands/createas.c
@@ -62,7 +62,7 @@ typedef struct
 
 /* utility functions for CTAS definition creation */
 static ObjectAddress create_ctas_internal(List *attrList, IntoClause *into);
-static ObjectAddress create_ctas_nodata(List *tlist, IntoClause *into);
+static ObjectAddress create_ctas_nodata(const List *tlist, IntoClause *into);
 
 /* DestReceiver routines for collecting data */
 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
@@ -152,7 +152,7 @@ create_ctas_internal(List *attrList, IntoClause *into)
  * the targetlist of the SELECT or view definition.
  */
 static ObjectAddress
-create_ctas_nodata(List *tlist, IntoClause *into)
+create_ctas_nodata(const List *tlist, IntoClause *into)
 {
 	List	   *attrList;
 	ListCell   *t,
diff --git a/src/backend/commands/dropcmds.c b/src/backend/commands/dropcmds.c
index ceb9a229b63..2dfddf99f15 100644
--- a/src/backend/commands/dropcmds.c
+++ b/src/backend/commands/dropcmds.c
@@ -34,7 +34,7 @@ static bool owningrel_does_not_exist_skipping(List *object,
 											  const char **msg, char **name);
 static bool schema_does_not_exist_skipping(List *object,
 										   const char **msg, char **name);
-static bool type_in_list_does_not_exist_skipping(List *typenames,
+static bool type_in_list_does_not_exist_skipping(const List *typenames,
 												 const char **msg, char **name);
 
 
@@ -203,7 +203,7 @@ schema_does_not_exist_skipping(List *object, const char **msg, char **name)
  * First parameter is a list of TypeNames.
  */
 static bool
-type_in_list_does_not_exist_skipping(List *typenames, const char **msg,
+type_in_list_does_not_exist_skipping(const List *typenames, const char **msg,
 									 char **name)
 {
 	ListCell   *l;
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..1d1399f1e97 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -145,7 +145,7 @@ static Datum convert_requires_to_datum(List *requires);
 static void ApplyExtensionUpdates(Oid extensionOid,
 								  ExtensionControlFile *pcontrol,
 								  const char *initialVersion,
-								  List *updateVersions,
+								  const List *updateVersions,
 								  char *origSchemaName,
 								  bool cascade,
 								  bool is_create);
@@ -1042,7 +1042,7 @@ execute_sql_string(const char *sql, const char *filename)
  * (Update the errhint logic below if you change this.)
  */
 static bool
-extension_is_trusted(ExtensionControlFile *control)
+extension_is_trusted(const ExtensionControlFile *control)
 {
 	AclResult	aclresult;
 
@@ -1370,7 +1370,7 @@ get_ext_ver_info(const char *versionname, List **evi_list)
  * make it much faster, but for now there's no need.
  */
 static ExtensionVersionInfo *
-get_nearest_unprocessed_vertex(List *evi_list)
+get_nearest_unprocessed_vertex(const List *evi_list)
 {
 	ExtensionVersionInfo *evi = NULL;
 	ListCell   *lc;
@@ -3426,7 +3426,7 @@ static void
 ApplyExtensionUpdates(Oid extensionOid,
 					  ExtensionControlFile *pcontrol,
 					  const char *initialVersion,
-					  List *updateVersions,
+					  const List *updateVersions,
 					  char *origSchemaName,
 					  bool cascade,
 					  bool is_create)
diff --git a/src/backend/commands/foreigncmds.c b/src/backend/commands/foreigncmds.c
index 536065dc515..e2609a96c0b 100644
--- a/src/backend/commands/foreigncmds.c
+++ b/src/backend/commands/foreigncmds.c
@@ -63,7 +63,7 @@ static void import_error_callback(void *arg);
  * conversion.
  */
 static Datum
-optionListToArray(List *options)
+optionListToArray(const List *options)
 {
 	ArrayBuildState *astate = NULL;
 	ListCell   *cell;
@@ -483,7 +483,7 @@ AlterForeignServerOwner_oid(Oid srvId, Oid newOwnerId)
  * Convert a handler function name passed from the parser to an Oid.
  */
 static Oid
-lookup_fdw_handler_func(DefElem *handler)
+lookup_fdw_handler_func(const DefElem *handler)
 {
 	Oid			handlerOid;
 
@@ -507,7 +507,7 @@ lookup_fdw_handler_func(DefElem *handler)
  * Convert a validator function name passed from the parser to an Oid.
  */
 static Oid
-lookup_fdw_validator_func(DefElem *validator)
+lookup_fdw_validator_func(const DefElem *validator)
 {
 	Oid			funcargtypes[2];
 
@@ -526,7 +526,7 @@ lookup_fdw_validator_func(DefElem *validator)
  * Process function options of CREATE/ALTER FDW
  */
 static void
-parse_func_options(ParseState *pstate, List *func_options,
+parse_func_options(ParseState *pstate, const List *func_options,
 				   bool *handler_given, Oid *fdwhandler,
 				   bool *validator_given, Oid *fdwvalidator)
 {
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 59d00638ee6..3102f5383de 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -659,7 +659,7 @@ interpret_func_parallel(DefElem *defel)
  * The input and result may be NULL to signify a null entry.
  */
 static ArrayType *
-update_proconfig_value(ArrayType *a, List *set_items)
+update_proconfig_value(ArrayType *a, const List *set_items)
 {
 	ListCell   *l;
 
@@ -730,7 +730,7 @@ interpret_func_support(DefElem *defel)
 static void
 compute_function_attributes(ParseState *pstate,
 							bool is_procedure,
-							List *options,
+							const List *options,
 							List **as,
 							char **language,
 							Node **transform,
diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c
index a6dd8eab518..1522461a30a 100644
--- a/src/backend/commands/opclasscmds.c
+++ b/src/backend/commands/opclasscmds.c
@@ -51,25 +51,28 @@
 static void AlterOpFamilyAdd(AlterOpFamilyStmt *stmt,
 							 Oid amoid, Oid opfamilyoid,
 							 int maxOpNumber, int maxProcNumber,
-							 int optsProcNumber, List *items);
+							 int optsProcNumber,
+							 const List *items);
 static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt,
 							  Oid amoid, Oid opfamilyoid,
 							  int maxOpNumber, int maxProcNumber,
-							  List *items);
+							  const List *items);
 static void processTypesSpec(List *args, Oid *lefttype, Oid *righttype);
 static void assignOperTypes(OpFamilyMember *member, Oid amoid, Oid typeoid);
 static void assignProcTypes(OpFamilyMember *member, Oid amoid, Oid typeoid,
 							int opclassOptsProcNum);
 static void addFamilyMember(List **list, OpFamilyMember *member);
 static void storeOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-						   List *operators, bool isAdd);
+						   const List *operators,
+						   bool isAdd);
 static void storeProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-							List *procedures, bool isAdd);
+							const List *procedures,
+							bool isAdd);
 static bool typeDepNeeded(Oid typid, OpFamilyMember *member);
 static void dropOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-						  List *operators);
+						  const List *operators);
 static void dropProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-						   List *procedures);
+						   const List *procedures);
 
 /*
  * OpFamilyCacheLookup
@@ -880,7 +883,7 @@ AlterOpFamily(AlterOpFamilyStmt *stmt)
 static void
 AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
 				 int maxOpNumber, int maxProcNumber, int optsProcNumber,
-				 List *items)
+				 const List *items)
 {
 	IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(amoid, false);
 	List	   *operators;		/* OpFamilyMember list for operators */
@@ -1028,7 +1031,8 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
  */
 static void
 AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
-				  int maxOpNumber, int maxProcNumber, List *items)
+				  int maxOpNumber, int maxProcNumber,
+				  const List *items)
 {
 	List	   *operators;		/* OpFamilyMember list for operators */
 	List	   *procedures;		/* OpFamilyMember list for support procs */
@@ -1452,7 +1456,7 @@ addFamilyMember(List **list, OpFamilyMember *member)
  */
 static void
 storeOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-			   List *operators, bool isAdd)
+			   const List *operators, bool isAdd)
 {
 	Relation	rel;
 	Datum		values[Natts_pg_amop];
@@ -1582,7 +1586,7 @@ storeOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
  */
 static void
 storeProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-				List *procedures, bool isAdd)
+				const List *procedures, bool isAdd)
 {
 	Relation	rel;
 	Datum		values[Natts_pg_amproc];
@@ -1748,7 +1752,7 @@ typeDepNeeded(Oid typid, OpFamilyMember *member)
  */
 static void
 dropOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-			  List *operators)
+			  const List *operators)
 {
 	ListCell   *l;
 
@@ -1788,7 +1792,7 @@ dropOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
  */
 static void
 dropProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
-			   List *procedures)
+			   const List *procedures)
 {
 	ListCell   *l;
 
diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c
index 34b6410d6a2..ead69134df5 100644
--- a/src/backend/commands/prepare.c
+++ b/src/backend/commands/prepare.c
@@ -50,7 +50,7 @@ static void InitQueryHashTable(void);
 static ParamListInfo EvaluateParams(ParseState *pstate,
 									PreparedStatement *pstmt, List *params,
 									EState *estate);
-static Datum build_regtype_array(Oid *param_types, int num_params);
+static Datum build_regtype_array(const Oid *param_types, int num_params);
 
 /*
  * Implements the 'PREPARE' utility statement.
@@ -744,7 +744,7 @@ pg_prepared_statement(PG_FUNCTION_ARGS)
  * array is returned as a zero-element array, not NULL.
  */
 static Datum
-build_regtype_array(Oid *param_types, int num_params)
+build_regtype_array(const Oid *param_types, int num_params)
 {
 	Datum	   *tmp_ary;
 	ArrayType  *result;
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index 51567994126..41c9c02ab6a 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -93,7 +93,8 @@ static void create_seq_hashtable(void);
 static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
 static Form_pg_sequence_data read_seq_tuple(Relation rel,
 											Buffer *buf, HeapTuple seqdatatuple);
-static void init_params(ParseState *pstate, List *options, bool for_identity,
+static void init_params(ParseState *pstate, const List *options,
+						bool for_identity,
 						bool isInit,
 						Form_pg_sequence seqform,
 						int64 *last_value,
@@ -1257,7 +1258,7 @@ read_seq_tuple(Relation rel, Buffer *buf, HeapTuple seqdatatuple)
  * relfilenumber.
  */
 static void
-init_params(ParseState *pstate, List *options, bool for_identity,
+init_params(ParseState *pstate, const List *options, bool for_identity,
 			bool isInit,
 			Form_pg_sequence seqform,
 			int64 *last_value,
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..1f28b9cfcbd 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -42,7 +42,7 @@
 
 static char *ChooseExtendedStatisticName(const char *name1, const char *name2,
 										 const char *label, Oid namespaceid);
-static char *ChooseExtendedStatisticNameAddition(List *exprs);
+static char *ChooseExtendedStatisticNameAddition(const List *exprs);
 
 
 /* qsort comparator for the attnums in CreateStatistics */
@@ -888,7 +888,7 @@ ChooseExtendedStatisticName(const char *name1, const char *name2,
  * ChooseIndexNameAddition.
  */
 static char *
-ChooseExtendedStatisticNameAddition(List *exprs)
+ChooseExtendedStatisticNameAddition(const List *exprs)
 {
 	char		buf[NAMEDATALEN * 2];
 	int			buflen = 0;
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 8c856af3493..ceb64bb078e 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -121,19 +121,20 @@ static void check_publications_origin_tables(WalReceiverConn *wrconn,
 											 List *publications, bool copydata,
 											 bool retain_dead_tuples,
 											 char *origin,
-											 Oid *subrel_local_oids,
+											 const Oid *subrel_local_oids,
 											 int subrel_count, char *subname);
 static void check_publications_origin_sequences(WalReceiverConn *wrconn,
 												List *publications,
 												bool copydata, char *origin,
-												Oid *subrel_local_oids,
+												const Oid *subrel_local_oids,
 												int subrel_count,
 												char *subname);
 static void check_pub_dead_tuple_retention(WalReceiverConn *wrconn);
-static void check_duplicates_in_publist(List *publist, Datum *datums);
+static void check_duplicates_in_publist(const List *publist, Datum *datums);
 static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
-static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
-static void CheckAlterSubOption(Subscription *sub, const char *option,
+static void ReportSlotConnectionError(const List *rstates, Oid subid,
+									  char *slotname, char *err);
+static void CheckAlterSubOption(const Subscription *sub, const char *option,
 								bool slot_needs_update, bool isTopLevel);
 
 
@@ -144,7 +145,7 @@ static void CheckAlterSubOption(Subscription *sub, const char *option,
  * will report an error if mutually exclusive options are specified.
  */
 static void
-parse_subscription_options(ParseState *pstate, List *stmt_options,
+parse_subscription_options(ParseState *pstate, const List *stmt_options,
 						   bits32 supported_opts, SubOpts *opts)
 {
 	ListCell   *lc;
@@ -1240,7 +1241,7 @@ AlterSubscription_refresh_seq(Subscription *sub)
  * options.
  */
 static void
-CheckAlterSubOption(Subscription *sub, const char *option,
+CheckAlterSubOption(const Subscription *sub, const char *option,
 					bool slot_needs_update, bool isTopLevel)
 {
 	Assert(strcmp(option, "failover") == 0 ||
@@ -2494,7 +2495,8 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
 static void
 check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
 								 bool copydata, bool retain_dead_tuples,
-								 char *origin, Oid *subrel_local_oids,
+								 char *origin,
+								 const Oid *subrel_local_oids,
 								 int subrel_count, char *subname)
 {
 	WalRcvExecResult *res;
@@ -2637,7 +2639,8 @@ check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
 static void
 check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications,
 									bool copydata, char *origin,
-									Oid *subrel_local_oids, int subrel_count,
+									const Oid *subrel_local_oids,
+									int subrel_count,
 									char *subname)
 {
 	WalRcvExecResult *res;
@@ -2994,7 +2997,8 @@ fetch_relation_list(WalReceiverConn *wrconn, List *publications)
  * them manually, if required.
  */
 static void
-ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
+ReportSlotConnectionError(const List *rstates, Oid subid, char *slotname,
+						  char *err)
 {
 	ListCell   *lc;
 
@@ -3038,7 +3042,7 @@ ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
  * NULL.
  */
 static void
-check_duplicates_in_publist(List *publist, Datum *datums)
+check_duplicates_in_publist(const List *publist, Datum *datums)
 {
 	ListCell   *cell;
 	int			j = 0;
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..764965392c6 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -3945,7 +3945,7 @@ static void AfterTriggerExecute(EState *estate,
 								ResultRelInfo *relInfo,
 								ResultRelInfo *src_relInfo,
 								ResultRelInfo *dst_relInfo,
-								TriggerDesc *trigdesc,
+								const TriggerDesc *trigdesc,
 								FmgrInfo *finfo,
 								Instrumentation *instr,
 								MemoryContext per_tuple_context,
@@ -3958,9 +3958,9 @@ static TupleTableSlot *GetAfterTriggersStoreSlot(AfterTriggersTableData *table,
 static Tuplestorestate *GetAfterTriggersTransitionTable(int event,
 														TupleTableSlot *oldslot,
 														TupleTableSlot *newslot,
-														TransitionCaptureState *transition_capture);
+														const TransitionCaptureState *transition_capture);
 static void TransitionTableAddTuple(EState *estate,
-									TransitionCaptureState *transition_capture,
+									const TransitionCaptureState *transition_capture,
 									ResultRelInfo *relinfo,
 									TupleTableSlot *slot,
 									TupleTableSlot *original_insert_tuple,
@@ -4339,8 +4339,9 @@ AfterTriggerExecute(EState *estate,
 					ResultRelInfo *relInfo,
 					ResultRelInfo *src_relInfo,
 					ResultRelInfo *dst_relInfo,
-					TriggerDesc *trigdesc,
-					FmgrInfo *finfo, Instrumentation *instr,
+					const TriggerDesc *trigdesc,
+					FmgrInfo *finfo,
+					Instrumentation *instr,
 					MemoryContext per_tuple_context,
 					TupleTableSlot *trig_tuple_slot1,
 					TupleTableSlot *trig_tuple_slot2)
@@ -4626,7 +4627,7 @@ AfterTriggerExecute(EState *estate,
  *	Returns true if any invokable events were found.
  */
 static bool
-afterTriggerMarkEvents(AfterTriggerEventList *events,
+afterTriggerMarkEvents(const AfterTriggerEventList *events,
 					   AfterTriggerEventList *move_list,
 					   bool immediate_only)
 {
@@ -5532,7 +5533,7 @@ static Tuplestorestate *
 GetAfterTriggersTransitionTable(int event,
 								TupleTableSlot *oldslot,
 								TupleTableSlot *newslot,
-								TransitionCaptureState *transition_capture)
+								const TransitionCaptureState *transition_capture)
 {
 	Tuplestorestate *tuplestore = NULL;
 	bool		delete_old_table = transition_capture->tcs_delete_old_table;
@@ -5581,7 +5582,7 @@ GetAfterTriggersTransitionTable(int event,
  */
 static void
 TransitionTableAddTuple(EState *estate,
-						TransitionCaptureState *transition_capture,
+						const TransitionCaptureState *transition_capture,
 						ResultRelInfo *relinfo,
 						TupleTableSlot *slot,
 						TupleTableSlot *original_insert_tuple,
diff --git a/src/backend/commands/tsearchcmds.c b/src/backend/commands/tsearchcmds.c
index dc7df736fb8..f93d4ac1ffd 100644
--- a/src/backend/commands/tsearchcmds.c
+++ b/src/backend/commands/tsearchcmds.c
@@ -1201,7 +1201,7 @@ AlterTSConfiguration(AlterTSConfigurationStmt *stmt)
  * Check whether a token type name is a member of a TSTokenTypeItem list.
  */
 static bool
-tstoken_list_member(char *token_name, List *tokens)
+tstoken_list_member(char *token_name, const List *tokens)
 {
 	ListCell   *c;
 	bool		found = false;
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index 6ae42ea5656..78575f4a228 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -101,7 +101,7 @@ static void check_role_membership_authorization(Oid currentUserId, Oid roleid,
 												bool is_grant);
 static Oid	check_role_grantor(Oid currentUserId, Oid roleid, Oid grantorId,
 							   bool is_grant);
-static RevokeRoleGrantAction *initialize_revoke_actions(CatCList *memlist);
+static RevokeRoleGrantAction *initialize_revoke_actions(const CatCList *memlist);
 static bool plan_single_revoke(CatCList *memlist,
 							   RevokeRoleGrantAction *actions,
 							   Oid member, Oid grantor,
@@ -2287,7 +2287,7 @@ check_role_grantor(Oid currentUserId, Oid roleid, Oid grantorId, bool is_grant)
  * that is, every element is initially RRG_NOOP.
  */
 static RevokeRoleGrantAction *
-initialize_revoke_actions(CatCList *memlist)
+initialize_revoke_actions(const CatCList *memlist)
 {
 	RevokeRoleGrantAction *result;
 	int			i;
diff --git a/src/backend/commands/vacuumparallel.c b/src/backend/commands/vacuumparallel.c
index 0feea1d30ec..893cba404bb 100644
--- a/src/backend/commands/vacuumparallel.c
+++ b/src/backend/commands/vacuumparallel.c
@@ -221,7 +221,9 @@ struct ParallelVacuumState
 	PVIndVacStatus status;
 };
 
-static int	parallel_vacuum_compute_workers(Relation *indrels, int nindexes, int nrequested,
+static int	parallel_vacuum_compute_workers(const Relation *indrels,
+											int nindexes,
+											int nrequested,
 											bool *will_parallel_vacuum);
 static void parallel_vacuum_process_all_indexes(ParallelVacuumState *pvs, int num_index_scans,
 												bool vacuum);
@@ -546,7 +548,8 @@ parallel_vacuum_cleanup_all_indexes(ParallelVacuumState *pvs, long num_table_tup
  * vacuum.
  */
 static int
-parallel_vacuum_compute_workers(Relation *indrels, int nindexes, int nrequested,
+parallel_vacuum_compute_workers(const Relation *indrels, int nindexes,
+								int nrequested,
 								bool *will_parallel_vacuum)
 {
 	int			nindexes_parallel = 0;
diff --git a/src/backend/commands/view.c b/src/backend/commands/view.c
index 4cc2af7b5ec..d4757872c44 100644
--- a/src/backend/commands/view.c
+++ b/src/backend/commands/view.c
@@ -41,7 +41,7 @@ static void checkViewColumns(TupleDesc newdesc, TupleDesc olddesc);
  *---------------------------------------------------------------------
  */
 static ObjectAddress
-DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace,
+DefineVirtualRelation(RangeVar *relation, const List *tlist, bool replace,
 					  List *options, Query *viewParse)
 {
 	Oid			viewOid;
diff --git a/src/backend/executor/execCurrent.c b/src/backend/executor/execCurrent.c
index 3bfdc0230ff..131fb6eb770 100644
--- a/src/backend/executor/execCurrent.c
+++ b/src/backend/executor/execCurrent.c
@@ -23,7 +23,8 @@
 #include "utils/rel.h"
 
 
-static char *fetch_cursor_param_value(ExprContext *econtext, int paramId);
+static char *fetch_cursor_param_value(const ExprContext *econtext,
+									  int paramId);
 static ScanState *search_plan_tree(PlanState *node, Oid table_oid,
 								   bool *pending_rescan);
 
@@ -255,7 +256,7 @@ execCurrentOf(CurrentOfExpr *cexpr,
  * Fetch the string value of a param, verifying it is of type REFCURSOR.
  */
 static char *
-fetch_cursor_param_value(ExprContext *econtext, int paramId)
+fetch_cursor_param_value(const ExprContext *econtext, int paramId)
 {
 	ParamListInfo paramInfo = econtext->ecxt_param_list_info;
 
diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 5e7bd933afc..8523e726c28 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -145,8 +145,10 @@ static Datum ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnul
 static void ExecInitInterpreter(void);
 
 /* support functions */
-static void CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype);
-static void CheckOpSlotCompatibility(ExprEvalStep *op, TupleTableSlot *slot);
+static void CheckVarSlotCompatibility(const TupleTableSlot *slot, int attnum,
+									  Oid vartype);
+static void CheckOpSlotCompatibility(const ExprEvalStep *op,
+									 const TupleTableSlot *slot);
 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
 									ExprEvalRowtypeCache *rowcache,
 									bool *changed);
@@ -168,12 +170,14 @@ static Datum ExecJustScanVarVirt(ExprState *state, ExprContext *econtext, bool *
 static Datum ExecJustAssignInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
 static Datum ExecJustAssignOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
 static Datum ExecJustAssignScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
-static Datum ExecJustHashInnerVarWithIV(ExprState *state, ExprContext *econtext, bool *isnull);
+static Datum ExecJustHashInnerVarWithIV(const ExprState *state,
+										ExprContext *econtext, bool *isnull);
 static Datum ExecJustHashOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
 static Datum ExecJustHashInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
 static Datum ExecJustHashOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
 static Datum ExecJustHashInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
-static Datum ExecJustHashOuterVarStrict(ExprState *state, ExprContext *econtext, bool *isnull);
+static Datum ExecJustHashOuterVarStrict(const ExprState *state,
+										ExprContext *econtext, bool *isnull);
 
 /* execution helper functions */
 static pg_attribute_always_inline void ExecAggPlainTransByVal(AggState *aggstate,
@@ -206,9 +210,10 @@ typedef struct ScalarArrayOpExprHashEntry
 #define SH_DECLARE
 #include "lib/simplehash.h"
 
-static bool saop_hash_element_match(struct saophash_hash *tb, Datum key1,
+static bool saop_hash_element_match(const struct saophash_hash *tb,
+									Datum key1,
 									Datum key2);
-static uint32 saop_element_hash(struct saophash_hash *tb, Datum key);
+static uint32 saop_element_hash(const struct saophash_hash *tb, Datum key);
 
 /*
  * ScalarArrayOpExprHashTable
@@ -2375,7 +2380,7 @@ CheckExprStillValid(ExprState *state, ExprContext *econtext)
  * since the expression tree has been created.
  */
 static void
-CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype)
+CheckVarSlotCompatibility(const TupleTableSlot *slot, int attnum, Oid vartype)
 {
 	/*
 	 * What we have to check for here is the possibility of an attribute
@@ -2430,7 +2435,7 @@ CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype)
  * Verify that the slot is compatible with a EEOP_*_FETCHSOME operation.
  */
 static void
-CheckOpSlotCompatibility(ExprEvalStep *op, TupleTableSlot *slot)
+CheckOpSlotCompatibility(const ExprEvalStep *op, const TupleTableSlot *slot)
 {
 #ifdef USE_ASSERT_CHECKING
 	/* there's nothing to check */
@@ -2543,7 +2548,7 @@ get_cached_rowtype(Oid type_id, int32 typmod,
 
 /* implementation of ExecJust(Inner|Outer|Scan)Var */
 static pg_attribute_always_inline Datum
-ExecJustVarImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
+ExecJustVarImpl(const ExprState *state, TupleTableSlot *slot, bool *isnull)
 {
 	ExprEvalStep *op = &state->steps[1];
 	int			attnum = op->d.var.attnum + 1;
@@ -2581,7 +2586,8 @@ ExecJustScanVar(ExprState *state, ExprContext *econtext, bool *isnull)
 
 /* implementation of ExecJustAssign(Inner|Outer|Scan)Var */
 static pg_attribute_always_inline Datum
-ExecJustAssignVarImpl(ExprState *state, TupleTableSlot *inslot, bool *isnull)
+ExecJustAssignVarImpl(const ExprState *state, TupleTableSlot *inslot,
+					  bool *isnull)
 {
 	ExprEvalStep *op = &state->steps[1];
 	int			attnum = op->d.assign_var.attnum + 1;
@@ -2676,7 +2682,8 @@ ExecJustConst(ExprState *state, ExprContext *econtext, bool *isnull)
 
 /* implementation of ExecJust(Inner|Outer|Scan)VarVirt */
 static pg_attribute_always_inline Datum
-ExecJustVarVirtImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
+ExecJustVarVirtImpl(const ExprState *state, TupleTableSlot *slot,
+					bool *isnull)
 {
 	ExprEvalStep *op = &state->steps[0];
 	int			attnum = op->d.var.attnum;
@@ -2719,7 +2726,8 @@ ExecJustScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
 
 /* implementation of ExecJustAssign(Inner|Outer|Scan)VarVirt */
 static pg_attribute_always_inline Datum
-ExecJustAssignVarVirtImpl(ExprState *state, TupleTableSlot *inslot, bool *isnull)
+ExecJustAssignVarVirtImpl(const ExprState *state, TupleTableSlot *inslot,
+						  bool *isnull)
 {
 	ExprEvalStep *op = &state->steps[0];
 	int			attnum = op->d.assign_var.attnum;
@@ -2764,7 +2772,7 @@ ExecJustAssignScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
  * implementation for hashing an inner Var, seeding with an initial value.
  */
 static Datum
-ExecJustHashInnerVarWithIV(ExprState *state, ExprContext *econtext,
+ExecJustHashInnerVarWithIV(const ExprState *state, ExprContext *econtext,
 						   bool *isnull)
 {
 	ExprEvalStep *fetchop = &state->steps[0];
@@ -2798,7 +2806,8 @@ ExecJustHashInnerVarWithIV(ExprState *state, ExprContext *econtext,
 
 /* implementation of ExecJustHash(Inner|Outer)Var */
 static pg_attribute_always_inline Datum
-ExecJustHashVarImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
+ExecJustHashVarImpl(const ExprState *state, TupleTableSlot *slot,
+					bool *isnull)
 {
 	ExprEvalStep *fetchop = &state->steps[0];
 	ExprEvalStep *var = &state->steps[1];
@@ -2836,7 +2845,8 @@ ExecJustHashInnerVar(ExprState *state, ExprContext *econtext, bool *isnull)
 
 /* implementation of ExecJustHash(Inner|Outer)VarVirt */
 static pg_attribute_always_inline Datum
-ExecJustHashVarVirtImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
+ExecJustHashVarVirtImpl(const ExprState *state, const TupleTableSlot *slot,
+						bool *isnull)
 {
 	ExprEvalStep *var = &state->steps[0];
 	ExprEvalStep *hashop = &state->steps[1];
@@ -2874,7 +2884,7 @@ ExecJustHashOuterVarVirt(ExprState *state, ExprContext *econtext,
  * implementation for hashing an outer Var.  Returns NULL on NULL input.
  */
 static Datum
-ExecJustHashOuterVarStrict(ExprState *state, ExprContext *econtext,
+ExecJustHashOuterVarStrict(const ExprState *state, ExprContext *econtext,
 						   bool *isnull)
 {
 	ExprEvalStep *fetchop = &state->steps[0];
@@ -4173,7 +4183,7 @@ ExecEvalScalarArrayOp(ExprState *state, ExprEvalStep *op)
  * if the type is collation-sensitive.
  */
 static uint32
-saop_element_hash(struct saophash_hash *tb, Datum key)
+saop_element_hash(const struct saophash_hash *tb, Datum key)
 {
 	ScalarArrayOpExprHashTable *elements_tab = (ScalarArrayOpExprHashTable *) tb->private_data;
 	FunctionCallInfo fcinfo = &elements_tab->hash_fcinfo_data;
@@ -4192,7 +4202,8 @@ saop_element_hash(struct saophash_hash *tb, Datum key)
  * lookups.
  */
 static bool
-saop_hash_element_match(struct saophash_hash *tb, Datum key1, Datum key2)
+saop_hash_element_match(const struct saophash_hash *tb, Datum key1,
+						Datum key2)
 {
 	Datum		result;
 
@@ -5161,7 +5172,7 @@ ExecEvalJsonCoercion(ExprState *state, ExprEvalStep *op,
 }
 
 static char *
-GetJsonBehaviorValueString(JsonBehavior *behavior)
+GetJsonBehaviorValueString(const JsonBehavior *behavior)
 {
 	/*
 	 * The order of array elements must correspond to the order of
diff --git a/src/backend/executor/execGrouping.c b/src/backend/executor/execGrouping.c
index 8b64a625ca5..d2067375d4c 100644
--- a/src/backend/executor/execGrouping.c
+++ b/src/backend/executor/execGrouping.c
@@ -23,8 +23,10 @@
 #include "miscadmin.h"
 #include "utils/lsyscache.h"
 
-static int	TupleHashTableMatch(struct tuplehash_hash *tb, MinimalTuple tuple1, MinimalTuple tuple2);
-static inline uint32 TupleHashTableHash_internal(struct tuplehash_hash *tb,
+static int	TupleHashTableMatch(const struct tuplehash_hash *tb,
+								MinimalTuple tuple1,
+								MinimalTuple tuple2);
+static inline uint32 TupleHashTableHash_internal(const struct tuplehash_hash *tb,
 												 MinimalTuple tuple);
 static inline TupleHashEntry LookupTupleHashEntry_internal(TupleHashTable hashtable,
 														   TupleTableSlot *slot,
@@ -499,7 +501,7 @@ FindTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot,
  * the hash functions.
  */
 static uint32
-TupleHashTableHash_internal(struct tuplehash_hash *tb,
+TupleHashTableHash_internal(const struct tuplehash_hash *tb,
 							MinimalTuple tuple)
 {
 	TupleHashTable hashtable = (TupleHashTable) tb->private_data;
@@ -598,7 +600,8 @@ LookupTupleHashEntry_internal(TupleHashTable hashtable, TupleTableSlot *slot,
  * See whether two tuples (presumably of the same hash value) match
  */
 static int
-TupleHashTableMatch(struct tuplehash_hash *tb, MinimalTuple tuple1, MinimalTuple tuple2)
+TupleHashTableMatch(const struct tuplehash_hash *tb, MinimalTuple tuple1,
+					MinimalTuple tuple2)
 {
 	TupleTableSlot *slot1;
 	TupleTableSlot *slot2;
diff --git a/src/backend/executor/execParallel.c b/src/backend/executor/execParallel.c
index 0125464d942..8bf12f84787 100644
--- a/src/backend/executor/execParallel.c
+++ b/src/backend/executor/execParallel.c
@@ -125,7 +125,7 @@ typedef struct ExecParallelInitializeDSMContext
 } ExecParallelInitializeDSMContext;
 
 /* Helper functions that run in the parallel leader. */
-static char *ExecSerializePlan(Plan *plan, EState *estate);
+static char *ExecSerializePlan(Plan *plan, const EState *estate);
 static bool ExecParallelEstimate(PlanState *planstate,
 								 ExecParallelEstimateContext *e);
 static bool ExecParallelInitializeDSM(PlanState *planstate,
@@ -144,7 +144,7 @@ static DestReceiver *ExecParallelGetReceiver(dsm_segment *seg, shm_toc *toc);
  * Create a serialized representation of the plan to be sent to each worker.
  */
 static char *
-ExecSerializePlan(Plan *plan, EState *estate)
+ExecSerializePlan(Plan *plan, const EState *estate)
 {
 	PlannedStmt *pstmt;
 	ListCell   *lc;
@@ -323,7 +323,7 @@ ExecParallelEstimate(PlanState *planstate, ExecParallelEstimateContext *e)
  * Estimate the amount of space required to serialize the indicated parameters.
  */
 static Size
-EstimateParamExecSpace(EState *estate, Bitmapset *params)
+EstimateParamExecSpace(const EState *estate, Bitmapset *params)
 {
 	int			paramid;
 	Size		sz = sizeof(int);
@@ -422,7 +422,7 @@ SerializeParamExecParams(EState *estate, Bitmapset *params, dsa_area *area)
  * Restore specified PARAM_EXEC parameters.
  */
 static void
-RestoreParamExecParams(char *start_address, EState *estate)
+RestoreParamExecParams(char *start_address, const EState *estate)
 {
 	int			nparams;
 	int			i;
diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c
index b3960bb7151..bbd822aaff8 100644
--- a/src/backend/executor/execPartition.c
+++ b/src/backend/executor/execPartition.c
@@ -181,7 +181,8 @@ static char *ExecBuildSlotPartitionKeyDescription(Relation rel,
 												  const bool *isnull,
 												  int maxfieldlen);
 static List *adjust_partition_colnos(List *colnos, ResultRelInfo *leaf_part_rri);
-static List *adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap);
+static List *adjust_partition_colnos_using_map(const List *colnos,
+											   const AttrMap *attrMap);
 static PartitionPruneState *CreatePartitionPruneState(EState *estate,
 													  PartitionPruneInfo *pruneinfo,
 													  Bitmapset **all_leafpart_rtis);
@@ -500,9 +501,9 @@ ExecFindPartition(ModifyTableState *mtstate,
  */
 static bool
 IsIndexCompatibleAsArbiter(Relation arbiterIndexRelation,
-						   IndexInfo *arbiterIndexInfo,
+						   const IndexInfo *arbiterIndexInfo,
 						   Relation indexRelation,
-						   IndexInfo *indexInfo)
+						   const IndexInfo *indexInfo)
 {
 	Assert(arbiterIndexRelation->rd_index->indrelid == indexRelation->rd_index->indrelid);
 
@@ -1854,7 +1855,7 @@ adjust_partition_colnos(List *colnos, ResultRelInfo *leaf_part_rri)
  * Note: mustn't be called if no adjustment is required.
  */
 static List *
-adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap)
+adjust_partition_colnos_using_map(const List *colnos, const AttrMap *attrMap)
 {
 	List	   *new_colnos = NIL;
 	ListCell   *lc;
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index def32774c90..fe58a3b9a0c 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -55,7 +55,7 @@ static bool tuples_equal(TupleTableSlot *slot1, TupleTableSlot *slot2,
  */
 static int
 build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
-						 TupleTableSlot *searchslot)
+						 const TupleTableSlot *searchslot)
 {
 	int			index_attoff;
 	int			skey_attoff = 0;
@@ -448,7 +448,7 @@ retry:
  * Build additional index information necessary for conflict detection.
  */
 static void
-BuildConflictIndexInfo(ResultRelInfo *resultRelInfo, Oid conflictindex)
+BuildConflictIndexInfo(const ResultRelInfo *resultRelInfo, Oid conflictindex)
 {
 	for (int i = 0; i < resultRelInfo->ri_NumIndices; i++)
 	{
diff --git a/src/backend/executor/execTuples.c b/src/backend/executor/execTuples.c
index 8e02d68824f..b82f229819f 100644
--- a/src/backend/executor/execTuples.c
+++ b/src/backend/executor/execTuples.c
@@ -1016,7 +1016,7 @@ tts_buffer_heap_store_tuple(TupleTableSlot *slot, HeapTuple tuple,
  * slow mode.
  */
 static pg_attribute_always_inline int
-slot_deform_heap_tuple_internal(TupleTableSlot *slot, HeapTuple tuple,
+slot_deform_heap_tuple_internal(const TupleTableSlot *slot, HeapTuple tuple,
 								int attnum, int natts, bool slow,
 								bool hasnulls, uint32 *offp, bool *slowp)
 {
diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c
index fdc65c2b42b..3ac27284433 100644
--- a/src/backend/executor/execUtils.c
+++ b/src/backend/executor/execUtils.c
@@ -64,7 +64,8 @@
 
 static bool tlist_matches_tupdesc(PlanState *ps, List *tlist, int varno, TupleDesc tupdesc);
 static void ShutdownExprContext(ExprContext *econtext, bool isCommit);
-static RTEPermissionInfo *GetResultRTEPermissionInfo(ResultRelInfo *relinfo, EState *estate);
+static RTEPermissionInfo *GetResultRTEPermissionInfo(const ResultRelInfo *relinfo,
+													 EState *estate);
 
 
 /* ----------------------------------------------------------------
@@ -1435,7 +1436,7 @@ ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
  *		Looks up RTEPermissionInfo for ExecGet*Cols() routines
  */
 static RTEPermissionInfo *
-GetResultRTEPermissionInfo(ResultRelInfo *relinfo, EState *estate)
+GetResultRTEPermissionInfo(const ResultRelInfo *relinfo, EState *estate)
 {
 	Index		rti;
 	RangeTblEntry *rte;
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 630d708d2a3..b088407dd9f 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -223,8 +223,8 @@ static void sql_compile_error_callback(void *arg);
 static void sql_exec_error_callback(void *arg);
 static void ShutdownSQLFunction(Datum arg);
 static void RemoveSQLFunctionCache(void *arg);
-static void check_sql_fn_statement(List *queryTreeList);
-static bool check_sql_stmt_retval(List *queryTreeList,
+static void check_sql_fn_statement(const List *queryTreeList);
+static bool check_sql_stmt_retval(const List *queryTreeList,
 								  Oid rettype, TupleDesc rettupdesc,
 								  char prokind, bool insertDroppedCols);
 static bool coerce_fn_result_column(TargetEntry *src_tle,
@@ -232,7 +232,7 @@ static bool coerce_fn_result_column(TargetEntry *src_tle,
 									bool tlist_is_modifiable,
 									List **upper_tlist,
 									bool *upper_tlist_nontrivial);
-static List *get_sql_fn_result_tlist(List *queryTreeList);
+static List *get_sql_fn_result_tlist(const List *queryTreeList);
 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
 static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
 static void sqlfunction_shutdown(DestReceiver *self);
@@ -2049,7 +2049,7 @@ check_sql_fn_statements(List *queryTreeLists)
  * As above, for a single sublist of Queries.
  */
 static void
-check_sql_fn_statement(List *queryTreeList)
+check_sql_fn_statement(const List *queryTreeList)
 {
 	ListCell   *lc;
 
@@ -2147,7 +2147,7 @@ check_sql_fn_retval(List *queryTreeLists,
  * rewritten-queries list.
  */
 static bool
-check_sql_stmt_retval(List *queryTreeList,
+check_sql_stmt_retval(const List *queryTreeList,
 					  Oid rettype, TupleDesc rettupdesc,
 					  char prokind, bool insertDroppedCols)
 {
@@ -2583,7 +2583,7 @@ coerce_fn_result_column(TargetEntry *src_tle,
  * of parsed-and-rewritten Queries.  Returns NIL if there is none.
  */
 static List *
-get_sql_fn_result_tlist(List *queryTreeList)
+get_sql_fn_result_tlist(const List *queryTreeList)
 {
 	Query	   *parse = NULL;
 	ListCell   *lc;
diff --git a/src/backend/executor/instrument.c b/src/backend/executor/instrument.c
index 9e11c662a7c..4784cc317c4 100644
--- a/src/backend/executor/instrument.c
+++ b/src/backend/executor/instrument.c
@@ -23,7 +23,7 @@ WalUsage	pgWalUsage;
 static WalUsage save_pgWalUsage;
 
 static void BufferUsageAdd(BufferUsage *dst, const BufferUsage *add);
-static void WalUsageAdd(WalUsage *dst, WalUsage *add);
+static void WalUsageAdd(WalUsage *dst, const WalUsage *add);
 
 
 /* Allocate new instrumentation structure(s) */
@@ -275,7 +275,7 @@ BufferUsageAccumDiff(BufferUsage *dst,
 
 /* helper functions for WAL usage accumulation */
 static void
-WalUsageAdd(WalUsage *dst, WalUsage *add)
+WalUsageAdd(WalUsage *dst, const WalUsage *add)
 {
 	dst->wal_bytes += add->wal_bytes;
 	dst->wal_records += add->wal_records;
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..944086a0741 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -368,7 +368,7 @@ static void select_current_set(AggState *aggstate, int setno, bool is_hash);
 static void initialize_phase(AggState *aggstate, int newphase);
 static TupleTableSlot *fetch_input_tuple(AggState *aggstate);
 static void initialize_aggregates(AggState *aggstate,
-								  AggStatePerGroup *pergroups,
+								  const AggStatePerGroup *pergroups,
 								  int numReset);
 static void advance_transition_function(AggState *aggstate,
 										AggStatePerTrans pertrans,
@@ -384,7 +384,7 @@ static void finalize_aggregate(AggState *aggstate,
 							   AggStatePerAgg peragg,
 							   AggStatePerGroup pergroupstate,
 							   Datum *resultVal, bool *resultIsNull);
-static void finalize_partialaggregate(AggState *aggstate,
+static void finalize_partialaggregate(const AggState *aggstate,
 									  AggStatePerAgg peragg,
 									  AggStatePerGroup pergroupstate,
 									  Datum *resultVal, bool *resultIsNull);
@@ -398,7 +398,7 @@ static void finalize_aggregates(AggState *aggstate,
 								AggStatePerAgg peraggs,
 								AggStatePerGroup pergroup);
 static TupleTableSlot *project_aggregates(AggState *aggstate);
-static void find_cols(AggState *aggstate, Bitmapset **aggregated,
+static void find_cols(const AggState *aggstate, Bitmapset **aggregated,
 					  Bitmapset **unaggregated);
 static bool find_cols_walker(Node *node, FindColsContext *context);
 static void build_hash_tables(AggState *aggstate);
@@ -430,7 +430,8 @@ static void hashagg_reset_spill_state(AggState *aggstate);
 static HashAggBatch *hashagg_batch_new(LogicalTape *input_tape, int setno,
 									   int64 input_tuples, double input_card,
 									   int used_bits);
-static MinimalTuple hashagg_batch_read(HashAggBatch *batch, uint32 *hashp);
+static MinimalTuple hashagg_batch_read(const HashAggBatch *batch,
+									   uint32 *hashp);
 static void hashagg_spill_init(HashAggSpill *spill, LogicalTapeSet *tapeset,
 							   int used_bits, double input_groups,
 							   double hashentrysize);
@@ -576,7 +577,7 @@ fetch_input_tuple(AggState *aggstate)
  * When called, CurrentMemoryContext should be the per-query context.
  */
 static void
-initialize_aggregate(AggState *aggstate, AggStatePerTrans pertrans,
+initialize_aggregate(const AggState *aggstate, AggStatePerTrans pertrans,
 					 AggStatePerGroup pergroupstate)
 {
 	/*
@@ -664,7 +665,7 @@ initialize_aggregate(AggState *aggstate, AggStatePerTrans pertrans,
  */
 static void
 initialize_aggregates(AggState *aggstate,
-					  AggStatePerGroup *pergroups,
+					  const AggStatePerGroup *pergroups,
 					  int numReset)
 {
 	int			transno;
@@ -1141,7 +1142,7 @@ finalize_aggregate(AggState *aggstate,
  * output-tuple context; caller's CurrentMemoryContext does not matter.
  */
 static void
-finalize_partialaggregate(AggState *aggstate,
+finalize_partialaggregate(const AggState *aggstate,
 						  AggStatePerAgg peragg,
 						  AggStatePerGroup pergroupstate,
 						  Datum *resultVal, bool *resultIsNull)
@@ -1392,7 +1393,8 @@ project_aggregates(AggState *aggstate)
  * aggregated and unaggregated sets.
  */
 static void
-find_cols(AggState *aggstate, Bitmapset **aggregated, Bitmapset **unaggregated)
+find_cols(const AggState *aggstate, Bitmapset **aggregated,
+		  Bitmapset **unaggregated)
 {
 	Agg		   *agg = (Agg *) aggstate->ss.ps.plan;
 	FindColsContext context;
@@ -3113,7 +3115,7 @@ hashagg_batch_new(LogicalTape *input_tape, int setno,
  * 		read the next tuple from a batch's tape.  Return NULL if no more.
  */
 static MinimalTuple
-hashagg_batch_read(HashAggBatch *batch, uint32 *hashp)
+hashagg_batch_read(const HashAggBatch *batch, uint32 *hashp)
 {
 	LogicalTape *tape = batch->input_tape;
 	MinimalTuple tuple;
diff --git a/src/backend/executor/nodeGatherMerge.c b/src/backend/executor/nodeGatherMerge.c
index 93f3dbc6cf4..8ac5beb109f 100644
--- a/src/backend/executor/nodeGatherMerge.c
+++ b/src/backend/executor/nodeGatherMerge.c
@@ -50,12 +50,13 @@ typedef struct GMReaderTupleBuffer
 static TupleTableSlot *ExecGatherMerge(PlanState *pstate);
 static int32 heap_compare_slots(Datum a, Datum b, void *arg);
 static TupleTableSlot *gather_merge_getnext(GatherMergeState *gm_state);
-static MinimalTuple gm_readnext_tuple(GatherMergeState *gm_state, int nreader,
+static MinimalTuple gm_readnext_tuple(const GatherMergeState *gm_state,
+									  int nreader,
 									  bool nowait, bool *done);
 static void ExecShutdownGatherMergeWorkers(GatherMergeState *node);
 static void gather_merge_setup(GatherMergeState *gm_state);
 static void gather_merge_init(GatherMergeState *gm_state);
-static void gather_merge_clear_tuples(GatherMergeState *gm_state);
+static void gather_merge_clear_tuples(const GatherMergeState *gm_state);
 static bool gather_merge_readnext(GatherMergeState *gm_state, int reader,
 								  bool nowait);
 static void load_tuple_array(GatherMergeState *gm_state, int reader);
@@ -524,7 +525,7 @@ reread:
  * for each gather merge input.
  */
 static void
-gather_merge_clear_tuples(GatherMergeState *gm_state)
+gather_merge_clear_tuples(const GatherMergeState *gm_state)
 {
 	int			i;
 
@@ -712,7 +713,7 @@ gather_merge_readnext(GatherMergeState *gm_state, int reader, bool nowait)
  * Attempt to read a tuple from given worker.
  */
 static MinimalTuple
-gm_readnext_tuple(GatherMergeState *gm_state, int nreader, bool nowait,
+gm_readnext_tuple(const GatherMergeState *gm_state, int nreader, bool nowait,
 				  bool *done)
 {
 	TupleQueueReader *reader;
diff --git a/src/backend/executor/nodeIncrementalSort.c b/src/backend/executor/nodeIncrementalSort.c
index 975b0397e7a..51b8f8ddd87 100644
--- a/src/backend/executor/nodeIncrementalSort.c
+++ b/src/backend/executor/nodeIncrementalSort.c
@@ -209,7 +209,8 @@ preparePresortedCols(IncrementalSortState *node)
  * ----------------------------------------------------------------
  */
 static bool
-isCurrentGroup(IncrementalSortState *node, TupleTableSlot *pivot, TupleTableSlot *tuple)
+isCurrentGroup(const IncrementalSortState *node, TupleTableSlot *pivot,
+			   TupleTableSlot *tuple)
 {
 	int			nPresortedCols;
 
diff --git a/src/backend/executor/nodeIndexonlyscan.c b/src/backend/executor/nodeIndexonlyscan.c
index f464cca9507..38005907491 100644
--- a/src/backend/executor/nodeIndexonlyscan.c
+++ b/src/backend/executor/nodeIndexonlyscan.c
@@ -47,7 +47,8 @@
 
 
 static TupleTableSlot *IndexOnlyNext(IndexOnlyScanState *node);
-static void StoreIndexTuple(IndexOnlyScanState *node, TupleTableSlot *slot,
+static void StoreIndexTuple(const IndexOnlyScanState *node,
+							TupleTableSlot *slot,
 							IndexTuple itup, TupleDesc itupdesc);
 
 
@@ -266,7 +267,7 @@ IndexOnlyNext(IndexOnlyScanState *node)
  * right now we don't need it elsewhere.
  */
 static void
-StoreIndexTuple(IndexOnlyScanState *node, TupleTableSlot *slot,
+StoreIndexTuple(const IndexOnlyScanState *node, TupleTableSlot *slot,
 				IndexTuple itup, TupleDesc itupdesc)
 {
 	/*
diff --git a/src/backend/executor/nodeIndexscan.c b/src/backend/executor/nodeIndexscan.c
index f36929deec3..cd35a6c39ee 100644
--- a/src/backend/executor/nodeIndexscan.c
+++ b/src/backend/executor/nodeIndexscan.c
@@ -61,7 +61,7 @@ static void EvalOrderByExpressions(IndexScanState *node, ExprContext *econtext);
 static bool IndexRecheck(IndexScanState *node, TupleTableSlot *slot);
 static int	cmp_orderbyvals(const Datum *adist, const bool *anulls,
 							const Datum *bdist, const bool *bnulls,
-							IndexScanState *node);
+							const IndexScanState *node);
 static int	reorderqueue_cmp(const pairingheap_node *a,
 							 const pairingheap_node *b, void *arg);
 static void reorderqueue_push(IndexScanState *node, TupleTableSlot *slot,
@@ -406,7 +406,7 @@ IndexRecheck(IndexScanState *node, TupleTableSlot *slot)
 static int
 cmp_orderbyvals(const Datum *adist, const bool *anulls,
 				const Datum *bdist, const bool *bnulls,
-				IndexScanState *node)
+				const IndexScanState *node)
 {
 	int			i;
 	int			result;
diff --git a/src/backend/executor/nodeLimit.c b/src/backend/executor/nodeLimit.c
index f957da4470e..c0b70b8f691 100644
--- a/src/backend/executor/nodeLimit.c
+++ b/src/backend/executor/nodeLimit.c
@@ -26,7 +26,7 @@
 #include "miscadmin.h"
 
 static void recompute_limits(LimitState *node);
-static int64 compute_tuples_needed(LimitState *node);
+static int64 compute_tuples_needed(const LimitState *node);
 
 
 /* ----------------------------------------------------------------
@@ -428,7 +428,7 @@ recompute_limits(LimitState *node)
  * Return a negative value if there is not a determinable limit.
  */
 static int64
-compute_tuples_needed(LimitState *node)
+compute_tuples_needed(const LimitState *node)
 {
 	if ((node->noCount) || (node->limitOption == LIMIT_OPTION_WITH_TIES))
 		return -1;
diff --git a/src/backend/executor/nodeMemoize.c b/src/backend/executor/nodeMemoize.c
index d652663cb6a..4249638679b 100644
--- a/src/backend/executor/nodeMemoize.c
+++ b/src/backend/executor/nodeMemoize.c
@@ -131,9 +131,9 @@ typedef struct MemoizeEntry
 #define SH_DECLARE
 #include "lib/simplehash.h"
 
-static uint32 MemoizeHash_hash(struct memoize_hash *tb,
+static uint32 MemoizeHash_hash(const struct memoize_hash *tb,
 							   const MemoizeKey *key);
-static bool MemoizeHash_equal(struct memoize_hash *tb,
+static bool MemoizeHash_equal(const struct memoize_hash *tb,
 							  const MemoizeKey *key1,
 							  const MemoizeKey *key2);
 
@@ -156,7 +156,7 @@ static bool MemoizeHash_equal(struct memoize_hash *tb,
  *		probeslot with the key values to be looked up.
  */
 static uint32
-MemoizeHash_hash(struct memoize_hash *tb, const MemoizeKey *key)
+MemoizeHash_hash(const struct memoize_hash *tb, const MemoizeKey *key)
 {
 	MemoizeState *mstate = (MemoizeState *) tb->private_data;
 	ExprContext *econtext = mstate->ss.ps.ps_ExprContext;
@@ -219,7 +219,7 @@ MemoizeHash_hash(struct memoize_hash *tb, const MemoizeKey *key)
  *		probeslot is always populated with details of what's being looked up.
  */
 static bool
-MemoizeHash_equal(struct memoize_hash *tb, const MemoizeKey *key1,
+MemoizeHash_equal(const struct memoize_hash *tb, const MemoizeKey *key1,
 				  const MemoizeKey *key2)
 {
 	MemoizeState *mstate = (MemoizeState *) tb->private_data;
@@ -300,7 +300,7 @@ build_hash_table(MemoizeState *mstate, uint32 size)
  *		mstate's param_exprs.
  */
 static inline void
-prepare_probe_slot(MemoizeState *mstate, MemoizeKey *key)
+prepare_probe_slot(const MemoizeState *mstate, MemoizeKey *key)
 {
 	TupleTableSlot *pslot = mstate->probeslot;
 	TupleTableSlot *tslot = mstate->tableslot;
@@ -438,7 +438,7 @@ cache_purge_all(MemoizeState *mstate)
  * which the key belongs to is removed from the cache.
  */
 static bool
-cache_reduce_memory(MemoizeState *mstate, MemoizeKey *specialkey)
+cache_reduce_memory(MemoizeState *mstate, const MemoizeKey *specialkey)
 {
 	bool		specialkey_intact = true;	/* for now */
 	dlist_mutable_iter iter;
diff --git a/src/backend/executor/nodeMergejoin.c b/src/backend/executor/nodeMergejoin.c
index a233313128a..28a41c02fdf 100644
--- a/src/backend/executor/nodeMergejoin.c
+++ b/src/backend/executor/nodeMergejoin.c
@@ -173,10 +173,10 @@ typedef enum
  */
 static MergeJoinClause
 MJExamineQuals(List *mergeclauses,
-			   Oid *mergefamilies,
-			   Oid *mergecollations,
-			   bool *mergereversals,
-			   bool *mergenullsfirst,
+			   const Oid *mergefamilies,
+			   const Oid *mergecollations,
+			   const bool *mergereversals,
+			   const bool *mergenullsfirst,
 			   PlanState *parent)
 {
 	MergeJoinClause clauses;
@@ -333,7 +333,7 @@ MJEvalOuterValues(MergeJoinState *mergestate)
  * so caller must tell us which slot to load from.
  */
 static MJEvalResult
-MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot)
+MJEvalInnerValues(const MergeJoinState *mergestate, TupleTableSlot *innerslot)
 {
 	ExprContext *econtext = mergestate->mj_InnerEContext;
 	MJEvalResult result = MJEVAL_MATCHABLE;
@@ -383,7 +383,7 @@ MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot)
  * for the current outer and inner tuples, respectively.
  */
 static int
-MJCompare(MergeJoinState *mergestate)
+MJCompare(const MergeJoinState *mergestate)
 {
 	int			result = 0;
 	bool		nulleqnull = false;
@@ -511,7 +511,7 @@ MJFillInner(MergeJoinState *node)
  * away any non-constant terms that have been ANDed with a constant false.
  */
 static bool
-check_constant_qual(List *qual, bool *is_const_false)
+check_constant_qual(const List *qual, bool *is_const_false)
 {
 	ListCell   *lc;
 
@@ -538,7 +538,7 @@ check_constant_qual(List *qual, bool *is_const_false)
 #ifdef EXEC_MERGEJOINDEBUG
 
 static void
-ExecMergeTupleDumpOuter(MergeJoinState *mergestate)
+ExecMergeTupleDumpOuter(const MergeJoinState *mergestate)
 {
 	TupleTableSlot *outerSlot = mergestate->mj_OuterTupleSlot;
 
@@ -550,7 +550,7 @@ ExecMergeTupleDumpOuter(MergeJoinState *mergestate)
 }
 
 static void
-ExecMergeTupleDumpInner(MergeJoinState *mergestate)
+ExecMergeTupleDumpInner(const MergeJoinState *mergestate)
 {
 	TupleTableSlot *innerSlot = mergestate->mj_InnerTupleSlot;
 
@@ -562,7 +562,7 @@ ExecMergeTupleDumpInner(MergeJoinState *mergestate)
 }
 
 static void
-ExecMergeTupleDumpMarked(MergeJoinState *mergestate)
+ExecMergeTupleDumpMarked(const MergeJoinState *mergestate)
 {
 	TupleTableSlot *markedSlot = mergestate->mj_MarkedTupleSlot;
 
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
index e44f1223886..90106c0efc2 100644
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -173,7 +173,7 @@ static TupleTableSlot *ExecMergeMatched(ModifyTableContext *context,
 										bool canSetTag,
 										bool *matched);
 static TupleTableSlot *ExecMergeNotMatched(ModifyTableContext *context,
-										   ResultRelInfo *resultRelInfo,
+										   const ResultRelInfo *resultRelInfo,
 										   bool canSetTag);
 
 
@@ -193,7 +193,7 @@ static TupleTableSlot *ExecMergeNotMatched(ModifyTableContext *context,
  * are done in ExecBuildUpdateProjection.
  */
 static void
-ExecCheckPlanOutput(Relation resultRel, List *targetList)
+ExecCheckPlanOutput(Relation resultRel, const List *targetList)
 {
 	TupleDesc	resultDesc = RelationGetDescr(resultRel);
 	int			attno = 0;
@@ -286,7 +286,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList)
  * Returns a slot holding the result tuple
  */
 static TupleTableSlot *
-ExecProcessReturning(ModifyTableContext *context,
+ExecProcessReturning(const ModifyTableContext *context,
 					 ResultRelInfo *resultRelInfo,
 					 CmdType cmdType,
 					 TupleTableSlot *oldSlot,
@@ -396,7 +396,7 @@ ExecCheckTupleVisible(EState *estate,
  */
 static void
 ExecCheckTIDVisible(EState *estate,
-					ResultRelInfo *relinfo,
+					const ResultRelInfo *relinfo,
 					ItemPointer tid,
 					TupleTableSlot *tempSlot)
 {
@@ -1513,7 +1513,8 @@ ExecDeleteAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
  * cross-partition tuple move.
  */
 static void
-ExecDeleteEpilogue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
+ExecDeleteEpilogue(const ModifyTableContext *context,
+				   ResultRelInfo *resultRelInfo,
 				   ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
 {
 	ModifyTableState *mtstate = context->mtstate;
@@ -2320,7 +2321,8 @@ lreplace:
  * returns indicating that the tuple was updated.
  */
 static void
-ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt,
+ExecUpdateEpilogue(ModifyTableContext *context,
+				   const UpdateContext *updateCxt,
 				   ResultRelInfo *resultRelInfo, ItemPointer tupleid,
 				   HeapTuple oldtuple, TupleTableSlot *slot)
 {
@@ -3605,7 +3607,8 @@ out:
  * Execute the first qualifying NOT MATCHED [BY TARGET] action.
  */
 static TupleTableSlot *
-ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
+ExecMergeNotMatched(ModifyTableContext *context,
+					const ResultRelInfo *resultRelInfo,
 					bool canSetTag)
 {
 	ModifyTableState *mtstate = context->mtstate;
@@ -3988,7 +3991,7 @@ ExecInitMergeTupleSlots(ModifyTableState *mtstate,
  * Process BEFORE EACH STATEMENT triggers
  */
 static void
-fireBSTriggers(ModifyTableState *node)
+fireBSTriggers(const ModifyTableState *node)
 {
 	ModifyTable *plan = (ModifyTable *) node->ps.plan;
 	ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
diff --git a/src/backend/executor/nodeSetOp.c b/src/backend/executor/nodeSetOp.c
index 9e0f9274fb1..8f257ae50af 100644
--- a/src/backend/executor/nodeSetOp.c
+++ b/src/backend/executor/nodeSetOp.c
@@ -72,7 +72,7 @@ static TupleTableSlot *setop_retrieve_sorted(SetOpState *setopstate);
 static void setop_load_group(SetOpStatePerInput *input, PlanState *inputPlan,
 							 SetOpState *setopstate);
 static int	setop_compare_slots(TupleTableSlot *s1, TupleTableSlot *s2,
-								SetOpState *setopstate);
+								const SetOpState *setopstate);
 static void setop_fill_hash_table(SetOpState *setopstate);
 static TupleTableSlot *setop_retrieve_hash_table(SetOpState *setopstate);
 
@@ -384,7 +384,7 @@ setop_load_group(SetOpStatePerInput *input, PlanState *inputPlan,
  */
 static int
 setop_compare_slots(TupleTableSlot *s1, TupleTableSlot *s2,
-					SetOpState *setopstate)
+					const SetOpState *setopstate)
 {
 	/* We'll often need to fetch all the columns, so just do it */
 	slot_getallattrs(s1);
diff --git a/src/backend/executor/nodeSubplan.c b/src/backend/executor/nodeSubplan.c
index c8b7bd9eb66..d9e1e01cb04 100644
--- a/src/backend/executor/nodeSubplan.c
+++ b/src/backend/executor/nodeSubplan.c
@@ -700,7 +700,7 @@ static bool
 execTuplesUnequal(TupleTableSlot *slot1,
 				  TupleTableSlot *slot2,
 				  int numCols,
-				  AttrNumber *matchColIdx,
+				  const AttrNumber *matchColIdx,
 				  FmgrInfo *eqfunctions,
 				  const Oid *collations,
 				  MemoryContext evalContext)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 3a0d1f0c922..cbb7ead369e 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -170,7 +170,7 @@ typedef struct WindowStatePerAggData
 	bool		restart;		/* need to restart this agg in this cycle? */
 } WindowStatePerAggData;
 
-static void initialize_windowaggregate(WindowAggState *winstate,
+static void initialize_windowaggregate(const WindowAggState *winstate,
 									   WindowStatePerFunc perfuncstate,
 									   WindowStatePerAgg peraggstate);
 static void advance_windowaggregate(WindowAggState *winstate,
@@ -199,7 +199,7 @@ static void update_frameheadpos(WindowAggState *winstate);
 static void update_frametailpos(WindowAggState *winstate);
 static void update_grouptailpos(WindowAggState *winstate);
 
-static WindowStatePerAggData *initialize_peragg(WindowAggState *winstate,
+static WindowStatePerAggData *initialize_peragg(const WindowAggState *winstate,
 												WindowFunc *wfunc,
 												WindowStatePerAgg peraggstate);
 static Datum GetAggInitVal(Datum textInitVal, Oid transtype);
@@ -247,7 +247,7 @@ static void put_notnull_info(WindowObject winobj,
  * parallel to initialize_aggregates in nodeAgg.c
  */
 static void
-initialize_windowaggregate(WindowAggState *winstate,
+initialize_windowaggregate(const WindowAggState *winstate,
 						   WindowStatePerFunc perfuncstate,
 						   WindowStatePerAgg peraggstate)
 {
@@ -2883,7 +2883,7 @@ ExecReScanWindowAgg(WindowAggState *node)
  * Almost same as in nodeAgg.c, except we don't support DISTINCT currently.
  */
 static WindowStatePerAggData *
-initialize_peragg(WindowAggState *winstate, WindowFunc *wfunc,
+initialize_peragg(const WindowAggState *winstate, WindowFunc *wfunc,
 				  WindowStatePerAgg peraggstate)
 {
 	Oid			inputTypes[FUNC_MAX_ARGS];
diff --git a/src/backend/executor/nodeWorktablescan.c b/src/backend/executor/nodeWorktablescan.c
index f6379c35d2f..941d755fdb8 100644
--- a/src/backend/executor/nodeWorktablescan.c
+++ b/src/backend/executor/nodeWorktablescan.c
@@ -18,7 +18,7 @@
 #include "executor/executor.h"
 #include "executor/nodeWorktablescan.h"
 
-static TupleTableSlot *WorkTableScanNext(WorkTableScanState *node);
+static TupleTableSlot *WorkTableScanNext(const WorkTableScanState *node);
 
 /* ----------------------------------------------------------------
  *		WorkTableScanNext
@@ -27,7 +27,7 @@ static TupleTableSlot *WorkTableScanNext(WorkTableScanState *node);
  * ----------------------------------------------------------------
  */
 static TupleTableSlot *
-WorkTableScanNext(WorkTableScanState *node)
+WorkTableScanNext(const WorkTableScanState *node)
 {
 	TupleTableSlot *slot;
 	Tuplestorestate *tuplestorestate;
diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c
index 653500b38dc..2adbea94c88 100644
--- a/src/backend/executor/spi.c
+++ b/src/backend/executor/spi.c
@@ -67,7 +67,7 @@ static int	_SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
 							  Snapshot snapshot, Snapshot crosscheck_snapshot,
 							  bool fire_triggers);
 
-static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes,
+static ParamListInfo _SPI_convert_params(int nargs, const Oid *argtypes,
 										 const Datum *Values, const char *Nulls);
 
 static int	_SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount);
@@ -2846,7 +2846,7 @@ fail:
  * Convert arrays of query parameters to form wanted by planner and executor
  */
 static ParamListInfo
-_SPI_convert_params(int nargs, Oid *argtypes,
+_SPI_convert_params(int nargs, const Oid *argtypes,
 					const Datum *Values, const char *Nulls)
 {
 	ParamListInfo paramLI;
diff --git a/src/backend/jit/llvm/llvmjit_expr.c b/src/backend/jit/llvm/llvmjit_expr.c
index ac88881e995..56df097a779 100644
--- a/src/backend/jit/llvm/llvmjit_expr.c
+++ b/src/backend/jit/llvm/llvmjit_expr.c
@@ -61,7 +61,8 @@ static LLVMValueRef build_EvalXFuncInt(LLVMBuilderRef b, LLVMModuleRef mod,
 									   const char *funcname,
 									   LLVMValueRef v_state,
 									   ExprEvalStep *op,
-									   int natts, LLVMValueRef *v_args);
+									   int natts,
+									   const LLVMValueRef *v_args);
 static LLVMValueRef create_LifetimeEnd(LLVMModuleRef mod);
 
 /* macro making it easier to call ExecEval* functions */
@@ -3056,7 +3057,7 @@ BuildV1Call(LLVMJitContext *context, LLVMBuilderRef b,
 static LLVMValueRef
 build_EvalXFuncInt(LLVMBuilderRef b, LLVMModuleRef mod, const char *funcname,
 				   LLVMValueRef v_state, ExprEvalStep *op,
-				   int nargs, LLVMValueRef *v_args)
+				   int nargs, const LLVMValueRef *v_args)
 {
 	LLVMValueRef v_fn = llvm_pg_func(mod, funcname);
 	LLVMValueRef *params;
diff --git a/src/backend/lib/bipartite_match.c b/src/backend/lib/bipartite_match.c
index 5af789652c7..18409fe7388 100644
--- a/src/backend/lib/bipartite_match.c
+++ b/src/backend/lib/bipartite_match.c
@@ -28,7 +28,7 @@
  */
 #define HK_INFINITY  SHRT_MAX
 
-static bool hk_breadth_search(BipartiteMatchState *state);
+static bool hk_breadth_search(const BipartiteMatchState *state);
 static bool hk_depth_search(BipartiteMatchState *state, int u);
 
 /*
@@ -90,7 +90,7 @@ BipartiteMatchFree(BipartiteMatchState *state)
  * Returns true if successful.
  */
 static bool
-hk_breadth_search(BipartiteMatchState *state)
+hk_breadth_search(const BipartiteMatchState *state)
 {
 	int			usize = state->u_size;
 	short	   *queue = state->queue;
diff --git a/src/backend/lib/dshash.c b/src/backend/lib/dshash.c
index e1ba367cf17..b3e1b698b24 100644
--- a/src/backend/lib/dshash.c
+++ b/src/backend/lib/dshash.c
@@ -183,7 +183,7 @@ static bool delete_key_from_bucket(dshash_table *hash_table,
 								   const void *key,
 								   dsa_pointer *bucket_head);
 static bool delete_item_from_bucket(dshash_table *hash_table,
-									dshash_table_item *item,
+									const dshash_table_item *item,
 									dsa_pointer *bucket_head);
 static inline dshash_hash hash_key(dshash_table *hash_table, const void *key);
 static inline bool equal_keys(dshash_table *hash_table,
@@ -1035,7 +1035,7 @@ delete_key_from_bucket(dshash_table *hash_table,
  */
 static bool
 delete_item_from_bucket(dshash_table *hash_table,
-						dshash_table_item *item,
+						const dshash_table_item *item,
 						dsa_pointer *bucket_head)
 {
 	while (DsaPointerIsValid(*bucket_head))
diff --git a/src/backend/lib/integerset.c b/src/backend/lib/integerset.c
index f4153b0e15a..1e74534ecc5 100644
--- a/src/backend/lib/integerset.c
+++ b/src/backend/lib/integerset.c
@@ -259,12 +259,15 @@ struct IntegerSet
  * Prototypes for internal functions.
  */
 static void intset_update_upper(IntegerSet *intset, int level,
-								intset_node *child, uint64 child_key);
+								intset_node *child,
+								uint64 child_key);
 static void intset_flush_buffered_values(IntegerSet *intset);
 
-static int	intset_binsrch_uint64(uint64 item, uint64 *arr, int arr_elems,
+static int	intset_binsrch_uint64(uint64 item, const uint64 *arr,
+								  int arr_elems,
 								  bool nextkey);
-static int	intset_binsrch_leaf(uint64 item, leaf_item *arr, int arr_elems,
+static int	intset_binsrch_leaf(uint64 item, const leaf_item *arr,
+								int arr_elems,
 								bool nextkey);
 
 static uint64 simple8b_encode(const uint64 *ints, int *num_encoded, uint64 base);
@@ -710,7 +713,8 @@ intset_iterate_next(IntegerSet *intset, uint64 *next)
  * equal key.  If false, this returns the position of the equal key itself.
  */
 static int
-intset_binsrch_uint64(uint64 item, uint64 *arr, int arr_elems, bool nextkey)
+intset_binsrch_uint64(uint64 item, const uint64 *arr, int arr_elems,
+					  bool nextkey)
 {
 	int			low,
 				high,
@@ -743,7 +747,8 @@ intset_binsrch_uint64(uint64 item, uint64 *arr, int arr_elems, bool nextkey)
 
 /* same, but for an array of leaf items */
 static int
-intset_binsrch_leaf(uint64 item, leaf_item *arr, int arr_elems, bool nextkey)
+intset_binsrch_leaf(uint64 item, const leaf_item *arr, int arr_elems,
+					bool nextkey)
 {
 	int			low,
 				high,
diff --git a/src/backend/lib/pairingheap.c b/src/backend/lib/pairingheap.c
index fa8431f7946..1aa126b766b 100644
--- a/src/backend/lib/pairingheap.c
+++ b/src/backend/lib/pairingheap.c
@@ -312,7 +312,7 @@ pairingheap_dump_recurse(StringInfo buf,
 						 void (*dumpfunc) (pairingheap_node *node, StringInfo buf, void *opaque),
 						 void *opaque,
 						 int depth,
-						 pairingheap_node *prev_or_parent)
+						 const pairingheap_node *prev_or_parent)
 {
 	while (node)
 	{
diff --git a/src/backend/lib/rbtree.c b/src/backend/lib/rbtree.c
index 1f0553f914d..8826da9dae3 100644
--- a/src/backend/lib/rbtree.c
+++ b/src/backend/lib/rbtree.c
@@ -124,7 +124,7 @@ rbt_create(Size node_size,
 
 /* Copy the additional data fields from one RBTNode to another */
 static inline void
-rbt_copy_data(RBTree *rbt, RBTNode *dest, const RBTNode *src)
+rbt_copy_data(const RBTree *rbt, RBTNode *dest, const RBTNode *src)
 {
 	memcpy(dest + 1, src + 1, rbt->node_size - sizeof(RBTNode));
 }
diff --git a/src/backend/libpq/auth-scram.c b/src/backend/libpq/auth-scram.c
index e343ffea46f..9463e36051f 100644
--- a/src/backend/libpq/auth-scram.c
+++ b/src/backend/libpq/auth-scram.c
@@ -181,7 +181,7 @@ static bool verify_final_nonce(scram_state *state);
 static void mock_scram_secret(const char *username, pg_cryptohash_type *hash_type,
 							  int *iterations, int *key_length, char **salt,
 							  uint8 *stored_key, uint8 *server_key);
-static bool is_scram_printable(char *p);
+static bool is_scram_printable(const char *p);
 static char *sanitize_char(char c);
 static char *sanitize_str(const char *s);
 static uint8 *scram_mock_salt(const char *username,
@@ -774,7 +774,7 @@ read_attr_value(char **input, char attr)
 }
 
 static bool
-is_scram_printable(char *p)
+is_scram_printable(const char *p)
 {
 	/*------
 	 * Printable characters, as defined by SCRAM spec: (RFC 5802)
diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c
index 8045dbffe04..73776f66061 100644
--- a/src/backend/libpq/auth.c
+++ b/src/backend/libpq/auth.c
@@ -2223,7 +2223,7 @@ static int	errdetail_for_ldap(LDAP *ldap);
  * TLS if requested.
  */
 static int
-InitializeLDAPConnection(Port *port, LDAP **ldap)
+InitializeLDAPConnection(const Port *port, LDAP **ldap)
 {
 	const char *scheme;
 	int			ldapversion = LDAP_VERSION3;
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index d228318dc72..a47df94bd62 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -26,7 +26,7 @@
 static bool expression_returns_set_walker(Node *node, void *context);
 static int	leftmostLoc(int loc1, int loc2);
 static bool fix_opfuncids_walker(Node *node, void *context);
-static bool planstate_walk_subplans(List *plans,
+static bool planstate_walk_subplans(const List *plans,
 									planstate_tree_walker_callback walker,
 									void *context);
 static bool planstate_walk_members(PlanState **planstates, int nplans,
@@ -4800,7 +4800,7 @@ planstate_tree_walker_impl(PlanState *planstate,
  * Walk a list of SubPlans (or initPlans, which also use SubPlan nodes).
  */
 static bool
-planstate_walk_subplans(List *plans,
+planstate_walk_subplans(const List *plans,
 						planstate_tree_walker_callback walker,
 						void *context)
 {
diff --git a/src/backend/nodes/tidbitmap.c b/src/backend/nodes/tidbitmap.c
index 1f83d0d55f5..06ceac8b828 100644
--- a/src/backend/nodes/tidbitmap.c
+++ b/src/backend/nodes/tidbitmap.c
@@ -932,7 +932,7 @@ tbm_extract_page_tuple(TBMIterateResult *iteritem,
  *	tbm_advance_schunkbit - Advance the schunkbit
  */
 static inline void
-tbm_advance_schunkbit(PagetableEntry *chunk, int *schunkbitp)
+tbm_advance_schunkbit(const PagetableEntry *chunk, int *schunkbitp)
 {
 	int			schunkbit = *schunkbitp;
 
diff --git a/src/backend/optimizer/geqo/geqo_erx.c b/src/backend/optimizer/geqo/geqo_erx.c
index af289f7eeb7..9ba106e1483 100644
--- a/src/backend/optimizer/geqo/geqo_erx.c
+++ b/src/backend/optimizer/geqo/geqo_erx.c
@@ -41,9 +41,10 @@
 
 static int	gimme_edge(PlannerInfo *root, Gene gene1, Gene gene2, Edge *edge_table);
 static void remove_gene(PlannerInfo *root, Gene gene, Edge edge, Edge *edge_table);
-static Gene gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table);
+static Gene gimme_gene(PlannerInfo *root, Edge edge, const Edge *edge_table);
 
-static Gene edge_failure(PlannerInfo *root, Gene *gene, int index, Edge *edge_table, int num_gene);
+static Gene edge_failure(PlannerInfo *root, const Gene *gene, int index,
+						 const Edge *edge_table, int num_gene);
 
 
 /* alloc_edge_table
@@ -279,7 +280,7 @@ remove_gene(PlannerInfo *root, Gene gene, Edge edge, Edge *edge_table)
  *
  */
 static Gene
-gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
+gimme_gene(PlannerInfo *root, Edge edge, const Edge *edge_table)
 {
 	int			i;
 	Gene		friend;
@@ -369,7 +370,8 @@ gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
  *
  */
 static Gene
-edge_failure(PlannerInfo *root, Gene *gene, int index, Edge *edge_table, int num_gene)
+edge_failure(PlannerInfo *root, const Gene *gene, int index,
+			 const Edge *edge_table, int num_gene)
 {
 	int			i;
 	Gene		fail_gene = gene[index];
diff --git a/src/backend/optimizer/geqo/geqo_misc.c b/src/backend/optimizer/geqo/geqo_misc.c
index b8fcc9b6a2f..a56805890ee 100644
--- a/src/backend/optimizer/geqo/geqo_misc.c
+++ b/src/backend/optimizer/geqo/geqo_misc.c
@@ -31,7 +31,7 @@
  * avg_pool
  */
 static double
-avg_pool(Pool *pool)
+avg_pool(const Pool *pool)
 {
 	int			i;
 	double		cumulative = 0.0;
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 5a7283bd2f5..d09b5bcadca 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -170,19 +170,21 @@ typedef struct
 	QualCost	total;
 } cost_qual_eval_context;
 
-static List *extract_nonindex_conditions(List *qual_clauses, List *indexclauses);
+static List *extract_nonindex_conditions(const List *qual_clauses,
+										 List *indexclauses);
 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
 										 RestrictInfo *rinfo,
 										 PathKey *pathkey);
 static void cost_rescan(PlannerInfo *root, Path *path,
 						Cost *rescan_startup_cost, Cost *rescan_total_cost);
 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
-static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
+static void get_restriction_qual_cost(PlannerInfo *root,
+									  const RelOptInfo *baserel,
 									  ParamPathInfo *param_info,
 									  QualCost *qpqual_cost);
 static bool has_indexed_join_quals(NestPath *path);
-static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
-								 List *quals);
+static double approx_tuple_count(PlannerInfo *root, const JoinPath *path,
+								 const List *quals);
 static double calc_joinrel_size_estimate(PlannerInfo *root,
 										 RelOptInfo *joinrel,
 										 RelOptInfo *outer_rel,
@@ -196,13 +198,13 @@ static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root,
 													Relids inner_relids,
 													SpecialJoinInfo *sjinfo,
 													List **restrictlist);
-static Cost append_nonpartial_cost(List *subpaths, int numpaths,
+static Cost append_nonpartial_cost(const List *subpaths, int numpaths,
 								   int parallel_workers);
 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
-static int32 get_expr_width(PlannerInfo *root, const Node *expr);
+static int32 get_expr_width(const PlannerInfo *root, const Node *expr);
 static double relation_byte_size(double tuples, int width);
 static double page_size(double tuples, int width);
-static double get_parallel_divisor(Path *path);
+static double get_parallel_divisor(const Path *path);
 
 
 /*
@@ -821,7 +823,7 @@ cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
  * indexclauses is a list of IndexClauses.
  */
 static List *
-extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
+extract_nonindex_conditions(const List *qual_clauses, List *indexclauses)
 {
 	List	   *result = NIL;
 	ListCell   *lc;
@@ -2161,7 +2163,8 @@ cost_sort(Path *path, PlannerInfo *root,
  *	  from the subpaths list, and to be in order of decreasing cost.
  */
 static Cost
-append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
+append_nonpartial_cost(const List *subpaths, int numpaths,
+					   int parallel_workers)
 {
 	Cost	   *costarr;
 	int			arrlen;
@@ -5094,7 +5097,7 @@ cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
  * set_baserel_size_estimates().
  */
 static void
-get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
+get_restriction_qual_cost(PlannerInfo *root, const RelOptInfo *baserel,
 						  ParamPathInfo *param_info,
 						  QualCost *qpqual_cost)
 {
@@ -5326,7 +5329,7 @@ has_indexed_join_quals(NestPath *path)
  * seems OK to live with the approximation.
  */
 static double
-approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
+approx_tuple_count(PlannerInfo *root, const JoinPath *path, const List *quals)
 {
 	double		tuples;
 	double		outer_tuples = path->outerjoinpath->rows;
@@ -6427,7 +6430,7 @@ set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
  *		average width when unable to or when the given Node is not a Var.
  */
 static int32
-get_expr_width(PlannerInfo *root, const Node *expr)
+get_expr_width(const PlannerInfo *root, const Node *expr)
 {
 	int32		width;
 
@@ -6496,7 +6499,7 @@ page_size(double tuples, int width)
  * number of workers budgeted for the path.
  */
 static double
-get_parallel_divisor(Path *path)
+get_parallel_divisor(const Path *path)
 {
 	double		parallel_divisor = path->parallel_workers;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..19eb6821edc 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -56,19 +56,19 @@ static void generate_base_implied_equalities_const(PlannerInfo *root,
 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
 													  EquivalenceClass *ec);
 static void generate_base_implied_equalities_broken(PlannerInfo *root,
-													EquivalenceClass *ec);
+													const EquivalenceClass *ec);
 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
 													 EquivalenceClass *ec,
 													 Relids join_relids,
 													 Relids outer_relids,
 													 Relids inner_relids);
 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
-													 EquivalenceClass *ec,
+													 const EquivalenceClass *ec,
 													 Relids nominal_join_relids,
 													 Relids outer_relids,
 													 Relids nominal_inner_relids,
 													 RelOptInfo *inner_rel);
-static Oid	select_equality_operator(EquivalenceClass *ec,
+static Oid	select_equality_operator(const EquivalenceClass *ec,
 									 Oid lefttype, Oid righttype);
 static RestrictInfo *create_join_clause(PlannerInfo *root,
 										EquivalenceClass *ec, Oid opno,
@@ -76,11 +76,11 @@ static RestrictInfo *create_join_clause(PlannerInfo *root,
 										EquivalenceMember *rightem,
 										EquivalenceClass *parent_ec);
 static bool reconsider_outer_join_clause(PlannerInfo *root,
-										 OuterJoinClauseInfo *ojcinfo,
+										 const OuterJoinClauseInfo *ojcinfo,
 										 bool outer_on_left);
 static bool reconsider_full_join_clause(PlannerInfo *root,
-										OuterJoinClauseInfo *ojcinfo);
-static JoinDomain *find_join_domain(PlannerInfo *root, Relids relids);
+										const OuterJoinClauseInfo *ojcinfo);
+static JoinDomain *find_join_domain(const PlannerInfo *root, Relids relids);
 static Bitmapset *get_eclass_indexes_for_relids(PlannerInfo *root,
 												Relids relids);
 static Bitmapset *get_common_eclass_indexes(PlannerInfo *root, Relids relids1,
@@ -1485,7 +1485,7 @@ generate_base_implied_equalities_no_const(PlannerInfo *root,
  */
 static void
 generate_base_implied_equalities_broken(PlannerInfo *root,
-										EquivalenceClass *ec)
+										const EquivalenceClass *ec)
 {
 	ListCell   *lc;
 
@@ -1897,7 +1897,7 @@ generate_join_implied_equalities_normal(PlannerInfo *root,
  */
 static List *
 generate_join_implied_equalities_broken(PlannerInfo *root,
-										EquivalenceClass *ec,
+										const EquivalenceClass *ec,
 										Relids nominal_join_relids,
 										Relids outer_relids,
 										Relids nominal_inner_relids,
@@ -1945,7 +1945,8 @@ generate_join_implied_equalities_broken(PlannerInfo *root,
  * Returns InvalidOid if no operator can be found for this datatype combination
  */
 static Oid
-select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
+select_equality_operator(const EquivalenceClass *ec, Oid lefttype,
+						 Oid righttype)
 {
 	ListCell   *lc;
 
@@ -2254,7 +2255,8 @@ reconsider_outer_join_clauses(PlannerInfo *root)
  * Returns true if we were able to propagate a constant through the clause.
  */
 static bool
-reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
+reconsider_outer_join_clause(PlannerInfo *root,
+							 const OuterJoinClauseInfo *ojcinfo,
 							 bool outer_on_left)
 {
 	RestrictInfo *rinfo = ojcinfo->rinfo;
@@ -2381,7 +2383,8 @@ reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
  * Returns true if we were able to propagate a constant through the clause.
  */
 static bool
-reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
+reconsider_full_join_clause(PlannerInfo *root,
+							const OuterJoinClauseInfo *ojcinfo)
 {
 	RestrictInfo *rinfo = ojcinfo->rinfo;
 	SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
@@ -2614,7 +2617,7 @@ rebuild_eclass_attr_needed(PlannerInfo *root)
  * which doesn't seem worth it.)
  */
 static JoinDomain *
-find_join_domain(PlannerInfo *root, Relids relids)
+find_join_domain(const PlannerInfo *root, Relids relids)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c
index 2654c59c4c6..8efb5666c02 100644
--- a/src/backend/optimizer/path/indxpath.c
+++ b/src/backend/optimizer/path/indxpath.c
@@ -93,19 +93,21 @@ static void consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
 										   List **considered_relids);
 static void get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
 								 IndexOptInfo *index,
-								 IndexClauseSet *rclauseset,
-								 IndexClauseSet *jclauseset,
-								 IndexClauseSet *eclauseset,
+								 const IndexClauseSet *rclauseset,
+								 const IndexClauseSet *jclauseset,
+								 const IndexClauseSet *eclauseset,
 								 List **bitindexpaths,
 								 Relids relids,
 								 List **considered_relids);
-static bool eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
-								List *indexjoinclauses);
+static bool eclass_already_used(const EquivalenceClass *parent_ec,
+								Relids oldrelids,
+								const List *indexjoinclauses);
 static void get_index_paths(PlannerInfo *root, RelOptInfo *rel,
 							IndexOptInfo *index, IndexClauseSet *clauses,
 							List **bitindexpaths);
 static List *build_index_paths(PlannerInfo *root, RelOptInfo *rel,
-							   IndexOptInfo *index, IndexClauseSet *clauses,
+							   IndexOptInfo *index,
+							   const IndexClauseSet *clauses,
 							   bool useful_predicate,
 							   ScanTypeControl scantype,
 							   bool *skip_nonnative_saop);
@@ -124,13 +126,13 @@ static PathClauseUsage *classify_index_clause_usage(Path *path,
 													List **clauselist);
 static void find_indexpath_quals(Path *bitmapqual, List **quals, List **preds);
 static int	find_list_position(Node *node, List **nodelist);
-static bool check_index_only(RelOptInfo *rel, IndexOptInfo *index);
+static bool check_index_only(RelOptInfo *rel, const IndexOptInfo *index);
 static double get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids);
 static double adjust_rowcount_for_semijoins(PlannerInfo *root,
 											Index cur_relid,
 											Index outer_relid,
 											double rowcount);
-static double approximate_joinrel_size(PlannerInfo *root, Relids relids);
+static double approximate_joinrel_size(const PlannerInfo *root, Relids relids);
 static void match_restriction_clauses_to_index(PlannerInfo *root,
 											   IndexOptInfo *index,
 											   IndexClauseSet *clauseset);
@@ -142,7 +144,7 @@ static void match_eclass_clauses_to_index(PlannerInfo *root,
 										  IndexOptInfo *index,
 										  IndexClauseSet *clauseset);
 static void match_clauses_to_index(PlannerInfo *root,
-								   List *clauses,
+								   const List *clauses,
 								   IndexOptInfo *index,
 								   IndexClauseSet *clauseset);
 static void match_clause_to_index(PlannerInfo *root,
@@ -189,7 +191,7 @@ static IndexClause *expand_indexqual_rowcompare(PlannerInfo *root,
 												IndexOptInfo *index,
 												Oid expr_op,
 												bool var_on_left);
-static void match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
+static void match_pathkeys_to_index(IndexOptInfo *index, const List *pathkeys,
 									List **orderby_clauses_p,
 									List **clause_columns_p);
 static Expr *match_clause_to_ordering_op(IndexOptInfo *index,
@@ -605,9 +607,9 @@ consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
 static void
 get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
 					 IndexOptInfo *index,
-					 IndexClauseSet *rclauseset,
-					 IndexClauseSet *jclauseset,
-					 IndexClauseSet *eclauseset,
+					 const IndexClauseSet *rclauseset,
+					 const IndexClauseSet *jclauseset,
+					 const IndexClauseSet *eclauseset,
 					 List **bitindexpaths,
 					 Relids relids,
 					 List **considered_relids)
@@ -681,8 +683,8 @@ get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
  *		the specified equivalence class.
  */
 static bool
-eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
-					List *indexjoinclauses)
+eclass_already_used(const EquivalenceClass *parent_ec, Relids oldrelids,
+					const List *indexjoinclauses)
 {
 	ListCell   *lc;
 
@@ -808,7 +810,8 @@ get_index_paths(PlannerInfo *root, RelOptInfo *rel,
  */
 static List *
 build_index_paths(PlannerInfo *root, RelOptInfo *rel,
-				  IndexOptInfo *index, IndexClauseSet *clauses,
+				  IndexOptInfo *index,
+				  const IndexClauseSet *clauses,
 				  bool useful_predicate,
 				  ScanTypeControl scantype,
 				  bool *skip_nonnative_saop)
@@ -1268,7 +1271,8 @@ or_arg_index_match_cmp_group(const void *a, const void *b)
  * Returns the processed list of OR-clause arguments.
  */
 static List *
-group_similar_or_args(PlannerInfo *root, RelOptInfo *rel, RestrictInfo *rinfo)
+group_similar_or_args(PlannerInfo *root, const RelOptInfo *rel,
+					  RestrictInfo *rinfo)
 {
 	int			n;
 	int			i;
@@ -2225,7 +2229,7 @@ find_list_position(Node *node, List **nodelist)
  *		Determine whether an index-only scan is possible for this index.
  */
 static bool
-check_index_only(RelOptInfo *rel, IndexOptInfo *index)
+check_index_only(RelOptInfo *rel, const IndexOptInfo *index)
 {
 	bool		result;
 	Bitmapset  *attrs_used = NULL;
@@ -2421,7 +2425,7 @@ adjust_rowcount_for_semijoins(PlannerInfo *root,
  * overestimate of the RHS's raw size.
  */
 static double
-approximate_joinrel_size(PlannerInfo *root, Relids relids)
+approximate_joinrel_size(const PlannerInfo *root, Relids relids)
 {
 	double		rowcount = 1.0;
 	int			relid;
@@ -2552,7 +2556,7 @@ match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index,
  */
 static void
 match_clauses_to_index(PlannerInfo *root,
-					   List *clauses,
+					   const List *clauses,
 					   IndexOptInfo *index,
 					   IndexClauseSet *clauseset)
 {
@@ -3714,7 +3718,7 @@ expand_indexqual_rowcompare(PlannerInfo *root,
  * item in the given 'pathkeys' list.
  */
 static void
-match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
+match_pathkeys_to_index(IndexOptInfo *index, const List *pathkeys,
 						List **orderby_clauses_p,
 						List **clause_columns_p)
 {
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index ea5b6415186..f4aabc33617 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -70,7 +70,7 @@ static void consider_parallel_nestloop(PlannerInfo *root,
 									   JoinPathExtraData *extra);
 static void consider_parallel_mergejoin(PlannerInfo *root,
 										RelOptInfo *joinrel,
-										RelOptInfo *outerrel,
+										const RelOptInfo *outerrel,
 										RelOptInfo *innerrel,
 										JoinType jointype,
 										JoinPathExtraData *extra,
@@ -82,7 +82,7 @@ static List *select_mergejoin_clauses(PlannerInfo *root,
 									  RelOptInfo *joinrel,
 									  RelOptInfo *outerrel,
 									  RelOptInfo *innerrel,
-									  List *restrictlist,
+									  const List *restrictlist,
 									  JoinType jointype,
 									  bool *mergejoin_allowed);
 static void generate_mergejoin_paths(PlannerInfo *root,
@@ -442,7 +442,8 @@ have_unsafe_outer_join_ref(PlannerInfo *root,
  * required.
  */
 static bool
-paraminfo_get_equal_hashops(PlannerInfo *root, ParamPathInfo *param_info,
+paraminfo_get_equal_hashops(PlannerInfo *root,
+							const ParamPathInfo *param_info,
 							RelOptInfo *outerrel, RelOptInfo *innerrel,
 							List *ph_lateral_vars, List **param_exprs,
 							List **operators, bool *binary_mode)
@@ -2001,7 +2002,7 @@ match_unsorted_outer(PlannerInfo *root,
 static void
 consider_parallel_mergejoin(PlannerInfo *root,
 							RelOptInfo *joinrel,
-							RelOptInfo *outerrel,
+							const RelOptInfo *outerrel,
 							RelOptInfo *innerrel,
 							JoinType jointype,
 							JoinPathExtraData *extra,
@@ -2355,7 +2356,7 @@ select_mergejoin_clauses(PlannerInfo *root,
 						 RelOptInfo *joinrel,
 						 RelOptInfo *outerrel,
 						 RelOptInfo *innerrel,
-						 List *restrictlist,
+						 const List *restrictlist,
 						 JoinType jointype,
 						 bool *mergejoin_allowed)
 {
diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c
index 139fa1f875a..b49d7988dae 100644
--- a/src/backend/optimizer/path/pathkeys.c
+++ b/src/backend/optimizer/path/pathkeys.c
@@ -31,12 +31,15 @@
 /* Consider reordering of GROUP BY keys? */
 bool		enable_group_by_reordering = true;
 
-static bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys);
-static bool matches_boolean_partition_clause(RestrictInfo *rinfo,
-											 RelOptInfo *partrel,
+static bool pathkey_is_redundant(const PathKey *new_pathkey,
+								 const List *pathkeys);
+static bool matches_boolean_partition_clause(const RestrictInfo *rinfo,
+											 const RelOptInfo *partrel,
 											 int partkeycol);
-static Var *find_var_for_subquery_tle(RelOptInfo *rel, TargetEntry *tle);
-static bool right_merge_direction(PlannerInfo *root, PathKey *pathkey);
+static Var *find_var_for_subquery_tle(const RelOptInfo *rel,
+									  const TargetEntry *tle);
+static bool right_merge_direction(const PlannerInfo *root,
+								  const PathKey *pathkey);
 
 
 /****************************************************************************
@@ -156,7 +159,7 @@ append_pathkeys(List *target, List *source)
  * pointer comparison is enough to decide whether canonical ECs are the same.
  */
 static bool
-pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys)
+pathkey_is_redundant(const PathKey *new_pathkey, const List *pathkeys)
 {
 	EquivalenceClass *new_ec = new_pathkey->pk_eclass;
 	ListCell   *lc;
@@ -367,7 +370,7 @@ pathkeys_contained_in(List *keys1, List *keys2)
  * Returns the number of GROUP BY keys with a matching pathkey.
  */
 static int
-group_keys_reorder_by_pathkeys(List *pathkeys, List **group_pathkeys,
+group_keys_reorder_by_pathkeys(const List *pathkeys, List **group_pathkeys,
 							   List **group_clauses,
 							   int num_groupby_pathkeys)
 {
@@ -881,8 +884,9 @@ partkey_is_bool_constant_for_query(RelOptInfo *partrel, int partkeycol)
  * or a NOT above an exact match (equivalent to partkey = false).
  */
 static bool
-matches_boolean_partition_clause(RestrictInfo *rinfo,
-								 RelOptInfo *partrel, int partkeycol)
+matches_boolean_partition_clause(const RestrictInfo *rinfo,
+								 const RelOptInfo *partrel,
+								 int partkeycol)
 {
 	Node	   *clause = (Node *) rinfo->clause;
 	Node	   *partexpr = (Node *) linitial(partrel->partexprs[partkeycol]);
@@ -1249,7 +1253,7 @@ convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel,
  * that are unavailable above the level of the subquery scan.
  */
 static Var *
-find_var_for_subquery_tle(RelOptInfo *rel, TargetEntry *tle)
+find_var_for_subquery_tle(const RelOptInfo *rel, const TargetEntry *tle)
 {
 	ListCell   *lc;
 
@@ -2053,7 +2057,8 @@ trim_mergeclauses_for_inner_pathkeys(PlannerInfo *root,
  * right_merge_direction() implements this heuristic.
  */
 static int
-pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
+pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel,
+							const List *pathkeys)
 {
 	int			useful = 0;
 	ListCell   *i;
@@ -2120,7 +2125,7 @@ pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
  *		for merging its target column.
  */
 static bool
-right_merge_direction(PlannerInfo *root, PathKey *pathkey)
+right_merge_direction(const PlannerInfo *root, const PathKey *pathkey)
 {
 	ListCell   *l;
 
@@ -2166,7 +2171,7 @@ count_common_leading_pathkeys_ordered(List *keys1, List *keys2)
  *		'keys1'.
  */
 static int
-count_common_leading_pathkeys_unordered(List *keys1, List *keys2)
+count_common_leading_pathkeys_unordered(List *keys1, const List *keys2)
 {
 	int			ncommon = 0;
 
diff --git a/src/backend/optimizer/path/tidpath.c b/src/backend/optimizer/path/tidpath.c
index 3ddbc10bbdf..258d840e7ca 100644
--- a/src/backend/optimizer/path/tidpath.c
+++ b/src/backend/optimizer/path/tidpath.c
@@ -53,7 +53,7 @@
  * Does this Var represent the CTID column of the specified baserel?
  */
 static inline bool
-IsCTIDVar(Var *var, RelOptInfo *rel)
+IsCTIDVar(const Var *var, const RelOptInfo *rel)
 {
 	/* The vartype check is strictly paranoia */
 	if (var->varattno == SelfItemPointerAttributeNumber &&
@@ -209,7 +209,7 @@ IsTidEqualAnyClause(PlannerInfo *root, RestrictInfo *rinfo, RelOptInfo *rel)
  * Check to see if a RestrictInfo is a CurrentOfExpr referencing "rel".
  */
 static bool
-IsCurrentOfClause(RestrictInfo *rinfo, RelOptInfo *rel)
+IsCurrentOfClause(RestrictInfo *rinfo, const RelOptInfo *rel)
 {
 	CurrentOfExpr *node;
 
@@ -278,7 +278,8 @@ RestrictInfoIsTidQual(PlannerInfo *root, RestrictInfo *rinfo, RelOptInfo *rel)
  * that there's more than one choice.
  */
 static List *
-TidQualFromRestrictInfoList(PlannerInfo *root, List *rlist, RelOptInfo *rel,
+TidQualFromRestrictInfoList(PlannerInfo *root, const List *rlist,
+							RelOptInfo *rel,
 							bool *isCurrentOf)
 {
 	RestrictInfo *tidclause = NULL; /* best simple CTID qual so far */
@@ -395,7 +396,7 @@ TidQualFromRestrictInfoList(PlannerInfo *root, List *rlist, RelOptInfo *rel,
  * scans.
  */
 static List *
-TidRangeQualFromRestrictInfoList(List *rlist, RelOptInfo *rel)
+TidRangeQualFromRestrictInfoList(const List *rlist, RelOptInfo *rel)
 {
 	List	   *rlst = NIL;
 	ListCell   *l;
@@ -423,7 +424,8 @@ TidRangeQualFromRestrictInfoList(List *rlist, RelOptInfo *rel)
  * troubling over.
  */
 static void
-BuildParameterizedTidPaths(PlannerInfo *root, RelOptInfo *rel, List *clauses)
+BuildParameterizedTidPaths(PlannerInfo *root, RelOptInfo *rel,
+						   const List *clauses)
 {
 	ListCell   *l;
 
diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c
index 296a894b857..e7be0871436 100644
--- a/src/backend/optimizer/plan/analyzejoins.c
+++ b/src/backend/optimizer/plan/analyzejoins.c
@@ -62,17 +62,20 @@ static void remove_rel_from_restrictinfo(RestrictInfo *rinfo,
 static void remove_rel_from_eclass(EquivalenceClass *ec,
 								   SpecialJoinInfo *sjinfo,
 								   int relid, int subst);
-static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved);
-static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel);
+static List *remove_rel_from_joinlist(const List *joinlist, int relid,
+									  int *nremoved);
+static bool rel_supports_distinctness(const PlannerInfo *root,
+									  const RelOptInfo *rel);
 static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel,
 								List *clause_list, List **extra_clauses);
-static Oid	distinct_col_search(int colno, List *colnos, List *opids);
+static Oid	distinct_col_search(int colno, const List *colnos,
+								const List *opids);
 static bool is_innerrel_unique_for(PlannerInfo *root,
 								   Relids joinrelids,
 								   Relids outerrelids,
 								   RelOptInfo *innerrel,
 								   JoinType jointype,
-								   List *restrictlist,
+								   const List *restrictlist,
 								   List **extra_clauses);
 static int	self_join_candidates_cmp(const void *a, const void *b);
 static bool replace_relid_callback(Node *node,
@@ -323,7 +326,7 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo)
  * self-join removal.
  */
 static void
-remove_rel_from_query(PlannerInfo *root, RelOptInfo *rel,
+remove_rel_from_query(PlannerInfo *root, const RelOptInfo *rel,
 					  int subst, SpecialJoinInfo *sjinfo,
 					  Relids joinrelids)
 {
@@ -788,7 +791,7 @@ remove_rel_from_eclass(EquivalenceClass *ec, SpecialJoinInfo *sjinfo,
  * should be exactly one, but the caller checks that).
  */
 static List *
-remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved)
+remove_rel_from_joinlist(const List *joinlist, int relid, int *nremoved)
 {
 	List	   *result = NIL;
 	ListCell   *jl;
@@ -918,7 +921,7 @@ reduce_unique_semijoins(PlannerInfo *root)
  * succeed.
  */
 static bool
-rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel)
+rel_supports_distinctness(const PlannerInfo *root, const RelOptInfo *rel)
 {
 	/* We only know about baserels ... */
 	if (rel->reloptkind != RELOPT_BASEREL)
@@ -1267,7 +1270,7 @@ query_is_distinct_for(Query *query, List *colnos, List *opids)
  * but if it does, we arbitrarily select the first match.)
  */
 static Oid
-distinct_col_search(int colno, List *colnos, List *opids)
+distinct_col_search(int colno, const List *colnos, const List *opids)
 {
 	ListCell   *lc1,
 			   *lc2;
@@ -1461,7 +1464,7 @@ is_innerrel_unique_for(PlannerInfo *root,
 					   Relids outerrelids,
 					   RelOptInfo *innerrel,
 					   JoinType jointype,
-					   List *restrictlist,
+					   const List *restrictlist,
 					   List **extra_clauses)
 {
 	List	   *clause_list = NIL;
@@ -1657,7 +1660,7 @@ restrict_infos_logically_equal(RestrictInfo *a, RestrictInfo *b)
  */
 static void
 add_non_redundant_clauses(PlannerInfo *root,
-						  List *rinfo_candidates,
+						  const List *rinfo_candidates,
 						  List **keep_rinfo_list,
 						  Index removed_relid)
 {
@@ -1824,7 +1827,8 @@ replace_relid_callback(Node *node, ChangeVarNodes_context *context)
  * self-join elimination procedure.
  */
 static void
-remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark,
+remove_self_join_rel(PlannerInfo *root, const PlanRowMark *kmark,
+					 PlanRowMark *rmark,
 					 RelOptInfo *toKeep, RelOptInfo *toRemove,
 					 List *restrictlist)
 {
@@ -2007,7 +2011,8 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark,
  * itself.
  */
 static void
-split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals,
+split_selfjoin_quals(PlannerInfo *root, const List *joinquals,
+					 List **selfjoinquals,
 					 List **otherjoinquals, int from, int to)
 {
 	List	   *sjoinquals = NIL;
@@ -2072,7 +2077,8 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals,
  * are different).
  */
 static bool
-match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses,
+match_unique_clauses(PlannerInfo *root, RelOptInfo *outer,
+					 const List *uclauses,
 					 Index relid)
 {
 	foreach_node(RestrictInfo, rinfo, uclauses)
@@ -2305,7 +2311,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids)
  * joins.
  */
 static Relids
-remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove)
+remove_self_joins_recurse(PlannerInfo *root, const List *joinlist,
+						  Relids toRemove)
 {
 	ListCell   *jl;
 	Relids		relids = NULL;
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..c0a76bd7742 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -77,8 +77,8 @@ static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
 								 int flags);
 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
 							  int flags);
-static List *build_path_tlist(PlannerInfo *root, Path *path);
-static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
+static List *build_path_tlist(PlannerInfo *root, const Path *path);
+static bool use_physical_tlist(const PlannerInfo *root, Path *path, int flags);
 static List *get_gating_quals(PlannerInfo *root, List *quals);
 static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
 								List *gating_quals);
@@ -123,10 +123,13 @@ static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
 										  List *tlist, List *scan_clauses);
 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
-								   List *tlist, List *scan_clauses, bool indexonly);
+								   List *tlist,
+								   const List *scan_clauses,
+								   bool indexonly);
 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
 											   BitmapHeapPath *best_path,
-											   List *tlist, List *scan_clauses);
+											   List *tlist,
+											   const List *scan_clauses);
 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
 								   List **qual, List **indexqual, List **indexECs);
 static void bitmap_subplan_mark_shared(Plan *plan);
@@ -163,18 +166,20 @@ static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path)
 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
-static void fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
+static void fix_indexqual_references(PlannerInfo *root,
+									 const IndexPath *index_path,
 									 List **stripped_indexquals_p,
 									 List **fixed_indexquals_p);
-static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
+static List *fix_indexorderby_references(PlannerInfo *root,
+										 const IndexPath *index_path);
 static Node *fix_indexqual_clause(PlannerInfo *root,
 								  IndexOptInfo *index, int indexcol,
 								  Node *clause, List *indexcolnos);
 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
-static List *get_switched_clauses(List *clauses, Relids outerrelids);
+static List *get_switched_clauses(const List *clauses, Relids outerrelids);
 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
-static void copy_generic_path_info(Plan *dest, Path *src);
-static void copy_plan_costsize(Plan *dest, Plan *src);
+static void copy_generic_path_info(Plan *dest, const Path *src);
+static void copy_plan_costsize(Plan *dest, const Plan *src);
 static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
 									 double limit_tuples);
 static void label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan,
@@ -276,7 +281,7 @@ static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
 static IncrementalSort *make_incrementalsort_from_pathkeys(Plan *lefttree,
 														   List *pathkeys, Relids relids, int nPresortedCols);
 static Sort *make_sort_from_groupcols(List *groupcls,
-									  AttrNumber *grpColIdx,
+									  const AttrNumber *grpColIdx,
 									  Plan *lefttree);
 static Material *make_material(Plan *lefttree);
 static Memoize *make_memoize(Plan *lefttree, Oid *hashoperators,
@@ -286,7 +291,7 @@ static Memoize *make_memoize(Plan *lefttree, Oid *hashoperators,
 							 Cardinality est_calls,
 							 Cardinality est_unique_keys,
 							 double est_hit_ratio);
-static WindowAgg *make_windowagg(List *tlist, WindowClause *wc,
+static WindowAgg *make_windowagg(List *tlist, const WindowClause *wc,
 								 int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations,
 								 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations,
 								 List *runCondition, List *qual, bool topWindow,
@@ -314,7 +319,8 @@ static ModifyTable *make_modifytable(PlannerInfo *root, Plan *subplan,
 									 List *resultRelations,
 									 List *updateColnosLists,
 									 List *withCheckOptionLists, List *returningLists,
-									 List *rowMarks, OnConflictExpr *onconflict,
+									 List *rowMarks,
+									 const OnConflictExpr *onconflict,
 									 List *mergeActionLists, List *mergeJoinConditions,
 									 int epqParam);
 static GatherMerge *create_gather_merge_plan(PlannerInfo *root,
@@ -815,7 +821,7 @@ create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
  * deal with replacing nestloop params.
  */
 static List *
-build_path_tlist(PlannerInfo *root, Path *path)
+build_path_tlist(PlannerInfo *root, const Path *path)
 {
 	List	   *tlist = NIL;
 	Index	   *sortgrouprefs = path->pathtarget->sortgrouprefs;
@@ -855,7 +861,7 @@ build_path_tlist(PlannerInfo *root, Path *path)
  *		rather than only those Vars actually referenced.
  */
 static bool
-use_physical_tlist(PlannerInfo *root, Path *path, int flags)
+use_physical_tlist(const PlannerInfo *root, Path *path, int flags)
 {
 	RelOptInfo *rel = path->parent;
 	int			i;
@@ -2198,7 +2204,7 @@ create_agg_plan(PlannerInfo *root, AggPath *best_path)
  * look them up there.
  */
 static AttrNumber *
-remap_groupColIdx(PlannerInfo *root, List *groupClause)
+remap_groupColIdx(const PlannerInfo *root, List *groupClause)
 {
 	AttrNumber *grouping_map = root->grouping_map;
 	AttrNumber *new_grpColIdx;
@@ -2842,7 +2848,7 @@ static Scan *
 create_indexscan_plan(PlannerInfo *root,
 					  IndexPath *best_path,
 					  List *tlist,
-					  List *scan_clauses,
+					  const List *scan_clauses,
 					  bool indexonly)
 {
 	Scan	   *scan_plan;
@@ -3038,7 +3044,7 @@ static BitmapHeapScan *
 create_bitmap_scan_plan(PlannerInfo *root,
 						BitmapHeapPath *best_path,
 						List *tlist,
-						List *scan_clauses)
+						const List *scan_clauses)
 {
 	Index		baserelid = best_path->path.parent->relid;
 	Plan	   *bitmapqualplan;
@@ -4962,7 +4968,7 @@ replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
  * things will go awry).
  */
 static void
-fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
+fix_indexqual_references(PlannerInfo *root, const IndexPath *index_path,
 						 List **stripped_indexquals_p, List **fixed_indexquals_p)
 {
 	IndexOptInfo *index = index_path->indexinfo;
@@ -5003,7 +5009,7 @@ fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
  * bare clauses and a separate indexcol list, instead of IndexClauses.
  */
 static List *
-fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
+fix_indexorderby_references(PlannerInfo *root, const IndexPath *index_path)
 {
 	IndexOptInfo *index = index_path->indexinfo;
 	List	   *fixed_indexorderbys;
@@ -5178,7 +5184,7 @@ fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
  *	  outer_is_left field in each RestrictInfo to show which side was which.
  */
 static List *
-get_switched_clauses(List *clauses, Relids outerrelids)
+get_switched_clauses(const List *clauses, Relids outerrelids)
 {
 	List	   *t_list = NIL;
 	ListCell   *l;
@@ -5349,7 +5355,7 @@ order_qual_clauses(PlannerInfo *root, List *clauses)
  * Also copy the parallel-related flags, which the executor *will* use.
  */
 static void
-copy_generic_path_info(Plan *dest, Path *src)
+copy_generic_path_info(Plan *dest, const Path *src)
 {
 	dest->disabled_nodes = src->disabled_nodes;
 	dest->startup_cost = src->startup_cost;
@@ -5365,7 +5371,7 @@ copy_generic_path_info(Plan *dest, Path *src)
  * (Most callers alter the info after copying it.)
  */
 static void
-copy_plan_costsize(Plan *dest, Plan *src)
+copy_plan_costsize(Plan *dest, const Plan *src)
 {
 	dest->disabled_nodes = src->disabled_nodes;
 	dest->startup_cost = src->startup_cost;
@@ -6436,7 +6442,7 @@ make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
  */
 static Sort *
 make_sort_from_groupcols(List *groupcls,
-						 AttrNumber *grpColIdx,
+						 const AttrNumber *grpColIdx,
 						 Plan *lefttree)
 {
 	List	   *sub_tlist = lefttree->targetlist;
@@ -6601,7 +6607,7 @@ make_agg(List *tlist, List *qual,
 }
 
 static WindowAgg *
-make_windowagg(List *tlist, WindowClause *wc,
+make_windowagg(List *tlist, const WindowClause *wc,
 			   int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations,
 			   int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations,
 			   List *runCondition, List *qual, bool topWindow, Plan *lefttree)
@@ -6999,7 +7005,8 @@ make_modifytable(PlannerInfo *root, Plan *subplan,
 				 List *resultRelations,
 				 List *updateColnosLists,
 				 List *withCheckOptionLists, List *returningLists,
-				 List *rowMarks, OnConflictExpr *onconflict,
+				 List *rowMarks,
+				 const OnConflictExpr *onconflict,
 				 List *mergeActionLists, List *mergeJoinConditions,
 				 int epqParam)
 {
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index 671c5cde8fc..cee8f0f20cf 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -82,7 +82,7 @@ typedef struct JoinTreeItem
 } JoinTreeItem;
 
 
-static bool is_partial_agg_memory_risky(PlannerInfo *root);
+static bool is_partial_agg_memory_risky(const PlannerInfo *root);
 static void create_agg_clause_infos(PlannerInfo *root);
 static void create_grouping_expr_infos(PlannerInfo *root);
 static EquivalenceClass *get_eclass_for_sortgroupclause(PlannerInfo *root,
@@ -105,11 +105,11 @@ static SpecialJoinInfo *make_outerjoininfo(PlannerInfo *root,
 										   JoinType jointype, Index ojrelid,
 										   List *clause);
 static void compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo,
-								  List *clause);
+								  const List *clause);
 static void deconstruct_distribute_oj_quals(PlannerInfo *root,
-											List *jtitems,
+											const List *jtitems,
 											JoinTreeItem *jtitem);
-static void distribute_quals_to_rels(PlannerInfo *root, List *clauses,
+static void distribute_quals_to_rels(PlannerInfo *root, const List *clauses,
 									 JoinTreeItem *jtitem,
 									 SpecialJoinInfo *sjinfo,
 									 Index security_level,
@@ -133,7 +133,8 @@ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause,
 									bool has_clone,
 									bool is_clone,
 									List **postponed_oj_qual_list);
-static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause);
+static bool check_redundant_nullability_qual(const PlannerInfo *root,
+											 Node *clause);
 static Relids get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids);
 static void check_mergejoinable(RestrictInfo *restrictinfo);
 static void check_hashjoinable(RestrictInfo *restrictinfo);
@@ -728,7 +729,7 @@ setup_eager_aggregation(PlannerInfo *root)
  * materialized nodes.
  */
 static bool
-is_partial_agg_memory_risky(PlannerInfo *root)
+is_partial_agg_memory_risky(const PlannerInfo *root)
 {
 	ListCell   *lc;
 
@@ -2414,7 +2415,8 @@ make_outerjoininfo(PlannerInfo *root,
  * SpecialJoinInfo; the rest may not be set yet.
  */
 static void
-compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo, List *clause)
+compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo,
+					  const List *clause)
 {
 	List	   *semi_operators;
 	List	   *semi_rhs_exprs;
@@ -2593,7 +2595,7 @@ compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo, List *clause)
  */
 static void
 deconstruct_distribute_oj_quals(PlannerInfo *root,
-								List *jtitems,
+								const List *jtitems,
 								JoinTreeItem *jtitem)
 {
 	SpecialJoinInfo *sjinfo = jtitem->sjinfo;
@@ -2833,7 +2835,7 @@ deconstruct_distribute_oj_quals(PlannerInfo *root,
  *	  of an AND'ed list of clauses.
  */
 static void
-distribute_quals_to_rels(PlannerInfo *root, List *clauses,
+distribute_quals_to_rels(PlannerInfo *root, const List *clauses,
 						 JoinTreeItem *jtitem,
 						 SpecialJoinInfo *sjinfo,
 						 Index security_level,
@@ -3301,7 +3303,7 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause,
  * the qual.
  */
 static bool
-check_redundant_nullability_qual(PlannerInfo *root, Node *clause)
+check_redundant_nullability_qual(const PlannerInfo *root, Node *clause)
 {
 	Var		   *forced_null_var;
 	ListCell   *lc;
diff --git a/src/backend/optimizer/plan/planagg.c b/src/backend/optimizer/plan/planagg.c
index a2ac58d246e..dd3f7787a6b 100644
--- a/src/backend/optimizer/plan/planagg.c
+++ b/src/backend/optimizer/plan/planagg.c
@@ -47,7 +47,7 @@
 #include "utils/lsyscache.h"
 #include "utils/syscache.h"
 
-static bool can_minmax_aggs(PlannerInfo *root, List **context);
+static bool can_minmax_aggs(const PlannerInfo *root, List **context);
 static bool build_minmax_path(PlannerInfo *root, MinMaxAggInfo *mminfo,
 							  Oid eqop, Oid sortop, bool reverse_sort,
 							  bool nulls_first);
@@ -235,7 +235,7 @@ preprocess_minmax_aggregates(PlannerInfo *root)
  * Returns false if a non-MIN/MAX aggregate is found, true otherwise.
  */
 static bool
-can_minmax_aggs(PlannerInfo *root, List **context)
+can_minmax_aggs(const PlannerInfo *root, List **context)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index fd77334e5fd..ee5898904f3 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -140,15 +140,17 @@ static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
 static void grouping_planner(PlannerInfo *root, double tuple_fraction,
 							 SetOperationStmt *setops);
 static grouping_sets_data *preprocess_grouping_sets(PlannerInfo *root);
-static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
+static List *remap_to_groupclause_idx(const List *groupClause,
+									  const List *gsets,
 									  int *tleref_to_colnum_map);
 static void preprocess_rowmarks(PlannerInfo *root);
 static double preprocess_limit(PlannerInfo *root,
 							   double tuple_fraction,
 							   int64 *offset_est, int64 *count_est);
-static List *preprocess_groupclause(PlannerInfo *root, List *force);
+static List *preprocess_groupclause(const PlannerInfo *root,
+									const List *force);
 static List *extract_rollup_sets(List *groupingSets);
-static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
+static List *reorder_grouping_sets(const List *groupingSets, List *sortclause);
 static void standard_qp_callback(PlannerInfo *root, void *extra);
 static double get_number_of_groups(PlannerInfo *root,
 								   double path_rows,
@@ -159,7 +161,7 @@ static RelOptInfo *create_grouping_paths(PlannerInfo *root,
 										 PathTarget *target,
 										 bool target_parallel_safe,
 										 grouping_sets_data *gd);
-static bool is_degenerate_grouping(PlannerInfo *root);
+static bool is_degenerate_grouping(const PlannerInfo *root);
 static void create_degenerate_grouping_paths(PlannerInfo *root,
 											 RelOptInfo *input_rel,
 											 RelOptInfo *grouped_rel);
@@ -193,7 +195,7 @@ static void create_one_window_path(PlannerInfo *root,
 								   Path *path,
 								   PathTarget *input_target,
 								   PathTarget *output_target,
-								   WindowFuncLists *wflists,
+								   const WindowFuncLists *wflists,
 								   List *activeWindows);
 static RelOptInfo *create_distinct_paths(PlannerInfo *root,
 										 RelOptInfo *input_rel,
@@ -203,11 +205,11 @@ static void create_partial_distinct_paths(PlannerInfo *root,
 										  RelOptInfo *final_distinct_rel,
 										  PathTarget *target);
 static RelOptInfo *create_final_distinct_paths(PlannerInfo *root,
-											   RelOptInfo *input_rel,
+											   const RelOptInfo *input_rel,
 											   RelOptInfo *distinct_rel);
 static List *get_useful_pathkeys_for_distinct(PlannerInfo *root,
 											  List *needed_pathkeys,
-											  List *path_pathkeys);
+											  const List *path_pathkeys);
 static RelOptInfo *create_ordered_paths(PlannerInfo *root,
 										RelOptInfo *input_rel,
 										PathTarget *target,
@@ -219,13 +221,14 @@ static PathTarget *make_partial_grouping_target(PlannerInfo *root,
 												PathTarget *grouping_target,
 												Node *havingQual);
 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
-static void optimize_window_clauses(PlannerInfo *root,
+static void optimize_window_clauses(const PlannerInfo *root,
 									WindowFuncLists *wflists);
-static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
-static void name_active_windows(List *activeWindows);
+static List *select_active_windows(const PlannerInfo *root,
+								   const WindowFuncLists *wflists);
+static void name_active_windows(const List *activeWindows);
 static PathTarget *make_window_input_target(PlannerInfo *root,
 											PathTarget *final_target,
-											List *activeWindows);
+											const List *activeWindows);
 static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
 									  List *tlist);
 static PathTarget *make_sort_input_target(PlannerInfo *root,
@@ -233,9 +236,10 @@ static PathTarget *make_sort_input_target(PlannerInfo *root,
 										  bool *have_postponed_srfs);
 static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
 								  List *targets, List *targets_contain_srfs);
-static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
+static void add_paths_to_grouping_rel(PlannerInfo *root,
+									  const RelOptInfo *input_rel,
 									  RelOptInfo *grouped_rel,
-									  RelOptInfo *partially_grouped_rel,
+									  const RelOptInfo *partially_grouped_rel,
 									  const AggClauseCosts *agg_costs,
 									  grouping_sets_data *gd,
 									  GroupPathExtraData *extra);
@@ -248,11 +252,11 @@ static RelOptInfo *create_partial_grouping_paths(PlannerInfo *root,
 static Path *make_ordered_path(PlannerInfo *root,
 							   RelOptInfo *rel,
 							   Path *path,
-							   Path *cheapest_path,
+							   const Path *cheapest_path,
 							   List *pathkeys,
 							   double limit_tuples);
 static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel);
-static bool can_partial_agg(PlannerInfo *root);
+static bool can_partial_agg(const PlannerInfo *root);
 static void apply_scanjoin_target_to_paths(PlannerInfo *root,
 										   RelOptInfo *rel,
 										   List *scanjoin_targets,
@@ -273,7 +277,8 @@ static bool group_by_has_partkey(RelOptInfo *input_rel,
 static int	common_prefix_cmp(const void *a, const void *b);
 static List *generate_setop_child_grouplist(SetOperationStmt *op,
 											List *targetlist);
-static void create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
+static void create_final_unique_paths(PlannerInfo *root,
+									  const RelOptInfo *input_rel,
 									  List *sortPathkeys, List *groupClause,
 									  SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
 static void create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
@@ -2387,8 +2392,8 @@ preprocess_grouping_sets(PlannerInfo *root)
  * (without annotation) mapped to indexes into the given groupclause.
  */
 static List *
-remap_to_groupclause_idx(List *groupClause,
-						 List *gsets,
+remap_to_groupclause_idx(const List *groupClause,
+						 const List *gsets,
 						 int *tleref_to_colnum_map)
 {
 	int			ref = 0;
@@ -2853,7 +2858,7 @@ limit_needed(Query *parse)
  * possible is done elsewhere.
  */
 static List *
-preprocess_groupclause(PlannerInfo *root, List *force)
+preprocess_groupclause(const PlannerInfo *root, const List *force)
 {
 	Query	   *parse = root->parse;
 	List	   *new_groupclause = NIL;
@@ -3161,7 +3166,7 @@ extract_rollup_sets(List *groupingSets)
  * gets implemented in one pass.)
  */
 static List *
-reorder_grouping_sets(List *groupingSets, List *sortclause)
+reorder_grouping_sets(const List *groupingSets, List *sortclause)
 {
 	ListCell   *lc;
 	List	   *previous = NIL;
@@ -3209,7 +3214,7 @@ reorder_grouping_sets(List *groupingSets, List *sortclause)
  *		containing a volatile function.  Otherwise returns false.
  */
 static bool
-has_volatile_pathkey(List *keys)
+has_volatile_pathkey(const List *keys)
 {
 	ListCell   *lc;
 
@@ -3971,7 +3976,7 @@ make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
  * grouping sets are all empty).
  */
 static bool
-is_degenerate_grouping(PlannerInfo *root)
+is_degenerate_grouping(const PlannerInfo *root)
 {
 	Query	   *parse = root->parse;
 
@@ -4641,7 +4646,7 @@ create_one_window_path(PlannerInfo *root,
 					   Path *path,
 					   PathTarget *input_target,
 					   PathTarget *output_target,
-					   WindowFuncLists *wflists,
+					   const WindowFuncLists *wflists,
 					   List *activeWindows)
 {
 	PathTarget *window_target;
@@ -5059,7 +5064,7 @@ create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
  * distinct_rel: destination relation for storing created paths
  */
 static RelOptInfo *
-create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
+create_final_distinct_paths(PlannerInfo *root, const RelOptInfo *input_rel,
 							RelOptInfo *distinct_rel)
 {
 	Query	   *parse = root->parse;
@@ -5240,7 +5245,7 @@ create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
  */
 static List *
 get_useful_pathkeys_for_distinct(PlannerInfo *root, List *needed_pathkeys,
-								 List *path_pathkeys)
+								 const List *path_pathkeys)
 {
 	List	   *useful_pathkeys_list = NIL;
 	List	   *useful_pathkeys = NIL;
@@ -5831,7 +5836,7 @@ postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
  * may allow more things to be done here in the future.
  */
 static void
-optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
+optimize_window_clauses(const PlannerInfo *root, WindowFuncLists *wflists)
 {
 	List	   *windowClause = root->parse->windowClause;
 	ListCell   *lc;
@@ -5971,7 +5976,7 @@ optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
  *		by non-deleted WindowFuncs) in the order they are to be executed.
  */
 static List *
-select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
+select_active_windows(const PlannerInfo *root, const WindowFuncLists *wflists)
 {
 	List	   *windowClause = root->parse->windowClause;
 	List	   *result = NIL;
@@ -6054,7 +6059,7 @@ select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
  * activeWindows: result of select_active_windows
  */
 static void
-name_active_windows(List *activeWindows)
+name_active_windows(const List *activeWindows)
 {
 	int			next_n = 1;
 	char		newname[16];
@@ -6176,7 +6181,7 @@ common_prefix_cmp(const void *a, const void *b)
 static PathTarget *
 make_window_input_target(PlannerInfo *root,
 						 PathTarget *final_target,
-						 List *activeWindows)
+						 const List *activeWindows)
 {
 	PathTarget *input_target;
 	Bitmapset  *sgrefs;
@@ -7095,9 +7100,9 @@ done:
  * Add non-partial paths to grouping relation.
  */
 static void
-add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
+add_paths_to_grouping_rel(PlannerInfo *root, const RelOptInfo *input_rel,
 						  RelOptInfo *grouped_rel,
-						  RelOptInfo *partially_grouped_rel,
+						  const RelOptInfo *partially_grouped_rel,
 						  const AggClauseCosts *agg_costs,
 						  grouping_sets_data *gd,
 						  GroupPathExtraData *extra)
@@ -7708,7 +7713,8 @@ create_partial_grouping_paths(PlannerInfo *root,
  */
 static Path *
 make_ordered_path(PlannerInfo *root, RelOptInfo *rel, Path *path,
-				  Path *cheapest_path, List *pathkeys, double limit_tuples)
+				  const Path *cheapest_path, List *pathkeys,
+				  double limit_tuples)
 {
 	bool		is_sorted;
 	int			presorted_keys;
@@ -7849,7 +7855,7 @@ gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
  * Returns true when possible, false otherwise.
  */
 static bool
-can_partial_agg(PlannerInfo *root)
+can_partial_agg(const PlannerInfo *root)
 {
 	Query	   *parse = root->parse;
 
@@ -8681,7 +8687,7 @@ create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo)
  *    Create unique paths in 'unique_rel' based on 'input_rel' pathlist
  */
 static void
-create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
+create_final_unique_paths(PlannerInfo *root, const RelOptInfo *input_rel,
 						  List *sortPathkeys, List *groupClause,
 						  SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
 {
diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c
index ff63d20f8d5..30995975742 100644
--- a/src/backend/optimizer/plan/subselect.c
+++ b/src/backend/optimizer/plan/subselect.c
@@ -67,13 +67,14 @@ typedef struct inline_cte_walker_context
 
 
 static Node *build_subplan(PlannerInfo *root, Plan *plan, Path *path,
-						   PlannerInfo *subroot, List *plan_params,
+						   PlannerInfo *subroot,
+						   const List *plan_params,
 						   SubLinkType subLinkType, int subLinkId,
 						   Node *testexpr, List *testexpr_paramids,
 						   bool unknownEqFalse);
-static List *generate_subquery_params(PlannerInfo *root, List *tlist,
+static List *generate_subquery_params(PlannerInfo *root, const List *tlist,
 									  List **paramIds);
-static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
+static List *generate_subquery_vars(PlannerInfo *root, const List *tlist,
 									Index varno);
 static Node *convert_testexpr(PlannerInfo *root,
 							  Node *testexpr,
@@ -89,7 +90,7 @@ static bool contain_dml(Node *node);
 static bool contain_dml_walker(Node *node, void *context);
 static bool contain_outer_selfref(Node *node);
 static bool contain_outer_selfref_walker(Node *node, Index *depth);
-static void inline_cte(PlannerInfo *root, CommonTableExpr *cte);
+static void inline_cte(const PlannerInfo *root, CommonTableExpr *cte);
 static bool inline_cte_walker(Node *node, inline_cte_walker_context *context);
 static bool simplify_EXISTS_query(PlannerInfo *root, Query *query);
 static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
@@ -324,7 +325,7 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
  */
 static Node *
 build_subplan(PlannerInfo *root, Plan *plan, Path *path,
-			  PlannerInfo *subroot, List *plan_params,
+			  PlannerInfo *subroot, const List *plan_params,
 			  SubLinkType subLinkType, int subLinkId,
 			  Node *testexpr, List *testexpr_paramids,
 			  bool unknownEqFalse)
@@ -582,7 +583,8 @@ build_subplan(PlannerInfo *root, Plan *plan, Path *path,
  * We also return an integer list of the paramids of the Params.
  */
 static List *
-generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
+generate_subquery_params(PlannerInfo *root, const List *tlist,
+						 List **paramIds)
 {
 	List	   *result;
 	List	   *ids;
@@ -615,7 +617,7 @@ generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
  * The Vars have the specified varno (RTE index).
  */
 static List *
-generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
+generate_subquery_vars(PlannerInfo *root, const List *tlist, Index varno)
 {
 	List	   *result;
 	ListCell   *lc;
@@ -1136,7 +1138,7 @@ contain_outer_selfref_walker(Node *node, Index *depth)
  * inline_cte: convert RTE_CTE references to given CTE into RTE_SUBQUERYs
  */
 static void
-inline_cte(PlannerInfo *root, CommonTableExpr *cte)
+inline_cte(const PlannerInfo *root, CommonTableExpr *cte)
 {
 	struct inline_cte_walker_context context;
 
diff --git a/src/backend/optimizer/prep/prepagg.c b/src/backend/optimizer/prep/prepagg.c
index c0a2f04a8c3..5dc3077b910 100644
--- a/src/backend/optimizer/prep/prepagg.c
+++ b/src/backend/optimizer/prep/prepagg.c
@@ -52,7 +52,7 @@
 #include "utils/syscache.h"
 
 static bool preprocess_aggrefs_walker(Node *node, PlannerInfo *root);
-static int	find_compatible_agg(PlannerInfo *root, Aggref *newagg,
+static int	find_compatible_agg(const PlannerInfo *root, Aggref *newagg,
 								List **same_input_transnos);
 static int	find_compatible_trans(PlannerInfo *root, Aggref *newagg,
 								  bool shareable,
@@ -61,7 +61,7 @@ static int	find_compatible_trans(PlannerInfo *root, Aggref *newagg,
 								  Oid aggcombinefn,
 								  Oid aggserialfn, Oid aggdeserialfn,
 								  Datum initValue, bool initValueIsNull,
-								  List *transnos);
+								  const List *transnos);
 static Datum GetAggInitVal(Datum textInitVal, Oid transtype);
 
 /* -----------------
@@ -376,7 +376,7 @@ preprocess_aggrefs_walker(Node *node, PlannerInfo *root)
  * the state value of another aggregate.
  */
 static int
-find_compatible_agg(PlannerInfo *root, Aggref *newagg,
+find_compatible_agg(const PlannerInfo *root, Aggref *newagg,
 					List **same_input_transnos)
 {
 	ListCell   *lc;
@@ -460,7 +460,7 @@ find_compatible_trans(PlannerInfo *root, Aggref *newagg, bool shareable,
 					  Oid aggcombinefn,
 					  Oid aggserialfn, Oid aggdeserialfn,
 					  Datum initValue, bool initValueIsNull,
-					  List *transnos)
+					  const List *transnos)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/optimizer/prep/prepqual.c b/src/backend/optimizer/prep/prepqual.c
index 008dce2478c..fa7acba61a6 100644
--- a/src/backend/optimizer/prep/prepqual.c
+++ b/src/backend/optimizer/prep/prepqual.c
@@ -37,8 +37,8 @@
 #include "utils/lsyscache.h"
 
 
-static List *pull_ands(List *andlist);
-static List *pull_ors(List *orlist);
+static List *pull_ands(const List *andlist);
+static List *pull_ors(const List *orlist);
 static Expr *find_duplicate_ors(Expr *qual, bool is_check);
 static Expr *process_duplicate_ors(List *orlist);
 
@@ -320,7 +320,7 @@ canonicalize_qual(Expr *qual, bool is_check)
  * Returns the rebuilt arglist (note original list structure is not touched).
  */
 static List *
-pull_ands(List *andlist)
+pull_ands(const List *andlist)
 {
 	List	   *out_list = NIL;
 	ListCell   *arg;
@@ -346,7 +346,7 @@ pull_ands(List *andlist)
  * Returns the rebuilt arglist (note original list structure is not touched).
  */
 static List *
-pull_ors(List *orlist)
+pull_ors(const List *orlist)
 {
 	List	   *out_list = NIL;
 	ListCell   *arg;
diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c
index f528f096a56..66bff2ccab4 100644
--- a/src/backend/optimizer/prep/prepunion.c
+++ b/src/backend/optimizer/prep/prepunion.c
@@ -66,18 +66,20 @@ static List *plan_union_children(PlannerInfo *root,
 								 List **tlist_list,
 								 List **istrivial_tlist);
 static void postprocess_setop_rel(PlannerInfo *root, RelOptInfo *rel);
-static List *generate_setop_tlist(List *colTypes, List *colCollations,
+static List *generate_setop_tlist(const List *colTypes,
+								  const List *colCollations,
 								  Index varno,
 								  bool hack_constants,
-								  List *input_tlist,
-								  List *refnames_tlist,
+								  const List *input_tlist,
+								  const List *refnames_tlist,
 								  bool *trivial_tlist);
-static List *generate_append_tlist(List *colTypes, List *colCollations,
+static List *generate_append_tlist(List *colTypes, const List *colCollations,
 								   List *input_tlists,
-								   List *refnames_tlist);
-static List *generate_setop_grouplist(SetOperationStmt *op, List *targetlist);
+								   const List *refnames_tlist);
+static List *generate_setop_grouplist(SetOperationStmt *op,
+									  const List *targetlist);
 static PathTarget *create_setop_pathtarget(PlannerInfo *root, List *tlist,
-										   List *child_pathlist);
+										   const List *child_pathlist);
 
 
 /*
@@ -1480,11 +1482,11 @@ postprocess_setop_rel(PlannerInfo *root, RelOptInfo *rel)
  * trivial_tlist: output parameter, set to true if targetlist is trivial
  */
 static List *
-generate_setop_tlist(List *colTypes, List *colCollations,
+generate_setop_tlist(const List *colTypes, const List *colCollations,
 					 Index varno,
 					 bool hack_constants,
-					 List *input_tlist,
-					 List *refnames_tlist,
+					 const List *input_tlist,
+					 const List *refnames_tlist,
 					 bool *trivial_tlist)
 {
 	List	   *tlist = NIL;
@@ -1608,9 +1610,9 @@ generate_setop_tlist(List *colTypes, List *colCollations,
  * ought to refactor this code to produce a PathTarget directly, anyway.
  */
 static List *
-generate_append_tlist(List *colTypes, List *colCollations,
+generate_append_tlist(List *colTypes, const List *colCollations,
 					  List *input_tlists,
-					  List *refnames_tlist)
+					  const List *refnames_tlist)
 {
 	List	   *tlist = NIL;
 	int			resno = 1;
@@ -1717,7 +1719,7 @@ generate_append_tlist(List *colTypes, List *colCollations,
  * proper sortgrouprefs into it (copying those from the targetlist).
  */
 static List *
-generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
+generate_setop_grouplist(SetOperationStmt *op, const List *targetlist)
 {
 	List	   *grouplist = copyObject(op->groupClauses);
 	ListCell   *lg;
@@ -1757,7 +1759,8 @@ generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
  * statistics of the columns from the set op children.
  */
 static PathTarget *
-create_setop_pathtarget(PlannerInfo *root, List *tlist, List *child_pathlist)
+create_setop_pathtarget(PlannerInfo *root, List *tlist,
+						const List *child_pathlist)
 {
 	PathTarget *reltarget;
 	ListCell   *lc;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index bda4c4eb292..b61ac17a512 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -118,7 +118,7 @@ static Node *eval_const_expressions_mutator(Node *node,
 											eval_const_expressions_context *context);
 static bool contain_non_const_walker(Node *node, void *context);
 static bool ece_function_is_safe(Oid funcid,
-								 eval_const_expressions_context *context);
+								 const eval_const_expressions_context *context);
 static List *simplify_or_arguments(List *args,
 								   eval_const_expressions_context *context,
 								   bool *haveNull, bool *forceTrue);
@@ -132,7 +132,7 @@ static Expr *simplify_function(Oid funcid,
 							   bool funcvariadic, bool process_args, bool allow_non_const,
 							   eval_const_expressions_context *context);
 static Node *simplify_aggref(Aggref *aggref,
-							 eval_const_expressions_context *context);
+							 const eval_const_expressions_context *context);
 static List *reorder_function_arguments(List *args, int pronargs,
 										HeapTuple func_tuple);
 static List *add_function_defaults(List *args, int pronargs,
@@ -145,7 +145,7 @@ static Expr *evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
 							   Oid result_collid, Oid input_collid, List *args,
 							   bool funcvariadic,
 							   HeapTuple func_tuple,
-							   eval_const_expressions_context *context);
+							   const eval_const_expressions_context *context);
 static Expr *inline_function(Oid funcid, Oid result_type, Oid result_collid,
 							 Oid input_collid, List *args,
 							 bool funcvariadic,
@@ -3805,7 +3805,8 @@ contain_non_const_walker(Node *node, void *context)
  * Subroutine for eval_const_expressions: check if a function is OK to evaluate
  */
 static bool
-ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
+ece_function_is_safe(Oid funcid,
+					 const eval_const_expressions_context *context)
 {
 	char		provolatile = func_volatile(funcid);
 
@@ -4218,7 +4219,7 @@ simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
  * details.
  */
 static Node *
-simplify_aggref(Aggref *aggref, eval_const_expressions_context *context)
+simplify_aggref(Aggref *aggref, const eval_const_expressions_context *context)
 {
 	Oid			prosupport = get_func_support(aggref->aggfnoid);
 
@@ -4611,7 +4612,7 @@ evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
 				  Oid result_collid, Oid input_collid, List *args,
 				  bool funcvariadic,
 				  HeapTuple func_tuple,
-				  eval_const_expressions_context *context)
+				  const eval_const_expressions_context *context)
 {
 	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
 	bool		has_nonconst_input = false;
diff --git a/src/backend/optimizer/util/inherit.c b/src/backend/optimizer/util/inherit.c
index 6d5225079f8..6408f313e1f 100644
--- a/src/backend/optimizer/util/inherit.c
+++ b/src/backend/optimizer/util/inherit.c
@@ -49,7 +49,7 @@ static void expand_single_inheritance_child(PlannerInfo *root,
 											RangeTblEntry **childrte_p,
 											Index *childRTindex_p);
 static Bitmapset *translate_col_privs(const Bitmapset *parent_privs,
-									  List *translated_vars);
+									  const List *translated_vars);
 static Bitmapset *translate_col_privs_multilevel(PlannerInfo *root,
 												 RelOptInfo *rel,
 												 RelOptInfo *parent_rel,
@@ -704,7 +704,7 @@ get_rel_all_updated_cols(PlannerInfo *root, RelOptInfo *rel)
  */
 static Bitmapset *
 translate_col_privs(const Bitmapset *parent_privs,
-					List *translated_vars)
+					const List *translated_vars)
 {
 	Bitmapset  *child_privs = NULL;
 	bool		whole_row;
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index b6be4ddbd01..497edc53160 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -51,9 +51,9 @@ typedef enum
 static int	append_total_cost_compare(const ListCell *a, const ListCell *b);
 static int	append_startup_cost_compare(const ListCell *a, const ListCell *b);
 static List *reparameterize_pathlist_by_child(PlannerInfo *root,
-											  List *pathlist,
+											  const List *pathlist,
 											  RelOptInfo *child_rel);
-static bool pathlist_is_reparameterizable_by_child(List *pathlist,
+static bool pathlist_is_reparameterizable_by_child(const List *pathlist,
 												   RelOptInfo *child_rel);
 
 
@@ -4445,7 +4445,7 @@ do { \
  */
 static List *
 reparameterize_pathlist_by_child(PlannerInfo *root,
-								 List *pathlist,
+								 const List *pathlist,
 								 RelOptInfo *child_rel)
 {
 	ListCell   *lc;
@@ -4473,7 +4473,8 @@ reparameterize_pathlist_by_child(PlannerInfo *root,
  *		Helper function to check if a list of paths can be reparameterized.
  */
 static bool
-pathlist_is_reparameterizable_by_child(List *pathlist, RelOptInfo *child_rel)
+pathlist_is_reparameterizable_by_child(const List *pathlist,
+									   RelOptInfo *child_rel)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index ed0dac37f51..b5b081c2976 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -67,7 +67,8 @@ typedef struct NotnullHashEntry
 } NotnullHashEntry;
 
 
-static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
+static void get_relation_foreign_keys(PlannerInfo *root,
+									  const RelOptInfo *rel,
 									  Relation relation, bool inhparent);
 static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
 										  List *idxExprs);
@@ -592,7 +593,7 @@ get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
  * relcache entries would probably exceed any savings.
  */
 static void
-get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
+get_relation_foreign_keys(PlannerInfo *root, const RelOptInfo *rel,
 						  Relation relation, bool inhparent)
 {
 	List	   *rtable = root->parse->rtable;
diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c
index 1158bc194c3..820a3879032 100644
--- a/src/backend/optimizer/util/relnode.c
+++ b/src/backend/optimizer/util/relnode.c
@@ -47,10 +47,10 @@ typedef struct JoinHashEntry
 	RelOptInfo *join_rel;
 } JoinHashEntry;
 
-static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
-								RelOptInfo *input_rel,
+static void build_joinrel_tlist(PlannerInfo *root, const RelOptInfo *joinrel,
+								const RelOptInfo *input_rel,
 								SpecialJoinInfo *sjinfo,
-								List *pushed_down_joins,
+								const List *pushed_down_joins,
 								bool can_null);
 static List *build_joinrel_restrictlist(PlannerInfo *root,
 										RelOptInfo *joinrel,
@@ -62,11 +62,11 @@ static void build_joinrel_joinlist(RelOptInfo *joinrel,
 								   RelOptInfo *inner_rel);
 static List *subbuild_joinrel_restrictlist(PlannerInfo *root,
 										   RelOptInfo *joinrel,
-										   RelOptInfo *input_rel,
+										   const RelOptInfo *input_rel,
 										   Relids both_input_relids,
 										   List *new_restrictlist);
 static List *subbuild_joinrel_joinlist(RelOptInfo *joinrel,
-									   List *joininfo_list,
+									   const List *joininfo_list,
 									   List *new_joininfo);
 static void set_foreign_rel_properties(RelOptInfo *joinrel,
 									   RelOptInfo *outer_rel, RelOptInfo *inner_rel);
@@ -78,15 +78,17 @@ static void build_joinrel_partition_info(PlannerInfo *root,
 										 List *restrictlist);
 static bool have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
 								   RelOptInfo *rel1, RelOptInfo *rel2,
-								   JoinType jointype, List *restrictlist);
+								   JoinType jointype,
+								   const List *restrictlist);
 static int	match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel,
 										 bool strict_op);
 static void set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
-											RelOptInfo *outer_rel, RelOptInfo *inner_rel,
+											const RelOptInfo *outer_rel,
+											const RelOptInfo *inner_rel,
 											JoinType jointype);
 static void build_child_join_reltarget(PlannerInfo *root,
-									   RelOptInfo *parentrel,
-									   RelOptInfo *childrel,
+									   const RelOptInfo *parentrel,
+									   const RelOptInfo *childrel,
 									   int nappinfos,
 									   AppendRelInfo **appinfos);
 static bool eager_aggregation_possible_for_relation(PlannerInfo *root,
@@ -96,7 +98,7 @@ static bool init_grouping_targets(PlannerInfo *root, RelOptInfo *rel,
 								  List **group_clauses, List **group_exprs);
 static bool is_var_in_aggref_only(PlannerInfo *root, Var *var);
 static bool is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel);
-static Index get_expression_sortgroupref(PlannerInfo *root, Expr *expr);
+static Index get_expression_sortgroupref(const PlannerInfo *root, Expr *expr);
 
 
 /*
@@ -1220,10 +1222,10 @@ min_join_parameterization(PlannerInfo *root,
  * A/B join.
  */
 static void
-build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
-					RelOptInfo *input_rel,
+build_joinrel_tlist(PlannerInfo *root, const RelOptInfo *joinrel,
+					const RelOptInfo *input_rel,
 					SpecialJoinInfo *sjinfo,
-					List *pushed_down_joins,
+					const List *pushed_down_joins,
 					bool can_null)
 {
 	Relids		relids = joinrel->relids;
@@ -1462,7 +1464,7 @@ build_joinrel_joinlist(RelOptInfo *joinrel,
 static List *
 subbuild_joinrel_restrictlist(PlannerInfo *root,
 							  RelOptInfo *joinrel,
-							  RelOptInfo *input_rel,
+							  const RelOptInfo *input_rel,
 							  Relids both_input_relids,
 							  List *new_restrictlist)
 {
@@ -1527,7 +1529,7 @@ subbuild_joinrel_restrictlist(PlannerInfo *root,
 
 static List *
 subbuild_joinrel_joinlist(RelOptInfo *joinrel,
-						  List *joininfo_list,
+						  const List *joininfo_list,
 						  List *new_joininfo)
 {
 	ListCell   *l;
@@ -2185,7 +2187,8 @@ build_joinrel_partition_info(PlannerInfo *root,
 static bool
 have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
 					   RelOptInfo *rel1, RelOptInfo *rel2,
-					   JoinType jointype, List *restrictlist)
+					   JoinType jointype,
+					   const List *restrictlist)
 {
 	PartitionScheme part_scheme = rel1->part_scheme;
 	bool		pk_known_equal[PARTITION_MAX_KEYS];
@@ -2480,7 +2483,8 @@ match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
  */
 static void
 set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
-								RelOptInfo *outer_rel, RelOptInfo *inner_rel,
+								const RelOptInfo *outer_rel,
+								const RelOptInfo *inner_rel,
 								JoinType jointype)
 {
 	PartitionScheme part_scheme = joinrel->part_scheme;
@@ -2624,8 +2628,8 @@ set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
  */
 static void
 build_child_join_reltarget(PlannerInfo *root,
-						   RelOptInfo *parentrel,
-						   RelOptInfo *childrel,
+						   const RelOptInfo *parentrel,
+						   const RelOptInfo *childrel,
 						   int nappinfos,
 						   AppendRelInfo **appinfos)
 {
@@ -3133,7 +3137,7 @@ is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel)
  *	  match is found.
  */
 static Index
-get_expression_sortgroupref(PlannerInfo *root, Expr *expr)
+get_expression_sortgroupref(const PlannerInfo *root, Expr *expr)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/optimizer/util/tlist.c b/src/backend/optimizer/util/tlist.c
index d2b4ecc5e51..e2df0fd925b 100644
--- a/src/backend/optimizer/util/tlist.c
+++ b/src/backend/optimizer/util/tlist.c
@@ -63,7 +63,7 @@ static bool split_pathtarget_walker(Node *node,
 									split_pathtarget_context *context);
 static void add_sp_item_to_pathtarget(PathTarget *target,
 									  split_pathtarget_item *item);
-static void add_sp_items_to_pathtarget(PathTarget *target, List *items);
+static void add_sp_items_to_pathtarget(PathTarget *target, const List *items);
 
 
 /*****************************************************************************
@@ -99,7 +99,7 @@ tlist_member(Expr *node, List *targetlist)
  * match.  For safety, though, we insist on vartype match.
  */
 static TargetEntry *
-tlist_member_match_var(Var *var, List *targetlist)
+tlist_member_match_var(const Var *var, const List *targetlist)
 {
 	ListCell   *temp;
 
@@ -1243,7 +1243,7 @@ add_sp_item_to_pathtarget(PathTarget *target, split_pathtarget_item *item)
  * Apply add_sp_item_to_pathtarget to each element of list.
  */
 static void
-add_sp_items_to_pathtarget(PathTarget *target, List *items)
+add_sp_items_to_pathtarget(PathTarget *target, const List *items)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 05314e7e76b..826d8db90dd 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -80,13 +80,14 @@ static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
 									   bool isTopLevel, List **targetlist);
 static void determineRecursiveColTypes(ParseState *pstate,
-									   Node *larg, List *nrtargetlist);
+									   Node *larg,
+									   const List *nrtargetlist);
 static Query *transformReturnStmt(ParseState *pstate, ReturnStmt *stmt);
 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
 static Query *transformPLAssignStmt(ParseState *pstate,
 									PLAssignStmt *stmt);
 static List *transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
-										 SelectStmtPassthrough *passthru);
+										 const SelectStmtPassthrough *passthru);
 static Query *transformDeclareCursorStmt(ParseState *pstate,
 										 DeclareCursorStmt *stmt);
 static Query *transformExplainStmt(ParseState *pstate,
@@ -2403,7 +2404,8 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
  * to set up the parent CTE's columns
  */
 static void
-determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
+determineRecursiveColTypes(ParseState *pstate, Node *larg,
+						   const List *nrtargetlist)
 {
 	Node	   *node;
 	int			leftmostRTI;
@@ -2867,7 +2869,7 @@ transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
  */
 static List *
 transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
-							SelectStmtPassthrough *passthru)
+							const SelectStmtPassthrough *passthru)
 {
 	PLAssignStmt *stmt = passthru->stmt;
 	Node	   *target = passthru->target;
diff --git a/src/backend/parser/parse_collate.c b/src/backend/parser/parse_collate.c
index d2e218353f3..ae98ccf7c9a 100644
--- a/src/backend/parser/parse_collate.c
+++ b/src/backend/parser/parse_collate.c
@@ -81,7 +81,7 @@ static void merge_collation_state(Oid collation,
 								  Oid collation2,
 								  int location2,
 								  assign_collations_context *context);
-static void assign_aggregate_collations(Aggref *aggref,
+static void assign_aggregate_collations(const Aggref *aggref,
 										assign_collations_context *loccontext);
 static void assign_ordered_set_collations(Aggref *aggref,
 										  assign_collations_context *loccontext);
@@ -878,7 +878,7 @@ merge_collation_state(Oid collation,
  * contain only SortGroupClause nodes which we need not process.
  */
 static void
-assign_aggregate_collations(Aggref *aggref,
+assign_aggregate_collations(const Aggref *aggref,
 							assign_collations_context *loccontext)
 {
 	ListCell   *lc;
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 4524e49c326..e01bc282149 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -57,13 +57,13 @@ static Node *transformMergeSupportFunc(ParseState *pstate, MergeSupportFunc *f);
 static Node *transformBoolExpr(ParseState *pstate, BoolExpr *a);
 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
 static Node *transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref);
-static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
+static Node *transformCaseExpr(ParseState *pstate, const CaseExpr *c);
 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
 								Oid array_type, Oid element_type, int32 typmod);
 static Node *transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault);
-static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
-static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
+static Node *transformCoalesceExpr(ParseState *pstate, const CoalesceExpr *c);
+static Node *transformMinMaxExpr(ParseState *pstate, const MinMaxExpr *m);
 static Node *transformSQLValueFunction(ParseState *pstate,
 									   SQLValueFunction *svf);
 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
@@ -92,9 +92,11 @@ static Node *transformJsonSerializeExpr(ParseState *pstate,
 										JsonSerializeExpr *expr);
 static Node *transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func);
 static void transformJsonPassingArgs(ParseState *pstate, const char *constructName,
-									 JsonFormatType format, List *args,
+									 JsonFormatType format,
+									 const List *args,
 									 List **passing_values, List **passing_names);
-static JsonBehavior *transformJsonBehavior(ParseState *pstate, JsonExpr *jsexpr,
+static JsonBehavior *transformJsonBehavior(ParseState *pstate,
+										   const JsonExpr *jsexpr,
 										   JsonBehavior *behavior,
 										   JsonBehaviorType default_behavior,
 										   JsonReturning *returning);
@@ -102,11 +104,14 @@ static Node *GetJsonBehaviorConst(JsonBehaviorType btype, int location);
 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
 									List *largs, List *rargs, int location);
 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
-								  RowExpr *lrow, RowExpr *rrow, int location);
+								  const RowExpr *lrow,
+								  const RowExpr *rrow,
+								  int location);
 static Expr *make_distinct_op(ParseState *pstate, List *opname,
 							  Node *ltree, Node *rtree, int location);
 static Node *make_nulltest_from_distinct(ParseState *pstate,
-										 A_Expr *distincta, Node *arg);
+										 const A_Expr *distincta,
+										 Node *arg);
 
 
 /*
@@ -1630,7 +1635,7 @@ transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref)
 }
 
 static Node *
-transformCaseExpr(ParseState *pstate, CaseExpr *c)
+transformCaseExpr(ParseState *pstate, const CaseExpr *c)
 {
 	CaseExpr   *newc = makeNode(CaseExpr);
 	Node	   *last_srf = pstate->p_last_srf;
@@ -2214,7 +2219,7 @@ transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault)
 }
 
 static Node *
-transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
+transformCoalesceExpr(ParseState *pstate, const CoalesceExpr *c)
 {
 	CoalesceExpr *newc = makeNode(CoalesceExpr);
 	Node	   *last_srf = pstate->p_last_srf;
@@ -2263,7 +2268,7 @@ transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
 }
 
 static Node *
-transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
+transformMinMaxExpr(ParseState *pstate, const MinMaxExpr *m)
 {
 	MinMaxExpr *newm = makeNode(MinMaxExpr);
 	List	   *newargs = NIL;
@@ -3029,7 +3034,8 @@ make_row_comparison_op(ParseState *pstate, List *opname,
  */
 static Node *
 make_row_distinct_op(ParseState *pstate, List *opname,
-					 RowExpr *lrow, RowExpr *rrow,
+					 const RowExpr *lrow,
+					 const RowExpr *rrow,
 					 int location)
 {
 	Node	   *result = NULL;
@@ -3107,7 +3113,8 @@ make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
  * "arg" is the untransformed other argument
  */
 static Node *
-make_nulltest_from_distinct(ParseState *pstate, A_Expr *distincta, Node *arg)
+make_nulltest_from_distinct(ParseState *pstate, const A_Expr *distincta,
+							Node *arg)
 {
 	NullTest   *nt = makeNode(NullTest);
 
@@ -3237,7 +3244,7 @@ ParseExprKindName(ParseExprKind exprKind)
  * UTF8 is default encoding.
  */
 static Const *
-getJsonEncodingConst(JsonFormat *format)
+getJsonEncodingConst(const JsonFormat *format)
 {
 	JsonEncoding encoding;
 	const char *enc;
@@ -3558,7 +3565,7 @@ transformJsonOutput(ParseState *pstate, const JsonOutput *output,
  */
 static JsonReturning *
 transformJsonConstructorOutput(ParseState *pstate, JsonOutput *output,
-							   List *args)
+							   const List *args)
 {
 	JsonReturning *returning = transformJsonOutput(pstate, output, true);
 
@@ -4672,7 +4679,8 @@ transformJsonFuncExpr(ParseState *pstate, JsonFuncExpr *func)
  */
 static void
 transformJsonPassingArgs(ParseState *pstate, const char *constructName,
-						 JsonFormatType format, List *args,
+						 JsonFormatType format,
+						 const List *args,
 						 List **passing_values, List **passing_names)
 {
 	ListCell   *lc;
@@ -4730,7 +4738,7 @@ ValidJsonBehaviorDefaultExpr(Node *expr, void *context)
  * Transform a JSON BEHAVIOR clause.
  */
 static JsonBehavior *
-transformJsonBehavior(ParseState *pstate, JsonExpr *jsexpr,
+transformJsonBehavior(ParseState *pstate, const JsonExpr *jsexpr,
 					  JsonBehavior *behavior,
 					  JsonBehaviorType default_behavior,
 					  JsonReturning *returning)
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 778d69c6f3c..88aabbe3400 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -42,11 +42,13 @@ typedef enum
 	FUNCLOOKUP_AMBIGUOUS,
 } FuncLookupError;
 
-static int	func_lookup_failure_details(int fgc_flags, List *argnames,
+static int	func_lookup_failure_details(int fgc_flags,
+										const List *argnames,
 										bool proc_call);
 static void unify_hypothetical_args(ParseState *pstate,
 									List *fargs, int numAggregatedArgs,
-									Oid *actual_arg_types, Oid *declared_arg_types);
+									Oid *actual_arg_types,
+									const Oid *declared_arg_types);
 static Oid	FuncNameAsType(List *funcname);
 static Node *ParseComplexProjection(ParseState *pstate, const char *funcname,
 									Node *first_arg, int location);
@@ -927,7 +929,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
  * function-not-found error.
  */
 static int
-func_lookup_failure_details(int fgc_flags, List *argnames, bool proc_call)
+func_lookup_failure_details(int fgc_flags, const List *argnames,
+							bool proc_call)
 {
 	/*
 	 * If not FGC_NAME_VISIBLE, we shouldn't raise the question of whether the
@@ -1865,7 +1868,7 @@ unify_hypothetical_args(ParseState *pstate,
 						List *fargs,
 						int numAggregatedArgs,
 						Oid *actual_arg_types,
-						Oid *declared_arg_types)
+						const Oid *declared_arg_types)
 {
 	int			numDirectArgs,
 				numNonHypotheticalArgs;
diff --git a/src/backend/parser/parse_merge.c b/src/backend/parser/parse_merge.c
index 51d7703eff7..eb69eb1d30b 100644
--- a/src/backend/parser/parse_merge.c
+++ b/src/backend/parser/parse_merge.c
@@ -29,10 +29,11 @@
 #include "utils/rel.h"
 
 static void setNamespaceForMergeWhen(ParseState *pstate,
-									 MergeWhenClause *mergeWhenClause,
+									 const MergeWhenClause *mergeWhenClause,
 									 Index targetRTI,
 									 Index sourceRTI);
-static void setNamespaceVisibilityForRTE(List *namespace, RangeTblEntry *rte,
+static void setNamespaceVisibilityForRTE(const List *namespace,
+										 const RangeTblEntry *rte,
 										 bool rel_visible,
 										 bool cols_visible);
 
@@ -49,7 +50,8 @@ static void setNamespaceVisibilityForRTE(List *namespace, RangeTblEntry *rte,
  * that columns can be referenced unqualified from these relations.
  */
 static void
-setNamespaceForMergeWhen(ParseState *pstate, MergeWhenClause *mergeWhenClause,
+setNamespaceForMergeWhen(ParseState *pstate,
+						 const MergeWhenClause *mergeWhenClause,
 						 Index targetRTI, Index sourceRTI)
 {
 	RangeTblEntry *targetRelRTE,
@@ -412,7 +414,7 @@ transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
 }
 
 static void
-setNamespaceVisibilityForRTE(List *namespace, RangeTblEntry *rte,
+setNamespaceVisibilityForRTE(const List *namespace, const RangeTblEntry *rte,
 							 bool rel_visible,
 							 bool cols_visible)
 {
diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c
index d544a69fc80..73bdc041a1a 100644
--- a/src/backend/parser/parse_relation.c
+++ b/src/backend/parser/parse_relation.c
@@ -77,10 +77,11 @@ static ParseNamespaceItem *scanNameSpaceForRefname(ParseState *pstate,
 												   int location);
 static ParseNamespaceItem *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
 												 int location);
-static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
+static void check_lateral_ref_ok(ParseState *pstate,
+								 const ParseNamespaceItem *nsitem,
 								 int location);
 static int	scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
-							 Alias *eref,
+							 const Alias *eref,
 							 const char *colname, int location,
 							 int fuzzy_rte_penalty,
 							 FuzzyAttrMatchState *fuzzystate);
@@ -314,7 +315,7 @@ scanNameSpaceForCTE(ParseState *pstate, const char *refname,
  * SQL semantics, but it's important for error reporting purposes.
  */
 static bool
-isFutureCTE(ParseState *pstate, const char *refname)
+isFutureCTE(const ParseState *pstate, const char *refname)
 {
 	for (; pstate != NULL; pstate = pstate->parentParseState)
 	{
@@ -484,7 +485,7 @@ checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
  * Convenience subroutine to avoid multiple copies of a rather ugly ereport.
  */
 static void
-check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
+check_lateral_ref_ok(ParseState *pstate, const ParseNamespaceItem *nsitem,
 					 int location)
 {
 	if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
@@ -809,7 +810,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem,
  */
 static int
 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
-				 Alias *eref,
+				 const Alias *eref,
 				 const char *colname, int location,
 				 int fuzzy_rte_penalty,
 				 FuzzyAttrMatchState *fuzzystate)
@@ -1263,7 +1264,8 @@ buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
  */
 static char *
 chooseScalarFunctionAlias(Node *funcexpr, char *funcname,
-						  Alias *alias, int nfuncs)
+						  const Alias *alias,
+						  int nfuncs)
 {
 	char	   *pname;
 
@@ -3857,7 +3859,7 @@ errorMissingColumn(ParseState *pstate,
  * We assume an RTE couldn't appear more than once in the namespace lists.
  */
 static ParseNamespaceItem *
-findNSItemForRTE(ParseState *pstate, RangeTblEntry *rte)
+findNSItemForRTE(const ParseState *pstate, const RangeTblEntry *rte)
 {
 	while (pstate != NULL)
 	{
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index e96b38a59d5..4c2ac766df5 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -128,16 +128,17 @@ static IndexStmt *transformIndexConstraint(Constraint *constraint,
 static void transformFKConstraints(CreateStmtContext *cxt,
 								   bool skipValidation,
 								   bool isAddConstraint);
-static void transformCheckConstraints(CreateStmtContext *cxt,
+static void transformCheckConstraints(const CreateStmtContext *cxt,
 									  bool skipValidation);
 static void transformConstraintAttrs(CreateStmtContext *cxt,
-									 List *constraintList);
+									 const List *constraintList);
 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
 static void setSchemaName(const char *context_schema, char **stmt_schema_name);
 static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd);
-static List *transformPartitionRangeBounds(ParseState *pstate, List *blist,
+static List *transformPartitionRangeBounds(ParseState *pstate,
+										   const List *blist,
 										   Relation parent);
-static void validateInfiniteBounds(ParseState *pstate, List *blist);
+static void validateInfiniteBounds(ParseState *pstate, const List *blist);
 static Const *transformPartitionBoundValue(ParseState *pstate, Node *val,
 										   const char *colName, Oid colType, int32 colTypmod,
 										   Oid partCollation);
@@ -2942,7 +2943,7 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
  * don't do anything if we're not authorized to skip validation.
  */
 static void
-transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
+transformCheckConstraints(const CreateStmtContext *cxt, bool skipValidation)
 {
 	ListCell   *ckclist;
 
@@ -3887,7 +3888,7 @@ transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
  * supported for other constraint types.
  */
 static void
-transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
+transformConstraintAttrs(CreateStmtContext *cxt, const List *constraintList)
 {
 	Constraint *lastprimarycon = NULL;
 	bool		saw_deferrability = false;
@@ -4429,7 +4430,7 @@ transformPartitionBound(ParseState *pstate, Relation parent,
  *		grammar representation to PartitionRangeDatum structs
  */
 static List *
-transformPartitionRangeBounds(ParseState *pstate, List *blist,
+transformPartitionRangeBounds(ParseState *pstate, const List *blist,
 							  Relation parent)
 {
 	List	   *result = NIL;
@@ -4546,7 +4547,7 @@ transformPartitionRangeBounds(ParseState *pstate, List *blist,
  * followed only by more of the same.
  */
 static void
-validateInfiniteBounds(ParseState *pstate, List *blist)
+validateInfiniteBounds(ParseState *pstate, const List *blist)
 {
 	ListCell   *lc;
 	PartitionRangeDatumKind kind = PARTITION_RANGE_DATUM_VALUE;
diff --git a/src/backend/partitioning/partbounds.c b/src/backend/partitioning/partbounds.c
index 8ba038c5ef4..5a7dd785158 100644
--- a/src/backend/partitioning/partbounds.c
+++ b/src/backend/partitioning/partbounds.c
@@ -103,7 +103,7 @@ static PartitionBoundInfo create_list_bounds(PartitionBoundSpec **boundspecs,
 static PartitionBoundInfo create_range_bounds(PartitionBoundSpec **boundspecs,
 											  int nparts, PartitionKey key, int **mapping);
 static PartitionBoundInfo merge_list_bounds(FmgrInfo *partsupfunc,
-											Oid *partcollation,
+											const Oid *partcollation,
 											RelOptInfo *outer_rel,
 											RelOptInfo *inner_rel,
 											JoinType jointype,
@@ -117,9 +117,9 @@ static PartitionBoundInfo merge_range_bounds(int partnatts,
 											 JoinType jointype,
 											 List **outer_parts,
 											 List **inner_parts);
-static void init_partition_map(RelOptInfo *rel, PartitionMap *map);
+static void init_partition_map(const RelOptInfo *rel, PartitionMap *map);
 static void free_partition_map(PartitionMap *map);
-static bool is_dummy_partition(RelOptInfo *rel, int part_index);
+static bool is_dummy_partition(const RelOptInfo *rel, int part_index);
 static int	merge_matching_partitions(PartitionMap *outer_map,
 									  PartitionMap *inner_map,
 									  int outer_index,
@@ -163,13 +163,14 @@ static void merge_default_partitions(PartitionMap *outer_map,
 									 int *default_index);
 static int	merge_partition_with_dummy(PartitionMap *map, int index,
 									   int *next_index);
-static void fix_merged_indexes(PartitionMap *outer_map,
-							   PartitionMap *inner_map,
-							   int nmerged, List *merged_indexes);
-static void generate_matching_part_pairs(RelOptInfo *outer_rel,
-										 RelOptInfo *inner_rel,
-										 PartitionMap *outer_map,
-										 PartitionMap *inner_map,
+static void fix_merged_indexes(const PartitionMap *outer_map,
+							   const PartitionMap *inner_map,
+							   int nmerged,
+							   const List *merged_indexes);
+static void generate_matching_part_pairs(const RelOptInfo *outer_rel,
+										 const RelOptInfo *inner_rel,
+										 const PartitionMap *outer_map,
+										 const PartitionMap *inner_map,
 										 int nmerged,
 										 List **outer_parts,
 										 List **inner_parts);
@@ -213,13 +214,16 @@ static void add_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
 									List **merged_kinds,
 									List **merged_indexes);
 static PartitionRangeBound *make_one_partition_rbound(PartitionKey key, int index,
-													  List *datums, bool lower);
+													  const List *datums,
+													  bool lower);
 static int32 partition_hbound_cmp(int modulus1, int remainder1, int modulus2,
 								  int remainder2);
 static int32 partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc,
-								  Oid *partcollation, Datum *datums1,
-								  PartitionRangeDatumKind *kind1, bool lower1,
-								  PartitionRangeBound *b2);
+								  const Oid *partcollation,
+								  const Datum *datums1,
+								  const PartitionRangeDatumKind *kind1,
+								  bool lower1,
+								  const PartitionRangeBound *b2);
 static int	partition_range_bsearch(int partnatts, FmgrInfo *partsupfunc,
 									Oid *partcollation,
 									PartitionBoundInfo boundinfo,
@@ -229,7 +233,8 @@ static Expr *make_partition_op_expr(PartitionKey key, int keynum,
 static Oid	get_partition_operator(PartitionKey key, int col,
 								   StrategyNumber strategy, bool *need_relabel);
 static List *get_qual_for_hash(Relation parent, PartitionBoundSpec *spec);
-static List *get_qual_for_list(Relation parent, PartitionBoundSpec *spec);
+static List *get_qual_for_list(Relation parent,
+							   const PartitionBoundSpec *spec);
 static List *get_qual_for_range(Relation parent, PartitionBoundSpec *spec,
 								bool for_default);
 static void get_range_key_properties(PartitionKey key, int keynum,
@@ -1196,7 +1201,7 @@ partition_bounds_merge(int partnatts,
  * join can't handle.
  */
 static PartitionBoundInfo
-merge_list_bounds(FmgrInfo *partsupfunc, Oid *partcollation,
+merge_list_bounds(FmgrInfo *partsupfunc, const Oid *partcollation,
 				  RelOptInfo *outer_rel, RelOptInfo *inner_rel,
 				  JoinType jointype,
 				  List **outer_parts, List **inner_parts)
@@ -1809,7 +1814,7 @@ cleanup:
  *		Initialize a PartitionMap struct for given relation
  */
 static void
-init_partition_map(RelOptInfo *rel, PartitionMap *map)
+init_partition_map(const RelOptInfo *rel, PartitionMap *map)
 {
 	int			nparts = rel->nparts;
 	int			i;
@@ -1841,7 +1846,7 @@ free_partition_map(PartitionMap *map)
  * is_dummy_partition --- has partition been proven empty?
  */
 static bool
-is_dummy_partition(RelOptInfo *rel, int part_index)
+is_dummy_partition(const RelOptInfo *rel, int part_index)
 {
 	RelOptInfo *part_rel;
 
@@ -2383,8 +2388,9 @@ merge_partition_with_dummy(PartitionMap *map, int index, int *next_index)
  *		Adjust merged indexes of re-merged partitions
  */
 static void
-fix_merged_indexes(PartitionMap *outer_map, PartitionMap *inner_map,
-				   int nmerged, List *merged_indexes)
+fix_merged_indexes(const PartitionMap *outer_map,
+				   const PartitionMap *inner_map,
+				   int nmerged, const List *merged_indexes)
 {
 	int		   *new_indexes;
 	int			merged_index;
@@ -2437,8 +2443,10 @@ fix_merged_indexes(PartitionMap *outer_map, PartitionMap *inner_map,
  * and returned in *outer_parts and *inner_parts.
  */
 static void
-generate_matching_part_pairs(RelOptInfo *outer_rel, RelOptInfo *inner_rel,
-							 PartitionMap *outer_map, PartitionMap *inner_map,
+generate_matching_part_pairs(const RelOptInfo *outer_rel,
+							 const RelOptInfo *inner_rel,
+							 const PartitionMap *outer_map,
+							 const PartitionMap *inner_map,
 							 int nmerged,
 							 List **outer_parts, List **inner_parts)
 {
@@ -3426,7 +3434,8 @@ get_hash_partition_greatest_modulus(PartitionBoundInfo bound)
  * because there are multiple sites that want to use this facility.
  */
 static PartitionRangeBound *
-make_one_partition_rbound(PartitionKey key, int index, List *datums, bool lower)
+make_one_partition_rbound(PartitionKey key, int index, const List *datums,
+						  bool lower)
 {
 	PartitionRangeBound *bound;
 	ListCell   *lc;
@@ -3487,9 +3496,11 @@ make_one_partition_rbound(PartitionKey key, int index, List *datums, bool lower)
  */
 static int32
 partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc,
-					 Oid *partcollation,
-					 Datum *datums1, PartitionRangeDatumKind *kind1,
-					 bool lower1, PartitionRangeBound *b2)
+					 const Oid *partcollation,
+					 const Datum *datums1,
+					 const PartitionRangeDatumKind *kind1,
+					 bool lower1,
+					 const PartitionRangeBound *b2)
 {
 	int32		colnum = 0;
 	int32		cmpval = 0;		/* placate compiler */
@@ -4064,7 +4075,7 @@ get_qual_for_hash(Relation parent, PartitionBoundSpec *spec)
  * partition since in that case there is no constraint.
  */
 static List *
-get_qual_for_list(Relation parent, PartitionBoundSpec *spec)
+get_qual_for_list(Relation parent, const PartitionBoundSpec *spec)
 {
 	PartitionKey key = RelationGetPartitionKey(parent);
 	List	   *result;
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index f4830f896f3..f9030259126 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -349,7 +349,7 @@ static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts,
 											  bool *dovacuum, bool *doanalyze, bool *wraparound);
 static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts,
 									  Form_pg_class classForm,
-									  PgStat_StatTabEntry *tabentry,
+									  const PgStat_StatTabEntry *tabentry,
 									  int effective_multixact_freeze_max_age,
 									  bool *dovacuum, bool *doanalyze, bool *wraparound);
 
@@ -2998,7 +2998,7 @@ static void
 relation_needs_vacanalyze(Oid relid,
 						  AutoVacOpts *relopts,
 						  Form_pg_class classForm,
-						  PgStat_StatTabEntry *tabentry,
+						  const PgStat_StatTabEntry *tabentry,
 						  int effective_multixact_freeze_max_age,
  /* output params below */
 						  bool *dovacuum,
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index a956db4ad27..a0554ce3eeb 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -154,7 +154,7 @@ btmask(BackendType t)
 }
 
 static inline BackendTypeMask
-btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
+btmask_add_n(BackendTypeMask mask, int nargs, const BackendType *t)
 {
 	for (int i = 0; i < nargs; i++)
 		mask.mask |= 1 << t[i];
@@ -175,7 +175,7 @@ btmask_del(BackendTypeMask mask, BackendType t)
 }
 
 static inline BackendTypeMask
-btmask_all_except_n(int nargs, BackendType *t)
+btmask_all_except_n(int nargs, const BackendType *t)
 {
 	BackendTypeMask mask = BTYPE_MASK_ALL;
 
diff --git a/src/backend/regex/regprefix.c b/src/backend/regex/regprefix.c
index 8c07e963b89..ef9ee076809 100644
--- a/src/backend/regex/regprefix.c
+++ b/src/backend/regex/regprefix.c
@@ -19,7 +19,7 @@
 /*
  * forward declarations
  */
-static int	findprefix(struct cnfa *cnfa, struct colormap *cm,
+static int	findprefix(const struct cnfa *cnfa, struct colormap *cm,
 					   chr *string, size_t *slength);
 
 
@@ -113,7 +113,7 @@ pg_regprefix(regex_t *re,
  * *slength (which must be preset to zero) incremented for each chr.
  */
 static int						/* regprefix return code */
-findprefix(struct cnfa *cnfa,
+findprefix(const struct cnfa *cnfa,
 		   struct colormap *cm,
 		   chr *string,
 		   size_t *slength)
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index 239641bfbb6..34cd7fc8547 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -114,7 +114,7 @@ static WalReceiverFunctionsType PQWalReceiverFunctions = {
 };
 
 /* Prototypes for private functions */
-static char *stringlist_to_identifierstr(PGconn *conn, List *strings);
+static char *stringlist_to_identifierstr(PGconn *conn, const List *strings);
 
 /*
  * Module initialization function
@@ -1180,7 +1180,7 @@ libpqrcv_exec(WalReceiverConn *conn, const char *query,
  * The caller should free the result.
  */
 static char *
-stringlist_to_identifierstr(PGconn *conn, List *strings)
+stringlist_to_identifierstr(PGconn *conn, const List *strings)
 {
 	ListCell   *lc;
 	StringInfoData res;
diff --git a/src/backend/replication/logical/launcher.c b/src/backend/replication/logical/launcher.c
index fdf1ccad462..eb572e20876 100644
--- a/src/backend/replication/logical/launcher.c
+++ b/src/backend/replication/logical/launcher.c
@@ -566,7 +566,7 @@ retry:
  * slot.
  */
 static void
-logicalrep_worker_stop_internal(LogicalRepWorker *worker, int signo)
+logicalrep_worker_stop_internal(const LogicalRepWorker *worker, int signo)
 {
 	uint16		generation;
 
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 10b3d0d9b82..efcde1e36e8 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -54,7 +54,8 @@ typedef struct LogicalRepPartMapEntry
 	LogicalRepRelMapEntry relmapentry;
 } LogicalRepPartMapEntry;
 
-static Oid	FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
+static Oid	FindLogicalRepLocalIndex(Relation localrel,
+									 const LogicalRepRelation *remoterel,
 									 AttrMap *attrMap);
 
 /*
@@ -217,7 +218,8 @@ logicalrep_relmap_update(LogicalRepRelation *remoterel)
  * Returns -1 if not found.
  */
 static int
-logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
+logicalrep_rel_att_by_name(const LogicalRepRelation *remoterel,
+						   const char *attname)
 {
 	int			i;
 
@@ -235,7 +237,7 @@ logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
  * relation and bitmap indicating which attributes to include.
  */
 static char *
-logicalrep_get_attrs_str(LogicalRepRelation *remoterel, Bitmapset *atts)
+logicalrep_get_attrs_str(const LogicalRepRelation *remoterel, Bitmapset *atts)
 {
 	StringInfoData attsbuf;
 	int			attcnt = 0;
@@ -918,7 +920,8 @@ GetRelationIdentityOrPK(Relation rel)
  * returns InvalidOid.
  */
 static Oid
-FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
+FindLogicalRepLocalIndex(Relation localrel,
+						 const LogicalRepRelation *remoterel,
 						 AttrMap *attrMap)
 {
 	Oid			idxoid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index eb6a84554b7..1174c867b65 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -289,7 +289,7 @@ static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
  * Streaming support functions
  * ---------------------------------------
  */
-static inline bool ReorderBufferCanStream(ReorderBuffer *rb);
+static inline bool ReorderBufferCanStream(const ReorderBuffer *rb);
 static inline bool ReorderBufferCanStartStreaming(ReorderBuffer *rb);
 static void ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
 static void ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn);
@@ -298,7 +298,8 @@ static void ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn);
  * toast reassembly support
  * ---------------------------------------
  */
-static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
+static void ReorderBufferToastInitHash(const ReorderBuffer *rb,
+									   ReorderBufferTXN *txn);
 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
 									  Relation relation, ReorderBufferChange *change);
@@ -310,9 +311,9 @@ static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *t
  * memory accounting
  * ---------------------------------------
  */
-static Size ReorderBufferChangeSize(ReorderBufferChange *change);
+static Size ReorderBufferChangeSize(const ReorderBufferChange *change);
 static void ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
-											ReorderBufferChange *change,
+											const ReorderBufferChange *change,
 											ReorderBufferTXN *txn,
 											bool addition, Size sz);
 
@@ -1833,7 +1834,7 @@ ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn
  * HeapTupleSatisfiesHistoricMVCC.
  */
 static void
-ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
+ReorderBufferBuildTupleCidHash(const ReorderBuffer *rb, ReorderBufferTXN *txn)
 {
 	dlist_iter	iter;
 	HASHCTL		hash_ctl;
@@ -3383,7 +3384,7 @@ ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
  */
 static void
 ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
-								ReorderBufferChange *change,
+								const ReorderBufferChange *change,
 								ReorderBufferTXN *txn,
 								bool addition, Size sz)
 {
@@ -4307,7 +4308,7 @@ ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
 
 /* Returns true, if the output plugin supports streaming, false, otherwise. */
 static inline bool
-ReorderBufferCanStream(ReorderBuffer *rb)
+ReorderBufferCanStream(const ReorderBuffer *rb)
 {
 	LogicalDecodingContext *ctx = rb->private_data;
 
@@ -4459,7 +4460,7 @@ ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
  * Size of a change in memory.
  */
 static Size
-ReorderBufferChangeSize(ReorderBufferChange *change)
+ReorderBufferChangeSize(const ReorderBufferChange *change)
 {
 	Size		sz = sizeof(ReorderBufferChange);
 
@@ -4975,7 +4976,7 @@ StartupReorderBuffer(void)
  * Initialize per tuple toast reconstruction support.
  */
 static void
-ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
+ReorderBufferToastInitHash(const ReorderBuffer *rb, ReorderBufferTXN *txn)
 {
 	HASHCTL		hash_ctl;
 
diff --git a/src/backend/replication/logical/sequencesync.c b/src/backend/replication/logical/sequencesync.c
index 019e5ec6a7d..476af7aa3ff 100644
--- a/src/backend/replication/logical/sequencesync.c
+++ b/src/backend/replication/logical/sequencesync.c
@@ -143,7 +143,7 @@ ProcessSequencesForSync(void)
  * for the given list of sequence indexes.
  */
 static void
-get_sequences_string(List *seqindexes, StringInfo buf)
+get_sequences_string(const List *seqindexes, StringInfo buf)
 {
 	resetStringInfo(buf);
 	foreach_int(seqidx, seqindexes)
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index 7e3b4c4413e..182e9850999 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -419,7 +419,8 @@ get_local_synced_slots(void)
  * otherwise true.
  */
 static bool
-local_sync_slot_required(ReplicationSlot *local_slot, List *remote_slots)
+local_sync_slot_required(ReplicationSlot *local_slot,
+						 const List *remote_slots)
 {
 	bool		remote_exists = false;
 	bool		locally_invalidated = false;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 6e18baa33cb..d4e96c9691b 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -168,7 +168,8 @@ static inline bool SnapBuildXidHasCatalogChanges(SnapBuild *builder, Transaction
 
 /* xlog reading helper functions for SnapBuildProcessRunningXacts */
 static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running);
-static void SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff);
+static void SnapBuildWaitSnapshot(const xl_running_xacts *running,
+								  TransactionId cutoff);
 
 /* serialization functions */
 static void SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn);
@@ -1432,7 +1433,7 @@ SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *runn
  * ---
  */
 static void
-SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff)
+SnapBuildWaitSnapshot(const xl_running_xacts *running, TransactionId cutoff)
 {
 	int			off;
 
diff --git a/src/backend/replication/logical/tablesync.c b/src/backend/replication/logical/tablesync.c
index 6bb0cbeedad..4098aa10d9c 100644
--- a/src/backend/replication/logical/tablesync.c
+++ b/src/backend/replication/logical/tablesync.c
@@ -623,7 +623,7 @@ ProcessSyncingTablesForApply(XLogRecPtr current_lsn)
  * Create list of columns for COPY based on logical relation mapping.
  */
 static List *
-make_copy_attnamelist(LogicalRepRelMapEntry *rel)
+make_copy_attnamelist(const LogicalRepRelMapEntry *rel)
 {
 	List	   *attnamelist = NIL;
 	int			i;
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index a46f8e0644b..042749f4a41 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -587,7 +587,7 @@ static void adjust_xid_advance_interval(RetainDeadTuplesData *rdt_data,
 static void apply_worker_exit(void);
 
 static void apply_handle_commit_internal(LogicalRepCommitData *commit_data);
-static void apply_handle_insert_internal(ApplyExecutionData *edata,
+static void apply_handle_insert_internal(const ApplyExecutionData *edata,
 										 ResultRelInfo *relinfo,
 										 TupleTableSlot *remoteslot);
 static void apply_handle_update_internal(ApplyExecutionData *edata,
@@ -599,8 +599,9 @@ static void apply_handle_delete_internal(ApplyExecutionData *edata,
 										 ResultRelInfo *relinfo,
 										 TupleTableSlot *remoteslot,
 										 Oid localindexoid);
-static bool FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
-									LogicalRepRelation *remoterel,
+static bool FindReplTupleInLocalRel(const ApplyExecutionData *edata,
+									Relation localrel,
+									const LogicalRepRelation *remoterel,
 									Oid localidxoid,
 									TupleTableSlot *remoteslot,
 									TupleTableSlot **localslot);
@@ -678,7 +679,7 @@ ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid,
  * while applying this transaction.
  */
 static bool
-should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
+should_apply_changes_for_rel(const LogicalRepRelMapEntry *rel)
 {
 	switch (MyLogicalRepWorker->type)
 	{
@@ -1014,8 +1015,8 @@ slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate,
  * Incoming data can be either text or binary format.
  */
 static void
-slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel,
-				LogicalRepTupleData *tupleData)
+slot_store_data(TupleTableSlot *slot, const LogicalRepRelMapEntry *rel,
+				const LogicalRepTupleData *tupleData)
 {
 	int			natts = slot->tts_tupleDescriptor->natts;
 	int			i;
@@ -1116,8 +1117,8 @@ slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel,
  */
 static void
 slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot,
-				 LogicalRepRelMapEntry *rel,
-				 LogicalRepTupleData *tupleData)
+				 const LogicalRepRelMapEntry *rel,
+				 const LogicalRepTupleData *tupleData)
 {
 	int			natts = slot->tts_tupleDescriptor->natts;
 	int			i;
@@ -2721,7 +2722,7 @@ apply_handle_insert(StringInfo s)
  * (could be a child partition of edata->targetRelInfo)
  */
 static void
-apply_handle_insert_internal(ApplyExecutionData *edata,
+apply_handle_insert_internal(const ApplyExecutionData *edata,
 							 ResultRelInfo *relinfo,
 							 TupleTableSlot *remoteslot)
 {
@@ -3171,8 +3172,8 @@ apply_handle_delete_internal(ApplyExecutionData *edata,
  * Local tuple, if found, is returned in '*localslot'.
  */
 static bool
-FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
-						LogicalRepRelation *remoterel,
+FindReplTupleInLocalRel(const ApplyExecutionData *edata, Relation localrel,
+						const LogicalRepRelation *remoterel,
 						Oid localidxoid,
 						TupleTableSlot *remoteslot,
 						TupleTableSlot **localslot)
diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 942e1abdb58..e73b358f5b8 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -85,7 +85,7 @@ static void pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx,
 
 static bool publications_valid;
 
-static List *LoadPublications(List *pubnames);
+static List *LoadPublications(const List *pubnames);
 static void publication_invalidation_cb(Datum arg, int cacheid,
 										uint32 hashvalue);
 static void send_repl_origin(LogicalDecodingContext *ctx,
@@ -225,7 +225,7 @@ static RelationSyncEntry *get_rel_sync_entry(PGOutputData *data,
 											 Relation relation);
 static void send_relation_and_attrs(Relation relation, TransactionId xid,
 									LogicalDecodingContext *ctx,
-									RelationSyncEntry *relentry);
+									const RelationSyncEntry *relentry);
 static void rel_sync_cache_relation_cb(Datum arg, Oid relid);
 static void rel_sync_cache_publication_cb(Datum arg, int cacheid,
 										  uint32 hashvalue);
@@ -240,7 +240,7 @@ static void pgoutput_memory_context_reset(void *arg);
 /* row filter routines */
 static EState *create_estate_for_relation(Relation rel);
 static void pgoutput_row_filter_init(PGOutputData *data,
-									 List *publications,
+									 const List *publications,
 									 RelationSyncEntry *entry);
 static bool pgoutput_row_filter_exec_expr(ExprState *state,
 										  ExprContext *econtext);
@@ -287,7 +287,7 @@ _PG_output_plugin_init(OutputPluginCallbacks *cb)
 }
 
 static void
-parse_output_parameters(List *options, PGOutputData *data)
+parse_output_parameters(const List *options, PGOutputData *data)
 {
 	ListCell   *lc;
 	bool		protocol_version_given = false;
@@ -793,7 +793,7 @@ maybe_send_schema(LogicalDecodingContext *ctx,
 static void
 send_relation_and_attrs(Relation relation, TransactionId xid,
 						LogicalDecodingContext *ctx,
-						RelationSyncEntry *relentry)
+						const RelationSyncEntry *relentry)
 {
 	TupleDesc	desc = RelationGetDescr(relation);
 	Bitmapset  *columns = relentry->columns;
@@ -911,7 +911,7 @@ pgoutput_ensure_entry_cxt(PGOutputData *data, RelationSyncEntry *entry)
  * Initialize the row filter.
  */
 static void
-pgoutput_row_filter_init(PGOutputData *data, List *publications,
+pgoutput_row_filter_init(PGOutputData *data, const List *publications,
 						 RelationSyncEntry *entry)
 {
 	ListCell   *lc;
@@ -1058,7 +1058,7 @@ pgoutput_row_filter_init(PGOutputData *data, List *publications,
  * values of 'publish_generated_columns' parameter in the publications.
  */
 static void
-check_and_init_gencol(PGOutputData *data, List *publications,
+check_and_init_gencol(PGOutputData *data, const List *publications,
 					  RelationSyncEntry *entry)
 {
 	Relation	relation = RelationIdGetRelation(entry->publish_as_relid);
@@ -1795,7 +1795,7 @@ pgoutput_shutdown(LogicalDecodingContext *ctx)
  * have specified the required publications at the time of replication start.
  */
 static List *
-LoadPublications(List *pubnames)
+LoadPublications(const List *pubnames)
 {
 	List	   *result = NIL;
 	ListCell   *lc;
diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
index 682eccd116c..7e95bff6a0c 100644
--- a/src/backend/replication/slot.c
+++ b/src/backend/replication/slot.c
@@ -1730,7 +1730,7 @@ ReportSlotInvalidation(ReplicationSlotInvalidationCause cause,
  *	  inactive because they don't perform logical decoding to produce changes.
  */
 static inline bool
-CanInvalidateIdleSlot(ReplicationSlot *s)
+CanInvalidateIdleSlot(const ReplicationSlot *s)
 {
 	return (idle_replication_slot_timeout_secs != 0 &&
 			XLogRecPtrIsValid(s->data.restart_lsn) &&
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index a0c79958fd5..a350a740f0a 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -108,12 +108,12 @@ static bool SyncRepGetSyncRecPtr(XLogRecPtr *writePtr,
 static void SyncRepGetOldestSyncRecPtr(XLogRecPtr *writePtr,
 									   XLogRecPtr *flushPtr,
 									   XLogRecPtr *applyPtr,
-									   SyncRepStandbyData *sync_standbys,
+									   const SyncRepStandbyData *sync_standbys,
 									   int num_standbys);
 static void SyncRepGetNthLatestSyncRecPtr(XLogRecPtr *writePtr,
 										  XLogRecPtr *flushPtr,
 										  XLogRecPtr *applyPtr,
-										  SyncRepStandbyData *sync_standbys,
+										  const SyncRepStandbyData *sync_standbys,
 										  int num_standbys,
 										  uint8 nth);
 static int	SyncRepGetStandbyPriority(void);
@@ -660,7 +660,7 @@ static void
 SyncRepGetOldestSyncRecPtr(XLogRecPtr *writePtr,
 						   XLogRecPtr *flushPtr,
 						   XLogRecPtr *applyPtr,
-						   SyncRepStandbyData *sync_standbys,
+						   const SyncRepStandbyData *sync_standbys,
 						   int num_standbys)
 {
 	int			i;
@@ -693,7 +693,7 @@ static void
 SyncRepGetNthLatestSyncRecPtr(XLogRecPtr *writePtr,
 							  XLogRecPtr *flushPtr,
 							  XLogRecPtr *applyPtr,
-							  SyncRepStandbyData *sync_standbys,
+							  const SyncRepStandbyData *sync_standbys,
 							  int num_standbys,
 							  uint8 nth)
 {
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 0564c995500..6ef02ab8c78 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -1115,7 +1115,7 @@ logical_read_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int req
  * Process extra options given to CREATE_REPLICATION_SLOT.
  */
 static void
-parseCreateReplSlotOptions(CreateReplicationSlotCmd *cmd,
+parseCreateReplSlotOptions(const CreateReplicationSlotCmd *cmd,
 						   bool *reserve_wal,
 						   CRSSnapshotAction *snapshot_action,
 						   bool *two_phase, bool *failover)
diff --git a/src/backend/rewrite/rewriteDefine.c b/src/backend/rewrite/rewriteDefine.c
index a96fbdc1ddd..793769b9d60 100644
--- a/src/backend/rewrite/rewriteDefine.c
+++ b/src/backend/rewrite/rewriteDefine.c
@@ -37,7 +37,7 @@
 #include "utils/syscache.h"
 
 
-static void checkRuleResultList(List *targetList, TupleDesc resultDesc,
+static void checkRuleResultList(const List *targetList, TupleDesc resultDesc,
 								bool isSelect, bool requireColumnNameMatch);
 static bool setRuleCheckAsUser_walker(Node *node, Oid *context);
 static void setRuleCheckAsUser_Query(Query *qry, Oid userid);
@@ -503,7 +503,8 @@ DefineQueryRewrite(const char *rulename,
  * A SELECT targetlist may optionally require that column names match.
  */
 static void
-checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect,
+checkRuleResultList(const List *targetList, TupleDesc resultDesc,
+					bool isSelect,
 					bool requireColumnNameMatch)
 {
 	ListCell   *tllist;
diff --git a/src/backend/rewrite/rowsecurity.c b/src/backend/rewrite/rowsecurity.c
index 4dad384d04d..c0ff69011da 100644
--- a/src/backend/rewrite/rowsecurity.c
+++ b/src/backend/rewrite/rowsecurity.c
@@ -58,16 +58,16 @@ static void sort_policies_by_name(List *policies);
 static int	row_security_policy_cmp(const ListCell *a, const ListCell *b);
 
 static void add_security_quals(int rt_index,
-							   List *permissive_policies,
-							   List *restrictive_policies,
+							   const List *permissive_policies,
+							   const List *restrictive_policies,
 							   List **securityQuals,
 							   bool *hasSubLinks);
 
 static void add_with_check_options(Relation rel,
 								   int rt_index,
 								   WCOKind kind,
-								   List *permissive_policies,
-								   List *restrictive_policies,
+								   const List *permissive_policies,
+								   const List *restrictive_policies,
 								   List **withCheckOptions,
 								   bool *hasSubLinks,
 								   bool force_using);
@@ -698,8 +698,8 @@ row_security_policy_cmp(const ListCell *a, const ListCell *b)
  */
 static void
 add_security_quals(int rt_index,
-				   List *permissive_policies,
-				   List *restrictive_policies,
+				   const List *permissive_policies,
+				   const List *restrictive_policies,
 				   List **securityQuals,
 				   bool *hasSubLinks)
 {
@@ -796,8 +796,8 @@ static void
 add_with_check_options(Relation rel,
 					   int rt_index,
 					   WCOKind kind,
-					   List *permissive_policies,
-					   List *restrictive_policies,
+					   const List *permissive_policies,
+					   const List *restrictive_policies,
 					   List **withCheckOptions,
 					   bool *hasSubLinks,
 					   bool force_using)
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index d7bf6b7e846..629b7787f9a 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -64,8 +64,9 @@ static void generate_dependencies(DependencyGenerator state);
 static DependencyGenerator DependencyGenerator_init(int n, int k);
 static void DependencyGenerator_free(DependencyGenerator state);
 static AttrNumber *DependencyGenerator_next(DependencyGenerator state);
-static double dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency);
-static bool dependency_is_fully_matched(MVDependency *dependency,
+static double dependency_degree(StatsBuildData *data, int k,
+								const AttrNumber *dependency);
+static bool dependency_is_fully_matched(const MVDependency *dependency,
 										Bitmapset *attnums);
 static bool dependency_is_compatible_clause(Node *clause, Index relid,
 											AttrNumber *attnum);
@@ -73,12 +74,13 @@ static bool dependency_is_compatible_expression(Node *clause, Index relid,
 												List *statlist, Node **expr);
 static MVDependency *find_strongest_dependency(MVDependencies **dependencies,
 											   int ndependencies, Bitmapset *attnums);
-static Selectivity clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
+static Selectivity clauselist_apply_dependencies(PlannerInfo *root,
+												 const List *clauses,
 												 int varRelid, JoinType jointype,
 												 SpecialJoinInfo *sjinfo,
 												 MVDependency **dependencies,
 												 int ndependencies,
-												 AttrNumber *list_attnums,
+												 const AttrNumber *list_attnums,
 												 Bitmapset **estimatedclauses);
 
 static void
@@ -212,7 +214,7 @@ DependencyGenerator_next(DependencyGenerator state)
  * the last one.
  */
 static double
-dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency)
+dependency_degree(StatsBuildData *data, int k, const AttrNumber *dependency)
 {
 	int			i,
 				nitems;
@@ -586,7 +588,8 @@ statext_dependencies_deserialize(bytea *data)
  *		attributes (assuming the clauses are suitable equality clauses)
  */
 static bool
-dependency_is_fully_matched(MVDependency *dependency, Bitmapset *attnums)
+dependency_is_fully_matched(const MVDependency *dependency,
+							Bitmapset *attnums)
 {
 	int			j;
 
@@ -920,11 +923,11 @@ find_strongest_dependency(MVDependencies **dependencies, int ndependencies,
  * clauses are not consistent with the functional dependency.
  */
 static Selectivity
-clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
+clauselist_apply_dependencies(PlannerInfo *root, const List *clauses,
 							  int varRelid, JoinType jointype,
 							  SpecialJoinInfo *sjinfo,
 							  MVDependency **dependencies, int ndependencies,
-							  AttrNumber *list_attnums,
+							  const AttrNumber *list_attnums,
 							  Bitmapset **estimatedclauses)
 {
 	Bitmapset  *attnums;
diff --git a/src/backend/statistics/mvdistinct.c b/src/backend/statistics/mvdistinct.c
index fe452f53ae4..4a05f6f4010 100644
--- a/src/backend/statistics/mvdistinct.c
+++ b/src/backend/statistics/mvdistinct.c
@@ -32,8 +32,10 @@
 #include "utils/typcache.h"
 #include "varatt.h"
 
-static double ndistinct_for_combination(double totalrows, StatsBuildData *data,
-										int k, int *combination);
+static double ndistinct_for_combination(double totalrows,
+										const StatsBuildData *data,
+										int k,
+										const int *combination);
 static double estimate_ndistinct(double totalrows, int numrows, int d, int f1);
 static int	n_choose_k(int n, int k);
 static int	num_combinations(int n);
@@ -337,8 +339,9 @@ statext_ndistinct_deserialize(bytea *data)
  * combination of multiple columns.
  */
 static double
-ndistinct_for_combination(double totalrows, StatsBuildData *data,
-						  int k, int *combination)
+ndistinct_for_combination(double totalrows, const StatsBuildData *data,
+						  int k,
+						  const int *combination)
 {
 	int			i,
 				j;
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index a12b785ade6..f1112071026 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -55,7 +55,8 @@ static inline void pgaio_io_update_state(PgAioHandle *ioh, PgAioHandleState new_
 static void pgaio_io_reclaim(PgAioHandle *ioh);
 static void pgaio_io_resowner_register(PgAioHandle *ioh);
 static void pgaio_io_wait_for_free(void);
-static PgAioHandle *pgaio_io_from_wref(PgAioWaitRef *iow, uint64 *ref_generation);
+static PgAioHandle *pgaio_io_from_wref(const PgAioWaitRef *iow,
+									   uint64 *ref_generation);
 static const char *pgaio_io_state_get_name(PgAioHandleState s);
 static void pgaio_io_wait(PgAioHandle *ioh, uint64 ref_generation);
 
@@ -888,7 +889,7 @@ pgaio_io_wait_for_free(void)
  * such code to be safe.
  */
 static PgAioHandle *
-pgaio_io_from_wref(PgAioWaitRef *iow, uint64 *ref_generation)
+pgaio_io_from_wref(const PgAioWaitRef *iow, uint64 *ref_generation)
 {
 	PgAioHandle *ioh;
 
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..610598696f7 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -148,7 +148,7 @@ struct ReadStream
  * Return a pointer to the per-buffer data by index.
  */
 static inline void *
-get_per_buffer_data(ReadStream *stream, int16 buffer_index)
+get_per_buffer_data(const ReadStream *stream, int16 buffer_index)
 {
 	return (char *) stream->per_buffer_data +
 		stream->per_buffer_data_size * buffer_index;
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index ce52d6ca81f..c6f543ba271 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -531,7 +531,8 @@ static inline BufferDesc *BufferAlloc(SMgrRelation smgr,
 									  BufferAccessStrategy strategy,
 									  bool *foundPtr, IOContext io_context);
 static bool AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress);
-static void CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete);
+static void CheckReadBuffersOperation(const ReadBuffersOperation *operation,
+									  bool is_complete);
 static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
 static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
 								IOObject io_object, IOContext io_context);
@@ -1505,7 +1506,8 @@ StartReadBuffer(ReadBuffersOperation *operation,
  * Perform sanity checks on the ReadBuffersOperation.
  */
 static void
-CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete)
+CheckReadBuffersOperation(const ReadBuffersOperation *operation,
+						  bool is_complete)
 {
 #ifdef USE_ASSERT_CHECKING
 	Assert(operation->nblocks_done <= operation->nblocks);
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index 200f72c6e25..58639e3265c 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -351,7 +351,7 @@ static bool KnownAssignedXidsSearch(TransactionId xid, bool remove);
 static bool KnownAssignedXidExists(TransactionId xid);
 static void KnownAssignedXidsRemove(TransactionId xid);
 static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids,
-										TransactionId *subxids);
+										const TransactionId *subxids);
 static void KnownAssignedXidsRemovePreceding(TransactionId removeXid);
 static int	KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax);
 static int	KnownAssignedXidsGetAndSetXmin(TransactionId *xarray,
@@ -4973,7 +4973,7 @@ KnownAssignedXidsRemove(TransactionId xid)
  */
 static void
 KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids,
-							TransactionId *subxids)
+							const TransactionId *subxids)
 {
 	int			i;
 
diff --git a/src/backend/storage/ipc/waiteventset.c b/src/backend/storage/ipc/waiteventset.c
index b5431ad3c5c..9970d323b1e 100644
--- a/src/backend/storage/ipc/waiteventset.c
+++ b/src/backend/storage/ipc/waiteventset.c
@@ -198,9 +198,10 @@ static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action
 #elif defined(WAIT_USE_KQUEUE)
 static void WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events);
 #elif defined(WAIT_USE_POLL)
-static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustPoll(const WaitEventSet *set,
+								const WaitEvent *event);
 #elif defined(WAIT_USE_WIN32)
-static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustWin32(const WaitEventSet *set, WaitEvent *event);
 #endif
 
 static inline int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
@@ -787,7 +788,7 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 #if defined(WAIT_USE_POLL)
 static void
-WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustPoll(const WaitEventSet *set, const WaitEvent *event)
 {
 	struct pollfd *pollfd = &set->pollfds[event->pos];
 
@@ -836,7 +837,7 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
 
 static inline void
 WaitEventAdjustKqueueAdd(struct kevent *k_ev, int filter, int action,
-						 WaitEvent *event)
+						 const WaitEvent *event)
 {
 	k_ev->ident = event->fd;
 	k_ev->filter = filter;
@@ -847,7 +848,8 @@ WaitEventAdjustKqueueAdd(struct kevent *k_ev, int filter, int action,
 }
 
 static inline void
-WaitEventAdjustKqueueAddPostmaster(struct kevent *k_ev, WaitEvent *event)
+WaitEventAdjustKqueueAddPostmaster(struct kevent *k_ev,
+								   const WaitEvent *event)
 {
 	/* For now postmaster death can only be added, not removed. */
 	k_ev->ident = PostmasterPid;
@@ -859,7 +861,7 @@ WaitEventAdjustKqueueAddPostmaster(struct kevent *k_ev, WaitEvent *event)
 }
 
 static inline void
-WaitEventAdjustKqueueAddLatch(struct kevent *k_ev, WaitEvent *event)
+WaitEventAdjustKqueueAddLatch(struct kevent *k_ev, const WaitEvent *event)
 {
 	/* For now latch can only be added, not removed. */
 	k_ev->ident = SIGURG;
@@ -980,7 +982,7 @@ WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events)
 
 #if defined(WAIT_USE_WIN32)
 static void
-WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustWin32(const WaitEventSet *set, WaitEvent *event)
 {
 	HANDLE	   *handle = &set->handles[event->pos + 1];
 
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 9cb78ead105..a66a2009677 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -426,7 +426,7 @@ static void CleanUpLock(LOCK *lock, PROCLOCK *proclock,
 static void LockRefindAndRelease(LockMethod lockMethodTable, PGPROC *proc,
 								 LOCKTAG *locktag, LOCKMODE lockmode,
 								 bool decrement_strong_lock_count);
-static void GetSingleProcBlockerStatusData(PGPROC *blocked_proc,
+static void GetSingleProcBlockerStatusData(const PGPROC *blocked_proc,
 										   BlockedProcsData *data);
 
 
@@ -4075,7 +4075,8 @@ GetBlockerStatusData(int blocked_pid)
 
 /* Accumulate data about one possibly-blocked proc for GetBlockerStatusData */
 static void
-GetSingleProcBlockerStatusData(PGPROC *blocked_proc, BlockedProcsData *data)
+GetSingleProcBlockerStatusData(const PGPROC *blocked_proc,
+							   BlockedProcsData *data)
 {
 	LOCK	   *theLock = blocked_proc->waitLock;
 	BlockedProcData *bproc;
diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c
index 255cfa8fa95..2c30bc72e48 100644
--- a/src/backend/storage/lmgr/lwlock.c
+++ b/src/backend/storage/lmgr/lwlock.c
@@ -204,7 +204,7 @@ static int	LocalLWLockCounter;
 #define MAX_NAMED_TRANCHES 256
 
 static void InitializeLWLocks(void);
-static inline void LWLockReportWaitStart(LWLock *lock);
+static inline void LWLockReportWaitStart(const LWLock *lock);
 static inline void LWLockReportWaitEnd(void);
 static const char *GetLWTrancheName(uint16 trancheId);
 
@@ -716,7 +716,7 @@ LWLockInitialize(LWLock *lock, int tranche_id)
  * event based on tranche and lock id.
  */
 static inline void
-LWLockReportWaitStart(LWLock *lock)
+LWLockReportWaitStart(const LWLock *lock)
 {
 	pgstat_report_wait_start(PG_WAIT_LWLOCK | lock->tranche);
 }
diff --git a/src/backend/tcop/fastpath.c b/src/backend/tcop/fastpath.c
index 62f9ffa0dc0..39c8f6ae947 100644
--- a/src/backend/tcop/fastpath.c
+++ b/src/backend/tcop/fastpath.c
@@ -56,7 +56,8 @@ struct fp_info
 };
 
 
-static int16 parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip,
+static int16 parse_fcall_arguments(StringInfo msgBuf,
+								   const struct fp_info *fip,
 								   FunctionCallInfo fcinfo);
 
 /* ----------------
@@ -326,7 +327,7 @@ HandleFunctionRequest(StringInfo msgBuf)
  * is returned.
  */
 static int16
-parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip,
+parse_fcall_arguments(StringInfo msgBuf, const struct fp_info *fip,
 					  FunctionCallInfo fcinfo)
 {
 	int			nargs;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 7dd75a490aa..dc7b66bd030 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -172,8 +172,8 @@ static int	interactive_getc(void);
 static int	SocketBackend(StringInfo inBuf);
 static int	ReadCommand(StringInfo inBuf);
 static void forbidden_in_wal_sender(char firstchar);
-static bool check_log_statement(List *stmt_list);
-static int	errdetail_execute(List *raw_parsetree_list);
+static bool check_log_statement(const List *stmt_list);
+static int	errdetail_execute(const List *raw_parsetree_list);
 static int	errdetail_params(ParamListInfo params);
 static int	errdetail_abort(void);
 static void bind_param_error_callback(void *arg);
@@ -2387,7 +2387,7 @@ exec_execute_message(const char *portal_name, long max_rows)
  * statements
  */
 static bool
-check_log_statement(List *stmt_list)
+check_log_statement(const List *stmt_list)
 {
 	ListCell   *stmt_item;
 
@@ -2489,7 +2489,7 @@ check_log_duration(char *msec_str, bool was_logged)
  * The argument is the raw parsetree list.
  */
 static int
-errdetail_execute(List *raw_parsetree_list)
+errdetail_execute(const List *raw_parsetree_list)
 {
 	ListCell   *parsetree_item;
 
diff --git a/src/backend/tsearch/dict_thesaurus.c b/src/backend/tsearch/dict_thesaurus.c
index 1e6bbde1ca7..aa56ad67721 100644
--- a/src/backend/tsearch/dict_thesaurus.c
+++ b/src/backend/tsearch/dict_thesaurus.c
@@ -69,7 +69,8 @@ typedef struct
 
 
 static void
-newLexeme(DictThesaurus *d, char *b, char *e, uint32 idsubst, uint16 posinsubst)
+newLexeme(DictThesaurus *d, char *b, const char *e, uint32 idsubst,
+		  uint16 posinsubst)
 {
 	TheLexeme  *ptr;
 
@@ -103,7 +104,8 @@ newLexeme(DictThesaurus *d, char *b, char *e, uint32 idsubst, uint16 posinsubst)
 }
 
 static void
-addWrd(DictThesaurus *d, char *b, char *e, uint32 idsubst, uint16 nwrd, uint16 posinsubst, bool useasis)
+addWrd(DictThesaurus *d, char *b, const char *e, uint32 idsubst, uint16 nwrd,
+	   uint16 posinsubst, bool useasis)
 {
 	static int	nres = 0;
 	static int	ntres = 0;
@@ -301,7 +303,8 @@ thesaurusRead(const char *filename, DictThesaurus *d)
 }
 
 static TheLexeme *
-addCompiledLexeme(TheLexeme *newwrds, int *nnw, int *tnm, TSLexeme *lexeme, LexemeInfo *src, uint16 tnvariant)
+addCompiledLexeme(TheLexeme *newwrds, int *nnw, int *tnm, TSLexeme *lexeme,
+				  const LexemeInfo *src, uint16 tnvariant)
 {
 	if (*nnw >= *tnm)
 	{
@@ -332,7 +335,7 @@ addCompiledLexeme(TheLexeme *newwrds, int *nnw, int *tnm, TSLexeme *lexeme, Lexe
 }
 
 static int
-cmpLexemeInfo(LexemeInfo *a, LexemeInfo *b)
+cmpLexemeInfo(const LexemeInfo *a, const LexemeInfo *b)
 {
 	if (a == NULL || b == NULL)
 		return 0;
@@ -674,7 +677,7 @@ findTheLexeme(DictThesaurus *d, char *lexeme)
 }
 
 static bool
-matchIdSubst(LexemeInfo *stored, uint32 idsubst)
+matchIdSubst(const LexemeInfo *stored, uint32 idsubst)
 {
 	bool		res = true;
 
@@ -751,7 +754,7 @@ findVariant(LexemeInfo *in, LexemeInfo *stored, uint16 curpos, LexemeInfo **newi
 }
 
 static TSLexeme *
-copyTSLexeme(TheSubstitute *ts)
+copyTSLexeme(const TheSubstitute *ts)
 {
 	TSLexeme   *res;
 	uint16		i;
@@ -769,7 +772,8 @@ copyTSLexeme(TheSubstitute *ts)
 }
 
 static TSLexeme *
-checkMatch(DictThesaurus *d, LexemeInfo *info, uint16 curpos, bool *moreres)
+checkMatch(const DictThesaurus *d, const LexemeInfo *info, uint16 curpos,
+		   bool *moreres)
 {
 	*moreres = false;
 	while (info)
diff --git a/src/backend/tsearch/ts_parse.c b/src/backend/tsearch/ts_parse.c
index cba421892bf..b249529302a 100644
--- a/src/backend/tsearch/ts_parse.c
+++ b/src/backend/tsearch/ts_parse.c
@@ -139,7 +139,7 @@ setCorrLex(LexizeData *ld, ParsedLex **correspondLexem)
 }
 
 static void
-moveToWaste(LexizeData *ld, ParsedLex *stop)
+moveToWaste(LexizeData *ld, const ParsedLex *stop)
 {
 	bool		go = true;
 
diff --git a/src/backend/tsearch/wparser_def.c b/src/backend/tsearch/wparser_def.c
index 251a2ae6563..eb370f31cf0 100644
--- a/src/backend/tsearch/wparser_def.c
+++ b/src/backend/tsearch/wparser_def.c
@@ -448,7 +448,7 @@ p_isneC(TParser *prs)
 }
 
 static int
-p_isascii(TParser *prs)
+p_isascii(const TParser *prs)
 {
 	return (prs->state->charlen == 1 && isascii((unsigned char) *(prs->str + prs->state->posbyte))) ? 1 : 0;
 }
@@ -1984,7 +1984,7 @@ checkcondition_HL(void *opaque, QueryOperand *val, ExecPhraseData *data)
  * words used in the query.
  */
 static bool
-hlCover(HeadlineParsedText *prs, TSQuery query, List *locations,
+hlCover(const HeadlineParsedText *prs, TSQuery query, const List *locations,
 		int *nextpos, int *p, int *q)
 {
 	int			pos = *nextpos;
@@ -2172,7 +2172,7 @@ mark_fragment(HeadlineParsedText *prs, bool highlightall,
  * interesting words respectively.
  */
 static void
-get_next_fragment(HeadlineParsedText *prs, int *startpos, int *endpos,
+get_next_fragment(const HeadlineParsedText *prs, int *startpos, int *endpos,
 				  int *curlen, int *poslen, int max_words)
 {
 	int			i;
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index 199ba2cc17a..ed61332008a 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -163,7 +163,7 @@ pgstat_fetch_stat_backend_by_pid(int pid, BackendType *bktype)
  * by the caller.
  */
 static void
-pgstat_flush_backend_entry_io(PgStat_EntryRef *entry_ref)
+pgstat_flush_backend_entry_io(const PgStat_EntryRef *entry_ref)
 {
 	PgStatShared_Backend *shbackendent;
 	PgStat_BktypeIO *bktype_shstats;
@@ -223,7 +223,7 @@ pgstat_backend_wal_have_pending(void)
  * by the caller.
  */
 static void
-pgstat_flush_backend_entry_wal(PgStat_EntryRef *entry_ref)
+pgstat_flush_backend_entry_wal(const PgStat_EntryRef *entry_ref)
 {
 	PgStatShared_Backend *shbackendent;
 	PgStat_WalCounters *bktype_shstats;
diff --git a/src/backend/utils/adt/array_userfuncs.c b/src/backend/utils/adt/array_userfuncs.c
index 8eb342e3382..a350dc85eb8 100644
--- a/src/backend/utils/adt/array_userfuncs.c
+++ b/src/backend/utils/adt/array_userfuncs.c
@@ -1611,7 +1611,7 @@ array_positions(PG_FUNCTION_ARGS)
  */
 static ArrayType *
 array_shuffle_n(ArrayType *array, int n, bool keep_lb,
-				Oid elmtyp, TypeCacheEntry *typentry)
+				Oid elmtyp, const TypeCacheEntry *typentry)
 {
 	ArrayType  *result;
 	int			ndim,
@@ -1772,7 +1772,7 @@ array_sample(PG_FUNCTION_ARGS)
  * in a better position to cache this info across multiple calls.
  */
 static ArrayType *
-array_reverse_n(ArrayType *array, Oid elmtyp, TypeCacheEntry *typentry)
+array_reverse_n(ArrayType *array, Oid elmtyp, const TypeCacheEntry *typentry)
 {
 	ArrayType  *result;
 	int			ndim,
diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c
index 24e5b2adea1..438b713c417 100644
--- a/src/backend/utils/adt/arrayfuncs.c
+++ b/src/backend/utils/adt/arrayfuncs.c
@@ -125,7 +125,8 @@ static Datum ArrayCast(char *value, bool byval, int len);
 static int	ArrayCastAndSet(Datum src,
 							int typlen, bool typbyval, char typalign,
 							char *dest);
-static char *array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems,
+static char *array_seek(char *ptr, int offset, const bits8 *nullbitmap,
+						int nitems,
 						int typlen, bool typbyval, char typalign);
 static int	array_nelems_size(char *ptr, int offset, bits8 *nullbitmap,
 							  int nitems, int typlen, bool typbyval, char typalign);
@@ -4864,7 +4865,7 @@ ArrayCastAndSet(Datum src,
  * It is caller's responsibility to ensure that nitems is within range
  */
 static char *
-array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems,
+array_seek(char *ptr, int offset, const bits8 *nullbitmap, int nitems,
 		   int typlen, bool typbyval, char typalign)
 {
 	int			bitmask;
diff --git a/src/backend/utils/adt/ascii.c b/src/backend/utils/adt/ascii.c
index e3654dc7f3f..1b2c06e59b9 100644
--- a/src/backend/utils/adt/ascii.c
+++ b/src/backend/utils/adt/ascii.c
@@ -16,7 +16,7 @@
 #include "utils/fmgrprotos.h"
 #include "varatt.h"
 
-static void pg_to_ascii(unsigned char *src, unsigned char *src_end,
+static void pg_to_ascii(unsigned char *src, const unsigned char *src_end,
 						unsigned char *dest, int enc);
 static text *encode_to_ascii(text *data, int enc);
 
@@ -26,7 +26,8 @@ static text *encode_to_ascii(text *data, int enc);
  * ----------
  */
 static void
-pg_to_ascii(unsigned char *src, unsigned char *src_end, unsigned char *dest, int enc)
+pg_to_ascii(unsigned char *src, const unsigned char *src_end,
+			unsigned char *dest, int enc)
 {
 	unsigned char *x;
 	const unsigned char *ascii;
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..44791f32c91 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -2536,7 +2536,7 @@ timetz_scale(PG_FUNCTION_ARGS)
 
 
 static int
-timetz_cmp_internal(TimeTzADT *time1, TimeTzADT *time2)
+timetz_cmp_internal(const TimeTzADT *time1, const TimeTzADT *time2)
 {
 	TimeOffset	t1,
 				t2;
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index c3cb022a400..920b94af9e1 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -1078,7 +1078,7 @@ static const KeyWord *index_seq_search(const char *str, const KeyWord *kw,
 									   const int *index);
 static const KeySuffix *suff_search(const char *str, const KeySuffix *suf, enum KeySuffixType type);
 static bool is_separator_char(const char *str);
-static void NUMDesc_prepare(NUMDesc *num, FormatNode *n);
+static void NUMDesc_prepare(NUMDesc *num, const FormatNode *n);
 static void parse_format(FormatNode *node, const char *str, const KeyWord *kw,
 						 const KeySuffix *suf, const int *index, uint32 flags, NUMDesc *Num);
 
@@ -1110,7 +1110,8 @@ static int	seq_search_localized(const char *name, char **array, size_t *len,
 static bool from_char_seq_search(int *dest, const char **src,
 								 const char *const *array,
 								 char **localized_array, Oid collid,
-								 FormatNode *node, Node *escontext);
+								 const FormatNode *node,
+								 Node *escontext);
 static bool do_to_timestamp(const text *date_txt, const text *fmt, Oid collid, bool std,
 							struct pg_tm *tm, fsec_t *fsec, struct fmt_tz *tz,
 							int *fprec, uint32 *flags, Node *escontext);
@@ -1190,7 +1191,7 @@ is_separator_char(const char *str)
  * Prepare NUMDesc (number description struct) via FormatNode struct
  */
 static void
-NUMDesc_prepare(NUMDesc *num, FormatNode *n)
+NUMDesc_prepare(NUMDesc *num, const FormatNode *n)
 {
 	if (n->type != NODE_TYPE_ACTION)
 		return;
@@ -2432,7 +2433,8 @@ seq_search_localized(const char *name, char **array, size_t *len, Oid collid)
 static bool
 from_char_seq_search(int *dest, const char **src, const char *const *array,
 					 char **localized_array, Oid collid,
-					 FormatNode *node, Node *escontext)
+					 const FormatNode *node,
+					 Node *escontext)
 {
 	size_t		len;
 
diff --git a/src/backend/utils/adt/geo_spgist.c b/src/backend/utils/adt/geo_spgist.c
index 4308a3065cd..cf7a15e9373 100644
--- a/src/backend/utils/adt/geo_spgist.c
+++ b/src/backend/utils/adt/geo_spgist.c
@@ -127,7 +127,7 @@ typedef struct
  * This makes 16 quadrants in total.
  */
 static uint8
-getQuadrant(BOX *centroid, BOX *inBox)
+getQuadrant(const BOX *centroid, const BOX *inBox)
 {
 	uint8		quadrant = 0;
 
@@ -154,7 +154,7 @@ getQuadrant(BOX *centroid, BOX *inBox)
  * access the values with this structure.
  */
 static RangeBox *
-getRangeBox(BOX *box)
+getRangeBox(const BOX *box)
 {
 	RangeBox   *range_box = (RangeBox *) palloc(sizeof(RangeBox));
 
@@ -202,7 +202,7 @@ initRectBox(void)
  * using centroid and quadrant.
  */
 static RectBox *
-nextRectBox(RectBox *rect_box, RangeBox *centroid, uint8 quadrant)
+nextRectBox(RectBox *rect_box, const RangeBox *centroid, uint8 quadrant)
 {
 	RectBox    *next_rect_box = (RectBox *) palloc(sizeof(RectBox));
 
@@ -233,7 +233,7 @@ nextRectBox(RectBox *rect_box, RangeBox *centroid, uint8 quadrant)
 
 /* Can any range from range_box overlap with this argument? */
 static bool
-overlap2D(RangeBox *range_box, Range *query)
+overlap2D(const RangeBox *range_box, Range *query)
 {
 	return FPge(range_box->right.high, query->low) &&
 		FPle(range_box->left.low, query->high);
@@ -249,7 +249,7 @@ overlap4D(RectBox *rect_box, RangeBox *query)
 
 /* Can any range from range_box contain this argument? */
 static bool
-contain2D(RangeBox *range_box, Range *query)
+contain2D(const RangeBox *range_box, Range *query)
 {
 	return FPge(range_box->right.high, query->high) &&
 		FPle(range_box->left.low, query->low);
@@ -265,7 +265,7 @@ contain4D(RectBox *rect_box, RangeBox *query)
 
 /* Can any range from range_box be contained by this argument? */
 static bool
-contained2D(RangeBox *range_box, Range *query)
+contained2D(const RangeBox *range_box, Range *query)
 {
 	return FPle(range_box->left.low, query->high) &&
 		FPge(range_box->left.high, query->low) &&
@@ -283,7 +283,7 @@ contained4D(RectBox *rect_box, RangeBox *query)
 
 /* Can any range from range_box to be lower than this argument? */
 static bool
-lower2D(RangeBox *range_box, Range *query)
+lower2D(const RangeBox *range_box, Range *query)
 {
 	return FPlt(range_box->left.low, query->low) &&
 		FPlt(range_box->right.low, query->low);
@@ -291,7 +291,7 @@ lower2D(RangeBox *range_box, Range *query)
 
 /* Can any range from range_box not extend to the right side of the query? */
 static bool
-overLower2D(RangeBox *range_box, Range *query)
+overLower2D(const RangeBox *range_box, Range *query)
 {
 	return FPle(range_box->left.low, query->high) &&
 		FPle(range_box->right.low, query->high);
@@ -299,7 +299,7 @@ overLower2D(RangeBox *range_box, Range *query)
 
 /* Can any range from range_box to be higher than this argument? */
 static bool
-higher2D(RangeBox *range_box, Range *query)
+higher2D(const RangeBox *range_box, Range *query)
 {
 	return FPgt(range_box->left.high, query->high) &&
 		FPgt(range_box->right.high, query->high);
@@ -307,7 +307,7 @@ higher2D(RangeBox *range_box, Range *query)
 
 /* Can any range from range_box not extend to the left side of the query? */
 static bool
-overHigher2D(RangeBox *range_box, Range *query)
+overHigher2D(const RangeBox *range_box, Range *query)
 {
 	return FPge(range_box->left.high, query->low) &&
 		FPge(range_box->right.high, query->low);
@@ -371,7 +371,7 @@ overAbove4D(RectBox *rect_box, RangeBox *query)
 
 /* Lower bound for the distance between point and rect_box */
 static double
-pointToRectBoxDistance(Point *point, RectBox *rect_box)
+pointToRectBoxDistance(const Point *point, const RectBox *rect_box)
 {
 	double		dx;
 	double		dy;
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index c4fe6e00dcd..4c6b59184a7 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -43,7 +43,8 @@ static JsonParseErrorType jsonb_in_object_end(void *pstate);
 static JsonParseErrorType jsonb_in_array_start(void *pstate);
 static JsonParseErrorType jsonb_in_array_end(void *pstate);
 static JsonParseErrorType jsonb_in_object_field_start(void *pstate, char *fname, bool isnull);
-static void jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal);
+static void jsonb_put_escaped_value(StringInfo out,
+									const JsonbValue *scalarVal);
 static JsonParseErrorType jsonb_in_scalar(void *pstate, char *token, JsonTokenType tokentype);
 static void composite_to_jsonb(Datum composite, JsonbInState *result);
 static void array_dim_to_jsonb(JsonbInState *result, int dim, int ndims, int *dims,
@@ -339,7 +340,7 @@ jsonb_in_object_field_start(void *pstate, char *fname, bool isnull)
 }
 
 static void
-jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal)
+jsonb_put_escaped_value(StringInfo out, const JsonbValue *scalarVal)
 {
 	switch (scalarVal->type)
 	{
diff --git a/src/backend/utils/adt/jsonb_util.c b/src/backend/utils/adt/jsonb_util.c
index 1eb8dffa8bd..2061f01d4d6 100644
--- a/src/backend/utils/adt/jsonb_util.c
+++ b/src/backend/utils/adt/jsonb_util.c
@@ -40,15 +40,20 @@
 #define JSONB_MAX_PAIRS (Min(MaxAllocSize / sizeof(JsonbPair), JB_CMASK))
 
 static void fillJsonbValue(JsonbContainer *container, int index,
-						   char *base_addr, uint32 offset,
+						   char *base_addr,
+						   uint32 offset,
 						   JsonbValue *result);
 static bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b);
-static int	compareJsonbScalarValue(JsonbValue *a, JsonbValue *b);
+static int	compareJsonbScalarValue(const JsonbValue *a,
+									const JsonbValue *b);
 static Jsonb *convertToJsonb(JsonbValue *val);
 static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
-static void convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
-static void convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
-static void convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal);
+static void convertJsonbArray(StringInfo buffer, JEntry *header,
+							  const JsonbValue *val, int level);
+static void convertJsonbObject(StringInfo buffer, JEntry *header,
+							   const JsonbValue *val, int level);
+static void convertJsonbScalar(StringInfo buffer, JEntry *header,
+							   const JsonbValue *scalarVal);
 
 static int	reserveFromBuffer(StringInfo buffer, int len);
 static void appendToBuffer(StringInfo buffer, const void *data, int len);
@@ -58,9 +63,12 @@ static short padBufferToInt(StringInfo buffer);
 static JsonbIterator *iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent);
 static JsonbIterator *freeAndGetParent(JsonbIterator *it);
 static JsonbParseState *pushState(JsonbInState *pstate);
-static void appendKey(JsonbInState *pstate, JsonbValue *string, bool needCopy);
-static void appendValue(JsonbInState *pstate, JsonbValue *scalarVal, bool needCopy);
-static void appendElement(JsonbInState *pstate, JsonbValue *scalarVal, bool needCopy);
+static void appendKey(JsonbInState *pstate, const JsonbValue *string,
+					  bool needCopy);
+static void appendValue(JsonbInState *pstate, const JsonbValue *scalarVal,
+						bool needCopy);
+static void appendElement(JsonbInState *pstate, const JsonbValue *scalarVal,
+						  bool needCopy);
 static void copyScalarSubstructure(JsonbValue *v, MemoryContext outcontext);
 static int	lengthCompareJsonbStringValue(const void *a, const void *b);
 static int	lengthCompareJsonbString(const char *val1, int len1,
@@ -782,7 +790,7 @@ pushState(JsonbInState *pstate)
  * pushJsonbValue() worker:  Append a pair key to pstate
  */
 static void
-appendKey(JsonbInState *pstate, JsonbValue *string, bool needCopy)
+appendKey(JsonbInState *pstate, const JsonbValue *string, bool needCopy)
 {
 	JsonbParseState *ppstate = pstate->parseState;
 	JsonbValue *object = &ppstate->contVal;
@@ -815,7 +823,7 @@ appendKey(JsonbInState *pstate, JsonbValue *string, bool needCopy)
  * pushJsonbValue() worker:  Append a pair value to pstate
  */
 static void
-appendValue(JsonbInState *pstate, JsonbValue *scalarVal, bool needCopy)
+appendValue(JsonbInState *pstate, const JsonbValue *scalarVal, bool needCopy)
 {
 	JsonbValue *object = &pstate->parseState->contVal;
 	JsonbPair  *pair;
@@ -834,7 +842,8 @@ appendValue(JsonbInState *pstate, JsonbValue *scalarVal, bool needCopy)
  * pushJsonbValue() worker:  Append an array element to pstate
  */
 static void
-appendElement(JsonbInState *pstate, JsonbValue *scalarVal, bool needCopy)
+appendElement(JsonbInState *pstate, const JsonbValue *scalarVal,
+			  bool needCopy)
 {
 	JsonbParseState *ppstate = pstate->parseState;
 	JsonbValue *array = &ppstate->contVal;
@@ -1557,7 +1566,7 @@ equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b)
  * operators, where a lexical sort order is generally expected.
  */
 static int
-compareJsonbScalarValue(JsonbValue *a, JsonbValue *b)
+compareJsonbScalarValue(const JsonbValue *a, const JsonbValue *b)
 {
 	if (a->type == b->type)
 	{
@@ -1739,7 +1748,8 @@ convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
 }
 
 static void
-convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
+convertJsonbArray(StringInfo buffer, JEntry *header, const JsonbValue *val,
+				  int level)
 {
 	int			base_offset;
 	int			jentry_offset;
@@ -1823,7 +1833,8 @@ convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
 }
 
 static void
-convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
+convertJsonbObject(StringInfo buffer, JEntry *header, const JsonbValue *val,
+				   int level)
 {
 	int			base_offset;
 	int			jentry_offset;
@@ -1939,7 +1950,8 @@ convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level
 }
 
 static void
-convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal)
+convertJsonbScalar(StringInfo buffer, JEntry *header,
+				   const JsonbValue *scalarVal)
 {
 	int			numlen;
 	short		padlen;
diff --git a/src/backend/utils/adt/jsonfuncs.c b/src/backend/utils/adt/jsonfuncs.c
index 22de18bc5b9..23d12957f9a 100644
--- a/src/backend/utils/adt/jsonfuncs.c
+++ b/src/backend/utils/adt/jsonfuncs.c
@@ -361,7 +361,7 @@ static Datum get_path_all(FunctionCallInfo fcinfo, bool as_text);
 static text *get_worker(text *json, char **tpath, int *ipath, int npath,
 						bool normalize_results);
 static Datum get_jsonb_path_all(FunctionCallInfo fcinfo, bool as_text);
-static text *JsonbValueAsText(JsonbValue *v);
+static text *JsonbValueAsText(const JsonbValue *v);
 
 /* semantic action functions for json_array_length */
 static JsonParseErrorType alen_object_start(void *state);
@@ -443,12 +443,14 @@ static void get_record_type_from_argument(FunctionCallInfo fcinfo,
 static void get_record_type_from_query(FunctionCallInfo fcinfo,
 									   const char *funcname,
 									   PopulateRecordCache *cache);
-static bool JsValueToJsObject(JsValue *jsv, JsObject *jso, Node *escontext);
+static bool JsValueToJsObject(const JsValue *jsv, JsObject *jso,
+							  Node *escontext);
 static Datum populate_composite(CompositeIOData *io, Oid typid,
 								const char *colname, MemoryContext mcxt,
 								HeapTupleHeader defaultval, JsValue *jsv, bool *isnull,
 								Node *escontext);
-static Datum populate_scalar(ScalarIOData *io, Oid typid, int32 typmod, JsValue *jsv,
+static Datum populate_scalar(ScalarIOData *io, Oid typid, int32 typmod,
+							 const JsValue *jsv,
 							 bool *isnull, Node *escontext, bool omit_quotes);
 static void prepare_column_cache(ColumnIOData *column, Oid typid, int32 typmod,
 								 MemoryContext mcxt, bool need_scalar);
@@ -457,17 +459,19 @@ static Datum populate_record_field(ColumnIOData *col, Oid typid, int32 typmod,
 								   JsValue *jsv, bool *isnull, Node *escontext,
 								   bool omit_scalar_quotes);
 static RecordIOData *allocate_record_info(MemoryContext mcxt, int ncolumns);
-static bool JsObjectGetField(JsObject *obj, char *field, JsValue *jsv);
+static bool JsObjectGetField(const JsObject *obj, char *field, JsValue *jsv);
 static void populate_recordset_record(PopulateRecordsetState *state, JsObject *obj);
 static bool populate_array_json(PopulateArrayContext *ctx, const char *json, int len);
-static bool populate_array_dim_jsonb(PopulateArrayContext *ctx, JsonbValue *jbv,
+static bool populate_array_dim_jsonb(PopulateArrayContext *ctx,
+									 const JsonbValue *jbv,
 									 int ndim);
 static void populate_array_report_expected_array(PopulateArrayContext *ctx, int ndim);
 static bool populate_array_assign_ndims(PopulateArrayContext *ctx, int ndims);
 static bool populate_array_check_dimension(PopulateArrayContext *ctx, int ndim);
 static bool populate_array_element(PopulateArrayContext *ctx, int ndim, JsValue *jsv);
 static Datum populate_array(ArrayIOData *aio, const char *colname,
-							MemoryContext mcxt, JsValue *jsv,
+							MemoryContext mcxt,
+							const JsValue *jsv,
 							bool *isnull,
 							Node *escontext);
 static Datum populate_domain(DomainIOData *io, Oid typid, const char *colname,
@@ -1799,7 +1803,7 @@ push_path(JsonbInState *st, int level, const Datum *path_elems,
  * Return the text representation of the given JsonbValue.
  */
 static text *
-JsonbValueAsText(JsonbValue *v)
+JsonbValueAsText(const JsonbValue *v)
 {
 	switch (v->type)
 	{
@@ -2820,7 +2824,8 @@ populate_array_json(PopulateArrayContext *ctx, const char *json, int len)
  */
 static bool
 populate_array_dim_jsonb(PopulateArrayContext *ctx, /* context */
-						 JsonbValue *jbv,	/* jsonb sub-array */
+						 const JsonbValue *jbv,
+ /* jsonb sub-array */
 						 int ndim)	/* current dimension */
 {
 	JsonbContainer *jbc = jbv->val.binary.data;
@@ -2912,7 +2917,7 @@ static Datum
 populate_array(ArrayIOData *aio,
 			   const char *colname,
 			   MemoryContext mcxt,
-			   JsValue *jsv,
+			   const JsValue *jsv,
 			   bool *isnull,
 			   Node *escontext)
 {
@@ -2976,7 +2981,7 @@ populate_array(ArrayIOData *aio,
  * ErrorSaveContext.
  */
 static bool
-JsValueToJsObject(JsValue *jsv, JsObject *jso, Node *escontext)
+JsValueToJsObject(const JsValue *jsv, JsObject *jso, Node *escontext)
 {
 	jso->is_json = jsv->is_json;
 
@@ -3119,7 +3124,7 @@ populate_composite(CompositeIOData *io,
  * provided escontext is valid.
  */
 static Datum
-populate_scalar(ScalarIOData *io, Oid typid, int32 typmod, JsValue *jsv,
+populate_scalar(ScalarIOData *io, Oid typid, int32 typmod, const JsValue *jsv,
 				bool *isnull, Node *escontext, bool omit_quotes)
 {
 	Datum		res;
@@ -3486,7 +3491,7 @@ allocate_record_info(MemoryContext mcxt, int ncolumns)
 }
 
 static bool
-JsObjectGetField(JsObject *obj, char *field, JsValue *jsv)
+JsObjectGetField(const JsObject *obj, char *field, JsValue *jsv)
 {
 	jsv->is_json = obj->is_json;
 
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 3f92baf6e82..b0f06f12b9b 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -321,21 +321,23 @@ static JsonbValue *getJsonPathVariableFromJsonb(void *varsJsonb, char *varName,
 												int varNameLength,
 												JsonbValue *baseObject,
 												int *baseObjectId);
-static int	JsonbArraySize(JsonbValue *jb);
+static int	JsonbArraySize(const JsonbValue *jb);
 static JsonPathBool executeComparison(JsonPathItem *cmp, JsonbValue *lv,
 									  JsonbValue *rv, void *p);
-static JsonPathBool compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2,
+static JsonPathBool compareItems(int32 op, JsonbValue *jb1,
+								 const JsonbValue *jb2,
 								 bool useTz);
 static int	compareNumeric(Numeric a, Numeric b);
-static JsonbValue *copyJsonbValue(JsonbValue *src);
+static JsonbValue *copyJsonbValue(const JsonbValue *src);
 static JsonPathExecResult getArrayIndex(JsonPathExecContext *cxt,
 										JsonPathItem *jsp, JsonbValue *jb, int32 *index);
 static JsonBaseObjectInfo setBaseObject(JsonPathExecContext *cxt,
-										JsonbValue *jbv, int32 id);
+										const JsonbValue *jbv,
+										int32 id);
 static void JsonValueListClear(JsonValueList *jvl);
 static void JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv);
 static int	JsonValueListLength(const JsonValueList *jvl);
-static bool JsonValueListIsEmpty(JsonValueList *jvl);
+static bool JsonValueListIsEmpty(const JsonValueList *jvl);
 static JsonbValue *JsonValueListHead(JsonValueList *jvl);
 static List *JsonValueListGetList(JsonValueList *jvl);
 static void JsonValueListInitIterator(const JsonValueList *jvl,
@@ -343,7 +345,7 @@ static void JsonValueListInitIterator(const JsonValueList *jvl,
 static JsonbValue *JsonValueListNext(const JsonValueList *jvl,
 									 JsonValueListIterator *it);
 static JsonbValue *JsonbInitBinary(JsonbValue *jbv, Jsonb *jb);
-static int	JsonbType(JsonbValue *jb);
+static int	JsonbType(const JsonbValue *jb);
 static JsonbValue *getScalar(JsonbValue *scalar, enum jbvType type);
 static JsonbValue *wrapItemsInArray(const JsonValueList *items);
 static int	compareDatetime(Datum val1, Oid typid1, Datum val2, Oid typid2,
@@ -3223,7 +3225,7 @@ countVariablesFromJsonb(void *varsJsonb)
  * Returns the size of an array item, or -1 if item is not an array.
  */
 static int
-JsonbArraySize(JsonbValue *jb)
+JsonbArraySize(const JsonbValue *jb)
 {
 	Assert(jb->type != jbvArray);
 
@@ -3339,7 +3341,7 @@ compareStrings(const char *mbstr1, int mblen1,
  * Compare two SQL/JSON items using comparison operation 'op'.
  */
 static JsonPathBool
-compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2, bool useTz)
+compareItems(int32 op, JsonbValue *jb1, const JsonbValue *jb2, bool useTz)
 {
 	int			cmp;
 	bool		res;
@@ -3443,7 +3445,7 @@ compareNumeric(Numeric a, Numeric b)
 }
 
 static JsonbValue *
-copyJsonbValue(JsonbValue *src)
+copyJsonbValue(const JsonbValue *src)
 {
 	JsonbValue *dst = palloc(sizeof(*dst));
 
@@ -3492,7 +3494,7 @@ getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
 
 /* Save base object and its id needed for the execution of .keyvalue(). */
 static JsonBaseObjectInfo
-setBaseObject(JsonPathExecContext *cxt, JsonbValue *jbv, int32 id)
+setBaseObject(JsonPathExecContext *cxt, const JsonbValue *jbv, int32 id)
 {
 	JsonBaseObjectInfo baseObject = cxt->baseObject;
 
@@ -3531,7 +3533,7 @@ JsonValueListLength(const JsonValueList *jvl)
 }
 
 static bool
-JsonValueListIsEmpty(JsonValueList *jvl)
+JsonValueListIsEmpty(const JsonValueList *jvl)
 {
 	return !jvl->singleton && (jvl->list == NIL);
 }
@@ -3612,7 +3614,7 @@ JsonbInitBinary(JsonbValue *jbv, Jsonb *jb)
  * Returns jbv* type of JsonbValue. Note, it never returns jbvBinary as is.
  */
 static int
-JsonbType(JsonbValue *jb)
+JsonbType(const JsonbValue *jb)
 {
 	int			type = jb->type;
 
diff --git a/src/backend/utils/adt/multirangetypes_selfuncs.c b/src/backend/utils/adt/multirangetypes_selfuncs.c
index 21f0205d803..5bd812c5f9f 100644
--- a/src/backend/utils/adt/multirangetypes_selfuncs.c
+++ b/src/backend/utils/adt/multirangetypes_selfuncs.c
@@ -34,7 +34,7 @@ static double calc_multirangesel(TypeCacheEntry *typcache,
 								 VariableStatData *vardata,
 								 const MultirangeType *constval, Oid operator);
 static double default_multirange_selectivity(Oid operator);
-static double calc_hist_selectivity(TypeCacheEntry *typcache,
+static double calc_hist_selectivity(const TypeCacheEntry *typcache,
 									VariableStatData *vardata,
 									const MultirangeType *constval,
 									Oid operator);
@@ -453,7 +453,8 @@ calc_multirangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
  * NULL.
  */
 static double
-calc_hist_selectivity(TypeCacheEntry *typcache, VariableStatData *vardata,
+calc_hist_selectivity(const TypeCacheEntry *typcache,
+					  VariableStatData *vardata,
 					  const MultirangeType *constval, Oid operator)
 {
 	TypeCacheEntry *rng_typcache = typcache->rngtype;
diff --git a/src/backend/utils/adt/network_gist.c b/src/backend/utils/adt/network_gist.c
index a08c4953789..b7ebd9b07b7 100644
--- a/src/backend/utils/adt/network_gist.c
+++ b/src/backend/utils/adt/network_gist.c
@@ -405,7 +405,8 @@ calc_inet_union_params(GISTENTRY *ent,
  */
 static void
 calc_inet_union_params_indexed(GISTENTRY *ent,
-							   OffsetNumber *offsets, int noffsets,
+							   const OffsetNumber *offsets,
+							   int noffsets,
 							   int *minfamily_p,
 							   int *maxfamily_p,
 							   int *minbits_p,
diff --git a/src/backend/utils/adt/network_selfuncs.c b/src/backend/utils/adt/network_selfuncs.c
index d08f40e0332..79aab587eac 100644
--- a/src/backend/utils/adt/network_selfuncs.c
+++ b/src/backend/utils/adt/network_selfuncs.c
@@ -47,13 +47,18 @@ static Selectivity networkjoinsel_inner(Oid operator,
 										VariableStatData *vardata1, VariableStatData *vardata2);
 static Selectivity networkjoinsel_semi(Oid operator,
 									   VariableStatData *vardata1, VariableStatData *vardata2);
-static Selectivity mcv_population(float4 *mcv_numbers, int mcv_nvalues);
+static Selectivity mcv_population(const float4 *mcv_numbers, int mcv_nvalues);
 static Selectivity inet_hist_value_sel(const Datum *values, int nvalues,
 									   Datum constvalue, int opr_codenum);
-static Selectivity inet_mcv_join_sel(Datum *mcv1_values,
-									 float4 *mcv1_numbers, int mcv1_nvalues, Datum *mcv2_values,
-									 float4 *mcv2_numbers, int mcv2_nvalues, Oid operator);
-static Selectivity inet_mcv_hist_sel(const Datum *mcv_values, float4 *mcv_numbers,
+static Selectivity inet_mcv_join_sel(const Datum *mcv1_values,
+									 const float4 *mcv1_numbers,
+									 int mcv1_nvalues,
+									 const Datum *mcv2_values,
+									 const float4 *mcv2_numbers,
+									 int mcv2_nvalues,
+									 Oid operator);
+static Selectivity inet_mcv_hist_sel(const Datum *mcv_values,
+									 const float4 *mcv_numbers,
 									 int mcv_nvalues, const Datum *hist_values, int hist_nvalues,
 									 int opr_codenum);
 static Selectivity inet_hist_inclusion_join_sel(const Datum *hist1_values,
@@ -61,7 +66,9 @@ static Selectivity inet_hist_inclusion_join_sel(const Datum *hist1_values,
 												const Datum *hist2_values, int hist2_nvalues,
 												int opr_codenum);
 static Selectivity inet_semi_join_sel(Datum lhs_value,
-									  bool mcv_exists, Datum *mcv_values, int mcv_nvalues,
+									  bool mcv_exists,
+									  const Datum *mcv_values,
+									  int mcv_nvalues,
 									  bool hist_exists, Datum *hist_values, int hist_nvalues,
 									  double hist_weight,
 									  FmgrInfo *proc, int opr_codenum);
@@ -536,7 +543,7 @@ networkjoinsel_semi(Oid operator,
  * by the MCV list.
  */
 static Selectivity
-mcv_population(float4 *mcv_numbers, int mcv_nvalues)
+mcv_population(const float4 *mcv_numbers, int mcv_nvalues)
 {
 	Selectivity sumcommon = 0.0;
 	int			i;
@@ -670,8 +677,11 @@ inet_hist_value_sel(const Datum *values, int nvalues, Datum constvalue,
  * The result is exact and does not need to be scaled further.
  */
 static Selectivity
-inet_mcv_join_sel(Datum *mcv1_values, float4 *mcv1_numbers, int mcv1_nvalues,
-				  Datum *mcv2_values, float4 *mcv2_numbers, int mcv2_nvalues,
+inet_mcv_join_sel(const Datum *mcv1_values, const float4 *mcv1_numbers,
+				  int mcv1_nvalues,
+				  const Datum *mcv2_values,
+				  const float4 *mcv2_numbers,
+				  int mcv2_nvalues,
 				  Oid operator)
 {
 	Selectivity selec = 0.0;
@@ -702,7 +712,8 @@ inet_mcv_join_sel(Datum *mcv1_values, float4 *mcv1_numbers, int mcv1_nvalues,
  * the histogram.
  */
 static Selectivity
-inet_mcv_hist_sel(const Datum *mcv_values, float4 *mcv_numbers, int mcv_nvalues,
+inet_mcv_hist_sel(const Datum *mcv_values, const float4 *mcv_numbers,
+				  int mcv_nvalues,
 				  const Datum *hist_values, int hist_nvalues,
 				  int opr_codenum)
 {
@@ -791,7 +802,8 @@ inet_hist_inclusion_join_sel(const Datum *hist1_values, int hist1_nvalues,
  */
 static Selectivity
 inet_semi_join_sel(Datum lhs_value,
-				   bool mcv_exists, Datum *mcv_values, int mcv_nvalues,
+				   bool mcv_exists, const Datum *mcv_values,
+				   int mcv_nvalues,
 				   bool hist_exists, Datum *hist_values, int hist_nvalues,
 				   double hist_weight,
 				   FmgrInfo *proc, int opr_codenum)
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index 1d626aecbe7..0fa1a152155 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -498,7 +498,7 @@ static void alloc_var(NumericVar *var, int ndigits);
 static void free_var(NumericVar *var);
 static void zero_var(NumericVar *var);
 
-static bool set_var_from_str(const char *str, const char *cp,
+static bool set_var_from_str(char *str, const char *cp,
 							 NumericVar *dest, const char **endptr,
 							 Node *escontext);
 static bool set_var_from_non_decimal_integer_str(const char *str,
@@ -4110,7 +4110,7 @@ numeric_scale(PG_FUNCTION_ARGS)
  * Calculate minimum scale for value.
  */
 static int
-get_min_scale(NumericVar *var)
+get_min_scale(const NumericVar *var)
 {
 	int			min_scale;
 	int			last_digit_pos;
@@ -6740,7 +6740,7 @@ zero_var(NumericVar *var)
  * ErrorSaveContext; otherwise errors are thrown).
  */
 static bool
-set_var_from_str(const char *str, const char *cp,
+set_var_from_str(char *str, const char *cp,
 				 NumericVar *dest, const char **endptr,
 				 Node *escontext)
 {
diff --git a/src/backend/utils/adt/pg_locale.c b/src/backend/utils/adt/pg_locale.c
index d73bab97c15..5a44da1e8e4 100644
--- a/src/backend/utils/adt/pg_locale.c
+++ b/src/backend/utils/adt/pg_locale.c
@@ -439,7 +439,7 @@ free_struct_lconv(struct lconv *s)
  * about) are non-NULL.  The field list must match free_struct_lconv().
  */
 static bool
-struct_lconv_is_valid(struct lconv *s)
+struct_lconv_is_valid(const struct lconv *s)
 {
 	if (s->decimal_point == NULL)
 		return false;
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index ef6fffe60b9..5e33e0d7f81 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1458,7 +1458,7 @@ pg_stat_us_to_ms(PgStat_Counter val_ms)
  */
 static void
 pg_stat_io_build_tuples(ReturnSetInfo *rsinfo,
-						PgStat_BktypeIO *bktype_stats,
+						const PgStat_BktypeIO *bktype_stats,
 						BackendType bktype,
 						TimestampTz stat_reset_timestamp)
 {
diff --git a/src/backend/utils/adt/rangetypes.c b/src/backend/utils/adt/rangetypes.c
index d8e5130d642..e304c5a9eee 100644
--- a/src/backend/utils/adt/rangetypes.c
+++ b/src/backend/utils/adt/rangetypes.c
@@ -78,7 +78,7 @@ static Node *find_simplified_clause(PlannerInfo *root,
 									Expr *rangeExpr, Expr *elemExpr);
 static Expr *build_bound_expr(Expr *elemExpr, Datum val,
 							  bool isLowerBound, bool isInclusive,
-							  TypeCacheEntry *typeCache,
+							  const TypeCacheEntry *typeCache,
 							  Oid opfamily, Oid rng_collation);
 
 
@@ -3139,7 +3139,7 @@ find_simplified_clause(PlannerInfo *root, Expr *rangeExpr, Expr *elemExpr)
 static Expr *
 build_bound_expr(Expr *elemExpr, Datum val,
 				 bool isLowerBound, bool isInclusive,
-				 TypeCacheEntry *typeCache,
+				 const TypeCacheEntry *typeCache,
 				 Oid opfamily, Oid rng_collation)
 {
 	Oid			elemType = typeCache->type_id;
diff --git a/src/backend/utils/adt/rangetypes_gist.c b/src/backend/utils/adt/rangetypes_gist.c
index a60ee985e74..bcec6a86a8e 100644
--- a/src/backend/utils/adt/rangetypes_gist.c
+++ b/src/backend/utils/adt/rangetypes_gist.c
@@ -161,14 +161,14 @@ static bool range_gist_consistent_leaf_element(TypeCacheEntry *typcache,
 											   const RangeType *key,
 											   Datum query);
 static void range_gist_fallback_split(TypeCacheEntry *typcache,
-									  GistEntryVector *entryvec,
+									  const GistEntryVector *entryvec,
 									  GIST_SPLITVEC *v);
 static void range_gist_class_split(TypeCacheEntry *typcache,
-								   GistEntryVector *entryvec,
+								   const GistEntryVector *entryvec,
 								   GIST_SPLITVEC *v,
-								   SplitLR *classes_groups);
+								   const SplitLR *classes_groups);
 static void range_gist_single_sorting_split(TypeCacheEntry *typcache,
-											GistEntryVector *entryvec,
+											const GistEntryVector *entryvec,
 											GIST_SPLITVEC *v,
 											bool use_upper_bound);
 static void range_gist_double_sorting_split(TypeCacheEntry *typcache,
@@ -1146,7 +1146,7 @@ range_gist_consistent_leaf_element(TypeCacheEntry *typcache,
  */
 static void
 range_gist_fallback_split(TypeCacheEntry *typcache,
-						  GistEntryVector *entryvec,
+						  const GistEntryVector *entryvec,
 						  GIST_SPLITVEC *v)
 {
 	RangeType  *left_range = NULL;
@@ -1184,9 +1184,9 @@ range_gist_fallback_split(TypeCacheEntry *typcache,
  */
 static void
 range_gist_class_split(TypeCacheEntry *typcache,
-					   GistEntryVector *entryvec,
+					   const GistEntryVector *entryvec,
 					   GIST_SPLITVEC *v,
-					   SplitLR *classes_groups)
+					   const SplitLR *classes_groups)
 {
 	RangeType  *left_range = NULL;
 	RangeType  *right_range = NULL;
@@ -1227,7 +1227,7 @@ range_gist_class_split(TypeCacheEntry *typcache,
  */
 static void
 range_gist_single_sorting_split(TypeCacheEntry *typcache,
-								GistEntryVector *entryvec,
+								const GistEntryVector *entryvec,
 								GIST_SPLITVEC *v,
 								bool use_upper_bound)
 {
diff --git a/src/backend/utils/adt/regexp.c b/src/backend/utils/adt/regexp.c
index b0cdef9b19f..c16ced23f82 100644
--- a/src/backend/utils/adt/regexp.c
+++ b/src/backend/utils/adt/regexp.c
@@ -115,7 +115,7 @@ static cached_re_str re_array[MAX_CACHED_RES];	/* cached re's */
 
 /* Local functions */
 static regexp_matches_ctx *setup_regexp_matches(text *orig_str, text *pattern,
-												pg_re_flags *re_flags,
+												const pg_re_flags *re_flags,
 												int start_search,
 												Oid collation,
 												bool use_subpatterns,
@@ -1482,7 +1482,8 @@ regexp_matches_no_flags(PG_FUNCTION_ARGS)
  * anyway, and it didn't seem worth complicating the code further.)
  */
 static regexp_matches_ctx *
-setup_regexp_matches(text *orig_str, text *pattern, pg_re_flags *re_flags,
+setup_regexp_matches(text *orig_str, text *pattern,
+					 const pg_re_flags *re_flags,
 					 int start_search,
 					 Oid collation,
 					 bool use_subpatterns,
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 540aa9628d7..051cc6927e7 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -197,7 +197,8 @@ static double eqjoinsel_inner(FmgrInfo *eqproc, Oid collation,
 static double eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 							 Oid hashLeft, Oid hashRight,
 							 bool op_is_reversed,
-							 VariableStatData *vardata1, VariableStatData *vardata2,
+							 VariableStatData *vardata1,
+							 const VariableStatData *vardata2,
 							 double nd1, double nd2,
 							 bool isdefault1, bool isdefault2,
 							 AttStatsSlot *sslot1, AttStatsSlot *sslot2,
@@ -205,7 +206,7 @@ static double eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 							 bool have_mcvs1, bool have_mcvs2,
 							 bool *hasmatch1, bool *hasmatch2,
 							 int *p_nmatches,
-							 RelOptInfo *inner_rel);
+							 const RelOptInfo *inner_rel);
 static void eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 								   Oid hashLeft, Oid hashRight,
 								   bool op_is_reversed,
@@ -213,8 +214,8 @@ static void eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 								   int nvalues1, int nvalues2,
 								   bool *hasmatch1, bool *hasmatch2,
 								   int *p_nmatches, double *p_matchprodfreq);
-static uint32 hash_mcv(MCVHashTable_hash *tab, Datum key);
-static bool mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1);
+static uint32 hash_mcv(const MCVHashTable_hash *tab, Datum key);
+static bool mcvs_equal(const MCVHashTable_hash *tab, Datum key0, Datum key1);
 static bool estimate_multivariate_ndistinct(PlannerInfo *root,
 											RelOptInfo *rel, List **varinfos, double *ndistinct);
 static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid,
@@ -244,16 +245,17 @@ static double convert_timevalue_to_scalar(Datum value, Oid typid,
 										  bool *failure);
 static void examine_simple_variable(PlannerInfo *root, Var *var,
 									VariableStatData *vardata);
-static void examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
+static void examine_indexcol_variable(PlannerInfo *root,
+									  const IndexOptInfo *index,
 									  int indexcol, VariableStatData *vardata);
 static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
 							   Oid sortop, Oid collation,
 							   Datum *min, Datum *max);
-static void get_stats_slot_range(AttStatsSlot *sslot,
+static void get_stats_slot_range(const AttStatsSlot *sslot,
 								 Oid opfuncoid, FmgrInfo *opproc,
 								 Oid collation, int16 typLen, bool typByVal,
 								 Datum *min, Datum *max, bool *p_have_data);
-static bool get_actual_variable_range(PlannerInfo *root,
+static bool get_actual_variable_range(const PlannerInfo *root,
 									  VariableStatData *vardata,
 									  Oid sortop, Oid collation,
 									  Datum *min, Datum *max);
@@ -267,7 +269,7 @@ static bool get_actual_variable_endpoint(Relation heapRel,
 										 MemoryContext outercontext,
 										 Datum *endpointDatum);
 static RelOptInfo *find_join_input_rel(PlannerInfo *root, Relids relids);
-static double btcost_correlation(IndexOptInfo *index,
+static double btcost_correlation(const IndexOptInfo *index,
 								 VariableStatData *vardata);
 
 /* Define support routines for MCV hash tables */
@@ -2715,7 +2717,8 @@ static double
 eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 			   Oid hashLeft, Oid hashRight,
 			   bool op_is_reversed,
-			   VariableStatData *vardata1, VariableStatData *vardata2,
+			   VariableStatData *vardata1,
+			   const VariableStatData *vardata2,
 			   double nd1, double nd2,
 			   bool isdefault1, bool isdefault2,
 			   AttStatsSlot *sslot1, AttStatsSlot *sslot2,
@@ -2723,7 +2726,7 @@ eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 			   bool have_mcvs1, bool have_mcvs2,
 			   bool *hasmatch1, bool *hasmatch2,
 			   int *p_nmatches,
-			   RelOptInfo *inner_rel)
+			   const RelOptInfo *inner_rel)
 {
 	double		selec;
 
@@ -3085,7 +3088,7 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
  * Support functions for the hash tables used by eqjoinsel_find_matches
  */
 static uint32
-hash_mcv(MCVHashTable_hash *tab, Datum key)
+hash_mcv(const MCVHashTable_hash *tab, Datum key)
 {
 	MCVHashContext *context = (MCVHashContext *) tab->private_data;
 	FunctionCallInfo fcinfo = context->hash_fcinfo;
@@ -3099,7 +3102,7 @@ hash_mcv(MCVHashTable_hash *tab, Datum key)
 }
 
 static bool
-mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1)
+mcvs_equal(const MCVHashTable_hash *tab, Datum key0, Datum key1)
 {
 	MCVHashContext *context = (MCVHashContext *) tab->private_data;
 
@@ -6415,7 +6418,7 @@ all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
  * Caller is responsible for doing ReleaseVariableStats() before exiting.
  */
 static void
-examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
+examine_indexcol_variable(PlannerInfo *root, const IndexOptInfo *index,
 						  int indexcol, VariableStatData *vardata)
 {
 	AttrNumber	colnum;
@@ -6778,7 +6781,8 @@ get_variable_range(PlannerInfo *root, VariableStatData *vardata,
  * to what we find in the statistics array.
  */
 static void
-get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
+get_stats_slot_range(const AttStatsSlot *sslot, Oid opfuncoid,
+					 FmgrInfo *opproc,
 					 Oid collation, int16 typLen, bool typByVal,
 					 Datum *min, Datum *max, bool *p_have_data)
 {
@@ -6841,7 +6845,7 @@ get_stats_slot_range(AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc,
  * collation is the required collation.
  */
 static bool
-get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
+get_actual_variable_range(const PlannerInfo *root, VariableStatData *vardata,
 						  Oid sortop, Oid collation,
 						  Datum *min, Datum *max)
 {
@@ -7565,7 +7569,7 @@ add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
  * We already filled in the stats tuple for *vardata when called.
  */
 static double
-btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
+btcost_correlation(const IndexOptInfo *index, VariableStatData *vardata)
 {
 	Oid			sortop;
 	AttStatsSlot sslot;
diff --git a/src/backend/utils/adt/tsquery_util.c b/src/backend/utils/adt/tsquery_util.c
index 1c24b041aa2..59e64c2efa9 100644
--- a/src/backend/utils/adt/tsquery_util.c
+++ b/src/backend/utils/adt/tsquery_util.c
@@ -289,7 +289,7 @@ QTNBinary(QTNode *in)
  * Caller must initialize *sumlen and *nnode to zeroes.
  */
 static void
-cntsize(QTNode *in, int *sumlen, int *nnode)
+cntsize(const QTNode *in, int *sumlen, int *nnode)
 {
 	/* since this function recurses, it could be driven to stack overflow. */
 	check_stack_depth();
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index f202b8df4e2..2e8ccc500b9 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -138,7 +138,7 @@ static int	text_position(text *t1, text *t2, Oid collid);
 static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state);
 static bool text_position_next(TextPositionState *state);
 static char *text_position_next_internal(char *start_ptr, TextPositionState *state);
-static char *text_position_get_match_ptr(TextPositionState *state);
+static char *text_position_get_match_ptr(const TextPositionState *state);
 static int	text_position_get_match_pos(TextPositionState *state);
 static void text_position_cleanup(TextPositionState *state);
 static void check_collation_set(Oid collid);
@@ -1234,7 +1234,7 @@ text_position_next_internal(char *start_ptr, TextPositionState *state)
  * The returned pointer points into the original haystack string.
  */
 static char *
-text_position_get_match_ptr(TextPositionState *state)
+text_position_get_match_ptr(const TextPositionState *state)
 {
 	return state->last_match;
 }
@@ -3211,7 +3211,7 @@ check_replace_text_has_escape(const text *replace_text)
  */
 static void
 appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
-							 regmatch_t *pmatch,
+							 const regmatch_t *pmatch,
 							 char *start_ptr, int data_pos)
 {
 	const char *p = VARDATA_ANY(replace_text);
diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c
index 02ae7d5a831..ce14ec78124 100644
--- a/src/backend/utils/cache/catcache.c
+++ b/src/backend/utils/cache/catcache.c
@@ -1279,7 +1279,7 @@ InitCatCachePhase2(CatCache *cache, bool touch_index)
  *		catalogs' indexes.
  */
 static bool
-IndexScanOK(CatCache *cache)
+IndexScanOK(const CatCache *cache)
 {
 	switch (cache->id)
 	{
diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index 6661d2c6b73..524d04f2b82 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -98,10 +98,10 @@ static CachedPlan *BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
 								   ParamListInfo boundParams, QueryEnvironment *queryEnv);
 static bool choose_custom_plan(CachedPlanSource *plansource,
 							   ParamListInfo boundParams);
-static double cached_plan_cost(CachedPlan *plan, bool include_planner);
-static Query *QueryListGetPrimaryStmt(List *stmts);
-static void AcquireExecutorLocks(List *stmt_list, bool acquire);
-static void AcquirePlannerLocks(List *stmt_list, bool acquire);
+static double cached_plan_cost(const CachedPlan *plan, bool include_planner);
+static Query *QueryListGetPrimaryStmt(const List *stmts);
+static void AcquireExecutorLocks(const List *stmt_list, bool acquire);
+static void AcquirePlannerLocks(const List *stmt_list, bool acquire);
 static void ScanQueryForLocks(Query *parsetree, bool acquire);
 static bool ScanQueryWalker(Node *node, bool *acquire);
 static TupleDesc PlanCacheComputeResultDesc(List *stmt_list);
@@ -1227,7 +1227,7 @@ choose_custom_plan(CachedPlanSource *plansource, ParamListInfo boundParams)
  * we don't count it for a generic plan.)
  */
 static double
-cached_plan_cost(CachedPlan *plan, bool include_planner)
+cached_plan_cost(const CachedPlan *plan, bool include_planner)
 {
 	double		result = 0;
 	ListCell   *lc;
@@ -1888,7 +1888,7 @@ FreeCachedExpression(CachedExpression *cexpr)
  * occur in present usages of this function.
  */
 static Query *
-QueryListGetPrimaryStmt(List *stmts)
+QueryListGetPrimaryStmt(const List *stmts)
 {
 	ListCell   *lc;
 
@@ -1907,7 +1907,7 @@ QueryListGetPrimaryStmt(List *stmts)
  * or release them if acquire is false.
  */
 static void
-AcquireExecutorLocks(List *stmt_list, bool acquire)
+AcquireExecutorLocks(const List *stmt_list, bool acquire)
 {
 	ListCell   *lc1;
 
@@ -1963,7 +1963,7 @@ AcquireExecutorLocks(List *stmt_list, bool acquire)
  * a non-conflicting lock.
  */
 static void
-AcquirePlannerLocks(List *stmt_list, bool acquire)
+AcquirePlannerLocks(const List *stmt_list, bool acquire)
 {
 	ListCell   *lc;
 
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 915d0bc9084..27fe20bcf81 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -310,7 +310,7 @@ static int	AttrDefaultCmp(const void *a, const void *b);
 static void CheckNNConstraintFetch(Relation relation);
 static int	CheckConstraintCmp(const void *a, const void *b);
 static void InitIndexAmRoutine(Relation relation);
-static void IndexSupportInitialize(oidvector *indclass,
+static void IndexSupportInitialize(const oidvector *indclass,
 								   RegProcedure *indexSupport,
 								   Oid *opFamily,
 								   Oid *opcInType,
@@ -924,7 +924,7 @@ RelationBuildRuleLock(Relation relation)
  *		Probably this should be in the rules code someplace...
  */
 static bool
-equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
+equalRuleLocks(const RuleLock *rlock1, const RuleLock *rlock2)
 {
 	int			i;
 
@@ -1613,7 +1613,7 @@ RelationInitIndexAccessInfo(Relation relation)
  * for the index and access method.
  */
 static void
-IndexSupportInitialize(oidvector *indclass,
+IndexSupportInitialize(const oidvector *indclass,
 					   RegProcedure *indexSupport,
 					   Oid *opFamily,
 					   Oid *opcInType,
diff --git a/src/backend/utils/fmgr/funcapi.c b/src/backend/utils/fmgr/funcapi.c
index 5f2317211c9..972e96a38c6 100644
--- a/src/backend/utils/fmgr/funcapi.c
+++ b/src/backend/utils/fmgr/funcapi.c
@@ -51,7 +51,7 @@ static void resolve_anyarray_from_others(polymorphic_actuals *actuals);
 static void resolve_anyrange_from_others(polymorphic_actuals *actuals);
 static void resolve_anymultirange_from_others(polymorphic_actuals *actuals);
 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc,
-										oidvector *declared_args,
+										const oidvector *declared_args,
 										Node *call_expr);
 static TypeFuncClass get_type_func_class(Oid typid, Oid *base_typeid);
 
@@ -741,7 +741,7 @@ resolve_anymultirange_from_others(polymorphic_actuals *actuals)
  * is not provided (call_expr is NULL or arg types aren't identifiable).
  */
 static bool
-resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
+resolve_polymorphic_tupdesc(TupleDesc tupdesc, const oidvector *declared_args,
 							Node *call_expr)
 {
 	int			natts = tupdesc->natts;
diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c
index ac94b9e93c6..07ba01384ed 100644
--- a/src/backend/utils/hash/dynahash.c
+++ b/src/backend/utils/hash/dynahash.c
@@ -269,12 +269,12 @@ struct HTAB
  * Private function prototypes
  */
 static void *DynaHashAlloc(Size size);
-static HASHSEGMENT seg_alloc(HTAB *hashp);
+static HASHSEGMENT seg_alloc(const HTAB *hashp);
 static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx);
 static bool dir_realloc(HTAB *hashp);
 static bool expand_table(HTAB *hashp);
 static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx);
-static void hdefault(HTAB *hashp);
+static void hdefault(const HTAB *hashp);
 static int	choose_nelem_alloc(Size entrysize);
 static bool init_htab(HTAB *hashp, int64 nelem);
 pg_noreturn static void hash_corrupted(HTAB *hashp);
@@ -285,7 +285,7 @@ static int64 next_pow2_int64(int64 num);
 static int	next_pow2_int(int64 num);
 static void register_seq_scan(HTAB *hashp);
 static void deregister_seq_scan(HTAB *hashp);
-static bool has_seq_scans(HTAB *hashp);
+static bool has_seq_scans(const HTAB *hashp);
 
 
 /*
@@ -635,7 +635,7 @@ hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
  * Set default HASHHDR parameters.
  */
 static void
-hdefault(HTAB *hashp)
+hdefault(const HTAB *hashp)
 {
 	HASHHDR    *hctl = hashp->hctl;
 
@@ -912,7 +912,7 @@ get_hash_value(HTAB *hashp, const void *keyPtr)
 
 /* Convert a hash value to a bucket number */
 static inline uint32
-calc_bucket(HASHHDR *hctl, uint32 hash_val)
+calc_bucket(const HASHHDR *hctl, uint32 hash_val)
 {
 	uint32		bucket;
 
@@ -1679,7 +1679,7 @@ dir_realloc(HTAB *hashp)
 
 
 static HASHSEGMENT
-seg_alloc(HTAB *hashp)
+seg_alloc(const HTAB *hashp)
 {
 	HASHSEGMENT segp;
 
@@ -1914,7 +1914,7 @@ deregister_seq_scan(HTAB *hashp)
 
 /* Check if a table has any active scan */
 static bool
-has_seq_scans(HTAB *hashp)
+has_seq_scans(const HTAB *hashp)
 {
 	int			i;
 
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index d495ff15945..e2c98d1d8fe 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -253,7 +253,8 @@ static void reapply_stacked_values(struct config_generic *variable,
 static void free_placeholder(struct config_generic *pHolder);
 static bool validate_option_array_item(const char *name, const char *value,
 									   bool skipIfNoPermissions);
-static void write_auto_conf_file(int fd, const char *filename, ConfigVariable *head);
+static void write_auto_conf_file(int fd, const char *filename,
+								 ConfigVariable *head);
 static void replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
 									  const char *name, const char *value);
 static bool valid_custom_variable_name(const char *name);
@@ -703,7 +704,7 @@ guc_free(void *ptr)
  * Detect whether strval is referenced anywhere in a GUC string item
  */
 static bool
-string_field_used(struct config_generic *conf, char *strval)
+string_field_used(const struct config_generic *conf, const char *strval)
 {
 	if (strval == *(conf->_string.variable) ||
 		strval == conf->_string.reset_val ||
@@ -740,7 +741,7 @@ set_string_field(struct config_generic *conf, char **field, char *newval)
  * Detect whether an "extra" struct is referenced anywhere in a GUC item
  */
 static bool
-extra_field_used(struct config_generic *gconf, void *extra)
+extra_field_used(const struct config_generic *gconf, const void *extra)
 {
 	if (extra == gconf->extra)
 		return true;
@@ -5680,7 +5681,7 @@ read_nondefault_variables(void)
  * comments here and in RestoreGUCState thoroughly before changing this.
  */
 static bool
-can_skip_gucvar(struct config_generic *gconf)
+can_skip_gucvar(const struct config_generic *gconf)
 {
 	/*
 	 * We can skip GUCs that are guaranteed to have the same values in leaders
@@ -6000,7 +6001,7 @@ SerializeGUCState(Size maxsize, char *start_address)
  * to read the next string.
  */
 static char *
-read_gucstate(char **srcptr, char *srcend)
+read_gucstate(char **srcptr, const char *srcend)
 {
 	char	   *retptr = *srcptr;
 	char	   *ptr;
@@ -6023,7 +6024,7 @@ read_gucstate(char **srcptr, char *srcend)
 
 /* Binary read version of read_gucstate(). Copies into dest */
 static void
-read_gucstate_binary(char **srcptr, char *srcend, void *dest, Size size)
+read_gucstate_binary(char **srcptr, const char *srcend, void *dest, Size size)
 {
 	if (*srcptr + size > srcend)
 		elog(ERROR, "incomplete GUC state");
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..8ab4e9ad3f6 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -132,7 +132,7 @@ static FreePageBtree *FreePageBtreeFindLeftSibling(char *base,
 												   FreePageBtree *btp);
 static FreePageBtree *FreePageBtreeFindRightSibling(char *base,
 													FreePageBtree *btp);
-static Size FreePageBtreeFirstKey(FreePageBtree *btp);
+static Size FreePageBtreeFirstKey(const FreePageBtree *btp);
 static FreePageBtree *FreePageBtreeGetRecycled(FreePageManager *fpm);
 static void FreePageBtreeInsertInternal(char *base, FreePageBtree *btp,
 										Size index, Size first_page, FreePageBtree *child);
@@ -144,8 +144,9 @@ static void FreePageBtreeRemove(FreePageManager *fpm, FreePageBtree *btp,
 static void FreePageBtreeRemovePage(FreePageManager *fpm, FreePageBtree *btp);
 static void FreePageBtreeSearch(FreePageManager *fpm, Size first_page,
 								FreePageBtreeSearchResult *result);
-static Size FreePageBtreeSearchInternal(FreePageBtree *btp, Size first_page);
-static Size FreePageBtreeSearchLeaf(FreePageBtree *btp, Size first_page);
+static Size FreePageBtreeSearchInternal(const FreePageBtree *btp,
+										Size first_page);
+static Size FreePageBtreeSearchLeaf(const FreePageBtree *btp, Size first_page);
 static FreePageBtree *FreePageBtreeSplitPage(FreePageManager *fpm,
 											 FreePageBtree *btp);
 static void FreePageBtreeUpdateParentPointers(char *base, FreePageBtree *btp);
@@ -249,7 +250,8 @@ FreePageManagerGet(FreePageManager *fpm, Size npages, Size *first_page)
 
 #ifdef FPM_EXTRA_ASSERTS
 static void
-sum_free_pages_recurse(FreePageManager *fpm, FreePageBtree *btp, Size *sum)
+sum_free_pages_recurse(FreePageManager *fpm, const FreePageBtree *btp,
+					   Size *sum)
 {
 	char	   *base = fpm_segment_base(fpm);
 
@@ -860,7 +862,7 @@ FreePageBtreeFindRightSibling(char *base, FreePageBtree *btp)
  * Get the first key on a btree page.
  */
 static Size
-FreePageBtreeFirstKey(FreePageBtree *btp)
+FreePageBtreeFirstKey(const FreePageBtree *btp)
 {
 	Assert(btp->hdr.nused > 0);
 
@@ -1137,7 +1139,7 @@ FreePageBtreeSearch(FreePageManager *fpm, Size first_page,
  * of keys on the page if none.
  */
 static Size
-FreePageBtreeSearchInternal(FreePageBtree *btp, Size first_page)
+FreePageBtreeSearchInternal(const FreePageBtree *btp, Size first_page)
 {
 	Size		low = 0;
 	Size		high = btp->hdr.nused;
@@ -1167,7 +1169,7 @@ FreePageBtreeSearchInternal(FreePageBtree *btp, Size first_page)
  * of keys on the page if none.
  */
 static Size
-FreePageBtreeSearchLeaf(FreePageBtree *btp, Size first_page)
+FreePageBtreeSearchLeaf(const FreePageBtree *btp, Size first_page)
 {
 	Size		low = 0;
 	Size		high = btp->hdr.nused;
diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c
index f6203501956..83c3aa9f87d 100644
--- a/src/backend/utils/mmgr/generation.c
+++ b/src/backend/utils/mmgr/generation.c
@@ -138,7 +138,7 @@ static inline void GenerationBlockInit(GenerationContext *context,
 									   GenerationBlock *block,
 									   Size blksize);
 static inline void GenerationBlockMarkEmpty(GenerationBlock *block);
-static inline Size GenerationBlockFreeBytes(GenerationBlock *block);
+static inline Size GenerationBlockFreeBytes(const GenerationBlock *block);
 static inline void GenerationBlockFree(GenerationContext *set,
 									   GenerationBlock *block);
 
@@ -677,7 +677,7 @@ GenerationBlockMarkEmpty(GenerationBlock *block)
  *		Returns the number of bytes free in 'block'
  */
 static inline Size
-GenerationBlockFreeBytes(GenerationBlock *block)
+GenerationBlockFreeBytes(const GenerationBlock *block)
 {
 	return (block->endptr - block->freeptr);
 }
diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c
index 0bb96187603..b6154414b45 100644
--- a/src/backend/utils/mmgr/slab.c
+++ b/src/backend/utils/mmgr/slab.c
@@ -208,7 +208,7 @@ typedef struct SlabBlock
  *		number of free chunks.
  */
 static inline int32
-SlabBlocklistIndex(SlabContext *slab, int nfree)
+SlabBlocklistIndex(const SlabContext *slab, int nfree)
 {
 	int32		index;
 	int32		blocklist_shift = slab->blocklist_shift;
@@ -248,7 +248,7 @@ SlabBlocklistIndex(SlabContext *slab, int nfree)
  * blocks will eventually become completely empty so they can be free'd.
  */
 static int32
-SlabFindNextBlockListIndex(SlabContext *slab)
+SlabFindNextBlockListIndex(const SlabContext *slab)
 {
 	/* start at 1 as blocklist[0] is for full blocks. */
 	for (int i = 1; i < SLAB_BLOCKLIST_COUNT; i++)
diff --git a/src/backend/utils/sort/sharedtuplestore.c b/src/backend/utils/sort/sharedtuplestore.c
index 1dedbaa29cf..3c5a28bdfc9 100644
--- a/src/backend/utils/sort/sharedtuplestore.c
+++ b/src/backend/utils/sort/sharedtuplestore.c
@@ -92,7 +92,7 @@ struct SharedTuplestoreAccessor
 	char	   *write_end;		/* One past the end of the current chunk. */
 };
 
-static void sts_filename(char *name, SharedTuplestoreAccessor *accessor,
+static void sts_filename(char *name, const SharedTuplestoreAccessor *accessor,
 						 int participant);
 
 /*
@@ -594,7 +594,8 @@ sts_parallel_scan_next(SharedTuplestoreAccessor *accessor, void *meta_data)
  * Create the name used for the BufFile that a given participant will write.
  */
 static void
-sts_filename(char *name, SharedTuplestoreAccessor *accessor, int participant)
+sts_filename(char *name, const SharedTuplestoreAccessor *accessor,
+			 int participant)
 {
 	snprintf(name, MAXPGPATH, "%s.p%d", accessor->sts->name, participant);
 }
diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index 5d4411dc33f..058f8451632 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -468,7 +468,7 @@ static void tuplesort_sort_memtuples(Tuplesortstate *state);
 static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple);
 static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple);
 static void tuplesort_heap_delete_top(Tuplesortstate *state);
-static void reversedirection(Tuplesortstate *state);
+static void reversedirection(const Tuplesortstate *state);
 static unsigned int getlen(LogicalTape *tape, bool eofOK);
 static void markrunend(LogicalTape *tape);
 static int	worker_get_identifier(Tuplesortstate *state);
@@ -2829,7 +2829,7 @@ tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
  * It is not safe to call this when performing hash tuplesorts
  */
 static void
-reversedirection(Tuplesortstate *state)
+reversedirection(const Tuplesortstate *state)
 {
 	SortSupport sortKey = state->base.sortKeys;
 	int			nkey;
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..58e061e9dd2 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -172,7 +172,7 @@ static void scan_available_timezones(char *tzdir, char *tzdirsub,
  * Get GMT offset from a system struct tm
  */
 static int
-get_timezone_offset(struct tm *tm)
+get_timezone_offset(const struct tm *tm)
 {
 #if defined(HAVE_STRUCT_TM_TM_ZONE)
 	return tm->tm_gmtoff;
@@ -204,7 +204,7 @@ build_time_t(int year, int month, int day)
  * Does a system tm value match one we computed ourselves?
  */
 static bool
-compare_tm(struct tm *s, struct pg_tm *p)
+compare_tm(const struct tm *s, const struct pg_tm *p)
 {
 	if (s->tm_sec != p->tm_sec ||
 		s->tm_min != p->tm_min ||
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tzname, const struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..f0083b8544f 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -211,7 +211,7 @@ static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor);
 static char *GetCopyDataString(size_t r, char *copybuf, size_t *cursor);
 static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor);
 static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor);
-static void ReportCopyDataParseError(size_t r, char *copybuf);
+static void ReportCopyDataParseError(size_t r, const char *copybuf);
 static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 						   bool tablespacenum, pg_compress_specification *compress);
 static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data);
@@ -1583,7 +1583,7 @@ GetCopyDataEnd(size_t r, char *copybuf, size_t cursor)
  * can't-happen case.
  */
 static void
-ReportCopyDataParseError(size_t r, char *copybuf)
+ReportCopyDataParseError(size_t r, const char *copybuf)
 {
 	if (r == 0)
 		pg_fatal("empty COPY message");
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..7afd3578554 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -37,7 +37,8 @@ static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
 static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
 static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream,
+								const char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
 static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
@@ -991,7 +992,8 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, const char *copybuf,
+					int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
diff --git a/src/bin/pg_combinebackup/backup_label.c b/src/bin/pg_combinebackup/backup_label.c
index e774bc78a62..7b8e3daa334 100644
--- a/src/bin/pg_combinebackup/backup_label.c
+++ b/src/bin/pg_combinebackup/backup_label.c
@@ -20,7 +20,8 @@
 #include "write_manifest.h"
 
 static int	get_eol_offset(StringInfo buf);
-static bool line_starts_with(char *s, char *e, char *match, char **sout);
+static bool line_starts_with(char *s, const char *e, const char *match,
+							 char **sout);
 static bool parse_lsn(char *s, char *e, XLogRecPtr *lsn, char **c);
 static bool parse_tli(char *s, char *e, TimeLineID *tli);
 
@@ -221,7 +222,7 @@ get_eol_offset(StringInfo buf)
  * byte following the match into *sout.
  */
 static bool
-line_starts_with(char *s, char *e, char *match, char **sout)
+line_starts_with(char *s, const char *e, const char *match, char **sout)
 {
 	while (s < e && *match != '\0' && *s == *match)
 		++s, ++match;
diff --git a/src/bin/pg_combinebackup/pg_combinebackup.c b/src/bin/pg_combinebackup/pg_combinebackup.c
index c9bf0a9e105..619077a90bc 100644
--- a/src/bin/pg_combinebackup/pg_combinebackup.c
+++ b/src/bin/pg_combinebackup/pg_combinebackup.c
@@ -106,7 +106,7 @@ static StringInfo check_backup_label_files(int n_backups, char **backup_dirs);
 static uint64 check_control_files(int n_backups, char **backup_dirs);
 static void check_input_dir_permissions(char *dir);
 static void cleanup_directories_atexit(void);
-static void create_output_directory(char *dirname, cb_options *opt);
+static void create_output_directory(char *dirname, const cb_options *opt);
 static void help(const char *progname);
 static bool parse_oid(char *s, Oid *result);
 static void process_directory_recursively(Oid tsoid,
@@ -734,7 +734,7 @@ cleanup_directories_atexit(void)
  * at process exit.
  */
 static void
-create_output_directory(char *dirname, cb_options *opt)
+create_output_directory(char *dirname, const cb_options *opt)
 {
 	switch (pg_check_dir(dirname))
 	{
diff --git a/src/bin/pg_combinebackup/reconstruct.c b/src/bin/pg_combinebackup/reconstruct.c
index 38d8e8a2dc9..2fb0d964f3a 100644
--- a/src/bin/pg_combinebackup/reconstruct.c
+++ b/src/bin/pg_combinebackup/reconstruct.c
@@ -49,14 +49,14 @@ typedef struct rfile
 static void debug_reconstruction(int n_source,
 								 rfile **sources,
 								 bool dry_run);
-static unsigned find_reconstructed_block_length(rfile *s);
+static unsigned find_reconstructed_block_length(const rfile *s);
 static rfile *make_incremental_rfile(char *filename);
 static rfile *make_rfile(char *filename, bool missing_ok);
 static void write_reconstructed_file(char *input_filename,
 									 char *output_filename,
 									 unsigned block_length,
 									 rfile **sourcemap,
-									 off_t *offsetmap,
+									 const off_t *offsetmap,
 									 pg_checksum_context *checksum_ctx,
 									 CopyMethod copy_method,
 									 bool debug,
@@ -436,7 +436,7 @@ debug_reconstruction(int n_source, rfile **sources, bool dry_run)
  * necessary to include those blocks.
  */
 static unsigned
-find_reconstructed_block_length(rfile *s)
+find_reconstructed_block_length(const rfile *s)
 {
 	unsigned	block_length = s->truncation_block_length;
 	unsigned	i;
@@ -554,7 +554,7 @@ write_reconstructed_file(char *input_filename,
 						 char *output_filename,
 						 unsigned block_length,
 						 rfile **sourcemap,
-						 off_t *offsetmap,
+						 const off_t *offsetmap,
 						 pg_checksum_context *checksum_ctx,
 						 CopyMethod copy_method,
 						 bool debug,
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 0007e78667f..1813ec69034 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -84,7 +84,8 @@ static catalogid_hash *catalogIdHash = NULL;
 static void flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
 						  InhInfo *inhinfo, int numInherits);
 static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
-static void flagInhAttrs(Archive *fout, DumpOptions *dopt, TableInfo *tblinfo,
+static void flagInhAttrs(const Archive *fout, DumpOptions *dopt,
+						 TableInfo *tblinfo,
 						 int numTables);
 static int	strInArray(const char *pattern, char **arr, int arr_size);
 static IndxInfo *findIndexByOid(Oid oid);
@@ -475,7 +476,8 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
  * modifies tblinfo
  */
 static void
-flagInhAttrs(Archive *fout, DumpOptions *dopt, TableInfo *tblinfo, int numTables)
+flagInhAttrs(const Archive *fout, DumpOptions *dopt, TableInfo *tblinfo,
+			 int numTables)
 {
 	int			i,
 				j,
diff --git a/src/bin/pg_dump/compress_gzip.c b/src/bin/pg_dump/compress_gzip.c
index be31209f811..09b9e8416a5 100644
--- a/src/bin/pg_dump/compress_gzip.c
+++ b/src/bin/pg_dump/compress_gzip.c
@@ -44,7 +44,8 @@ typedef struct GzipCompressorState
 /* Private routines that support gzip compressed data I/O */
 static void DeflateCompressorInit(CompressorState *cs);
 static void DeflateCompressorEnd(ArchiveHandle *AH, CompressorState *cs);
-static void DeflateCompressorCommon(ArchiveHandle *AH, CompressorState *cs,
+static void DeflateCompressorCommon(ArchiveHandle *AH,
+									const CompressorState *cs,
 									bool flush);
 static void EndCompressorGzip(ArchiveHandle *AH, CompressorState *cs);
 static void WriteDataToArchiveGzip(ArchiveHandle *AH, CompressorState *cs,
@@ -108,7 +109,8 @@ DeflateCompressorEnd(ArchiveHandle *AH, CompressorState *cs)
 }
 
 static void
-DeflateCompressorCommon(ArchiveHandle *AH, CompressorState *cs, bool flush)
+DeflateCompressorCommon(ArchiveHandle *AH, const CompressorState *cs,
+						bool flush)
 {
 	GzipCompressorState *gzipcs = (GzipCompressorState *) cs->private_data;
 	z_streamp	zp = gzipcs->zp;
diff --git a/src/bin/pg_dump/compress_zstd.c b/src/bin/pg_dump/compress_zstd.c
index 36c1fd264ee..7dba8fc6dc2 100644
--- a/src/bin/pg_dump/compress_zstd.c
+++ b/src/bin/pg_dump/compress_zstd.c
@@ -91,7 +91,7 @@ _ZstdCStreamParams(pg_compress_specification compress)
 
 /* Helper function for WriteDataToArchiveZstd and EndCompressorZstd */
 static void
-_ZstdWriteCommon(ArchiveHandle *AH, CompressorState *cs, bool flush)
+_ZstdWriteCommon(ArchiveHandle *AH, const CompressorState *cs, bool flush)
 {
 	ZstdCompressorState *zstdcs = (ZstdCompressorState *) cs->private_data;
 	ZSTD_inBuffer *input = &zstdcs->input;
@@ -258,7 +258,8 @@ InitCompressorZstd(CompressorState *cs,
  */
 
 static size_t
-Zstd_read_internal(void *ptr, size_t size, CompressFileHandle *CFH, bool exit_on_error)
+Zstd_read_internal(void *ptr, size_t size, const CompressFileHandle *CFH,
+				   bool exit_on_error)
 {
 	ZstdCompressorState *zstdcs = (ZstdCompressorState *) CFH->private_data;
 	ZSTD_inBuffer *input = &zstdcs->input;
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index 086adcdc502..f0544d86424 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -202,7 +202,7 @@ DWORD		mainThreadId;
 #endif							/* WIN32 */
 
 /* Local function prototypes */
-static ParallelSlot *GetMyPSlot(ParallelState *pstate);
+static ParallelSlot *GetMyPSlot(const ParallelState *pstate);
 static void archive_close_connection(int code, void *arg);
 static void ShutdownWorkersHard(ParallelState *pstate);
 static void WaitForTerminatingWorkers(ParallelState *pstate);
@@ -210,8 +210,8 @@ static void set_cancel_handler(void);
 static void set_cancel_pstate(ParallelState *pstate);
 static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH);
 static void RunWorker(ArchiveHandle *AH, ParallelSlot *slot);
-static int	GetIdleWorker(ParallelState *pstate);
-static bool HasEveryWorkerTerminated(ParallelState *pstate);
+static int	GetIdleWorker(const ParallelState *pstate);
+static bool HasEveryWorkerTerminated(const ParallelState *pstate);
 static void lockTableForWorker(ArchiveHandle *AH, TocEntry *te);
 static void WaitForCommands(ArchiveHandle *AH, int pipefd[2]);
 static bool ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate,
@@ -219,9 +219,9 @@ static bool ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate,
 static char *getMessageFromLeader(int pipefd[2]);
 static void sendMessageToLeader(int pipefd[2], const char *str);
 static int	select_loop(int maxFd, fd_set *workerset);
-static char *getMessageFromWorker(ParallelState *pstate,
+static char *getMessageFromWorker(const ParallelState *pstate,
 								  bool do_wait, int *worker);
-static void sendMessageToWorker(ParallelState *pstate,
+static void sendMessageToWorker(const ParallelState *pstate,
 								int worker, const char *str);
 static char *readMessageFromPipe(int fd);
 
@@ -263,7 +263,7 @@ init_parallel_dump_utils(void)
  * Returns NULL if no matching slot is found (this implies we're the leader).
  */
 static ParallelSlot *
-GetMyPSlot(ParallelState *pstate)
+GetMyPSlot(const ParallelState *pstate)
 {
 	int			i;
 
@@ -1155,7 +1155,8 @@ parseWorkerCommand(ArchiveHandle *AH, TocEntry **te, T_Action *act,
  * The string is built in the caller-supplied buffer of size buflen.
  */
 static void
-buildWorkerResponse(ArchiveHandle *AH, TocEntry *te, T_Action act, int status,
+buildWorkerResponse(const ArchiveHandle *AH, TocEntry *te, T_Action act,
+					int status,
 					char *buf, int buflen)
 {
 	snprintf(buf, buflen, "OK %d %d %d",
@@ -1170,7 +1171,7 @@ buildWorkerResponse(ArchiveHandle *AH, TocEntry *te, T_Action act, int status,
  * Returns the integer status code, and may update fields of AH and/or te.
  */
 static int
-parseWorkerResponse(ArchiveHandle *AH, TocEntry *te,
+parseWorkerResponse(ArchiveHandle *AH, const TocEntry *te,
 					const char *msg)
 {
 	DumpId		dumpId;
@@ -1235,7 +1236,7 @@ DispatchJobForTocEntry(ArchiveHandle *AH,
  * Return NO_SLOT if none are idle.
  */
 static int
-GetIdleWorker(ParallelState *pstate)
+GetIdleWorker(const ParallelState *pstate)
 {
 	int			i;
 
@@ -1251,7 +1252,7 @@ GetIdleWorker(ParallelState *pstate)
  * Return true iff no worker is running.
  */
 static bool
-HasEveryWorkerTerminated(ParallelState *pstate)
+HasEveryWorkerTerminated(const ParallelState *pstate)
 {
 	int			i;
 
@@ -1578,7 +1579,7 @@ select_loop(int maxFd, fd_set *workerset)
  * This function is executed in the leader process.
  */
 static char *
-getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker)
+getMessageFromWorker(const ParallelState *pstate, bool do_wait, int *worker)
 {
 	int			i;
 	fd_set		workerset;
@@ -1643,7 +1644,7 @@ getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker)
  * This function is executed in the leader process.
  */
 static void
-sendMessageToWorker(ParallelState *pstate, int worker, const char *str)
+sendMessageToWorker(const ParallelState *pstate, int worker, const char *str)
 {
 	int			len = strlen(str) + 1;
 
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index 4a63f7392ae..1d77a499c92 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -82,12 +82,12 @@ static void buildTocEntryArrays(ArchiveHandle *AH);
 static void _moveBefore(TocEntry *pos, TocEntry *te);
 static int	_discoverArchiveFormat(ArchiveHandle *AH);
 
-static int	RestoringToDB(ArchiveHandle *AH);
+static int	RestoringToDB(const ArchiveHandle *AH);
 static void dump_lo_buf(ArchiveHandle *AH);
 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
 static void SetOutput(ArchiveHandle *AH, const char *filename,
 					  const pg_compress_specification compression_spec);
-static CompressFileHandle *SaveOutput(ArchiveHandle *AH);
+static CompressFileHandle *SaveOutput(const ArchiveHandle *AH);
 static void RestoreOutput(ArchiveHandle *AH, CompressFileHandle *savedOutput);
 
 static int	restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel);
@@ -97,17 +97,17 @@ static void restore_toc_entries_parallel(ArchiveHandle *AH,
 										 ParallelState *pstate,
 										 TocEntry *pending_list);
 static void restore_toc_entries_postfork(ArchiveHandle *AH,
-										 TocEntry *pending_list);
+										 const TocEntry *pending_list);
 static void pending_list_header_init(TocEntry *l);
 static void pending_list_append(TocEntry *l, TocEntry *te);
 static void pending_list_remove(TocEntry *te);
 static int	TocEntrySizeCompareQsort(const void *p1, const void *p2);
 static int	TocEntrySizeCompareBinaryheap(void *p1, void *p2, void *arg);
-static void move_to_ready_heap(TocEntry *pending_list,
+static void move_to_ready_heap(const TocEntry *pending_list,
 							   binaryheap *ready_heap,
 							   RestorePass pass);
 static TocEntry *pop_next_work_item(binaryheap *ready_heap,
-									ParallelState *pstate);
+									const ParallelState *pstate);
 static void mark_dump_job_done(ArchiveHandle *AH,
 							   TocEntry *te,
 							   int status,
@@ -117,13 +117,15 @@ static void mark_restore_job_done(ArchiveHandle *AH,
 								  int status,
 								  void *callback_data);
 static void fix_dependencies(ArchiveHandle *AH);
-static bool has_lock_conflicts(TocEntry *te1, TocEntry *te2);
-static void repoint_table_dependencies(ArchiveHandle *AH);
-static void identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te);
-static void reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
+static bool has_lock_conflicts(const TocEntry *te1, const TocEntry *te2);
+static void repoint_table_dependencies(const ArchiveHandle *AH);
+static void identify_locking_dependencies(const ArchiveHandle *AH,
+										  TocEntry *te);
+static void reduce_dependencies(const ArchiveHandle *AH, TocEntry *te,
 								binaryheap *ready_heap);
-static void mark_create_done(ArchiveHandle *AH, TocEntry *te);
-static void inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te);
+static void mark_create_done(const ArchiveHandle *AH, const TocEntry *te);
+static void inhibit_data_for_failed_table(const ArchiveHandle *AH,
+										  TocEntry *te);
 
 static void StrictNamesCheck(RestoreOptions *ropt);
 
@@ -1734,7 +1736,7 @@ SetOutput(ArchiveHandle *AH, const char *filename,
 }
 
 static CompressFileHandle *
-SaveOutput(ArchiveHandle *AH)
+SaveOutput(const ArchiveHandle *AH)
 {
 	return (CompressFileHandle *) AH->OF;
 }
@@ -1792,7 +1794,7 @@ ahprintf(ArchiveHandle *AH, const char *fmt,...)
  * Single place for logic which says 'We are restoring to a direct DB connection'.
  */
 static int
-RestoringToDB(ArchiveHandle *AH)
+RestoringToDB(const ArchiveHandle *AH)
 {
 	RestoreOptions *ropt = AH->public.ropt;
 
@@ -4561,7 +4563,7 @@ restore_toc_entries_parallel(ArchiveHandle *AH, ParallelState *pstate,
  * at least some chance of completing the restore successfully.
  */
 static void
-restore_toc_entries_postfork(ArchiveHandle *AH, TocEntry *pending_list)
+restore_toc_entries_postfork(ArchiveHandle *AH, const TocEntry *pending_list)
 {
 	RestoreOptions *ropt = AH->public.ropt;
 	TocEntry   *te;
@@ -4595,7 +4597,7 @@ restore_toc_entries_postfork(ArchiveHandle *AH, TocEntry *pending_list)
  * requires, whether or not te2's requirement is for an exclusive lock.
  */
 static bool
-has_lock_conflicts(TocEntry *te1, TocEntry *te2)
+has_lock_conflicts(const TocEntry *te1, const TocEntry *te2)
 {
 	int			j,
 				k;
@@ -4685,7 +4687,7 @@ TocEntrySizeCompareBinaryheap(void *p1, void *p2, void *arg)
  * which applies the same logic one-at-a-time.)
  */
 static void
-move_to_ready_heap(TocEntry *pending_list,
+move_to_ready_heap(const TocEntry *pending_list,
 				   binaryheap *ready_heap,
 				   RestorePass pass)
 {
@@ -4721,7 +4723,7 @@ move_to_ready_heap(TocEntry *pending_list,
  */
 static TocEntry *
 pop_next_work_item(binaryheap *ready_heap,
-				   ParallelState *pstate)
+				   const ParallelState *pstate)
 {
 	/*
 	 * Search the ready_heap until we find a suitable item.  Note that we do a
@@ -4971,7 +4973,7 @@ fix_dependencies(ArchiveHandle *AH)
  * end a restore with only one active job working on a large table.
  */
 static void
-repoint_table_dependencies(ArchiveHandle *AH)
+repoint_table_dependencies(const ArchiveHandle *AH)
 {
 	TocEntry   *te;
 	int			i;
@@ -5005,7 +5007,7 @@ repoint_table_dependencies(ArchiveHandle *AH)
  * itself).  Record their dump IDs in the entry's lockDeps[] array.
  */
 static void
-identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te)
+identify_locking_dependencies(const ArchiveHandle *AH, TocEntry *te)
 {
 	DumpId	   *lockids;
 	int			nlockids;
@@ -5069,7 +5071,7 @@ identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te)
  * becomes ready should be moved to the ready_heap, if that's provided.
  */
 static void
-reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
+reduce_dependencies(const ArchiveHandle *AH, TocEntry *te,
 					binaryheap *ready_heap)
 {
 	int			i;
@@ -5109,7 +5111,7 @@ reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
  * TABLE member
  */
 static void
-mark_create_done(ArchiveHandle *AH, TocEntry *te)
+mark_create_done(const ArchiveHandle *AH, const TocEntry *te)
 {
 	if (AH->tableDataId[te->dumpId] != 0)
 	{
@@ -5124,7 +5126,7 @@ mark_create_done(ArchiveHandle *AH, TocEntry *te)
  * as not wanted
  */
 static void
-inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
+inhibit_data_for_failed_table(const ArchiveHandle *AH, TocEntry *te)
 {
 	pg_log_info("table \"%s\" could not be created, will not restore its data",
 				te->tag);
diff --git a/src/bin/pg_dump/pg_backup_custom.c b/src/bin/pg_dump/pg_backup_custom.c
index 2226520dffc..6d9b48c88d7 100644
--- a/src/bin/pg_dump/pg_backup_custom.c
+++ b/src/bin/pg_dump/pg_backup_custom.c
@@ -85,7 +85,7 @@ typedef struct
  *------
  */
 static void _readBlockHeader(ArchiveHandle *AH, int *type, int *id);
-static pgoff_t _getFilePos(ArchiveHandle *AH, lclContext *ctx);
+static pgoff_t _getFilePos(ArchiveHandle *AH, const lclContext *ctx);
 
 static void _CustomWriteFunc(ArchiveHandle *AH, const char *buf, size_t len);
 static size_t _CustomReadFunc(ArchiveHandle *AH, char **buf, size_t *buflen);
@@ -941,7 +941,7 @@ _WorkerJobRestoreCustom(ArchiveHandle *AH, TocEntry *te)
  * data block offsets anyway.
  */
 static pgoff_t
-_getFilePos(ArchiveHandle *AH, lclContext *ctx)
+_getFilePos(ArchiveHandle *AH, const lclContext *ctx)
 {
 	pgoff_t		pos;
 
diff --git a/src/bin/pg_dump/pg_backup_directory.c b/src/bin/pg_dump/pg_backup_directory.c
index 94d401d8a4e..4d2e07c55dc 100644
--- a/src/bin/pg_dump/pg_backup_directory.c
+++ b/src/bin/pg_dump/pg_backup_directory.c
@@ -84,7 +84,7 @@ static void _StartLOs(ArchiveHandle *AH, TocEntry *te);
 static void _StartLO(ArchiveHandle *AH, TocEntry *te, Oid oid);
 static void _EndLO(ArchiveHandle *AH, TocEntry *te, Oid oid);
 static void _EndLOs(ArchiveHandle *AH, TocEntry *te);
-static void _LoadLOs(ArchiveHandle *AH, TocEntry *te);
+static void _LoadLOs(ArchiveHandle *AH, const TocEntry *te);
 
 static void _PrepParallelRestore(ArchiveHandle *AH);
 static void _Clone(ArchiveHandle *AH);
@@ -93,7 +93,7 @@ static void _DeClone(ArchiveHandle *AH);
 static int	_WorkerJobRestoreDirectory(ArchiveHandle *AH, TocEntry *te);
 static int	_WorkerJobDumpDirectory(ArchiveHandle *AH, TocEntry *te);
 
-static void setFilePath(ArchiveHandle *AH, char *buf,
+static void setFilePath(const ArchiveHandle *AH, char *buf,
 						const char *relativeFilename);
 
 /*
@@ -393,7 +393,7 @@ _PrintTocData(ArchiveHandle *AH, TocEntry *te)
 }
 
 static void
-_LoadLOs(ArchiveHandle *AH, TocEntry *te)
+_LoadLOs(ArchiveHandle *AH, const TocEntry *te)
 {
 	Oid			oid;
 	lclContext *ctx = (lclContext *) AH->formatData;
@@ -679,7 +679,7 @@ _EndLOs(ArchiveHandle *AH, TocEntry *te)
  * multithreaded on Windows.
  */
 static void
-setFilePath(ArchiveHandle *AH, char *buf, const char *relativeFilename)
+setFilePath(const ArchiveHandle *AH, char *buf, const char *relativeFilename)
 {
 	lclContext *ctx = (lclContext *) AH->formatData;
 	char	   *dname;
diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c
index b5ba3b46dd9..8403dbcb221 100644
--- a/src/bin/pg_dump/pg_backup_tar.c
+++ b/src/bin/pg_dump/pg_backup_tar.c
@@ -104,7 +104,7 @@ static char *tarGets(char *buf, size_t len, TAR_MEMBER *th);
 #endif
 static int	tarPrintf(TAR_MEMBER *th, const char *fmt,...) pg_attribute_printf(2, 3);
 
-static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th);
+static void _tarAddFile(const ArchiveHandle *AH, TAR_MEMBER *th);
 static TAR_MEMBER *_tarPositionTo(ArchiveHandle *AH, const char *filename);
 static size_t tarRead(void *buf, size_t len, TAR_MEMBER *th);
 static size_t tarWrite(const void *buf, size_t len, TAR_MEMBER *th);
@@ -1011,7 +1011,7 @@ isValidTarHeader(char *header)
 
 /* Given the member, write the TAR header & copy the file */
 static void
-_tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th)
+_tarAddFile(const ArchiveHandle *AH, TAR_MEMBER *th)
 {
 	lclContext *ctx = (lclContext *) AH->formatData;
 	FILE	   *tmp = th->tmpFH;	/* Grab it for convenience */
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 8fa04930399..72a4c3f3cee 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -73,7 +73,8 @@ static void buildShSecLabels(PGconn *conn,
 							 const char *objtype, const char *objname,
 							 PQExpBuffer buffer);
 static void executeCommand(PGconn *conn, const char *query);
-static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
+static void expand_dbname_patterns(PGconn *conn,
+								   const SimpleStringList *patterns,
 								   SimpleStringList *names);
 static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
 
@@ -1562,7 +1563,7 @@ dumpUserConfig(PGconn *conn, const char *username)
  */
 static void
 expand_dbname_patterns(PGconn *conn,
-					   SimpleStringList *patterns,
+					   const SimpleStringList *patterns,
 					   SimpleStringList *names)
 {
 	PQExpBuffer query;
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index 06c464f6ac5..ead75c8ac2c 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -34,7 +34,7 @@
 
 static void usage(const char *progname);
 
-static void perform_rewind(filemap_t *filemap, rewind_source *source,
+static void perform_rewind(const filemap_t *filemap, rewind_source *source,
 						   XLogRecPtr chkptrec,
 						   TimeLineID chkpttli,
 						   XLogRecPtr chkptredo);
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(const filemap_t *filemap, rewind_source *source,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c
index 7ce08270168..88cdf0192a3 100644
--- a/src/bin/pg_upgrade/info.c
+++ b/src/bin/pg_upgrade/info.c
@@ -26,9 +26,9 @@ static void get_db_infos(ClusterInfo *cluster);
 static char *get_rel_infos_query(void);
 static void process_rel_infos(DbInfo *dbinfo, PGresult *res, void *arg);
 static void free_rel_infos(RelInfoArr *rel_arr);
-static void print_db_infos(DbInfoArr *db_arr);
-static void print_rel_infos(RelInfoArr *rel_arr);
-static void print_slot_infos(LogicalSlotInfoArr *slot_arr);
+static void print_db_infos(const DbInfoArr *db_arr);
+static void print_rel_infos(const RelInfoArr *rel_arr);
+static void print_slot_infos(const LogicalSlotInfoArr *slot_arr);
 static char *get_old_cluster_logical_slot_infos_query(void);
 static void process_old_cluster_logical_slot_infos(DbInfo *dbinfo, PGresult *res, void *arg);
 
@@ -854,7 +854,7 @@ free_rel_infos(RelInfoArr *rel_arr)
 
 
 static void
-print_db_infos(DbInfoArr *db_arr)
+print_db_infos(const DbInfoArr *db_arr)
 {
 	int			dbnum;
 
@@ -870,7 +870,7 @@ print_db_infos(DbInfoArr *db_arr)
 
 
 static void
-print_rel_infos(RelInfoArr *rel_arr)
+print_rel_infos(const RelInfoArr *rel_arr)
 {
 	int			relnum;
 
@@ -883,7 +883,7 @@ print_rel_infos(RelInfoArr *rel_arr)
 }
 
 static void
-print_slot_infos(LogicalSlotInfoArr *slot_arr)
+print_slot_infos(const LogicalSlotInfoArr *slot_arr)
 {
 	/* Quick return if there are no logical slots. */
 	if (slot_arr->nslots == 0)
diff --git a/src/bin/pg_waldump/pg_waldump.c b/src/bin/pg_waldump/pg_waldump.c
index 1c1ccf59f65..0f49991df5e 100644
--- a/src/bin/pg_waldump/pg_waldump.c
+++ b/src/bin/pg_waldump/pg_waldump.c
@@ -623,7 +623,7 @@ XLogDumpStatsRow(const char *name,
  * Display summary statistics about the records seen so far.
  */
 static void
-XLogDumpDisplayStats(XLogDumpConfig *config, XLogStats *stats)
+XLogDumpDisplayStats(const XLogDumpConfig *config, XLogStats *stats)
 {
 	int			ri,
 				rj;
diff --git a/src/bin/pg_walsummary/pg_walsummary.c b/src/bin/pg_walsummary/pg_walsummary.c
index cd7a6b147b2..816e6a7b14f 100644
--- a/src/bin/pg_walsummary/pg_walsummary.c
+++ b/src/bin/pg_walsummary/pg_walsummary.c
@@ -36,7 +36,7 @@ typedef struct ws_file_info
 static BlockNumber *block_buffer = NULL;
 static unsigned block_buffer_size = 512;	/* Initial size. */
 
-static void dump_one_relation(ws_options *opt, RelFileLocator *rlocator,
+static void dump_one_relation(const ws_options *opt, RelFileLocator *rlocator,
 							  ForkNumber forknum, BlockNumber limit_block,
 							  BlockRefTableReader *reader);
 static void help(const char *progname);
@@ -125,7 +125,7 @@ main(int argc, char *argv[])
  * Dump details for one relation.
  */
 static void
-dump_one_relation(ws_options *opt, RelFileLocator *rlocator,
+dump_one_relation(const ws_options *opt, RelFileLocator *rlocator,
 				  ForkNumber forknum, BlockNumber limit_block,
 				  BlockRefTableReader *reader)
 {
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 45b340d3da5..b41e6911b69 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -847,7 +847,7 @@ static void free_socket_set(socket_set *sa);
 static void clear_socket_set(socket_set *sa);
 static void add_socket_to_set(socket_set *sa, int fd, int idx);
 static int	wait_on_socket_set(socket_set *sa, int64 usecs);
-static bool socket_has_input(socket_set *sa, int fd, int idx);
+static bool socket_has_input(const socket_set *sa, int fd, int idx);
 
 /* callback used to build rows for COPY during data loading */
 typedef void (*initRowMethod) (PQExpBufferData *sql, int64 curr);
@@ -1406,7 +1406,7 @@ addToSimpleStats(SimpleStats *ss, double val)
  * Merge two SimpleStats objects
  */
 static void
-mergeSimpleStats(SimpleStats *acc, SimpleStats *ss)
+mergeSimpleStats(SimpleStats *acc, const SimpleStats *ss)
 {
 	if (acc->count == 0 || ss->min < acc->min)
 		acc->min = ss->min;
@@ -1974,7 +1974,7 @@ getQueryParams(Variables *variables, const Command *command,
 }
 
 static char *
-valueTypeName(PgBenchValue *pval)
+valueTypeName(const PgBenchValue *pval)
 {
 	if (pval->type == PGBT_NO_VALUE)
 		return "none";
@@ -2016,7 +2016,7 @@ coerceToBool(PgBenchValue *pval, bool *bval)
  * Non zero numerical values are true, zero and NULL are false.
  */
 static bool
-valueTruth(PgBenchValue *pval)
+valueTruth(const PgBenchValue *pval)
 {
 	switch (pval->type)
 	{
@@ -6310,7 +6310,8 @@ addScript(const ParsedScript *script)
  * progress report.  On exit, they are updated with the new stats.
  */
 static void
-printProgressReport(TState *threads, int64 test_start, pg_time_usec_t now,
+printProgressReport(const TState *threads, int64 test_start,
+					pg_time_usec_t now,
 					StatsData *last, int64 *last_report)
 {
 	/* generate and show report */
@@ -6405,7 +6406,7 @@ printProgressReport(TState *threads, int64 test_start, pg_time_usec_t now,
 }
 
 static void
-printSimpleStats(const char *prefix, SimpleStats *ss)
+printSimpleStats(const char *prefix, const SimpleStats *ss)
 {
 	if (ss->count > 0)
 	{
@@ -7969,7 +7970,7 @@ wait_on_socket_set(socket_set *sa, int64 usecs)
 }
 
 static bool
-socket_has_input(socket_set *sa, int fd, int idx)
+socket_has_input(const socket_set *sa, int fd, int idx)
 {
 	/*
 	 * In some cases, threadRun will apply clear_socket_set and then try to
@@ -8052,7 +8053,7 @@ wait_on_socket_set(socket_set *sa, int64 usecs)
 }
 
 static bool
-socket_has_input(socket_set *sa, int fd, int idx)
+socket_has_input(const socket_set *sa, int fd, int idx)
 {
 	return (FD_ISSET(fd, &sa->fds) != 0);
 }
diff --git a/src/bin/psql/crosstabview.c b/src/bin/psql/crosstabview.c
index 3e5cd0a96d4..7dd8efb25bb 100644
--- a/src/bin/psql/crosstabview.c
+++ b/src/bin/psql/crosstabview.c
@@ -84,7 +84,7 @@ static bool printCrosstab(const PGresult *result,
 						  int field_for_data);
 static void avlInit(avl_tree *tree);
 static void avlMergeValue(avl_tree *tree, char *name, char *sort_value);
-static int	avlCollectFields(avl_tree *tree, avl_node *node,
+static int	avlCollectFields(avl_tree *tree, const avl_node *node,
 							 pivot_field *fields, int idx);
 static void avlFree(avl_tree *tree, avl_node *node);
 static void rankSort(int num_columns, pivot_field *piv_columns);
@@ -492,7 +492,7 @@ avlRotate(avl_node **current, int dir)
 }
 
 static int
-avlBalance(avl_node *n)
+avlBalance(const avl_node *n)
 {
 	return n->children[0]->height - n->children[1]->height;
 }
@@ -503,7 +503,7 @@ avlBalance(avl_node *n)
  * May update *node.
  */
 static void
-avlAdjustBalance(avl_tree *tree, avl_node **node)
+avlAdjustBalance(const avl_tree *tree, avl_node **node)
 {
 	avl_node   *current = *node;
 	int			b = avlBalance(current) / 2;
@@ -574,7 +574,8 @@ avlMergeValue(avl_tree *tree, char *name, char *sort_value)
  * fields[] must be preallocated to hold tree->count entries
  */
 static int
-avlCollectFields(avl_tree *tree, avl_node *node, pivot_field *fields, int idx)
+avlCollectFields(avl_tree *tree, const avl_node *node, pivot_field *fields,
+				 int idx)
 {
 	if (node == tree->end)
 		return idx;
diff --git a/src/bin/scripts/clusterdb.c b/src/bin/scripts/clusterdb.c
index a0aa950b784..f1a816bbcc8 100644
--- a/src/bin/scripts/clusterdb.c
+++ b/src/bin/scripts/clusterdb.c
@@ -20,7 +20,8 @@
 
 static void cluster_one_database(const ConnParams *cparams, const char *table,
 								 const char *progname, bool verbose, bool echo);
-static void cluster_all_databases(ConnParams *cparams, SimpleStringList *tables,
+static void cluster_all_databases(ConnParams *cparams,
+								  const SimpleStringList *tables,
 								  const char *progname, bool verbose, bool echo,
 								  bool quiet);
 static void help(const char *progname);
@@ -224,7 +225,7 @@ cluster_one_database(const ConnParams *cparams, const char *table,
 
 
 static void
-cluster_all_databases(ConnParams *cparams, SimpleStringList *tables,
+cluster_all_databases(ConnParams *cparams, const SimpleStringList *tables,
 					  const char *progname, bool verbose, bool echo,
 					  bool quiet)
 {
diff --git a/src/bin/scripts/reindexdb.c b/src/bin/scripts/reindexdb.c
index 8ddcc5312f7..caf32a3d74e 100644
--- a/src/bin/scripts/reindexdb.c
+++ b/src/bin/scripts/reindexdb.c
@@ -36,7 +36,7 @@ typedef enum ReindexType
 
 static SimpleStringList *get_parallel_tables_list(PGconn *conn,
 												  ReindexType type,
-												  SimpleStringList *user_list,
+												  const SimpleStringList *user_list,
 												  bool echo);
 static void get_parallel_tabidx_list(PGconn *conn,
 									 SimpleStringList *index_list,
@@ -627,7 +627,8 @@ run_reindex_command(PGconn *conn, ReindexType type, const char *name,
  */
 static SimpleStringList *
 get_parallel_tables_list(PGconn *conn, ReindexType type,
-						 SimpleStringList *user_list, bool echo)
+						 const SimpleStringList *user_list,
+						 bool echo)
 {
 	PQExpBufferData catalog_query;
 	PGresult   *res;
diff --git a/src/bin/scripts/vacuuming.c b/src/bin/scripts/vacuuming.c
index 9f44cae02ae..9133779b1ad 100644
--- a/src/bin/scripts/vacuuming.c
+++ b/src/bin/scripts/vacuuming.c
@@ -38,7 +38,7 @@ static int	vacuum_all_databases(ConnParams *cparams,
 								 const char *progname, bool echo, bool quiet);
 static SimpleStringList *retrieve_objects(PGconn *conn,
 										  vacuumingOptions *vacopts,
-										  SimpleStringList *objects,
+										  const SimpleStringList *objects,
 										  bool echo);
 static void free_retrieved_objects(SimpleStringList *list);
 static void prepare_vacuum_command(PGconn *conn, PQExpBuffer sql,
@@ -524,7 +524,7 @@ vacuum_all_databases(ConnParams *cparams,
  */
 static SimpleStringList *
 retrieve_objects(PGconn *conn, vacuumingOptions *vacopts,
-				 SimpleStringList *objects, bool echo)
+				 const SimpleStringList *objects, bool echo)
 {
 	PQExpBufferData buf;
 	PQExpBufferData catalog_query;
diff --git a/src/common/parse_manifest.c b/src/common/parse_manifest.c
index cc5fa0e5e07..6fdc2867dd6 100644
--- a/src/common/parse_manifest.c
+++ b/src/common/parse_manifest.c
@@ -118,7 +118,7 @@ pg_noreturn static void json_manifest_parse_failure(JsonManifestParseContext *co
 													char *msg);
 
 static int	hexdecode_char(char c);
-static bool hexdecode_string(uint8 *result, char *input, int nbytes);
+static bool hexdecode_string(uint8 *result, const char *input, int nbytes);
 static bool parse_xlogrecptr(XLogRecPtr *result, char *input);
 
 /*
@@ -916,7 +916,7 @@ hexdecode_char(char c)
  * Returns false if invalid characters are encountered; otherwise true.
  */
 static bool
-hexdecode_string(uint8 *result, char *input, int nbytes)
+hexdecode_string(uint8 *result, const char *input, int nbytes)
 {
 	int			i;
 
diff --git a/src/common/pg_lzcompress.c b/src/common/pg_lzcompress.c
index 86354d660fd..0f445d62451 100644
--- a/src/common/pg_lzcompress.c
+++ b/src/common/pg_lzcompress.c
@@ -396,7 +396,7 @@ do { \
  * ----------
  */
 static inline int
-pglz_find_match(int16 *hstart, const char *input, const char *end,
+pglz_find_match(const int16 *hstart, const char *input, const char *end,
 				int *lenp, int *offp, int good_match, int good_drop, int mask)
 {
 	PGLZ_HistEntry *hent;
diff --git a/src/interfaces/ecpg/ecpglib/execute.c b/src/interfaces/ecpg/ecpglib/execute.c
index bd10fef5748..8d19d2895cd 100644
--- a/src/interfaces/ecpg/ecpglib/execute.c
+++ b/src/interfaces/ecpg/ecpglib/execute.c
@@ -108,7 +108,7 @@ free_statement(struct statement *stmt)
 }
 
 static int
-next_insert(char *text, int pos, bool questionmarks, bool std_strings)
+next_insert(const char *text, int pos, bool questionmarks, bool std_strings)
 {
 	bool		string = false;
 	int			p = pos;
diff --git a/src/interfaces/ecpg/pgtypeslib/interval.c b/src/interfaces/ecpg/pgtypeslib/interval.c
index 936a6883816..f0e06c9f79d 100644
--- a/src/interfaces/ecpg/pgtypeslib/interval.c
+++ b/src/interfaces/ecpg/pgtypeslib/interval.c
@@ -969,7 +969,7 @@ interval2tm(interval span, struct tm *tm, fsec_t *fsec)
 }								/* interval2tm() */
 
 static int
-tm2interval(struct tm *tm, fsec_t fsec, interval * span)
+tm2interval(const struct tm *tm, fsec_t fsec, interval * span)
 {
 	if ((double) tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon > INT_MAX ||
 		(double) tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon < INT_MIN)
diff --git a/src/interfaces/ecpg/pgtypeslib/numeric.c b/src/interfaces/ecpg/pgtypeslib/numeric.c
index bb2a86981ca..1a63645709b 100644
--- a/src/interfaces/ecpg/pgtypeslib/numeric.c
+++ b/src/interfaces/ecpg/pgtypeslib/numeric.c
@@ -404,7 +404,7 @@ PGTYPESdecimal_free(decimal *var)
  * ----------
  */
 static int
-cmp_abs(numeric *var1, numeric *var2)
+cmp_abs(const numeric *var1, const numeric *var2)
 {
 	int			i1 = 0;
 	int			i2 = 0;
diff --git a/src/interfaces/ecpg/preproc/type.c b/src/interfaces/ecpg/preproc/type.c
index 9f6dacd2aea..e2c692665bb 100644
--- a/src/interfaces/ecpg/preproc/type.c
+++ b/src/interfaces/ecpg/preproc/type.c
@@ -212,7 +212,10 @@ static void ECPGdump_a_simple(FILE *o, const char *name, enum ECPGttype type,
 							  char *varcharsize,
 							  char *arrsize, const char *size, const char *prefix, int counter);
 static void ECPGdump_a_struct(FILE *o, const char *name, const char *ind_name, char *arrsize,
-							  struct ECPGtype *type, struct ECPGtype *ind_type, const char *prefix, const char *ind_prefix);
+							  struct ECPGtype *type,
+							  const struct ECPGtype *ind_type,
+							  const char *prefix,
+							  const char *ind_prefix);
 
 void
 ECPGdump_a_type(FILE *o, const char *name, struct ECPGtype *type, const int brace_level,
@@ -555,7 +558,9 @@ ECPGdump_a_simple(FILE *o, const char *name, enum ECPGttype type,
 
 /* Penetrate a struct and dump the contents. */
 static void
-ECPGdump_a_struct(FILE *o, const char *name, const char *ind_name, char *arrsize, struct ECPGtype *type, struct ECPGtype *ind_type, const char *prefix, const char *ind_prefix)
+ECPGdump_a_struct(FILE *o, const char *name, const char *ind_name, char *arrsize, struct ECPGtype *type,
+				  const struct ECPGtype *ind_type, const char *prefix,
+				  const char *ind_prefix)
 {
 	/*
 	 * If offset is NULL, then this is the first recursive level. If not then
diff --git a/src/interfaces/libpq/fe-print.c b/src/interfaces/libpq/fe-print.c
index fc153bee630..5cddbfe7cea 100644
--- a/src/interfaces/libpq/fe-print.c
+++ b/src/interfaces/libpq/fe-print.c
@@ -41,14 +41,18 @@
 static bool do_field(const PQprintOpt *po, const PGresult *res,
 					 const int i, const int j, const int fs_len,
 					 char **fields,
-					 const int nFields, const char **fieldNames,
+					 const int nFields,
+					 const char **fieldNames,
 					 unsigned char *fieldNotNum, int *fieldMax,
 					 const int fieldMaxLen, FILE *fout);
 static char *do_header(FILE *fout, const PQprintOpt *po, const int nFields,
-					   int *fieldMax, const char **fieldNames, unsigned char *fieldNotNum,
+					   int *fieldMax,
+					   const char **fieldNames,
+					   const unsigned char *fieldNotNum,
 					   const int fs_len, const PGresult *res);
 static void output_row(FILE *fout, const PQprintOpt *po, const int nFields, char **fields,
-					   unsigned char *fieldNotNum, int *fieldMax, char *border,
+					   const unsigned char *fieldNotNum,
+					   const int *fieldMax, char *border,
 					   const int row_index);
 static void fill(int length, int max, char filler, FILE *fp);
 
@@ -341,7 +345,7 @@ static bool
 do_field(const PQprintOpt *po, const PGresult *res,
 		 const int i, const int j, const int fs_len,
 		 char **fields,
-		 const int nFields, char const **fieldNames,
+		 const int nFields, const char **fieldNames,
 		 unsigned char *fieldNotNum, int *fieldMax,
 		 const int fieldMaxLen, FILE *fout)
 {
@@ -454,7 +458,8 @@ do_field(const PQprintOpt *po, const PGresult *res,
 
 static char *
 do_header(FILE *fout, const PQprintOpt *po, const int nFields, int *fieldMax,
-		  const char **fieldNames, unsigned char *fieldNotNum,
+		  const char **fieldNames,
+		  const unsigned char *fieldNotNum,
 		  const int fs_len, const PGresult *res)
 {
 	int			j;				/* for loop index */
@@ -560,7 +565,8 @@ overflow:
 
 static void
 output_row(FILE *fout, const PQprintOpt *po, const int nFields, char **fields,
-		   unsigned char *fieldNotNum, int *fieldMax, char *border,
+		   const unsigned char *fieldNotNum, const int *fieldMax,
+		   char *border,
 		   const int row_index)
 {
 	int			field_index;	/* for loop index */
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index 02eced3b2c5..fea78648b76 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -1761,7 +1761,7 @@ plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
 
 /* Construct the modified new tuple to be returned from a trigger. */
 static HeapTuple
-plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
+plperl_modify_tuple(HV *hvTD, const TriggerData *tdata, HeapTuple otup)
 {
 	dTHX;
 	SV		  **svp;
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 63598aba8a8..2fd17d34d88 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -280,15 +280,15 @@ static int	exec_toplevel_block(PLpgSQL_execstate *estate,
 static int	exec_stmt_block(PLpgSQL_execstate *estate,
 							PLpgSQL_stmt_block *block);
 static int	exec_stmts(PLpgSQL_execstate *estate,
-					   List *stmts);
+					   const List *stmts);
 static int	exec_stmt_assign(PLpgSQL_execstate *estate,
 							 PLpgSQL_stmt_assign *stmt);
 static int	exec_stmt_perform(PLpgSQL_execstate *estate,
-							  PLpgSQL_stmt_perform *stmt);
+							  const PLpgSQL_stmt_perform *stmt);
 static int	exec_stmt_call(PLpgSQL_execstate *estate,
 						   PLpgSQL_stmt_call *stmt);
 static int	exec_stmt_getdiag(PLpgSQL_execstate *estate,
-							  PLpgSQL_stmt_getdiag *stmt);
+							  const PLpgSQL_stmt_getdiag *stmt);
 static int	exec_stmt_if(PLpgSQL_execstate *estate,
 						 PLpgSQL_stmt_if *stmt);
 static int	exec_stmt_case(PLpgSQL_execstate *estate,
@@ -310,7 +310,7 @@ static int	exec_stmt_open(PLpgSQL_execstate *estate,
 static int	exec_stmt_fetch(PLpgSQL_execstate *estate,
 							PLpgSQL_stmt_fetch *stmt);
 static int	exec_stmt_close(PLpgSQL_execstate *estate,
-							PLpgSQL_stmt_close *stmt);
+							const PLpgSQL_stmt_close *stmt);
 static int	exec_stmt_exit(PLpgSQL_execstate *estate,
 						   PLpgSQL_stmt_exit *stmt);
 static int	exec_stmt_return(PLpgSQL_execstate *estate,
@@ -330,9 +330,9 @@ static int	exec_stmt_dynexecute(PLpgSQL_execstate *estate,
 static int	exec_stmt_dynfors(PLpgSQL_execstate *estate,
 							  PLpgSQL_stmt_dynfors *stmt);
 static int	exec_stmt_commit(PLpgSQL_execstate *estate,
-							 PLpgSQL_stmt_commit *stmt);
+							 const PLpgSQL_stmt_commit *stmt);
 static int	exec_stmt_rollback(PLpgSQL_execstate *estate,
-							   PLpgSQL_stmt_rollback *stmt);
+							   const PLpgSQL_stmt_rollback *stmt);
 
 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
 								 PLpgSQL_function *func,
@@ -388,7 +388,7 @@ static int	exec_run_select(PLpgSQL_execstate *estate,
 							PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
 static int	exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
 						   Portal portal, bool prefetch_ok);
-static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
+static ParamListInfo setup_param_list(const PLpgSQL_execstate *estate,
 									  PLpgSQL_expr *expr);
 static ParamExternData *plpgsql_param_fetch(ParamListInfo params,
 											int paramid, bool speculative,
@@ -425,7 +425,7 @@ static void exec_move_row_from_fields(PLpgSQL_execstate *estate,
 									  TupleDesc tupdesc);
 static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc);
 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
-									 PLpgSQL_row *row,
+									 const PLpgSQL_row *row,
 									 TupleDesc tupdesc);
 static TupleDesc deconstruct_composite_datum(Datum value,
 											 HeapTupleData *tmptup);
@@ -1591,7 +1591,7 @@ pop_stmt_mcontext(PLpgSQL_execstate *estate)
  * match the current exception?
  */
 static bool
-exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
+exception_matches_conditions(ErrorData *edata, const PLpgSQL_condition *cond)
 {
 	for (; cond != NULL; cond = cond->next)
 	{
@@ -1992,7 +1992,7 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
  * ----------
  */
 static int
-exec_stmts(PLpgSQL_execstate *estate, List *stmts)
+exec_stmts(PLpgSQL_execstate *estate, const List *stmts)
 {
 	PLpgSQL_stmt *save_estmt = estate->err_stmt;
 	ListCell   *s;
@@ -2176,7 +2176,7 @@ exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
  * ----------
  */
 static int
-exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
+exec_stmt_perform(PLpgSQL_execstate *estate, const PLpgSQL_stmt_perform *stmt)
 {
 	PLpgSQL_expr *expr = stmt->expr;
 
@@ -2406,7 +2406,7 @@ make_callstmt_target(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
  * ----------
  */
 static int
-exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
+exec_stmt_getdiag(PLpgSQL_execstate *estate, const PLpgSQL_stmt_getdiag *stmt)
 {
 	ListCell   *lc;
 
@@ -4923,7 +4923,7 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
  * ----------
  */
 static int
-exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
+exec_stmt_close(PLpgSQL_execstate *estate, const PLpgSQL_stmt_close *stmt)
 {
 	PLpgSQL_var *curvar;
 	Portal		portal;
@@ -4966,7 +4966,7 @@ exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
  * Commit the transaction.
  */
 static int
-exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
+exec_stmt_commit(PLpgSQL_execstate *estate, const PLpgSQL_stmt_commit *stmt)
 {
 	if (stmt->chain)
 		SPI_commit_and_chain();
@@ -4990,7 +4990,8 @@ exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
  * Abort the transaction.
  */
 static int
-exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
+exec_stmt_rollback(PLpgSQL_execstate *estate,
+				   const PLpgSQL_stmt_rollback *stmt)
 {
 	if (stmt->chain)
 		SPI_rollback_and_chain();
@@ -6260,7 +6261,7 @@ exec_eval_simple_expr(PLpgSQL_execstate *estate,
  * that seems like a waste of memory.)
  */
 static ParamListInfo
-setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
+setup_param_list(const PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
 {
 	ParamListInfo paramLI;
 
@@ -7502,7 +7503,7 @@ compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
  */
 static HeapTuple
 make_tuple_from_row(PLpgSQL_execstate *estate,
-					PLpgSQL_row *row,
+					const PLpgSQL_row *row,
 					TupleDesc tupdesc)
 {
 	int			natts = tupdesc->natts;
diff --git a/src/pl/plpgsql/src/pl_funcs.c b/src/pl/plpgsql/src/pl_funcs.c
index bc7a61feb4d..d9eca96f2b3 100644
--- a/src/pl/plpgsql/src/pl_funcs.c
+++ b/src/pl/plpgsql/src/pl_funcs.c
@@ -811,8 +811,8 @@ static void dump_cursor_direction(PLpgSQL_stmt_fetch *stmt);
 static void dump_close(PLpgSQL_stmt_close *stmt);
 static void dump_perform(PLpgSQL_stmt_perform *stmt);
 static void dump_call(PLpgSQL_stmt_call *stmt);
-static void dump_commit(PLpgSQL_stmt_commit *stmt);
-static void dump_rollback(PLpgSQL_stmt_rollback *stmt);
+static void dump_commit(const PLpgSQL_stmt_commit *stmt);
+static void dump_rollback(const PLpgSQL_stmt_rollback *stmt);
 static void dump_expr(PLpgSQL_expr *expr);
 
 
@@ -919,7 +919,7 @@ dump_stmt(PLpgSQL_stmt *stmt)
 }
 
 static void
-dump_stmts(List *stmts)
+dump_stmts(const List *stmts)
 {
 	ListCell   *s;
 
@@ -1294,7 +1294,7 @@ dump_call(PLpgSQL_stmt_call *stmt)
 }
 
 static void
-dump_commit(PLpgSQL_stmt_commit *stmt)
+dump_commit(const PLpgSQL_stmt_commit *stmt)
 {
 	dump_ind();
 	if (stmt->chain)
@@ -1304,7 +1304,7 @@ dump_commit(PLpgSQL_stmt_commit *stmt)
 }
 
 static void
-dump_rollback(PLpgSQL_stmt_rollback *stmt)
+dump_rollback(const PLpgSQL_stmt_rollback *stmt)
 {
 	dump_ind();
 	if (stmt->chain)
diff --git a/src/pl/plpgsql/src/pl_scanner.c b/src/pl/plpgsql/src/pl_scanner.c
index 19825e5c718..91239d0d6e3 100644
--- a/src/pl/plpgsql/src/pl_scanner.c
+++ b/src/pl/plpgsql/src/pl_scanner.c
@@ -130,7 +130,8 @@ struct plpgsql_yy_extra_type
 
 /* Internal functions */
 static int	internal_yylex(TokenAuxData *auxdata, yyscan_t yyscanner);
-static void push_back_token(int token, TokenAuxData *auxdata, yyscan_t yyscanner);
+static void push_back_token(int token, const TokenAuxData *auxdata,
+							yyscan_t yyscanner);
 static void location_lineno_init(yyscan_t yyscanner);
 
 /*
@@ -382,7 +383,7 @@ internal_yylex(TokenAuxData *auxdata, yyscan_t yyscanner)
  * Push back a token to be re-read by next internal_yylex() call.
  */
 static void
-push_back_token(int token, TokenAuxData *auxdata, yyscan_t yyscanner)
+push_back_token(int token, const TokenAuxData *auxdata, yyscan_t yyscanner)
 {
 	if (yyextra->num_pushbacks >= MAX_PUSHBACKS)
 		elog(ERROR, "too many tokens pushed back");
diff --git a/src/pl/plpython/plpy_exec.c b/src/pl/plpython/plpy_exec.c
index 0117f1e77ef..521bf08992e 100644
--- a/src/pl/plpython/plpy_exec.c
+++ b/src/pl/plpython/plpy_exec.c
@@ -41,7 +41,7 @@ static void plpython_return_error_callback(void *arg);
 
 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc,
 										HeapTuple *rv);
-static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd,
+static HeapTuple PLy_modify_tuple(const PLyProcedure *proc, PyObject *pltd,
 								  TriggerData *tdata, HeapTuple otup);
 static void plpython_trigger_error_callback(void *arg);
 
@@ -959,7 +959,7 @@ PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *r
  * Apply changes requested by a MODIFY return from a trigger function.
  */
 static HeapTuple
-PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
+PLy_modify_tuple(const PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
 				 HeapTuple otup)
 {
 	HeapTuple	rtup;
diff --git a/src/pl/plpython/plpy_typeio.c b/src/pl/plpython/plpy_typeio.c
index 1f69109b081..c1da5f61ecf 100644
--- a/src/pl/plpython/plpy_typeio.c
+++ b/src/pl/plpython/plpy_typeio.c
@@ -37,7 +37,8 @@ static PyObject *PLyList_FromArray(PLyDatumToOb *arg, Datum d);
 static PyObject *PLyList_FromArray_recurse(PLyDatumToOb *elm, int *dims, int ndim, int dim,
 										   char **dataptr_p, bits8 **bitmap_p, int *bitmask_p);
 static PyObject *PLyDict_FromComposite(PLyDatumToOb *arg, Datum d);
-static PyObject *PLyDict_FromTuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc, bool include_generated);
+static PyObject *PLyDict_FromTuple(const PLyDatumToOb *arg, HeapTuple tuple,
+								   TupleDesc desc, bool include_generated);
 
 /* conversion from Python objects to Datums */
 static Datum PLyObject_ToBool(PLyObToDatum *arg, PyObject *plrv,
@@ -61,9 +62,13 @@ static void PLySequence_ToArray_recurse(PyObject *obj,
 
 /* conversion from Python objects to composite Datums */
 static Datum PLyUnicode_ToComposite(PLyObToDatum *arg, PyObject *string, bool inarray);
-static Datum PLyMapping_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *mapping);
-static Datum PLySequence_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *sequence);
-static Datum PLyGenericObject_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *object, bool inarray);
+static Datum PLyMapping_ToComposite(const PLyObToDatum *arg, TupleDesc desc,
+									PyObject *mapping);
+static Datum PLySequence_ToComposite(const PLyObToDatum *arg, TupleDesc desc,
+									 PyObject *sequence);
+static Datum PLyGenericObject_ToComposite(const PLyObToDatum *arg,
+										  TupleDesc desc, PyObject *object,
+										  bool inarray);
 
 
 /*
@@ -812,7 +817,8 @@ PLyDict_FromComposite(PLyDatumToOb *arg, Datum d)
  * Transform a tuple into a Python dict object.
  */
 static PyObject *
-PLyDict_FromTuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc, bool include_generated)
+PLyDict_FromTuple(const PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc,
+				  bool include_generated)
 {
 	PyObject   *volatile dict;
 
@@ -1342,7 +1348,8 @@ PLyUnicode_ToComposite(PLyObToDatum *arg, PyObject *string, bool inarray)
 
 
 static Datum
-PLyMapping_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *mapping)
+PLyMapping_ToComposite(const PLyObToDatum *arg, TupleDesc desc,
+					   PyObject *mapping)
 {
 	Datum		result;
 	HeapTuple	tuple;
@@ -1407,7 +1414,8 @@ PLyMapping_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *mapping)
 
 
 static Datum
-PLySequence_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *sequence)
+PLySequence_ToComposite(const PLyObToDatum *arg, TupleDesc desc,
+						PyObject *sequence)
 {
 	Datum		result;
 	HeapTuple	tuple;
@@ -1484,7 +1492,8 @@ PLySequence_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *sequence)
 
 
 static Datum
-PLyGenericObject_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *object, bool inarray)
+PLyGenericObject_ToComposite(const PLyObToDatum *arg, TupleDesc desc,
+							 PyObject *object, bool inarray)
 {
 	Datum		result;
 	HeapTuple	tuple;
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 187698ccdd2..73957f7c229 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -335,7 +335,7 @@ static void pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname,
 static Tcl_Obj *pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
 static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp,
 										  Tcl_Obj **kvObjv, int kvObjc,
-										  pltcl_call_state *call_state);
+										  const pltcl_call_state *call_state);
 static void pltcl_init_tuple_store(pltcl_call_state *call_state);
 
 
@@ -3265,7 +3265,7 @@ pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_gene
  **********************************************************************/
 static HeapTuple
 pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc,
-						 pltcl_call_state *call_state)
+						 const pltcl_call_state *call_state)
 {
 	HeapTuple	tuple;
 	TupleDesc	tupdesc;
diff --git a/src/test/modules/injection_points/injection_points.c b/src/test/modules/injection_points/injection_points.c
index 417b61f31c5..50fa3af9d14 100644
--- a/src/test/modules/injection_points/injection_points.c
+++ b/src/test/modules/injection_points/injection_points.c
@@ -189,7 +189,7 @@ injection_init_shmem(void)
  * otherwise.
  */
 static bool
-injection_point_allowed(InjectionPointCondition *condition)
+injection_point_allowed(const InjectionPointCondition *condition)
 {
 	bool		result = true;
 
diff --git a/src/test/modules/libpq_pipeline/libpq_pipeline.c b/src/test/modules/libpq_pipeline/libpq_pipeline.c
index b3af70fa09b..5bb353968ea 100644
--- a/src/test/modules/libpq_pipeline/libpq_pipeline.c
+++ b/src/test/modules/libpq_pipeline/libpq_pipeline.c
@@ -165,7 +165,8 @@ consume_query_cancel_impl(int line, PGconn *conn)
  */
 static void
 wait_for_connection_state(int line, PGconn *monitorConn, int procpid,
-						  char *state, char *event)
+						  const char *state,
+						  const char *event)
 {
 	const Oid	paramTypes[] = {INT4OID, TEXTOID};
 	const char *paramValues[2];
diff --git a/src/test/modules/test_radixtree/test_radixtree.c b/src/test/modules/test_radixtree/test_radixtree.c
index 031e8737d45..b37e6af3d6f 100644
--- a/src/test/modules/test_radixtree/test_radixtree.c
+++ b/src/test/modules/test_radixtree/test_radixtree.c
@@ -108,7 +108,7 @@ static rt_node_class_test_elem rt_node_class_tests[] =
  * Return the number of keys in the radix tree.
  */
 static uint64
-rt_num_entries(rt_radix_tree *tree)
+rt_num_entries(const rt_radix_tree *tree)
 {
 	return tree->ctl->num_keys;
 }
diff --git a/src/test/modules/test_regex/test_regex.c b/src/test/modules/test_regex/test_regex.c
index 32ff9b13d8f..a8de213726a 100644
--- a/src/test/modules/test_regex/test_regex.c
+++ b/src/test/modules/test_regex/test_regex.c
@@ -62,8 +62,8 @@ static test_regex_ctx *setup_test_matches(text *orig_str,
 										  test_re_flags *re_flags,
 										  Oid collation,
 										  bool use_subpatterns);
-static ArrayType *build_test_info_result(regex_t *cpattern,
-										 test_re_flags *flags);
+static ArrayType *build_test_info_result(const regex_t *cpattern,
+										 const test_re_flags *flags);
 static ArrayType *build_test_match_result(test_regex_ctx *matchctx);
 
 
@@ -612,7 +612,7 @@ setup_test_matches(text *orig_str,
  * This borrows some code from Tcl's TclRegAbout().
  */
 static ArrayType *
-build_test_info_result(regex_t *cpattern, test_re_flags *flags)
+build_test_info_result(const regex_t *cpattern, const test_re_flags *flags)
 {
 	/* Translation data for flag bits in regex_t.re_info */
 	struct infoname
diff --git a/src/test/modules/test_resowner/test_resowner_many.c b/src/test/modules/test_resowner/test_resowner_many.c
index e43f911244a..40c5a2d83fb 100644
--- a/src/test/modules/test_resowner/test_resowner_many.c
+++ b/src/test/modules/test_resowner/test_resowner_many.c
@@ -60,7 +60,8 @@ static void RememberManyTestResources(ResourceOwner owner,
 static void ForgetManyTestResources(ResourceOwner owner,
 									ManyTestResourceKind *kinds, int nkinds,
 									int nresources);
-static int	GetTotalResourceCount(ManyTestResourceKind *kinds, int nkinds);
+static int	GetTotalResourceCount(const ManyTestResourceKind *kinds,
+								  int nkinds);
 
 /* ResourceOwner callback */
 static void
@@ -181,7 +182,7 @@ ForgetManyTestResources(ResourceOwner owner,
  * Get total number of currently active resources among 'kinds'.
  */
 static int
-GetTotalResourceCount(ManyTestResourceKind *kinds, int nkinds)
+GetTotalResourceCount(const ManyTestResourceKind *kinds, int nkinds)
 {
 	int			ntotal = 0;
 
diff --git a/src/test/modules/test_shm_mq/setup.c b/src/test/modules/test_shm_mq/setup.c
index 2a20ffb1273..da87f2cf41b 100644
--- a/src/test/modules/test_shm_mq/setup.c
+++ b/src/test/modules/test_shm_mq/setup.c
@@ -37,7 +37,7 @@ static worker_state *setup_background_workers(int nworkers,
 static void cleanup_background_workers(dsm_segment *seg, Datum arg);
 static void wait_for_workers_to_become_ready(worker_state *wstate,
 											 volatile test_shm_mq_header *hdr);
-static bool check_worker_status(worker_state *wstate);
+static bool check_worker_status(const worker_state *wstate);
 
 /* value cached, fetched from shared memory */
 static uint32 we_bgworker_startup = 0;
@@ -302,7 +302,7 @@ wait_for_workers_to_become_ready(worker_state *wstate,
 }
 
 static bool
-check_worker_status(worker_state *wstate)
+check_worker_status(const worker_state *wstate)
 {
 	int			n;
 
diff --git a/src/test/modules/test_shm_mq/test.c b/src/test/modules/test_shm_mq/test.c
index 443281addd0..b039042a404 100644
--- a/src/test/modules/test_shm_mq/test.c
+++ b/src/test/modules/test_shm_mq/test.c
@@ -25,8 +25,8 @@ PG_MODULE_MAGIC;
 PG_FUNCTION_INFO_V1(test_shm_mq);
 PG_FUNCTION_INFO_V1(test_shm_mq_pipelined);
 
-static void verify_message(Size origlen, char *origdata, Size newlen,
-						   char *newdata);
+static void verify_message(Size origlen, const char *origdata, Size newlen,
+						   const char *newdata);
 
 /* value cached, fetched from shared memory */
 static uint32 we_message_queue = 0;
@@ -255,7 +255,8 @@ test_shm_mq_pipelined(PG_FUNCTION_ARGS)
  * Verify that two messages are the same.
  */
 static void
-verify_message(Size origlen, char *origdata, Size newlen, char *newdata)
+verify_message(Size origlen, const char *origdata, Size newlen,
+			   const char *newdata)
 {
 	Size		i;
 
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index c27305cf10b..a4528cd7a36 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -80,7 +80,8 @@
 #define RDELIM			')'
 #define DELIM			','
 
-static void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
+static void regress_lseg_construct(LSEG *lseg, const Point *pt1,
+								   const Point *pt2);
 
 PG_MODULE_MAGIC_EXT(
 					.name = "regress",
@@ -133,7 +134,7 @@ interpt_pp(PG_FUNCTION_ARGS)
 
 /* like lseg_construct, but assume space already allocated */
 static void
-regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2)
+regress_lseg_construct(LSEG *lseg, const Point *pt1, const Point *pt2)
 {
 	lseg->p[0].x = pt1->x;
 	lseg->p[0].y = pt1->y;
-- 
2.34.1

