[clang-tools-extra] [clang-tidy] add misc-constexpr check (PR #162741)
Julian Schmidt via cfe-commits
cfe-commits at lists.llvm.org
Thu Oct 9 14:38:32 PDT 2025
https://github.com/5chmidti created https://github.com/llvm/llvm-project/pull/162741
This check finds all functions and variables that can be declared as `constexpr`, using the specified standard version to check if the requirements are met.
This is part 1/N, adding only the C++11 rule-set.
Fixes #115622
>From e491932773acabeb1e8ad62cafd97ae753b23206 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <git.julian.schmidt at gmail.com>
Date: Fri, 6 Sep 2024 22:58:46 +0200
Subject: [PATCH] [clang-tidy] add misc-constexpr check
This check finds all functions and variables that can be declared as
`constexpr`, using the specified standard version to check if the
requirements are met.
This is part 1/N, adding only the C++11 rule-set.
Fixes #115622
---
.../clang-tidy/modernize/CMakeLists.txt | 1 +
.../modernize/ModernizeTidyModule.cpp | 2 +
.../modernize/UseConstexprCheck.cpp | 517 ++++++++++++++++++
.../clang-tidy/modernize/UseConstexprCheck.h | 45 ++
.../clang-tidy/utils/ASTUtils.cpp | 17 +
clang-tools-extra/clang-tidy/utils/ASTUtils.h | 3 +
clang-tools-extra/docs/ReleaseNotes.rst | 5 +
.../docs/clang-tidy/checks/list.rst | 1 +
.../checks/modernize/use-constexpr.rst | 73 +++
.../modernize/use-constexpr-cxx20.cpp | 36 ++
.../modernize/use-constexpr-locals.cpp | 20 +
.../use-constexpr-replacement-opts.cpp | 32 ++
.../checkers/modernize/use-constexpr.cpp | 461 ++++++++++++++++
13 files changed, 1213 insertions(+)
create mode 100644 clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.cpp
create mode 100644 clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.h
create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-constexpr.rst
create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-cxx20.cpp
create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-locals.cpp
create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-replacement-opts.cpp
create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 882f2dc9fb4d8..f7dbc1d7312ee 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -32,6 +32,7 @@ add_clang_library(clangTidyModernizeModule STATIC
UnaryStaticAssertCheck.cpp
UseAutoCheck.cpp
UseBoolLiteralsCheck.cpp
+ UseConstexprCheck.cpp
UseConstraintsCheck.cpp
UseDefaultMemberInitCheck.cpp
UseDesignatedInitializersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 360e2b8434d0c..1b54adeef9281 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -33,6 +33,7 @@
#include "UnaryStaticAssertCheck.h"
#include "UseAutoCheck.h"
#include "UseBoolLiteralsCheck.h"
+#include "UseConstexprCheck.h"
#include "UseConstraintsCheck.h"
#include "UseDefaultMemberInitCheck.h"
#include "UseDesignatedInitializersCheck.h"
@@ -82,6 +83,7 @@ class ModernizeModule : public ClangTidyModule {
CheckFactories.registerCheck<MinMaxUseInitializerListCheck>(
"modernize-min-max-use-initializer-list");
CheckFactories.registerCheck<PassByValueCheck>("modernize-pass-by-value");
+ CheckFactories.registerCheck<UseConstexprCheck>("modernize-use-constexpr");
CheckFactories.registerCheck<UseDesignatedInitializersCheck>(
"modernize-use-designated-initializers");
CheckFactories.registerCheck<UseIntegerSignComparisonCheck>(
diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.cpp
new file mode 100644
index 0000000000000..9238605b3cb4a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.cpp
@@ -0,0 +1,517 @@
+//===--- UseConstexprCheck.cpp - clang-tidy--------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "UseConstexprCheck.h"
+#include "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+namespace {
+AST_MATCHER(FunctionDecl, locationPermitsConstexpr) {
+ const bool IsInMainFile =
+ Finder->getASTContext().getSourceManager().isInMainFile(
+ Node.getLocation());
+
+ if (IsInMainFile && Node.hasExternalFormalLinkage())
+ return false;
+ if (!IsInMainFile && !Node.isInlined())
+ return false;
+
+ return true;
+}
+
+AST_MATCHER(Expr, isCXX11ConstantExpr) {
+ return !Node.isValueDependent() &&
+ Node.isCXX11ConstantExpr(Finder->getASTContext());
+}
+
+AST_MATCHER(DeclaratorDecl, isInMacro) {
+ const SourceRange R =
+ SourceRange(Node.getTypeSpecStartLoc(), Node.getLocation());
+
+ return Node.getLocation().isMacroID() || Node.getEndLoc().isMacroID() ||
+ utils::rangeContainsMacroExpansion(
+ R, &Finder->getASTContext().getSourceManager()) ||
+ utils::rangeIsEntirelyWithinMacroArgument(
+ R, &Finder->getASTContext().getSourceManager());
+}
+
+AST_MATCHER(Decl, hasNoRedecl) {
+ // There is always the actual declaration
+ return !Node.redecls().empty() &&
+ std::next(Node.redecls_begin()) == Node.redecls_end();
+}
+
+AST_MATCHER(Decl, allRedeclsInSameFile) {
+ const SourceManager &SM = Finder->getASTContext().getSourceManager();
+ const SourceLocation L = Node.getLocation();
+ for (const Decl *ReDecl : Node.redecls()) {
+ if (!SM.isWrittenInSameFile(L, ReDecl->getLocation()))
+ return false;
+ }
+ return true;
+}
+} // namespace
+
+static bool
+satisfiesConstructorPropertiesUntil20(const CXXConstructorDecl *Ctor,
+ ASTContext &Ctx) {
+ const CXXRecordDecl *Rec = Ctor->getParent();
+ llvm::SmallPtrSet<const RecordDecl *, 8> Bases{};
+ for (const CXXBaseSpecifier Base : Rec->bases())
+ Bases.insert(Base.getType()->getAsRecordDecl());
+
+ llvm::SmallPtrSet<const FieldDecl *, 8> Fields{Rec->field_begin(),
+ Rec->field_end()};
+ llvm::SmallPtrSet<const FieldDecl *, 4> Indirects{};
+
+ for (const CXXCtorInitializer *const Init : Ctor->inits()) {
+ const Type *InitType = Init->getBaseClass();
+ if (InitType && InitType->isRecordType()) {
+ const auto *ConstructingInit =
+ llvm::dyn_cast<CXXConstructExpr>(Init->getInit());
+ if (ConstructingInit &&
+ !ConstructingInit->getConstructor()->isConstexprSpecified())
+ return false;
+ }
+
+ if (Init->isBaseInitializer()) {
+ Bases.erase(Init->getBaseClass()->getAsRecordDecl());
+ continue;
+ }
+
+ if (Init->isMemberInitializer()) {
+ const FieldDecl *Field = Init->getMember();
+
+ if (Field->isAnonymousStructOrUnion())
+ Indirects.insert(Field);
+
+ Fields.erase(Field);
+ continue;
+ }
+ }
+
+ for (const auto &Match :
+ match(cxxRecordDecl(forEach(indirectFieldDecl().bind("indirect"))), *Rec,
+ Ctx)) {
+ const auto *IField = Match.getNodeAs<IndirectFieldDecl>("indirect");
+
+ size_t NumInitializations = false;
+ for (const NamedDecl *ND : IField->chain())
+ NumInitializations += Indirects.erase(llvm::dyn_cast<FieldDecl>(ND));
+
+ if (NumInitializations != 1)
+ return false;
+
+ for (const NamedDecl *ND : IField->chain())
+ Fields.erase(llvm::dyn_cast<FieldDecl>(ND));
+ }
+
+ if (!Fields.empty())
+ return false;
+
+ return true;
+}
+
+static bool isLiteralType(QualType QT, const ASTContext &Ctx,
+ bool ConservativeLiteralType);
+
+static bool isLiteralType(const Type *T, const ASTContext &Ctx,
+ const bool ConservativeLiteralType) {
+ if (!T)
+ return false;
+
+ if (!T->isLiteralType(Ctx))
+ return false;
+
+ if (!ConservativeLiteralType)
+ return T->isLiteralType(Ctx) && !T->isVoidType();
+
+ if (T->isIncompleteType() || T->isIncompleteArrayType())
+ return false;
+
+ T = utils::unwrapPointee(T);
+ if (!T)
+ return false;
+
+ assert(!T->isPointerOrReferenceType());
+
+ if (T->isIncompleteType() || T->isIncompleteArrayType())
+ return false;
+
+ if (T->isLiteralType(Ctx))
+ return true;
+
+ if (const CXXRecordDecl *Rec = T->getAsCXXRecordDecl()) {
+ if (llvm::any_of(Rec->ctors(), [](const CXXConstructorDecl *Ctor) {
+ return !Ctor->isCopyOrMoveConstructor() &&
+ Ctor->isConstexprSpecified();
+ }))
+ return false;
+
+ for (const CXXBaseSpecifier Base : Rec->bases()) {
+ if (!isLiteralType(Base.getType(), Ctx, ConservativeLiteralType))
+ return false;
+ }
+ }
+
+ if (const Type *ArrayElementType = T->getArrayElementTypeNoTypeQual())
+ return isLiteralType(ArrayElementType, Ctx, ConservativeLiteralType);
+
+ return false;
+}
+
+static bool isLiteralType(QualType QT, const ASTContext &Ctx,
+ const bool ConservativeLiteralType) {
+ return !QT.isVolatileQualified() &&
+ isLiteralType(QT.getTypePtr(), Ctx, ConservativeLiteralType);
+}
+
+static bool satisfiesProperties11(
+ const FunctionDecl *FDecl, ASTContext &Ctx,
+ const bool ConservativeLiteralType,
+ const bool AddConstexprToMethodOfClassWithoutConstexprConstructor) {
+ if (FDecl->isConstexprSpecified())
+ return true;
+
+ const LangOptions LO = Ctx.getLangOpts();
+ const auto *Method = llvm::dyn_cast<CXXMethodDecl>(FDecl);
+ if (Method && !Method->isStatic() &&
+ !Method->getParent()->hasConstexprNonCopyMoveConstructor() &&
+ !AddConstexprToMethodOfClassWithoutConstexprConstructor)
+ return false;
+
+ if (Method &&
+ (Method->isVirtual() ||
+ !match(cxxMethodDecl(hasBody(cxxTryStmt())), *Method, Ctx).empty()))
+ return false;
+
+ if (const auto *Ctor = llvm::dyn_cast<CXXConstructorDecl>(FDecl);
+ Ctor && (!satisfiesConstructorPropertiesUntil20(Ctor, Ctx) ||
+ llvm::any_of(Ctor->getParent()->bases(),
+ [](const CXXBaseSpecifier &Base) {
+ return Base.isVirtual();
+ })))
+ return false;
+
+ if (const auto *Dtor = llvm::dyn_cast<CXXDestructorDecl>(FDecl);
+ Dtor && !Dtor->isTrivial())
+ return false;
+
+ if (!isLiteralType(FDecl->getReturnType(), Ctx, ConservativeLiteralType))
+ return false;
+
+ for (const ParmVarDecl *Param : FDecl->parameters())
+ if (!isLiteralType(Param->getType(), Ctx, ConservativeLiteralType))
+ return false;
+
+ class Visitor11 : public clang::RecursiveASTVisitor<Visitor11> {
+ public:
+ using Base = clang::RecursiveASTVisitor<Visitor11>;
+ bool shouldVisitImplicitCode() const { return true; }
+
+ Visitor11(ASTContext &Ctx, bool ConservativeLiteralType)
+ : Ctx(Ctx), ConservativeLiteralType(ConservativeLiteralType) {}
+
+ bool WalkUpFromNullStmt(NullStmt *) {
+ Possible = false;
+ return false;
+ }
+ bool WalkUpFromDeclStmt(DeclStmt *DS) {
+ for (const Decl *D : DS->decls())
+ if (!llvm::isa<StaticAssertDecl, TypedefNameDecl, UsingDecl,
+ UsingDirectiveDecl>(D)) {
+ Possible = false;
+ return false;
+ }
+ return true;
+ }
+
+ bool WalkUpFromExpr(Expr *) { return true; }
+ bool WalkUpFromCompoundStmt(CompoundStmt *S) {
+ for (const DynTypedNode &Node : Ctx.getParents(*S))
+ if (Node.get<FunctionDecl>() != nullptr)
+ return true;
+
+ Possible = false;
+ return false;
+ }
+ bool WalkUpFromStmt(Stmt *) {
+ Possible = false;
+ return false;
+ }
+
+ bool WalkUpFromReturnStmt(ReturnStmt *) {
+ ++NumReturns;
+ if (NumReturns != 1U) {
+ Possible = false;
+ return false;
+ }
+ return true;
+ }
+
+ bool WalkUpFromCastExpr(CastExpr *CE) {
+ if (llvm::is_contained(
+ {
+ CK_LValueBitCast,
+ CK_IntegralToPointer,
+ CK_PointerToIntegral,
+ },
+ CE->getCastKind())) {
+ Possible = false;
+ return false;
+ }
+ return true;
+ }
+
+ bool TraverseCXXDynamicCastExpr(CXXDynamicCastExpr *) {
+ Possible = false;
+ return false;
+ }
+
+ bool TraverseCXXReinterpretCastExpr(CXXReinterpretCastExpr *) {
+ Possible = false;
+ return false;
+ }
+
+ bool TraverseType(QualType QT, const bool TraverseQualifier = true) {
+ if (QT.isNull())
+ return true;
+ if (!isLiteralType(QT, Ctx, ConservativeLiteralType)) {
+ Possible = false;
+ return false;
+ }
+ return Base::TraverseType(QT, TraverseQualifier);
+ }
+
+ bool WalkUpFromCXXConstructExpr(CXXConstructExpr *CE) {
+ if (const CXXConstructorDecl *Ctor = CE->getConstructor();
+ Ctor && !Ctor->isConstexprSpecified()) {
+ Possible = false;
+ return false;
+ }
+
+ return true;
+ }
+ bool WalkUpFromCallExpr(CallExpr *CE) {
+ if (const auto *FDecl =
+ llvm::dyn_cast_if_present<FunctionDecl>(CE->getCalleeDecl());
+ FDecl && !FDecl->isConstexprSpecified()) {
+ Possible = false;
+ return false;
+ }
+ return true;
+ }
+
+ bool TraverseCXXNewExpr(CXXNewExpr *) {
+ Possible = false;
+ return false;
+ }
+
+ bool TraverseDeclRefExpr(DeclRefExpr *DRef) {
+ if (DRef->getType().isVolatileQualified()) {
+ Possible = false;
+ return false;
+ }
+ return Base::TraverseDeclRefExpr(DRef);
+ }
+
+ ASTContext &Ctx;
+ const bool ConservativeLiteralType;
+ bool Possible = true;
+ size_t NumReturns = 0;
+ };
+
+ Visitor11 V{Ctx, ConservativeLiteralType};
+ V.TraverseDecl(const_cast<FunctionDecl *>(FDecl));
+ if (!V.Possible)
+ return false;
+
+ return true;
+}
+
+namespace {
+AST_MATCHER_P2(FunctionDecl, satisfiesProperties, bool, ConservativeLiteralType,
+ bool, AddConstexprToMethodOfClassWithoutConstexprConstructor) {
+ ASTContext &Ctx = Finder->getASTContext();
+ const LangOptions LO = Ctx.getLangOpts();
+
+ if (LO.CPlusPlus11)
+ return satisfiesProperties11(
+ &Node, Ctx, ConservativeLiteralType,
+ AddConstexprToMethodOfClassWithoutConstexprConstructor);
+
+ return false;
+}
+
+AST_MATCHER_P(VarDecl, satisfiesVariableProperties, bool,
+ ConservativeLiteralType) {
+ ASTContext &Ctx = Finder->getASTContext();
+
+ const QualType QT = Node.getType();
+ const Type *T = QT.getTypePtr();
+ if (!T)
+ return false;
+
+ if (!isLiteralType(QT, Ctx, ConservativeLiteralType))
+ return false;
+
+ const bool IsDeclaredInsideConstexprFunction = std::invoke([&Node]() {
+ const auto *Func = llvm::dyn_cast<FunctionDecl>(Node.getDeclContext());
+ if (!Func)
+ return false;
+ return Func->isConstexpr();
+ });
+
+ if (Node.isStaticLocal() && IsDeclaredInsideConstexprFunction)
+ return false;
+
+ if (!Ctx.getLangOpts().CPlusPlus20)
+ return true;
+
+ const CXXRecordDecl *RDecl = T->getAsCXXRecordDecl();
+ const Type *const ArrayOrPtrElement = T->getPointeeOrArrayElementType();
+ if (ArrayOrPtrElement)
+ RDecl = ArrayOrPtrElement->getAsCXXRecordDecl();
+
+ if (RDecl && (!RDecl->hasDefinition() || !RDecl->hasConstexprDestructor()))
+ return false;
+
+ return true;
+}
+} // namespace
+
+void UseConstexprCheck::registerMatchers(MatchFinder *Finder) {
+ Finder->addMatcher(
+ functionDecl(
+ isDefinition(),
+ unless(anyOf(isConstexpr(), isImplicit(), hasExternalFormalLinkage(),
+ isInMacro(), isMain(), isInStdNamespace(),
+ isExpansionInSystemHeader(), isExternC(),
+ cxxMethodDecl(ofClass(cxxRecordDecl(isLambda()))))),
+ locationPermitsConstexpr(), allRedeclsInSameFile(),
+ satisfiesProperties(
+ ConservativeLiteralType,
+ AddConstexprToMethodOfClassWithoutConstexprConstructor))
+ .bind("func"),
+ this);
+
+ const auto CallToNonConstexprFunction =
+ callExpr(callee(functionDecl(unless(isConstexpr()))));
+
+ const auto VarSupportingConstexpr =
+ varDecl(
+ unless(anyOf(parmVarDecl(), isImplicit(), isInStdNamespace(),
+ isExpansionInSystemHeader(), isConstexpr(), isExternC(),
+ hasExternalFormalLinkage(), isInMacro())),
+ hasNoRedecl(), hasType(qualType(isConstQualified())),
+ satisfiesVariableProperties(ConservativeLiteralType),
+ hasInitializer(
+ expr(isCXX11ConstantExpr(), unless(CallToNonConstexprFunction),
+ unless(hasDescendant(CallToNonConstexprFunction)))))
+ .bind("var");
+ Finder->addMatcher(mapAnyOf(translationUnitDecl, namespaceDecl)
+ .with(forEach(VarSupportingConstexpr)),
+ this);
+ Finder->addMatcher(declStmt(hasSingleDecl(VarSupportingConstexpr)), this);
+}
+
+static const FunctionDecl *
+maybeResolveToTemplateDecl(const FunctionDecl *Func) {
+ if (Func && Func->isTemplateInstantiation())
+ Func = Func->getTemplateInstantiationPattern();
+ return Func;
+}
+
+void UseConstexprCheck::check(const MatchFinder::MatchResult &Result) {
+ if (const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func")) {
+ Func = maybeResolveToTemplateDecl(Func);
+ if (Func)
+ Functions.insert(Func);
+ return;
+ }
+
+ if (const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var")) {
+ if (const VarDecl *VarTemplate = Var->getTemplateInstantiationPattern())
+ Var = VarTemplate;
+
+ Variables.insert(Var);
+ return;
+ }
+}
+
+void UseConstexprCheck::onEndOfTranslationUnit() {
+ const std::string FunctionReplacement = ConstexprString + " ";
+
+ for (const FunctionDecl *Func : Functions) {
+ const SourceRange R =
+ SourceRange(Func->getTypeSpecStartLoc(), Func->getLocation());
+ auto Diag = diag(Func->getLocation(), "declare function %0 as 'constexpr'")
+ << Func << R;
+
+ for (const Decl *D : Func->redecls())
+ if (const auto *FDecl = llvm::dyn_cast<FunctionDecl>(D))
+ Diag << FixItHint::CreateInsertion(FDecl->getTypeSpecStartLoc(),
+ FunctionReplacement);
+ }
+
+ const auto MaybeRemoveConst = [&, this](DiagnosticBuilder &Diag,
+ const VarDecl *Var) {
+ // Since either of the locs can be in a macro, use `makeFileCharRange` to be
+ // sure that we have a consistent `CharSourceRange`, located entirely in the
+ // source file.
+ const CharSourceRange FileRange = Lexer::makeFileCharRange(
+ CharSourceRange::getCharRange(Var->getInnerLocStart(),
+ Var->getLocation()),
+ Var->getASTContext().getSourceManager(), getLangOpts());
+ if (const std::optional<Token> ConstToken =
+ utils::lexer::getQualifyingToken(
+ tok::TokenKind::kw_const, FileRange, Var->getASTContext(),
+ Var->getASTContext().getSourceManager())) {
+ Diag << FixItHint::CreateRemoval(ConstToken->getLocation());
+ }
+ };
+
+ for (const auto *Var : Variables) {
+ const SourceRange R =
+ SourceRange(Var->getTypeSpecStartLoc(), Var->getLocation());
+ auto Diag = diag(Var->getLocation(), "declare variable %0 as 'constexpr'")
+ << Var << R
+ << FixItHint::CreateInsertion(Var->getTypeSpecStartLoc(),
+ FunctionReplacement);
+ MaybeRemoveConst(Diag, Var);
+ }
+
+ Functions.clear();
+ Variables.clear();
+}
+
+UseConstexprCheck::UseConstexprCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ ConservativeLiteralType(Options.get("ConservativeLiteralType", true)),
+ AddConstexprToMethodOfClassWithoutConstexprConstructor(Options.get(
+ "AddConstexprToMethodOfClassWithoutConstexprConstructor", false)),
+ ConstexprString(Options.get("ConstexprString", "constexpr")),
+ StaticConstexprString(
+ Options.get("StaticConstexprString", "static " + ConstexprString)) {}
+
+void UseConstexprCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "ConservativeLiteralType", ConservativeLiteralType);
+ Options.store(Opts, "AddConstexprToMethodOfClassWithoutConstexprConstructor",
+ AddConstexprToMethodOfClassWithoutConstexprConstructor);
+ Options.store(Opts, "ConstexprString", ConstexprString);
+ Options.store(Opts, "StaticConstexprString", StaticConstexprString);
+}
+} // namespace clang::tidy::modernize
diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.h b/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.h
new file mode 100644
index 0000000000000..bfb206d40ba47
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseConstexprCheck.h
@@ -0,0 +1,45 @@
+//===--- UseUseConstexprCheck.h - clang-tidy --------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USECONSTEXPRCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USECONSTEXPRCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+
+namespace clang::tidy::modernize {
+
+/// Finds functions and variables that can be declared 'constexpr'.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-constexpr.html
+class UseConstexprCheck : public ClangTidyCheck {
+public:
+ UseConstexprCheck(StringRef Name, ClangTidyContext *Context);
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+ return LangOpts.CPlusPlus11;
+ }
+ void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+ void onEndOfTranslationUnit() override;
+
+private:
+ const bool ConservativeLiteralType;
+ const bool AddConstexprToMethodOfClassWithoutConstexprConstructor;
+ const std::string ConstexprString;
+ const std::string StaticConstexprString;
+ llvm::SmallPtrSet<const FunctionDecl *, 32> Functions;
+ llvm::SmallPtrSet<const VarDecl *, 32> Variables;
+};
+
+} // namespace clang::tidy::modernize
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USECONSTEXPRCHECK_H
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
index d5deb99a8442d..ac940fe9e7421 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
@@ -137,4 +137,21 @@ findOutermostIndirectFieldDeclForField(const FieldDecl *FD) {
return nullptr;
}
+const Type *unwrapPointee(const Type *T) {
+ if (!T->isPointerOrReferenceType())
+ return T;
+
+ while (T && T->isPointerOrReferenceType()) {
+ if (T->isReferenceType()) {
+ const QualType QType = T->getPointeeType();
+ if (QType.isNull())
+ return T;
+ T = QType.getTypePtr();
+ } else
+ T = T->getPointeeOrArrayElementType();
+ }
+
+ return T;
+}
+
} // namespace clang::tidy::utils
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.h b/clang-tools-extra/clang-tidy/utils/ASTUtils.h
index c2127f0746986..b945d91466310 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.h
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.h
@@ -45,6 +45,9 @@ bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt *SecondStmt,
const IndirectFieldDecl *
findOutermostIndirectFieldDeclForField(const FieldDecl *FD);
+// Undoes any pointer, reference or array indirections to get to the base type
+const Type *unwrapPointee(const Type *T);
+
} // namespace clang::tidy::utils
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ASTUTILS_H
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index d2d79dcc92ec2..12ead9eac6bfc 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -216,6 +216,11 @@ New checks
Finds virtual function overrides with different visibility than the function
in the base class.
+- New :doc:`modernize-use-constexr
+ <clang-tidy/checks/modernize/use-constexpr>` check.
+
+ Finds functions and variables that can be declared 'constexpr'.
+
- New :doc:`readability-redundant-parentheses
<clang-tidy/checks/readability/redundant-parentheses>` check.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 41391847618ce..d301e1e8d66a7 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -309,6 +309,7 @@ Clang-Tidy Checks
:doc:`modernize-unary-static-assert <modernize/unary-static-assert>`, "Yes"
:doc:`modernize-use-auto <modernize/use-auto>`, "Yes"
:doc:`modernize-use-bool-literals <modernize/use-bool-literals>`, "Yes"
+ :doc:`modernize-use-constexpr <modernize/use-constexpr>`, "Yes"
:doc:`modernize-use-constraints <modernize/use-constraints>`, "Yes"
:doc:`modernize-use-default-member-init <modernize/use-default-member-init>`, "Yes"
:doc:`modernize-use-designated-initializers <modernize/use-designated-initializers>`, "Yes"
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constexpr.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constexpr.rst
new file mode 100644
index 0000000000000..c8e1b95ce5f78
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constexpr.rst
@@ -0,0 +1,73 @@
+.. title:: clang-tidy - modernize-use-constexpr
+
+modernize-use-constexpr
+=======================
+
+Finds functions and variables that can be declared ``constexpr``.
+
+This check currently supports the ``constexpr`` rule-set of C++11.
+
+The check analyses any function and variable according to the rules defined
+for the language version that the code compiles with.
+Changing to a newer language standard may therefore offer additional
+opportunities to declare a function or variable as ``constexpr``.
+Furthermore, this check can be incremental in terms of its diagnostics. For
+example, declaring a function ``constepxr`` might create new opportunities of
+marking additional variables or function ``constexpr``, which can only be found
+in subsequent runs of this check.
+
+Before C++23, ``static constexpr`` variables could not be declared inside a
+``constexpr`` function. This check prefers adding ``constexpr`` to an enclosing
+function over adding ``constexpr`` to a static local variable inside that
+function.
+
+Limitations
+-----------
+
+* Only analyzes variables declared ``const``, because this check would have
+ to duplicate the expensive analysis of the
+ :doc:`misc-const-correctness<../misc/const-correctness>` check.
+ For the best results, enable both `misc-const-correctness` and
+ `modernize-use-constexpr` together.
+
+* Only analyzes variable declarations that declare a single variable
+
+Options
+-------
+
+.. option:: ConservativeLiteralType
+
+ With this option enabled, only literal types that can be constructed at
+ compile-time are considered to supoprt ``constexpr``.
+
+ .. code-block:: c++
+
+ struct NonLiteral{
+ NonLiteral();
+ ~NonLiteral();
+ int &ref;
+ };
+
+ This type is a literal type, but can not be constructed at compile-time.
+ With `ConservativeLiteralType` equal to `true`, variables or funtions
+ with this type are not diagnosed to add ``constexpr``. Default is
+ `true`.
+
+.. option:: AddConstexprToMethodOfClassWithoutConstexprConstructor
+
+ While a function of a class or struct could be declared ``constexpr``, when
+ the class itself can never be constructed at compile-time, then adding
+ ``constexpr`` to a member function is superfluous. This option controls if
+ ``constexpr`` should be added anyways. Default is `false`.
+
+.. option:: ConstexprString
+
+ The string to use to specify a variable or function as ``constexpr``, for
+ example, a macro. Default is `constexpr`.
+
+.. option:: ConstexprString
+
+ The string to use with C++23 to specify a function-local variable as
+ ``static constexpr``, for example, a macro. Default is `static constexpr`
+ (concatenating `static` with the `ConstexprString` option).
+
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-cxx20.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-cxx20.cpp
new file mode 100644
index 0000000000000..dd400fe5185fc
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-cxx20.cpp
@@ -0,0 +1,36 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-constexpr %t
+
+namespace std {
+template <typename T = void>
+struct coroutine_handle {
+ static constexpr coroutine_handle from_address(void* addr) {
+ return {};
+ }
+};
+
+struct always_suspend {
+ bool await_ready() const noexcept;
+ bool await_resume() const noexcept;
+ template <typename T>
+ bool await_suspend(coroutine_handle<T>) const noexcept;
+};
+
+template <typename T>
+struct coroutine_traits {
+ using promise_type = T::promise_type;
+};
+} // namespace std
+
+struct generator {
+ struct promise_type {
+ void return_value(int v);
+ std::always_suspend yield_value(int&&);
+ std::always_suspend initial_suspend() const noexcept;
+ std::always_suspend final_suspend() const noexcept;
+ void unhandled_exception();
+ generator get_return_object();
+ };
+};
+
+
+generator f25() { co_return 10; }
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-locals.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-locals.cpp
new file mode 100644
index 0000000000000..62dbeaef27d21
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-locals.cpp
@@ -0,0 +1,20 @@
+// RUN: %check_clang_tidy -std=c++11 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++14 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++17 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++23-or-later -check-suffix=23 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+
+
+#define FUNC(N) void func##N()
+FUNC(0) {
+ static int f1 = 1;
+ static const int f2 = 2;
+ // CHECK-MESSAGES-23: :[[@LINE-1]]:22: warning: variable 'f2' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23: static constexpr int f2 = 2;
+ const int f3 = 3;
+ // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: variable 'f3' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES: constexpr int f3 = 3;
+ // CHECK-MESSAGES-23: :[[@LINE-3]]:15: warning: variable 'f3' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23: static constexpr int f3 = 3;
+}
+
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-replacement-opts.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-replacement-opts.cpp
new file mode 100644
index 0000000000000..ea80a6ce2a003
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr-replacement-opts.cpp
@@ -0,0 +1,32 @@
+// RUN: %check_clang_tidy -std=c++11 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR'}}"
+// RUN: %check_clang_tidy -std=c++14 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR'}}"
+// RUN: %check_clang_tidy -std=c++17 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR'}}"
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR'}}"
+// RUN: %check_clang_tidy -std=c++23-or-later -check-suffix=23 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR'}}"
+// RUN: %check_clang_tidy -std=c++23-or-later -check-suffix=23-STATIC %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConstexprString: 'CXPR', modernize-use-constexpr.StaticConstexprString: 'STATIC_CXPR'}}"
+
+static int f1() { return 0; }
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: function 'f1' can be declared 'constexpr' [modernize-use-constexpr]
+// CHECK-FIXES: static CXPR int f1() { return 0; }
+// CHECK-MESSAGES-23: :[[@LINE-3]]:12: warning: function 'f1' can be declared 'constexpr' [modernize-use-constexpr]
+// CHECK-FIXES-23: static CXPR int f1() { return 0; }
+// CHECK-MESSAGES-23-STATIC: :[[@LINE-5]]:12: warning: function 'f1' can be declared 'constexpr' [modernize-use-constexpr]
+// CHECK-FIXES-23-STATIC: static CXPR int f1() { return 0; }
+
+#define FUNC(N) void func##N()
+FUNC(0) {
+ static int f1 = 1;
+ static const int f2 = 2;
+ // CHECK-MESSAGES-23: :[[@LINE-1]]:22: warning: variable 'f2' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23: static CXPR int f2 = 2;
+ // CHECK-MESSAGES-23-STATIC: :[[@LINE-3]]:22: warning: variable 'f2' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23-STATIC: static CXPR int f2 = 2;
+ const int f3 = 3;
+ // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: variable 'f3' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES: CXPR int f3 = 3;
+ // CHECK-MESSAGES-23: :[[@LINE-3]]:15: warning: variable 'f3' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23: static CXPR int f3 = 3;
+ // CHECK-MESSAGES-23-STATIC: :[[@LINE-5]]:15: warning: variable 'f3' can be declared 'constexpr' [modernize-use-constexpr]
+ // CHECK-FIXES-23-STATIC: STATIC_CXPR int f3 = 3;
+}
+
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr.cpp
new file mode 100644
index 0000000000000..7a81b4dfe235d
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constexpr.cpp
@@ -0,0 +1,461 @@
+// RUN: %check_clang_tidy -std=c++11 -check-suffix=11 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++14 -check-suffix=11 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++17 -check-suffix=11,17 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=11,17 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++23-or-later -check-suffix=11,17 %s modernize-use-constexpr %t -- -- -fno-delayed-template-parsing
+
+// RUN: %check_clang_tidy -std=c++11 -check-suffix=11,11-CLT %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConservativeLiteralType: false}}" -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++14 -check-suffix=11,11-CLT %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConservativeLiteralType: false}}" -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++17 -check-suffix=11,11-CLT,17 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConservativeLiteralType: false}}" -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=11,11-CLT,17 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConservativeLiteralType: false}}" -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++23-or-later -check-suffix=11,11-CLT,17 %s modernize-use-constexpr %t -- -config="{CheckOptions: {modernize-use-constexpr.ConservativeLiteralType: false}}" -- -fno-delayed-template-parsing
+
+namespace {
+namespace my {
+ struct point {
+ constexpr point() {}
+ int get_x() const { return x; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:9: warning: declare function 'get_x' as 'constexpr'
+ // CHECK-FIXES-11: constexpr int get_x() const { return x; }
+ int x;
+ int y;
+ };
+
+ struct point2 {
+ point2();
+ int get_x() const { return x; }
+ int x;
+ };
+} // namespace my
+} // namespace
+
+namespace function {
+ struct Empty {};
+
+ struct Base {
+ virtual void virt() = 0;
+ };
+ struct Derived : Base {
+ Derived() {}
+ void virt() override {}
+ };
+
+ static void f1() {}
+
+ static int f2() { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f2() { return 0; }
+
+ static int f3(int x) { return x; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f3' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f3(int x) { return x; }
+
+ static int f4(Empty x) { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f4' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f4(Empty x) { return 0; }
+
+ static int f5(Empty x) { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f5' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f5(Empty x) { return 0; }
+
+ static int f6(Empty x) { ; return 0; }
+
+ static int f7(Empty x) { static_assert(0 == 0, ""); return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f7' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f7(Empty x) { static_assert(0 == 0, ""); return 0; }
+
+ static int f8(Empty x) { using my_int = int; return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f8' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f8(Empty x) { using my_int = int; return 0; }
+
+ static int f9(Empty x) { using my::point; return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f9' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f9(Empty x) { using my::point; return 0; }
+
+ static int f10(Empty x) { return 10; return 0; }
+
+ static int f11(Empty x) { if (true) return 10; return 0; }
+
+ static int f12(Empty x) { label: ; goto label; return 0; }
+ static int f13(Empty x) { try { throw 0; } catch(int) {}; return 0; }
+ static int f14(Empty x) { asm ("mov %rax, %rax"); }
+ static int f15(Empty x) { int y; return 0; }
+ static int f16(Empty x) { static int y = 0; return 0; }
+ static int f17(Empty x) { thread_local int y = 0; return 0; }
+ static int f18(Empty x) { [](){ label: ; goto label; return 0; }; return 0; }
+ static int f19(Empty x) { [](){ try { throw 0; } catch(int) {}; return 0; }; return 0; }
+ static int f20(Empty x) { [](){ asm ("mov %rax, %rax"); }; return 0; }
+ static int f21(Empty x) { [](){ int y; return 0; }; return 0; }
+ static int f22(Empty x) { [](){ static int y = 0; return 0; }; return 0; }
+ static int f23(Empty x) { [](){ thread_local int y = 0; return 0; }; return 0; }
+
+ static int f24(Empty x) { return [](){ return 0; }(); }
+
+ static int f25(Empty x) { new int; return 0; }
+
+ struct Range0To10 {
+ struct iterator {
+ int operator*() const;
+ void operator++();
+ friend bool operator!=(const iterator&lhs, const iterator&rhs) { return lhs.i == rhs.i; }
+ int i;
+ };
+ iterator begin() const;
+ iterator end() const;
+ };
+ static int f26(Empty x) {
+ auto R = Range0To10{};
+ for (const int i: R) { }
+ return 0;
+ }
+
+ static const auto f27 = [](int X){ return X + 1; }(10);
+ // CHECK-MESSAGES-17: :[[@LINE-1]]:21: warning: declare variable 'f27' as 'constexpr'
+ // CHECK-FIXES-17: static constexpr auto f27 = [](int X){ return X + 1; }(10);
+
+ [[nodiscard]] static int f28() { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:28: warning: declare function 'f28' as 'constexpr'
+ // CHECK-FIXES-11: {{\[\[nodiscard\]\]}} static constexpr int f28() { return 0; }
+
+ // template <typename T>
+ // int f29() { return 0; }
+ //
+ // template <>
+ // int f29<int>() { return 1; }
+} // namespace function
+namespace function_non_literal {
+ struct NonLiteral{
+ NonLiteral();
+ ~NonLiteral();
+ int &ref;
+ };
+
+ struct Base {
+ virtual void virt() = 0;
+ };
+ struct Derived : Base {
+ Derived() {}
+ void virt() override {}
+ };
+
+ static void f1() {}
+
+ static int f2() { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f2() { return 0; }
+
+ static int f3(int x) { return x; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f3' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f3(int x) { return x; }
+
+ static int f4(NonLiteral x) { return 0; }
+
+ static int f5(NonLiteral x) { return 0; }
+
+ static int f6(NonLiteral x) { ; return 0; }
+
+ static int f7(NonLiteral x) { static_assert(0 == 0, ""); return 0; }
+
+ static int f8(NonLiteral x) { using my_int = int; return 0; }
+
+ static int f9(NonLiteral x) { using my::point; return 0; }
+
+ static int f10(NonLiteral x) { return 10; return 0; }
+
+ static int f11(NonLiteral x) { if (true) return 10; return 0; }
+
+ static int f12(NonLiteral x) { label: ; goto label; return 0; }
+ static int f13(NonLiteral x) { try { throw 0; } catch(int) {}; return 0; }
+ static int f14(NonLiteral x) { asm ("mov %rax, %rax"); }
+ static int f15(NonLiteral x) { int y; return 0; }
+ static int f16(NonLiteral x) { static int y = 0; return 0; }
+ static int f17(NonLiteral x) { thread_local int y = 0; return 0; }
+ static int f18(NonLiteral x) { [](){ label: ; goto label; return 0; }; return 0; }
+ static int f19(NonLiteral x) { [](){ try { throw 0; } catch(int) {}; return 0; }; return 0; }
+ static int f20(NonLiteral x) { [](){ asm ("mov %rax, %rax"); }; return 0; }
+ static int f21(NonLiteral x) { [](){ int y; return 0; }; return 0; }
+ static int f22(NonLiteral x) { [](){ static int y = 0; return 0; }; return 0; }
+ static int f23(NonLiteral x) { [](){ thread_local int y = 0; return 0; }; return 0; }
+
+ static int f24(NonLiteral x) { return [](){ return 0; }(); }
+
+ static int f25(NonLiteral x) { new int; return 0; }
+
+ struct Range0To10 {
+ struct iterator {
+ int operator*() const { return i; }
+ void operator++() { ++i; }
+ friend bool operator!=(const iterator&lhs, const iterator&rhs) { return lhs.i == rhs.i; }
+ int i;
+ };
+ iterator begin() const { return { 0 }; }
+ iterator end() const { return { 10 }; }
+ };
+ static int f26(NonLiteral x) {
+ auto R = Range0To10{};
+ for (const int i: R) { }
+ return 0;
+ }
+} // namespace function_non_literal
+namespace function_non_literal_ref {
+ struct NonLiteral{
+ NonLiteral();
+ ~NonLiteral();
+ int &ref;
+ };
+
+ struct Base {
+ virtual void virt() = 0;
+ };
+ struct Derived : Base {
+ Derived() {}
+ void virt() override {}
+ };
+
+ static void f1() {}
+
+ static int f2() { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f2() { return 0; }
+
+ static int f3(int x) { return x; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:14: warning: declare function 'f3' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int f3(int x) { return x; }
+
+ static int f4(NonLiteral& x) { return 0; }
+ // CHECK-MESSAGES-11-CLT: :[[@LINE-1]]:14: warning: declare function 'f4' as 'constexpr'
+ // CHECK-FIXES-11-CLT: static constexpr int f4(NonLiteral& x) { return 0; }
+
+ static int f5(NonLiteral& x) { return 0; }
+ // CHECK-MESSAGES-11-CLT: :[[@LINE-1]]:14: warning: declare function 'f5' as 'constexpr'
+ // CHECK-FIXES-11-CLT: static constexpr int f5(NonLiteral& x) { return 0; }
+
+ static int f6(NonLiteral& x) { ; return 0; }
+
+ static int f7(NonLiteral& x) { static_assert(0 == 0, ""); return 0; }
+ // CHECK-MESSAGES-11-CLT: :[[@LINE-1]]:14: warning: declare function 'f7' as 'constexpr'
+ // CHECK-FIXES-11-CLT: static constexpr int f7(NonLiteral& x) { static_assert(0 == 0, ""); return 0; }
+
+ static int f8(NonLiteral& x) { using my_int = int; return 0; }
+ // CHECK-MESSAGES-11-CLT: :[[@LINE-1]]:14: warning: declare function 'f8' as 'constexpr'
+ // CHECK-FIXES-11-CLT: static constexpr int f8(NonLiteral& x) { using my_int = int; return 0; }
+
+ static int f9(NonLiteral& x) { using my::point; return 0; }
+ // CHECK-MESSAGES-11-CLT: :[[@LINE-1]]:14: warning: declare function 'f9' as 'constexpr'
+ // CHECK-FIXES-11-CLT: static constexpr int f9(NonLiteral& x) { using my::point; return 0; }
+
+ static int f10(NonLiteral& x) { return 10; return 0; }
+
+ static int f11(NonLiteral& x) { if (true) return 10; return 0; }
+
+ static int f12(NonLiteral& x) { label: ; goto label; return 0; }
+ static int f13(NonLiteral& x) { try { throw 0; } catch(int) {}; return 0; }
+ static int f14(NonLiteral& x) { asm ("mov %rax, %rax"); }
+ static int f15(NonLiteral& x) { int y; return 0; }
+ static int f16(NonLiteral& x) { static int y = 0; return 0; }
+ static int f17(NonLiteral& x) { thread_local int y = 0; return 0; }
+ static int f18(NonLiteral& x) { [](){ label: ; goto label; return 0; }; return 0; }
+ static int f19(NonLiteral& x) { [](){ try { throw 0; } catch(int) {}; return 0; }; return 0; }
+ static int f20(NonLiteral& x) { [](){ asm ("mov %rax, %rax"); }; return 0; }
+ static int f21(NonLiteral& x) { [](){ int y; return 0; }; return 0; }
+ static int f22(NonLiteral& x) { [](){ static int y = 0; return 0; }; return 0; }
+ static int f23(NonLiteral& x) { [](){ thread_local int y = 0; return 0; }; return 0; }
+
+ static int f24(NonLiteral& x) { return [](){ return 0; }(); }
+
+ static int f25(NonLiteral& x) { new int; return 0; }
+
+ struct Range0To10 {
+ struct iterator {
+ int operator*() const { return i; }
+ void operator++() { ++i; }
+ friend bool operator!=(const iterator&lhs, const iterator&rhs) { return lhs.i == rhs.i; }
+ int i;
+ };
+ iterator begin() const { return { 0 }; }
+ iterator end() const { return { 10 }; }
+ };
+ static int f26(NonLiteral& x) {
+ auto R = Range0To10{};
+ for (const int i: R) { }
+ return 0;
+ }
+
+ template <typename> void f27() {
+ [](int N) { N; };
+ }
+
+} // namespace function_non_literal_ref
+
+template <typename T>
+static T forwardDeclared();
+
+template <typename T>
+static T forwardDeclared() { return T{}; }
+// CHECK-MESSAGES-11: :[[@LINE-1]]:10: warning: declare function 'forwardDeclared' as 'constexpr'
+// CHECK-FIXES-11: template <typename T>
+// CHECK-FIXES-11: static constexpr T forwardDeclared();
+// CHECK-FIXES-11: template <typename T>
+// CHECK-FIXES-11: static constexpr T forwardDeclared() { return T{}; }
+
+static void useForwardDeclared() {
+ forwardDeclared<int>() + forwardDeclared<double>() + forwardDeclared<char>();
+}
+
+namespace {
+namespace variable {
+ namespace literal_type {
+ constexpr int f1() { return 0; }
+ int g1() { return 0; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:13: warning: declare function 'g1' as 'constexpr'
+ // CHECK-FIXES-11: constexpr int g1() { return 0; }
+ static constexpr int A1 = 0;
+ static int B1 = 0;
+ static const int C1 = 0;
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:26: warning: declare variable 'C1' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int C1 = 0;
+ static const int D1 = f1();
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:26: warning: declare variable 'D1' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int D1 = f1();
+ static const int E1 = g1();
+
+ template <typename T>
+ const T TemplatedVar1 = T{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:17: warning: declare variable 'TemplatedVar1' as 'constexpr'
+ // CHECK-FIXES-11: constexpr T TemplatedVar1 = T{};
+
+ static volatile int VolatileInt = 10;
+
+ int h1() {
+ int a1 = 0;
+ const int b1 = 1;
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:23: warning: declare variable 'b1' as 'constexpr'
+ // CHECK-FIXES-11: constexpr int b1 = 1;
+ static int c1 = 2;
+ static const int d1 = 3;
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:30: warning: declare variable 'd1' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr int d1 = 3;
+
+ static auto e1 = TemplatedVar1<int> + TemplatedVar1<unsigned int>;
+
+ const auto check = [](const int & ref) { };
+ // CHECK-MESSAGES-17: :[[@LINE-1]]:24: warning: declare variable 'check' as 'constexpr'
+ // CHECK-FIXES-17: constexpr auto check = [](const int & ref) { };
+
+ [[maybe_unused]] const int f1 = 4;
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:40: warning: declare variable 'f1' as 'constexpr'
+ // CHECK-FIXES-11: {{\[\[maybe_unused\]\]}} constexpr int f1 = 4;
+
+ const int g1 = 10, h1 = 0;
+ const int i1 = 0, j1 = VolatileInt;
+
+ return 0;
+ }
+ } // namespace literal_type
+
+ namespace non_literal_type {
+ void unreferencedVolatile() {
+ const volatile int x = 0;
+ }
+ void referencedVolatile() {
+ const volatile int x = 0;
+ int y = x;
+ }
+ } // namespace non_literal_type
+
+ namespace struct_type {
+ struct AStruct { int val; };
+ constexpr AStruct f2() { return {}; }
+ AStruct g2() { return {}; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:17: warning: declare function 'g2' as 'constexpr'
+ // CHECK-FIXES-11: constexpr AStruct g2() { return {}; }
+ static constexpr AStruct A2 = {};
+ static AStruct B2 = {};
+ static const AStruct C2 = {};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:30: warning: declare variable 'C2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct C2 = {};
+ static const AStruct D2 = f2();
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:30: warning: declare variable 'D2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct D2 = f2();
+ static const AStruct E2 = g2();
+ void h2() {
+ AStruct a2{};
+ const AStruct b2{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:27: warning: declare variable 'b2' as 'constexpr'
+ // CHECK-FIXES-11: constexpr AStruct b2{};
+ static AStruct c2{};
+ static const AStruct d2{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:34: warning: declare variable 'd2' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct d2{};
+ }
+ } // namespace struct_type
+
+ namespace struct_type_non_literal {
+ struct AStruct { ~AStruct(); int val; };
+ AStruct g3() { return {}; }
+ static AStruct B3 = {};
+ static const AStruct C3 = {};
+ static const AStruct E3 = g3();
+
+ template <typename T>
+ const T TemplatedVar2 = T{};
+ template <typename T>
+ const T TemplatedVar2B = T{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:17: warning: declare variable 'TemplatedVar2B' as 'constexpr'
+ // CHECK-FIXES-11: constexpr T TemplatedVar2B = T{};
+
+ void h3() {
+ AStruct a3{};
+ const AStruct b3{};
+ static AStruct c3{};
+ static const AStruct d3{};
+
+ static auto e1 = TemplatedVar2<AStruct>;
+ static auto f1 = TemplatedVar2B<AStruct>;
+ static auto g1 = TemplatedVar2B<int>;
+ }
+ } // namespace struct_type_non_literal
+
+ namespace struct_type_non_literal2 {
+ struct AStruct { volatile int Val; };
+ AStruct g4() { return {}; }
+ static AStruct B4 = {};
+ static const AStruct C4 = {};
+ static const AStruct E4 = g4();
+ void h4() {
+ AStruct a4{};
+ const AStruct b4{};
+ static AStruct c4{};
+ static const AStruct d4{};
+ }
+ } // namespace struct_type_non_literal2
+
+ namespace struct_type_non_literal3 {
+ struct AStruct { union { int val; float val5; }; };
+ constexpr AStruct f5() { return {}; }
+ AStruct g5() { return {}; }
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:17: warning: declare function 'g5' as 'constexpr'
+ // CHECK-FIXES-11: constexpr AStruct g5() { return {}; }
+ static constexpr AStruct A5 = {};
+ static AStruct B5 = {};
+ static const AStruct C5 = {};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:30: warning: declare variable 'C5' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct C5 = {};
+ static const AStruct D5 = f5();
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:30: warning: declare variable 'D5' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct D5 = f5();
+ static const AStruct E5 = g5();
+ void h5() {
+ AStruct a5{};
+ const AStruct b5{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:27: warning: declare variable 'b5' as 'constexpr'
+ // CHECK-FIXES-11: constexpr AStruct b5{};
+ static AStruct c5{};
+ static const AStruct d5{};
+ // CHECK-MESSAGES-11: :[[@LINE-1]]:34: warning: declare variable 'd5' as 'constexpr'
+ // CHECK-FIXES-11: static constexpr AStruct d5{};
+ }
+ } // namespace struct_type_non_literal3
+} // namespace variable
+} // namespace
+
More information about the cfe-commits
mailing list