diff mbox series

[v2,2/3] bpf: CO-RE consumer of deferred constants

Message ID 20261105055645.286266-1-yjn@yjn-systems.com
State New
Headers show
Series Preserve semantic origins through C constant folding | expand

Commit Message

York Jasper Niebuhr Nov. 5, 2026, 5:56 a.m. UTC
This patch integrates deferred constant expressions into the BPF CO-RE
implementation.

When supported by the frontend, the BPF target marks enumeration types
and record types carrying the preserve_access_index attribute for
constant deferral.

For __builtin_preserve_enum_value, the originating CONST_DECL of a
deferred enumerator is recovered from the deferred constant expression.
The existing enum value mapping mechanism is retained as a fallback for
frontends without deferred enum support.

The BPF CO-RE lowering pass is extended to process deferred constants in
GIMPLE.  Deferred field offsets belonging to preserve_accedd_index
record types are converted into CO-RE relocations.  This explicitly
includes expressions using __builtin_offsetof or old-school offsetof
paradigms.  Deferred constants that do not require relocations are
resolved to their ordinary values.

A resolver callback handles deferred constants that require earlier
processing by the frontend.  A new IPA pass also resolves deferred
constants in static initializers before the generic deferred constant
barrier. CO-RE field-offset relocations in static initializers are
currently diagnosed as unsupported.

Two tests exercise automatic field-offset relocations and the resolution
of deferred constants that do not require CO-RE relocations.

gcc/ChangeLog:

	* config/bpf/bpf-passes.def: Register the BPF deferred static
	initializer pass.
	* config/bpf/bpf-protos.h (make_pass_bpf_deferred_static):
	Declare.
	* config/bpf/core-builtins.cc (has_deferred_cst_enum): New
	function.
	(has_deferred_cst_offsetof): Likewise.
	(is_attr_preserve_access_field): Likewise.
	(deferred_enum_value_call_p): Likewise.
	(enum_decl_from_deferred_call): Likewise.
	(deferred_field_offset_call_p): Likewise.
	(field_decl_from_deferred_call): Likewise.
	(deferred_cst_canonical_enum_value_decl): Likewise.
	(pack_enum_value): Recover enum declarations from deferred
	constants when supported by the frontend.
	(read_kind): Handle deferred enum constants.
	(bpf_handle_plugin_finish_type): Mark supported types for
	constant deferral.
	(bpf_init_core_builtins): Register the deferred constant
	resolver.
	(construct_core_reloc_from_data): New function.
	(construct_builtin_core_reloc): Use it.
	(bpf_core_field_offset_reloc): New function.
	(bpf_deferred_mode): New enumeration.
	(bpf_lower_deferred_inner): New function.
	(bpf_lower_deferred_wrapper): Likewise.
	(bpf_deferred_cst_resolver): Likewise.
	(bpf_lower_deferred_tree): Likewise.
	(bpf_initializer_has_deferred): Likewise.
	(bpf_transform_initializer): Likewise.
	(execute_lower_bpf_core): Lower deferred constants in GIMPLE.
	(execute_bpf_deferred_static): New function.
	(pass_data_bpf_deferred_static): New pass data.
	(pass_bpf_deferred_static): New pass.
	(make_pass_bpf_deferred_static): New function.

gcc/testsuite/ChangeLog:

	* gcc.target/bpf/core-auto-drain-1.c: New test.
	* gcc.target/bpf/core-auto-field-offset-1.c: New test.

Signed-off-by: York Jasper Niebuhr <yjn@yjn-systems.com>
---
 gcc/config/bpf/bpf-passes.def                 |   1 +
 gcc/config/bpf/bpf-protos.h                   |   3 +
 gcc/config/bpf/core-builtins.cc               | 677 ++++++++++++++++--
 .../gcc.target/bpf/core-auto-drain-1.c        |  41 ++
 .../gcc.target/bpf/core-auto-field-offset-1.c |  40 ++
 5 files changed, 718 insertions(+), 44 deletions(-)
 create mode 100644 gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
 create mode 100644 gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c
diff mbox series

Patch

diff --git a/gcc/config/bpf/bpf-passes.def b/gcc/config/bpf/bpf-passes.def
index eb0e9837d3a..eb0507fbec0 100644
--- a/gcc/config/bpf/bpf-passes.def
+++ b/gcc/config/bpf/bpf-passes.def
@@ -18,3 +18,4 @@ 
    <http://www.gnu.org/licenses/>.  */
 
 INSERT_PASS_BEFORE (pass_lower_omp, 1, pass_lower_bpf_core);
