[TargetVersion] Only enable on RISC-V and AArch64 (#115991)
[llvm-project.git] / clang-tools-extra / clang-tidy / bugprone / UndefinedMemoryManipulationCheck.cpp
blob4f6bc18151789da412a53cdf671d2b68f0b7986a
1 //===--- UndefinedMemoryManipulationCheck.cpp - clang-tidy-----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "UndefinedMemoryManipulationCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers;
15 namespace clang::tidy::bugprone {
17 namespace {
18 AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
19 // For incomplete types, assume they are TriviallyCopyable.
20 return Node.hasDefinition() ? !Node.isTriviallyCopyable() : false;
22 } // namespace
24 void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
25 const auto HasNotTriviallyCopyableDecl =
26 hasDeclaration(cxxRecordDecl(isNotTriviallyCopyable()));
27 const auto ArrayOfNotTriviallyCopyable =
28 arrayType(hasElementType(HasNotTriviallyCopyableDecl));
29 const auto NotTriviallyCopyableObject = hasType(hasCanonicalType(
30 anyOf(pointsTo(qualType(anyOf(HasNotTriviallyCopyableDecl,
31 ArrayOfNotTriviallyCopyable))),
32 ArrayOfNotTriviallyCopyable)));
34 // Check whether destination object is not TriviallyCopyable.
35 // Applicable to all three memory manipulation functions.
36 Finder->addMatcher(callExpr(callee(functionDecl(hasAnyName(
37 "::memset", "::memcpy", "::memmove"))),
38 hasArgument(0, NotTriviallyCopyableObject))
39 .bind("dest"),
40 this);
42 // Check whether source object is not TriviallyCopyable.
43 // Only applicable to memcpy() and memmove().
44 Finder->addMatcher(
45 callExpr(callee(functionDecl(hasAnyName("::memcpy", "::memmove"))),
46 hasArgument(1, NotTriviallyCopyableObject))
47 .bind("src"),
48 this);
51 void UndefinedMemoryManipulationCheck::check(
52 const MatchFinder::MatchResult &Result) {
53 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("dest")) {
54 QualType DestType = Call->getArg(0)->IgnoreImplicit()->getType();
55 if (!DestType->getPointeeType().isNull())
56 DestType = DestType->getPointeeType();
57 diag(Call->getBeginLoc(), "undefined behavior, destination object type %0 "
58 "is not TriviallyCopyable")
59 << DestType;
61 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("src")) {
62 QualType SourceType = Call->getArg(1)->IgnoreImplicit()->getType();
63 if (!SourceType->getPointeeType().isNull())
64 SourceType = SourceType->getPointeeType();
65 diag(Call->getBeginLoc(),
66 "undefined behavior, source object type %0 is not TriviallyCopyable")
67 << SourceType;
71 } // namespace clang::tidy::bugprone