https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127752

--- Comment #3 from Yongqiang Tian <yqtian668 at gmail dot com> ---
Hi Drea,

Thank you for these suggestions.  I investigated both cases on GCC 17 trunk at
a9b19ded78ca2dd8f66b355b05ebbbb149c2d320.

I confirmed that this is not specific to LTO:

* An externally visible object reproduces with -O2 -fwhole-program.
* A static object reproduces with plain -O2, without LTO or
  -fwhole-program.
* The same problem occurs when the volatile member is nested through
  another structure, an array, or a union.

In all of these cases, -fno-ipa-reference-addressable restores the
volatile load.  The IPA dump shows the affected object being marked:

  Varpool flags: initialized read-only const-value-known

I also constructed a more MMIO-like example.  A board linker script maps
the data section from one translation unit to address 0x40000000.  That
translation unit defines an initialized static register-block structure
with a volatile status field.  At -O0, read_status loads from the object
at 0x40000000.  At -O2, GCC replaces the function with a constant return
and removes both the object and the mapped section.  Disabling
-fipa-reference-addressable restores the object, the section, and the
load from 0x40000000.

For completeness, the more usual fixed-address-pointer form and an
object with an explicit section attribute did not reproduce this
particular problem.  The latter is protected by the existing
get_section() check.

I tested a prototype fix in ipa.cc that recursively checks record, union,
and array subobjects for volatile qualification.  A variable containing
such a subobject is then handled like a wholly volatile variable in
process_references(), rather than being marked read-only.  This fixes the
static, -fwhole-program, LTO, nested, and MMIO cases.  Non-volatile
objects and structures that merely contain a pointer to volatile data
remain optimizable.

The targeted DejaGNU test passes, as do the compiler self-tests.  I have
not yet run a full bootstrap and regression test.

Does this IPA-side approach look like the right direction for the
eventual patch?

If you think it make sense, I can run the full test and then open a PR for
this.

Reply via email to