clang-tidy: introduce readability-containter-data-pointer check
authorSaleem Abdulrasool <compnerd@compnerd.org>
Sun, 29 Aug 2021 05:05:59 +0000 (22:05 -0700)
committerSaleem Abdulrasool <compnerd@compnerd.org>
Tue, 14 Sep 2021 15:12:10 +0000 (08:12 -0700)
commitd0d9e6f0849b2e76e980e2edf365302f47f4e35f
tree235a31ae43d0dd19cc7f8d89d4538a9e7d6af0e8
parent2fd180bbb9a7bb8604a5aca31f1ca9dc5358a433
clang-tidy: introduce readability-containter-data-pointer check

This introduces a new check, readability-containter-data-pointer.  This
check is meant to catch the cases where the user may be trying to
materialize the data pointer by taking the address of the 0-th member of
a container.  With C++11 or newer, the `data` member should be used for
this.  This provides the following benefits:

- `.data()` is easier to read than `&[0]`
- it avoids an unnecessary re-materialization of the pointer
  * this doesn't matter in the case of optimized code, but in the case
    of unoptimized code, this will be visible
- it avoids a potential invalid memory de-reference caused by the
  indexing when the container is empty (in debug mode, clang will
  normally optimize away the re-materialization in optimized builds).

The small potential behavioural change raises the question of where the
check should belong.  A reasoning of defense in depth applies here, and
this does an unchecked conversion, with the assumption that users can
use the static analyzer to catch cases where we can statically identify
an invalid memory de-reference.  For the cases where the static analysis
is unable to prove the size of the container, UBSan can be used to track
the invalid access.

Special thanks to Aaron Ballmann for the discussion on whether this
check would be useful and where to place it.

This also partially resolves PR26817!

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D108893
clang-tools-extra/clang-tidy/readability/CMakeLists.txt
clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp [new file with mode: 0644]
clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.h [new file with mode: 0644]
clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/readability-data-pointer.rst [new file with mode: 0644]
clang-tools-extra/test/clang-tidy/checkers/readability-container-data-pointer.cpp [new file with mode: 0644]