+INSERT_PASS_BEFORE (pass_deferred_cst_barrier, 1, pass_bpf_deferred_static);
diff --git a/gcc/config/bpf/bpf-protos.h b/gcc/config/bpf/bpf-protos.h
index eee260b799b..db1e379577b 100644
--- a/gcc/config/bpf/bpf-protos.h
+++ b/gcc/config/bpf/bpf-protos.h
@@ -36,6 +36,9 @@  const char *bpf_output_move (rtx *operands, const char *templ);
 class gimple_opt_pass;
 gimple_opt_pass *make_pass_lower_bpf_core (gcc::context *ctxt);
 
+class simple_ipa_opt_pass;
+simple_ipa_opt_pass *make_pass_bpf_deferred_static (gcc::context *ctxt);
+
 bool bpf_expand_cpymem (rtx *, bool);
 bool bpf_expand_setmem (rtx *);
 
diff --git a/gcc/config/bpf/core-builtins.cc b/gcc/config/bpf/core-builtins.cc
index a5c973cd385..cbdfcc6ffce 100644
--- a/gcc/config/bpf/core-builtins.cc
+++ b/gcc/config/bpf/core-builtins.cc
@@ -42,6 +42,9 @@  along with GCC; see the file COPYING3.  If not see
 #include "tree-pass.h"
 #include "plugin.h"
 #include "gimplify.h"
+#include "gimplify-me.h"
+#include "cgraph.h"
+#include "deferred-cst.h"
 
 #include "ctfc.h"
 #include "btf.h"
@@ -283,6 +286,24 @@  compare_same_ptr_type (struct cr_builtins *a, struct cr_builtins *b)
   return compare_same_kind (a, b) && a->type == b->type;
 }
 
+/* Frontend capability check for deferred constants.  Returns true if
+   the current frontend seeds deferred constants for enum values.  */
+
+static inline bool
+has_deferred_cst_enum ()
+{
+  return lang_hooks.deferred_cst_capabilities & DEFERRED_CST_CAP_ENUM;
+}
+
+/* Frontend capability check for deferred constants.  Returns true if
+   the current frontend seeds deferred constants for offsetof expressions.  */
+
+static inline bool
+has_deferred_cst_offsetof ()
+{
+  return lang_hooks.deferred_cst_capabilities & DEFERRED_CST_CAP_OFFSETOF;
+}
+
 /* Handling for __attribute__((preserve_access_index)) for BPF CO-RE support.
 
    This attribute marks a structure/union/array type as "preserve", so that
@@ -356,6 +377,23 @@  is_attr_preserve_access (tree t)
   return false;
 }
 
+/* Like is_attr_preserve_access, but FIELD is a FIELD_DECL.  Returns
+   true if FIELD belongs to a struct type with the
+   PRESERVE_ACCESS_INDEX attribute.  */
+
+static bool
+is_attr_preserve_access_field (tree field)
+{
+  gcc_assert (field && TREE_CODE (field) == FIELD_DECL);
+
+  tree type = DECL_FIELD_CONTEXT (field);
+
+  return (type
+	  && TREE_CODE (type) == RECORD_TYPE
+	  && lookup_attribute ("preserve_access_index",
+			       TYPE_ATTRIBUTES (type)));
+}
+
 static tree
 root_for_core_field_info (tree node)
 {
@@ -832,6 +870,74 @@  get_index_for_enum_value (tree type, tree expr)
   return -1;
 }
 
+static bool
+deferred_enum_value_call_p (tree expr)
+{
+  return (expr
+	  && TREE_CODE (expr) == CALL_EXPR
+	  && CALL_EXPR_IFN (expr) == IFN_DEFERRED_CST_ENUM_VALUE);
+}
+
+static tree
+enum_decl_from_deferred_call (tree call)
+{
+  if (!deferred_enum_value_call_p (call)
+      || call_expr_nargs (call) != 1)
+    return NULL_TREE;
+
+  tree decl
+    = deferred_cst_ifn_enum_value_decl (CALL_EXPR_ARG (call, 0));
+
+  if (!decl
+      || TREE_CODE (decl) != CONST_DECL
+      || TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE)
+    return NULL_TREE;
+
+  return decl;
+}
+
+static bool
+deferred_field_offset_call_p (tree expr)
+{
+  return (expr
+	  && TREE_CODE (expr) == CALL_EXPR
+	  && CALL_EXPR_IFN (expr) == IFN_DEFERRED_CST_FIELD_OFFSET);
+}
+
+static tree
+field_decl_from_deferred_call (tree call)
+{
+  if (!deferred_field_offset_call_p (call)
+      || call_expr_nargs (call) != 1)
+    return NULL_TREE;
+
+  tree field
+    = deferred_cst_ifn_field_offset_field (CALL_EXPR_ARG (call, 0));
+
+  if (!field || TREE_CODE (field) != FIELD_DECL)
+    return NULL_TREE;
+
+  return field;
+}
+
+/* Helper for pack_enum_value to retrieve the CONST_DECL for an enum
+   value that is given as argument to __builtin_preserve_enum_value.
+
+   ENUM_VALUE is expected to be a DEFERRED_CST_EXPR wrapping only a
+   call to IFN_DEFERRED_CST_ENUM_VALUE, resembling a builtin parameter
+   that is only a canonical enum value (no complex expressions).
+
+   Returns NULL_TREE on failure.  */
+
+static tree
+deferred_cst_canonical_enum_value_decl (tree enum_value)
+{
+  if (!enum_value || TREE_CODE (enum_value) != DEFERRED_CST_EXPR)
+    return NULL_TREE;
+
+  return enum_decl_from_deferred_call (TREE_OPERAND (enum_value, 0));
+}
+
 /* Pack helper for the __builtin_preserve_enum_value.  */
 
 static struct cr_local
