| 1 |
//===--- DynamicStaticInitializersCheck.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 |
|
| 9 |
#include "DynamicStaticInitializersCheck.h" |
| 10 |
#include "clang/AST/ASTContext.h" |
| 11 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 |
|
| 13 |
using namespace clang::ast_matchers; |
| 14 |
|
| 15 |
namespace clang::tidy::bugprone { |
| 16 |
|
| 17 |
AST_MATCHER(clang::VarDecl, hasConstantDeclaration) { |
| 18 |
const Expr *Init = Node.getInit(); |
| 19 |
if (Init && !Init->isValueDependent()) { |
| 20 |
if (Node.isConstexpr()) |
| 21 |
return true; |
| 22 |
return Node.evaluateValue(); |
| 23 |
} |
| 24 |
return false; |
| 25 |
} |
| 26 |
|
| 27 |
DynamicStaticInitializersCheck::DynamicStaticInitializersCheck(StringRef Name, |
| 28 |
ClangTidyContext *Context) |
| 29 |
: ClangTidyCheck(Name, Context), |
| 30 |
RawStringHeaderFileExtensions(Options.getLocalOrGlobal( |
| 31 |
"HeaderFileExtensions", utils::defaultHeaderFileExtensions())) { |
| 32 |
if (!utils::parseFileExtensions(RawStringHeaderFileExtensions, |
| 33 |
HeaderFileExtensions, |
| 34 |
utils::defaultFileExtensionDelimiters())) { |
| 35 |
this->configurationDiag("Invalid header file extension: '%0'") |
| 36 |
<< RawStringHeaderFileExtensions; |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
void DynamicStaticInitializersCheck::storeOptions( |
| 41 |
ClangTidyOptions::OptionMap &Opts) { |
| 42 |
Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions); |
| 43 |
} |
| 44 |
|
| 45 |
void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) { |
| 46 |
Finder->addMatcher( |
| 47 |
varDecl(hasGlobalStorage(), unless(hasConstantDeclaration())).bind("var"), |
| 48 |
this); |
| 49 |
} |
| 50 |
|
| 51 |
void DynamicStaticInitializersCheck::check(const MatchFinder::MatchResult &Result) { |
| 52 |
const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var"); |
| 53 |
SourceLocation Loc = Var->getLocation(); |
| 54 |
if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager, |
| 55 |
HeaderFileExtensions)) |
| 56 |
return; |
| 57 |
// If the initializer is a constant expression, then the compiler |
| 58 |
// doesn't have to dynamically initialize it. |
| 59 |
diag(Loc, "static variable %0 may be dynamically initialized in this header file") |
| 60 |
<< Var; |
| 61 |
} |
| 62 |
|
| 63 |
} // namespace clang::tidy::bugprone |