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

            Bug ID: 106776
           Summary: Unexpected use-after-free warning
           Product: gcc
           Version: 12.2.0
            Status: UNCONFIRMED
          Keywords: diagnostic
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: drfiemost at email dot it
  Target Milestone: ---

Created attachment 53520
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=53520&action=edit
test program

When compiling the attached program with the -O2 and -Wuse-after-free flags I
get the following warning, which seems bogus as the pointer is not actually
dereferenced in case it is deleted:

$ g++ -O2 -Wuse-after-free test_ref.cpp
In member function 'unsigned int counter::decrease()',
    inlined from 'matrix_t::~matrix_t()' at test_ref.cpp:32:38,
    inlined from 'matrix_t* cache(int, const char*)' at test_ref.cpp:53:1:
test_ref.cpp:14:40: warning: pointer used after 'void operator delete(void*,
std::size_t)' [-Wuse-after-free]
   14 |     unsigned int decrease() { return --c; }
      |                                        ^
In destructor 'matrix_t::~matrix_t()',
    inlined from 'std::pair<const int, matrix_t>::~pair()' at
C:/msys64/mingw64/include/c++/12.2.0/bits/stl_pair.h:185:12,
    inlined from 'matrix_t* cache(int, const char*)' at test_ref.cpp:52:40:
test_ref.cpp:32:56: note: call to 'void operator delete(void*, std::size_t)'
here
   32 |     ~matrix_t() { if (count->decrease() == 0) { delete count; delete
data; } }
      |                                                        ^~~~~


The IL dump confirms that the pointer _1 is either accessed <bb 3> or deleted
<bb 5>:

void matrix<short int>::~matrix (struct matrix * const this)
{
  struct counter * _1;
  short int * _2;
  unsigned int _10;
  unsigned int _11;

  <bb 2> [local count: 1073741824]:
  _1 = this_5(D)->count;
  _10 = _1->c;
  _11 = _10 + 4294967295;
  if (_11 == 0)
    goto <bb 5>; [33.00%]
  else
    goto <bb 3>; [67.00%]

  <bb 3> [local count: 719407024]:
  _1->c = _11;

  <bb 4> [local count: 884279007]:
  goto <bb 7>; [100.00%]

  <bb 5> [local count: 354334800]:
  operator delete (_1, 4);
  _2 = this_5(D)->data;
  if (_2 != 0B)
    goto <bb 6>; [53.47%]
  else
    goto <bb 8>; [46.53%]

  <bb 8> [local count: 164871983]:
  goto <bb 4>; [100.00%]

  <bb 6> [local count: 189462817]:
  operator delete [] (_2); [tail call]

  <bb 7> [local count: 1073741824]:
  return;

}

The warning doesn't appear when using the -O1 flag or if the variable is
decalared volatile.
If I'm not missing anything obvious the warning should not be issued at all.

Reply via email to