@@ -842,10 +948,10 @@  pack_enum_value (tree *args, enum btf_core_reloc_kind kind,
   ret.reloc_decision = REPLACE_CREATE_RELOCATION;
   ret.fail = false;
 
-  tree *result = NULL;
   tree tmp = args[0];
   tree enum_value = args[1];
   tree type = NULL_TREE;
+  tree decl = NULL_TREE;
 
   /* Deconstructing "*(typeof (enum_type) *) enum_value" to collect both the
      enum_type and enum_value.  */
@@ -859,33 +965,44 @@  pack_enum_value (tree *args, enum btf_core_reloc_kind kind,
       ret.fail = true;
     }
 
-  if (TREE_CODE (enum_value) != INTEGER_CST)
-    goto pack_enum_value_fail;
-
-  result = bpf_enum_mappings->get (enum_value);
-  if (result == NULL)
-    goto pack_enum_value_fail;
+  if (has_deferred_cst_enum ())
+    {
+      decl = deferred_cst_canonical_enum_value_decl (enum_value);
+    }
+  else
+    {
+      /* Preserve the original enum mapping implementation for frontends
+	 which do not seed deferred enum constants.  */
+      if (TREE_CODE (enum_value) == INTEGER_CST)
+	{
+	  tree *result = bpf_enum_mappings->get (enum_value);
 
-  tmp = *result;
+	  if (result != NULL)
+	    decl = *result;
+	}
+    }
 
-  if (TREE_CODE (tmp) != CONST_DECL)
+  if (decl == NULL_TREE || TREE_CODE (decl) != CONST_DECL)
     {
-pack_enum_value_fail:
       bpf_error ("invalid enum value argument for enum value builtin");
       ret.fail = true;
     }
   else
     {
-      ret.reloc_data.expr = tmp;
+      ret.reloc_data.expr = decl;
+
       if (kind == BPF_RELO_ENUMVAL_VALUE)
-	ret.reloc_data.default_value = enum_value;
+	ret.reloc_data.default_value
+	  = has_deferred_cst_enum ()
+	    ? DECL_INITIAL (decl) : enum_value;
       else
 	ret.reloc_data.default_value = integer_one_node;
     }
 
-  if (ret.fail == false )
+  if (ret.fail == false)
     {
-      int index = get_index_for_enum_value (type, tmp);
+      int index = get_index_for_enum_value (type, decl);
+
       if (index == -1 || index >= (1 << 16))
 	{
 	  bpf_error ("enum value in CO-RE builtin cannot be represented");
@@ -1101,10 +1218,16 @@  read_kind (tree kind, char max_value, char enum_offset)
   if (kind == NULL_TREE)
     goto invalid_kind_arg_error;
 
-  if (TREE_CODE (kind) != CONST_DECL
-      && TREE_CODE (kind) == NOP_EXPR)
+  if (TREE_CODE (kind) == NOP_EXPR)
     kind = TREE_OPERAND (kind, 0);
 
+  if (has_deferred_cst_enum ()
+      && TREE_CODE (kind) == DEFERRED_CST_EXPR)
+    kind = deferred_cst_canonical_enum_value_decl (kind);
+
+  if (kind == NULL_TREE)
+    goto invalid_kind_arg_error;
+
   if (TREE_CODE (kind) == CONST_DECL)
     kind = DECL_INITIAL (kind);
 
@@ -1179,7 +1302,8 @@  kind_preserve_type_info (tree *args, int nargs)
 }
 
 /* Plugin handler used in the parser that allows to collect enum value
-   information that other wise would be folded and non recoverable.  */
+   and offsetof information that other wise would be folded and non
+   recoverable.  Uses deferred constants if the frontend seeds them.  */
 
 void
 bpf_handle_plugin_finish_type (void *event_data,
@@ -1187,24 +1311,43 @@  bpf_handle_plugin_finish_type (void *event_data,
 {
   tree type = (tree) event_data;
 
-  if (bpf_enum_mappings == NULL)
-    bpf_enum_mappings = hash_map<tree, tree>::create_ggc (10);
+  if (has_deferred_cst_enum ())
+    {
+      if (TREE_CODE (type) == ENUMERAL_TYPE)
+	/* We have to mark all enums so arguments passed to
+	   __builtin_preserve_enum_value are deferred.  */
+	deferred_cst_mark_type (type);
+    }
+  else
+    {
+      if (bpf_enum_mappings == NULL)
+	bpf_enum_mappings = hash_map<tree, tree>::create_ggc (10);
 
-  if (TREE_CODE (type) == ENUMERAL_TYPE)
-    for (tree l = TYPE_VALUES (type); l; l = TREE_CHAIN (l))
-      {
-	tree value = TREE_VALUE (l);
+      if (TREE_CODE (type) == ENUMERAL_TYPE)
+	for (tree l = TYPE_VALUES (type); l; l = TREE_CHAIN (l))
+	  {
+	    tree value = TREE_VALUE (l);
 
-	tree initial = DECL_INITIAL (value);
-	initial = copy_node (initial);
-	DECL_INITIAL (value) = initial;
+	    tree initial = DECL_INITIAL (value);
+	    initial = copy_node (initial);
+	    DECL_INITIAL (value) = initial;
 
-	tree *found = bpf_enum_mappings->get (initial);
-	if (found == NULL)
-	  bpf_enum_mappings->put (initial, value);
-      }
+	    tree *found = bpf_enum_mappings->get (initial);
+	    if (found == NULL)
+	      bpf_enum_mappings->put (initial, value);
+	  }
+    }
+
+  if (TREE_CODE (type) == RECORD_TYPE
+      && has_deferred_cst_offsetof ()
+      && lookup_attribute ("preserve_access_index",
+			   TYPE_ATTRIBUTES (type)))
+    deferred_cst_mark_type (type);
 }
 
+static tree bpf_deferred_cst_resolver
+  (tree, const deferred_cst_resolve_info *);
+
 /* Initializes support information to process CO-RE builtins.
    Defines information for the builtin processing, such as helper functions to
    support the builtin conversion.  */
@@ -1256,6 +1399,28 @@  bpf_init_core_builtins (void)
   flag_plugin_added = true;
   register_callback ("bpf_collect_enum_info", PLUGIN_FINISH_TYPE,
 		     bpf_handle_plugin_finish_type, NULL);
+
+  if (has_deferred_cst_enum () || has_deferred_cst_offsetof ())
+    deferred_cst_register_resolver (bpf_deferred_cst_resolver);
+}
+
+static tree
+construct_core_reloc_from_data (location_t loc,
+				struct cr_builtins *reloc_data,
+				builtin_helpers helper)
+{
+  int index = search_builtin_data (helper.compare, reloc_data);
+
+  if (index == -1)
+    index = allocate_builtin_data ();
+
+  struct cr_builtins *data = get_builtin_data (index);
+  memcpy (data, reloc_data, sizeof (struct cr_builtins));
+
+  tree fndecl = bpf_builtins[BPF_BUILTIN_CORE_RELOC];
+
+  return build_call_expr_loc (loc, fndecl, 1,
+			      build_int_cst (integer_type_node, index));
 }
 
 /* This function returns the related __builtin_core_reloc call tree node to a
@@ -1294,23 +1459,364 @@  construct_builtin_core_reloc (location_t loc, tree fndecl, tree *args,
 	return error_mark_node;
 
       if (local_data.reloc_decision == REPLACE_CREATE_RELOCATION)
+	return construct_core_reloc_from_data (loc,
+					       &local_data.reloc_data,
+					       helper);
+    }
+  return NULL_TREE;
+}
+
+/* Build a relocation for the offset of FIELD at LOC.  Internally
+   constructs a component reference for FIELD and passes it through
+   the existing preserve-field-info builtin machinery.  */
+
+static tree
+bpf_core_field_offset_reloc (location_t loc, tree field)
+{
+  gcc_assert (TREE_CODE (field) == FIELD_DECL);
+
+  tree record_type = DECL_FIELD_CONTEXT (field);
+  gcc_assert (TREE_CODE (record_type) == RECORD_TYPE);
+
+  /* Build an artificial COMPONENT_REF solely to feed the existing
+     preserve-field-info packing machinery.  */
+  tree object = build_decl (loc, VAR_DECL, NULL_TREE, record_type);
+  DECL_ARTIFICIAL (object) = 1;
+  DECL_IGNORED_P (object) = 1;
+
+  tree ref = build3_loc (loc, COMPONENT_REF, TREE_TYPE (field),
+			 object, field, NULL_TREE);
+
+  tree args[2];
+  args[0] = ref;
+  args[1] = build_int_cst (integer_type_node, BPF_FIELD_BYTE_OFFSET);
+
+  tree fndecl = bpf_builtins[BPF_BUILTIN_PRESERVE_FIELD_INFO];
+
+  return construct_builtin_core_reloc (loc, fndecl, args, 2);
+}
+
+enum bpf_deferred_mode
+{
+  BPF_DEFERRED_GIMPLE,
+  BPF_DEFERRED_STATIC,
+  BPF_DEFERRED_EARLY_RESOLVE
+};
+
+/* Lower the expression EXPR under a DEFERRED_CST_EXPR wrapper according
+   to MODE.
+
+   Deferred enum values and field offsets selected for CO-RE via type
+   attributes are replaced by corresponding relocation expressions.
+
+   Deferred values that are not selected for CO-RE are resolved to
+   their ordinary compile-time values.
+
+   In BPF_DEFERRED_STATIC mode, CO-RE relocations may not be emitted.
+   Future instrumentation logic could automatically generate update-code
+   or relocations for static data that depends on CO-RE values.
+
+   In BPF_DEFERRED_EARLY_RESOLVE mode, this does only partial lowering
+   of deferred constants that would not receive CO-RE relocations in
+   BPF_DEFERRED_GIMPLE mode.
+*/
+
+static tree
+bpf_lower_deferred_inner (tree expr, enum bpf_deferred_mode mode,
+			  bool *unresolved)
+{
+  if (!expr)
+    return NULL_TREE;
+
+  if (CONSTANT_CLASS_P (expr))
+    return expr;
+
+  gcc_assert (TREE_CODE (expr) != DEFERRED_CST_EXPR);
+
+  if (deferred_enum_value_call_p (expr))
+    {
+      tree decl = enum_decl_from_deferred_call (expr);
+      gcc_assert (decl);
+
+      return fold_convert_loc (EXPR_LOCATION (expr),
+			       TREE_TYPE (expr),
+			       DECL_INITIAL (decl));
+    }
+
+  if (deferred_field_offset_call_p (expr))
+    {
+      tree field = field_decl_from_deferred_call (expr);
+      gcc_assert (field);
+
+      if (!is_attr_preserve_access_field (field))
+	return fold_convert_loc (EXPR_LOCATION (expr),
+				 TREE_TYPE (expr),
+				 byte_position (field));
+
+      if (mode == BPF_DEFERRED_EARLY_RESOLVE)
 	{
-	  int index = search_builtin_data (helper.compare,
-					   &local_data.reloc_data);
-	  if (index == -1)
-	    index = allocate_builtin_data ();
-	  struct cr_builtins *data = get_builtin_data (index);
-	  memcpy (data, &local_data.reloc_data, sizeof (struct cr_builtins));
-
-	  tree fndecl = bpf_builtins[BPF_BUILTIN_CORE_RELOC];
-	  return  build_call_expr_loc (loc,
-				fndecl, 1,
-				build_int_cst (integer_type_node, index));
+	  if (unresolved)
+	    *unresolved = true;
+	  return expr;
 	}
+
+      if (mode == BPF_DEFERRED_STATIC)
+	{
+	  error_at (EXPR_LOCATION (expr),
+		    "BPF CO-RE field offsets are not yet supported "
+		    "in static initializers");
+
+	  return fold_convert_loc (EXPR_LOCATION (expr),
+				   TREE_TYPE (expr),
+				   byte_position (field));
+	}
+
+      tree reloc
+	= bpf_core_field_offset_reloc (EXPR_LOCATION (expr), field);
+
+      if (reloc == error_mark_node)
+	return reloc;
+
+      return fold_convert_loc (EXPR_LOCATION (expr),
+			       TREE_TYPE (expr), reloc);
     }
+
+  tree copy = copy_node (expr);
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    {
+      tree op = TREE_OPERAND (expr, i);
+
+      if (!op)
+	continue;
+
+      TREE_OPERAND (copy, i)
+	= bpf_lower_deferred_inner (op, mode, unresolved);
+    }
+
+  switch (mode)
+    {
+    case BPF_DEFERRED_STATIC:
+    case BPF_DEFERRED_EARLY_RESOLVE:
+      return fold (copy);
+    case BPF_DEFERRED_GIMPLE:
+      return copy;
+    }
+
+  return expr;
+}
+
+/* Lower a deferred constant expression WRAPPER according to the
+   transformations defined in bpf_lower_deferred_inner.  */
+
+static tree
+bpf_lower_deferred_wrapper (tree wrapper, enum bpf_deferred_mode mode)
+{
+  gcc_assert (wrapper && TREE_CODE (wrapper) == DEFERRED_CST_EXPR);
+
+  tree inner = TREE_OPERAND (wrapper, 0);
+  return bpf_lower_deferred_inner (inner, mode, nullptr);
+}
+
+/* Early resolver callback for deferred constants that do not need to
+   remain until BPF lowering and occur in problematic contexts.  */
+
+static tree
+bpf_deferred_cst_resolver (tree expr,
+			   const deferred_cst_resolve_info *info)
+{
+  gcc_assert (expr);
+
+  if (CONSTANT_CLASS_P (expr))
+    return expr;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    {
+      bool unresolved = false;
+
+      tree inner
+	= bpf_lower_deferred_inner (TREE_OPERAND (expr, 0),
+				    BPF_DEFERRED_EARLY_RESOLVE,
+				    &unresolved);
+
+      if (unresolved)
+	{
+	  if (info->consequence == DEFERRED_CST_CONSEQUENCE_ERROR)
+	    {
+	      error_at (EXPR_LOCATION (expr),
+			"BPF CO-RE deferred constants cannot be used "
+			"in this constant expression context");
+	      return error_mark_node;
+	    }
+	  else
+	    {
+	      return deferred_cst_build_expr (inner);
+	    }
+	}
+
+      return inner;
+    }
+
+  tree copy = copy_node (expr);
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    {
+      tree op = TREE_OPERAND (expr, i);
+
+      if (op)
+	TREE_OPERAND (copy, i)
+	  = bpf_deferred_cst_resolver (op, info);
+    }
+
+  return fold (copy);
+}
+
+/* Tree-walk callback for lowering deferred constants in GIMPLE statements.
+
+   Replaces each DEFERRED_CST_EXPR with its lowered and gimplified
+   equivalent.  Any new gimple statements are inserted immediately
+   before the current statement.  */
+
+static tree
+bpf_lower_deferred_tree (tree *tp, int *walk_subtrees, void *data)
+{
+  tree node = *tp;
+
+  if (!node)
+    return NULL_TREE;
+
+  if (TYPE_P (node) || DECL_P (node))
+    {
+      *walk_subtrees = 0;
+      return NULL_TREE;
+    }
+
+  if (TREE_CODE (node) != DEFERRED_CST_EXPR)
+    return NULL_TREE;
+
+  struct walk_stmt_info *wi
+    = static_cast<struct walk_stmt_info *> (data);
+
+  /* First transform the complete deferred expression.  */
+  tree replacement
+    = bpf_lower_deferred_wrapper (node, BPF_DEFERRED_GIMPLE);
+
+  if (replacement == error_mark_node)
+    {
+      *tp = replacement;
+      *walk_subtrees = 0;
+      return NULL_TREE;
+    }
+
+  /* Turn the resulting GENERIC expression into a GIMPLE value.  Any
+     statements required to compute it are emitted into BEFORE.  */
+  gimple_seq before = NULL;
+
+  push_gimplify_context ();
+
+  gimplify_expr (&replacement, &before, NULL,
+		 is_gimple_val, fb_rvalue);
+
+  pop_gimplify_context (NULL);
+
+  /* Insert computation of REPLACEMENT immediately before the
+     statement containing the original DEFERRED_CST_EXPR.  */
+  if (before)
+    gsi_insert_seq_before (&wi->gsi, before, GSI_SAME_STMT);
+
+  /* REPLACEMENT is now a valid GIMPLE value.  */
+  *tp = replacement;
+
+  /* Do not walk the newly generated expression.  */
+  *walk_subtrees = 0;
+
   return NULL_TREE;
 }
 
+/* Return true if the initializer expression EXPR contains deferred
+   constants.  */
+
+static bool
+bpf_initializer_has_deferred (tree expr)
+{
+  if (!expr || DECL_P (expr) || TYPE_P (expr))
+    return false;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    return true;
+
+  if (TREE_CODE (expr) == CONSTRUCTOR)
+    {
+      unsigned HOST_WIDE_INT i;
+      tree index, value;
+
+      FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (expr), i, index, value)
+	if (bpf_initializer_has_deferred (value))
+	  return true;
+
+      return false;
+    }
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    if (bpf_initializer_has_deferred (TREE_OPERAND (expr, i)))
+      return true;
+
+  return false;
+}
+
+/* Resolves deferred constants in the static initializer expression
+   EXPR.  Deferred constants that do not require CO-RE relocations
+   (because the corresponding types are not attributed accordingly)
+   are replaced with their ordinary compile-time values.
+
+   Expressions that would require CO-RE relocations are diagnosed as
+   errors.  Support for those may be added in the future.  */
+
+static tree
+bpf_transform_initializer (tree expr)
+{
+  if (!expr || DECL_P (expr) || TYPE_P (expr) || CONSTANT_CLASS_P (expr))
+    return expr;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    return bpf_lower_deferred_wrapper (expr, BPF_DEFERRED_STATIC);
+
+  if (TREE_CODE (expr) == CONSTRUCTOR)
+    {
+      vec<constructor_elt, va_gc> *elts = NULL;
+      unsigned HOST_WIDE_INT i;
+      tree index, value;
+
+      FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (expr), i, index, value)
+	{
+	  tree replacement = bpf_transform_initializer (value);
+	  CONSTRUCTOR_APPEND_ELT (elts, index, replacement);
+	}
+
+      tree result = build_constructor (TREE_TYPE (expr), elts);
+
+      TREE_CONSTANT (result) = TREE_CONSTANT (expr);
+      TREE_STATIC (result) = TREE_STATIC (expr);
+
+      return result;
+    }
+
+  if (!bpf_initializer_has_deferred (expr))
+    return expr;
+
+  tree copy = copy_node (expr);
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    {
+      tree op = TREE_OPERAND (expr, i);
+
+      if (op)
+	TREE_OPERAND (copy, i) = bpf_transform_initializer (op);
+    }
+
+  return fold (copy);
+}
+
 /* This function constructs the CO-RE safe code around field expressions.
    If the expression is an array access, create an offset by multiplying the
    index access by the __builtin_type_info call requesting the size of the
@@ -1944,11 +2450,13 @@  core_make_builtins (tree *tp, int *walk_subtrees, void *data)
   return NULL_TREE;
 }
 
-/* This is the entry point for the pass_data_lower_bpg_core.  It walks all the
+/* This is the entry point for the pass_lower_bpf_core.  It walks all the
    statements in gimple, looking for expressions that are suppose to be CO-RE
    preserve_access_index attributed, and should not.
-   It first splits CO-RE expressions from non CO-RE ones.
-   Then the CO-RE expressions are processed by core_make_builtins which will
+   It first instruments only deferred constant field offsets and enum values,
+   turning those relevant to CO-RE into relocations.
+   Then it splits all CO-RE expressions from non CO-RE ones.
+   Finally, the CO-RE expressions are processed by core_make_builtins which will
    create the required builtins that will result in the CO-RE relocations.  */
 static unsigned int
 execute_lower_bpf_core (void)
@@ -1962,6 +2470,12 @@  execute_lower_bpf_core (void)
   struct walk_stmt_info wi;
   memset (&wi, 0, sizeof (wi));
 
+  /* Deferred constants are still represented as GENERIC expression trees
+     embedded in GIMPLE operands.  Replace their leaves with ordinary
+     constants or BPF CO-RE relocation calls.  */
+  if (has_deferred_cst_enum () || has_deferred_cst_offsetof ())
+    walk_gimple_seq_mod (&body, NULL, bpf_lower_deferred_tree, &wi);
+
   /* Early split to guarantee base of expression is a preserve_access_index
      structure.  */
   walk_gimple_seq_mod (&body, NULL, gimple_core_early_split_expr, &wi);
@@ -1971,6 +2485,49 @@  execute_lower_bpf_core (void)
   return 0;
 }
 
