Subject: Add support for __attribute__((returns_nonnull))

From: "Tristan Partin" <[email-masked]>
Date: Tue, 19 Dec 2023 14:43:49 -0600

Here is a patch which adds support for the returns_nonnull attribute 
alongside all the other attributes we optionally support.

I recently wound up in a situation where I was checking for NULL return 
values of a function that couldn't ever return NULL because the 
inability to allocate memory was always elog(ERROR)ed (aborted).

I didn't go through and mark anything, but I feel like it could be 
useful for people going forward, including myself.

-- 
Tristan Partin
Neon (https://neon.tech)
From 15a36d68519b332e7ae970708399744cbc69c6c3 Mon Sep 17 00:00:00 2001
From: Tristan Partin <[email-masked]>
Date: Tue, 19 Dec 2023 14:39:03 -0600
Subject: [PATCH v1] Add support for __attribute__((returns_nonnull))

Allows for marking functions that can't possibly return NULL, like those
that always elog(ERROR) for instance in the case of failures.
---
 src/include/c.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 26bf7ec16e..e3a127f954 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -285,6 +285,18 @@
 #define pg_unreachable() abort()
 #endif
 
+/*
+ * Place on functions which return a pointer but can't return NULL. When used,
+ * it can allow the compiler to warn if a NULL check occurs in the parent
+ * function because that NULL check would always fail. It is also an opportunity
+ * to help the compiler with optimizations.
+ */
+#if __has_attribute (returns_nonnull)
+#define pg_returns_nonnull __attribute__((returns_nonnull))
+#else
+#define pg_returns_nonnull
+#endif
+
 /*
  * Hints to the compiler about the likelihood of a branch. Both likely() and
  * unlikely() return the boolean value of the contained expression.
-- 
Tristan Partin
Neon (https://neon.tech)