On 2024-09-20 20:20, Sam James wrote:
Siddhesh Poyarekar <siddh...@gotplt.org> writes:

This series makes a few improvements to get static object size estimates in
more cases, thus improving the success rate of the static
__builtin_object_size.  This should fully fix PR116556 and also covers a bulk
of use cases for PR77608.  I started to try and fix PR77608 fully, but in the
end it looks like too much work in the pass for what seems like a very small
set of uses, i.e. handling volatile offsets.  If that is a desirable end goal
then it could be done in a separate patchset since it will need
tree-object-size to handle trees with side-effects.

I could try play with https://github.com/siddhesh/fortify-metrics to see
how much it happens in the wild if you can help me figure out a
condition for when it punts (not tried). But I'm sceptical it's
worth the time.

That's an interesting idea, but unfortunately the very first attempt at folding such a __builtin_object_size () call eliminates it, which AFAICT happens right in the frontend. Maybe if the compiler is hacked up to move the TREE_SIDE_EFFECTS (ptr) into compute_builtin_object_size like the attached lightly tested patch, you could look for TREE_SIDE_EFFECTS (ptr) in fortify-metrics to identify such lost opportunities.

Thanks,
Sid
diff --git a/gcc/builtins.cc b/gcc/builtins.cc
index 37c7c98e5c7..7efd9d5df37 100644
--- a/gcc/builtins.cc
+++ b/gcc/builtins.cc
@@ -11640,12 +11640,6 @@ fold_builtin_object_size (tree ptr, tree ost, enum 
built_in_function fcode)
 
   object_size_type = tree_to_shwi (ost);
 
-  /* __builtin_object_size doesn't evaluate side-effects in its arguments;
-     if there are any side-effects, it returns (size_t) -1 for types 0 and 1
-     and (size_t) 0 for types 2 and 3.  */
-  if (TREE_SIDE_EFFECTS (ptr))
-    return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
-
   if (fcode == BUILT_IN_DYNAMIC_OBJECT_SIZE)
     object_size_type |= OST_DYNAMIC;
 
diff --git a/gcc/tree-object-size.cc b/gcc/tree-object-size.cc
index ebd2a4650aa..b8f60d1aff5 100644
--- a/gcc/tree-object-size.cc
+++ b/gcc/tree-object-size.cc
@@ -1193,6 +1193,12 @@ compute_builtin_object_size (tree ptr, int 
object_size_type,
      could be determined.  */
   *psize = size_unknown (object_size_type);
 
+  /* __builtin_object_size doesn't evaluate side-effects in its arguments;
+     if there are any side-effects, it returns (size_t) -1 for types 0 and 1
+     and (size_t) 0 for types 2 and 3.  */
+  if (TREE_SIDE_EFFECTS (ptr))
+    return false;
+
   if (! offset_limit)
     init_offset_limit ();
 

Reply via email to