+/* This is the entry point for pass_bpf_deferred_static.  It iterates
+   over all static initializers to lower deferred constants.  */
+
+static unsigned int
+execute_bpf_deferred_static (void)
+{
+  if (!TARGET_BPF_CORE)
+    return 0;
+
+  if (!(has_deferred_cst_enum ()
+	|| has_deferred_cst_offsetof ()))
+    return 0;
+
+  varpool_node *vnode;
+
+  FOR_EACH_VARIABLE (vnode)
+    {
+      tree decl = vnode->decl;
+
+      if (!decl
+	  || TREE_CODE (decl) != VAR_DECL
+	  || DECL_EXTERNAL (decl)
+	  || !TREE_STATIC (decl))
+	continue;
+
+      tree init = DECL_INITIAL (decl);
+
+      if (!init || !bpf_initializer_has_deferred (init))
+	continue;
+
+      tree replacement = bpf_transform_initializer (init);
+
+      DECL_INITIAL (decl) = replacement;
+
+      /* Even after emitting an error for an attributed leaf we replace it by
+	 its local compile-time value.  Therefore absolutely no deferred node
+	 should survive this pass.  */
+      gcc_assert (!bpf_initializer_has_deferred (replacement));
+    }
+
+  return 0;
+}
+
 namespace {
 
 const pass_data pass_data_lower_bpf_core =
@@ -2001,6 +2558,32 @@  public:
 
 }; /* class pass_lower_bpf_core */
 
