[clang] 364f988 - Reland "[clang-format] Fix FormatToken::isSimpleTypeSpecifier() (#91712)"
Author: Owen Pan Date: 2024-05-13T21:54:23-07:00 New Revision: 364f988d3feb46ead8fdb657c9eab78d93425a28 URL: https://github.com/llvm/llvm-project/commit/364f988d3feb46ead8fdb657c9eab78d93425a28 DIFF: https://github.com/llvm/llvm-project/commit/364f988d3feb46ead8fdb657c9eab78d93425a28.diff LOG: Reland "[clang-format] Fix FormatToken::isSimpleTypeSpecifier() (#91712)" Remove FormatToken::isSimpleTypeSpecifier() and call Token::isSimpleTypeSpecifier(LangOpts) instead. Added: Modified: clang/lib/Format/Format.cpp clang/lib/Format/FormatToken.cpp clang/lib/Format/FormatToken.h clang/lib/Format/FormatTokenLexer.cpp clang/lib/Format/QualifierAlignmentFixer.cpp clang/lib/Format/QualifierAlignmentFixer.h clang/lib/Format/TokenAnalyzer.cpp clang/lib/Format/TokenAnalyzer.h clang/lib/Format/TokenAnnotator.cpp clang/lib/Format/TokenAnnotator.h clang/lib/Format/UnwrappedLineParser.cpp clang/lib/Format/UnwrappedLineParser.h clang/unittests/Format/QualifierFixerTest.cpp Removed: diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 8f027ffa20cca..52005a6c881f3 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -3858,8 +3858,7 @@ LangOptions getFormattingLangOpts(const FormatStyle ) { LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11; LangOpts.LineComment = 1; - bool AlternativeOperators = Style.isCpp(); - LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0; + LangOpts.CXXOperatorNames = Style.isCpp(); LangOpts.Bool = 1; LangOpts.ObjC = 1; LangOpts.MicrosoftExt = 1;// To get kw___try, kw___finally. diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp index 4fb70ffac706d..85bec71ffbbc8 100644 --- a/clang/lib/Format/FormatToken.cpp +++ b/clang/lib/Format/FormatToken.cpp @@ -34,43 +34,6 @@ const char *getTokenTypeName(TokenType Type) { return nullptr; } -// FIXME: This is copy from Sema. Put it in a common place and remove -// duplication. -bool FormatToken::isSimpleTypeSpecifier() const { - switch (Tok.getKind()) { - case tok::kw_short: - case tok::kw_long: - case tok::kw___int64: - case tok::kw___int128: - case tok::kw_signed: - case tok::kw_unsigned: - case tok::kw_void: - case tok::kw_char: - case tok::kw_int: - case tok::kw_half: - case tok::kw_float: - case tok::kw_double: - case tok::kw___bf16: - case tok::kw__Float16: - case tok::kw___float128: - case tok::kw___ibm128: - case tok::kw_wchar_t: - case tok::kw_bool: -#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: -#include "clang/Basic/TransformTypeTraits.def" - case tok::annot_typename: - case tok::kw_char8_t: - case tok::kw_char16_t: - case tok::kw_char32_t: - case tok::kw_typeof: - case tok::kw_decltype: - case tok::kw__Atomic: -return true; - default: -return false; - } -} - // Sorted common C++ non-keyword types. static SmallVector CppNonKeywordTypes = { "clock_t", "int16_t", "int32_t", "int64_t", "int8_t", @@ -78,15 +41,16 @@ static SmallVector CppNonKeywordTypes = { "uint32_t", "uint64_t", "uint8_t", "uintptr_t", }; -bool FormatToken::isTypeName(bool IsCpp) const { - return is(TT_TypeName) || isSimpleTypeSpecifier() || +bool FormatToken::isTypeName(const LangOptions ) const { + const bool IsCpp = LangOpts.CXXOperatorNames; + return is(TT_TypeName) || Tok.isSimpleTypeSpecifier(LangOpts) || (IsCpp && is(tok::identifier) && std::binary_search(CppNonKeywordTypes.begin(), CppNonKeywordTypes.end(), TokenText)); } -bool FormatToken::isTypeOrIdentifier(bool IsCpp) const { - return isTypeName(IsCpp) || isOneOf(tok::kw_auto, tok::identifier); +bool FormatToken::isTypeOrIdentifier(const LangOptions ) const { + return isTypeName(LangOpts) || isOneOf(tok::kw_auto, tok::identifier); } bool FormatToken::isBlockIndentedInitRBrace(const FormatStyle ) const { diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 95f16fde5005f..8792f4c750748 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -684,12 +684,8 @@ struct FormatToken { isAttribute(); } - /// Determine whether the token is a simple-type-specifier. - [[nodiscard]] bool isSimpleTypeSpecifier() const; - - [[nodiscard]] bool isTypeName(bool IsCpp) const; - - [[nodiscard]] bool isTypeOrIdentifier(bool IsCpp) const; + [[nodiscard]] bool isTypeName(const LangOptions ) const; + [[nodiscard]] bool isTypeOrIdentifier(const LangOptions ) const; bool isObjCAccessSpecifier() const { return is(tok::at) && Next && diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index f430d3764babe..e21b5a882b777 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++
[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-constraints (PR #92019)
@@ -306,6 +306,10 @@ Changes in existing checks don't remove parentheses used in ``sizeof`` calls when they have array index accesses as arguments. +- Improved :doc:`modernize-use-constraints + ` check by fixing a crash that + occurred in some scenarios and excluded system headers from analysis. HerrCai0907 wrote: ```suggestion occurred in some scenarios and excluding system headers from analysis. ``` https://github.com/llvm/llvm-project/pull/92019 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-constraints (PR #92019)
https://github.com/HerrCai0907 approved this pull request. https://github.com/llvm/llvm-project/pull/92019 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore implicit casts with errors in bugprone-implicit-widening-of-multiplication-result (PR #92025)
https://github.com/HerrCai0907 approved this pull request. https://github.com/llvm/llvm-project/pull/92025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Allow explicit instantiation of Ref/RefPtr on call arguments. (PR #91875)
https://github.com/haoNoQ approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/91875 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Treat break, continue, goto, and label statements as trivial in WebKit checkers. (PR #91873)
@@ -445,6 +456,10 @@ class TrivialFunctionAnalysisVisitor return Visit(VMT->getSubExpr()); } + bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr* BTE) { +return Visit(BTE->getSubExpr()); haoNoQ wrote: At this point you probably want to double-check that the destructor itself is trivial (in the sense of your analysis, not in the general C++ sense). Destructor calls are generally not represented in the AST at all (unless they're explicit), CodeGen just figures them out from the rest of the syntax. `CXXBindTemporaryExpr` is probably the right place to look for destructors, at least according to me after reading a lot of ASTs. But at the same time nobody really understands what `CXXBindTemporaryExpr` stands for anymore and a few famous people have argued for removing it. Note that `CXXBindTemporaryExpr` doesn't guarantee that there will be a destructor call at the end of the full-expression (lifetime extension is a thing - need to consult `MaterializeTemporaryExpr` to see where this is going), or even at the end of function (RVO is a thing), even when the constructor is targeting a local variable (NRVO is a thing). In case of RVO/NRVO the caller doesn't necessarily call the destructor either; it could also be RVOing/NRVOing it further up the call stack up to arbitrarily large depth. In pre-C++17 AST, and even in C++17 and later if NRVO is involved, the AST would look as if a copy/move is being made even if it's elided in practice. So when checking the destructor, you need to think how far do you want to go when it comes to determining if the destructor actually happens by the time the function returns. Because in order to implement this accurately you'll need to re-implement a big chunk of CodeGen. You can also try to check the destructor inside `VisitCXXConstructExpr()`, as if assuming that every time an object is constructed, it'd be deleted "eventually". Except in this case you'll miss the part where you're receiving an object by value from a `CallExpr` (and such); then you'll also need to check the destructor for the received object even though you don't see the constructor. This isn't a problem when you're relying on `CXXBindTemporaryExpr` which will be present around the `CallExpr` normally when the object needs a destructor. https://github.com/llvm/llvm-project/pull/91873 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,78 @@ +//===--- UseInternalLinkageCheck.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 "UseInternalLinkageCheck.h" +#include "../utils/FileExtensionsUtils.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/STLExtras.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::misc { + +namespace { + +AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); } + +AST_MATCHER_P(Decl, isInMainFile, FileExtensionsSet, HeaderFileExtensions) { + return llvm::all_of(Node.redecls(), [&](const Decl *D) { +SourceManager = Finder->getASTContext().getSourceManager(); +const SourceLocation L = D->getLocation(); +return SM.isInMainFile(L) && + !utils::isSpellingLocInHeaderFile(L, SM, HeaderFileExtensions); + }); HerrCai0907 wrote: It will match more cases which I cannot understand the code style. e.g. ```c++ /// a.cpp void f(); // decl-1 /// b.cpp #include void f() {} // decl-2 ``` The current version will ignore this cases because decl-1 is not in main file. But the suggestion version will catch this cases because both file is source fill extensions. Actually I don't understand and didn't meet this code style, so I keep conservative to avoid false positive. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Revert "Generate assume loads only with -fstrict-vtable-pointers" (PR #91900)
aeubanks wrote: > -fstrict-vtable-pointers IS experimental, but if you recall, this particular > optimization was added to -fstrict-vtable-pointers because of the effects it > had on compile-time, not because of correctness issues. can you clarify what you mean by "this particular optimization"? you mean adding or not adding assume loads? when I said "regress", I meant runtime performance, not compile times, I should have been clearer https://github.com/llvm/llvm-project/pull/91900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] e20800c - [clang-format][NFC] Test IsQualifier only needs to call the lexer
Author: Owen Pan Date: 2024-05-13T19:45:11-07:00 New Revision: e20800c16f0570562fea31e9a02d65ba56e6858a URL: https://github.com/llvm/llvm-project/commit/e20800c16f0570562fea31e9a02d65ba56e6858a DIFF: https://github.com/llvm/llvm-project/commit/e20800c16f0570562fea31e9a02d65ba56e6858a.diff LOG: [clang-format][NFC] Test IsQualifier only needs to call the lexer Added: Modified: clang/unittests/Format/QualifierFixerTest.cpp Removed: diff --git a/clang/unittests/Format/QualifierFixerTest.cpp b/clang/unittests/Format/QualifierFixerTest.cpp index 1e997bb06b867..4ddeef50f5f78 100644 --- a/clang/unittests/Format/QualifierFixerTest.cpp +++ b/clang/unittests/Format/QualifierFixerTest.cpp @@ -1055,7 +1055,9 @@ TEST_F(QualifierFixerTest, IsQualifierType) { ConfiguredTokens.push_back(tok::kw_constexpr); ConfiguredTokens.push_back(tok::kw_friend); - auto Tokens = annotate( + TestLexer lexer{Allocator, Buffers}; + + auto Tokens = lexer.lex( "const static inline auto restrict int double long constexpr friend"); ASSERT_EQ(Tokens.size(), 11u) << Tokens; @@ -1081,7 +1083,7 @@ TEST_F(QualifierFixerTest, IsQualifierType) { EXPECT_TRUE(isQualifierOrType(Tokens[8])); EXPECT_TRUE(isQualifierOrType(Tokens[9])); - auto NotTokens = annotate("for while do Foo Bar "); + auto NotTokens = lexer.lex("for while do Foo Bar "); ASSERT_EQ(NotTokens.size(), 6u) << Tokens; EXPECT_FALSE(isConfiguredQualifierOrType(NotTokens[0], ConfiguredTokens)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)
@@ -9806,7 +9806,7 @@ QualType Sema::BuildCountAttributedArrayType(QualType WrappedTy, /// that expression, according to the rules in C++11 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. QualType Sema::getDecltypeForExpr(Expr *E) { - if (E->isTypeDependent()) + if (E->isInstantiationDependent()) zyn0217 wrote: Is it... right? I was assuming this would bring such regressions e.g. ```cpp template const int val = sizeof(T); template void foo() { decltype(val); // <-- this is instantiation-dependent, but not type-dependent. } ``` Perhaps we can move it to line 9816 where the `PackIndexingExpr` is handled? https://github.com/llvm/llvm-project/pull/91933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,78 @@ +//===--- UseInternalLinkageCheck.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 "UseInternalLinkageCheck.h" +#include "../utils/FileExtensionsUtils.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/STLExtras.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::misc { + +namespace { + +AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); } + +AST_MATCHER_P(Decl, isInMainFile, FileExtensionsSet, HeaderFileExtensions) { + return llvm::all_of(Node.redecls(), [&](const Decl *D) { +SourceManager = Finder->getASTContext().getSourceManager(); +const SourceLocation L = D->getLocation(); +return SM.isInMainFile(L) && + !utils::isSpellingLocInHeaderFile(L, SM, HeaderFileExtensions); + }); +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.getStorageClass() == SC_Extern; +} + +} // namespace + +void UseInternalLinkageCheck::registerMatchers(MatchFinder *Finder) { + auto Common = allOf(isFirstDecl(), isInMainFile(HeaderFileExtensions), HerrCai0907 wrote: It still work fine. The reason I add `isFirstDecl` is that the check will check all redecl and add this limitation can avoid O(n^2) complexity. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)
phoebewang wrote: > @phoebewang Can you add a release note for this on the PR for the release > branch and then add the release:note label. Done. https://github.com/llvm/llvm-project/pull/91694 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
Lancern wrote: FWIW, the current practice uses CamelCase for CIRGen and camelBack for all other CIR stuff. Most code in CIRGen is directly ported from clang CodeGen and the code style is kept as-is, while other part of CIR is invented from scratch and we follow MLIR style guides. I'm not sure whether this is an acceptable scheme, but the naming style problems pointed out specifically in this PR (e.g. `langOpts`) should be resolved if this scheme is to be followed as they appear in CIRGen. https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (PR #91930)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/91930 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] c72e943 - [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (#91930)
Author: Owen Pan Date: 2024-05-13T19:19:15-07:00 New Revision: c72e94382c21db2f5ff066d72103ac55eb8d2874 URL: https://github.com/llvm/llvm-project/commit/c72e94382c21db2f5ff066d72103ac55eb8d2874 DIFF: https://github.com/llvm/llvm-project/commit/c72e94382c21db2f5ff066d72103ac55eb8d2874.diff LOG: [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (#91930) Move static member functions LeftRightQualifierAlignmentFixer::is...() out of the class so that #91712 can reland. Added: Modified: clang/lib/Format/QualifierAlignmentFixer.cpp clang/lib/Format/QualifierAlignmentFixer.h clang/unittests/Format/QualifierFixerTest.cpp Removed: diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp b/clang/lib/Format/QualifierAlignmentFixer.cpp index c263530456727..36d0639041c6c 100644 --- a/clang/lib/Format/QualifierAlignmentFixer.cpp +++ b/clang/lib/Format/QualifierAlignmentFixer.cpp @@ -614,22 +614,21 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer( } } -bool LeftRightQualifierAlignmentFixer::isQualifierOrType(const FormatToken *Tok, - bool IsCpp) { +bool isQualifierOrType(const FormatToken *Tok, bool IsCpp) { return Tok && (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) || isQualifier(Tok)); } -bool LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( -const FormatToken *Tok, const std::vector , -bool IsCpp) { +bool isConfiguredQualifierOrType(const FormatToken *Tok, + const std::vector , + bool IsCpp) { return Tok && (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) || isConfiguredQualifier(Tok, Qualifiers)); } // If a token is an identifier and it's upper case, it could // be a macro and hence we need to be able to ignore it. -bool LeftRightQualifierAlignmentFixer::isPossibleMacro(const FormatToken *Tok) { +bool isPossibleMacro(const FormatToken *Tok) { if (!Tok) return false; if (Tok->isNot(tok::identifier)) diff --git a/clang/lib/Format/QualifierAlignmentFixer.h b/clang/lib/Format/QualifierAlignmentFixer.h index e1cc27e62b13a..e31d525da1640 100644 --- a/clang/lib/Format/QualifierAlignmentFixer.h +++ b/clang/lib/Format/QualifierAlignmentFixer.h @@ -32,6 +32,15 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer( std::vector , std::vector ); +// Is the Token a simple or qualifier type +bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true); +bool isConfiguredQualifierOrType(const FormatToken *Tok, + const std::vector , + bool IsCpp = true); + +// Is the Token likely a Macro +bool isPossibleMacro(const FormatToken *Tok); + class LeftRightQualifierAlignmentFixer : public TokenAnalyzer { std::string Qualifier; bool RightAlign; @@ -69,16 +78,6 @@ class LeftRightQualifierAlignmentFixer : public TokenAnalyzer { const FormatToken *Tok, const std::string , tok::TokenKind QualifierType); - - // Is the Token a simple or qualifier type - static bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true); - static bool - isConfiguredQualifierOrType(const FormatToken *Tok, - const std::vector , - bool IsCpp = true); - - // Is the Token likely a Macro - static bool isPossibleMacro(const FormatToken *Tok); }; } // end namespace format diff --git a/clang/unittests/Format/QualifierFixerTest.cpp b/clang/unittests/Format/QualifierFixerTest.cpp index 792d8f3c3a982..1e997bb06b867 100644 --- a/clang/unittests/Format/QualifierFixerTest.cpp +++ b/clang/unittests/Format/QualifierFixerTest.cpp @@ -1059,66 +1059,44 @@ TEST_F(QualifierFixerTest, IsQualifierType) { "const static inline auto restrict int double long constexpr friend"); ASSERT_EQ(Tokens.size(), 11u) << Tokens; - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[0], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[1], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[2], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[3], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[4], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[5], ConfiguredTokens)); - EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType( - Tokens[6], ConfiguredTokens)); -
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH 1/7] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e8785..8f58d9f24ba49 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e..d389287e8f490 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 0..4970d3339ef05 --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.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 "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang-tools-extra] [clang-tidy] support expect no diagnosis test (PR #91293)
https://github.com/HerrCai0907 closed https://github.com/llvm/llvm-project/pull/91293 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] f12018e - [clang-tidy] support expect no diagnosis test (#91293)
Author: Congcong Cai Date: 2024-05-14T09:48:57+08:00 New Revision: f12018eba11f8d4b74cf67dbc416c429c870a5f4 URL: https://github.com/llvm/llvm-project/commit/f12018eba11f8d4b74cf67dbc416c429c870a5f4 DIFF: https://github.com/llvm/llvm-project/commit/f12018eba11f8d4b74cf67dbc416c429c870a5f4.diff LOG: [clang-tidy] support expect no diagnosis test (#91293) When someone wants to declare a test case without any diagnosis. check-clang-tidy will failed with error message ``` CHECK-FIXES, CHECK-MESSAGES or CHECK-NOTES not found in the input ``` This PR want to check there are no diagnosis from clang-tidy when CHECK-FIXES, CHECK-MESSAGES or CHECK-NOTES are not found. It also changes the extension of a test case. `hxx` is not a valid test case extension and won't be tested. - Co-authored-by: Danny Mösch Added: clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp Modified: clang-tools-extra/test/clang-tidy/check_clang_tidy.py Removed: clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx diff --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py index 6d4b466afa691..e92179ac82c6a 100755 --- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py +++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py @@ -99,6 +99,7 @@ def __init__(self, args, extra_args): self.has_check_fixes = False self.has_check_messages = False self.has_check_notes = False +self.expect_no_diagnosis = False self.export_fixes = args.export_fixes self.fixes = MessagePrefix("CHECK-FIXES") self.messages = MessagePrefix("CHECK-MESSAGES") @@ -172,12 +173,21 @@ def get_prefixes(self): ) if not has_check_fix and not has_check_message and not has_check_note: -sys.exit( -"%s, %s or %s not found in the input" -% (self.fixes.prefix, self.messages.prefix, self.notes.prefix) -) +self.expect_no_diagnosis = True -assert self.has_check_fixes or self.has_check_messages or self.has_check_notes +expect_diagnosis = ( +self.has_check_fixes or self.has_check_messages or self.has_check_notes +) +if self.expect_no_diagnosis and expect_diagnosis: +sys.exit( +"%s, %s or %s not found in the input" +% ( +self.fixes.prefix, +self.messages.prefix, +self.notes.prefix, +) +) +assert expect_diagnosis or self.expect_no_diagnosis def prepare_test_inputs(self): # Remove the contents of the CHECK lines to avoid CHECKs matching on @@ -226,6 +236,10 @@ def run_clang_tidy(self): print("--") return clang_tidy_output +def check_no_diagnosis(self, clang_tidy_output): +if clang_tidy_output != "": +sys.exit("No diagnostics were expected, but found the ones above") + def check_fixes(self): if self.has_check_fixes: try_run( @@ -277,7 +291,9 @@ def run(self): self.get_prefixes() self.prepare_test_inputs() clang_tidy_output = self.run_clang_tidy() -if self.export_fixes is None: +if self.expect_no_diagnosis: +self.check_no_diagnosis(clang_tidy_output) +elif self.export_fixes is None: self.check_fixes() self.check_messages(clang_tidy_output) self.check_notes(clang_tidy_output) diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp new file mode 100644 index 0..4918aae16cb94 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp @@ -0,0 +1,6 @@ +// RUN: %check_clang_tidy %s misc-unused-using-decls %t + +// Verify that we don't generate the warnings on header files. +namespace foo { class Foo {}; } + +using foo::Foo; diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx deleted file mode 100644 index f15e4fae80c0b..0 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx +++ /dev/null @@ -1,6 +0,0 @@ -// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes -- -fno-delayed-template-parsing -isystem %S/Inputs - -// Verify that we don't generate the warnings on header files. -namespace foo { class Foo {}; } - -using foo::Foo; ___ cfe-commits mailing list cfe-commits@lists.llvm.org
[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)
ChuanqiXu9 wrote: @rjmccall @dwblaikie Since I feel this is a bug we need to fix and I think this patch may not affect non-modules code, I'd like to land this in the end of July (before the next branching of 19) if no more comments came in. https://github.com/llvm/llvm-project/pull/75912 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Avoid unevaluated implicit private (PR #92055)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (SunilKuravinakop) Changes For every variable used under `#pragma omp task` directive (`DeclRefExpr`) an ImplicitPrivateVariable is created in the AST, if `private` or `shared` clauses are not present. If the variable has the property of `non_odr_use_unevaluated` e.g. for statements which use `sizeof( i )` `i` will have `non_odr_use_unevaluated` . In such cases CodeGen was asserting by avoiding emitting of LLVM IR for such variables. To prevent this assertion this checkin avoids adding the ImplicitPrivateVariable for variables with `non_odr_use_unevaluated`. --- Full diff: https://github.com/llvm/llvm-project/pull/92055.diff 2 Files Affected: - (modified) clang/lib/Sema/SemaOpenMP.cpp (+2-1) - (modified) clang/test/OpenMP/task_ast_print.cpp (+34) ``diff diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index 7d00cf6fb5b6a..6110e5229b076 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -3757,7 +3757,8 @@ class DSAAttrChecker final : public StmtVisitor { void VisitDeclRefExpr(DeclRefExpr *E) { if (TryCaptureCXXThisMembers || E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || -E->isInstantiationDependent()) +E->isInstantiationDependent() || +E->isNonOdrUse() == clang::NOUR_Unevaluated) return; if (auto *VD = dyn_cast(E->getDecl())) { // Check the datasharing rules for the expressions in the clauses. diff --git a/clang/test/OpenMP/task_ast_print.cpp b/clang/test/OpenMP/task_ast_print.cpp index 12923e6ab4244..9d545c5f6716c 100644 --- a/clang/test/OpenMP/task_ast_print.cpp +++ b/clang/test/OpenMP/task_ast_print.cpp @@ -5,6 +5,7 @@ // RUN: %clang_cc1 -verify -Wno-vla -fopenmp-simd -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -std=c++11 -include-pch %t -verify -Wno-vla %s -ast-print | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -ast-dump %s | FileCheck %s --check-prefix=DUMP // expected-no-diagnostics #ifndef HEADER @@ -208,4 +209,37 @@ int main(int argc, char **argv) { extern template int S::TS; extern template long S::TS; +int +implicit_firstprivate() { + +#pragma omp parallel num_threads(1) + { +int i = 0; +// DUMP : OMPTaskDirective +// DUMP-NEXT : OMPFirstprivateClause +// DUMP-NEXT : DeclRefExpr {{.+}} 'i' {{.+}} refers_to_enclosing_variable_or_capture +#pragma omp task +{ + int j = sizeof(i); + j = i; +} + } +} + +int +no_implicit_firstprivate() { + +#pragma omp parallel num_threads(1) + { +int i = 0; +// DUMP : OMPTaskDirective +// DUMP-NEXT : CapturedStmt +// DUMP : DeclRefExpr {{.+}} 'i' {{.+}} non_odr_use_unevaluated refers_to_enclosing_variable_or_capture +#pragma omp task +{ + int j = sizeof(i); +} + } +} + #endif `` https://github.com/llvm/llvm-project/pull/92055 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Avoid unevaluated implicit private (PR #92055)
https://github.com/SunilKuravinakop created https://github.com/llvm/llvm-project/pull/92055 For every variable used under `#pragma omp task` directive (`DeclRefExpr`) an ImplicitPrivateVariable is created in the AST, if `private` or `shared` clauses are not present. If the variable has the property of `non_odr_use_unevaluated` e.g. for statements which use `sizeof( i )` `i` will have `non_odr_use_unevaluated` . In such cases CodeGen was asserting by avoiding emitting of LLVM IR for such variables. To prevent this assertion this checkin avoids adding the ImplicitPrivateVariable for variables with `non_odr_use_unevaluated`. >From 6946c9f1285d5a27eafcdbf13f79c0641736198d Mon Sep 17 00:00:00 2001 From: Sunil Kuravinakop Date: Thu, 9 May 2024 12:09:15 -0500 Subject: [PATCH 1/2] Avoiding DeclRefExpr with "non_odr_use_unevaluated" to declare "Implicit Private variable" DeclRefExpr. Changes to be committed: modified: clang/lib/Sema/SemaOpenMP.cpp --- clang/lib/Sema/SemaOpenMP.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index cf5447f223d45..bb6518099b4df 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -3757,7 +3757,8 @@ class DSAAttrChecker final : public StmtVisitor { void VisitDeclRefExpr(DeclRefExpr *E) { if (TryCaptureCXXThisMembers || E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || -E->isInstantiationDependent()) +E->isInstantiationDependent() || +E->isNonOdrUse() == clang::NOUR_Unevaluated) return; if (auto *VD = dyn_cast(E->getDecl())) { // Check the datasharing rules for the expressions in the clauses. >From 862907f4a6d7cebfb1b816e9ec890c39d0da112e Mon Sep 17 00:00:00 2001 From: Sunil Kuravinakop Date: Mon, 13 May 2024 01:28:59 -0500 Subject: [PATCH 2/2] Adding checks for proper declaration of DeclRefExpr under the task directive (when variable can be non_odr_use_unevaluated). Changes to be committed: modified: clang/test/OpenMP/task_ast_print.cpp --- clang/test/OpenMP/task_ast_print.cpp | 34 1 file changed, 34 insertions(+) diff --git a/clang/test/OpenMP/task_ast_print.cpp b/clang/test/OpenMP/task_ast_print.cpp index 12923e6ab4244..9d545c5f6716c 100644 --- a/clang/test/OpenMP/task_ast_print.cpp +++ b/clang/test/OpenMP/task_ast_print.cpp @@ -5,6 +5,7 @@ // RUN: %clang_cc1 -verify -Wno-vla -fopenmp-simd -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -std=c++11 -include-pch %t -verify -Wno-vla %s -ast-print | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -ast-dump %s | FileCheck %s --check-prefix=DUMP // expected-no-diagnostics #ifndef HEADER @@ -208,4 +209,37 @@ int main(int argc, char **argv) { extern template int S::TS; extern template long S::TS; +int +implicit_firstprivate() { + +#pragma omp parallel num_threads(1) + { +int i = 0; +// DUMP : OMPTaskDirective +// DUMP-NEXT : OMPFirstprivateClause +// DUMP-NEXT : DeclRefExpr {{.+}} 'i' {{.+}} refers_to_enclosing_variable_or_capture +#pragma omp task +{ + int j = sizeof(i); + j = i; +} + } +} + +int +no_implicit_firstprivate() { + +#pragma omp parallel num_threads(1) + { +int i = 0; +// DUMP : OMPTaskDirective +// DUMP-NEXT : CapturedStmt +// DUMP : DeclRefExpr {{.+}} 'i' {{.+}} non_odr_use_unevaluated refers_to_enclosing_variable_or_capture +#pragma omp task +{ + int j = sizeof(i); +} + } +} + #endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #87933)
ZequanWu wrote: ``` $ cat a.cpp namespace std { template struct b { static const int c = a; }; template using e = d; template struct p { using g = f; }; template using i = p::g; template class initializer_list {}; template using j = __remove_pointer(d); template using k = j; template constexpr bool l = b<__is_base_of(int, int)>::c; template using ab = e; template using o = ab, n>; template constexpr bool ad = (l && ...); template struct u; template using ae = u::g; template struct u { using g = n; }; template class t { public: t(initializer_list); }; namespace ag { template struct D; template struct D { using ah = ae...>; using g = i<0, ah, ah *>; }; } template using r = ag::D, s...>::g; template t(s...) -> t, sizeof...(s)>; class v { public: template o *w(an &&); }; using ap = v; struct aq : ap { int *ar = w(t{w(int{})}); aq() {} } $ clang a.cpp [crash] ``` https://github.com/llvm/llvm-project/pull/87933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][HLSL] Add environment parameter to availability attribute (PR #89809)
https://github.com/hekota updated https://github.com/llvm/llvm-project/pull/89809 >From 22b67d30ca087d6a912183039c87fd1790eedfe4 Mon Sep 17 00:00:00 2001 From: Helena Kotas Date: Tue, 23 Apr 2024 00:49:28 -0700 Subject: [PATCH 1/7] Add environment parameter to clang availability attribute --- clang/include/clang/Basic/Attr.td | 33 +- clang/include/clang/Basic/AttrDocs.td | 2 + .../clang/Basic/DiagnosticParseKinds.td | 2 + .../clang/Basic/DiagnosticSemaKinds.td| 5 +- clang/include/clang/Parse/Parser.h| 3 + clang/include/clang/Sema/ParsedAttr.h | 40 --- clang/include/clang/Sema/Sema.h | 5 +- clang/lib/AST/DeclBase.cpp| 27 - clang/lib/Headers/hlsl/hlsl_intrinsics.h | 13 ++- clang/lib/Index/CommentToXML.cpp | 3 + clang/lib/Parse/ParseDecl.cpp | 20 +++- clang/lib/Sema/SemaAPINotes.cpp | 3 +- clang/lib/Sema/SemaAvailability.cpp | 109 +- clang/lib/Sema/SemaDecl.cpp | 2 +- clang/lib/Sema/SemaDeclAttr.cpp | 34 -- 15 files changed, 232 insertions(+), 69 deletions(-) diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index dc87a8c6f022d..1b07f4eb40809 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -956,7 +956,7 @@ def Availability : InheritableAttr { VersionArgument<"deprecated">, VersionArgument<"obsoleted">, BoolArgument<"unavailable">, StringArgument<"message">, BoolArgument<"strict">, StringArgument<"replacement">, - IntArgument<"priority">]; + IntArgument<"priority">, IdentifierArgument<"environment">]; let AdditionalMembers = [{static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) { return llvm::StringSwitch(Platform) @@ -976,7 +976,7 @@ def Availability : InheritableAttr { .Case("xros", "visionOS") .Case("xros_app_extension", "visionOS (App Extension)") .Case("swift", "Swift") - .Case("shadermodel", "HLSL ShaderModel") + .Case("shadermodel", "HLSL Shader Model") .Case("ohos", "OpenHarmony OS") .Default(llvm::StringRef()); } @@ -1016,7 +1016,34 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) { .Case("visionos_app_extension", "xros_app_extension") .Case("ShaderModel", "shadermodel") .Default(Platform); -} }]; +} +static llvm::StringRef getPrettyEnviromentName(llvm::StringRef Environment) { +return llvm::StringSwitch(Environment) + .Case("pixel", "pixel shader") + .Case("vertex", "vertex shader") + .Case("geometry", "geometry shader") + .Case("hull", "hull shader") + .Case("domain", "domain shader") + .Case("compute", "compute shader") + .Case("mesh", "mesh shader") + .Case("amplification", "amplification shader") + .Case("library", "shader library") + .Default(Environment); +} +static llvm::Triple::EnvironmentType getEnvironmentType(llvm::StringRef Environment) { +return llvm::StringSwitch(Environment) + .Case("pixel", llvm::Triple::Pixel) + .Case("vertex", llvm::Triple::Vertex) + .Case("geometry", llvm::Triple::Geometry) + .Case("hull", llvm::Triple::Hull) + .Case("domain", llvm::Triple::Domain) + .Case("compute", llvm::Triple::Compute) + .Case("mesh", llvm::Triple::Mesh) + .Case("amplification", llvm::Triple::Amplification) + .Case("library", llvm::Triple::Library) + .Default(llvm::Triple::UnknownEnvironment); +} +}]; let HasCustomParsing = 1; let InheritEvenIfAlreadyPresent = 1; let Subjects = SubjectList<[Named]>; diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td index a0bbe5861c572..a81163df35ca8 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -1593,6 +1593,8 @@ replacement=\ *string-literal* a warning about use of a deprecated declaration. The Fix-It will replace the deprecated declaration with the new declaration specified. +// HEKOTA TODO add docs here + Multiple availability attributes can be placed on a declaration, which may correspond to different platforms. For most platforms, the availability attribute with the platform corresponding to the target platform will be used; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 66405095d51de..631dc8880fcfc 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -1103,6 +1103,8 @@ def
[clang] [flang] [llvm] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)
nikic wrote: @sgundapa Does https://github.com/llvm/llvm-project/pull/90802 fix the issue you're seeing? https://github.com/llvm/llvm-project/pull/68882 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] fix crash due to assumed callee in min-max-use-initializer-list (PR #91992)
https://github.com/sopyb approved this pull request. Glad someone was around to make a fix https://github.com/llvm/llvm-project/pull/91992 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #87933)
yronglin wrote: > Heads up. This causes clang to crash on some code. I'm running creduce to > reduce the cpp source file. > > ``` > clang: > /usr/local/google/home/zequanwu/workspace/llvm/clang/lib/Sema/SemaDecl.cpp:16509: > Decl *clang::Sema::ActOnFinishFunctionBody(Decl *, Stmt *, bool): Assertion > `!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"' failed. > ``` Thanks report this, nice and small reproducer would definitely help resolving this. https://github.com/llvm/llvm-project/pull/87933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
MaskRay wrote: > Ideally FileCheck should prefix commands with some tag to distinguish > comments from filecheck annotations, like > `--command-tag=@` and use as `@CHECK: xxx`, `@MYCHECK-NEXT: yyy`, etc. Making > typo\error in both prefix and command tag will be harder, i guess. That way > tool can immediately fail if can see command tag with unknown > prefix\directive, without silently guessing that this is comment and skipping. I remember I have seen quite a few FileCheck and lit improvement proposals. While some have been implemented, others are still under consideration. You might be interested in some threads that you can find by searching for `FileCheck @jh7370` and `FileCheck @pogo59` on https://discourse.llvm.org/ . https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
https://github.com/MaskRay approved this pull request. Some CHECK prefixes are auto-generated by llvm/utils/update_*_test_checks.py. Let's say my build directory is `/tmp/Rel` while my source is at `~/llvm`, use ``` PATH=/tmp/Rel/bin:$PATH ~/llvm/llvm/utils/update_any_test_checks.py path/to/test ``` to re-generate tests. (It seems that some stale comments might not be removed. I haven't read these scripts for a long time.) Perhaps revert changes to files that cause failures and possibly keep just `llvm/` in this PR. Feel free to raise a post on https://discourse.llvm.org/ and possibly refer to https://discourse.llvm.org/t/rfc-improving-filecheck/54962 (a previous post about these typos in tests). Thank you so much for cleaning up these tests! https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Revert "Generate assume loads only with -fstrict-vtable-pointers" (PR #91900)
AtariDreams wrote: -fstrict-vtable-pointers IS experimental, but if you recall, this particular optimization was added to -fstrict-vtable-pointers because of the effects it had on compile-time, not because of correctness issues. https://github.com/llvm/llvm-project/pull/91900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Revert "Generate assume loads only with -fstrict-vtable-pointers" (PR #91900)
aeubanks wrote: adding assumes in general has issues: https://discourse.llvm.org/t/llvm-assume-blocks-optimization/71609 do you have proof that this change helps binaries and doesn't regress things? I have a feeling this will regress many things. `-fstrict-vtable-pointers` is still somewhat experimental https://github.com/llvm/llvm-project/pull/91900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Replace localUncachedLookup with noload_lookup in ASTImporterFixtures (NFC) (PR #91955)
https://github.com/AtariDreams updated https://github.com/llvm/llvm-project/pull/91955 >From bfd1ce3e91bb21fd4ff2d722cac47cffab1e407b Mon Sep 17 00:00:00 2001 From: Rose Date: Mon, 13 May 2024 08:54:36 -0400 Subject: [PATCH] [AST] Replace localUncachedLookup with noload_lookup in ASTImporterFixtures --- clang/unittests/AST/ASTImporterFixtures.cpp | 7 ++- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/clang/unittests/AST/ASTImporterFixtures.cpp b/clang/unittests/AST/ASTImporterFixtures.cpp index 897b370dd3cdc..cf6a52331125b 100644 --- a/clang/unittests/AST/ASTImporterFixtures.cpp +++ b/clang/unittests/AST/ASTImporterFixtures.cpp @@ -157,11 +157,8 @@ std::tuple ASTImporterTestBase::getImportedDecl( assert(ImportedII && "Declaration with the given identifier " "should be specified in test!"); DeclarationName ImportDeclName(ImportedII); - SmallVector FoundDecls; - FromCtx.getTranslationUnitDecl()->localUncachedLookup(ImportDeclName, -FoundDecls); - - assert(FoundDecls.size() == 1); + DeclContext::lookup_result FoundDecls = + FromCtx.getTranslationUnitDecl()->noload_lookup(ImportDeclName); Decl *Imported = FromTU.import(SharedStatePtr, ToAST.get(), FoundDecls.front()); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Replace localUncachedLookup with noload_lookup in ASTImporterFixtures (NFC) (PR #91955)
https://github.com/AtariDreams reopened https://github.com/llvm/llvm-project/pull/91955 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Replace localUncachedLookup with noload_lookup in ASTImporterFixtures (NFC) (PR #91955)
https://github.com/AtariDreams edited https://github.com/llvm/llvm-project/pull/91955 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Revert "Generate assume loads only with -fstrict-vtable-pointers" (PR #91900)
AtariDreams wrote: @aeubanks What do you think about this change? https://github.com/llvm/llvm-project/pull/91900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)
bader wrote: @AlexVlx, do you think it's worth promoting [SPV_INTEL_inline_assembly](https://github.com/intel/llvm/blob/sycl/sycl/doc/design/spirv-extensions/SPV_INTEL_inline_assembly.asciidoc) and [SPV_INTEL_function_pointers](https://github.com/intel/llvm/blob/sycl/sycl/doc/design/spirv-extensions/SPV_INTEL_function_pointers.asciidoc) to Khronos extensions? https://github.com/llvm/llvm-project/pull/89796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Add missing spaces in BoolOption for apinotes (PR #92027)
https://github.com/egorzhdan approved this pull request. Thank you, LGTM! https://github.com/llvm/llvm-project/pull/92027 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][flang][windows] Prefer user-provided library paths (-L) (PR #90758)
DavidTruby wrote: I've left the flang test as the flang directory doesn't change with `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR` and removed the other test. I hope this is what you meant @MaskRay https://github.com/llvm/llvm-project/pull/90758 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)
tstellar wrote: @phoebewang Can you add a release note for this on the PR for the release branch and then add the release:note label. https://github.com/llvm/llvm-project/pull/91694 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Respect the [[clang::unsafe_buffer_usage]] attribute for constructors (PR #91777)
haoNoQ wrote: Hi! Thank you for digging into this! Sorry for the delay. > The new UnsafeBufferUsageCtorAttrGadget gadget explicitly avoids matching > against the std::span(ptr, size) constructor because that is handled by > SpanTwoParamConstructorGadget and we never want two gadgets to match the same > thing (and this is guarded by asserts). Hmm at a glance I'm not sure this should really be illegal. It's a big problem when fixable gadgets overlap, because this means that they'll try to fix the same code in two incompatible ways. I don't immediately see why this would be a problem for warning gadgets that don't try to fix anything. This just means that the code is non-compliant for two different reasons, which is theoretically fine. I also tried to reproduce your assert and I didn't hit it; which one are you running into? > To handle this we allow the gadget to control if the warning is general (it > calls handleUnsafeBufferUsage()) or is a std-container-specific warning (it > calls handleUnsafeOperationInContainer()). Ooo I love this. My initial thinking was, just make the base Gadget class "public" (move it into `UnsafeBufferUsage.h` so that the handler could see it) and make the handler switch over the gadget's `getKind()` to produce specialized messages for each gadget. This would help us unscrew the rest of the `Reporter` code so that it also didn't have to guess by statement kind. Your design can grow into that too - make a separate handler method for each gadget kind (or group of kinds), and it preserves even more encapsulation. Additionally it throws away `getBaseStmt()` in favor of a more "integrated" solution. I'm a big fan, let's keep this. https://github.com/llvm/llvm-project/pull/91777 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Throw error when calling atomic with pointer to zero size object (PR #91057)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff 561c42df5712c346d4de2e6499b06712403d3164 dfa0b6b840b1ab12c27b7203ab372bd147885173 -- clang/lib/Sema/SemaChecking.cpp clang/test/Sema/atomic-ops.c `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index f91ab833b4..85d1b2f72c 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -8499,7 +8499,7 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, << /*is non object*/ 0 << ExprRange; return ExprError(); } - + if (Args.size() > AdjustedNumArgs) { Diag(Args[AdjustedNumArgs]->getBeginLoc(), diag::err_typecheck_call_too_many_args) `` https://github.com/llvm/llvm-project/pull/91057 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Throw error when calling atomic with pointer to zero size object (PR #91057)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Hendrik Hübner (HendrikHuebner) Changes When an atomic builtin is called with a pointer to an object of size zero, an arithmetic exception gets thrown because there is a modulo operation with the objects size in codegen. This is described here: #90330 I have added a check to SemaChecking.cpp, which throws an error if this is the case. --- Full diff: https://github.com/llvm/llvm-project/pull/91057.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+3) - (modified) clang/lib/Sema/SemaChecking.cpp (+11-1) - (modified) clang/test/Sema/atomic-ops.c (+32) ``diff diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index e456ec2cac461..74d96a8cbe0dc 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -330,6 +330,9 @@ def warn_atomic_op_misaligned : Warning< "; the expected alignment (%0 bytes) exceeds the actual alignment (%1 bytes)">, InGroup; +def err_atomic_op_size_zero : Error< + "First argument cannot be a pointer to an object of size zero">; + def warn_atomic_op_oversized : Warning< "large atomic operation may incur " "significant performance penalty" diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index ecd1821651140..f91ab833b4fc7 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -40,6 +40,7 @@ #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" @@ -8497,7 +8498,9 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, << 0 << AdjustedNumArgs << static_cast(Args.size()) << /*is non object*/ 0 << ExprRange; return ExprError(); - } else if (Args.size() > AdjustedNumArgs) { + } + + if (Args.size() > AdjustedNumArgs) { Diag(Args[AdjustedNumArgs]->getBeginLoc(), diag::err_typecheck_call_too_many_args) << 0 << AdjustedNumArgs << static_cast(Args.size()) @@ -8544,6 +8547,13 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, } } + // pointer to object of size zero is not allowed + if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) { +Diag(ExprRange.getBegin(), diag::err_atomic_op_size_zero) +<< Ptr->getSourceRange(); +return ExprError(); + } + // For an arithmetic operation, the implied arithmetic must be well-formed. if (Form == Arithmetic) { // GCC does not enforce these rules for GNU atomics, but we do to help catch diff --git a/clang/test/Sema/atomic-ops.c b/clang/test/Sema/atomic-ops.c index 1d36667d6cf40..97da2582312bb 100644 --- a/clang/test/Sema/atomic-ops.c +++ b/clang/test/Sema/atomic-ops.c @@ -639,6 +639,38 @@ void memory_checks(_Atomic(int) *Ap, int *p, int val) { (void)__atomic_compare_exchange_n(p, p, val, 0, memory_order_seq_cst, -1); // expected-warning {{memory order argument to atomic operation is invalid}} } +struct Z { + char z[]; +}; + +void zeroSizeArgError(struct Z *a, struct Z *b, struct Z *c) { + __atomic_exchange(b, b, c, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_release); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_seq_cst); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_release); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_seq_cst); // expected-error {{First argument cannot be a pointer to an object of size zero}} +
[clang] [Clang] Throw error when calling atomic with pointer to zero size object (PR #91057)
https://github.com/HendrikHuebner updated https://github.com/llvm/llvm-project/pull/91057 From dfa0b6b840b1ab12c27b7203ab372bd147885173 Mon Sep 17 00:00:00 2001 From: hhuebner Date: Sat, 4 May 2024 13:49:38 +0200 Subject: [PATCH] [Clang] Throw error when calling atomic with pointer to zero size object --- .../clang/Basic/DiagnosticFrontendKinds.td| 3 ++ clang/lib/Sema/SemaChecking.cpp | 12 ++- clang/test/Sema/atomic-ops.c | 32 +++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index e456ec2cac461..74d96a8cbe0dc 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -330,6 +330,9 @@ def warn_atomic_op_misaligned : Warning< "; the expected alignment (%0 bytes) exceeds the actual alignment (%1 bytes)">, InGroup; +def err_atomic_op_size_zero : Error< + "First argument cannot be a pointer to an object of size zero">; + def warn_atomic_op_oversized : Warning< "large atomic operation may incur " "significant performance penalty" diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index ecd1821651140..f91ab833b4fc7 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -40,6 +40,7 @@ #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" @@ -8497,7 +8498,9 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, << 0 << AdjustedNumArgs << static_cast(Args.size()) << /*is non object*/ 0 << ExprRange; return ExprError(); - } else if (Args.size() > AdjustedNumArgs) { + } + + if (Args.size() > AdjustedNumArgs) { Diag(Args[AdjustedNumArgs]->getBeginLoc(), diag::err_typecheck_call_too_many_args) << 0 << AdjustedNumArgs << static_cast(Args.size()) @@ -8544,6 +8547,13 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, } } + // pointer to object of size zero is not allowed + if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) { +Diag(ExprRange.getBegin(), diag::err_atomic_op_size_zero) +<< Ptr->getSourceRange(); +return ExprError(); + } + // For an arithmetic operation, the implied arithmetic must be well-formed. if (Form == Arithmetic) { // GCC does not enforce these rules for GNU atomics, but we do to help catch diff --git a/clang/test/Sema/atomic-ops.c b/clang/test/Sema/atomic-ops.c index 1d36667d6cf40..97da2582312bb 100644 --- a/clang/test/Sema/atomic-ops.c +++ b/clang/test/Sema/atomic-ops.c @@ -639,6 +639,38 @@ void memory_checks(_Atomic(int) *Ap, int *p, int val) { (void)__atomic_compare_exchange_n(p, p, val, 0, memory_order_seq_cst, -1); // expected-warning {{memory order argument to atomic operation is invalid}} } +struct Z { + char z[]; +}; + +void zeroSizeArgError(struct Z *a, struct Z *b, struct Z *c) { + __atomic_exchange(b, b, c, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_release); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_seq_cst); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_release); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_seq_cst); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_store(a, b, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} +
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
klensy wrote: > Were these found manually or using some automated tooling? Based on the Rust > PR, it seems like these were found by just manually going through the results > from a regex? At first - yes, but later i noticed other error patterns and tried them iteratively; maybe some edit distance metrics can find more. Ideally FileCheck should prefix commands with some tag to distinguish comments from filecheck annotations, like `--command-tag=@` and use as `@CHECK: xxx`, `@MYCHECK-NEXT: yyy`, etc. Making typo\error in both prefix and command tag will be harder, i guess. https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
bcardosolopes wrote: Thanks for everyone's input so far. Let me try to summarize two discussions in this PR so we can set on an approach and give advice to our CIR community (and encode on our webpage) on how to move forward in upcoming patches. Useful resources: - [LLVM Coding Standard](https://llvm.org/docs/CodingStandards.html) - [MLIR Style Guide](https://mlir.llvm.org/getting_started/DeveloperGuide/#style-guide) CC'ing more people who might care: @seven-mile, @Lancern. ## Use of `auto` As @joker-eph mentioned, MLIR isn't meant to differ from LLVM/Clang, though they encode the differences as part of their guidelines. The `auto` [guidance](https://llvm.org/docs/CodingStandards.html#use-auto-type-deduction-to-make-code-more-readable) is still in favor of us keeping it for all `isa`, `dyn_cast` and `cast`, which is used in CIR, so it probably doesn't affect most of what we currently care about. Here's my suggestion for the entire `lib/CIR`: 1. Use it for function templates such as `isa`, `dyn_cast`, `cast`, `create` and `rewriteOp.*` variants. 2. Use it for things considered obvious/common in MLIR space, examples: - `auto loc = op->getLoc()`. - Getting operands and results from operations (they obey Value Semantics), e.g.: `DepthwiseConv2DNhwcHwcmOp op; ...; auto stride = op.getStrides();` - Other examples we are happy to provide upon reviewer feedback if it makes sense. Using the logic above, all `auto`s in this current PR have to be changed (since none apply). ## Namings: CamelCase vs camelBack >From this discussion, seems like @AaronBallman and @erichkeane are fine with >us using camelBack and all the other differences from [MLIR Style >Guide](https://mlir.llvm.org/getting_started/DeveloperGuide/#style-guide) in >CIRGen and the rest of CIR. Is that right? This is based on the comment: > The mixed naming conventions in the header should be fixed (preference is to > follow LLVM style if we're changing code around, but if the local preference > is for MLIR, that's fine so long as it's consistent). However, @AaronBallman also wrote: > Also, the fact that the naming keeps being inconsistent is a pretty strong > reason to change to use the LLVM naming convention, at least for external > interfaces. Should we ignore this in light of your first comment? If not, can you clarify what do you mean by external interfaces? Just want to make sure we get it right looking fwd. Does this makes sense? Thoughts? https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
klensy wrote: > When doing large scale cleanups, it might make sense to partition them, e.g. > llvm/ (clang/ & clang-tools-extra/) mlir/ in different PRs. The number of > files will be smaller and github web UI will not make the page too slow to > load. The active contributors in these components are largely disjoint and > they may not be confident to approve the whole PR. I understand, but i didn't wanted to immediately create multiple PRs while was in process; idea was to move reviewed parts into separate PRs by me or reviewers, if they prefer (added that to title). Thanks for fixes. https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)
bwendling wrote: > > It's not a lie, because the contents of a pointer don't contribute to the > > size of the struct containing that pointer. > > Consider this example. It tries to illustrate why putting `__counted_by()` on > a pointer to a structs containing flexible array members doesn't make sense. > > ```c > struct HasFAM { > int count; > char buffer[] __counted_by(count); // This is OK > }; > > struct BufferOfFAMS { > int count; > struct HasFAM* fams __counted_by(count); // This is invalid > }; > > struct BufferOfFAMS* setup(void) { > const int numFams = 2; > const int famSizes[] = { 8, 16}; > > struct BufferOfFAMS *f = (struct BufferOfFAMS *)malloc( > sizeof(struct BufferOfFAMS) + (sizeof(struct HasFam *) * numFams)); > > f->count = numFams; > > size_t famsBufferSize = 0; > for (int i=0; i < numFams; ++i) { > famsBufferSize += sizeof(struct HasFAM) + sizeof(char)* famSizes[i]; > } > f->fams = (struct HasFAM*) malloc(famsBufferSize); > memset(f->fams, 0, famsBufferSize); > > size_t byteOffset = 0; > for (int i=0; i < numFams; ++i) { > struct HasFAM* cur = (struct HasFAM*) (((char*)f->fams) + byteOffset); > cur->count = famSizes[i]; > byteOffset = sizeof(struct HasFAM) + (sizeof(char) * famSizes[i]); > } > return f; > } > > int main(void) { > // How would we compute the bounds of f::fams here?? > // `sizeof(struct HasFAM) * f->count` is WRONG. It's too small but this > // is what writing `__counted_by(count)` on `HasFAM::buffer` means. > // > // It's actually > // `(sizeof(struct HasFAM) * f->count) + (sizeof(char) * (8 + 16))` > // > // This means we can't use the `__counted_by()` attribute on > // `BufferOfFAMS::fams` to compute its bounds. But allowing the bounds > // to be computed is the whole point of the attribute. > struct BufferOfFAMS* f = setup(); > > // Similary doing any kind of indexing on the pointer > // is extremely problematic for exactly the same reason. > // > // The address is completely wrong because the offset is computed using > // `sizeof(struct HasFAM)` which won't include the array at the end. > // > // So `bogus_ptr` points to the first byte of the first `HasFAM::buffer`, > // instead of the second `struct HasFAM`. > struct HasFAM* bogus_ptr = >fams[1]; > return 0; > } > ``` I agree that it doesn't make sense, but not every struct will have a flexible array member, of course. :-) I guess as long as there's a followup with the support @kees mentioned above then I have no issues with this PR also. https://github.com/llvm/llvm-project/pull/90786 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [PowerPC][AIX] 64-bit large code-model support for toc-data (PR #90619)
https://github.com/syzaara updated https://github.com/llvm/llvm-project/pull/90619 >From 70a6bc5bb5d5d43a3e87b7cc597682d6647166fc Mon Sep 17 00:00:00 2001 From: Zaara Syeda Date: Tue, 30 Apr 2024 10:22:26 -0400 Subject: [PATCH 1/2] [PowerPC] 64-bit large code-model support for toc-data This patch adds support for toc-data for 64-bit large code-model. The sequence ADDIStocHA8/ADDItocL8 is used to access the data directly from the TOC. When emitting the instruction ADDIStocHA8, we check if the symbol has toc-data attribute before creating a toc entry for it. When emitting the instruction ADDItocL8, we use the LA8 instruction to load the address. --- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp | 22 +++ llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp | 33 +- llvm/lib/Target/PowerPC/PPCInstrInfo.cpp| 6 ++ llvm/lib/Target/PowerPC/PPCInstrInfo.td | 2 +- llvm/test/CodeGen/PowerPC/toc-data.ll | 67 + 5 files changed, 101 insertions(+), 29 deletions(-) diff --git a/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp b/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp index 51b79dc2b04b4..14dc4d1249a88 100644 --- a/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp +++ b/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp @@ -1148,21 +1148,21 @@ void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); -// If the symbol isn't toc-data then use the TOC on AIX. +// If the symbol does not have the toc-data attribute, then we create the +// TOC entry on AIX. If the toc-data attribute is used, the TOC entry +// contains the data rather than the address of the MOSymbol. // Map the global address operand to be a reference to the TOC entry we // will synthesize later. 'TOCEntry' is a label used to reference the // storage allocated in the TOC which contains the address of 'MOSymbol'. -// If the toc-data attribute is used, the TOC entry contains the data -// rather than the address of the MOSymbol. if (![](const MachineOperand ) { if (!MO.isGlobal()) return false; - const GlobalVariable *GV = dyn_cast(MO.getGlobal()); - if (!GV) -return false; + if (const GlobalVariable *GV = + dyn_cast(MO.getGlobal())) +return GV->hasAttribute("toc-data"); - return GV->hasAttribute("toc-data"); + return false; }(MO)) { MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK); } @@ -1292,8 +1292,9 @@ void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { unsigned Op = MI->getOpcode(); -// Change the opcode to load address for tocdata -TmpInst.setOpcode(Op == PPC::ADDItocL8 ? PPC::ADDI8 : PPC::LA); +// Change the opcode to load address for toc data. +unsigned NewOp64 = IsAIX ? PPC::LA8 : PPC::ADDI8; +TmpInst.setOpcode(Op == PPC::ADDItocL8 ? NewOp64 : PPC::LA); const MachineOperand = MI->getOperand(2); assert((Op == PPC::ADDItocL8) @@ -1307,8 +1308,7 @@ void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { const MCExpr *Exp = MCSymbolRefExpr::create( MOSymbol, -Op == PPC::ADDItocL8 ? MCSymbolRefExpr::VK_PPC_TOC_LO - : MCSymbolRefExpr::VK_PPC_L, +IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); TmpInst.getOperand(2) = MCOperand::createExpr(Exp); diff --git a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp index 2f647daa4bcb5..c9b3cb58ca583 100644 --- a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp +++ b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp @@ -6141,24 +6141,23 @@ void PPCDAGToDAGISel::Select(SDNode *N) { assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit" " ELF/AIX or 32-bit AIX in the following."); -// Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode -// or 64-bit medium (ELF-only) or large (ELF and AIX) code model code non -// toc-data symbols. +// Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode, +// 64-bit medium (ELF-only), or large (ELF and AIX) code model code that +// does not contain TOC data symbols. // We generate two instructions as described below. The first source -// operand is a symbol reference. If it must be toc-referenced according to -// Subtarget, we generate: +// operand is a symbol reference. If it must be referenced via the TOC +// according to Subtarget, we generate: // [32-bit AIX] // LWZtocL(@sym, ADDIStocHA(%r2, @sym)) // [64-bit ELF/AIX] // LDtocL(@sym, ADDIStocHA8(%x2, @sym)) // Otherwise we generate: // ADDItocL8(ADDIStocHA8(%x2, @sym), @sym) - -// For large code model toc-data symbols we generate: +// For large code model with TOC data symbols we
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
boomanaiden154 wrote: Were these found manually or using some automated tooling? Based on the Rust PR, it seems like these were found by just manually going through the results from a regex? https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
MaskRay wrote: The previous failures reported by `buildkite/github-pull-requests Pending` were genuine. I have fixed them separately. When doing large scale cleanups, it might make sense to partition them, e.g. llvm/ (clang/ & clang-tools-extra/) mlir/ in different PRs. The number of files will be smaller and github web UI will not make the page too slow to load. The active contributors in these components are largely disjoint and they may not be confident to approve the whole PR. https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #87933)
ZequanWu wrote: Heads up. This causes clang to crash on some code. I'm running creduce to reduce the cpp source file. https://github.com/llvm/llvm-project/pull/87933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [WIP][Safe Buffers] Serialize unsafe_buffer_usage pragmas (PR #92031)
llvmbot wrote: @llvm/pr-subscribers-clang-modules Author: Ziqing Luo (ziqingluo-90) Changes A pair of `#pragma clang unsafe_buffer_usage begin/end` pragmas marks a warning-opt-out region. The begin and end locations (opt-out regions) are stored in preprocessor instances (PP) and will be queried by the `-Wunsafe-buffer-usage` analyzer. The commit adds serialization and de-serialization implementations for the stored regions. Basically, the serialized representation of the regions of a PP is a (ordered) sequence of source location encodings. During serialization, it only serializes regions of the current translation unit. Regions from loaded files are not serialized. During de-serialization, regions from loaded files are stored by their source files. When later one queries if a loaded location `l` is in an opt-out region, PP looks up regions by the source file of `l`. The reported issue at upstream: https://github.com/llvm/llvm-project/issues/90501 rdar://124035402 --- Full diff: https://github.com/llvm/llvm-project/pull/92031.diff 12 Files Affected: - (modified) clang/include/clang/Lex/Preprocessor.h (+18-4) - (modified) clang/include/clang/Serialization/ASTBitCodes.h (+3) - (modified) clang/lib/Lex/Preprocessor.cpp (+87-19) - (modified) clang/lib/Serialization/ASTReader.cpp (+11) - (modified) clang/lib/Serialization/ASTWriter.cpp (+7) - (added) clang/test/Modules/Inputs/SafeBuffers/base.h (+9) - (added) clang/test/Modules/Inputs/SafeBuffers/safe_buffers_test.modulemap (+10) - (added) clang/test/Modules/Inputs/SafeBuffers/test_sub1.h (+20) - (added) clang/test/Modules/Inputs/SafeBuffers/test_sub2.h (+11) - (added) clang/test/Modules/safe_buffers_optout.cpp (+39) - (added) clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-pch-complex.cpp (+72) - (added) clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-pch.cpp (+27) ``diff diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h index e89b4a2c5230e..8d6884ebe7597 100644 --- a/clang/include/clang/Lex/Preprocessor.h +++ b/clang/include/clang/Lex/Preprocessor.h @@ -2883,11 +2883,15 @@ class Preprocessor { /// otherwise. SourceLocation CurrentSafeBufferOptOutStart; // It is used to report the start location of an never-closed region. - // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in one - // translation unit. Each region is represented by a pair of start and end - // locations. A region is "open" if its' start and end locations are + using SafeBufferOptOutMapTy = + SmallVector, 16>; + // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in this + // translation unit. Each region is represented by a pair of start and + // end locations. A region is "open" if its' start and end locations are // identical. - SmallVector, 8> SafeBufferOptOutMap; + SafeBufferOptOutMapTy SafeBufferOptOutMap; + // `SafeBufferOptOutMap`s of loaded files: + llvm::DenseMap LoadedSafeBufferOptOutMap; public: /// \return true iff the given `Loc` is in a "-Wunsafe-buffer-usage" opt-out @@ -2918,6 +2922,16 @@ class Preprocessor { /// opt-out region bool isPPInSafeBufferOptOutRegion(SourceLocation ); + /// \return a sequence of SourceLocations representing ordered opt-out regions + /// specified by + /// `\#pragma clang unsafe_buffer_usage begin/end`s of this translation unit. + SmallVector serializeSafeBufferOptOutMap() const; + + /// \param SrcLocSeqs a sequence of SourceLocations deserialized from a + /// record of code `PP_UNSAFE_BUFFER_USAGE`. + void setDeserializedSafeBufferOptOutMap( + const SmallVectorImpl ); + private: /// Helper functions to forward lexing to the actual lexer. They all share the /// same signature. diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h index dcfa4ac0c1967..d1a0eba943039 100644 --- a/clang/include/clang/Serialization/ASTBitCodes.h +++ b/clang/include/clang/Serialization/ASTBitCodes.h @@ -775,6 +775,9 @@ enum ASTRecordTypes { /// Record code for lexical and visible block for delayed namespace in /// reduced BMI. DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD = 68, + + /// Record code for \#pragma clang unsafe_buffer_usage begin/end + PP_UNSAFE_BUFFER_USAGE = 69, }; /// Record types used within a source manager block. diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp index 0b70192743a39..6a41e3d4138aa 100644 --- a/clang/lib/Lex/Preprocessor.cpp +++ b/clang/lib/Lex/Preprocessor.cpp @@ -58,6 +58,7 @@ #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" +#include "llvm/ADT/iterator_range.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" @@ -1483,26 +1484,41 @@ void Preprocessor::emitFinalMacroWarning(const Token , } bool
[clang] [WIP][Safe Buffers] Serialize unsafe_buffer_usage pragmas (PR #92031)
https://github.com/ziqingluo-90 created https://github.com/llvm/llvm-project/pull/92031 A pair of `#pragma clang unsafe_buffer_usage begin/end` pragmas marks a warning-opt-out region. The begin and end locations (opt-out regions) are stored in preprocessor instances (PP) and will be queried by the `-Wunsafe-buffer-usage` analyzer. The commit adds serialization and de-serialization implementations for the stored regions. Basically, the serialized representation of the regions of a PP is a (ordered) sequence of source location encodings. During serialization, it only serializes regions of the current translation unit. Regions from loaded files are not serialized. During de-serialization, regions from loaded files are stored by their source files. When later one queries if a loaded location `l` is in an opt-out region, PP looks up regions by the source file of `l`. The reported issue at upstream: https://github.com/llvm/llvm-project/issues/90501 rdar://124035402 >From ac5aeb5c3a134d085320fc7fc5cf3f2c8c41a1f1 Mon Sep 17 00:00:00 2001 From: ziqingluo-90 Date: Mon, 13 May 2024 13:31:21 -0700 Subject: [PATCH] fix safe buffer opt-out region serialization --- clang/include/clang/Lex/Preprocessor.h| 22 +++- .../include/clang/Serialization/ASTBitCodes.h | 3 + clang/lib/Lex/Preprocessor.cpp| 106 ++ clang/lib/Serialization/ASTReader.cpp | 11 ++ clang/lib/Serialization/ASTWriter.cpp | 7 ++ clang/test/Modules/Inputs/SafeBuffers/base.h | 9 ++ .../SafeBuffers/safe_buffers_test.modulemap | 10 ++ .../Modules/Inputs/SafeBuffers/test_sub1.h| 20 .../Modules/Inputs/SafeBuffers/test_sub2.h| 11 ++ clang/test/Modules/safe_buffers_optout.cpp| 39 +++ ...unsafe-buffer-usage-pragma-pch-complex.cpp | 72 .../warn-unsafe-buffer-usage-pragma-pch.cpp | 27 + 12 files changed, 314 insertions(+), 23 deletions(-) create mode 100644 clang/test/Modules/Inputs/SafeBuffers/base.h create mode 100644 clang/test/Modules/Inputs/SafeBuffers/safe_buffers_test.modulemap create mode 100644 clang/test/Modules/Inputs/SafeBuffers/test_sub1.h create mode 100644 clang/test/Modules/Inputs/SafeBuffers/test_sub2.h create mode 100644 clang/test/Modules/safe_buffers_optout.cpp create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-pch-complex.cpp create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-pch.cpp diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h index e89b4a2c5230e..8d6884ebe7597 100644 --- a/clang/include/clang/Lex/Preprocessor.h +++ b/clang/include/clang/Lex/Preprocessor.h @@ -2883,11 +2883,15 @@ class Preprocessor { /// otherwise. SourceLocation CurrentSafeBufferOptOutStart; // It is used to report the start location of an never-closed region. - // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in one - // translation unit. Each region is represented by a pair of start and end - // locations. A region is "open" if its' start and end locations are + using SafeBufferOptOutMapTy = + SmallVector, 16>; + // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in this + // translation unit. Each region is represented by a pair of start and + // end locations. A region is "open" if its' start and end locations are // identical. - SmallVector, 8> SafeBufferOptOutMap; + SafeBufferOptOutMapTy SafeBufferOptOutMap; + // `SafeBufferOptOutMap`s of loaded files: + llvm::DenseMap LoadedSafeBufferOptOutMap; public: /// \return true iff the given `Loc` is in a "-Wunsafe-buffer-usage" opt-out @@ -2918,6 +2922,16 @@ class Preprocessor { /// opt-out region bool isPPInSafeBufferOptOutRegion(SourceLocation ); + /// \return a sequence of SourceLocations representing ordered opt-out regions + /// specified by + /// `\#pragma clang unsafe_buffer_usage begin/end`s of this translation unit. + SmallVector serializeSafeBufferOptOutMap() const; + + /// \param SrcLocSeqs a sequence of SourceLocations deserialized from a + /// record of code `PP_UNSAFE_BUFFER_USAGE`. + void setDeserializedSafeBufferOptOutMap( + const SmallVectorImpl ); + private: /// Helper functions to forward lexing to the actual lexer. They all share the /// same signature. diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h index dcfa4ac0c1967..d1a0eba943039 100644 --- a/clang/include/clang/Serialization/ASTBitCodes.h +++ b/clang/include/clang/Serialization/ASTBitCodes.h @@ -775,6 +775,9 @@ enum ASTRecordTypes { /// Record code for lexical and visible block for delayed namespace in /// reduced BMI. DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD = 68, + + /// Record code for \#pragma clang unsafe_buffer_usage begin/end + PP_UNSAFE_BUFFER_USAGE = 69, }; /// Record types used within a source manager block. diff
[clang] [NFC] Add missing spaces in BoolOption for apinotes (PR #92027)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Jacob Lambert (lamb-j) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/92027.diff 1 Files Affected: - (modified) clang/include/clang/Driver/Options.td (+2-2) ``diff diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index ed3f1b8b29810..c9d8a1f50fecf 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -1858,13 +1858,13 @@ defm apinotes : BoolOption<"f", "apinotes", LangOpts<"APINotes">, DefaultFalse, PosFlag, NegFlag, -BothFlags<[], [ClangOption, CC1Option], "external API notes support">>, +BothFlags<[], [ClangOption, CC1Option], " external API notes support">>, Group; defm apinotes_modules : BoolOption<"f", "apinotes-modules", LangOpts<"APINotesModules">, DefaultFalse, PosFlag, NegFlag, -BothFlags<[], [ClangOption, CC1Option], "module-based external API notes support">>, +BothFlags<[], [ClangOption, CC1Option], " module-based external API notes support">>, Group; def fapinotes_swift_version : Joined<["-"], "fapinotes-swift-version=">, Group, Visibility<[ClangOption, CC1Option]>, `` https://github.com/llvm/llvm-project/pull/92027 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Add missing spaces in BoolOption for apinotes (PR #92027)
lamb-j wrote: https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fapinotes https://github.com/llvm/llvm-project/pull/92027 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Add missing spaces in BoolOption for apinotes (PR #92027)
https://github.com/lamb-j created https://github.com/llvm/llvm-project/pull/92027 None >From b68e9e234c1ccd62be507fcb1a0ab77241216f75 Mon Sep 17 00:00:00 2001 From: Jacob Lambert Date: Mon, 13 May 2024 13:24:48 -0700 Subject: [PATCH] [NFC] Add missing spaces in BoolOption for apinotes --- clang/include/clang/Driver/Options.td | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index ed3f1b8b29810..c9d8a1f50fecf 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -1858,13 +1858,13 @@ defm apinotes : BoolOption<"f", "apinotes", LangOpts<"APINotes">, DefaultFalse, PosFlag, NegFlag, -BothFlags<[], [ClangOption, CC1Option], "external API notes support">>, +BothFlags<[], [ClangOption, CC1Option], " external API notes support">>, Group; defm apinotes_modules : BoolOption<"f", "apinotes-modules", LangOpts<"APINotesModules">, DefaultFalse, PosFlag, NegFlag, -BothFlags<[], [ClangOption, CC1Option], "module-based external API notes support">>, +BothFlags<[], [ClangOption, CC1Option], " module-based external API notes support">>, Group; def fapinotes_swift_version : Joined<["-"], "fapinotes-swift-version=">, Group, Visibility<[ClangOption, CC1Option]>, ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore implicit casts with errors in bugprone-implicit-widening-of-multiplication-result (PR #92025)
PiotrZSL wrote: Not adding release notes & tests, as this is issue happen only when asserts are enabled and input is invalid. Fix created only to improve diagnostic for end user (errors instead of crash) in this particular case. https://github.com/llvm/llvm-project/pull/92025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore implicit casts with errors in bugprone-implicit-widening-of-multiplication-result (PR #92025)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Piotr Zegar (PiotrZSL) Changes When expression got errors (missing typedef) and clang-tidy is compiled with asserts enabled, then we crash in this check on assert because type with errors is visible as an dependent one. This is issue caused by invalid input. But as there is not point to crash in such case and generate additional confusion, such expressions with errors will be now ignored. Fixes #89515, #55293 --- Full diff: https://github.com/llvm/llvm-project/pull/92025.diff 1 Files Affected: - (modified) clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp (+6-5) ``diff diff --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp index 6f22f02f30183..f99beac668ce7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp @@ -9,20 +9,20 @@ #include "ImplicitWideningOfMultiplicationResultCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" #include "clang/Lex/Lexer.h" #include using namespace clang::ast_matchers; -namespace clang { +namespace clang::tidy::bugprone { + namespace { AST_MATCHER(ImplicitCastExpr, isPartOfExplicitCast) { return Node.isPartOfExplicitCast(); } +AST_MATCHER(Expr, containsErrors) { return Node.containsErrors(); } } // namespace -} // namespace clang - -namespace clang::tidy::bugprone { static const Expr *getLHSOfMulBinOp(const Expr *E) { assert(E == E->IgnoreParens() && "Already skipped all parens!"); @@ -250,7 +250,8 @@ void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting( void ImplicitWideningOfMultiplicationResultCheck::registerMatchers( MatchFinder *Finder) { - Finder->addMatcher(implicitCastExpr(unless(anyOf(isInTemplateInstantiation(), + Finder->addMatcher(implicitCastExpr(unless(anyOf(containsErrors(), + isInTemplateInstantiation(), isPartOfExplicitCast())), hasCastKind(CK_IntegralCast)) .bind("x"), `` https://github.com/llvm/llvm-project/pull/92025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore implicit casts with errors in bugprone-implicit-widening-of-multiplication-result (PR #92025)
https://github.com/PiotrZSL created https://github.com/llvm/llvm-project/pull/92025 When expression got errors (missing typedef) and clang-tidy is compiled with asserts enabled, then we crash in this check on assert because type with errors is visible as an dependent one. This is issue caused by invalid input. But as there is not point to crash in such case and generate additional confusion, such expressions with errors will be now ignored. Fixes #89515, #55293 >From 59b71daa3a19d6fd7c8d5f7722afc10a20d9903c Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Mon, 13 May 2024 20:25:35 + Subject: [PATCH] [clang-tidy] Ignore implicit casts with errors in bugprone-implicit-widening-of-multiplication-result When expression got errors (missing typedef) and clang-tidy is compiled with asserts enabled, then we crash in this check on assert because type with errors is visible as an dependent one. This is issue caused by invalid input. But as there is not point to crash in such case and generate additional confusion, such expressions with errors will be now ignored. Fixes #89515, #55293 --- .../ImplicitWideningOfMultiplicationResultCheck.cpp | 11 ++- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp index 6f22f02f30183..f99beac668ce7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp @@ -9,20 +9,20 @@ #include "ImplicitWideningOfMultiplicationResultCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" #include "clang/Lex/Lexer.h" #include using namespace clang::ast_matchers; -namespace clang { +namespace clang::tidy::bugprone { + namespace { AST_MATCHER(ImplicitCastExpr, isPartOfExplicitCast) { return Node.isPartOfExplicitCast(); } +AST_MATCHER(Expr, containsErrors) { return Node.containsErrors(); } } // namespace -} // namespace clang - -namespace clang::tidy::bugprone { static const Expr *getLHSOfMulBinOp(const Expr *E) { assert(E == E->IgnoreParens() && "Already skipped all parens!"); @@ -250,7 +250,8 @@ void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting( void ImplicitWideningOfMultiplicationResultCheck::registerMatchers( MatchFinder *Finder) { - Finder->addMatcher(implicitCastExpr(unless(anyOf(isInTemplateInstantiation(), + Finder->addMatcher(implicitCastExpr(unless(anyOf(containsErrors(), + isInTemplateInstantiation(), isPartOfExplicitCast())), hasCastKind(CK_IntegralCast)) .bind("x"), ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
https://github.com/joker-eph edited https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
@@ -42,6 +47,14 @@ CreateFrontendBaseAction(CompilerInstance ) { StringRef Action("unknown"); (void)Action; + auto UseCIR = CI.getFrontendOpts().UseClangIRPipeline; joker-eph wrote: MLIR isn't meant to differ from LLVM/Clang. > Coding standard doesn't allow use of 'auto' here, only when the actual type > of the variable is spelled on the RHS side (see next 2 lines too). Nit: technically the coding standard does not say that, I believe you're mentioning a sufficient condition, not a necessary one, see https://llvm.org/docs/CodingStandards.html#use-auto-type-deduction-to-make-code-more-readable > Use auto if and only if it makes the code more readable or easier to > maintain. https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Teach .option arch to support experimental extensions. (PR #89727)
MaskRay wrote: The clang/test/Driver codegen tests might have been removed. Note: clang/test/Driver is to test how clangDriver passes options to cc1, not for sema/codegen/etc. https://github.com/llvm/llvm-project/pull/89727 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)
sgundapa wrote: I've observed a significant regression in one of the AMDGPU benchmarks after applying this patch. The base address calculation within the unrolled loop seems to be the source. I've attached "before.log" and "after.log" files that detail the issue. The modified GEP format, introduced by this patch, doesn't align with the canonical form expected by the "separate-constant-offset-from-gep" pass. Consequently, the "straight line strength reduction" (SLSR) pass cannot optimize the computation. While the intention behind this patch, replicating some "split-gep" pass functionality, is understood, the unintended impact on the SLSR pass is notable. Before I delve into potential solutions, I would greatly appreciate your insights and perspective on this matter.[ [after.log](https://github.com/llvm/llvm-project/files/15299364/after.log) [before.log](https://github.com/llvm/llvm-project/files/15299365/before.log) ](url) https://github.com/llvm/llvm-project/pull/68882 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a6d7828 - [test] Use conventional -emit-llvm-only
Author: Fangrui Song Date: 2024-05-13T12:53:16-07:00 New Revision: a6d7828f4c50c1ec7b0b5f61fe59d7a768175dcc URL: https://github.com/llvm/llvm-project/commit/a6d7828f4c50c1ec7b0b5f61fe59d7a768175dcc DIFF: https://github.com/llvm/llvm-project/commit/a6d7828f4c50c1ec7b0b5f61fe59d7a768175dcc.diff LOG: [test] Use conventional -emit-llvm-only This avoids 'Permission denied' when PWD is read-only. While here, change the triple from a Linux one to a generic ELF one. Added: Modified: clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_fmlas16.c clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_mopa_nonwide.c Removed: diff --git a/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_fmlas16.c b/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_fmlas16.c index b1582569971d4..66aba36ff68ad 100644 --- a/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_fmlas16.c +++ b/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_fmlas16.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme -verify -emit-llvm %s +// RUN: %clang_cc1 -triple aarch64 -target-feature +sme -verify -emit-llvm-only %s // REQUIRES: aarch64-registered-target @@ -87,4 +87,4 @@ void test_imm(uint32_t slice, svfloat16_t zm, svfloat16x2_t zn2,svfloat16x4_t zn svmls_lane_za16_bf16_vg1x2(slice, bzn2, bzm, -1); // expected-error@+1 {{argument value 18446744073709551615 is outside the valid range [0, 7]}} svmls_lane_za16_bf16_vg1x4(slice, bzn4, bzm, -1); -} \ No newline at end of file +} diff --git a/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_mopa_nonwide.c b/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_mopa_nonwide.c index 201ad4b8ff7f0..1331bf2050b71 100644 --- a/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_mopa_nonwide.c +++ b/clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_mopa_nonwide.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme -verify -emit-llvm %s +// RUN: %clang_cc1 -triple aarch64 -target-feature +sme -verify -emit-llvm-only %s // REQUIRES: aarch64-registered-target ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-constraints (PR #92019)
PiotrZSL wrote: @ccotter Can you take a look, somehow I cannot select you as reviewer. https://github.com/llvm/llvm-project/pull/92019 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-constraints (PR #92019)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Piotr Zegar (PiotrZSL) Changes Improved modernize-use-constraints check by fixing a crash that occurred in some scenarios and excluded system headers from analysis. Problem were with DependentNameTypeLoc having null type location as getQualifierLoc().getTypeLoc(). Fixes #91872 --- Full diff: https://github.com/llvm/llvm-project/pull/92019.diff 4 Files Affected: - (modified) clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp (+4) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp (+32) ``diff diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp index 6d7d1d6b87c60..d9fab64050adb 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp @@ -41,6 +41,8 @@ AST_MATCHER(FunctionDecl, hasOtherDeclarations) { void UseConstraintsCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( functionTemplateDecl( + // Skip external libraries included as system headers + unless(isExpansionInSystemHeader()), has(functionDecl(unless(hasOtherDeclarations()), isDefinition(), hasReturnTypeLoc(typeLoc().bind("return"))) .bind("function"))) @@ -57,6 +59,8 @@ matchEnableIfSpecializationImplTypename(TypeLoc TheType) { return std::nullopt; } TheType = Dep.getQualifierLoc().getTypeLoc(); +if (TheType.isNull()) + return std::nullopt; } if (const auto SpecializationLoc = diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index fc976ce3a33d5..91b24f654112f 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -306,6 +306,10 @@ Changes in existing checks don't remove parentheses used in ``sizeof`` calls when they have array index accesses as arguments. +- Improved :doc:`modernize-use-constraints + ` check by fixing a crash that + occurred in some scenarios and excluded system headers from analysis. + - Improved :doc:`modernize-use-nullptr ` check to include support for C23, which also has introduced the ``nullptr`` keyword. diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst index be62dd5823d55..a8b31b80e580b 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst @@ -68,3 +68,7 @@ The tool will replace the above code with, // The tool will not emit a diagnostic or attempt to replace the code. template = 0> struct my_class {}; + +.. note:: + + System headers are not analyzed by this check. diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp index 3ec44be8a1c8c..3bcd5cd74024e 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp @@ -724,3 +724,35 @@ void not_last_param() { } } // namespace enable_if_trailing_type_parameter + + +// Issue fixes: + +namespace PR91872 { + +enum expression_template_option { value1, value2 }; + +template struct number_category { + static const int value = 0; +}; + +constexpr int number_kind_complex = 1; + +template +struct number { + using type = T; +}; + +template struct component_type { + using type = T; +}; + +template +inline typename std::enable_if< +number_category::value == number_kind_complex, +component_type>>::type::type +abs(const number ) { + return {}; +} + +} `` https://github.com/llvm/llvm-project/pull/92019 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-constraints (PR #92019)
https://github.com/PiotrZSL created https://github.com/llvm/llvm-project/pull/92019 Improved modernize-use-constraints check by fixing a crash that occurred in some scenarios and excluded system headers from analysis. Problem were with DependentNameTypeLoc having null type location as getQualifierLoc().getTypeLoc(). Fixes #91872 >From 5f0302b0d1c34d13b566aa6f992568005a47fac0 Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Mon, 13 May 2024 19:47:44 + Subject: [PATCH] [clang-tidy] Fix crash in modernize-use-constraints Improved modernize-use-constraints check by fixing a crash that occurred in some scenarios and excluded system headers from analysis. Problem were with DependentNameTypeLoc having null type location as getQualifierLoc().getTypeLoc(). Fixes #91872 --- .../modernize/UseConstraintsCheck.cpp | 4 +++ clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../checks/modernize/use-constraints.rst | 4 +++ .../checkers/modernize/use-constraints.cpp| 32 +++ 4 files changed, 44 insertions(+) diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp index 6d7d1d6b87c60..d9fab64050adb 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp @@ -41,6 +41,8 @@ AST_MATCHER(FunctionDecl, hasOtherDeclarations) { void UseConstraintsCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( functionTemplateDecl( + // Skip external libraries included as system headers + unless(isExpansionInSystemHeader()), has(functionDecl(unless(hasOtherDeclarations()), isDefinition(), hasReturnTypeLoc(typeLoc().bind("return"))) .bind("function"))) @@ -57,6 +59,8 @@ matchEnableIfSpecializationImplTypename(TypeLoc TheType) { return std::nullopt; } TheType = Dep.getQualifierLoc().getTypeLoc(); +if (TheType.isNull()) + return std::nullopt; } if (const auto SpecializationLoc = diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index fc976ce3a33d5..91b24f654112f 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -306,6 +306,10 @@ Changes in existing checks don't remove parentheses used in ``sizeof`` calls when they have array index accesses as arguments. +- Improved :doc:`modernize-use-constraints + ` check by fixing a crash that + occurred in some scenarios and excluded system headers from analysis. + - Improved :doc:`modernize-use-nullptr ` check to include support for C23, which also has introduced the ``nullptr`` keyword. diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst index be62dd5823d55..a8b31b80e580b 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-constraints.rst @@ -68,3 +68,7 @@ The tool will replace the above code with, // The tool will not emit a diagnostic or attempt to replace the code. template = 0> struct my_class {}; + +.. note:: + + System headers are not analyzed by this check. diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp index 3ec44be8a1c8c..3bcd5cd74024e 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp @@ -724,3 +724,35 @@ void not_last_param() { } } // namespace enable_if_trailing_type_parameter + + +// Issue fixes: + +namespace PR91872 { + +enum expression_template_option { value1, value2 }; + +template struct number_category { + static const int value = 0; +}; + +constexpr int number_kind_complex = 1; + +template +struct number { + using type = T; +}; + +template struct component_type { + using type = T; +}; + +template +inline typename std::enable_if< +number_category::value == number_kind_complex, +component_type>>::type::type +abs(const number ) { + return {}; +} + +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Ignore try-statements in dead code checker (PR #91675)
https://github.com/soukatch updated https://github.com/llvm/llvm-project/pull/91675 >From 846be0552bd2da608fc1729e5928d85650e1ce06 Mon Sep 17 00:00:00 2001 From: Andrew Sukach Date: Thu, 9 May 2024 18:49:41 -0400 Subject: [PATCH] [clang][static analyzer] ignore try statements in dead code checker --- .../Checkers/UnreachableCodeChecker.cpp | 4 +++- clang/test/Analysis/unreachable-code-exceptions.cpp | 12 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 clang/test/Analysis/unreachable-code-exceptions.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp index d24a124f5ffee..7ce9a5b5bb6dc 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp @@ -159,6 +159,8 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph , SL = DL.asLocation(); if (SR.isInvalid() || !SL.isValid()) continue; + if (isa(S)) +continue; } else continue; @@ -254,4 +256,4 @@ void ento::registerUnreachableCodeChecker(CheckerManager ) { bool ento::shouldRegisterUnreachableCodeChecker(const CheckerManager ) { return true; -} +} \ No newline at end of file diff --git a/clang/test/Analysis/unreachable-code-exceptions.cpp b/clang/test/Analysis/unreachable-code-exceptions.cpp new file mode 100644 index 0..aad7625b92d71 --- /dev/null +++ b/clang/test/Analysis/unreachable-code-exceptions.cpp @@ -0,0 +1,12 @@ +// RUN: %clang_analyze_cc1 -verify %s -fcxx-exceptions -fexceptions -analyzer-checker=core -analyzer-checker=alpha.deadcode.UnreachableCode + +// expected-no-diagnostics + +void foo(); + +void f4() { + try { +foo(); + } catch (int) { + } +} \ No newline at end of file ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)
@@ -5636,6 +5636,84 @@ void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var, Var->addDebugInfo(GVE); } +void CGDebugInfo::EmitPseudoVariable(CGBuilderTy , + llvm::Instruction *Value, QualType Ty) { + // Only when -g2 or above is specified, debug info for variables will be + // generated. + if (CGM.getCodeGenOpts().getDebugInfo() <= + llvm::codegenoptions::DebugLineTablesOnly) +return; + + llvm::DIFile *Unit = Builder.getCurrentDebugLocation()->getFile(); + llvm::DIType *Type = getOrCreateType(Ty, Unit); + + // Check if Value is already a declared variable and has debug info, in this + // case we have nothing to do. Clang emits declared variable as alloca, and + // it is loaded upon use, so we identify such pattern here. + if (llvm::LoadInst *Load = dyn_cast(Value)) { +llvm::Value *Var = Load->getPointerOperand(); +if (llvm::Metadata *MDValue = llvm::ValueAsMetadata::getIfExists(Var)) { + if (llvm::Value *DbgValue = llvm::MetadataAsValue::getIfExists( + CGM.getLLVMContext(), MDValue)) { +for (llvm::User *U : DbgValue->users()) { + if (llvm::CallInst *DbgDeclare = dyn_cast(U)) { +if (DbgDeclare->getCalledFunction()->getIntrinsicID() == +llvm::Intrinsic::dbg_declare && +DbgDeclare->getArgOperand(0) == DbgValue) { + // There can be implicit type cast applied on a variable if it is + // an opaque ptr, in this case its debug info may not match the + // actual type of object being used as in the next instruction, so + // we will need to emit a pseudo variable for type-casted value. + llvm::DILocalVariable *MDNode = dyn_cast( + dyn_cast(DbgDeclare->getOperand(1)) + ->getMetadata()); + if (MDNode->getType() == Type) +return; +} + } +} + } +} + } + + // Find the correct location to insert a sequence of instructions to + // materialize Value on the stack. + auto SaveInsertionPoint = Builder.saveIP(); + if (llvm::InvokeInst *Invoke = dyn_cast(Value)) +Builder.SetInsertPoint(Invoke->getNormalDest()->begin()); + else if (llvm::Instruction *Next = Value->getIterator()->getNextNode()) +Builder.SetInsertPoint(Next); + else +Builder.SetInsertPoint(Value->getParent()); + auto SaveDebugLoc = Builder.getCurrentDebugLocation(); + llvm::DebugLoc DL = Value->getDebugLoc(); + if (DL.get()) +Builder.SetCurrentDebugLocation(DL); + + llvm::AllocaInst *PseudoVar = Builder.CreateAlloca(Value->getType()); + Address PseudoVarAddr(PseudoVar, Value->getType(), +CharUnits::fromQuantity(PseudoVar->getAlign())); + llvm::LoadInst *Load = Builder.CreateLoad(PseudoVarAddr); + Value->replaceAllUsesWith(Load); + Builder.SetInsertPoint(Load); + Builder.CreateStore(Value, PseudoVarAddr); + + // Emit debug info for materialized Value. + unsigned Line = Builder.getCurrentDebugLocation().getLine(); huangjd wrote: Updated https://github.com/llvm/llvm-project/pull/81545 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)
https://github.com/huangjd updated https://github.com/llvm/llvm-project/pull/81545 >From f2c82758e1cba7773e41d941d2812c829c339675 Mon Sep 17 00:00:00 2001 From: William Huang Date: Mon, 12 Feb 2024 02:27:13 -0500 Subject: [PATCH 01/13] Add option to generate additional info for expression containing pointer of pointers. Such expression does correspond to a variable in the source code thus does not have a debug location. However the user may want to collect sampling counter for memory accesses to analyze usage frequency of class members. By enabling -fdebug_info_for_pointer_type a psuedo variable and its debug info is generated in place whenever there's an intermediate expression with pointer access. --- clang/include/clang/Basic/DebugOptions.def | 4 ++ clang/include/clang/Driver/Options.td | 4 ++ clang/lib/CodeGen/CGDebugInfo.cpp | 16 + clang/lib/CodeGen/CGDebugInfo.h| 6 ++ clang/lib/CodeGen/CGDecl.cpp | 4 ++ clang/lib/CodeGen/CGExpr.cpp | 79 ++ clang/lib/CodeGen/CodeGenFunction.h| 5 ++ clang/lib/Driver/ToolChains/Clang.cpp | 3 + 8 files changed, 121 insertions(+) diff --git a/clang/include/clang/Basic/DebugOptions.def b/clang/include/clang/Basic/DebugOptions.def index 7cd3edf08a17e..6dd09f4684207 100644 --- a/clang/include/clang/Basic/DebugOptions.def +++ b/clang/include/clang/Basic/DebugOptions.def @@ -129,6 +129,10 @@ DEBUGOPT(CodeViewCommandLine, 1, 0) /// Whether emit extra debug info for sample pgo profile collection. DEBUGOPT(DebugInfoForProfiling, 1, 0) +/// Whether to generate pseudo variables and their debug info for intermediate +/// pointer accesses. +DEBUGOPT(DebugInfoForPointerType, 1, 0) + /// Whether to emit .debug_gnu_pubnames section instead of .debug_pubnames. DEBUGOPT(DebugNameTable, 2, 0) diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 7f4fa33748fac..96b22d3f7640d 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -1675,6 +1675,10 @@ defm debug_info_for_profiling : BoolFOption<"debug-info-for-profiling", PosFlag, NegFlag>; +def fdebug_info_for_pointer_type : Flag<["-"], "fdebug-info-for-pointer-type">, + Group, Visibility<[ClangOption, CC1Option]>, + HelpText<"Generate pseudo variables and their debug info for intermediate pointer accesses">, + MarshallingInfoFlag>; def fprofile_instr_generate : Flag<["-"], "fprofile-instr-generate">, Group, Visibility<[ClangOption, CLOption]>, HelpText<"Generate instrumented code to collect execution counts into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var)">; diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 0f3f684d61dc9..6ce40da22dc97 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -5636,6 +5636,22 @@ void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var, Var->addDebugInfo(GVE); } +void CGDebugInfo::EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty, + SourceLocation Loc) { + llvm::DIFile *Unit = getOrCreateFile(Loc); + unsigned Line = getLineNumber(Loc); + unsigned Column = getColumnNumber(Loc); + llvm::DILocalVariable *D = DBuilder.createAutoVariable( + LexicalBlockStack.back(), Alloca->getName(), getOrCreateFile(Loc), Line, + getOrCreateType(Ty, Unit)); + llvm::DILocation *DIL = + llvm::DILocation::get(CGM.getLLVMContext(), Line, Column, +LexicalBlockStack.back(), CurInlinedAt); + SmallVector Expr; + DBuilder.insertDeclare(Alloca, D, DBuilder.createExpression(Expr), DIL, + Alloca->getParent()); +} + void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl GD) { diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h index 7b60e94555d06..a2c484f50b2bc 100644 --- a/clang/lib/CodeGen/CGDebugInfo.h +++ b/clang/lib/CodeGen/CGDebugInfo.h @@ -529,6 +529,12 @@ class CGDebugInfo { /// Emit information about an external variable. void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl); + /// Emit debug information for a pseudo variable assigned to the value of an + /// intermediate expression, so that a performance counter can track the usage + /// of a specific expression of interest. + void EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty, + SourceLocation Loc); + /// Emit information about global variable alias. void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl); diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp index bbe14ef4c1724..5f7b252917900 100644 --- a/clang/lib/CodeGen/CGDecl.cpp +++ b/clang/lib/CodeGen/CGDecl.cpp @@ -793,6 +793,10 @@ void
[clang] [clang] Introduce `SemaObjC` (PR #89086)
https://github.com/Endilll closed https://github.com/llvm/llvm-project/pull/89086 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add support for builtin_verbose_trap (PR #79230)
@@ -3424,6 +3445,26 @@ llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, return DBuilder.createTempMacroFile(Parent, Line, FName); } +llvm::DILocation *CGDebugInfo::CreateTrapFailureMessageFor( dwblaikie wrote: Eh, I'm not too fussed about the separator for the prefix (we control that) and category (will the category be user-visible? Like a warning group? Or is that only still an implementation detail/contract between DWARF producer and DWARF consumer? I thought it was more the latter/implementation detail? In which case we can say what characters are valid there, and I'd keep it pretty simple, like the warning group names - all lower, dash or underscore separated seems fine) https://github.com/llvm/llvm-project/pull/79230 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add support for builtin_verbose_trap (PR #79230)
dwblaikie wrote: Hmm, do other builtins actually end up as symbol names? I think most of them lower to an instruction or two - I guess this one doesn't lower to an actual symbol, only a DWARF symbol - but maybe that's still different enough it should use an llvm or clang in the name... (sorry, I think I saw this was discussed somewhere on the review, but I can't find where now... :/) I guess it came up here: https://github.com/llvm/llvm-project/pull/79230#discussion_r1591335258 and at the time it still had `llvm` in it, wasn't clear conversation that showed how the alternative conclusion was reached. https://github.com/llvm/llvm-project/pull/79230 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL][CMake] Add clangd and distribution settings (PR #92011)
https://github.com/bob80905 approved this pull request. https://github.com/llvm/llvm-project/pull/92011 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL][CMake] Add clangd and distribution settings (PR #92011)
https://github.com/llvm-beanz updated https://github.com/llvm/llvm-project/pull/92011 >From e1b82c5bb1869ac74080e17633bd8ac7931a47b6 Mon Sep 17 00:00:00 2001 From: Chris B Date: Mon, 13 May 2024 13:55:49 -0500 Subject: [PATCH 1/2] [HLSL][CMake] Add clangd and distribution settings This just adds some simple distribution settings and includes clangd in the build for distribution. --- clang/cmake/caches/HLSL.cmake | 6 +- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake index 84850c86f12cd..9aa28625ab81e 100644 --- a/clang/cmake/caches/HLSL.cmake +++ b/clang/cmake/caches/HLSL.cmake @@ -8,6 +8,10 @@ set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD "DirectX;SPIRV" CACHE STRING "") # HLSL support is currently limted to clang, eventually it will expand to # clang-tools-extra too. -set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "") +set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "") set(CLANG_ENABLE_HLSL On CACHE BOOL "") + +set(LLVM_DISTRIBUTION_COMPONENTS +"clang;hlsl-resource-headers;clangd" +CACHE STRING "") >From b0f54990e3a5b9bb56c573d13af748b51e3c6115 Mon Sep 17 00:00:00 2001 From: Chris B Date: Mon, 13 May 2024 14:00:42 -0500 Subject: [PATCH 2/2] Don't setup distribuiton on multi-config generators --- clang/cmake/caches/HLSL.cmake | 8 +--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake index 9aa28625ab81e..27f848fdccf0c 100644 --- a/clang/cmake/caches/HLSL.cmake +++ b/clang/cmake/caches/HLSL.cmake @@ -12,6 +12,8 @@ set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "") set(CLANG_ENABLE_HLSL On CACHE BOOL "") -set(LLVM_DISTRIBUTION_COMPONENTS -"clang;hlsl-resource-headers;clangd" -CACHE STRING "") +if (NOT CMAKE_CONFIGURATION_TYPES) + set(LLVM_DISTRIBUTION_COMPONENTS + "clang;hlsl-resource-headers;clangd" + CACHE STRING "") +endif() ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL][CMake] Add clangd and distribution settings (PR #92011)
llvmbot wrote: @llvm/pr-subscribers-hlsl Author: Chris B (llvm-beanz) Changes This just adds some simple distribution settings and includes clangd in the build for distribution. --- Full diff: https://github.com/llvm/llvm-project/pull/92011.diff 1 Files Affected: - (modified) clang/cmake/caches/HLSL.cmake (+5-1) ``diff diff --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake index 84850c86f12cd..9aa28625ab81e 100644 --- a/clang/cmake/caches/HLSL.cmake +++ b/clang/cmake/caches/HLSL.cmake @@ -8,6 +8,10 @@ set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD "DirectX;SPIRV" CACHE STRING "") # HLSL support is currently limted to clang, eventually it will expand to # clang-tools-extra too. -set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "") +set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "") set(CLANG_ENABLE_HLSL On CACHE BOOL "") + +set(LLVM_DISTRIBUTION_COMPONENTS +"clang;hlsl-resource-headers;clangd" +CACHE STRING "") `` https://github.com/llvm/llvm-project/pull/92011 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL][CMake] Add clangd and distribution settings (PR #92011)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Chris B (llvm-beanz) Changes This just adds some simple distribution settings and includes clangd in the build for distribution. --- Full diff: https://github.com/llvm/llvm-project/pull/92011.diff 1 Files Affected: - (modified) clang/cmake/caches/HLSL.cmake (+5-1) ``diff diff --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake index 84850c86f12cd..9aa28625ab81e 100644 --- a/clang/cmake/caches/HLSL.cmake +++ b/clang/cmake/caches/HLSL.cmake @@ -8,6 +8,10 @@ set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD "DirectX;SPIRV" CACHE STRING "") # HLSL support is currently limted to clang, eventually it will expand to # clang-tools-extra too. -set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "") +set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "") set(CLANG_ENABLE_HLSL On CACHE BOOL "") + +set(LLVM_DISTRIBUTION_COMPONENTS +"clang;hlsl-resource-headers;clangd" +CACHE STRING "") `` https://github.com/llvm/llvm-project/pull/92011 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL][CMake] Add clangd and distribution settings (PR #92011)
https://github.com/llvm-beanz created https://github.com/llvm/llvm-project/pull/92011 This just adds some simple distribution settings and includes clangd in the build for distribution. >From e1b82c5bb1869ac74080e17633bd8ac7931a47b6 Mon Sep 17 00:00:00 2001 From: Chris B Date: Mon, 13 May 2024 13:55:49 -0500 Subject: [PATCH] [HLSL][CMake] Add clangd and distribution settings This just adds some simple distribution settings and includes clangd in the build for distribution. --- clang/cmake/caches/HLSL.cmake | 6 +- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake index 84850c86f12cd..9aa28625ab81e 100644 --- a/clang/cmake/caches/HLSL.cmake +++ b/clang/cmake/caches/HLSL.cmake @@ -8,6 +8,10 @@ set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD "DirectX;SPIRV" CACHE STRING "") # HLSL support is currently limted to clang, eventually it will expand to # clang-tools-extra too. -set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "") +set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "") set(CLANG_ENABLE_HLSL On CACHE BOOL "") + +set(LLVM_DISTRIBUTION_COMPONENTS +"clang;hlsl-resource-headers;clangd" +CACHE STRING "") ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Respect the [[clang::unsafe_buffer_usage]] attribute for field and constructor initializers (PR #91991)
https://github.com/danakj updated https://github.com/llvm/llvm-project/pull/91991 >From 8b318dadac6d0ec53b5d26461edfe19a391845ec Mon Sep 17 00:00:00 2001 From: danakj Date: Fri, 10 May 2024 13:31:17 -0400 Subject: [PATCH 1/3] Respect the [[clang::unsafe_buffer_usage]] attribute for constructors The -Wunsafe-buffer-usage warning should fire on any call to a function annotated with [[clang::unsafe_buffer_usage]], however it omitted calls to constructors, since the expression is a CXXConstructExpr which does not subclass CallExpr. Thus the matcher on callExpr() does not find these expressions. Add a new WarningGadget that matches cxxConstructExpr that are calling a CXXConstructDecl annotated by [[clang::unsafe_buffer_usage]] and fires the warning. The new UnsafeBufferUsageCtorAttrGadget gadget explicitly avoids matching against the std::span(ptr, size) constructor because that is handled by SpanTwoParamConstructorGadget and we never want two gadgets to match the same thing (and this is guarded by asserts). The gadgets themselves do not report the warnings, instead each gadget's Stmt is passed to the UnsafeBufferUsageHandler (implemented by UnsafeBufferUsageReporter). The Reporter is previously hardcoded that a CXXConstructExpr statement must be a match for std::span(ptr, size), but that is no longer the case. We want the Reporter to generate different warnings (in the -Wunsafe-buffer-usage-in-container subgroup) for the span contructor. And we will want it to report more warnings for other std-container-specific gadgets in the future. To handle this we allow the gadget to control if the warning is general (it calls handleUnsafeBufferUsage()) or is a std-container-specific warning (it calls handleUnsafeOperationInContainer()). Then the WarningGadget grows a virtual method to dispatch to the appropriate path in the UnsafeBufferUsageHandler. By doing so, we no longer need getBaseStmt in the Gadget interface. The only use of it for FixableGadgets was to get the SourceLocation, so we make an explicit virtual method for that on Gadget. Then the handleUnsafeOperation() dispatcher can be a virtual method that is only in WarningGadget. The SpanTwoParamConstructorGadget gadget dispatches to handleUnsafeOperationInContainer() while the other WarningGadgets all dispatch to the original handleUnsafeBufferUsage(). Tests are added for annotated constructors, conversion operattors, call operators, fold expressions, and regular methods. --- .../Analysis/Analyses/UnsafeBufferUsage.h | 5 + .../Analyses/UnsafeBufferUsageGadgets.def | 1 + clang/lib/Analysis/UnsafeBufferUsage.cpp | 167 -- clang/lib/Sema/AnalysisBasedWarnings.cpp | 22 ++- ...warn-unsafe-buffer-usage-function-attr.cpp | 38 5 files changed, 176 insertions(+), 57 deletions(-) diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h index 5d16dcc824c50..228b4ae1e3e11 100644 --- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h +++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h @@ -106,6 +106,11 @@ class UnsafeBufferUsageHandler { virtual void handleUnsafeOperation(const Stmt *Operation, bool IsRelatedToDecl, ASTContext ) = 0; + /// Invoked when an unsafe operation with a std container is found. + virtual void handleUnsafeOperationInContainer(const Stmt *Operation, +bool IsRelatedToDecl, +ASTContext ) = 0; + /// Invoked when a fix is suggested against a variable. This function groups /// all variables that must be fixed together (i.e their types must be changed /// to the same target type to prevent type mismatches) into a single fixit. diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def index 3273c642eed51..242ad763ba62b 100644 --- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def +++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def @@ -36,6 +36,7 @@ WARNING_GADGET(Decrement) WARNING_GADGET(ArraySubscript) WARNING_GADGET(PointerArithmetic) WARNING_GADGET(UnsafeBufferUsageAttr) +WARNING_GADGET(UnsafeBufferUsageCtorAttr) WARNING_GADGET(DataInvocation) WARNING_CONTAINER_GADGET(SpanTwoParamConstructor) // Uses of `std::span(arg0, arg1)` FIXABLE_GADGET(ULCArraySubscript) // `DRE[any]` in an Unspecified Lvalue Context diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp index c42e70d5b95ac..b24588e722aaa 100644 --- a/clang/lib/Analysis/UnsafeBufferUsage.cpp +++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp @@ -492,7 +492,7 @@ class Gadget { #endif virtual bool isWarningGadget() const = 0; - virtual const Stmt *getBaseStmt() const = 0; + virtual SourceLocation
[clang-tools-extra] [clang-tidy] Add AllowImplicitlyDeletedCopyOrMove option to cppcoreguidelines-special-member-functions (PR #71683)
PiotrZSL wrote: Bump. https://github.com/llvm/llvm-project/pull/71683 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
https://github.com/PiotrZSL closed https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] af79372 - [clang-tidy] Add modernize-use-std-format check (#90397)
Author: Mike Crowe Date: 2024-05-13T20:42:44+02:00 New Revision: af79372d6349cfba6beff26d54b7ad1b798fc4d5 URL: https://github.com/llvm/llvm-project/commit/af79372d6349cfba6beff26d54b7ad1b798fc4d5 DIFF: https://github.com/llvm/llvm-project/commit/af79372d6349cfba6beff26d54b7ad1b798fc4d5.diff LOG: [clang-tidy] Add modernize-use-std-format check (#90397) Add a new clang-tidy check that converts absl::StrFormat (and similar functions) to std::format (and similar functions.) Split the configuration of FormatStringConverter out to a separate Configuration class so that we don't risk confusion by passing two boolean configuration parameters into the constructor. Add AllowTrailingNewlineRemoval option since we never want to remove trailing newlines in this check. Added: clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.h clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-custom.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-fmt.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format.cpp Modified: clang-tools-extra/clang-tidy/modernize/CMakeLists.txt clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp clang-tools-extra/clang-tidy/utils/FormatStringConverter.h clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/docs/clang-tidy/checks/list.rst Removed: diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index 8005d6e91c060..576805c4c7f18 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -41,6 +41,7 @@ add_clang_library(clangTidyModernizeModule UseNullptrCheck.cpp UseOverrideCheck.cpp UseStartsEndsWithCheck.cpp + UseStdFormatCheck.cpp UseStdNumbersCheck.cpp UseStdPrintCheck.cpp UseTrailingReturnTypeCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp index 776558433c5ba..b9c7a2dc383e8 100644 --- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp @@ -42,6 +42,7 @@ #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" #include "UseStartsEndsWithCheck.h" +#include "UseStdFormatCheck.h" #include "UseStdNumbersCheck.h" #include "UseStdPrintCheck.h" #include "UseTrailingReturnTypeCheck.h" @@ -76,6 +77,7 @@ class ModernizeModule : public ClangTidyModule { "modernize-use-designated-initializers"); CheckFactories.registerCheck( "modernize-use-starts-ends-with"); + CheckFactories.registerCheck("modernize-use-std-format"); CheckFactories.registerCheck( "modernize-use-std-numbers"); CheckFactories.registerCheck("modernize-use-std-print"); diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp new file mode 100644 index 0..6cef21f1318a2 --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp @@ -0,0 +1,107 @@ +//===--- UseStdFormatCheck.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 "UseStdFormatCheck.h" +#include "../utils/FormatStringConverter.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { +AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); } +} // namespace + +UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StrictMode(Options.getLocalOrGlobal("StrictMode", false)), + StrFormatLikeFunctions(utils::options::parseStringList( + Options.get("StrFormatLikeFunctions", ""))), + ReplacementFormatFunction( + Options.get("ReplacementFormatFunction", "std::format")), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), +
[clang-tools-extra] [clang-tidy] Ignore unevaluated context in bugprone-optional-value-conversion (PR #90410)
https://github.com/PiotrZSL closed https://github.com/llvm/llvm-project/pull/90410 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 6993798 - [clang-tidy] Ignore unevaluated context in bugprone-optional-value-conversion (#90410)
Author: Piotr Zegar Date: 2024-05-13T20:41:42+02:00 New Revision: 69937982dbdd73172ec06580f6f93616edca8e9e URL: https://github.com/llvm/llvm-project/commit/69937982dbdd73172ec06580f6f93616edca8e9e DIFF: https://github.com/llvm/llvm-project/commit/69937982dbdd73172ec06580f6f93616edca8e9e.diff LOG: [clang-tidy] Ignore unevaluated context in bugprone-optional-value-conversion (#90410) Ignore optionals in unevaluated context, like static_assert or decltype. Closes #89593 Added: Modified: clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp index 9ab59e6b0474f..600eab3755276 100644 --- a/clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp @@ -71,7 +71,9 @@ void OptionalValueConversionCheck::registerMatchers(MatchFinder *Finder) { ofClass(matchers::matchesAnyListedName(OptionalTypes, hasType(ConstructTypeMatcher), hasArgument(0U, ignoringImpCasts(anyOf(OptionalDereferenceMatcher, - StdMoveCallMatcher + StdMoveCallMatcher))), + unless(anyOf(hasAncestor(typeLoc()), + hasAncestor(expr(matchers::hasUnevaluatedContext()) .bind("expr"), this); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 8183d394cf425..8c76f5f60ee3e 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -204,6 +204,10 @@ Changes in existing checks eliminating false positives resulting from direct usage of bitwise operators within parentheses. +- Improved :doc:`bugprone-optional-value-conversion + ` check by eliminating + false positives resulting from use of optionals in unevaluated context. + - Improved :doc:`bugprone-suspicious-include ` check by replacing the local options `HeaderFileExtensions` and `ImplementationFileExtensions` by the diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp index 72ef35c956d2e..1228d64bb6909 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp @@ -210,4 +210,6 @@ void correct(std::optional param) std::optional* p2 = takeOptionalValue(p2->value_or(5U)); takeOptionalRef(p2->value_or(5U)); + + using Type = decltype(takeOptionalValue(*param)); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,78 @@ +//===--- UseInternalLinkageCheck.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 "UseInternalLinkageCheck.h" +#include "../utils/FileExtensionsUtils.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/STLExtras.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::misc { + +namespace { + +AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); } + +AST_MATCHER_P(Decl, isInMainFile, FileExtensionsSet, HeaderFileExtensions) { + return llvm::all_of(Node.redecls(), [&](const Decl *D) { +SourceManager = Finder->getASTContext().getSourceManager(); +const SourceLocation L = D->getLocation(); +return SM.isInMainFile(L) && + !utils::isSpellingLocInHeaderFile(L, SM, HeaderFileExtensions); + }); PiotrZSL wrote: should be: ``` #source files or main file if its not a header. return utils::isSpellingLocInFile(L, SM, SourceFileExtensions) || (SM.isInMainFile(L) && !utils::isSpellingLocInFile(L, SM, HeaderFileExtensions)); ``` isSpellingLocInHeaderFile should be renamed into isSpellingLocInFile, that "Header" is not needed in those functions. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,78 @@ +//===--- UseInternalLinkageCheck.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 "UseInternalLinkageCheck.h" +#include "../utils/FileExtensionsUtils.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/STLExtras.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::misc { + +namespace { + +AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); } + +AST_MATCHER_P(Decl, isInMainFile, FileExtensionsSet, HeaderFileExtensions) { + return llvm::all_of(Node.redecls(), [&](const Decl *D) { +SourceManager = Finder->getASTContext().getSourceManager(); +const SourceLocation L = D->getLocation(); +return SM.isInMainFile(L) && + !utils::isSpellingLocInHeaderFile(L, SM, HeaderFileExtensions); + }); +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.getStorageClass() == SC_Extern; +} + +} // namespace + +void UseInternalLinkageCheck::registerMatchers(MatchFinder *Finder) { + auto Common = allOf(isFirstDecl(), isInMainFile(HeaderFileExtensions), PiotrZSL wrote: isFirstDecl wont work if someone do: ``` void foo() { } #include "foo.h" ``` but thats, fine, just would be good if documentation mention that it checks first declaration https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/PiotrZSL commented: Few nits. Missing: - more proper handling for unity files (.cpp included from .cpp) - nits - auto-fixes (any) - in worst case you can provide just fixes with static, but attaching them to notes. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/PiotrZSL edited https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
PiotrZSL wrote: > > * The auto-fix should be configurable to choose `static` or anonymous > > namespace. > > Should I implement auto-fix for this check? Maybe some functions / variables > will be marked incorrectly and cause link error because the coder just forget > to include the header file but this check mark it as internal linkage. WDYT? > @carlosgalvezp @PiotrZSL @EugeneZelenko @SimplyDanny YES. I used such check on a project that I work for. In short it found over an 1000 issues, manually fixing them was not an option. I had an quick fix with adding `static`, and that worked fine, in some places code didn't compile so had to fix those by my self, but that was fine. Add an option for "static / anonymous namespace", and generate fixes/hints accordingly. You can use optional values, or enums and by default suggest one or other, and in such state you may not need to provide fixes. In other config state just provide fixes, even if that would mean wrapping every function in separate anonymous namespace or adding static. There allways can be other check or some clang-format option to merge multiple namespaces. Do not reorder functions, and one can use other. Also static is safer as it's does not change scope, with namespace user may run into issues, but still fixes are needed. You can always mention in documentation that fixes are not perfect and manual intervention may be required. Even if check will do 80% of job, thats already huge help. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)
https://github.com/klensy edited https://github.com/llvm/llvm-project/pull/91854 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
https://github.com/justincady updated https://github.com/llvm/llvm-project/pull/91400 >From 58d3d52c666bdaa3534cd16080bb895d49f61008 Mon Sep 17 00:00:00 2001 From: Justin Cady Date: Tue, 7 May 2024 16:54:35 -0400 Subject: [PATCH] Add option to exclude headers from clang-tidy analysis This is a renewed attempt to land @toddlipcon's D34654. The comments on that patch indicate a broad desire for some ability to ignore headers. After considering various options, including migrating to std::regex, I believe this is the best path forward. It's intuitive to have separate regexes for including headers versus excluding them, and this approach has the added benefit of being completely opt-in. No existing configs will break, regardless of existing HeaderFilterRegex values. This functionality is useful for improving performance when analyzing a targeted subset of code, as well as in cases where some collection of headers cannot be modified (third party source, for example). --- .../ClangTidyDiagnosticConsumer.cpp | 28 ++- .../clang-tidy/ClangTidyDiagnosticConsumer.h | 1 + .../clang-tidy/ClangTidyOptions.cpp | 6 +- .../clang-tidy/ClangTidyOptions.h | 4 + .../clang-tidy/tool/ClangTidyMain.cpp | 18 ++ .../clang-tidy/tool/run-clang-tidy.py | 13 + clang-tools-extra/docs/ReleaseNotes.rst | 3 + clang-tools-extra/docs/clang-tidy/index.rst | 235 +- .../Inputs/config-files/.clang-tidy | 1 + .../Inputs/config-files/1/.clang-tidy | 1 + .../Inputs/config-files/3/.clang-tidy | 1 + .../infrastructure/config-files.cpp | 15 +- .../clang-tidy/infrastructure/file-filter.cpp | 7 + 13 files changed, 207 insertions(+), 126 deletions(-) diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index de2a3b51422a5..200bb87a5ac3c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -311,7 +311,18 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer( : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine), RemoveIncompatibleErrors(RemoveIncompatibleErrors), GetFixesFromNotes(GetFixesFromNotes), - EnableNolintBlocks(EnableNolintBlocks) {} + EnableNolintBlocks(EnableNolintBlocks) { + + if (Context.getOptions().HeaderFilterRegex && + !Context.getOptions().HeaderFilterRegex->empty()) +HeaderFilter = +std::make_unique(*Context.getOptions().HeaderFilterRegex); + + if (Context.getOptions().ExcludeHeaderFilterRegex && + !Context.getOptions().ExcludeHeaderFilterRegex->empty()) +ExcludeHeaderFilter = std::make_unique( +*Context.getOptions().ExcludeHeaderFilterRegex); +} void ClangTidyDiagnosticConsumer::finalizeLastError() { if (!Errors.empty()) { @@ -562,22 +573,17 @@ void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location, } StringRef FileName(File->getName()); - LastErrorRelatesToUserCode = LastErrorRelatesToUserCode || - Sources.isInMainFile(Location) || - getHeaderFilter()->match(FileName); + LastErrorRelatesToUserCode = + LastErrorRelatesToUserCode || Sources.isInMainFile(Location) || + (HeaderFilter && + (HeaderFilter->match(FileName) && +!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName; unsigned LineNumber = Sources.getExpansionLineNumber(Location); LastErrorPassesLineFilter = LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber); } -llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() { - if (!HeaderFilter) -HeaderFilter = -std::make_unique(*Context.getOptions().HeaderFilterRegex); - return HeaderFilter.get(); -} - void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() { // Each error is modelled as the set of intervals in which it applies // replacements. To detect overlapping replacements, we use a sweep line diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index 9280eb1e1f218..97e16a12febd0 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -313,6 +313,7 @@ class ClangTidyDiagnosticConsumer : public DiagnosticConsumer { bool EnableNolintBlocks; std::vector Errors; std::unique_ptr HeaderFilter; + std::unique_ptr ExcludeHeaderFilter; bool LastErrorRelatesToUserCode = false; bool LastErrorPassesLineFilter = false; bool LastErrorWasIgnored = false; diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index cbf21a0e2ae34..445c7f85c900c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++
[clang] [Coverage] Handle array decomposition correctly (PR #88881)
bolshakov-a wrote: This looks like supporting my words: https://github.com/llvm/llvm-project/blob/llvmorg-19-init/clang/lib/CodeGen/CodeGenPGO.cpp#L935-L936 https://github.com/llvm/llvm-project/pull/1 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
https://github.com/justincady updated https://github.com/llvm/llvm-project/pull/91400 >From e65bd48ef896f3327a1397a1b2f6f0a34e3711d2 Mon Sep 17 00:00:00 2001 From: Justin Cady Date: Tue, 7 May 2024 16:54:35 -0400 Subject: [PATCH 1/3] Add option to exclude headers from clang-tidy analysis This is a renewed attempt to land @toddlipcon's D34654. The comments on that patch indicate a broad desire for some ability to ignore headers. After considering various options, including migrating to std::regex, I believe this is the best path forward. It's intuitive to have separate regexes for including headers versus excluding them, and this approach has the added benefit of being completely opt-in. No existing configs will break, regardless of existing HeaderFilterRegex values. This functionality is useful for improving performance when analyzing a targeted subset of code, as well as in cases where some collection of headers cannot be modified (third party source, for example). --- .../ClangTidyDiagnosticConsumer.cpp | 28 ++- .../clang-tidy/ClangTidyDiagnosticConsumer.h | 1 + .../clang-tidy/ClangTidyOptions.cpp | 6 +- .../clang-tidy/ClangTidyOptions.h | 4 + .../clang-tidy/tool/ClangTidyMain.cpp | 18 ++ .../clang-tidy/tool/run-clang-tidy.py | 13 + clang-tools-extra/docs/ReleaseNotes.rst | 2 + clang-tools-extra/docs/clang-tidy/index.rst | 235 +- .../Inputs/config-files/.clang-tidy | 1 + .../Inputs/config-files/1/.clang-tidy | 1 + .../Inputs/config-files/3/.clang-tidy | 1 + .../infrastructure/config-files.cpp | 15 +- .../clang-tidy/infrastructure/file-filter.cpp | 7 + 13 files changed, 206 insertions(+), 126 deletions(-) diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index de2a3b51422a5..200bb87a5ac3c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -311,7 +311,18 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer( : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine), RemoveIncompatibleErrors(RemoveIncompatibleErrors), GetFixesFromNotes(GetFixesFromNotes), - EnableNolintBlocks(EnableNolintBlocks) {} + EnableNolintBlocks(EnableNolintBlocks) { + + if (Context.getOptions().HeaderFilterRegex && + !Context.getOptions().HeaderFilterRegex->empty()) +HeaderFilter = +std::make_unique(*Context.getOptions().HeaderFilterRegex); + + if (Context.getOptions().ExcludeHeaderFilterRegex && + !Context.getOptions().ExcludeHeaderFilterRegex->empty()) +ExcludeHeaderFilter = std::make_unique( +*Context.getOptions().ExcludeHeaderFilterRegex); +} void ClangTidyDiagnosticConsumer::finalizeLastError() { if (!Errors.empty()) { @@ -562,22 +573,17 @@ void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location, } StringRef FileName(File->getName()); - LastErrorRelatesToUserCode = LastErrorRelatesToUserCode || - Sources.isInMainFile(Location) || - getHeaderFilter()->match(FileName); + LastErrorRelatesToUserCode = + LastErrorRelatesToUserCode || Sources.isInMainFile(Location) || + (HeaderFilter && + (HeaderFilter->match(FileName) && +!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName; unsigned LineNumber = Sources.getExpansionLineNumber(Location); LastErrorPassesLineFilter = LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber); } -llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() { - if (!HeaderFilter) -HeaderFilter = -std::make_unique(*Context.getOptions().HeaderFilterRegex); - return HeaderFilter.get(); -} - void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() { // Each error is modelled as the set of intervals in which it applies // replacements. To detect overlapping replacements, we use a sweep line diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index 9280eb1e1f218..97e16a12febd0 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -313,6 +313,7 @@ class ClangTidyDiagnosticConsumer : public DiagnosticConsumer { bool EnableNolintBlocks; std::vector Errors; std::unique_ptr HeaderFilter; + std::unique_ptr ExcludeHeaderFilter; bool LastErrorRelatesToUserCode = false; bool LastErrorPassesLineFilter = false; bool LastErrorWasIgnored = false; diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index cbf21a0e2ae34..445c7f85c900c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
@@ -42,6 +47,14 @@ CreateFrontendBaseAction(CompilerInstance ) { StringRef Action("unknown"); (void)Action; + auto UseCIR = CI.getFrontendOpts().UseClangIRPipeline; bcardosolopes wrote: Right, it's a different discussion than naming. @joker-eph: what's the `auto` policy for MLIR, is it different from LLVM/Clang? I'm also having trouble to find the previous discussions, let me search a bit more. https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
https://github.com/justincady updated https://github.com/llvm/llvm-project/pull/91400 >From e65bd48ef896f3327a1397a1b2f6f0a34e3711d2 Mon Sep 17 00:00:00 2001 From: Justin Cady Date: Tue, 7 May 2024 16:54:35 -0400 Subject: [PATCH 1/2] Add option to exclude headers from clang-tidy analysis This is a renewed attempt to land @toddlipcon's D34654. The comments on that patch indicate a broad desire for some ability to ignore headers. After considering various options, including migrating to std::regex, I believe this is the best path forward. It's intuitive to have separate regexes for including headers versus excluding them, and this approach has the added benefit of being completely opt-in. No existing configs will break, regardless of existing HeaderFilterRegex values. This functionality is useful for improving performance when analyzing a targeted subset of code, as well as in cases where some collection of headers cannot be modified (third party source, for example). --- .../ClangTidyDiagnosticConsumer.cpp | 28 ++- .../clang-tidy/ClangTidyDiagnosticConsumer.h | 1 + .../clang-tidy/ClangTidyOptions.cpp | 6 +- .../clang-tidy/ClangTidyOptions.h | 4 + .../clang-tidy/tool/ClangTidyMain.cpp | 18 ++ .../clang-tidy/tool/run-clang-tidy.py | 13 + clang-tools-extra/docs/ReleaseNotes.rst | 2 + clang-tools-extra/docs/clang-tidy/index.rst | 235 +- .../Inputs/config-files/.clang-tidy | 1 + .../Inputs/config-files/1/.clang-tidy | 1 + .../Inputs/config-files/3/.clang-tidy | 1 + .../infrastructure/config-files.cpp | 15 +- .../clang-tidy/infrastructure/file-filter.cpp | 7 + 13 files changed, 206 insertions(+), 126 deletions(-) diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index de2a3b51422a5..200bb87a5ac3c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -311,7 +311,18 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer( : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine), RemoveIncompatibleErrors(RemoveIncompatibleErrors), GetFixesFromNotes(GetFixesFromNotes), - EnableNolintBlocks(EnableNolintBlocks) {} + EnableNolintBlocks(EnableNolintBlocks) { + + if (Context.getOptions().HeaderFilterRegex && + !Context.getOptions().HeaderFilterRegex->empty()) +HeaderFilter = +std::make_unique(*Context.getOptions().HeaderFilterRegex); + + if (Context.getOptions().ExcludeHeaderFilterRegex && + !Context.getOptions().ExcludeHeaderFilterRegex->empty()) +ExcludeHeaderFilter = std::make_unique( +*Context.getOptions().ExcludeHeaderFilterRegex); +} void ClangTidyDiagnosticConsumer::finalizeLastError() { if (!Errors.empty()) { @@ -562,22 +573,17 @@ void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location, } StringRef FileName(File->getName()); - LastErrorRelatesToUserCode = LastErrorRelatesToUserCode || - Sources.isInMainFile(Location) || - getHeaderFilter()->match(FileName); + LastErrorRelatesToUserCode = + LastErrorRelatesToUserCode || Sources.isInMainFile(Location) || + (HeaderFilter && + (HeaderFilter->match(FileName) && +!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName; unsigned LineNumber = Sources.getExpansionLineNumber(Location); LastErrorPassesLineFilter = LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber); } -llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() { - if (!HeaderFilter) -HeaderFilter = -std::make_unique(*Context.getOptions().HeaderFilterRegex); - return HeaderFilter.get(); -} - void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() { // Each error is modelled as the set of intervals in which it applies // replacements. To detect overlapping replacements, we use a sweep line diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index 9280eb1e1f218..97e16a12febd0 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -313,6 +313,7 @@ class ClangTidyDiagnosticConsumer : public DiagnosticConsumer { bool EnableNolintBlocks; std::vector Errors; std::unique_ptr HeaderFilter; + std::unique_ptr ExcludeHeaderFilter; bool LastErrorRelatesToUserCode = false; bool LastErrorPassesLineFilter = false; bool LastErrorWasIgnored = false; diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index cbf21a0e2ae34..445c7f85c900c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
@@ -0,0 +1,61 @@ +//===--- CIRGenModule.h - Per-Module state for CIR gen --*- 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 +// +//===--===// +// +// This is the internal per-translation-unit state used for CIR translation. +// +//===--===// + +#ifndef LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H +#define LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H + +#include "CIRGenTypeCache.h" + +#include "clang/AST/ASTContext.h" +#include "clang/Basic/CodeGenOptions.h" +#include "clang/Basic/Diagnostic.h" + +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/MLIRContext.h" + +using namespace clang; +namespace cir { + +/// This class organizes the cross-function state that is used while generating +/// CIR code. +class CIRGenModule : public CIRGenTypeCache { + CIRGenModule(CIRGenModule &) = delete; + CIRGenModule =(CIRGenModule &) = delete; + +public: + CIRGenModule(mlir::MLIRContext , clang::ASTContext , + const clang::CodeGenOptions , + clang::DiagnosticsEngine ); + + ~CIRGenModule(); + +private: + /// Hold Clang AST information. + clang::ASTContext + + const clang::LangOptions bcardosolopes wrote: Agreed, we've been using a mix so we didn't had to go the extra length for something the community could ask us to change as part of upstreaming, so indeed this is the right time to make it happen. https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] support expect no diagnosis test (PR #91293)
https://github.com/PiotrZSL approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/91293 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
@@ -0,0 +1,88 @@ +//===--- CIRGenAction.cpp - LLVM Code generation Frontend Action -===// +// +// 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 "clang/CIRFrontendAction/CIRGenAction.h" +#include "clang/CIR/CIRGenerator.h" +#include "clang/Frontend/CompilerInstance.h" + +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OwningOpRef.h" + +using namespace cir; +using namespace clang; + +namespace cir { + +class CIRGenConsumer : public clang::ASTConsumer { + + virtual void anchor(); + + [[maybe_unused]] CIRGenAction::OutputType action; bcardosolopes wrote: To silence warnings for things we are about to introduce in follow up commits. Sometimes we prefetch the skeleton in NFC fashion, in order to make functionality changes have a smaller / more relevant diff. But we could surely remove them too. https://github.com/llvm/llvm-project/pull/91007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
@@ -115,6 +115,8 @@ Improvements to clang-tidy - Fixed `--verify-config` option not properly parsing checks when using the literal operator in the `.clang-tidy` config. +- Added argument `--exclude-header-filter` to exclude headers from analysis via a RegEx. PiotrZSL wrote: Mention that config option ExcludeHeaderFilterRegex is also added. ```suggestion - Added argument `--exclude-header-filter` and config option `ExcludeHeaderFilterRegex` to exclude headers from analysis via a RegEx. ``` https://github.com/llvm/llvm-project/pull/91400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
https://github.com/PiotrZSL edited https://github.com/llvm/llvm-project/pull/91400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)
https://github.com/PiotrZSL approved this pull request. LGTM, just 2 nits. https://github.com/llvm/llvm-project/pull/91400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits