ipa-icf: Compare access path type sizes without TBAA [PR105438]
Commit Message
With -fno-strict-aliasing, IPA ICF merges functions that copy the same
fields between two struct types of different sizes, and the merged body,
inlined at the other function's call sites, can trip diagnostics like
-Warray-bounds:
struct small { char pad[16]; int a; unsigned int b, c; };
struct big { char pad[16]; int a; unsigned int b, c; int extra; };
void small_to_big (struct big *dst, const struct small *src)
{
dst->a = src->a;
...
}
void big_to_small (struct small *dst, const struct big *src)
{
dst->a = src->a;
...
}
void f (struct big *p)
{
struct small tmp;
big_to_small (&tmp, p);
...
}
In function 'small_to_big', inlined from 'f' at t.c:22:3:
warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
Without TBAA, compare those sizes at each level of the path, so we don't
see mismatched sizes on a merged body. Require the same tree codes at
each level too, as the TBAA comparison does, and array members of the
same kind: -Warray-bounds treats an array member that ends its object as
possibly flexible, so "int arr[1]" at the end of one struct and in the
middle of another, at the same offset in structs of the same size, must
not merge either. The sizes are compared with ICF's operand_equal_p, so
those of variably modified types, which refer to each function's own
decls, still match. Functions accessing distinct types of the same
layout still merge, as gcc.dg/lto/pr113359-*.c tests expect.
The Linux kernel (which uses -fno-strict-aliasing) hit this with GCC 16 in
net/ipv6/ip6_tunnel.c: ip6_tnl_parm_from_user() and ip6_tnl_parm_to_user()
copy the same fields between struct ip6_tnl_parm and the larger struct
__ip6_tnl_parm in opposite directions. This was only seen on m68k,
parisc, arc, xtensa, and openrisc. Those functions also memcpy a char
array member, and since r17-4004 (PR119006) ICF compares the fields in
those addresses and keeps the two apart, but functions that copy only
the scalar fields (as Linux is) still merged.
The stricter comparison doesn't cost merges in the kernel code I
measured: across the 636 objects of net/ipv6, fs/ext4, kernel, and mm in
an x86 allmodconfig build, none of the 1569 ICF merges is between
accesses whose sizes or array kinds differ, so the count and the text
size are the same with and without this change.
This turned out to match PR105438, but on trunk (with -fstrict-aliasing)
the access path comparison refused the merge. But with -fno-strict-aliasing
it was exposed. (Its testcase also now needed -fno-early-inlining, or both
instantiations were inlined before ICF runs.)
Assisted-by: LLM [tests]
gcc/ChangeLog:
PR ipa/105438
* tree-ssa-alias.cc (ao_compare::compare_ao_refs): Without TBAA,
compare the tree codes, the sizes of the types, and the kinds of
array members along the access paths.
gcc/testsuite/ChangeLog:
PR ipa/105438
* g++.dg/ipa/pr105438.C: New test.
* gcc.dg/ipa/ipa-icf-41.c: New test.
* gcc.dg/ipa/ipa-icf-42.c: New test.
Signed-off-by: Kees Cook <kees@kernel.org>
---
I tried to copy neighboring style. I don't like "while (true)", but that
seemed to be idiomatic?
---
gcc/testsuite/g++.dg/ipa/pr105438.C | 33 ++++++++++++
gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c | 73 ++++++++++++++++++++++++++
gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c | 75 +++++++++++++++++++++++++++
gcc/tree-ssa-alias.cc | 34 +++++++++++-
4 files changed, 213 insertions(+), 2 deletions(-)
create mode 100644 gcc/testsuite/g++.dg/ipa/pr105438.C
create mode 100644 gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c
create mode 100644 gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c
Comments
On Sat, Oct 10, 2026 at 7:06 AM Kees Cook <kees@kernel.org> wrote:
>
> With -fno-strict-aliasing, IPA ICF merges functions that copy the same
> fields between two struct types of different sizes, and the merged body,
> inlined at the other function's call sites, can trip diagnostics like
> -Warray-bounds:
>
> struct small { char pad[16]; int a; unsigned int b, c; };
> struct big { char pad[16]; int a; unsigned int b, c; int extra; };
>
> void small_to_big (struct big *dst, const struct small *src)
> {
> dst->a = src->a;
> ...
> }
>
> void big_to_small (struct small *dst, const struct big *src)
> {
> dst->a = src->a;
> ...
> }
>
> void f (struct big *p)
> {
> struct small tmp;
>
> big_to_small (&tmp, p);
> ...
> }
>
> In function 'small_to_big', inlined from 'f' at t.c:22:3:
> warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
I think these diagnostics are dubious with -fno-strict-aliasing which
essentially
says you can access every object via any other objects type.
> Without TBAA, compare those sizes at each level of the path, so we don't
> see mismatched sizes on a merged body. Require the same tree codes at
> each level too, as the TBAA comparison does, and array members of the
> same kind: -Warray-bounds treats an array member that ends its object as
> possibly flexible, so "int arr[1]" at the end of one struct and in the
> middle of another, at the same offset in structs of the same size, must
> not merge either. The sizes are compared with ICF's operand_equal_p, so
> those of variably modified types, which refer to each function's own
> decls, still match. Functions accessing distinct types of the same
> layout still merge, as gcc.dg/lto/pr113359-*.c tests expect.
>
> The Linux kernel (which uses -fno-strict-aliasing) hit this with GCC 16 in
> net/ipv6/ip6_tunnel.c: ip6_tnl_parm_from_user() and ip6_tnl_parm_to_user()
> copy the same fields between struct ip6_tnl_parm and the larger struct
> __ip6_tnl_parm in opposite directions. This was only seen on m68k,
> parisc, arc, xtensa, and openrisc. Those functions also memcpy a char
> array member, and since r17-4004 (PR119006) ICF compares the fields in
> those addresses and keeps the two apart, but functions that copy only
> the scalar fields (as Linux is) still merged.
>
> The stricter comparison doesn't cost merges in the kernel code I
> measured: across the 636 objects of net/ipv6, fs/ext4, kernel, and mm in
> an x86 allmodconfig build, none of the 1569 ICF merges is between
> accesses whose sizes or array kinds differ, so the count and the text
> size are the same with and without this change.
>
> This turned out to match PR105438, but on trunk (with -fstrict-aliasing)
> the access path comparison refused the merge. But with -fno-strict-aliasing
> it was exposed. (Its testcase also now needed -fno-early-inlining, or both
> instantiations were inlined before ICF runs.)
So instead of this I'd rather work towards inlining the original
body rather than the ICF prevailing one.
And force-disable these kind of diagnostics with -fno-strict-aliasing?
Richard.
>
> Assisted-by: LLM [tests]
>
> gcc/ChangeLog:
>
> PR ipa/105438
> * tree-ssa-alias.cc (ao_compare::compare_ao_refs): Without TBAA,
> compare the tree codes, the sizes of the types, and the kinds of
> array members along the access paths.
>
> gcc/testsuite/ChangeLog:
>
> PR ipa/105438
> * g++.dg/ipa/pr105438.C: New test.
> * gcc.dg/ipa/ipa-icf-41.c: New test.
> * gcc.dg/ipa/ipa-icf-42.c: New test.
>
> Signed-off-by: Kees Cook <kees@kernel.org>
> ---
> I tried to copy neighboring style. I don't like "while (true)", but that
> seemed to be idiomatic?
> ---
> gcc/testsuite/g++.dg/ipa/pr105438.C | 33 ++++++++++++
> gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c | 73 ++++++++++++++++++++++++++
> gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c | 75 +++++++++++++++++++++++++++
> gcc/tree-ssa-alias.cc | 34 +++++++++++-
> 4 files changed, 213 insertions(+), 2 deletions(-)
> create mode 100644 gcc/testsuite/g++.dg/ipa/pr105438.C
> create mode 100644 gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c
> create mode 100644 gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c
>
> diff --git a/gcc/testsuite/g++.dg/ipa/pr105438.C b/gcc/testsuite/g++.dg/ipa/pr105438.C
> new file mode 100644
> index 000000000000..45daece51abf
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/ipa/pr105438.C
> @@ -0,0 +1,33 @@
> +// PR ipa/105438
> +// { dg-do compile }
> +// { dg-options "-O2 -fno-strict-aliasing -fno-early-inlining -Warray-bounds -fdump-ipa-icf-optimized" }
> +
> +// With -fno-strict-aliasing, IPA ICF merged configure<7> and configure<2>,
> +// whose accesses through IN differ only in the bound of the array type,
> +// and the merged body, inlined for the call with SHORTER, read it as a
> +// const int[7]. (-fno-early-inlining keeps the instantiations from being
> +// inlined into main before ICF runs.)
> +
> +int longer[7] = {};
> +int shorter[2] = {};
> +int out[10] = {};
> +
> +template <int N>
> +void configure(const int(&in)[N], const int nrows = N)
> +{
> + if (nrows <= 10)
> + {
> + for (int i = 0; i < nrows; i++)
> + {
> + out[i] = in[i]; // { dg-bogus "outside array bounds" }
> + }
> + }
> +}
> +
> +int main()
> +{
> + configure(longer);
> + configure(shorter);
> +}
> +
> +// { dg-final { scan-ipa-dump-not "Semantic equality hit" "icf" } }
> diff --git a/gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c b/gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c
> new file mode 100644
> index 000000000000..64bf871de0f8
> --- /dev/null
> +++ b/gcc/testsuite/gcc.dg/ipa/ipa-icf-41.c
> @@ -0,0 +1,73 @@
> +/* Verify that with -fno-strict-aliasing, IPA ICF doesn't merge functions
> + whose memory accesses go through types of different sizes, which would
> + put one function's types into the other's inlined copies, and that it
> + still merges functions whose accesses go through the same types, or
> + through distinct types of the same layout.
> + { dg-do compile }
> + { dg-options "-O2 -fno-strict-aliasing -fno-early-inlining -Warray-bounds -fdump-ipa-icf-optimized" } */
> +
> +struct small { char pad[16]; int a; unsigned int b, c; };
> +struct big { char pad[16]; int a; unsigned int b, c; int extra; };
> +struct small_twin { char pad[16]; int a; unsigned int b, c; };
> +
> +/* Not merged: the same offsets, but through types of different sizes.
> + Merged, the call to big_to_small in f would get small_to_big's body,
> + which stores to TMP through a "struct big *". */
> +
> +void small_to_big (struct big *dst, const struct small *src)
> +{
> + dst->a = src->a; /* { dg-bogus "outside array bounds" } */
> + dst->b = src->b; /* { dg-bogus "outside array bounds" } */
> + dst->c = src->c; /* { dg-bogus "outside array bounds" } */
> +}
> +
> +void big_to_small (struct small *dst, const struct big *src)
> +{
> + dst->a = src->a;
> + dst->b = src->b;
> + dst->c = src->c;
> +}
> +
> +void f (struct big *p)
> +{
> + struct small tmp;
> +
> + big_to_small (&tmp, p);
> + small_to_big (p, &tmp);
> +}
> +
> +/* Merged: the same types. */
> +
> +void big_to_big_1 (struct big *dst, const struct big *src)
> +{
> + dst->a = src->a;
> + dst->b = src->b;
> + dst->c = src->c;
> +}
> +
> +void big_to_big_2 (struct big *dst, const struct big *src)
> +{
> + dst->a = src->a;
> + dst->b = src->b;
> + dst->c = src->c;
> +}
> +
> +/* Merged: distinct types of the same layout. */
> +
> +void small_to_twin (struct small_twin *dst, const struct small *src)
> +{
> + dst->a = src->a;
> + dst->b = src->b;
> + dst->c = src->c;
> +}
> +
> +void twin_to_small (struct small *dst, const struct small_twin *src)
> +{
> + dst->a = src->a;
> + dst->b = src->b;
> + dst->c = src->c;
> +}
> +
> +/* { dg-final { scan-ipa-dump-not {Semantic equality hit:[^\n]*(small_to_big|big_to_small)/} "icf" } } */
> +/* { dg-final { scan-ipa-dump {Semantic equality hit:big_to_big_[12]/[0-9]+->big_to_big_[12]/[0-9]+} "icf" } } */
> +/* { dg-final { scan-ipa-dump {Semantic equality hit:(small_to_twin|twin_to_small)/[0-9]+->(small_to_twin|twin_to_small)/[0-9]+} "icf" } } */
> diff --git a/gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c b/gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c
> new file mode 100644
> index 000000000000..cb6a0ab9fdc3
> --- /dev/null
> +++ b/gcc/testsuite/gcc.dg/ipa/ipa-icf-42.c
> @@ -0,0 +1,75 @@
> +/* Verify that with -fno-strict-aliasing, IPA ICF compares each level of
> + an access path, not just its base: an array element against a scalar
> + member, a nested size mismatch, an array member that ends its object
> + against one that doesn't, and a flexible array member against a
> + zero-length one keep functions apart, while
> + flexible array members of the same layout, and identical functions
> + accessing variably modified types, still merge.
> + { dg-do compile }
> + { dg-options "-O2 -fno-strict-aliasing -fdump-ipa-icf-details" } */
> +
> +/* ICF hashes memory accesses with their alias sets even with
> + -fno-strict-aliasing, so functions accessing distinct structs would
> + not get the same hash and would never be compared. may_alias gives
> + each struct alias set 0, so each pair below is compared, which the
> + "Equals called for" scans check, along with the reason for each
> + refusal. */
> +
> +#define MA __attribute__ ((may_alias))
> +
> +/* Not merged: the stores are to the same offset and size, but one is to
> + an array element and the other to a scalar member, so the access
> + paths have different tree codes. (The tree code of a load is part of
> + ICF's hash, so a load would not be compared.) */
> +
> +struct MA c1 { int tag[2]; int x[1]; int y; };
> +struct MA c2 { int tag[2]; int x; int y; };
> +
> +void codes_1 (struct c1 *dst, int v) { dst->x[0] = v; }
> +void codes_2 (struct c2 *dst, int v) { dst->x = v; }
> +
> +/* Not merged: the outer structs are the same size, but the structs
> + holding A are 16 and 8 bytes. */
> +
> +struct MA n1 { struct { int a; int pad[3]; } in; int t[1]; };
> +struct MA n2 { struct { int a; int pad; } in; int t[3]; };
> +
> +void nested_1 (struct n1 *dst, const struct n1 *src) { dst->in.a = src->in.a; }
> +void nested_2 (struct n2 *dst, const struct n2 *src) { dst->in.a = src->in.a; }
> +
> +/* Not merged: both structs are 16 bytes, but ARR ends struct t1, so it
> + may be a flexible array, and not struct t2. */
> +
> +struct MA __attribute__ ((aligned (16))) t1 { int tag; int arr[1]; };
> +struct MA __attribute__ ((aligned (16))) t2 { int tag; int arr[1]; int x; };
> +
> +void trailing_1 (struct t1 *dst, const struct t1 *src) { dst->arr[0] = src->arr[0]; }
> +void trailing_2 (struct t2 *dst, const struct t2 *src) { dst->arr[0] = src->arr[0]; }
> +
> +/* Merged: flexible array members, whose types have no size. Not merged:
> + either of those and a zero-length array. */
> +
> +struct MA f1 { int tag; int arr[]; };
> +struct MA f2 { int tag; int arr[]; };
> +struct MA z { int tag; int arr[0]; };
> +
> +void flex_1 (struct f1 *dst, const struct f1 *src, int i) { dst->arr[i] = src->arr[i]; }
> +void flex_2 (struct f2 *dst, const struct f2 *src, int i) { dst->arr[i] = src->arr[i]; }
> +void zero_len (struct z *dst, const struct z *src, int i) { dst->arr[i] = src->arr[i]; }
> +
> +/* Merged: the sizes of variably modified types refer to each function's
> + own parameters. */
> +
> +void vla_1 (int n, int (*p)[n], int i) { p[i][1] = 1; p[i][2] = 2; }
> +void vla_2 (int n, int (*p)[n], int i) { p[i][1] = 1; p[i][2] = 2; }
> +
> +/* Each refusal is logged as its reason, a few more lines, and then the
> + pair compared; match the reason and the pair with no other comparison
> + between them. */
> +/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: codes_[12]/[0-9]+:codes_[12]/[0-9]+ with result: false} "icf" } } */
> +/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: nested_[12]/[0-9]+:nested_[12]/[0-9]+ with result: false} "icf" } } */
> +/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: trailing_[12]/[0-9]+:trailing_[12]/[0-9]+ with result: false} "icf" } } */
> +/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: (zero_len/[0-9]+:flex_[12]|flex_[12]/[0-9]+:zero_len)/[0-9]+ with result: false} "icf" } } */
> +/* { dg-final { scan-ipa-dump {Semantic equality hit:flex_[12]/[0-9]+->flex_[12]/[0-9]+} "icf" } } */
> +/* { dg-final { scan-ipa-dump {Semantic equality hit:vla_[12]/[0-9]+->vla_[12]/[0-9]+} "icf" } } */
> +/* { dg-final { scan-ipa-dump-not {Semantic equality hit:[^\n]*(codes_|nested_|trailing_|zero_len)} "icf" } } */
> diff --git a/gcc/tree-ssa-alias.cc b/gcc/tree-ssa-alias.cc
> index a8196d116355..2f3d7f523a02 100644
> --- a/gcc/tree-ssa-alias.cc
> +++ b/gcc/tree-ssa-alias.cc
> @@ -4262,7 +4262,9 @@ types_equal_for_same_type_for_tbaa_p (tree type1, tree type2)
> /* Compare REF1 and REF2 and return flags specifying their differences.
> If LTO_STREAMING_SAFE is true do not use alias sets and canonical
> types that are going to be recomputed.
> - If TBAA is true also compare TBAA metadata. */
> + If TBAA is true also compare TBAA metadata, and otherwise only the
> + shape of the access paths: the tree codes along them, the sizes of
> + their types, and the kind of each array member. */
>
> int
> ao_compare::compare_ao_refs (ao_ref *ref1, ao_ref *ref2,
> @@ -4379,8 +4381,36 @@ ao_compare::compare_ao_refs (ao_ref *ref1, ao_ref *ref2,
> || (MR_DEPENDENCE_BASE (rbase1) != MR_DEPENDENCE_BASE (rbase2))))
> flags |= DEPENDENCE_CLIQUE;
>
> + /* Without TBAA, the types along the access paths don't matter for
> + aliasing, but other consumers read their sizes (e.g. ranger
> + diagnostics like -Warray-bounds). Require the same tree codes at
> + each level, with sizes that match and array members of the same
> + kind, so the references of a merged function are valid for the
> + callers of both. The types themselves may differ, so functions
> + accessing distinct but identically laid out types still merge. */
> if (!tbaa)
> - return flags;
> + {
> + tree c1 = ref1->ref, c2 = ref2->ref;
> + while (true)
> + {
> + if (TREE_CODE (c1) != TREE_CODE (c2))
> + return flags | ACCESS_PATH;
> + tree size1 = TYPE_SIZE (TREE_TYPE (c1));
> + tree size2 = TYPE_SIZE (TREE_TYPE (c2));
> + if (size1 && size2
> + ? !operand_equal_p (size1, size2, 0)
> + : size1 != size2)
> + return flags | ACCESS_PATH;
> + if (TREE_CODE (c1) == COMPONENT_REF
> + && component_ref_sam_type (c1) != component_ref_sam_type (c2))
> + return flags | ACCESS_PATH;
> + if (!handled_component_p (c1))
> + break;
> + c1 = TREE_OPERAND (c1, 0);
> + c2 = TREE_OPERAND (c2, 0);
> + }
> + return flags;
> + }
>
> /* Alias sets are not stable across LTO sreaming; be conservative here
> and compare types the alias sets are ultimately based on. */
> --
> 2.55.0
>
On Sun, Oct 11, 2026 at 04:50:41PM +0200, Richard Biener wrote:
> > In function 'small_to_big', inlined from 'f' at t.c:22:3:
> > warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
>
> I think these diagnostics are dubious with -fno-strict-aliasing which
> essentially says you can access every object via any other objects type.
The source has no such access, though: each function reads and writes
members through its own types, and every byte touched is inside the
object. The "struct big" access to a "struct small" exists only in the
body ICF picked, so the warning is about code GCC wrote rather than
code the programmer wrote.
> So instead of this I'd rather work towards inlining the original
> body rather than the ICF prevailing one.
That does seem like it could be better, but it's not clear to me how
large a project that would be to accomplish.
This patch seems to DTRT, though. It doesn't appear to regress merging
in a meaningful way for the Linux at least.
> And force-disable these kind of diagnostics with -fno-strict-aliasing?
I'd really rather not. Linux builds everything with -fno-strict-aliasing,
so that would remove these checks from the kernel entirely. GCC's
-Warray-bounds is still off by default for the kernel because of false
positives like this one (which is why I'm trying to solve it), and I've
been working toward enabling it, since it finds real bugs. (I have a
stack of a dozen real issues that this found while doing a recent pass.)
For example (since I don't yet have links to the above stack), here
are some random examples from a few years ago: a response struct passed
where a bigger error struct was expected, whose "error" field was past
the end of the object[1]:
drivers/thunderbolt/xdomain.c:226:22: error: array subscript 'const struct tb_xdp_error_response[0]' is partly outside array bounds of 'struct tb_xdp_properties_changed_response[1]'
and a u64 remainder stored into an int on the stack[2]:
include/linux/math64.h:56:20: error: array subscript 'u64 {aka long long unsigned int}[0]' is partly outside array bounds of 'int[1]'
But if you did disable diagnostics, which did you have in mind? If it's
only warnings about an access whose type is bigger than the object while
the bytes it touches are in bounds, that's narrower, but the first
example above would still need to be caught, so I'd much rather just
get ICF behaving nicely. :)
-Kees
[1] https://git.kernel.org/linus/19813551701d0
[2] https://git.kernel.org/linus/9f3d543a9f737
On Wed, 14 Oct 2026, Kees Cook wrote:
> On Sun, Oct 11, 2026 at 04:50:41PM +0200, Richard Biener wrote:
> > > In function 'small_to_big', inlined from 'f' at t.c:22:3:
> > > warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
> >
> > I think these diagnostics are dubious with -fno-strict-aliasing which
> > essentially says you can access every object via any other objects type.
>
> The source has no such access, though: each function reads and writes
> members through its own types, and every byte touched is inside the
> object. The "struct big" access to a "struct small" exists only in the
> body ICF picked, so the warning is about code GCC wrote rather than
> code the programmer wrote.
>
> > So instead of this I'd rather work towards inlining the original
> > body rather than the ICF prevailing one.
>
> That does seem like it could be better, but it's not clear to me how
> large a project that would be to accomplish.
I think for the case of ICF and non-LTO it should be possible to
"hack" this in; it should be just to make sure the inline edges
point to the original body and hopefully the ICF "merge" is somehow
encoded clearly. When the inline edge is set up correctly it should
possibly even work with LTO.
> This patch seems to DTRT, though. It doesn't appear to regress merging
> in a meaningful way for the Linux at least.
I don't dispute this, but it feels like a hack. Either ICF should
work as if -fstrict-aliasing were given, but consistently so, and
for a good reason, or you could as well do -fno-ipa-icf when
building the kernel as you are doing so many we-don't-quite-want-C
things already.
> > And force-disable these kind of diagnostics with -fno-strict-aliasing?
>
> I'd really rather not. Linux builds everything with -fno-strict-aliasing,
> so that would remove these checks from the kernel entirely. GCC's
> -Warray-bounds is still off by default for the kernel because of false
> positives like this one (which is why I'm trying to solve it), and I've
> been working toward enabling it, since it finds real bugs. (I have a
> stack of a dozen real issues that this found while doing a recent pass.)
>
> For example (since I don't yet have links to the above stack), here
> are some random examples from a few years ago: a response struct passed
> where a bigger error struct was expected, whose "error" field was past
> the end of the object[1]:
>
> drivers/thunderbolt/xdomain.c:226:22: error: array subscript 'const struct tb_xdp_error_response[0]' is partly outside array bounds of 'struct tb_xdp_properties_changed_response[1]'
>
> and a u64 remainder stored into an int on the stack[2]:
>
> include/linux/math64.h:56:20: error: array subscript 'u64 {aka long long unsigned int}[0]' is partly outside array bounds of 'int[1]'
>
> But if you did disable diagnostics, which did you have in mind? If it's
> only warnings about an access whose type is bigger than the object while
> the bytes it touches are in bounds, that's narrower, but the first
> example above would still need to be caught, so I'd much rather just
> get ICF behaving nicely. :)
>
> -Kees
>
> [1] https://git.kernel.org/linus/19813551701d0
> [2] https://git.kernel.org/linus/9f3d543a9f737
>
>
On Thu, 15 Oct 2026, Richard Biener wrote:
> On Wed, 14 Oct 2026, Kees Cook wrote:
>
> > On Sun, Oct 11, 2026 at 04:50:41PM +0200, Richard Biener wrote:
> > > > In function 'small_to_big', inlined from 'f' at t.c:22:3:
> > > > warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
> > >
> > > I think these diagnostics are dubious with -fno-strict-aliasing which
> > > essentially says you can access every object via any other objects type.
> >
> > The source has no such access, though: each function reads and writes
> > members through its own types, and every byte touched is inside the
> > object. The "struct big" access to a "struct small" exists only in the
> > body ICF picked, so the warning is about code GCC wrote rather than
> > code the programmer wrote.
> >
> > > So instead of this I'd rather work towards inlining the original
> > > body rather than the ICF prevailing one.
> >
> > That does seem like it could be better, but it's not clear to me how
> > large a project that would be to accomplish.
>
> I think for the case of ICF and non-LTO it should be possible to
> "hack" this in; it should be just to make sure the inline edges
> point to the original body and hopefully the ICF "merge" is somehow
> encoded clearly. When the inline edge is set up correctly it should
> possibly even work with LTO.
I one-shotted the attached. It definitely fails to do this in a
proper IPA way - it should have used IPA function/variable transform
stages and stream out the "defered aliases" in
write/read_optimization_summary.
I'm sure this can be completed with some interaction, but our AI
policy makes this questionable.
Richard.
> > This patch seems to DTRT, though. It doesn't appear to regress merging
> > in a meaningful way for the Linux at least.
>
> I don't dispute this, but it feels like a hack. Either ICF should
> work as if -fstrict-aliasing were given, but consistently so, and
> for a good reason, or you could as well do -fno-ipa-icf when
> building the kernel as you are doing so many we-don't-quite-want-C
> things already.
>
> > > And force-disable these kind of diagnostics with -fno-strict-aliasing?
> >
> > I'd really rather not. Linux builds everything with -fno-strict-aliasing,
> > so that would remove these checks from the kernel entirely. GCC's
> > -Warray-bounds is still off by default for the kernel because of false
> > positives like this one (which is why I'm trying to solve it), and I've
> > been working toward enabling it, since it finds real bugs. (I have a
> > stack of a dozen real issues that this found while doing a recent pass.)
> >
> > For example (since I don't yet have links to the above stack), here
> > are some random examples from a few years ago: a response struct passed
> > where a bigger error struct was expected, whose "error" field was past
> > the end of the object[1]:
> >
> > drivers/thunderbolt/xdomain.c:226:22: error: array subscript 'const struct tb_xdp_error_response[0]' is partly outside array bounds of 'struct tb_xdp_properties_changed_response[1]'
> >
> > and a u64 remainder stored into an int on the stack[2]:
> >
> > include/linux/math64.h:56:20: error: array subscript 'u64 {aka long long unsigned int}[0]' is partly outside array bounds of 'int[1]'
> >
> > But if you did disable diagnostics, which did you have in mind? If it's
> > only warnings about an access whose type is bigger than the object while
> > the bytes it touches are in bounds, that's narrower, but the first
> > example above would still need to be caught, so I'd much rather just
> > get ICF behaving nicely. :)
> >
> > -Kees
> >
> > [1] https://git.kernel.org/linus/19813551701d0
> > [2] https://git.kernel.org/linus/9f3d543a9f737
> >
> >
>
>
On Thu, 15 Oct 2026, Richard Biener wrote:
> On Thu, 15 Oct 2026, Richard Biener wrote:
>
> > On Wed, 14 Oct 2026, Kees Cook wrote:
> >
> > > On Sun, Oct 11, 2026 at 04:50:41PM +0200, Richard Biener wrote:
> > > > > In function 'small_to_big', inlined from 'f' at t.c:22:3:
> > > > > warning: array subscript 'struct big[0]' is partly outside array bounds of 'struct small[1]' [-Warray-bounds=]
> > > >
> > > > I think these diagnostics are dubious with -fno-strict-aliasing which
> > > > essentially says you can access every object via any other objects type.
> > >
> > > The source has no such access, though: each function reads and writes
> > > members through its own types, and every byte touched is inside the
> > > object. The "struct big" access to a "struct small" exists only in the
> > > body ICF picked, so the warning is about code GCC wrote rather than
> > > code the programmer wrote.
> > >
> > > > So instead of this I'd rather work towards inlining the original
> > > > body rather than the ICF prevailing one.
> > >
> > > That does seem like it could be better, but it's not clear to me how
> > > large a project that would be to accomplish.
> >
> > I think for the case of ICF and non-LTO it should be possible to
> > "hack" this in; it should be just to make sure the inline edges
> > point to the original body and hopefully the ICF "merge" is somehow
> > encoded clearly. When the inline edge is set up correctly it should
> > possibly even work with LTO.
>
> I one-shotted the attached. It definitely fails to do this in a
> proper IPA way - it should have used IPA function/variable transform
> stages and stream out the "defered aliases" in
> write/read_optimization_summary.
>
> I'm sure this can be completed with some interaction, but our AI
> policy makes this questionable.
A few kg CO2 later here's a prototype that looks like proper IPA
and LTO capable. Note it still does varpool handling early which
I think is OK. I'm not sure it fits a possible design of different
inline from non-inline bodies in more general (GNU extern inline).
Thanks,
Richard.
> Richard.
>
> > > This patch seems to DTRT, though. It doesn't appear to regress merging
> > > in a meaningful way for the Linux at least.
> >
> > I don't dispute this, but it feels like a hack. Either ICF should
> > work as if -fstrict-aliasing were given, but consistently so, and
> > for a good reason, or you could as well do -fno-ipa-icf when
> > building the kernel as you are doing so many we-don't-quite-want-C
> > things already.
> >
> > > > And force-disable these kind of diagnostics with -fno-strict-aliasing?
> > >
> > > I'd really rather not. Linux builds everything with -fno-strict-aliasing,
> > > so that would remove these checks from the kernel entirely. GCC's
> > > -Warray-bounds is still off by default for the kernel because of false
> > > positives like this one (which is why I'm trying to solve it), and I've
> > > been working toward enabling it, since it finds real bugs. (I have a
> > > stack of a dozen real issues that this found while doing a recent pass.)
> > >
> > > For example (since I don't yet have links to the above stack), here
> > > are some random examples from a few years ago: a response struct passed
> > > where a bigger error struct was expected, whose "error" field was past
> > > the end of the object[1]:
> > >
> > > drivers/thunderbolt/xdomain.c:226:22: error: array subscript 'const struct tb_xdp_error_response[0]' is partly outside array bounds of 'struct tb_xdp_properties_changed_response[1]'
> > >
> > > and a u64 remainder stored into an int on the stack[2]:
> > >
> > > include/linux/math64.h:56:20: error: array subscript 'u64 {aka long long unsigned int}[0]' is partly outside array bounds of 'int[1]'
> > >
> > > But if you did disable diagnostics, which did you have in mind? If it's
> > > only warnings about an access whose type is bigger than the object while
> > > the bytes it touches are in bounds, that's narrower, but the first
> > > example above would still need to be caught, so I'd much rather just
> > > get ICF behaving nicely. :)
> > >
> > > -Kees
> > >
> > > [1] https://git.kernel.org/linus/19813551701d0
> > > [2] https://git.kernel.org/linus/9f3d543a9f737
> > >
> > >
> >
> >
>
>
On Thu, Oct 15, 2026 at 02:04:44PM +0200, Richard Biener wrote:
> A few kg CO2 later here's a prototype that looks like proper IPA
> and LTO capable. Note it still does varpool handling early which
> I think is OK. I'm not sure it fits a possible design of different
> inline from non-inline bodies in more general (GNU extern inline).
Thanks for this! I gave it a spin. It fixes both PR105438
testcases and a static-function case (the second patch adds it as
gcc.dg/ipa/pr105438-5.c), but I ran into a few problems. These are solved
by the two attached patches that apply on top of yours (on 84348add236):
1. Wrong code from IPA-CP. With the alias deferred, IPA-CP runs between
the merge decision and the alias. For a local function it can't
clone, it narrows the parameter ranges in place to what its own
calls pass, so making the other function an alias of it sends it
values outside them. 27 of the c-c++-common/torture/
builtin-arith-overflow tests abort at -O2 -flto, in C and C++, and
this aborts at plain -O2:
__attribute__ ((noinline, noclone)) static int
f1 (int x, int y) { return x * 7 + y; }
__attribute__ ((noinline, noclone)) static int
f2 (int x, int y) { return x * 7 + y; }
__attribute__ ((noinline)) int t1 (void) { return f1 (2, 3); }
__attribute__ ((noinline)) int t2 (void) { return f2 (5, 1); }
t2 returns 17. The first patch makes the alias, or redirects the
alias's calls, only when the ranges IPA-CP gave the alias's
parameters are within the original's.
2. Nodes in deferred_merge_aliases can be removed before the list is
processed, by the IPA passes between ICF and the inliner. Building
the kernel's fs/ext4/super.c crashed in
can_remove_if_no_direct_calls_p on a removed node. The first patch
adds a cgraph removal hook.
3. Your g++.dg/lto/pr105438_0.C passes without your patch: with -r the
link is incremental and ICF never runs. The first patch adds
-flinker-output=nolto-rel so it'll fail on master and pass with
your patch.
4. It doesn't look like the optimization summary and the function
transform are needed. Under LTO the inliner, and with it the alias
creation, runs at WPA, so the aliases reach LTRANS the way ICF's
aliases do now, and inline_transform already redirects the call
statements. At LTRANS every streamed pair should already be an
alias. Reading them also opened an ICF dump at LTRANS, which
outputs.exp reports as an extra file (68 new FAILs). The first patch
removes both hooks.
5. Only the alias path was deferred, so merges that took the
wrapper/redirect path still inlined the other body: two global
functions (both addresses matter), and everything on targets
without symbol aliases. My original two-global-functions case still
warned. The second patch handles that path with an inline-only copy:
before the calls are redirected, the merged function's direct calls
go to a copy of its own body, the wrapper is made as before, and
after inlining the calls that weren't inlined go to the original and
the copies go away. (I first tried just deferring the wrapper, but
then the inliner never inlines the original into the wrapper, which
changed code generation all over the testsuite and broke
always_inline functions and interrupt handlers.)
With both patches on yours, check-c and check-c++ on x86_64 match
master. For the paths without symbol aliases I checked with an
x86_64-apple-darwin cross compiler. An x86_64 allmodconfig kernel build
gets the same ICF merge count as master and 7038 bytes more text (of
648 MB, so no big deal).
The kernel case that started this, net/ipv6/ip6_tunnel.c, gets 16
warnings on m68k from GCC 16 but none from master, where r17-4004's
check keeps the two functions apart because of their memcpy. The same
code without the memcpy still gets the 16 warnings from master on
m68k, and none with your patch, with or without mine on top.
> > I'm sure this can be completed with some interaction, but our AI
> > policy makes this questionable.
These were written with an LLM's help too, especially the build
orchestration and test creation. It has been explaining the glitches it
found to me, and that's shaped the code, but I'm hardly a subject matter
expert on aliases, inlining, and ICF. :P
But if this direction looks right to you, we don't need my access
path patch.
-Kees
On Thu, 15 Oct 2026, Kees Cook wrote:
> On Thu, Oct 15, 2026 at 02:04:44PM +0200, Richard Biener wrote:
> > A few kg CO2 later here's a prototype that looks like proper IPA
> > and LTO capable. Note it still does varpool handling early which
> > I think is OK. I'm not sure it fits a possible design of different
> > inline from non-inline bodies in more general (GNU extern inline).
>
> Thanks for this! I gave it a spin. It fixes both PR105438
> testcases and a static-function case (the second patch adds it as
> gcc.dg/ipa/pr105438-5.c), but I ran into a few problems. These are solved
> by the two attached patches that apply on top of yours (on 84348add236):
>
> 1. Wrong code from IPA-CP. With the alias deferred, IPA-CP runs between
> the merge decision and the alias. For a local function it can't
> clone, it narrows the parameter ranges in place to what its own
> calls pass, so making the other function an alias of it sends it
> values outside them. 27 of the c-c++-common/torture/
> builtin-arith-overflow tests abort at -O2 -flto, in C and C++, and
> this aborts at plain -O2:
>
> __attribute__ ((noinline, noclone)) static int
> f1 (int x, int y) { return x * 7 + y; }
> __attribute__ ((noinline, noclone)) static int
> f2 (int x, int y) { return x * 7 + y; }
>
> __attribute__ ((noinline)) int t1 (void) { return f1 (2, 3); }
> __attribute__ ((noinline)) int t2 (void) { return f2 (5, 1); }
>
> t2 returns 17. The first patch makes the alias, or redirects the
> alias's calls, only when the ranges IPA-CP gave the alias's
> parameters are within the original's.
>
> 2. Nodes in deferred_merge_aliases can be removed before the list is
> processed, by the IPA passes between ICF and the inliner. Building
> the kernel's fs/ext4/super.c crashed in
> can_remove_if_no_direct_calls_p on a removed node. The first patch
> adds a cgraph removal hook.
>
> 3. Your g++.dg/lto/pr105438_0.C passes without your patch: with -r the
> link is incremental and ICF never runs. The first patch adds
> -flinker-output=nolto-rel so it'll fail on master and pass with
> your patch.
>
> 4. It doesn't look like the optimization summary and the function
> transform are needed. Under LTO the inliner, and with it the alias
> creation, runs at WPA, so the aliases reach LTRANS the way ICF's
> aliases do now, and inline_transform already redirects the call
> statements. At LTRANS every streamed pair should already be an
> alias. Reading them also opened an ICF dump at LTRANS, which
> outputs.exp reports as an extra file (68 new FAILs). The first patch
> removes both hooks.
>
> 5. Only the alias path was deferred, so merges that took the
> wrapper/redirect path still inlined the other body: two global
> functions (both addresses matter), and everything on targets
> without symbol aliases. My original two-global-functions case still
> warned. The second patch handles that path with an inline-only copy:
> before the calls are redirected, the merged function's direct calls
> go to a copy of its own body, the wrapper is made as before, and
> after inlining the calls that weren't inlined go to the original and
> the copies go away. (I first tried just deferring the wrapper, but
> then the inliner never inlines the original into the wrapper, which
> changed code generation all over the testsuite and broke
> always_inline functions and interrupt handlers.)
>
> With both patches on yours, check-c and check-c++ on x86_64 match
> master. For the paths without symbol aliases I checked with an
> x86_64-apple-darwin cross compiler. An x86_64 allmodconfig kernel build
> gets the same ICF merge count as master and 7038 bytes more text (of
> 648 MB, so no big deal).
>
> The kernel case that started this, net/ipv6/ip6_tunnel.c, gets 16
> warnings on m68k from GCC 16 but none from master, where r17-4004's
> check keeps the two functions apart because of their memcpy. The same
> code without the memcpy still gets the 16 warnings from master on
> m68k, and none with your patch, with or without mine on top.
>
> > > I'm sure this can be completed with some interaction, but our AI
> > > policy makes this questionable.
>
> These were written with an LLM's help too, especially the build
> orchestration and test creation. It has been explaining the glitches it
> found to me, and that's shaped the code, but I'm hardly a subject matter
> expert on aliases, inlining, and ICF. :P
>
> But if this direction looks right to you, we don't need my access
> path patch.
So I've thrown the patchset of three back to the LLM for review
with the following result. At this point I'd expect guidance
from IPA folks.
Richard.
# Code Review: IPA-ICF Deferred Merging Series [PR ipa/105438]
This document reviews the top three commits on `master` in `gcc/`:
1. **`4b2f31435c7`** (`Richard Biener`): *ipa-icf: Defer creating aliases until after inlining [PR105438]*
2. **`4d613c36ad6`** (`Kees Cook`): *ipa-icf: Keep deferred merges from bypassing IPA-CP [PR105438]*
3. **`5e4bdec0d78`** (`Kees Cook`): *ipa-icf: Inline the merged function's own body when it becomes a wrapper [PR105438]*
---
## 1. Executive Summary & Architectural Critique
The series attempts to address **PR ipa/105438**, where Identical Code Folding (IPA-ICF) merges two functions operating on different types (such as different structure layouts or array bounds). When ICF replaces one function with an alias or wrapper of the other prior to inlining, inlining calls to the merged function substitutes the prevailing function's body, whose types do not match the caller's arguments. This leads to bogus `-Warray-bounds` warnings, diagnostic confusion, and potential Type-Based Alias Analysis (TBAA) issues.
Rather than addressing type compatibility during ICF equivalence checking or handling diagnostics during inlining, the series defers ICF alias creation and body deletion until post-inlining (`ipa_inline ()`).
### Fundamental Architectural Breakdown
Deferring the transformation of an early IPA pass across subsequent passes breaks fundamental pipeline invariants in GCC:
```
[pass_ipa_icf] -> [pass_ipa_devirt] -> [pass_ipa_cp] -> [pass_ipa_sra] -> [pass_ipa_fn_summary] -> [pass_ipa_inline]
| |
+--- "Deferred Merges" list (unapplied side-effects) ------------------------------------------------>+
```
1. **Inter-Pass Desynchronization:**
`pass_ipa_devirt`, `pass_ipa_cp`, `pass_ipa_sra`, and `pass_ipa_fn_summary` run between ICF and inlining. Because the functions are kept separate, each pass analyzes and optimizes `alias` and `original` independently based only on their local call sites:
- **IPA-CP** narrows parameter ranges in-place or creates specialized clones for one function without the other.
- **IPA-SRA** splits aggregate parameters or eliminates unused arguments on one function without the other.
- **IPA-fnsummary** computes separate size, time, and growth summaries.
Applying ICF merges post-inlining forces two functions together that intermediate passes have diverged, causing invalid GIMPLE, signature mismatches, or silent abandonment of ICF merges.
2. **Heuristic & Metric Distortion:**
Inlining decisions depend on size summaries and growth estimations. Retaining duplicate bodies throughout inlining distorts the inliner's badness queue and unit growth limits (`estimate_growth`), causing the inliner to evaluate candidates under false assumptions.
3. **Memory Inversion:**
ICF exists to eliminate duplicate code and conserve memory. By creating version clones (`create_version_clone_with_body`) for wrapper merges and retaining all unmerged bodies through IPA passes, peak compiler memory consumption (RSS) is increased rather than reduced.
4. **LTO Ineffectiveness:**
At WPA time under LTO, function bodies are not loaded. Clone creation in commit 3 immediately bails out (`if (in_lto_p ... ) return 0;`), redirecting callers directly to the prevailing function before inlining. Consequently, under LTO, PR 105438 remains completely unfixed for wrapper/redirection merges.
---
## 2. In-Depth Critique per Commit
### Commit 1: `4b2f31435c7`
*Author: Richard Biener <rguenther@suse.de>*
*Commit: `ipa-icf: Defer creating aliases until after inlining [PR105438]`*
#### Key Defects:
1. **Inlining Decision Asymmetry and Lost Merges:**
```cpp
if (original->inlined_to)
continue;
```
If `original` is a local function called only once, the inliner inlines it into its single caller and marks `original->inlined_to != NULL`. Post-inlining, `ipa_icf_create_deferred_aliases` encounters this check and drops the merge completely. `alias`, which may have multiple un-inlined callers, is left unmerged. Whether two functions are merged becomes arbitrarily dependent on symbol table hash ordering (which selects which function is `original` vs `alias`).
2. **Inliner Cost and Growth Distortion:**
Retaining `alias` as a full body through `ipa_fn_summary` and `ipa_inline` means `estimate_growth` treats `alias` as an independent entity that must be preserved offline unless inlined into all callers. The inliner does not credit the elimination of `alias` as an alias, skewing the inlining priority queue across the entire translation unit.
3. **Stale Profile Merging:**
`ipa_merge_profiles (original, alias)` is deferred until after inlining. Callsite edge counts inlined during `ipa_inline` were calculated using unmerged, isolated profiles. Merging profiles post-inlining fails to back-propagate through already-inlined call sites, producing inconsistent frequency estimates in downstream RTL and tree passes.
4. **Flawed LTO Summary Streaming:**
The commit originally introduced `ipa_icf_write_optimization_summary`, `ipa_icf_read_optimization_summary`, and `ipa_icf_transform`. Under LTO, `ipa_inline` runs at WPA and executes `ipa_icf_create_deferred_aliases ()`, creating symbol aliases before LTRANS partitions are formed. Streaming deferred aliases to LTRANS was completely redundant and produced extraneous ICF dump files in LTRANS runs (prompting removal in commit 2).
5. **Unchecked Clones on `original`:**
In `ipa_icf_create_deferred_aliases`:
```cpp
if (alias->clones || (in_lto_p && original->in_other_partition))
{
redirect_all_callers (alias, original);
continue;
}
```
The check only tests `alias->clones` and ignores `original->clones`. If `original` was cloned or specialized by an intermediate pass, creating an alias directly to `original->decl` bypasses those clones or targets an unspecialized node.
---
### Commit 2: `4d613c36ad6`
*Author: Kees Cook <kees@kernel.org>*
*Commit: `ipa-icf: Keep deferred merges from bypassing IPA-CP [PR105438]`*
#### Key Defects:
1. **Symptom-Patching That Silently Drops Valid Merges:**
Commit 2 adds `ipcp_compatible_p` to verify whether parameter ranges narrowed by IPA-CP allow merging. If `ipcp_compatible_p` returns `false`, ICF's equivalence decision is silently abandoned. Deferring the merge directly causes IPA-CP to narrow ranges based on partial caller subsets, which subsequently prevents the merge.
2. **Complete Neglect of IPA-SRA Signature Transformations:**
`ipcp_compatible_p` checks only `ipcp_transformation` (`m_vr` and `m_agg_values`). It completely ignores `pass_ipa_sra`, which also executes between ICF and inlining. IPA-SRA can split aggregate parameters or eliminate unused arguments. If IPA-SRA modifies `original` but not `alias`, post-inlining alias creation or redirection links call sites to functions with mismatched signatures, producing invalid GIMPLE and potential compiler crashes.
3. **Spurious Incompatibility via `types_compatible_p`:**
In `ipcp_compatible_p`:
```cpp
const ipa_vr &fvr = (*ft->m_vr)[i];
if (!types_compatible_p (tvr.type (), fvr.type ()))
return false;
```
PR 105438 specifically arises when ICF merges functions operating on distinct pointer/struct types (e.g. `struct small *` vs `struct big *`). If IPA-CP happens to deduce a value range for a pointer argument (e.g. non-null), `types_compatible_p` returns `false` due to differing base types. Consequently, the merge is rejected if IPA-CP discovered non-nullness, but accepted if IPA-CP discovered nothing.
4. **Unhandled IPA-CP Cloning:**
If IPA-CP specializes `original` by creating a clone (`create_specialized_node`) and redirects `original`'s callers to it, `original` may be left as an unspecialized or uncalled node. Redirecting `alias`'s callers to `original` routes execution to an unspecialized stub.
5. **Missed-Optimization Enshrined in Testsuite:**
In `gcc.dg/ipa/pr105438-4.c`:
```c
/* { dg-final { scan-ipa-dump {ICF: f[12]/[0-9]+ keeps its body; IPA-CP specialized f[12]/[0-9]+ for other calls} "inline" { target alias } } } */
/* { dg-final { scan-ipa-dump-not {ICF: f[12]/[0-9]+ is now an alias} "inline" } } */
```
The test explicitly asserts that ICF failed to merge identical functions, codifying an optimization regression as expected behavior.
6. **Contribution Policy / Metadata:**
The commit trailer `Assisted-by: LLM [tests]` should be placed in the commit narrative rather than formatted as an official git trailer to conform to upstream GCC contribution and DCO guidelines.
---
### Commit 3: `5e4bdec0d78`
*Author: Kees Cook <kees@kernel.org>*
*Commit: `ipa-icf: Inline the merged function's own body when it becomes a wrapper [PR105438]`*
#### Key Defects:
1. **Ineffective Under LTO (WPA):**
In `make_inline_copy`:
```cpp
if (in_lto_p
|| !gimple_has_body_p (alias->decl)
|| lookup_attribute ("noclone", DECL_ATTRIBUTES (alias->decl))
|| lookup_attribute ("noipa", DECL_ATTRIBUTES (alias->decl)))
return 0;
```
Because function bodies are not loaded at WPA time, `in_lto_p` causes `make_inline_copy` to immediately return `0`. Callers are redirected to `local_original` before inlining. At WPA, `ipa_inline` inlines `local_original`'s body into `alias`'s callers, leaving PR 105438 completely unfixed for LTO wrapper merges.
2. **Re-Duplication Defeating ICF Goals:**
When wrapper merges occur, `make_inline_copy` calls `alias->create_version_clone_with_body ()`. This allocates a third copy of the function body (CFG, gimple statements, SSA names). In codebases with numerous duplicate functions (such as C++ template instantiations), this significantly increases compiler peak RSS during IPA.
3. **Inlining Heuristics Subverted via `force_output = true`:**
Setting `copy->force_output = true` marks the clone as an unremovable symbol. In `ipa-inline-analysis.cc`, `will_be_removed_from_program_if_no_direct_calls_p ()` returns `false`, causing `offline_size ()` to return `0`. The inliner calculates code growth without subtracting the elimination of the function body, artificially penalizing inlining of the very clone created specifically to be inlined.
4. **Fragile Dead-Copy Cleanup:**
Because `force_output` is set, `TODO_remove_functions` cannot reclaim copies whose callers disappear. The loop added to `ipa_icf_driver`:
```cpp
for (auto &p : merge_inline_copies)
if (p.first && !p.first->callers)
p.first->force_output = false;
```
only catches callers eliminated during ICF. If an intermediate pass (like `pass_ipa_devirt` or `pass_ipa_cp`) later eliminates the last caller, `copy` remains with `force_output = true` and no callers, reproducing the IPA-CP assertion on an uncalled local function.
5. **Latent Bug in `redirect_all_callers`:**
In `redirect_all_callers`:
```cpp
else
e = e->next_callee;
```
When `e` is an edge in `n->callers`, advancing via `next_callee` traverses the callee chain of `e->caller`, not `n->callers`.
6. **Unscheduled Reachability Sweeps:**
Calling `symtab->remove_unreachable_nodes (dump_file)` directly within `move_inline_copy_calls` triggers a full callgraph sweep outside of the pass manager's standard TODO flag scheduling.
---
## 3. Recommended Structural Solutions
Rather than maintaining deferred state across five intermediate IPA passes, PR ipa/105438 should be solved through one of the following architectural approaches:
### Approach A: Differentiate Incompatible Layouts at ICF Time
If inlining a merged function will cause invalid memory references, diagnostic warnings, or TBAA violations due to mismatched pointer types or array bounds, ICF's equivalence checks (`func_checker::compatible_types_p` and `func_checker::compare_operand`) should not declare the functions identical when:
- Parameter types differ in array bounds or struct sizes.
- Memory access offsets or base types are not strictly identical across types.
### Approach B: Schedule ICF Post-Inlining
If ICF is intended to merge functions that survive inlining without impacting inlining decisions or diagnostics:
- Schedule an ICF pass after `pass_ipa_inline` (or as a late IPA / LTRANS deduplication pass).
- When ICF runs post-inlining, inlining has already completed using each caller's original body. ICF then only merges remaining out-of-line functions, eliminating the need for deferred alias vectors, removal hooks, inline-only copies, or IPA-CP compatibility checks.
On Mon, Oct 19, 2026 at 02:17:47PM +0200, Richard Biener wrote:
> ## 3. Recommended Structural Solutions
>
> Rather than maintaining deferred state across five intermediate IPA passes, PR ipa/105438 should be solved through one of the following architectural approaches:
>
> ### Approach A: Differentiate Incompatible Layouts at ICF Time
> If inlining a merged function will cause invalid memory references, diagnostic warnings, or TBAA violations due to mismatched pointer types or array bounds, ICF's equivalence checks (`func_checker::compatible_types_p` and `func_checker::compare_operand`) should not declare the functions identical when:
> - Parameter types differ in array bounds or struct sizes.
> - Memory access offsets or base types are not strictly identical across types.
Heh. I think this is describing the original patch I sent that started
this thread? :P
-Kees
new file mode 100644
@@ -0,0 +1,33 @@
+// PR ipa/105438
+// { dg-do compile }
+// { dg-options "-O2 -fno-strict-aliasing -fno-early-inlining -Warray-bounds -fdump-ipa-icf-optimized" }
+
+// With -fno-strict-aliasing, IPA ICF merged configure<7> and configure<2>,
+// whose accesses through IN differ only in the bound of the array type,
+// and the merged body, inlined for the call with SHORTER, read it as a
+// const int[7]. (-fno-early-inlining keeps the instantiations from being
+// inlined into main before ICF runs.)
+
+int longer[7] = {};
+int shorter[2] = {};
+int out[10] = {};
+
+template <int N>
+void configure(const int(&in)[N], const int nrows = N)
+{
+ if (nrows <= 10)
+ {
+ for (int i = 0; i < nrows; i++)
+ {
+ out[i] = in[i]; // { dg-bogus "outside array bounds" }
+ }
+ }
+}
+
+int main()
+{
+ configure(longer);
+ configure(shorter);
+}
+
+// { dg-final { scan-ipa-dump-not "Semantic equality hit" "icf" } }
new file mode 100644
@@ -0,0 +1,73 @@
+/* Verify that with -fno-strict-aliasing, IPA ICF doesn't merge functions
+ whose memory accesses go through types of different sizes, which would
+ put one function's types into the other's inlined copies, and that it
+ still merges functions whose accesses go through the same types, or
+ through distinct types of the same layout.
+ { dg-do compile }
+ { dg-options "-O2 -fno-strict-aliasing -fno-early-inlining -Warray-bounds -fdump-ipa-icf-optimized" } */
+
+struct small { char pad[16]; int a; unsigned int b, c; };
+struct big { char pad[16]; int a; unsigned int b, c; int extra; };
+struct small_twin { char pad[16]; int a; unsigned int b, c; };
+
+/* Not merged: the same offsets, but through types of different sizes.
+ Merged, the call to big_to_small in f would get small_to_big's body,
+ which stores to TMP through a "struct big *". */
+
+void small_to_big (struct big *dst, const struct small *src)
+{
+ dst->a = src->a; /* { dg-bogus "outside array bounds" } */
+ dst->b = src->b; /* { dg-bogus "outside array bounds" } */
+ dst->c = src->c; /* { dg-bogus "outside array bounds" } */
+}
+
+void big_to_small (struct small *dst, const struct big *src)
+{
+ dst->a = src->a;
+ dst->b = src->b;
+ dst->c = src->c;
+}
+
+void f (struct big *p)
+{
+ struct small tmp;
+
+ big_to_small (&tmp, p);
+ small_to_big (p, &tmp);
+}
+
+/* Merged: the same types. */
+
+void big_to_big_1 (struct big *dst, const struct big *src)
+{
+ dst->a = src->a;
+ dst->b = src->b;
+ dst->c = src->c;
+}
+
+void big_to_big_2 (struct big *dst, const struct big *src)
+{
+ dst->a = src->a;
+ dst->b = src->b;
+ dst->c = src->c;
+}
+
+/* Merged: distinct types of the same layout. */
+
+void small_to_twin (struct small_twin *dst, const struct small *src)
+{
+ dst->a = src->a;
+ dst->b = src->b;
+ dst->c = src->c;
+}
+
+void twin_to_small (struct small *dst, const struct small_twin *src)
+{
+ dst->a = src->a;
+ dst->b = src->b;
+ dst->c = src->c;
+}
+
+/* { dg-final { scan-ipa-dump-not {Semantic equality hit:[^\n]*(small_to_big|big_to_small)/} "icf" } } */
+/* { dg-final { scan-ipa-dump {Semantic equality hit:big_to_big_[12]/[0-9]+->big_to_big_[12]/[0-9]+} "icf" } } */
+/* { dg-final { scan-ipa-dump {Semantic equality hit:(small_to_twin|twin_to_small)/[0-9]+->(small_to_twin|twin_to_small)/[0-9]+} "icf" } } */
new file mode 100644
@@ -0,0 +1,75 @@
+/* Verify that with -fno-strict-aliasing, IPA ICF compares each level of
+ an access path, not just its base: an array element against a scalar
+ member, a nested size mismatch, an array member that ends its object
+ against one that doesn't, and a flexible array member against a
+ zero-length one keep functions apart, while
+ flexible array members of the same layout, and identical functions
+ accessing variably modified types, still merge.
+ { dg-do compile }
+ { dg-options "-O2 -fno-strict-aliasing -fdump-ipa-icf-details" } */
+
+/* ICF hashes memory accesses with their alias sets even with
+ -fno-strict-aliasing, so functions accessing distinct structs would
+ not get the same hash and would never be compared. may_alias gives
+ each struct alias set 0, so each pair below is compared, which the
+ "Equals called for" scans check, along with the reason for each
+ refusal. */
+
+#define MA __attribute__ ((may_alias))
+
+/* Not merged: the stores are to the same offset and size, but one is to
+ an array element and the other to a scalar member, so the access
+ paths have different tree codes. (The tree code of a load is part of
+ ICF's hash, so a load would not be compared.) */
+
+struct MA c1 { int tag[2]; int x[1]; int y; };
+struct MA c2 { int tag[2]; int x; int y; };
+
+void codes_1 (struct c1 *dst, int v) { dst->x[0] = v; }
+void codes_2 (struct c2 *dst, int v) { dst->x = v; }
+
+/* Not merged: the outer structs are the same size, but the structs
+ holding A are 16 and 8 bytes. */
+
+struct MA n1 { struct { int a; int pad[3]; } in; int t[1]; };
+struct MA n2 { struct { int a; int pad; } in; int t[3]; };
+
+void nested_1 (struct n1 *dst, const struct n1 *src) { dst->in.a = src->in.a; }
+void nested_2 (struct n2 *dst, const struct n2 *src) { dst->in.a = src->in.a; }
+
+/* Not merged: both structs are 16 bytes, but ARR ends struct t1, so it
+ may be a flexible array, and not struct t2. */
+
+struct MA __attribute__ ((aligned (16))) t1 { int tag; int arr[1]; };
+struct MA __attribute__ ((aligned (16))) t2 { int tag; int arr[1]; int x; };
+
+void trailing_1 (struct t1 *dst, const struct t1 *src) { dst->arr[0] = src->arr[0]; }
+void trailing_2 (struct t2 *dst, const struct t2 *src) { dst->arr[0] = src->arr[0]; }
+
+/* Merged: flexible array members, whose types have no size. Not merged:
+ either of those and a zero-length array. */
+
+struct MA f1 { int tag; int arr[]; };
+struct MA f2 { int tag; int arr[]; };
+struct MA z { int tag; int arr[0]; };
+
+void flex_1 (struct f1 *dst, const struct f1 *src, int i) { dst->arr[i] = src->arr[i]; }
+void flex_2 (struct f2 *dst, const struct f2 *src, int i) { dst->arr[i] = src->arr[i]; }
+void zero_len (struct z *dst, const struct z *src, int i) { dst->arr[i] = src->arr[i]; }
+
+/* Merged: the sizes of variably modified types refer to each function's
+ own parameters. */
+
+void vla_1 (int n, int (*p)[n], int i) { p[i][1] = 1; p[i][2] = 2; }
+void vla_2 (int n, int (*p)[n], int i) { p[i][1] = 1; p[i][2] = 2; }
+
+/* Each refusal is logged as its reason, a few more lines, and then the
+ pair compared; match the reason and the pair with no other comparison
+ between them. */
+/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: codes_[12]/[0-9]+:codes_[12]/[0-9]+ with result: false} "icf" } } */
+/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: nested_[12]/[0-9]+:nested_[12]/[0-9]+ with result: false} "icf" } } */
+/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: trailing_[12]/[0-9]+:trailing_[12]/[0-9]+ with result: false} "icf" } } */
+/* { dg-final { scan-ipa-dump {access path difference\)'[^\n]*\n(?:(?!Equals called)[^\n]*\n)*Equals called for: (zero_len/[0-9]+:flex_[12]|flex_[12]/[0-9]+:zero_len)/[0-9]+ with result: false} "icf" } } */
+/* { dg-final { scan-ipa-dump {Semantic equality hit:flex_[12]/[0-9]+->flex_[12]/[0-9]+} "icf" } } */
+/* { dg-final { scan-ipa-dump {Semantic equality hit:vla_[12]/[0-9]+->vla_[12]/[0-9]+} "icf" } } */
+/* { dg-final { scan-ipa-dump-not {Semantic equality hit:[^\n]*(codes_|nested_|trailing_|zero_len)} "icf" } } */
@@ -4262,7 +4262,9 @@ types_equal_for_same_type_for_tbaa_p (tree type1, tree type2)
/* Compare REF1 and REF2 and return flags specifying their differences.
If LTO_STREAMING_SAFE is true do not use alias sets and canonical
types that are going to be recomputed.
- If TBAA is true also compare TBAA metadata. */
+ If TBAA is true also compare TBAA metadata, and otherwise only the
+ shape of the access paths: the tree codes along them, the sizes of
+ their types, and the kind of each array member. */
int
ao_compare::compare_ao_refs (ao_ref *ref1, ao_ref *ref2,
@@ -4379,8 +4381,36 @@ ao_compare::compare_ao_refs (ao_ref *ref1, ao_ref *ref2,
|| (MR_DEPENDENCE_BASE (rbase1) != MR_DEPENDENCE_BASE (rbase2))))
flags |= DEPENDENCE_CLIQUE;
+ /* Without TBAA, the types along the access paths don't matter for
+ aliasing, but other consumers read their sizes (e.g. ranger
+ diagnostics like -Warray-bounds). Require the same tree codes at
+ each level, with sizes that match and array members of the same
+ kind, so the references of a merged function are valid for the
+ callers of both. The types themselves may differ, so functions
+ accessing distinct but identically laid out types still merge. */
if (!tbaa)
- return flags;
+ {
+ tree c1 = ref1->ref, c2 = ref2->ref;
+ while (true)
+ {
+ if (TREE_CODE (c1) != TREE_CODE (c2))
+ return flags | ACCESS_PATH;
+ tree size1 = TYPE_SIZE (TREE_TYPE (c1));
+ tree size2 = TYPE_SIZE (TREE_TYPE (c2));
+ if (size1 && size2
+ ? !operand_equal_p (size1, size2, 0)
+ : size1 != size2)
+ return flags | ACCESS_PATH;
+ if (TREE_CODE (c1) == COMPONENT_REF
+ && component_ref_sam_type (c1) != component_ref_sam_type (c2))
+ return flags | ACCESS_PATH;
+ if (!handled_component_p (c1))
+ break;
+ c1 = TREE_OPERAND (c1, 0);
+ c2 = TREE_OPERAND (c2, 0);
+ }
+ return flags;
+ }
/* Alias sets are not stable across LTO sreaming; be conservative here
and compare types the alias sets are ultimately based on. */