+const pass_data pass_data_bpf_deferred_static =
+{
+  SIMPLE_IPA_PASS, /* type */
+  "bpf_deferred_static", /* name */
+  OPTGROUP_NONE, /* optinfo_flags */
+  TV_NONE, /* tv_id */
+  0, /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  0, /* todo_flags_finish */
+};
+
+class pass_bpf_deferred_static : public simple_ipa_opt_pass
+{
+public:
+  pass_bpf_deferred_static (gcc::context *ctxt)
+    : simple_ipa_opt_pass (pass_data_bpf_deferred_static, ctxt)
+  {}
+
+  unsigned int execute (function *) final override
+  {
+    return execute_bpf_deferred_static ();
+  }
+};
+
 } /* anon namespace */
 
 gimple_opt_pass *
@@ -2009,4 +2592,10 @@  make_pass_lower_bpf_core (gcc::context *ctxt)
   return new pass_lower_bpf_core (ctxt);
 }
 
+simple_ipa_opt_pass *
+make_pass_bpf_deferred_static (gcc::context *ctxt)
+{
+  return new pass_bpf_deferred_static (ctxt);
+}
+
 #include "gt-core-builtins.h"
diff --git a/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c b/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
new file mode 100644
index 00000000000..251cdca5414
--- /dev/null
+++ b/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
@@ -0,0 +1,41 @@ 
+/* This test makes sure that the BPF lowering pass properly drains
+   deferred constants that are not intended to receive CO-RE
+   relocations.  Similarly, such constants must be resolved by the
+   BPF deferred constant resolver before they can cause frontend
+   errors.  */
+
+/* { dg-do compile } */
+/* { dg-options "-O0 -dA -gbtf -mco-re -masm=normal" } */
+
+enum E
+{
+  A = 1,
+  B = 2
+};
+
+int
+foo (void)
+{
+  return B;
+}
+
+struct S
+{
+  int a;
+  long b;
+  int c;
+};
+
+unsigned long
+bar (void)
+{
+  return __builtin_offsetof (struct S, c);
+}
+
+/* { dg-final { scan-assembler-not "bpfcr_kind" } } */
+
+/* Deferred constants are not permitted in some contexts, but the BPF
+   backend marks ALL enums for deferral initially.  Check whether the
+   deferred constant resolver callback correctly un-defers expressions
+   early enough.  If it doesn't, this causes a frontend error.  */
+int global[B];
diff --git a/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c b/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c
new file mode 100644
index 00000000000..3f1b5e4821c
--- /dev/null
+++ b/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c
@@ -0,0 +1,40 @@ 
+/* This test validates that offsetof expressions refering to struct types
+   marked with "preserve_access_index" automatically receive
+   BPF_RELO_FIELD_BYTE_OFFSET relocations.  */
+
+/* { dg-do compile } */
+/* { dg-options "-O0 -dA -gbtf -mco-re -masm=normal" } */
+
+struct S
+{
+  int a;
+  long b;
+  int c;
+} __attribute__((preserve_access_index));
+
+unsigned long
+foo (void)
+{
+  return (__builtin_offsetof (struct S, a)
+	  + __builtin_offsetof (struct S, b)
+	  + __builtin_offsetof (struct S, c));
+}
+
+/* Check the local field offsets.  */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],0" 1 } } */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],8" 1 } } */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],16" 1 } } */
+
+/* Check the BTF access strings.  */
+/* { dg-final { scan-assembler-times "ascii \"0:0.0\"\[\t \]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"0:1.0\"\[\t \]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"0:2.0\"\[\t \]+\[^\n\]*btf_aux_string" 1 } } */
+
+/* Check that each relocation identifies the correct field.  */
+/* { dg-final { scan-assembler-times "bpfcr_type \\(struct S\\)" 3 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:0\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:1\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:2\"\\)" 1 } } */
+
+/* All three are BPF_FIELD_BYTE_OFFSET relocations.  */
+/* { dg-final { scan-assembler-times "0\[\t \]+\[^\n\]*bpfcr_kind" 3 } } */