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

--- Comment #4 from tarun thammisetty <thammisettytarun at gmail dot com> ---
Right, the noinline was there to simulate the realistic case where the concrete
type isn't visible at the call site. Here's an updated multi-TU reproducer
without
noinline or noclone that shows the same issue:

base.h:
  #pragma once
  #include <vector>

  struct Base {
    virtual ~Base() = default;
    virtual int f(int x) = 0;
  };

  struct Derived final : Base {
    int val = 0;
    int f(int x) override { val += x; return val; }
  };

  struct Holder { Base* ptr; };
  int process_all(std::vector<Holder>& holders, int x);

dispatch.cpp:
  #include "base.h"

  int process_all(std::vector<Holder>& holders, int x) {
    int sum = 0;
    for (auto& h : holders)
      sum += h.ptr->f(x);
    return sum;
  }

 main.cpp:
  #include "base.h"

  std::vector<Holder> make_holders(int n) {
    std::vector<Holder> v;
    v.reserve(n);
    for (int i = 0; i < n; ++i)
      v.push_back({new Derived()});
    return v;
  }

  int main(int argc, char**) {
    auto v = make_holders(argc);
    int r = process_all(v, argc);
    for (auto& h : v) delete h.ptr;
    return r;
  }

g++-15 -O3 -flto=auto -fno-fat-lto-objects -fwhole-program \
    -fvisibility=hidden -fdevirtualize -fdevirtualize-speculatively \
    -fdevirtualize-at-ltrans -o test main.cpp dispatch.cpp

  GCC inlines process_all into main, but the virtual call is speculative —
guard with indirect fallback:

  mov    0x0(%rbp),%rdi        ; load Base* from Holder
  mov    (%rdi),%rax           ; load vtable pointer
  mov    0x10(%rax),%rax       ; load vtable slot
  cmp    $0x401400,%rax        ; is it Derived::f?
  je     inlined_path          ; yes → inlined Derived::f
  call   *%rax                 ; INDIRECT fallback

0x401400 is Derived::f(int). Only one user vtable in the binary (nm -C test |
grep 'vtable for' shows only vtable for Derived). Derived is final,
-fwhole-program is set — the fallback is unreachable.

On the shared library question: -fwhole-program guarantees main is the only
entry point and no external code exists. Combined with final, no further
subclassing is
possible.  If -fwhole-program isn't sufficient for GCC to close the hierarchy
here, is there another flag or annotation that would be?

Reply via email to