clang-tools 18.0.0git
AssertSideEffectCheck.cpp
Go to the documentation of this file.
1//===--- AssertSideEffectCheck.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//===----------------------------------------------------------------------===//
8
10#include "../utils/Matchers.h"
11#include "../utils/OptionsUtils.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/Lexer.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Support/Casting.h"
19#include <algorithm>
20#include <string>
21
22using namespace clang::ast_matchers;
23
24namespace clang::tidy::bugprone {
25
26namespace {
27
28AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
29 clang::ast_matchers::internal::Matcher<NamedDecl>,
30 IgnoredFunctionsMatcher) {
31 const Expr *E = &Node;
32
33 if (const auto *Op = dyn_cast<UnaryOperator>(E)) {
34 UnaryOperator::Opcode OC = Op->getOpcode();
35 return OC == UO_PostInc || OC == UO_PostDec || OC == UO_PreInc ||
36 OC == UO_PreDec;
37 }
38
39 if (const auto *Op = dyn_cast<BinaryOperator>(E)) {
40 return Op->isAssignmentOp();
41 }
42
43 if (const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E)) {
44 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
45 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
46 OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
47 OpKind == OO_SlashEqual || OpKind == OO_AmpEqual ||
48 OpKind == OO_PipeEqual || OpKind == OO_CaretEqual ||
49 OpKind == OO_LessLessEqual || OpKind == OO_GreaterGreaterEqual ||
50 OpKind == OO_PlusPlus || OpKind == OO_MinusMinus ||
51 OpKind == OO_PercentEqual || OpKind == OO_New ||
52 OpKind == OO_Delete || OpKind == OO_Array_New ||
53 OpKind == OO_Array_Delete;
54 }
55
56 if (const auto *CExpr = dyn_cast<CallExpr>(E)) {
57 bool Result = CheckFunctionCalls;
58 if (const auto *FuncDecl = CExpr->getDirectCallee()) {
59 if (FuncDecl->getDeclName().isIdentifier() &&
60 IgnoredFunctionsMatcher.matches(*FuncDecl, Finder,
61 Builder)) // exceptions come here
62 Result = false;
63 else if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
64 Result &= !MethodDecl->isConst();
65 }
66 return Result;
67 }
68
69 return isa<CXXNewExpr>(E) || isa<CXXDeleteExpr>(E) || isa<CXXThrowExpr>(E);
70}
71
72} // namespace
73
75 ClangTidyContext *Context)
76 : ClangTidyCheck(Name, Context),
77 CheckFunctionCalls(Options.get("CheckFunctionCalls", false)),
78 RawAssertList(Options.get("AssertMacros", "assert,NSAssert,NSCAssert")),
79 IgnoredFunctions(utils::options::parseListPair(
80 "__builtin_expect;", Options.get("IgnoredFunctions", ""))) {
81 StringRef(RawAssertList).split(AssertMacros, ",", -1, false);
82}
83
84// The options are explained in AssertSideEffectCheck.h.
86 Options.store(Opts, "CheckFunctionCalls", CheckFunctionCalls);
87 Options.store(Opts, "AssertMacros", RawAssertList);
88 Options.store(Opts, "IgnoredFunctions",
89 utils::options::serializeStringList(IgnoredFunctions));
90}
91
92void AssertSideEffectCheck::registerMatchers(MatchFinder *Finder) {
93 auto IgnoredFunctionsMatcher =
94 matchers::matchesAnyListedName(IgnoredFunctions);
95
96 auto DescendantWithSideEffect =
97 traverse(TK_AsIs, hasDescendant(expr(hasSideEffect(
98 CheckFunctionCalls, IgnoredFunctionsMatcher))));
99 auto ConditionWithSideEffect = hasCondition(DescendantWithSideEffect);
100 Finder->addMatcher(
101 stmt(
102 anyOf(conditionalOperator(ConditionWithSideEffect),
103 ifStmt(ConditionWithSideEffect),
104 unaryOperator(hasOperatorName("!"),
105 hasUnaryOperand(unaryOperator(
106 hasOperatorName("!"),
107 hasUnaryOperand(DescendantWithSideEffect))))))
108 .bind("condStmt"),
109 this);
110}
111
112void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) {
113 const SourceManager &SM = *Result.SourceManager;
114 const LangOptions LangOpts = getLangOpts();
115 SourceLocation Loc = Result.Nodes.getNodeAs<Stmt>("condStmt")->getBeginLoc();
116
117 StringRef AssertMacroName;
118 while (Loc.isValid() && Loc.isMacroID()) {
119 StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts);
120 Loc = SM.getImmediateMacroCallerLoc(Loc);
121
122 // Check if this macro is an assert.
123 if (llvm::is_contained(AssertMacros, MacroName)) {
124 AssertMacroName = MacroName;
125 break;
126 }
127 }
128 if (AssertMacroName.empty())
129 return;
130
131 diag(Loc, "side effect in %0() condition discarded in release builds")
132 << AssertMacroName;
133}
134
135} // namespace clang::tidy::bugprone
const Expr * E
CodeCompletionBuilder Builder
llvm::StringRef Name
SourceLocation Loc
std::string MacroName
Definition: Preamble.cpp:240
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
AssertSideEffectCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(llvm::ArrayRef< StringRef > NameList)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap