[clang] [clang][bytecode] Check for global decls in destructors (PR #137525)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `openmp-s390x-linux` running on `systemz-1` while building `clang` at step 6 "test-openmp". Full details are available at: https://lab.llvm.org/buildbot/#/builders/88/builds/10975 Here is the relevant piece of the build log for the reference ``` Step 6 (test-openmp) failure: 1200 seconds without output running [b'ninja', b'-j 4', b'check-openmp'], attempting to kill ... PASS: ompd-test :: openmp_examples/example_2.c (443 of 453) PASS: ompd-test :: openmp_examples/example_task.c (444 of 453) PASS: ompd-test :: openmp_examples/example_5.c (445 of 453) PASS: ompd-test :: openmp_examples/example_4.c (446 of 453) UNSUPPORTED: ompd-test :: openmp_examples/ompd_bt.c (447 of 453) PASS: ompd-test :: openmp_examples/fibonacci.c (448 of 453) UNSUPPORTED: ompd-test :: openmp_examples/ompd_parallel.c (449 of 453) PASS: ompd-test :: openmp_examples/nested.c (450 of 453) PASS: ompd-test :: openmp_examples/parallel.c (451 of 453) PASS: ompd-test :: openmp_examples/ompd_icvs.c (452 of 453) command timed out: 1200 seconds without output running [b'ninja', b'-j 4', b'check-openmp'], attempting to kill process killed by signal 9 program finished with exit code -1 elapsedTime=1335.076336 ``` https://github.com/llvm/llvm-project/pull/137525 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 41112db - [clang][NFC] Remove old commented out code
Author: Vlad Serebrennikov Date: 2025-04-28T08:50:14+03:00 New Revision: 41112db5a5a7806b27de9b6a460894b82036b41a URL: https://github.com/llvm/llvm-project/commit/41112db5a5a7806b27de9b6a460894b82036b41a DIFF: https://github.com/llvm/llvm-project/commit/41112db5a5a7806b27de9b6a460894b82036b41a.diff LOG: [clang][NFC] Remove old commented out code `CheckedConversionKind` was converted to a scoped enum quite a while ago. Added: Modified: clang/include/clang/Sema/Sema.h Removed: diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 0c77c5b5ca30a..f75a9cdcb2a75 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -753,20 +753,6 @@ class Sema final : public SemaBase { void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D = nullptr); - // /// The kind of conversion being performed. - // enum CheckedConversionKind { - // /// An implicit conversion. - // CCK_ImplicitConversion, - // /// A C-style cast. - // CCK_CStyleCast, - // /// A functional-style cast. - // CCK_FunctionalCast, - // /// A cast other than a C-style cast. - // CCK_OtherCast, - // /// A conversion for an operand of a builtin overloaded operator. - // CCK_ForBuiltinOverloadedOp - // }; - /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] b10296e - [clang][NFC] Convert `Sema::PragmaClangSectionKind` to scoped enum
Author: Vlad Serebrennikov Date: 2025-04-28T08:57:10+03:00 New Revision: b10296eff0c26497aac01b96d57a5dffacebec67 URL: https://github.com/llvm/llvm-project/commit/b10296eff0c26497aac01b96d57a5dffacebec67 DIFF: https://github.com/llvm/llvm-project/commit/b10296eff0c26497aac01b96d57a5dffacebec67.diff LOG: [clang][NFC] Convert `Sema::PragmaClangSectionKind` to scoped enum Added: Modified: clang/include/clang/Sema/Sema.h clang/lib/Parse/ParsePragma.cpp clang/lib/Sema/SemaAttr.cpp Removed: diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f75a9cdcb2a75..11b6f5934be4f 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -463,6 +463,16 @@ enum class FunctionEffectMode : uint8_t { Dependent // effect(expr) where expr is dependent. }; +/// pragma clang section kind +enum class PragmaClangSectionKind { + Invalid = 0, + BSS = 1, + Data = 2, + Rodata = 3, + Text = 4, + Relro = 5 +}; + /// Sema - This implements semantic analysis and AST building for C. /// \nosubgrouping class Sema final : public SemaBase { @@ -1412,16 +1422,6 @@ class Sema final : public SemaBase { /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; - /// pragma clang section kind - enum PragmaClangSectionKind { -PCSK_Invalid = 0, -PCSK_BSS = 1, -PCSK_Data = 2, -PCSK_Rodata = 3, -PCSK_Text = 4, -PCSK_Relro = 5 - }; - enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index 17b2b30942582..e08364d20a4ab 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -2314,7 +2314,7 @@ void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP, Token &FirstToken) { Token Tok; - auto SecKind = Sema::PragmaClangSectionKind::PCSK_Invalid; + auto SecKind = PragmaClangSectionKind::Invalid; PP.Lex(Tok); // eat 'section' while (Tok.isNot(tok::eod)) { @@ -2325,15 +2325,15 @@ void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP, const IdentifierInfo *SecType = Tok.getIdentifierInfo(); if (SecType->isStr("bss")) - SecKind = Sema::PragmaClangSectionKind::PCSK_BSS; + SecKind = PragmaClangSectionKind::BSS; else if (SecType->isStr("data")) - SecKind = Sema::PragmaClangSectionKind::PCSK_Data; + SecKind = PragmaClangSectionKind::Data; else if (SecType->isStr("rodata")) - SecKind = Sema::PragmaClangSectionKind::PCSK_Rodata; + SecKind = PragmaClangSectionKind::Rodata; else if (SecType->isStr("relro")) - SecKind = Sema::PragmaClangSectionKind::PCSK_Relro; + SecKind = PragmaClangSectionKind::Relro; else if (SecType->isStr("text")) - SecKind = Sema::PragmaClangSectionKind::PCSK_Text; + SecKind = PragmaClangSectionKind::Text; else { PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section"; return; @@ -2342,7 +2342,7 @@ void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP, SourceLocation PragmaLocation = Tok.getLocation(); PP.Lex(Tok); // eat ['bss'|'data'|'rodata'|'text'] if (Tok.isNot(tok::equal)) { - PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << SecKind; + PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << llvm::to_underlying(SecKind); return; } diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp index 4cfe000dccf61..cdc71658e259e 100644 --- a/clang/lib/Sema/SemaAttr.cpp +++ b/clang/lib/Sema/SemaAttr.cpp @@ -393,21 +393,21 @@ void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSection *CSec; int SectionFlags = ASTContext::PSF_Read; switch (SecKind) { -case PragmaClangSectionKind::PCSK_BSS: +case PragmaClangSectionKind::BSS: CSec = &PragmaClangBSSSection; SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit; break; -case PragmaClangSectionKind::PCSK_Data: +case PragmaClangSectionKind::Data: CSec = &PragmaClangDataSection; SectionFlags |= ASTContext::PSF_Write; break; -case PragmaClangSectionKind::PCSK_Rodata: +case PragmaClangSectionKind::Rodata: CSec = &PragmaClangRodataSection; break; -case PragmaClangSectionKind::PCSK_Relro: +case PragmaClangSectionKind::Relro: CSec = &PragmaClangRelroSection; break; -case PragmaClangSectionKind::PCSK_Text: +case PragmaClangSectionKind::Text: CSec = &PragmaClangTextSection; SectionFlags |= ASTContext::PSF_Execute; break; ___ cfe-commits maili
[clang] [lldb] [clang] Add `__ptrauth_restricted_intptr` qualifier (PR #137580)
https://github.com/ojhunt updated https://github.com/llvm/llvm-project/pull/137580 >From 0129e28643f667febb23dba1521134a6151c2f7d Mon Sep 17 00:00:00 2001 From: Oliver Hunt Date: Sun, 27 Apr 2025 22:33:44 -0700 Subject: [PATCH] [clang] Add `__ptrauth_restricted_intptr` qualifier __ptrauth_restricted_intptr provides a mechanism to apply pointer authentication to pointer sized integer types. --- clang/docs/PointerAuthentication.rst | 14 ++ clang/docs/ReleaseNotes.rst | 2 +- clang/include/clang/AST/Type.h| 52 +++-- clang/include/clang/Basic/Attr.td | 3 +- .../clang/Basic/DiagnosticSemaKinds.td| 31 ++- clang/include/clang/Basic/Features.def| 1 + clang/include/clang/Basic/TokenKinds.def | 1 + clang/include/clang/Sema/Sema.h | 3 +- clang/lib/AST/ASTContext.cpp | 3 + clang/lib/AST/Type.cpp| 6 + clang/lib/AST/TypePrinter.cpp | 5 +- clang/lib/CodeGen/CGExprConstant.cpp | 4 + clang/lib/CodeGen/CGExprScalar.cpp| 2 +- clang/lib/CodeGen/CGPointerAuth.cpp | 22 +- clang/lib/Parse/ParseDecl.cpp | 9 +- clang/lib/Sema/SemaCast.cpp | 2 +- clang/lib/Sema/SemaChecking.cpp | 10 +- clang/lib/Sema/SemaDecl.cpp | 3 +- clang/lib/Sema/SemaDeclCXX.cpp| 2 +- clang/lib/Sema/SemaObjCProperty.cpp | 6 +- clang/lib/Sema/SemaType.cpp | 49 ++-- clang/lib/Sema/TreeTransform.h| 21 +- .../ptrauth-restricted-intptr-qualifier.c | 220 ++ .../ptrauth-restricted-intptr-qualifier.c | 45 clang/test/SemaCXX/ptrauth-triviality.cpp | 44 .../SymbolFile/DWARF/DWARFASTParserClang.cpp | 7 +- 26 files changed, 491 insertions(+), 76 deletions(-) create mode 100644 clang/test/CodeGen/ptrauth-restricted-intptr-qualifier.c create mode 100644 clang/test/Sema/ptrauth-restricted-intptr-qualifier.c diff --git a/clang/docs/PointerAuthentication.rst b/clang/docs/PointerAuthentication.rst index 41818d43ac687..2278971d757c9 100644 --- a/clang/docs/PointerAuthentication.rst +++ b/clang/docs/PointerAuthentication.rst @@ -326,6 +326,20 @@ a discriminator determined as follows: is ``ptrauth_blend_discriminator(&x, discriminator)``; see `ptrauth_blend_discriminator`_. +__ptrauth_restricted_intptr qualifier +^ +This is a variant of the ``__ptrauth`` qualifier, that applies to pointer sized +integers. See the documentation for ``__ptrauth qualifier``. + +This feature exists to support older APIs that use [u]intptrs to hold opaque +pointer types. + +Care must be taken to avoid using the signature bit components of the signed +integers or subsequent authentication of the signed value may fail. + +Note: When applied to a global initialiser a signed uintptr can only be +initialised with the value 0 or a global address. + ~~~ diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index eb2e8f2b8a6c0..fe9badf7ba97a 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -608,7 +608,7 @@ Arm and AArch64 Support ARM targets, however this will now disable NEON instructions being generated. The ``simd`` option is also now printed when the ``--print-supported-extensions`` option is used. -- Support for __ptrauth type qualifier has been added. +- Support for __ptrauth and __ptrauth_restricted_intptr type qualifiers has been added. - For AArch64, added support for generating executable-only code sections by using the ``-mexecute-only`` or ``-mpure-code`` compiler flags. (#GH125688) diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index 3e1fb05ad537c..246b4aeba7876 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -168,8 +168,13 @@ class PointerAuthQualifier { AuthenticatesNullValuesBits = 1, AuthenticatesNullValuesMask = ((1 << AuthenticatesNullValuesBits) - 1) << AuthenticatesNullValuesShift, -KeyShift = AuthenticatesNullValuesShift + AuthenticatesNullValuesBits, -KeyBits = 10, +RestrictedIntegralShift = +AuthenticatesNullValuesShift + AuthenticatesNullValuesBits, +RestrictedIntegralBits = 1, +RestrictedIntegralMask = ((1 << RestrictedIntegralBits) - 1) + << RestrictedIntegralShift, +KeyShift = RestrictedIntegralShift + RestrictedIntegralBits, +KeyBits = 9, KeyMask = ((1 << KeyBits) - 1) << KeyShift, DiscriminatorShift = KeyShift + KeyBits, DiscriminatorBits = 16, @@ -178,32 +183,33 @@ class PointerAuthQualifier { // bits: |0 |1 |2..3 |4 | // |Enabled|Address|AuthenticationMode|ISA pointer| - // bits: |5
[clang] 4f96ce4 - [clang][NFC] Convert `Sema::PragmaClangSectionAction` to scoped enum
Author: Vlad Serebrennikov Date: 2025-04-28T09:06:32+03:00 New Revision: 4f96ce414bcc35ec7e3d8bec18f6a4d7a4c4632a URL: https://github.com/llvm/llvm-project/commit/4f96ce414bcc35ec7e3d8bec18f6a4d7a4c4632a DIFF: https://github.com/llvm/llvm-project/commit/4f96ce414bcc35ec7e3d8bec18f6a4d7a4c4632a.diff LOG: [clang][NFC] Convert `Sema::PragmaClangSectionAction` to scoped enum Added: Modified: clang/include/clang/Sema/Sema.h clang/lib/Parse/ParsePragma.cpp clang/lib/Sema/SemaAttr.cpp Removed: diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 11b6f5934be4f..0b57d50e2b22a 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -473,6 +473,8 @@ enum class PragmaClangSectionKind { Relro = 5 }; +enum class PragmaClangSectionAction { Set = 0, Clear = 1 }; + /// Sema - This implements semantic analysis and AST building for C. /// \nosubgrouping class Sema final : public SemaBase { @@ -1422,8 +1424,6 @@ class Sema final : public SemaBase { /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; - enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; - struct PragmaClangSection { std::string SectionName; bool Valid = false; diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index e08364d20a4ab..1d419106bf92b 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -2350,11 +2350,11 @@ void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP, if (!PP.LexStringLiteral(Tok, SecName, "pragma clang section", false)) return; -Actions.ActOnPragmaClangSection( -PragmaLocation, -(SecName.size() ? Sema::PragmaClangSectionAction::PCSA_Set -: Sema::PragmaClangSectionAction::PCSA_Clear), -SecKind, SecName); +Actions.ActOnPragmaClangSection(PragmaLocation, +(SecName.size() + ? PragmaClangSectionAction::Set + : PragmaClangSectionAction::Clear), +SecKind, SecName); } } diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp index cdc71658e259e..bade3a0502a2c 100644 --- a/clang/lib/Sema/SemaAttr.cpp +++ b/clang/lib/Sema/SemaAttr.cpp @@ -415,7 +415,7 @@ void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, llvm_unreachable("invalid clang section kind"); } - if (Action == PragmaClangSectionAction::PCSA_Clear) { + if (Action == PragmaClangSectionAction::Clear) { CSec->Valid = false; return; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
LorenzoMauro wrote: Thanks for taking a look! Happy to adjust anything if needed. https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [LLVM][Clang][Cygwin] Fix building Clang for Cygwin (PR #134494)
mstorsjo wrote: > > Then secondly, LLVM only allows "squash and merge" merging of PRs - so all > > these nicely split changes (with individual explanations soon, I'd hope!) > > would end up all mushed together. So unfortunately, to preserve the info > > about each of them, they'd need to be filed in separate individual PRs. > > I think the descriptions would be preserved if I combined them all into PR > description. I've split the commits only to make the review easier. Ok, fair enough - we can keep this as one single PR. If the PR description contains all the info needed to cover the why/how for all the changes here that's probably fine too. https://github.com/llvm/llvm-project/pull/134494 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Use llvm::is_detected (NFC) (PR #137560)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/137560.diff 2 Files Affected: - (modified) clang/include/clang/ASTMatchers/ASTMatchersInternal.h (+5-13) - (modified) clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp (+3-3) ``diff diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index c1130ff70cf5c..8290645768aa9 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -881,20 +881,12 @@ inline bool isDefaultedHelper(const FunctionDecl *FD) { } // Metafunction to determine if type T has a member called getDecl. -template -class has_getDecl { - using yes = char[1]; - using no = char[2]; - - template - static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr); - - template - static no& test(...); +template +using check_has_getDecl = decltype(std::declval().getDecl()); -public: - static const bool value = sizeof(test(nullptr)) == sizeof(yes); -}; +template +static constexpr bool has_getDecl = +llvm::is_detected::value; /// Matches overloaded operators with a specific name. /// diff --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp index 74844167d5e5a..8759811092b6f 100644 --- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp +++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp @@ -226,11 +226,11 @@ TEST(HasDeclaration, HasDeclarationOfEnumType) { } TEST(HasDeclaration, HasGetDeclTraitTest) { - static_assert(internal::has_getDecl::value, + static_assert(internal::has_getDecl, "Expected TypedefType to have a getDecl."); - static_assert(internal::has_getDecl::value, + static_assert(internal::has_getDecl, "Expected RecordType to have a getDecl."); - static_assert(!internal::has_getDecl::value, + static_assert(!internal::has_getDecl, "Expected TemplateSpecializationType to *not* have a getDecl."); } `` https://github.com/llvm/llvm-project/pull/137560 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Use llvm::is_detected (NFC) (PR #137560)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/137560 None >From 11261a022f2720eb3e368fd88981cb6b1c82c223 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sun, 27 Apr 2025 14:53:36 -0700 Subject: [PATCH] [ASTMatchers] Use llvm::is_detected (NFC) --- .../clang/ASTMatchers/ASTMatchersInternal.h| 18 +- .../ASTMatchers/ASTMatchersTraversalTest.cpp | 6 +++--- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index c1130ff70cf5c..8290645768aa9 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -881,20 +881,12 @@ inline bool isDefaultedHelper(const FunctionDecl *FD) { } // Metafunction to determine if type T has a member called getDecl. -template -class has_getDecl { - using yes = char[1]; - using no = char[2]; - - template - static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr); - - template - static no& test(...); +template +using check_has_getDecl = decltype(std::declval().getDecl()); -public: - static const bool value = sizeof(test(nullptr)) == sizeof(yes); -}; +template +static constexpr bool has_getDecl = +llvm::is_detected::value; /// Matches overloaded operators with a specific name. /// diff --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp index 74844167d5e5a..8759811092b6f 100644 --- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp +++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp @@ -226,11 +226,11 @@ TEST(HasDeclaration, HasDeclarationOfEnumType) { } TEST(HasDeclaration, HasGetDeclTraitTest) { - static_assert(internal::has_getDecl::value, + static_assert(internal::has_getDecl, "Expected TypedefType to have a getDecl."); - static_assert(internal::has_getDecl::value, + static_assert(internal::has_getDecl, "Expected RecordType to have a getDecl."); - static_assert(!internal::has_getDecl::value, + static_assert(!internal::has_getDecl, "Expected TemplateSpecializationType to *not* have a getDecl."); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] c215318 - [clang] Fix and test triviality of __ptrauth types (#137474)
Author: halbi2 Date: 2025-04-27T20:07:49-07:00 New Revision: c21531895a5d5e6ffc349d6e229d71dd1463860a URL: https://github.com/llvm/llvm-project/commit/c21531895a5d5e6ffc349d6e229d71dd1463860a DIFF: https://github.com/llvm/llvm-project/commit/c21531895a5d5e6ffc349d6e229d71dd1463860a.diff LOG: [clang] Fix and test triviality of __ptrauth types (#137474) Address-discriminated __ptrauth types do not have unique object representations so they are not trivially comparable. Test all other trivialities too even though they are not incorrect. Fixes #137473 Added: clang/test/SemaCXX/ptrauth-triviality.cpp Modified: clang/lib/AST/ASTContext.cpp Removed: diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index b1ecd9d63702b..c95e733f30494 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -2931,9 +2931,9 @@ bool ASTContext::hasUniqueObjectRepresentations( return true; } - // All other pointers are unique. + // All other pointers (except __ptrauth pointers) are unique. if (Ty->isPointerType()) -return true; +return !Ty.hasAddressDiscriminatedPointerAuth(); if (const auto *MPT = Ty->getAs()) return !ABI->getMemberPointerInfo(MPT).HasPadding; diff --git a/clang/test/SemaCXX/ptrauth-triviality.cpp b/clang/test/SemaCXX/ptrauth-triviality.cpp new file mode 100644 index 0..baadadca9f64f --- /dev/null +++ b/clang/test/SemaCXX/ptrauth-triviality.cpp @@ -0,0 +1,123 @@ +// RUN: %clang_cc1 -triple arm64-apple-ios -std=c++20 -fptrauth-calls -fptrauth-intrinsics -verify -fsyntax-only %s +// RUN: %clang_cc1 -triple aarch64-linux-gnu -std=c++20 -fptrauth-calls -fptrauth-intrinsics -verify -fsyntax-only %s +// expected-no-diagnostics + +#define AQ __ptrauth(1,1,50) +#define IQ __ptrauth(1,0,50) +#define AA [[clang::ptrauth_vtable_pointer(process_independent,address_discrimination,no_extra_discrimination)]] +#define IA [[clang::ptrauth_vtable_pointer(process_independent,no_address_discrimination,type_discrimination)]] +#define PA [[clang::ptrauth_vtable_pointer(process_dependent,no_address_discrimination,no_extra_discrimination)]] + +template +struct Holder { + T t_; + bool operator==(const Holder&) const = default; +}; + +struct S1 { + int * AQ p_; + void *payload_; + bool operator==(const S1&) const = default; +}; +static_assert(__is_trivially_constructible(S1)); +static_assert(!__is_trivially_constructible(S1, const S1&)); +static_assert(!__is_trivially_assignable(S1, const S1&)); +static_assert(__is_trivially_destructible(S1)); +static_assert(!__is_trivially_copyable(S1)); +static_assert(!__is_trivially_relocatable(S1)); +static_assert(!__is_trivially_equality_comparable(S1)); + +static_assert(__is_trivially_constructible(Holder)); +static_assert(!__is_trivially_constructible(Holder, const Holder&)); +static_assert(!__is_trivially_assignable(Holder, const Holder&)); +static_assert(__is_trivially_destructible(Holder)); +static_assert(!__is_trivially_copyable(Holder)); +static_assert(!__is_trivially_relocatable(Holder)); +static_assert(!__is_trivially_equality_comparable(Holder)); + +struct S2 { + int * IQ p_; + void *payload_; + bool operator==(const S2&) const = default; +}; +static_assert(__is_trivially_constructible(S2)); +static_assert(__is_trivially_constructible(S2, const S2&)); +static_assert(__is_trivially_assignable(S2, const S2&)); +static_assert(__is_trivially_destructible(S2)); +static_assert(__is_trivially_copyable(S2)); +static_assert(__is_trivially_relocatable(S2)); +static_assert(__is_trivially_equality_comparable(S2)); + +static_assert(__is_trivially_constructible(Holder)); +static_assert(__is_trivially_constructible(Holder, const Holder&)); +static_assert(__is_trivially_assignable(Holder, const Holder&)); +static_assert(__is_trivially_destructible(Holder)); +static_assert(__is_trivially_copyable(Holder)); +static_assert(__is_trivially_relocatable(Holder)); +static_assert(__is_trivially_equality_comparable(Holder)); + +struct AA S3 { + virtual void f(); + void *payload_; + bool operator==(const S3&) const = default; +}; + +static_assert(!__is_trivially_constructible(S3)); +static_assert(!__is_trivially_constructible(S3, const S3&)); +static_assert(!__is_trivially_assignable(S3, const S3&)); +static_assert(__is_trivially_destructible(S3)); +static_assert(!__is_trivially_copyable(S3)); +static_assert(!__is_trivially_relocatable(S3)); +static_assert(!__is_trivially_equality_comparable(S3)); + +static_assert(!__is_trivially_constructible(Holder)); +static_assert(!__is_trivially_constructible(Holder, const Holder&)); +static_assert(!__is_trivially_assignable(Holder, const Holder&)); +static_assert(__is_trivially_destructible(Holder)); +static_assert(!__is_trivially_copyable(Holder)); +static_assert(!__is_trivially_relocatable(Holder)); +static_assert(!__is_trivially_equality_comparable(Holder)); + +
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
ojhunt wrote: Thanks! https://github.com/llvm/llvm-project/pull/137474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
github-actions[bot] wrote: @halbi2 Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/137474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
https://github.com/ojhunt closed https://github.com/llvm/llvm-project/pull/137474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use range constructors of *Set (NFC) (PR #137574)
llvmbot wrote: @llvm/pr-subscribers-clang-analysis Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/137574.diff 5 Files Affected: - (modified) clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp (+1-1) - (modified) clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp (+3-4) - (modified) clang/lib/Sema/SemaTemplateVariadic.cpp (+1-1) - (modified) clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp (+1-1) - (modified) clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp (+1-2) ``diff diff --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp index 1c4fe5c6d5019..6409b4bc8ff4d 100644 --- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp +++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp @@ -86,7 +86,7 @@ StorageLocation &DataflowAnalysisContext::createStorageLocation(QualType Type) { // Can't use `StringSet` as the return type as it doesn't support `operator==`. template static llvm::DenseSet getKeys(const llvm::StringMap &Map) { - return llvm::DenseSet(Map.keys().begin(), Map.keys().end()); + return llvm::DenseSet(llvm::from_range, Map.keys()); } RecordStorageLocation &DataflowAnalysisContext::createRecordStorageLocation( diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp index f697c13f4c522..59a5f7b914ce5 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp @@ -129,8 +129,8 @@ static RecordDecl *buildRecordForGlobalizedVars( // }; RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty"); GlobalizedRD->startDefinition(); - llvm::SmallPtrSet SingleEscaped( - EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end()); + llvm::SmallPtrSet SingleEscaped(llvm::from_range, + EscapedDeclsForTeams); for (const auto &Pair : GlobalizedVars) { const ValueDecl *VD = Pair.second; QualType Type = VD->getType(); @@ -322,8 +322,7 @@ class CheckVarsEscapingDeclContext final public: CheckVarsEscapingDeclContext(CodeGenFunction &CGF, ArrayRef TeamsReductions) - : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) { - } + : CGF(CGF), EscapedDecls(llvm::from_range, TeamsReductions) {} virtual ~CheckVarsEscapingDeclContext() = default; void VisitDeclStmt(const DeclStmt *S) { if (!S) diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 87682233c5246..34fec069d6df6 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -498,7 +498,7 @@ bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { // We only care about unexpanded references to the RequiresExpr's own // parameter packs. auto Parms = RE->getLocalParameters(); - llvm::SmallPtrSet ParmSet(Parms.begin(), Parms.end()); + llvm::SmallPtrSet ParmSet(llvm::from_range, Parms); SmallVector UnexpandedParms; for (auto Parm : Unexpanded) if (ParmSet.contains(Parm.first.dyn_cast())) diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp index 90c95d5cf60d8..b88e6db7cceb7 100644 --- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp +++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp @@ -77,7 +77,7 @@ static int countSymbols(Lang Language) { } } #undef SYMBOL - return llvm::DenseSet(Symbols.begin(), Symbols.end()).size(); + return llvm::DenseSet(llvm::from_range, Symbols).size(); } static int initialize(Lang Language) { diff --git a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp index 1f34ae076d5ed..c82199c15e068 100644 --- a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp @@ -24,8 +24,7 @@ class SimplifyConstraintsTest : public ::testing::Test { protected: llvm::SetVector parse(StringRef Lines) { std::vector formulas = test::parseFormulas(A, Lines); -llvm::SetVector Constraints(formulas.begin(), - formulas.end()); +llvm::SetVector Constraints(llvm::from_range, formulas); return Constraints; } `` https://github.com/llvm/llvm-project/pull/137574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use range constructors of *Set (NFC) (PR #137574)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/137574 None >From b26fb883437b6822cfab50189d1fe96cb3ca330f Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sun, 13 Apr 2025 17:34:57 -0700 Subject: [PATCH] [clang] Use range constructors of *Set (NFC) --- .../lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp | 2 +- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp | 7 +++ clang/lib/Sema/SemaTemplateVariadic.cpp| 2 +- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp| 2 +- .../Analysis/FlowSensitive/SimplifyConstraintsTest.cpp | 3 +-- 5 files changed, 7 insertions(+), 9 deletions(-) diff --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp index 1c4fe5c6d5019..6409b4bc8ff4d 100644 --- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp +++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp @@ -86,7 +86,7 @@ StorageLocation &DataflowAnalysisContext::createStorageLocation(QualType Type) { // Can't use `StringSet` as the return type as it doesn't support `operator==`. template static llvm::DenseSet getKeys(const llvm::StringMap &Map) { - return llvm::DenseSet(Map.keys().begin(), Map.keys().end()); + return llvm::DenseSet(llvm::from_range, Map.keys()); } RecordStorageLocation &DataflowAnalysisContext::createRecordStorageLocation( diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp index f697c13f4c522..59a5f7b914ce5 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp @@ -129,8 +129,8 @@ static RecordDecl *buildRecordForGlobalizedVars( // }; RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty"); GlobalizedRD->startDefinition(); - llvm::SmallPtrSet SingleEscaped( - EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end()); + llvm::SmallPtrSet SingleEscaped(llvm::from_range, + EscapedDeclsForTeams); for (const auto &Pair : GlobalizedVars) { const ValueDecl *VD = Pair.second; QualType Type = VD->getType(); @@ -322,8 +322,7 @@ class CheckVarsEscapingDeclContext final public: CheckVarsEscapingDeclContext(CodeGenFunction &CGF, ArrayRef TeamsReductions) - : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) { - } + : CGF(CGF), EscapedDecls(llvm::from_range, TeamsReductions) {} virtual ~CheckVarsEscapingDeclContext() = default; void VisitDeclStmt(const DeclStmt *S) { if (!S) diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 87682233c5246..34fec069d6df6 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -498,7 +498,7 @@ bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { // We only care about unexpanded references to the RequiresExpr's own // parameter packs. auto Parms = RE->getLocalParameters(); - llvm::SmallPtrSet ParmSet(Parms.begin(), Parms.end()); + llvm::SmallPtrSet ParmSet(llvm::from_range, Parms); SmallVector UnexpandedParms; for (auto Parm : Unexpanded) if (ParmSet.contains(Parm.first.dyn_cast())) diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp index 90c95d5cf60d8..b88e6db7cceb7 100644 --- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp +++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp @@ -77,7 +77,7 @@ static int countSymbols(Lang Language) { } } #undef SYMBOL - return llvm::DenseSet(Symbols.begin(), Symbols.end()).size(); + return llvm::DenseSet(llvm::from_range, Symbols).size(); } static int initialize(Lang Language) { diff --git a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp index 1f34ae076d5ed..c82199c15e068 100644 --- a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp @@ -24,8 +24,7 @@ class SimplifyConstraintsTest : public ::testing::Test { protected: llvm::SetVector parse(StringRef Lines) { std::vector formulas = test::parseFormulas(A, Lines); -llvm::SetVector Constraints(formulas.begin(), - formulas.end()); +llvm::SetVector Constraints(llvm::from_range, formulas); return Constraints; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `lldb-arm-ubuntu` running on `linaro-lldb-arm-ubuntu` while building `clang` at step 6 "test". Full details are available at: https://lab.llvm.org/buildbot/#/builders/18/builds/15145 Here is the relevant piece of the build log for the reference ``` Step 6 (test) failure: build (failure) ... PASS: lldb-api :: symbol_ondemand/breakpoint_source_regex/TestSourceTextRegexBreakpoint.py (1143 of 3001) PASS: lldb-api :: python_api/watchpoint/watchlocation/TestSetWatchlocation.py (1144 of 3001) PASS: lldb-api :: source-manager/TestSourceManager.py (1145 of 3001) PASS: lldb-api :: symbol_ondemand/shared_library/TestSharedLibOnDemand.py (1146 of 3001) PASS: lldb-api :: terminal/TestSTTYBeforeAndAfter.py (1147 of 3001) PASS: lldb-api :: test_utils/TestDecorators.py (1148 of 3001) PASS: lldb-api :: test_utils/TestInlineTest.py (1149 of 3001) PASS: lldb-api :: test_utils/TestPExpectTest.py (1150 of 3001) PASS: lldb-api :: test_utils/base/TestBaseTest.py (1151 of 3001) PASS: lldb-api :: python_api/watchpoint/watchlocation/TestTargetWatchAddress.py (1152 of 3001) FAIL: lldb-api :: tools/lldb-dap/attach/TestDAP_attachByPortNum.py (1153 of 3001) TEST 'lldb-api :: tools/lldb-dap/attach/TestDAP_attachByPortNum.py' FAILED Script: -- /usr/bin/python3.10 /home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/dotest.py -u CXXFLAGS -u CFLAGS --env LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib --env LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/include --env LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --arch armv8l --build-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex --lldb-module-cache-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api --clang-module-cache-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api --executable /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/lldb --compiler /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/clang --dsymutil /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/dsymutil --make /usr/bin/gmake --llvm-tools-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --lldb-obj-root /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/tools/lldb --lldb-libs-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib /home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/tools/lldb-dap/attach -p TestDAP_attachByPortNum.py -- Exit Code: 1 Command Output (stdout): -- lldb version 21.0.0git (https://github.com/llvm/llvm-project.git revision c21531895a5d5e6ffc349d6e229d71dd1463860a) clang revision c21531895a5d5e6ffc349d6e229d71dd1463860a llvm revision c21531895a5d5e6ffc349d6e229d71dd1463860a Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 'debugserver', 'objc'] -- Command Output (stderr): -- Usage: /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/lldb-server v[ersion] /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/lldb-server g[dbserver] [options] /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/lldb-server p[latform] [options] Invoke subcommand for additional help PASS: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: test_by_illegal_port (TestDAP_attachByPortNum.TestDAP_attachByPortNum) = DEBUG ADAPTER PROTOCOL LOGS = 1745810504.017233849 --> (stdin/stdout) {"command":"initialize","type":"request","arguments":{"adapterID":"lldb-native","clientID":"vscode","columnsStartAt1":true,"linesStartAt1":true,"locale":"en-us","pathFormat":"path","supportsRunInTerminalRequest":true,"supportsVariablePaging":true,"supportsVariableType":true,"supportsStartDebuggingRequest":true,"supportsProgressReporting":true,"$__lldb_sourceInitFile":true},"seq":1} 1745810504.021262169 <-- (stdin/stdout) {"body":{"$__lldb_version":"lldb version 21.0.0git (https://github.com/llvm/llvm-project.git revision c21531895a5d5e6ffc349d6e229d71dd1463860a)\n clang revision c21531895a5d5e6ffc349d6e229d71dd1463860a\n llvm revision c21531895a5d5e6ffc349d6e229d71dd1463860a","completionTriggerCharacters":["."," ","\t"],"exceptionBreakpointFilters":[{"default":false,"filter":"cpp_catch","label":"C++ Catch"},{"default":false,"filter":"cpp_throw","label":"C++ Throw"},{"default":false,"filter":"objc_catch","label":"Objective-C Catch"},{"default":false,"filter":"objc_throw","label":"Objective-C Throw"}],"supportTerminateDebuggee":true,"supportsBreakpointLocationsRequest":true,"supportsCancelRequest":true,"supportsCompletionsRequest":true,"supportsConditionalBreakpoints":true,"supportsConfigurationDoneRequest":true,"supportsDataBreakpoints":true,"supportsDelayedStackTraceLoading":true,"supportsDisassembleRequest":true,"supportsEvaluateForHovers":true,"supportsExcep
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `llvm-clang-x86_64-gcc-ubuntu` running on `sie-linux-worker3` while building `clang` at step 6 "test-build-unified-tree-check-all". Full details are available at: https://lab.llvm.org/buildbot/#/builders/174/builds/16865 Here is the relevant piece of the build log for the reference ``` Step 6 (test-build-unified-tree-check-all) failure: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill ... PASS: lit :: shtest-not.py (90433 of 90443) PASS: lit :: allow-retries.py (90434 of 90443) PASS: lit :: discovery.py (90435 of 90443) PASS: lit :: shtest-external-shell-kill.py (90436 of 90443) PASS: lit :: googletest-timeout.py (90437 of 90443) PASS: lit :: selecting.py (90438 of 90443) PASS: lit :: shtest-timeout.py (90439 of 90443) PASS: lit :: max-time.py (90440 of 90443) PASS: lit :: shtest-shell.py (90441 of 90443) PASS: lit :: shtest-define.py (90442 of 90443) command timed out: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill process killed by signal 9 program finished with exit code -1 elapsedTime=1850.625370 ``` https://github.com/llvm/llvm-project/pull/137474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improve integer comparison by matching valid expressions outside implicitCastExpr (PR #134188)
@@ -52,8 +54,17 @@ intCastExpression(bool IsSigned, const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr)); const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr)); + // Match function calls or variable references not directly wrapped by an + // implicit cast + const auto CallIntExpr = CastBindName.empty() + ? callExpr(HasIntegerType) + : callExpr(HasIntegerType).bind(CastBindName); + const auto DeclRefIntExpr = HerrCai0907 wrote: Is there any usage of this variable? https://github.com/llvm/llvm-project/pull/134188 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ed95624 - [clang][NFC] Convert `StmtDiscardKind` to a scoped enum
Author: Vlad Serebrennikov Date: 2025-04-28T06:54:00+03:00 New Revision: ed95624e208e5bf7c3eeadfccee0fb6060a4ca98 URL: https://github.com/llvm/llvm-project/commit/ed95624e208e5bf7c3eeadfccee0fb6060a4ca98 DIFF: https://github.com/llvm/llvm-project/commit/ed95624e208e5bf7c3eeadfccee0fb6060a4ca98.diff LOG: [clang][NFC] Convert `StmtDiscardKind` to a scoped enum Added: Modified: clang/lib/Sema/TreeTransform.h Removed: diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 94d2b6b6cc808..5e83f83603335 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -357,10 +357,10 @@ class TreeTransform { /// @} /// The reason why the value of a statement is not discarded, if any. - enum StmtDiscardKind { -SDK_Discarded, -SDK_NotDiscarded, -SDK_StmtExprResult, + enum class StmtDiscardKind { +Discarded, +NotDiscarded, +StmtExprResult, }; /// Transform the given statement. @@ -372,7 +372,8 @@ class TreeTransform { /// other mechanism. /// /// \returns the transformed statement. - StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded); + StmtResult TransformStmt(Stmt *S, + StmtDiscardKind SDK = StmtDiscardKind::Discarded); /// Transform the given statement. /// @@ -4292,9 +4293,9 @@ StmtResult TreeTransform::TransformStmt(Stmt *S, StmtDiscardKind SDK) { { ExprResult E = getDerived().TransformExpr(cast(S)); - if (SDK == SDK_StmtExprResult) + if (SDK == StmtDiscardKind::StmtExprResult) E = getSema().ActOnStmtExprResult(E); - return getSema().ActOnExprStmt(E, SDK == SDK_Discarded); + return getSema().ActOnExprStmt(E, SDK == StmtDiscardKind::Discarded); } } @@ -8086,7 +8087,8 @@ TreeTransform::TransformCompoundStmt(CompoundStmt *S, SmallVector Statements; for (auto *B : S->body()) { StmtResult Result = getDerived().TransformStmt( -B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded); +B, IsStmtExpr && B == ExprResult ? StmtDiscardKind::StmtExprResult + : StmtDiscardKind::Discarded); if (Result.isInvalid()) { // Immediately fail if this was a DeclStmt, since it's very @@ -9067,8 +9069,8 @@ StmtResult TreeTransform::TransformObjCForCollectionStmt( ObjCForCollectionStmt *S) { // Transform the element statement. - StmtResult Element = - getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded); + StmtResult Element = getDerived().TransformStmt( + S->getElement(), StmtDiscardKind::NotDiscarded); if (Element.isInvalid()) return StmtError(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 096c20c - [clang][NFC] Convert enums in TypeLocBuilder into constants
Author: Vlad Serebrennikov Date: 2025-04-28T06:57:16+03:00 New Revision: 096c20c0b1284ccf3d3af106a026450403bc288f URL: https://github.com/llvm/llvm-project/commit/096c20c0b1284ccf3d3af106a026450403bc288f DIFF: https://github.com/llvm/llvm-project/commit/096c20c0b1284ccf3d3af106a026450403bc288f.diff LOG: [clang][NFC] Convert enums in TypeLocBuilder into constants Added: Modified: clang/lib/Sema/TypeLocBuilder.h Removed: diff --git a/clang/lib/Sema/TypeLocBuilder.h b/clang/lib/Sema/TypeLocBuilder.h index 15eb2226cdf7f..0c27088a1748b 100644 --- a/clang/lib/Sema/TypeLocBuilder.h +++ b/clang/lib/Sema/TypeLocBuilder.h @@ -20,7 +20,7 @@ namespace clang { class TypeLocBuilder { - enum { InlineCapacity = 8 * sizeof(SourceLocation) }; + static constexpr int InlineCapacity = 8 * sizeof(SourceLocation); /// The underlying location-data buffer. Data grows from the end /// of the buffer backwards. @@ -38,7 +38,7 @@ class TypeLocBuilder { #endif /// The inline buffer. - enum { BufferMaxAlignment = alignof(void *) }; + static constexpr int BufferMaxAlignment = alignof(void *); alignas(BufferMaxAlignment) char InlineBuffer[InlineCapacity]; unsigned NumBytesAtAlign4; bool AtAlign8; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 55651e7 - [clang] Use range constructors of *Set (NFC) (#137574)
Author: Kazu Hirata Date: 2025-04-27T21:17:14-07:00 New Revision: 55651e743b413af8787aa526de63d8c26c4a718b URL: https://github.com/llvm/llvm-project/commit/55651e743b413af8787aa526de63d8c26c4a718b DIFF: https://github.com/llvm/llvm-project/commit/55651e743b413af8787aa526de63d8c26c4a718b.diff LOG: [clang] Use range constructors of *Set (NFC) (#137574) Added: Modified: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp clang/lib/Sema/SemaTemplateVariadic.cpp clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp Removed: diff --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp index 1c4fe5c6d5019..6409b4bc8ff4d 100644 --- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp +++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp @@ -86,7 +86,7 @@ StorageLocation &DataflowAnalysisContext::createStorageLocation(QualType Type) { // Can't use `StringSet` as the return type as it doesn't support `operator==`. template static llvm::DenseSet getKeys(const llvm::StringMap &Map) { - return llvm::DenseSet(Map.keys().begin(), Map.keys().end()); + return llvm::DenseSet(llvm::from_range, Map.keys()); } RecordStorageLocation &DataflowAnalysisContext::createRecordStorageLocation( diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp index f697c13f4c522..59a5f7b914ce5 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp @@ -129,8 +129,8 @@ static RecordDecl *buildRecordForGlobalizedVars( // }; RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty"); GlobalizedRD->startDefinition(); - llvm::SmallPtrSet SingleEscaped( - EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end()); + llvm::SmallPtrSet SingleEscaped(llvm::from_range, + EscapedDeclsForTeams); for (const auto &Pair : GlobalizedVars) { const ValueDecl *VD = Pair.second; QualType Type = VD->getType(); @@ -322,8 +322,7 @@ class CheckVarsEscapingDeclContext final public: CheckVarsEscapingDeclContext(CodeGenFunction &CGF, ArrayRef TeamsReductions) - : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) { - } + : CGF(CGF), EscapedDecls(llvm::from_range, TeamsReductions) {} virtual ~CheckVarsEscapingDeclContext() = default; void VisitDeclStmt(const DeclStmt *S) { if (!S) diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 87682233c5246..34fec069d6df6 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -498,7 +498,7 @@ bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { // We only care about unexpanded references to the RequiresExpr's own // parameter packs. auto Parms = RE->getLocalParameters(); - llvm::SmallPtrSet ParmSet(Parms.begin(), Parms.end()); + llvm::SmallPtrSet ParmSet(llvm::from_range, Parms); SmallVector UnexpandedParms; for (auto Parm : Unexpanded) if (ParmSet.contains(Parm.first.dyn_cast())) diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp index 90c95d5cf60d8..b88e6db7cceb7 100644 --- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp +++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp @@ -77,7 +77,7 @@ static int countSymbols(Lang Language) { } } #undef SYMBOL - return llvm::DenseSet(Symbols.begin(), Symbols.end()).size(); + return llvm::DenseSet(llvm::from_range, Symbols).size(); } static int initialize(Lang Language) { diff --git a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp index 1f34ae076d5ed..c82199c15e068 100644 --- a/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/SimplifyConstraintsTest.cpp @@ -24,8 +24,7 @@ class SimplifyConstraintsTest : public ::testing::Test { protected: llvm::SetVector parse(StringRef Lines) { std::vector formulas = test::parseFormulas(A, Lines); -llvm::SetVector Constraints(formulas.begin(), - formulas.end()); +llvm::SetVector Constraints(llvm::from_range, formulas); return Constraints; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use range constructors of *Set (NFC) (PR #137574)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/137574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add OneLineFormatOffRegex option (PR #137577)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Close #54334 --- Full diff: https://github.com/llvm/llvm-project/pull/137577.diff 7 Files Affected: - (modified) clang/docs/ClangFormatStyleOptions.rst (+22) - (modified) clang/docs/ReleaseNotes.rst (+1) - (modified) clang/include/clang/Format/Format.h (+21) - (modified) clang/lib/Format/Format.cpp (+1) - (modified) clang/lib/Format/FormatTokenLexer.cpp (+34) - (modified) clang/unittests/Format/ConfigParseTest.cpp (+1) - (modified) clang/unittests/Format/FormatTest.cpp (+76) ``diff diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 3f8a5f49313b2..e3fe4a7529559 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -5195,6 +5195,28 @@ the configuration (without a prefix: ``Auto``). Add a space in front of an Objective-C protocol list, i.e. use ``Foo `` instead of ``Foo``. +.. _OneLineFormatOffRegex: + +**OneLineFormatOffRegex** (``String``) :versionbadge:`clang-format 21` :ref:`¶ ` + A regular expression that describes markers for turning formatting off for + one line. If it matches a line comment that is the first/only token of a + line, clang-format skips the next line. Otherwise, clang-format skips the + line that contains a matched token. + + .. code-block:: c++ + + // OneLineFormatOffRegex: ^(// NOLINT|logger$) + // results in the output below: + int a; + int b ; // NOLINT + int c; + // NOLINTNEXTLINE + int d ; + int e; + logger() ; + logger2(); + my_logger(); + .. _PPIndentWidth: **PPIndentWidth** (``Integer``) :versionbadge:`clang-format 13` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 3724c8cbc70fe..b22b3f13659ce 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -692,6 +692,7 @@ clang-format top of the file. - Add ``EnumTrailingComma`` option for inserting/removing commas at the end of ``enum`` enumerator lists. +- Add ``OneLineFormatOffRegex`` option for turning formatting off for one line. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index f6ceef08b46da..ce9a05f40be61 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -3654,6 +3654,26 @@ struct FormatStyle { /// \version 3.7 bool ObjCSpaceBeforeProtocolList; + /// A regular expression that describes markers for turning formatting off for + /// one line. If it matches a line comment that is the first/only token of a + /// line, clang-format skips the next line. Otherwise, clang-format skips the + /// line that contains a matched token. + /// \code + ///// OneLineFormatOffRegex: ^(// NOLINT|logger$) + ///// results in the output below: + ///int a; + ///int b ; // NOLINT + ///int c; + ///// NOLINTNEXTLINE + ///int d ; + ///int e; + ///logger() ; + ///logger2(); + ///my_logger(); + /// \endcode + /// \version 21 + std::string OneLineFormatOffRegex; + /// Different ways to try to fit all constructor initializers on a line. enum PackConstructorInitializersStyle : int8_t { /// Always put each constructor initializer on its own line. @@ -5399,6 +5419,7 @@ struct FormatStyle { ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder && ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty && ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList && + OneLineFormatOffRegex == R.OneLineFormatOffRegex && PackConstructorInitializers == R.PackConstructorInitializers && PenaltyBreakAssignment == R.PenaltyBreakAssignment && PenaltyBreakBeforeFirstCallParameter == diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 5a1c3f556b331..2f4b64ef4f5fe 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1100,6 +1100,7 @@ template <> struct MappingTraits { IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); IO.mapOptional("ObjCSpaceBeforeProtocolList", Style.ObjCSpaceBeforeProtocolList); +IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex); IO.mapOptional("PackConstructorInitializers", Style.PackConstructorInitializers); IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment); diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index a4c94ac411fe0..58991f9681c97 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -83,8 +83,42 @@ FormatTokenLexer::FormatTokenLexer( ArrayRef FormatTokenLexer::lex() { assert(Tokens.empty()); assert(FirstInLineIndex == 0); + const llvm::Regex FormatOffRegex(Style.OneLineFo
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
https://github.com/kazutakahirata updated https://github.com/llvm/llvm-project/pull/137571 >From 1f4e0a2f61f75c45aea2651dff2f08d1a60d4526 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sun, 27 Apr 2025 19:44:12 -0700 Subject: [PATCH 1/2] [ASTMatchers] Simplify isDefaultedHelper (NFC) We can use "constexpt if" to combine the two variants of functions. --- clang/include/clang/ASTMatchers/ASTMatchersInternal.h | 9 +++-- 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index 8290645768aa9..00a4fefeac8f8 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -871,14 +871,11 @@ IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, return End; } -template ::value> - * = nullptr> -inline bool isDefaultedHelper(const T *) { +template inline bool isDefaultedHelper(const T *FD) { + if constexpr (std::is_base_of::value) +return FD->isDefaulted(); return false; } -inline bool isDefaultedHelper(const FunctionDecl *FD) { - return FD->isDefaulted(); -} // Metafunction to determine if type T has a member called getDecl. template >From ee48b912d698b18f028a6ea709b9e7ba17b436bf Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sun, 27 Apr 2025 21:11:41 -0700 Subject: [PATCH 2/2] Update clang/include/clang/ASTMatchers/ASTMatchersInternal.h Co-authored-by: Jakub Kuderski --- clang/include/clang/ASTMatchers/ASTMatchersInternal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index 00a4fefeac8f8..71dfc49b7fcca 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -872,7 +872,7 @@ IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, } template inline bool isDefaultedHelper(const T *FD) { - if constexpr (std::is_base_of::value) + if constexpr (std::is_base_of_v) return FD->isDefaulted(); return false; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
https://github.com/kuhar approved this pull request. https://github.com/llvm/llvm-project/pull/137571 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
@@ -871,14 +871,11 @@ IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, return End; } -template ::value> - * = nullptr> -inline bool isDefaultedHelper(const T *) { +template inline bool isDefaultedHelper(const T *FD) { + if constexpr (std::is_base_of::value) kuhar wrote: ```suggestion if constexpr (std::is_base_of_v) ``` https://github.com/llvm/llvm-project/pull/137571 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use range constructors of *Set (NFC) (PR #137574)
https://github.com/kuhar approved this pull request. https://github.com/llvm/llvm-project/pull/137574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add OneLineFormatOffRegex option (PR #137577)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/137577 Close #54334 >From e505e4e1ca2457db2aba34e50b1eeaf9e8458020 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 27 Apr 2025 21:18:03 -0700 Subject: [PATCH] [clang-format] Add OneLineFormatOffRegex option Close #54334 --- clang/docs/ClangFormatStyleOptions.rst | 22 +++ clang/docs/ReleaseNotes.rst| 1 + clang/include/clang/Format/Format.h| 21 ++ clang/lib/Format/Format.cpp| 1 + clang/lib/Format/FormatTokenLexer.cpp | 34 ++ clang/unittests/Format/ConfigParseTest.cpp | 1 + clang/unittests/Format/FormatTest.cpp | 76 ++ 7 files changed, 156 insertions(+) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 3f8a5f49313b2..e3fe4a7529559 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -5195,6 +5195,28 @@ the configuration (without a prefix: ``Auto``). Add a space in front of an Objective-C protocol list, i.e. use ``Foo `` instead of ``Foo``. +.. _OneLineFormatOffRegex: + +**OneLineFormatOffRegex** (``String``) :versionbadge:`clang-format 21` :ref:`¶ ` + A regular expression that describes markers for turning formatting off for + one line. If it matches a line comment that is the first/only token of a + line, clang-format skips the next line. Otherwise, clang-format skips the + line that contains a matched token. + + .. code-block:: c++ + + // OneLineFormatOffRegex: ^(// NOLINT|logger$) + // results in the output below: + int a; + int b ; // NOLINT + int c; + // NOLINTNEXTLINE + int d ; + int e; + logger() ; + logger2(); + my_logger(); + .. _PPIndentWidth: **PPIndentWidth** (``Integer``) :versionbadge:`clang-format 13` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 3724c8cbc70fe..b22b3f13659ce 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -692,6 +692,7 @@ clang-format top of the file. - Add ``EnumTrailingComma`` option for inserting/removing commas at the end of ``enum`` enumerator lists. +- Add ``OneLineFormatOffRegex`` option for turning formatting off for one line. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index f6ceef08b46da..ce9a05f40be61 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -3654,6 +3654,26 @@ struct FormatStyle { /// \version 3.7 bool ObjCSpaceBeforeProtocolList; + /// A regular expression that describes markers for turning formatting off for + /// one line. If it matches a line comment that is the first/only token of a + /// line, clang-format skips the next line. Otherwise, clang-format skips the + /// line that contains a matched token. + /// \code + ///// OneLineFormatOffRegex: ^(// NOLINT|logger$) + ///// results in the output below: + ///int a; + ///int b ; // NOLINT + ///int c; + ///// NOLINTNEXTLINE + ///int d ; + ///int e; + ///logger() ; + ///logger2(); + ///my_logger(); + /// \endcode + /// \version 21 + std::string OneLineFormatOffRegex; + /// Different ways to try to fit all constructor initializers on a line. enum PackConstructorInitializersStyle : int8_t { /// Always put each constructor initializer on its own line. @@ -5399,6 +5419,7 @@ struct FormatStyle { ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder && ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty && ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList && + OneLineFormatOffRegex == R.OneLineFormatOffRegex && PackConstructorInitializers == R.PackConstructorInitializers && PenaltyBreakAssignment == R.PenaltyBreakAssignment && PenaltyBreakBeforeFirstCallParameter == diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 5a1c3f556b331..2f4b64ef4f5fe 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1100,6 +1100,7 @@ template <> struct MappingTraits { IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); IO.mapOptional("ObjCSpaceBeforeProtocolList", Style.ObjCSpaceBeforeProtocolList); +IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex); IO.mapOptional("PackConstructorInitializers", Style.PackConstructorInitializers); IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment); diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index a4c94ac411fe0..58991f9681c97 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -83,8 +83,42 @@ FormatTokenLexer::FormatTokenLexer( Arr
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -0,0 +1,748 @@ +//===--===// +// +// 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 "ConflictingGlobalAccesses.h" + +#include "clang/AST/RecursiveASTVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +using AccessKind = uint8_t; +static constexpr AccessKind AkRead = 0; +static constexpr AccessKind AkWrite = 1; +static constexpr AccessKind AkUncheckedRead = 2; +static constexpr AccessKind AkUncheckedWrite = 3; + +static constexpr uint8_t AkCount = 4; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArray represents one field inside a global struct/union system. +// The FieldIndexArray can be thought of as a path inside a tree. +using FieldIndex = uint16_t; +static constexpr FieldIndex FiUnion = 0x8000; + +// Note: This bit signals whether the field is a *field of* a struct or a +// union, not whether the type of the field itself is a struct or a union. +using FieldIndexArray = SmallVector; + +/// One traversal recurses into one side of a binary expression or one +/// parameter of a function call. At least two of these traversals are used to +/// find conflicting accesses. +/// +/// A TraversalResult represents one traversal. +struct TraversalResult { + int IndexCreated; // We use indices to keep track of which +// traversal we are in currently. The current +// index is stored in GlobalRWVisitor with the +// name TraversalIndex. + SourceLocation Loc[AkCount]; + TraversalResultKind Kind; + + TraversalResult(); + TraversalResult(int Index, SourceLocation Loc, AccessKind Access); + void addNewAccess(SourceLocation Loc, AccessKind Access); +}; + +/// The result of a number of traversals. +class TraversalAggregation { + DeclarationName DeclName; // The name of the global variable being checked. + + // We only store the result of two traversals as two conflicting accesses + // are enough to detect undefined behavior. The two stored TraversalResults + // have different traversal indices. + // + // Note: Sometimes multiple traversals are merged into one + // TraversalResult. + TraversalResult MainPart, OtherPart; + // Pairings that are not reportable: Read-Read, Read-Write, + // Read-UncheckedRead, Write-Write, UncheckedRead-UncheckedRead. + +public: + TraversalAggregation(); + TraversalAggregation(DeclarationName Name, SourceLocation Loc, + AccessKind Access, int Index); + void addGlobalRW(SourceLocation Loc, AccessKind Access, int Index); + DeclarationName getDeclName() const; + + bool isValid() const; + + // If there is a conflict and that conflict isn't reported by -Wunsequenced + // then we report the conflict. + bool shouldBeReported() const; + bool hasConflictingOperations() const; + +private: + bool hasTwoAccesses() const; + bool isReportedByWunsequenced() const; +}; + +/// The ObjectAccessTree stores the TraversalAggregations of one global +/// struct/union. Because each field can be handled as a single variable, the +/// tree stores one TraversalAggregation for every field. +/// +/// Note: structs, classes, and unions are called objects in the code. +struct ObjectAccessTree { + using FieldMap = llvm::DenseMap>; + TraversalAggregation OwnAccesses; + + // In a union, new fields should inherit from UnionTemporalAccesses + // instead of OwnAccesses. That's because an access to a field of a union is + // also an access to every other field of the same union. + TraversalAggregation UnionTemporalAccesses; + + // We try to be lazy and only store fields that are actually accessed. + FieldMap Fields; + bool IsUnion; + + ObjectAccessTree(TraversalAggregation Own); + + void addFieldToAll(SourceLocation Loc, AccessKind Access, int Index); + void addFieldToAllExcept(uint16_t ExceptIndex, SourceLocation Loc, + AccessKind Access, int Index); +}; + +/// This object is the root of all ObjectAccessTrees. +class ObjectTraversalAggregation { + DeclarationName
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -0,0 +1,77 @@ +//===--- ConflictingGlobalAccesses.h - clang-tidy ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SIDEEFFECTBETWEENSEQUENCE\ +POINTSCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SIDEEFFECTBETWEENSEQUENCE\ +POINTSCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Finds conflicting accesses on global variables. +/// +/// Modifying twice or reading and modifying a memory location without a +/// defined sequence of the operations is undefined behavior. This checker is +/// similar to the -Wunsequenced clang warning, however it only looks at global +/// variables and can find unsequenced operations inside functions as well. +/// +/// For example: \code +/// +/// int a = 0; +/// int b = (a++) - a; // This is flagged by -Wunsequenced. +/// +/// \endcode +/// +/// However global variables allow for more complex scenarios that +/// -Wunsequenced doesn't detect. E.g. \code +/// +/// int globalVar = 0; +/// +/// int incFun() { +/// globalVar++; +/// return globalVar; +/// } +/// +/// int main() { +/// return globalVar + incFun(); // This is not detected by -Wunsequenced. +/// } +/// +/// \endcode +/// +/// This checker attempts to detect such undefined behavior. It recurses into +/// functions that are inside the same translation unit. It also attempts not to +/// flag cases that are already covered by -Wunsequenced. Global unions and +/// structs are also handled. +/// +/// It's possible to enable handling mutable reference and pointer function +/// parameters as writes using the HandleMutableFunctionParametersAsWrites +/// option. For example: \code +/// +/// void func(int& a); +/// +/// int globalVar; +/// func(globalVar); // <- this could be a write to globalVar. +/// +/// \endcode +/// +/// This option is disabled by default. +class ConflictingGlobalAccesses : public ClangTidyCheck { ConcreteCactus wrote: Done. I'm guessing LangOpts.CPlusPlus also includes C, as I didn't find a language option that was for just C. https://github.com/llvm/llvm-project/pull/130421 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -0,0 +1,748 @@ +//===--===// +// +// 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 "ConflictingGlobalAccesses.h" + +#include "clang/AST/RecursiveASTVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +using AccessKind = uint8_t; +static constexpr AccessKind AkRead = 0; +static constexpr AccessKind AkWrite = 1; +static constexpr AccessKind AkUncheckedRead = 2; +static constexpr AccessKind AkUncheckedWrite = 3; + +static constexpr uint8_t AkCount = 4; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArray represents one field inside a global struct/union system. +// The FieldIndexArray can be thought of as a path inside a tree. +using FieldIndex = uint16_t; +static constexpr FieldIndex FiUnion = 0x8000; + +// Note: This bit signals whether the field is a *field of* a struct or a +// union, not whether the type of the field itself is a struct or a union. +using FieldIndexArray = SmallVector; + +/// One traversal recurses into one side of a binary expression or one +/// parameter of a function call. At least two of these traversals are used to +/// find conflicting accesses. +/// +/// A TraversalResult represents one traversal. +struct TraversalResult { + int IndexCreated; // We use indices to keep track of which +// traversal we are in currently. The current +// index is stored in GlobalRWVisitor with the +// name TraversalIndex. + SourceLocation Loc[AkCount]; + TraversalResultKind Kind; + + TraversalResult(); + TraversalResult(int Index, SourceLocation Loc, AccessKind Access); + void addNewAccess(SourceLocation Loc, AccessKind Access); +}; + +/// The result of a number of traversals. +class TraversalAggregation { + DeclarationName DeclName; // The name of the global variable being checked. + + // We only store the result of two traversals as two conflicting accesses + // are enough to detect undefined behavior. The two stored TraversalResults + // have different traversal indices. + // + // Note: Sometimes multiple traversals are merged into one + // TraversalResult. + TraversalResult MainPart, OtherPart; + // Pairings that are not reportable: Read-Read, Read-Write, + // Read-UncheckedRead, Write-Write, UncheckedRead-UncheckedRead. + +public: + TraversalAggregation(); + TraversalAggregation(DeclarationName Name, SourceLocation Loc, + AccessKind Access, int Index); + void addGlobalRW(SourceLocation Loc, AccessKind Access, int Index); + DeclarationName getDeclName() const; + + bool isValid() const; + + // If there is a conflict and that conflict isn't reported by -Wunsequenced + // then we report the conflict. + bool shouldBeReported() const; + bool hasConflictingOperations() const; + +private: + bool hasTwoAccesses() const; + bool isReportedByWunsequenced() const; +}; + +/// The ObjectAccessTree stores the TraversalAggregations of one global +/// struct/union. Because each field can be handled as a single variable, the +/// tree stores one TraversalAggregation for every field. +/// +/// Note: structs, classes, and unions are called objects in the code. +struct ObjectAccessTree { + using FieldMap = llvm::DenseMap>; + TraversalAggregation OwnAccesses; + + // In a union, new fields should inherit from UnionTemporalAccesses + // instead of OwnAccesses. That's because an access to a field of a union is + // also an access to every other field of the same union. + TraversalAggregation UnionTemporalAccesses; + + // We try to be lazy and only store fields that are actually accessed. + FieldMap Fields; + bool IsUnion; + + ObjectAccessTree(TraversalAggregation Own); + + void addFieldToAll(SourceLocation Loc, AccessKind Access, int Index); + void addFieldToAllExcept(uint16_t ExceptIndex, SourceLocation Loc, + AccessKind Access, int Index); +}; + +/// This object is the root of all ObjectAccessTrees. +class ObjectTraversalAggregation { + DeclarationName
[clang] [llvm] [WIP] Correct lowering of `fp128` intrinsics (PR #76558)
https://github.com/tgross35 updated https://github.com/llvm/llvm-project/pull/76558 >From dafb3a378876db6b3bf505b425b386fd8f79c918 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 11 Aug 2023 22:16:01 -0400 Subject: [PATCH 1/5] [IR] Add a test for `f128` libcall lowering (NFC) `f128` intrinsic functions sometimes lower to `long double` library calls when they instead need to be `f128` versions. Add a test demonstrating current behavior. --- .../CodeGen/Generic/f128-math-lowering.ll | 328 ++ 1 file changed, 328 insertions(+) create mode 100644 llvm/test/CodeGen/Generic/f128-math-lowering.ll diff --git a/llvm/test/CodeGen/Generic/f128-math-lowering.ll b/llvm/test/CodeGen/Generic/f128-math-lowering.ll new file mode 100644 index 0..dfbd1eaeda109 --- /dev/null +++ b/llvm/test/CodeGen/Generic/f128-math-lowering.ll @@ -0,0 +1,328 @@ +; RUN: llc < %s -mtriple=aarch64-unknown-none -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=i686-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=riscv32 -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=s390x-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-S390X +; RUN: llc < %s -mtriple=x86_64-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-NOTLD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-musl -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; +; REQUIRES: aarch64-registered-target +; REQUIRES: riscv-registered-target +; REQUIRES: systemz-registered-target +; REQUIRES: x86-registered-target +; +; Verify that fp128 intrinsics only lower to `long double` calls (e.g. `sinl`) +; on platforms where `f128` and `long double` have the same layout, and +; otherwise lower to `f128` versions (e.g. `sinf128`). +; +; Targets include: +; * x86, x64 (80-bit long double) +; * aarch64 (long double == f128) +; * riscv32 (long double == f64) +; * s390x (long double == f128, hardware support) +; * A couple assorted environments for x86 +; +; FIXME: only targets where long double is `f128` should be using `USELD`, all +; others need to be NOTLD. PowerPC should be added but it currently emits an +; interesting blend of both (e.g. `acosl` but `ceilf128`). + +define fp128 @test_acosf128(fp128 %a) { +; CHECK-LABEL: test_acosf128: +; CHECK-NOTLD: acosf128 +; CHECK-USELD: acosl +; CHECK-S390X: acosl +start: + %0 = tail call fp128 @llvm.acos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_asinf128(fp128 %a) { +; CHECK-LABEL: test_asinf128: +; CHECK-NOTLD: asinf128 +; CHECK-USELD: asinl +; CHECK-S390X: asinl +start: + %0 = tail call fp128 @llvm.asin.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_atanf128(fp128 %a) { +; CHECK-LABEL: test_atanf128: +; CHECK-NOTLD: atanf128 +; CHECK-USELD: atanl +; CHECK-S390X: atanl +start: + %0 = tail call fp128 @llvm.atan.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_ceilf128(fp128 %a) { +; CHECK-LABEL: test_ceilf128: +; CHECK-NOTLD: ceilf128 +; CHECK-USELD: ceill +; CHECK-S390X: ceill +start: + %0 = tail call fp128 @llvm.ceil.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_copysignf128(fp128 %a, fp128 %b) { +; copysign should always get lowered to assembly +; CHECK-LABEL: test_copysignf128: +; CHECK-NOT:copysignl +; CHECK-NOT:copysignf128 +start: + %0 = tail call fp128 @llvm.copysign.f128(fp128 %a, fp128 %b) + ret fp128 %0 +} + +define fp128 @test_cosf128(fp128 %a) { +; CHECK-LABEL: test_cosf128: +; CHECK-NOTLD: cosf128 +; CHECK-USELD: cosl +; CHECK-S390X: cosl +start: + %0 = tail call fp128 @llvm.cos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp10f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp10f128 +; CHECK-USELD: exp10l +; CHECK-S390X: exp10l +start: + %0 = tail call fp128 @llvm.exp10.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp2f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp2f128 +; CHECK-USELD: exp2l +; CHECK-S390X: exp2l +start: + %0 = tail call fp128 @llvm.exp2.f128(fp128 %a) + ret fp128 %0 +} + + +define fp128 @test_expf128(fp128 %a) { +; CHECK-LABEL: test_expf128: +; CHECK-NOTLD: expf128 +; CHECK-USELD: expl +; CHECK-S390X: expl +start: + %0 = tail call fp128 @llvm.exp.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_fabsf128(fp128 %a) { +; fabs should always get lowered to assembly +; CHECK-LABEL: test_fabsf128: +; CHECK-NOT:fabsl +; CHECK-NOT:fabsf128 +start: + %0 = tail call fp128 @llvm.fabs.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_floorf128(fp128 %a) { +; CHECK-LABEL: test
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -20,6 +20,7 @@ #include "CastingThroughVoidCheck.h" #include "ChainedComparisonCheck.h" #include "ComparePointerToMemberVirtualFunctionCheck.h" +#include "ConflictingGlobalAccesses.h" ConcreteCactus wrote: I renamed the files to end with check, and added the files and changes that the script would add. https://github.com/llvm/llvm-project/pull/130421 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] Correct lowering of `fp128` intrinsics (PR #76558)
https://github.com/tgross35 updated https://github.com/llvm/llvm-project/pull/76558 >From dafb3a378876db6b3bf505b425b386fd8f79c918 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 11 Aug 2023 22:16:01 -0400 Subject: [PATCH 1/4] [IR] Add a test for `f128` libcall lowering (NFC) `f128` intrinsic functions sometimes lower to `long double` library calls when they instead need to be `f128` versions. Add a test demonstrating current behavior. --- .../CodeGen/Generic/f128-math-lowering.ll | 328 ++ 1 file changed, 328 insertions(+) create mode 100644 llvm/test/CodeGen/Generic/f128-math-lowering.ll diff --git a/llvm/test/CodeGen/Generic/f128-math-lowering.ll b/llvm/test/CodeGen/Generic/f128-math-lowering.ll new file mode 100644 index 0..dfbd1eaeda109 --- /dev/null +++ b/llvm/test/CodeGen/Generic/f128-math-lowering.ll @@ -0,0 +1,328 @@ +; RUN: llc < %s -mtriple=aarch64-unknown-none -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=i686-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=riscv32 -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=s390x-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-S390X +; RUN: llc < %s -mtriple=x86_64-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-NOTLD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-musl -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; +; REQUIRES: aarch64-registered-target +; REQUIRES: riscv-registered-target +; REQUIRES: systemz-registered-target +; REQUIRES: x86-registered-target +; +; Verify that fp128 intrinsics only lower to `long double` calls (e.g. `sinl`) +; on platforms where `f128` and `long double` have the same layout, and +; otherwise lower to `f128` versions (e.g. `sinf128`). +; +; Targets include: +; * x86, x64 (80-bit long double) +; * aarch64 (long double == f128) +; * riscv32 (long double == f64) +; * s390x (long double == f128, hardware support) +; * A couple assorted environments for x86 +; +; FIXME: only targets where long double is `f128` should be using `USELD`, all +; others need to be NOTLD. PowerPC should be added but it currently emits an +; interesting blend of both (e.g. `acosl` but `ceilf128`). + +define fp128 @test_acosf128(fp128 %a) { +; CHECK-LABEL: test_acosf128: +; CHECK-NOTLD: acosf128 +; CHECK-USELD: acosl +; CHECK-S390X: acosl +start: + %0 = tail call fp128 @llvm.acos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_asinf128(fp128 %a) { +; CHECK-LABEL: test_asinf128: +; CHECK-NOTLD: asinf128 +; CHECK-USELD: asinl +; CHECK-S390X: asinl +start: + %0 = tail call fp128 @llvm.asin.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_atanf128(fp128 %a) { +; CHECK-LABEL: test_atanf128: +; CHECK-NOTLD: atanf128 +; CHECK-USELD: atanl +; CHECK-S390X: atanl +start: + %0 = tail call fp128 @llvm.atan.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_ceilf128(fp128 %a) { +; CHECK-LABEL: test_ceilf128: +; CHECK-NOTLD: ceilf128 +; CHECK-USELD: ceill +; CHECK-S390X: ceill +start: + %0 = tail call fp128 @llvm.ceil.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_copysignf128(fp128 %a, fp128 %b) { +; copysign should always get lowered to assembly +; CHECK-LABEL: test_copysignf128: +; CHECK-NOT:copysignl +; CHECK-NOT:copysignf128 +start: + %0 = tail call fp128 @llvm.copysign.f128(fp128 %a, fp128 %b) + ret fp128 %0 +} + +define fp128 @test_cosf128(fp128 %a) { +; CHECK-LABEL: test_cosf128: +; CHECK-NOTLD: cosf128 +; CHECK-USELD: cosl +; CHECK-S390X: cosl +start: + %0 = tail call fp128 @llvm.cos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp10f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp10f128 +; CHECK-USELD: exp10l +; CHECK-S390X: exp10l +start: + %0 = tail call fp128 @llvm.exp10.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp2f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp2f128 +; CHECK-USELD: exp2l +; CHECK-S390X: exp2l +start: + %0 = tail call fp128 @llvm.exp2.f128(fp128 %a) + ret fp128 %0 +} + + +define fp128 @test_expf128(fp128 %a) { +; CHECK-LABEL: test_expf128: +; CHECK-NOTLD: expf128 +; CHECK-USELD: expl +; CHECK-S390X: expl +start: + %0 = tail call fp128 @llvm.exp.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_fabsf128(fp128 %a) { +; fabs should always get lowered to assembly +; CHECK-LABEL: test_fabsf128: +; CHECK-NOT:fabsl +; CHECK-NOT:fabsf128 +start: + %0 = tail call fp128 @llvm.fabs.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_floorf128(fp128 %a) { +; CHECK-LABEL: test
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -0,0 +1,748 @@ +//===--===// +// +// 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 "ConflictingGlobalAccesses.h" + +#include "clang/AST/RecursiveASTVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +using AccessKind = uint8_t; +static constexpr AccessKind AkRead = 0; +static constexpr AccessKind AkWrite = 1; +static constexpr AccessKind AkUncheckedRead = 2; +static constexpr AccessKind AkUncheckedWrite = 3; + +static constexpr uint8_t AkCount = 4; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArray represents one field inside a global struct/union system. +// The FieldIndexArray can be thought of as a path inside a tree. +using FieldIndex = uint16_t; +static constexpr FieldIndex FiUnion = 0x8000; + +// Note: This bit signals whether the field is a *field of* a struct or a +// union, not whether the type of the field itself is a struct or a union. +using FieldIndexArray = SmallVector; + +/// One traversal recurses into one side of a binary expression or one +/// parameter of a function call. At least two of these traversals are used to +/// find conflicting accesses. +/// +/// A TraversalResult represents one traversal. +struct TraversalResult { + int IndexCreated; // We use indices to keep track of which +// traversal we are in currently. The current +// index is stored in GlobalRWVisitor with the +// name TraversalIndex. + SourceLocation Loc[AkCount]; + TraversalResultKind Kind; + + TraversalResult(); + TraversalResult(int Index, SourceLocation Loc, AccessKind Access); + void addNewAccess(SourceLocation Loc, AccessKind Access); +}; + +/// The result of a number of traversals. +class TraversalAggregation { + DeclarationName DeclName; // The name of the global variable being checked. + + // We only store the result of two traversals as two conflicting accesses + // are enough to detect undefined behavior. The two stored TraversalResults + // have different traversal indices. + // + // Note: Sometimes multiple traversals are merged into one + // TraversalResult. + TraversalResult MainPart, OtherPart; + // Pairings that are not reportable: Read-Read, Read-Write, + // Read-UncheckedRead, Write-Write, UncheckedRead-UncheckedRead. + +public: + TraversalAggregation(); + TraversalAggregation(DeclarationName Name, SourceLocation Loc, + AccessKind Access, int Index); + void addGlobalRW(SourceLocation Loc, AccessKind Access, int Index); + DeclarationName getDeclName() const; + + bool isValid() const; + + // If there is a conflict and that conflict isn't reported by -Wunsequenced + // then we report the conflict. + bool shouldBeReported() const; + bool hasConflictingOperations() const; + +private: + bool hasTwoAccesses() const; + bool isReportedByWunsequenced() const; +}; + +/// The ObjectAccessTree stores the TraversalAggregations of one global +/// struct/union. Because each field can be handled as a single variable, the +/// tree stores one TraversalAggregation for every field. +/// +/// Note: structs, classes, and unions are called objects in the code. +struct ObjectAccessTree { + using FieldMap = llvm::DenseMap>; + TraversalAggregation OwnAccesses; + + // In a union, new fields should inherit from UnionTemporalAccesses + // instead of OwnAccesses. That's because an access to a field of a union is + // also an access to every other field of the same union. + TraversalAggregation UnionTemporalAccesses; + + // We try to be lazy and only store fields that are actually accessed. + FieldMap Fields; + bool IsUnion; + + ObjectAccessTree(TraversalAggregation Own); + + void addFieldToAll(SourceLocation Loc, AccessKind Access, int Index); + void addFieldToAllExcept(uint16_t ExceptIndex, SourceLocation Loc, + AccessKind Access, int Index); +}; + +/// This object is the root of all ObjectAccessTrees. +class ObjectTraversalAggregation { + DeclarationName
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
https://github.com/ConcreteCactus updated https://github.com/llvm/llvm-project/pull/130421 >From 6879af38a7d22cad2850fed2fc146198b52348a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= Date: Fri, 22 Nov 2024 21:43:04 +0100 Subject: [PATCH] [clang-tidy] Added Conflicting Global Accesses checker This checker attempts to detect unsequenced accesses to global variables. It recurses into function calls in the same translation unit, and can handle fields on global structs/unions. --- .../bugprone/BugproneTidyModule.cpp | 3 + .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../ConflictingGlobalAccessesCheck.cpp| 976 ++ .../bugprone/ConflictingGlobalAccessesCheck.h | 35 + .../clang-tidy/cert/CERTTidyModule.cpp| 6 + clang-tools-extra/docs/ReleaseNotes.rst | 14 + .../bugprone/conflicting-global-accesses.rst | 72 ++ .../docs/clang-tidy/checks/list.rst | 3 + .../bugprone/conflicting-global-accesses.cpp | 599 +++ 9 files changed, 1709 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/conflicting-global-accesses.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/conflicting-global-accesses.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index b780a85bdf3fe..aa966a2278ca9 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -20,6 +20,7 @@ #include "CastingThroughVoidCheck.h" #include "ChainedComparisonCheck.h" #include "ComparePointerToMemberVirtualFunctionCheck.h" +#include "ConflictingGlobalAccessesCheck.h" #include "CopyConstructorInitCheck.h" #include "CrtpConstructorAccessibilityCheck.h" #include "DanglingHandleCheck.h" @@ -127,6 +128,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-chained-comparison"); CheckFactories.registerCheck( "bugprone-compare-pointer-to-member-virtual-function"); +CheckFactories.registerCheck( +"bugprone-conflicting-global-accesses"); CheckFactories.registerCheck( "bugprone-copy-constructor-init"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index e310ea9c94543..f04adca18a5ca 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -16,6 +16,7 @@ add_clang_library(clangTidyBugproneModule STATIC CastingThroughVoidCheck.cpp ChainedComparisonCheck.cpp ComparePointerToMemberVirtualFunctionCheck.cpp + ConflictingGlobalAccessesCheck.cpp CopyConstructorInitCheck.cpp CrtpConstructorAccessibilityCheck.cpp DanglingHandleCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp new file mode 100644 index 0..bb7978af74257 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp @@ -0,0 +1,976 @@ +//===--===// +// +// 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 "ConflictingGlobalAccessesCheck.h" + +#include "clang/AST/RecursiveASTVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +enum AccessKind : uint8_t { + AkRead = 0, + AkWrite, + AkUncheckedRead, + AkUncheckedWrite, + AkLast +}; + +static constexpr uint8_t AkCount = AkLast; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArray represents one field inside a global struct/union system. +// The FieldIndexArray can be thought of as a path inside a tree. +usi
[clang] [llvm] [WIP] Correct lowering of `fp128` intrinsics (PR #76558)
https://github.com/tgross35 updated https://github.com/llvm/llvm-project/pull/76558 >From dafb3a378876db6b3bf505b425b386fd8f79c918 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 11 Aug 2023 22:16:01 -0400 Subject: [PATCH 1/7] [IR] Add a test for `f128` libcall lowering (NFC) `f128` intrinsic functions sometimes lower to `long double` library calls when they instead need to be `f128` versions. Add a test demonstrating current behavior. --- .../CodeGen/Generic/f128-math-lowering.ll | 328 ++ 1 file changed, 328 insertions(+) create mode 100644 llvm/test/CodeGen/Generic/f128-math-lowering.ll diff --git a/llvm/test/CodeGen/Generic/f128-math-lowering.ll b/llvm/test/CodeGen/Generic/f128-math-lowering.ll new file mode 100644 index 0..dfbd1eaeda109 --- /dev/null +++ b/llvm/test/CodeGen/Generic/f128-math-lowering.ll @@ -0,0 +1,328 @@ +; RUN: llc < %s -mtriple=aarch64-unknown-none -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=i686-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=riscv32 -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=s390x-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-S390X +; RUN: llc < %s -mtriple=x86_64-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-NOTLD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-musl -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; +; REQUIRES: aarch64-registered-target +; REQUIRES: riscv-registered-target +; REQUIRES: systemz-registered-target +; REQUIRES: x86-registered-target +; +; Verify that fp128 intrinsics only lower to `long double` calls (e.g. `sinl`) +; on platforms where `f128` and `long double` have the same layout, and +; otherwise lower to `f128` versions (e.g. `sinf128`). +; +; Targets include: +; * x86, x64 (80-bit long double) +; * aarch64 (long double == f128) +; * riscv32 (long double == f64) +; * s390x (long double == f128, hardware support) +; * A couple assorted environments for x86 +; +; FIXME: only targets where long double is `f128` should be using `USELD`, all +; others need to be NOTLD. PowerPC should be added but it currently emits an +; interesting blend of both (e.g. `acosl` but `ceilf128`). + +define fp128 @test_acosf128(fp128 %a) { +; CHECK-LABEL: test_acosf128: +; CHECK-NOTLD: acosf128 +; CHECK-USELD: acosl +; CHECK-S390X: acosl +start: + %0 = tail call fp128 @llvm.acos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_asinf128(fp128 %a) { +; CHECK-LABEL: test_asinf128: +; CHECK-NOTLD: asinf128 +; CHECK-USELD: asinl +; CHECK-S390X: asinl +start: + %0 = tail call fp128 @llvm.asin.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_atanf128(fp128 %a) { +; CHECK-LABEL: test_atanf128: +; CHECK-NOTLD: atanf128 +; CHECK-USELD: atanl +; CHECK-S390X: atanl +start: + %0 = tail call fp128 @llvm.atan.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_ceilf128(fp128 %a) { +; CHECK-LABEL: test_ceilf128: +; CHECK-NOTLD: ceilf128 +; CHECK-USELD: ceill +; CHECK-S390X: ceill +start: + %0 = tail call fp128 @llvm.ceil.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_copysignf128(fp128 %a, fp128 %b) { +; copysign should always get lowered to assembly +; CHECK-LABEL: test_copysignf128: +; CHECK-NOT:copysignl +; CHECK-NOT:copysignf128 +start: + %0 = tail call fp128 @llvm.copysign.f128(fp128 %a, fp128 %b) + ret fp128 %0 +} + +define fp128 @test_cosf128(fp128 %a) { +; CHECK-LABEL: test_cosf128: +; CHECK-NOTLD: cosf128 +; CHECK-USELD: cosl +; CHECK-S390X: cosl +start: + %0 = tail call fp128 @llvm.cos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp10f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp10f128 +; CHECK-USELD: exp10l +; CHECK-S390X: exp10l +start: + %0 = tail call fp128 @llvm.exp10.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp2f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp2f128 +; CHECK-USELD: exp2l +; CHECK-S390X: exp2l +start: + %0 = tail call fp128 @llvm.exp2.f128(fp128 %a) + ret fp128 %0 +} + + +define fp128 @test_expf128(fp128 %a) { +; CHECK-LABEL: test_expf128: +; CHECK-NOTLD: expf128 +; CHECK-USELD: expl +; CHECK-S390X: expl +start: + %0 = tail call fp128 @llvm.exp.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_fabsf128(fp128 %a) { +; fabs should always get lowered to assembly +; CHECK-LABEL: test_fabsf128: +; CHECK-NOT:fabsl +; CHECK-NOT:fabsf128 +start: + %0 = tail call fp128 @llvm.fabs.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_floorf128(fp128 %a) { +; CHECK-LABEL: test
[clang] [CIR] Upstream global initialization for VectorType (PR #137511)
https://github.com/AmrDeveloper created https://github.com/llvm/llvm-project/pull/137511 This change adds global initialization for VectorType Issue https://github.com/llvm/llvm-project/issues/136487 >From 153f0c0daa33b1c71ced4a0f050d49656e72f505 Mon Sep 17 00:00:00 2001 From: AmrDeveloper Date: Sat, 26 Apr 2025 18:43:00 +0200 Subject: [PATCH] [CIR] Upstream global initialization for VectorType --- .../include/clang/CIR/Dialect/IR/CIRAttrs.td | 33 ++- clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp | 23 - clang/lib/CIR/Dialect/IR/CIRAttrs.cpp | 88 +++ clang/lib/CIR/Dialect/IR/CIRDialect.cpp | 2 +- .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 40 +++-- clang/test/CIR/CodeGen/vector-ext.cpp | 11 ++- clang/test/CIR/CodeGen/vector.cpp | 9 ++ 7 files changed, 196 insertions(+), 10 deletions(-) diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td index fb3f7b1632436..624a82762ab18 100644 --- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td +++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td @@ -204,7 +204,7 @@ def ConstArrayAttr : CIR_Attr<"ConstArray", "const_array", [TypedAttrInterface]> }]> ]; - // Printing and parsing available in CIRDialect.cpp + // Printing and parsing available in CIRAttrs.cpp let hasCustomAssemblyFormat = 1; // Enable verifier. @@ -215,6 +215,37 @@ def ConstArrayAttr : CIR_Attr<"ConstArray", "const_array", [TypedAttrInterface]> }]; } +//===--===// +// ConstVectorAttr +//===--===// + +def ConstVectorAttr : CIR_Attr<"ConstVector", "const_vector", + [TypedAttrInterface]> { + let summary = "A constant vector from ArrayAttr"; + let description = [{ +A CIR vector attribute is an array of literals of the specified attribute +types. + }]; + + let parameters = (ins AttributeSelfTypeParameter<"">:$type, + "mlir::ArrayAttr":$elts); + + // Define a custom builder for the type; that removes the need to pass in an + // MLIRContext instance, as it can be inferred from the `type`. + let builders = [ +AttrBuilderWithInferredContext<(ins "cir::VectorType":$type, + "mlir::ArrayAttr":$elts), [{ + return $_get(type.getContext(), type, elts); +}]> + ]; + + // Printing and parsing available in CIRAttrs.cpp + let hasCustomAssemblyFormat = 1; + + // Enable verifier. + let genVerifyDecl = 1; +} + //===--===// // ConstPtrAttr //===--===// diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp index b9a74e90a5960..6e5c7b8fb51f8 100644 --- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp @@ -373,8 +373,27 @@ mlir::Attribute ConstantEmitter::tryEmitPrivate(const APValue &value, elements, typedFiller); } case APValue::Vector: { -cgm.errorNYI("ConstExprEmitter::tryEmitPrivate vector"); -return {}; +const QualType elementType = +destType->castAs()->getElementType(); +const unsigned numElements = value.getVectorLength(); + +SmallVector elements; +elements.reserve(numElements); + +for (unsigned i = 0; i < numElements; ++i) { + const mlir::Attribute element = + tryEmitPrivateForMemory(value.getVectorElt(i), elementType); + if (!element) +return {}; + elements.push_back(element); +} + +const auto desiredVecTy = +mlir::cast(cgm.convertType(destType)); + +return cir::ConstVectorAttr::get( +desiredVecTy, +mlir::ArrayAttr::get(cgm.getBuilder().getContext(), elements)); } case APValue::MemberPointer: { cgm.errorNYI("ConstExprEmitter::tryEmitPrivate member pointer"); diff --git a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp index a8d9f6a0e6e9b..b9b27f33207b8 100644 --- a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp +++ b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp @@ -299,6 +299,94 @@ void ConstArrayAttr::print(AsmPrinter &printer) const { printer << ">"; } +//===--===// +// CIR ConstVectorAttr +//===--===// + +LogicalResult cir::ConstVectorAttr::verify( +function_ref<::mlir::InFlightDiagnostic()> emitError, Type type, +ArrayAttr elts) { + + if (!mlir::isa(type)) { +return emitError() << "type of cir::ConstVectorAttr is not a " + "cir::VectorType: " + << type; + } + + const auto vecType = mlir::cast(type)
[clang] [CIR] Upstream global initialization for VectorType (PR #137511)
llvmbot wrote: @llvm/pr-subscribers-clangir Author: Amr Hesham (AmrDeveloper) Changes This change adds global initialization for VectorType Issue https://github.com/llvm/llvm-project/issues/136487 --- Full diff: https://github.com/llvm/llvm-project/pull/137511.diff 7 Files Affected: - (modified) clang/include/clang/CIR/Dialect/IR/CIRAttrs.td (+32-1) - (modified) clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp (+21-2) - (modified) clang/lib/CIR/Dialect/IR/CIRAttrs.cpp (+88) - (modified) clang/lib/CIR/Dialect/IR/CIRDialect.cpp (+1-1) - (modified) clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp (+35-5) - (modified) clang/test/CIR/CodeGen/vector-ext.cpp (+10-1) - (modified) clang/test/CIR/CodeGen/vector.cpp (+9) ``diff diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td index fb3f7b1632436..624a82762ab18 100644 --- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td +++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td @@ -204,7 +204,7 @@ def ConstArrayAttr : CIR_Attr<"ConstArray", "const_array", [TypedAttrInterface]> }]> ]; - // Printing and parsing available in CIRDialect.cpp + // Printing and parsing available in CIRAttrs.cpp let hasCustomAssemblyFormat = 1; // Enable verifier. @@ -215,6 +215,37 @@ def ConstArrayAttr : CIR_Attr<"ConstArray", "const_array", [TypedAttrInterface]> }]; } +//===--===// +// ConstVectorAttr +//===--===// + +def ConstVectorAttr : CIR_Attr<"ConstVector", "const_vector", + [TypedAttrInterface]> { + let summary = "A constant vector from ArrayAttr"; + let description = [{ +A CIR vector attribute is an array of literals of the specified attribute +types. + }]; + + let parameters = (ins AttributeSelfTypeParameter<"">:$type, + "mlir::ArrayAttr":$elts); + + // Define a custom builder for the type; that removes the need to pass in an + // MLIRContext instance, as it can be inferred from the `type`. + let builders = [ +AttrBuilderWithInferredContext<(ins "cir::VectorType":$type, + "mlir::ArrayAttr":$elts), [{ + return $_get(type.getContext(), type, elts); +}]> + ]; + + // Printing and parsing available in CIRAttrs.cpp + let hasCustomAssemblyFormat = 1; + + // Enable verifier. + let genVerifyDecl = 1; +} + //===--===// // ConstPtrAttr //===--===// diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp index b9a74e90a5960..6e5c7b8fb51f8 100644 --- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp @@ -373,8 +373,27 @@ mlir::Attribute ConstantEmitter::tryEmitPrivate(const APValue &value, elements, typedFiller); } case APValue::Vector: { -cgm.errorNYI("ConstExprEmitter::tryEmitPrivate vector"); -return {}; +const QualType elementType = +destType->castAs()->getElementType(); +const unsigned numElements = value.getVectorLength(); + +SmallVector elements; +elements.reserve(numElements); + +for (unsigned i = 0; i < numElements; ++i) { + const mlir::Attribute element = + tryEmitPrivateForMemory(value.getVectorElt(i), elementType); + if (!element) +return {}; + elements.push_back(element); +} + +const auto desiredVecTy = +mlir::cast(cgm.convertType(destType)); + +return cir::ConstVectorAttr::get( +desiredVecTy, +mlir::ArrayAttr::get(cgm.getBuilder().getContext(), elements)); } case APValue::MemberPointer: { cgm.errorNYI("ConstExprEmitter::tryEmitPrivate member pointer"); diff --git a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp index a8d9f6a0e6e9b..b9b27f33207b8 100644 --- a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp +++ b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp @@ -299,6 +299,94 @@ void ConstArrayAttr::print(AsmPrinter &printer) const { printer << ">"; } +//===--===// +// CIR ConstVectorAttr +//===--===// + +LogicalResult cir::ConstVectorAttr::verify( +function_ref<::mlir::InFlightDiagnostic()> emitError, Type type, +ArrayAttr elts) { + + if (!mlir::isa(type)) { +return emitError() << "type of cir::ConstVectorAttr is not a " + "cir::VectorType: " + << type; + } + + const auto vecType = mlir::cast(type); + + if (vecType.getSize() != elts.size()) { +return emitError() + << "number of constant elements should ma
[clang] [llvm] [mlir] [AMDGPU] Add a new amdgcn.load.to.lds intrinsic (PR #137425)
jayfoad wrote: > This PR adds a amdgns_load_to_lds intrinsic that abstracts over loads to LDS > from global (address space 1) pointers and buffer fat pointers (address space > 7), since they use the same API and "gather from a pointer to LDS" is > something of an abstract operation. High level question: I don't understand why you call this a "gather" operation. What do you mean by that? Isn't it semantically just a memcpy, or a (global/buffer) load followed by a (LDS) store? https://github.com/llvm/llvm-project/pull/137425 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix and test triviality of __ptrauth types (PR #137474)
https://github.com/ojhunt approved this pull request. Good catch, we'll need to add cases to the test when pushing __ptrauth_restricted_intptr https://github.com/llvm/llvm-project/pull/137474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
https://github.com/LorenzoMauro created https://github.com/llvm/llvm-project/pull/137544 Introduce a new FormatStyle option, `ApplyAlwaysOnePerLineToTemplateArguments`, which controls whether `BinPackParameters=AlwaysOnePerLine` also applies to template argument lists. This allows users to enforce one-per-line formatting for function parameters without unintentionally splitting template arguments. Includes unit tests covering function declarations, definitions, and template instantiations, both with and without trailing comments. --- ## Behavior If `BinPackParameters` is set to `AlwaysOnePerLine`, this option controls whether template arguments are split across multiple lines. - When `true`, which is the current only behaviour, each template argument is placed on its own line: ```cpp template struct Foo { T mData[N]; Foo operator+(const Foo &other) const {} Foo bar(const Foo &other, float t) const {} }; ``` - When `false`, template argument lists remain compact even if function parameters are broken one per line: ```cpp template struct Foo { T mData[N]; Foo operator+(const Foo &other) const {} Foo bar(const Foo &other, float t) const {} }; ``` >From 9baa26111acaca5ec2f741aba2f7f4ce9b811c4e Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 27 Apr 2025 20:24:58 +0200 Subject: [PATCH] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option Introduce a new FormatStyle option, ApplyAlwaysOnePerLineToTemplateArguments, which controls whether BinPackParameters=AlwaysOnePerLine also applies to template argument lists. This allows users to enforce one-per-line for function parameters without unintentionally splitting template parameters. Includes unit tests covering both function declarations and definitions, with and without trailing comments. --- clang/include/clang/Format/Format.h | 26 clang/lib/Format/Format.cpp | 3 + clang/lib/Format/FormatToken.h| 13 ++-- clang/lib/Format/TokenAnnotator.cpp | 16 + clang/lib/Format/TokenAnnotator.h | 3 + clang/unittests/Format/ConfigParseTest.cpp| 6 ++ clang/unittests/Format/FormatTest.cpp | 49 +++ clang/unittests/Format/FormatTestComments.cpp | 60 +++ 8 files changed, 171 insertions(+), 5 deletions(-) diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index f6ceef08b46da..81dafb53b1e89 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -1259,6 +1259,30 @@ struct FormatStyle { /// \version 3.7 BinPackParametersStyle BinPackParameters; + /// If ``BinPackParameters`` is set to ``AlwaysOnePerLine``, specifies whether + /// template argument lists should also be split across multiple lines. + /// + /// When set to ``true``, each template argument will be placed on its own + /// line. When set to ``false``, template argument lists remain compact even + /// when function parameters are broken one per line. + /// + /// \code + /// true: + /// template < + /// typename T, + /// typename U> + /// void foo( + /// T a, + /// U b); + /// + /// false: + /// template + /// void foo( + /// T a, + /// U b); + /// \endcode + bool ApplyAlwaysOnePerLineToTemplateArguments = false; + /// Styles for adding spacing around ``:`` in bitfield definitions. enum BitFieldColonSpacingStyle : int8_t { /// Add one space on each side of the ``:`` @@ -5326,6 +5350,8 @@ struct FormatStyle { BinPackArguments == R.BinPackArguments && BinPackLongBracedList == R.BinPackLongBracedList && BinPackParameters == R.BinPackParameters && + ApplyAlwaysOnePerLineToTemplateArguments == + R.ApplyAlwaysOnePerLineToTemplateArguments && BitFieldColonSpacing == R.BitFieldColonSpacing && BracedInitializerIndentWidth == R.BracedInitializerIndentWidth && BreakAdjacentStringLiterals == R.BreakAdjacentStringLiterals && diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 5a1c3f556b331..13f3bc3db3cdc 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1007,6 +1007,8 @@ template <> struct MappingTraits { IO.mapOptional("BinPackArguments", Style.BinPackArguments); IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList); IO.mapOptional("BinPackParameters", Style.BinPackParameters); +IO.mapOptional("ApplyAlwaysOnePerLineToTemplateArguments", + Style.ApplyAlwaysOnePerLineToTemplateArguments); IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing); IO.mapOptional("BracedInitializerIndentWidth", Style.BracedInitializerIndentWidth); @@ -1521,6 +1523,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) { LLVMStyle.BinPackArguments = tr
[clang] [Clang][CodeGen][X86] don't coerce int128 into `{i64,i64}` for SysV-like ABIs (PR #135230)
https://github.com/T0b1-iOS updated https://github.com/llvm/llvm-project/pull/135230 >From f0bb89e5cfe2739dc51faef64215251cfe1516d4 Mon Sep 17 00:00:00 2001 From: T0b1 Date: Thu, 10 Apr 2025 19:16:00 +0200 Subject: [PATCH 1/2] [Clang][CodeGen][X86] don't coerce int128 into `{i64,i64}` for SysV-like ABIs --- clang/lib/CodeGen/Targets/X86.cpp | 18 +++ clang/test/CodeGen/X86/i128-debuginfo.c | 10 clang/test/CodeGen/X86/x86_64-arguments.c | 21 clang/test/CodeGen/alloc-align-attr.c | 58 +++ clang/test/CodeGen/builtins.c | 18 ++- clang/test/CodeGen/extend-arg-64.c| 2 +- 6 files changed, 70 insertions(+), 57 deletions(-) create mode 100644 clang/test/CodeGen/X86/i128-debuginfo.c diff --git a/clang/lib/CodeGen/Targets/X86.cpp b/clang/lib/CodeGen/Targets/X86.cpp index b36a6e1396653..aa4ab1c2e5490 100644 --- a/clang/lib/CodeGen/Targets/X86.cpp +++ b/clang/lib/CodeGen/Targets/X86.cpp @@ -2595,6 +2595,14 @@ GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, ABIArgInfo X86_64ABIInfo:: classifyReturnType(QualType RetTy) const { + // return int128 as i128 + if (const BuiltinType *BT = RetTy->getAs()) { +BuiltinType::Kind k = BT->getKind(); +if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { + return ABIArgInfo::getDirect(); +} + } + // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the // classification algorithm. X86_64ABIInfo::Class Lo, Hi; @@ -2727,6 +2735,16 @@ X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs, bool isNamedArg, bool IsRegCall) const { Ty = useFirstFieldIfTransparentUnion(Ty); + // represent int128 as i128 + if (const BuiltinType *BT = Ty->getAs()) { +BuiltinType::Kind k = BT->getKind(); +if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { + neededInt = 2; + neededSSE = 0; + return ABIArgInfo::getDirect(); +} + } + X86_64ABIInfo::Class Lo, Hi; classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall); diff --git a/clang/test/CodeGen/X86/i128-debuginfo.c b/clang/test/CodeGen/X86/i128-debuginfo.c new file mode 100644 index 0..4b865c1bed9f0 --- /dev/null +++ b/clang/test/CodeGen/X86/i128-debuginfo.c @@ -0,0 +1,10 @@ +// no autogeneration since update_cc_test_checks does not support -g +// RUN: %clang_cc1 -triple x86_64-pc-linux -O1 -debug-info-kind=limited -emit-llvm -o - %s | FileCheck %s + +// CHECK-LABEL: define{{.*}} i128 @add(i128 noundef %a) +// CHECK: #dbg_value(i128 %a, ![[DI:.*]], !DIExpression() +__int128_t add(__int128_t a) { + return a + a; +} + +// CHECK: ![[DI]] = !DILocalVariable(name: "a", arg: 1 diff --git a/clang/test/CodeGen/X86/x86_64-arguments.c b/clang/test/CodeGen/X86/x86_64-arguments.c index 82845f0a2b31f..fd73fbaa8e54f 100644 --- a/clang/test/CodeGen/X86/x86_64-arguments.c +++ b/clang/test/CodeGen/X86/x86_64-arguments.c @@ -551,6 +551,27 @@ struct s68 { void f68(struct s68 x) { } +// CHECK-LABEL: define{{.*}} i128 @f69(i128 noundef %a) +__int128_t f69(__int128_t a) { + return a; +} + +// CHECK-LABEL: define{{.*}} i128 @f70(i128 noundef %a) +__uint128_t f70(__uint128_t a) { + return a; +} + +// check that registers are correctly counted for (u)int128_t arguments +struct s71 { + long long a, b; +}; +// CHECK-LABEL: define{{.*}} void @f71(i128 noundef %a, i128 noundef %b, i64 noundef %c, ptr noundef byval(%struct.s71) align 8 %d) +void f71(__int128_t a, __int128_t b, long long c, struct s71 d) { +} +// CHECK-LABEL: define{{.*}} void @f72(i128 noundef %a, i128 noundef %b, i64 %d.coerce0, i64 %d.coerce1) +void f72(__int128_t a, __int128_t b, struct s71 d) { +} + /// The synthesized __va_list_tag does not have file/line fields. // CHECK: = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "__va_list_tag", // CHECK-NOT: file: diff --git a/clang/test/CodeGen/alloc-align-attr.c b/clang/test/CodeGen/alloc-align-attr.c index 76e5d1041b19f..c4c4e76eaaa04 100644 --- a/clang/test/CodeGen/alloc-align-attr.c +++ b/clang/test/CodeGen/alloc-align-attr.c @@ -70,66 +70,42 @@ __INT32_TYPE__ test4(__SIZE_TYPE__ a) { struct Empty {}; struct MultiArgs { __INT64_TYPE__ a, b;}; -// Struct parameter doesn't take up an IR parameter, 'i' takes up 2. +// Struct parameter doesn't take up an IR parameter, 'i' takes up 1. // Truncation to i64 is permissible, since alignments of greater than 2^64 are insane. __INT32_TYPE__ *m3(struct Empty s, __int128_t i) __attribute__((alloc_align(2))); // CHECK-LABEL: @test5( // CHECK-NEXT: entry: -// CHECK-NEXT:[[A:%.*]] = alloca i128, align 16 // CHECK-NEXT:[[A_ADDR:%.*]] = alloca i128, align 16 // CHECK-NEXT:[[E:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1 -// CHECK-NEXT:[[COERCE:%.*]] = alloca i128, align 16 -// CHECK-NEXT:[[TMP0:%.*]] = getelementptr inbounds nuw { i64, i64 }, ptr [[A]], i32 0, i32 0 -// CHECK-NEXT:store i64 [[A_COERCE0:%.*
[clang] [Clang][CodeGen][X86] don't coerce int128 into `{i64,i64}` for SysV-like ABIs (PR #135230)
@@ -2595,6 +2595,14 @@ GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, ABIArgInfo X86_64ABIInfo:: classifyReturnType(QualType RetTy) const { + // return int128 as i128 + if (const BuiltinType *BT = RetTy->getAs()) { +BuiltinType::Kind k = BT->getKind(); +if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { + return ABIArgInfo::getDirect(); +} + } + // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the // classification algorithm. X86_64ABIInfo::Class Lo, Hi; T0b1-iOS wrote: I changed GetINTEGERTypeAtOffset to return an i128 when appropriate. That also causes _BitInt(128) to be passed as an i128 but that should be fine as long as it doesn't change how it is passed on the stack. https://github.com/llvm/llvm-project/pull/135230 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] Check nullity before calling IgnoreParenCasts. (PR #137556)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: Ryosuke Niwa (rniwa) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/137556.diff 1 Files Affected: - (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp (+2-1) ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp index bba1d48e6db11..34c98daa78049 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp @@ -444,9 +444,10 @@ class RetainPtrCtorAdoptChecker return false; if (!ObjCMsgExpr->isInstanceMessage()) return false; -auto *Receiver = ObjCMsgExpr->getInstanceReceiver()->IgnoreParenCasts(); +auto *Receiver = ObjCMsgExpr->getInstanceReceiver(); if (!Receiver) return false; +Receiver = Receiver->IgnoreParenCasts(); if (auto *Inner = dyn_cast(Receiver)) { if (InnerExpr) *InnerExpr = Inner; `` https://github.com/llvm/llvm-project/pull/137556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (PR #135329)
rniwa wrote: Oops, fixing the assertion failure in https://github.com/llvm/llvm-project/pull/137556. https://github.com/llvm/llvm-project/pull/135329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [llvm] [mlir] [NFC] Use more isa and isa_and_nonnull instead dyn_cast for predicates (PR #137393)
steakhal wrote: > Nice cleanups! > > Do we have clang-tidy checks for these? It would be nice for tooling to take > care of all this. There is a Static Analyzer checker, but I'm not exactly sure if it would catch this of the top of my head. See [alpha.llvm.Conventions](https://clang.llvm.org/docs/analyzer/checkers.html#id178) I think the Static Analyzer is anyway overkill for checking this, probably an easy clang-tidy check would be better for looking for implicit conversions to bool of a CallExpr of `dyn_cast`. One could implement it in a matter of hours. https://github.com/llvm/llvm-project/pull/137393 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] [AMDGPU] Add a new amdgcn.load.to.lds intrinsic (PR #137425)
kuhar wrote: > High level question: I don't understand why you call this a "gather" > operation. What do you mean by that? Isn't it semantically just a memcpy, or > a (global/buffer) load followed by a (LDS) store? This is more like a subgroup operation because the destination offset is uniform. https://github.com/llvm/llvm-project/pull/137425 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -1259,6 +1259,45 @@ struct FormatStyle { /// \version 3.7 BinPackParametersStyle BinPackParameters; + /// If ``BinPackParameters`` is set to ``AlwaysOnePerLine``, specifies whether + /// template argument lists should also be split across multiple lines. + /// + /// When set to ``true``, each template argument will be placed on its own + /// line. When set to ``false``, template argument lists remain compact even + /// when function parameters are broken one per line. + /// + /// \code + /// true: + /// template + /// struct Foo { + /// T mData[N]; + /// + /// Foo + /// operator+(const Foo &other) const {} + /// + /// Foo + /// bar(const Foo &other, + /// float t) const {} + /// }; + /// + /// false: + /// template + /// struct Foo { + /// T mData[N]; + /// + /// Foo operator+(const Foo &other) const {} + /// + /// Foo bar(const Foo &other, + /// float t) const {} + /// }; + /// \endcode + /// \version 21 + bool ApplyAlwaysOnePerLineToTemplateArguments; HazardyKnusperkeks wrote: Please sort alphabetically. https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -9024,6 +9024,55 @@ TEST_F(FormatTest, FormatsDeclarationBreakAlways) { BreakAlways); } +TEST_F(FormatTest, ApplyAlwaysOnePerLineToTemplateArguments) { + FormatStyle Style = getGoogleStyle(); HazardyKnusperkeks wrote: Why google style? https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -5326,6 +5365,8 @@ struct FormatStyle { BinPackArguments == R.BinPackArguments && BinPackLongBracedList == R.BinPackLongBracedList && BinPackParameters == R.BinPackParameters && + ApplyAlwaysOnePerLineToTemplateArguments == HazardyKnusperkeks wrote: Also sorting. https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -186,6 +186,9 @@ class AnnotatedLine { bool MightBeFunctionDecl; bool IsMultiVariableDeclStmt; + /// \c True if this token is part o a template declaration. + bool InTemplateDecl = false; HazardyKnusperkeks wrote: A leftover? https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] Check nullity before calling IgnoreParenCasts. (PR #137556)
https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/137556 None >From 46d5c45c4c7a6abe0255aa31e2c7435d7f3e8289 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Sun, 27 Apr 2025 15:16:40 -0700 Subject: [PATCH] [alpha.webkit.RetainPtrCtorAdoptChecker] Check nullity before calling IgnoreParenCasts. --- .../Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp index bba1d48e6db11..34c98daa78049 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp @@ -444,9 +444,10 @@ class RetainPtrCtorAdoptChecker return false; if (!ObjCMsgExpr->isInstanceMessage()) return false; -auto *Receiver = ObjCMsgExpr->getInstanceReceiver()->IgnoreParenCasts(); +auto *Receiver = ObjCMsgExpr->getInstanceReceiver(); if (!Receiver) return false; +Receiver = Receiver->IgnoreParenCasts(); if (auto *Inner = dyn_cast(Receiver)) { if (InnerExpr) *InnerExpr = Inner; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -444,6 +444,66 @@ TEST_F(FormatTestComments, UnderstandsBlockComments) { " int jjj; /*b*/"); } +TEST_F(FormatTestComments, HazardyKnusperkeks wrote: What's your reason for this test? You didn't change anything comment related, right? https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -1259,6 +1259,45 @@ struct FormatStyle { /// \version 3.7 BinPackParametersStyle BinPackParameters; + /// If ``BinPackParameters`` is set to ``AlwaysOnePerLine``, specifies whether HazardyKnusperkeks wrote: Add a reference on `BinPackParameters` to this one. https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
@@ -2074,6 +2087,7 @@ class AnnotatingParser { if (ctx.ContextType == Context::StructArrayInitializer) return LT_ArrayOfStructInitializer; +markTokenAsTemplateArgumentInLine(); HazardyKnusperkeks wrote: I think you want this before the preceding loop. And can you get it into the first pass of the line? Just going through all tokens again doesn't seem nice. https://github.com/llvm/llvm-project/pull/137544 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Analysis] Remove has_arg_iterator_range (NFC) (PR #137568)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/137568 The last use was removed by: commit f8afb8fdedae04ad2670857c97925c439d47d862 Author: Aaron Puchert Date: Fri Apr 29 22:12:21 2022 +0200 >From dc12390ff2cb857ce68fd75c5e0c1e2536c1ef67 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sun, 27 Apr 2025 17:09:56 -0700 Subject: [PATCH] [Analysis] Remove has_arg_iterator_range (NFC) The last use was removed by: commit f8afb8fdedae04ad2670857c97925c439d47d862 Author: Aaron Puchert Date: Fri Apr 29 22:12:21 2022 +0200 --- clang/lib/Analysis/ThreadSafety.cpp | 19 --- 1 file changed, 19 deletions(-) diff --git a/clang/lib/Analysis/ThreadSafety.cpp b/clang/lib/Analysis/ThreadSafety.cpp index 42fb0fe7dcdaa..f50c2adda4bc0 100644 --- a/clang/lib/Analysis/ThreadSafety.cpp +++ b/clang/lib/Analysis/ThreadSafety.cpp @@ -1231,25 +1231,6 @@ static const ValueDecl *getValueDecl(const Expr *Exp) { return nullptr; } -namespace { - -template -class has_arg_iterator_range { - using yes = char[1]; - using no = char[2]; - - template - static yes& test(Inner *I, decltype(I->args()) * = nullptr); - - template - static no& test(...); - -public: - static const bool value = sizeof(test(nullptr)) == sizeof(yes); -}; - -} // namespace - bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { const threadSafety::til::SExpr *SExp = CapE.sexpr(); assert(SExp && "Null expressions should be ignored"); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Analysis] Remove has_arg_iterator_range (NFC) (PR #137568)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes The last use was removed by: commit f8afb8fdedae04ad2670857c97925c439d47d862 Author: Aaron PuchertDate: Fri Apr 29 22:12:21 2022 +0200 --- Full diff: https://github.com/llvm/llvm-project/pull/137568.diff 1 Files Affected: - (modified) clang/lib/Analysis/ThreadSafety.cpp (-19) ``diff diff --git a/clang/lib/Analysis/ThreadSafety.cpp b/clang/lib/Analysis/ThreadSafety.cpp index 42fb0fe7dcdaa..f50c2adda4bc0 100644 --- a/clang/lib/Analysis/ThreadSafety.cpp +++ b/clang/lib/Analysis/ThreadSafety.cpp @@ -1231,25 +1231,6 @@ static const ValueDecl *getValueDecl(const Expr *Exp) { return nullptr; } -namespace { - -template -class has_arg_iterator_range { - using yes = char[1]; - using no = char[2]; - - template - static yes& test(Inner *I, decltype(I->args()) * = nullptr); - - template - static no& test(...); - -public: - static const bool value = sizeof(test(nullptr)) == sizeof(yes); -}; - -} // namespace - bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { const threadSafety::til::SExpr *SExp = CapE.sexpr(); assert(SExp && "Null expressions should be ignored"); `` https://github.com/llvm/llvm-project/pull/137568 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Analysis] Remove has_arg_iterator_range (NFC) (PR #137568)
llvmbot wrote: @llvm/pr-subscribers-clang-analysis Author: Kazu Hirata (kazutakahirata) Changes The last use was removed by: commit f8afb8fdedae04ad2670857c97925c439d47d862 Author: Aaron PuchertDate: Fri Apr 29 22:12:21 2022 +0200 --- Full diff: https://github.com/llvm/llvm-project/pull/137568.diff 1 Files Affected: - (modified) clang/lib/Analysis/ThreadSafety.cpp (-19) ``diff diff --git a/clang/lib/Analysis/ThreadSafety.cpp b/clang/lib/Analysis/ThreadSafety.cpp index 42fb0fe7dcdaa..f50c2adda4bc0 100644 --- a/clang/lib/Analysis/ThreadSafety.cpp +++ b/clang/lib/Analysis/ThreadSafety.cpp @@ -1231,25 +1231,6 @@ static const ValueDecl *getValueDecl(const Expr *Exp) { return nullptr; } -namespace { - -template -class has_arg_iterator_range { - using yes = char[1]; - using no = char[2]; - - template - static yes& test(Inner *I, decltype(I->args()) * = nullptr); - - template - static no& test(...); - -public: - static const bool value = sizeof(test(nullptr)) == sizeof(yes); -}; - -} // namespace - bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { const threadSafety::til::SExpr *SExp = CapE.sexpr(); assert(SExp && "Null expressions should be ignored"); `` https://github.com/llvm/llvm-project/pull/137568 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Analysis] Remove has_arg_iterator_range (NFC) (PR #137568)
https://github.com/kuhar approved this pull request. https://github.com/llvm/llvm-project/pull/137568 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add ApplyAlwaysOnePerLineToTemplateArguments option (PR #137544)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Lorenzo Mauro (LorenzoMauro) Changes Introduce a new FormatStyle option, `ApplyAlwaysOnePerLineToTemplateArguments`, which controls whether `BinPackParameters=AlwaysOnePerLine` also applies to template argument lists. This allows users to enforce one-per-line formatting for function parameters without unintentionally splitting template arguments. Includes unit tests covering function declarations, definitions, and template instantiations, both with and without trailing comments. --- ## Behavior If `BinPackParameters` is set to `AlwaysOnePerLine`, this option controls whether template arguments are split across multiple lines. - When `true`, which is the current only behaviour, each template argument is placed on its own line: ```cpp templatestruct Foo { T mData[N]; Foo operator+(const Foo &other) const {} Foo bar(const Foo &other, float t) const {} }; ``` - When `false`, template argument lists remain compact even if function parameters are broken one per line: ```cpp template struct Foo { T mData[N]; Foo operator+(const Foo &other) const {} Foo bar(const Foo &other, float t) const {} }; ``` --- Full diff: https://github.com/llvm/llvm-project/pull/137544.diff 8 Files Affected: - (modified) clang/include/clang/Format/Format.h (+26) - (modified) clang/lib/Format/Format.cpp (+3) - (modified) clang/lib/Format/FormatToken.h (+8-5) - (modified) clang/lib/Format/TokenAnnotator.cpp (+16) - (modified) clang/lib/Format/TokenAnnotator.h (+3) - (modified) clang/unittests/Format/ConfigParseTest.cpp (+6) - (modified) clang/unittests/Format/FormatTest.cpp (+49) - (modified) clang/unittests/Format/FormatTestComments.cpp (+60) ``diff diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index f6ceef08b46da..81dafb53b1e89 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -1259,6 +1259,30 @@ struct FormatStyle { /// \version 3.7 BinPackParametersStyle BinPackParameters; + /// If ``BinPackParameters`` is set to ``AlwaysOnePerLine``, specifies whether + /// template argument lists should also be split across multiple lines. + /// + /// When set to ``true``, each template argument will be placed on its own + /// line. When set to ``false``, template argument lists remain compact even + /// when function parameters are broken one per line. + /// + /// \code + /// true: + /// template < + /// typename T, + /// typename U> + /// void foo( + /// T a, + /// U b); + /// + /// false: + /// template + /// void foo( + /// T a, + /// U b); + /// \endcode + bool ApplyAlwaysOnePerLineToTemplateArguments = false; + /// Styles for adding spacing around ``:`` in bitfield definitions. enum BitFieldColonSpacingStyle : int8_t { /// Add one space on each side of the ``:`` @@ -5326,6 +5350,8 @@ struct FormatStyle { BinPackArguments == R.BinPackArguments && BinPackLongBracedList == R.BinPackLongBracedList && BinPackParameters == R.BinPackParameters && + ApplyAlwaysOnePerLineToTemplateArguments == + R.ApplyAlwaysOnePerLineToTemplateArguments && BitFieldColonSpacing == R.BitFieldColonSpacing && BracedInitializerIndentWidth == R.BracedInitializerIndentWidth && BreakAdjacentStringLiterals == R.BreakAdjacentStringLiterals && diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 5a1c3f556b331..13f3bc3db3cdc 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1007,6 +1007,8 @@ template <> struct MappingTraits { IO.mapOptional("BinPackArguments", Style.BinPackArguments); IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList); IO.mapOptional("BinPackParameters", Style.BinPackParameters); +IO.mapOptional("ApplyAlwaysOnePerLineToTemplateArguments", + Style.ApplyAlwaysOnePerLineToTemplateArguments); IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing); IO.mapOptional("BracedInitializerIndentWidth", Style.BracedInitializerIndentWidth); @@ -1521,6 +1523,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) { LLVMStyle.BinPackArguments = true; LLVMStyle.BinPackLongBracedList = true; LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack; + LLVMStyle.ApplyAlwaysOnePerLineToTemplateArguments = true; LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both; LLVMStyle.BracedInitializerIndentWidth = -1; LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false, diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 946cd7b81587f..7f15c48f15bc3 100644 --
[clang] [Clang][CodeGen][X86] don't coerce int128 into `{i64,i64}` for SysV-like ABIs (PR #135230)
https://github.com/T0b1-iOS updated https://github.com/llvm/llvm-project/pull/135230 >From f0bb89e5cfe2739dc51faef64215251cfe1516d4 Mon Sep 17 00:00:00 2001 From: T0b1 Date: Thu, 10 Apr 2025 19:16:00 +0200 Subject: [PATCH 1/3] [Clang][CodeGen][X86] don't coerce int128 into `{i64,i64}` for SysV-like ABIs --- clang/lib/CodeGen/Targets/X86.cpp | 18 +++ clang/test/CodeGen/X86/i128-debuginfo.c | 10 clang/test/CodeGen/X86/x86_64-arguments.c | 21 clang/test/CodeGen/alloc-align-attr.c | 58 +++ clang/test/CodeGen/builtins.c | 18 ++- clang/test/CodeGen/extend-arg-64.c| 2 +- 6 files changed, 70 insertions(+), 57 deletions(-) create mode 100644 clang/test/CodeGen/X86/i128-debuginfo.c diff --git a/clang/lib/CodeGen/Targets/X86.cpp b/clang/lib/CodeGen/Targets/X86.cpp index b36a6e1396653..aa4ab1c2e5490 100644 --- a/clang/lib/CodeGen/Targets/X86.cpp +++ b/clang/lib/CodeGen/Targets/X86.cpp @@ -2595,6 +2595,14 @@ GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, ABIArgInfo X86_64ABIInfo:: classifyReturnType(QualType RetTy) const { + // return int128 as i128 + if (const BuiltinType *BT = RetTy->getAs()) { +BuiltinType::Kind k = BT->getKind(); +if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { + return ABIArgInfo::getDirect(); +} + } + // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the // classification algorithm. X86_64ABIInfo::Class Lo, Hi; @@ -2727,6 +2735,16 @@ X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs, bool isNamedArg, bool IsRegCall) const { Ty = useFirstFieldIfTransparentUnion(Ty); + // represent int128 as i128 + if (const BuiltinType *BT = Ty->getAs()) { +BuiltinType::Kind k = BT->getKind(); +if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { + neededInt = 2; + neededSSE = 0; + return ABIArgInfo::getDirect(); +} + } + X86_64ABIInfo::Class Lo, Hi; classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall); diff --git a/clang/test/CodeGen/X86/i128-debuginfo.c b/clang/test/CodeGen/X86/i128-debuginfo.c new file mode 100644 index 0..4b865c1bed9f0 --- /dev/null +++ b/clang/test/CodeGen/X86/i128-debuginfo.c @@ -0,0 +1,10 @@ +// no autogeneration since update_cc_test_checks does not support -g +// RUN: %clang_cc1 -triple x86_64-pc-linux -O1 -debug-info-kind=limited -emit-llvm -o - %s | FileCheck %s + +// CHECK-LABEL: define{{.*}} i128 @add(i128 noundef %a) +// CHECK: #dbg_value(i128 %a, ![[DI:.*]], !DIExpression() +__int128_t add(__int128_t a) { + return a + a; +} + +// CHECK: ![[DI]] = !DILocalVariable(name: "a", arg: 1 diff --git a/clang/test/CodeGen/X86/x86_64-arguments.c b/clang/test/CodeGen/X86/x86_64-arguments.c index 82845f0a2b31f..fd73fbaa8e54f 100644 --- a/clang/test/CodeGen/X86/x86_64-arguments.c +++ b/clang/test/CodeGen/X86/x86_64-arguments.c @@ -551,6 +551,27 @@ struct s68 { void f68(struct s68 x) { } +// CHECK-LABEL: define{{.*}} i128 @f69(i128 noundef %a) +__int128_t f69(__int128_t a) { + return a; +} + +// CHECK-LABEL: define{{.*}} i128 @f70(i128 noundef %a) +__uint128_t f70(__uint128_t a) { + return a; +} + +// check that registers are correctly counted for (u)int128_t arguments +struct s71 { + long long a, b; +}; +// CHECK-LABEL: define{{.*}} void @f71(i128 noundef %a, i128 noundef %b, i64 noundef %c, ptr noundef byval(%struct.s71) align 8 %d) +void f71(__int128_t a, __int128_t b, long long c, struct s71 d) { +} +// CHECK-LABEL: define{{.*}} void @f72(i128 noundef %a, i128 noundef %b, i64 %d.coerce0, i64 %d.coerce1) +void f72(__int128_t a, __int128_t b, struct s71 d) { +} + /// The synthesized __va_list_tag does not have file/line fields. // CHECK: = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "__va_list_tag", // CHECK-NOT: file: diff --git a/clang/test/CodeGen/alloc-align-attr.c b/clang/test/CodeGen/alloc-align-attr.c index 76e5d1041b19f..c4c4e76eaaa04 100644 --- a/clang/test/CodeGen/alloc-align-attr.c +++ b/clang/test/CodeGen/alloc-align-attr.c @@ -70,66 +70,42 @@ __INT32_TYPE__ test4(__SIZE_TYPE__ a) { struct Empty {}; struct MultiArgs { __INT64_TYPE__ a, b;}; -// Struct parameter doesn't take up an IR parameter, 'i' takes up 2. +// Struct parameter doesn't take up an IR parameter, 'i' takes up 1. // Truncation to i64 is permissible, since alignments of greater than 2^64 are insane. __INT32_TYPE__ *m3(struct Empty s, __int128_t i) __attribute__((alloc_align(2))); // CHECK-LABEL: @test5( // CHECK-NEXT: entry: -// CHECK-NEXT:[[A:%.*]] = alloca i128, align 16 // CHECK-NEXT:[[A_ADDR:%.*]] = alloca i128, align 16 // CHECK-NEXT:[[E:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1 -// CHECK-NEXT:[[COERCE:%.*]] = alloca i128, align 16 -// CHECK-NEXT:[[TMP0:%.*]] = getelementptr inbounds nuw { i64, i64 }, ptr [[A]], i32 0, i32 0 -// CHECK-NEXT:store i64 [[A_COERCE0:%.*
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (PR #135329)
https://github.com/t-rasmud approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/135329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (PR #135329)
rniwa wrote: Thanks for the review! https://github.com/llvm/llvm-project/pull/135329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 16e5c3d - [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (#135329)
Author: Ryosuke Niwa Date: 2025-04-27T14:24:32-07:00 New Revision: 16e5c3ddadaa8d25698a71c0308b1d0ca887d11f URL: https://github.com/llvm/llvm-project/commit/16e5c3ddadaa8d25698a71c0308b1d0ca887d11f DIFF: https://github.com/llvm/llvm-project/commit/16e5c3ddadaa8d25698a71c0308b1d0ca887d11f.diff LOG: [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (#135329) This PR implements various small enhancements to alpha.webkit.RetainPtrCtorAdoptChecker: - Detect leaks from [[X alloc] init] when ARC is disabled. - Detect leaks from calling Create, Copy, and other +1 CF functions. - Recognize [allocX() init] pattern where allocX is a C/C++ function. - Recognize _init in addition to init as an init function. - Recognize [[[X alloc] init] autorelease]. - Recognize CFBridgingRelease. - Support CF_RETRUNS_RETAINED on out arguments of a C function. - Support returning +1 object in Create, Copy, and other +1 functions or +1 selectors. - Support variadic Create, Copy, and other +1 C/C++ functions. To make these enhancements, this PR introduces new visit functions for ObjCMessageExpr, ReturnStmt, VarDecl, and BinaryOperator. These functions look for a specific construct mentioned above and adds an expression such as [[X alloc] init] or CreateX to a DenseSet CreateOrCopyFnCall when the expression does not result in leaks. When the code to detect leaks such as the one in visitObjCMessageExpr later encounters this expression, it can bail out early if the expression is in the set. Added: Modified: clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp clang/test/Analysis/Checkers/WebKit/objc-mock-types.h clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm Removed: diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp index d3eee11311d91..bba1d48e6db11 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RetainPtrCtorAdoptChecker.cpp @@ -12,6 +12,7 @@ #include "clang/AST/CXXInheritance.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/StmtVisitor.h" +#include "clang/Analysis/DomainSpecific/CocoaConventions.h" #include "clang/Analysis/RetainSummaryManager.h" #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" @@ -90,6 +91,26 @@ class RetainPtrCtorAdoptChecker Checker->visitConstructExpr(CE, DeclWithIssue); return true; } + + bool VisitObjCMessageExpr(const ObjCMessageExpr *ObjCMsgExpr) { +Checker->visitObjCMessageExpr(ObjCMsgExpr, DeclWithIssue); +return true; + } + + bool VisitReturnStmt(const ReturnStmt *RS) { +Checker->visitReturnStmt(RS, DeclWithIssue); +return true; + } + + bool VisitVarDecl(const VarDecl *VD) { +Checker->visitVarDecl(VD); +return true; + } + + bool VisitBinaryOperator(const BinaryOperator *BO) { +Checker->visitBinaryOperator(BO); +return true; + } }; LocalVisitor visitor(this); @@ -101,13 +122,14 @@ class RetainPtrCtorAdoptChecker } bool isAdoptFn(const Decl *FnDecl) const { -auto Name = safeGetName(FnDecl); -return Name == "adoptNS" || Name == "adoptCF" || Name == "adoptNSArc" || - Name == "adoptCFArc"; +return isAdoptFnName(safeGetName(FnDecl)); } - bool isAdoptNS(const Decl *FnDecl) const { -auto Name = safeGetName(FnDecl); + bool isAdoptFnName(const std::string &Name) const { +return isAdoptNS(Name) || Name == "adoptCF" || Name == "adoptCFArc"; + } + + bool isAdoptNS(const std::string &Name) const { return Name == "adoptNS" || Name == "adoptNSArc"; } @@ -116,44 +138,104 @@ class RetainPtrCtorAdoptChecker if (BR->getSourceManager().isInSystemHeader(CE->getExprLoc())) return; -auto *F = CE->getDirectCallee(); -if (!F) +std::string FnName; +if (auto *F = CE->getDirectCallee()) { + FnName = safeGetName(F); + if (isAdoptFnName(FnName)) +checkAdoptCall(CE, FnName, DeclWithIssue); + else { +checkCreateOrCopyFunction(CE, DeclWithIssue); +checkBridgingRelease(CE, F, DeclWithIssue); + } return; +} -if (!isAdoptFn(F) || !CE->getNumArgs()) { - checkCreateOrCopyFunction(CE, F, DeclWithIssue); +auto *CalleeExpr = CE->getCallee(); +if (!CalleeExpr) return; +CalleeExpr = CalleeExpr->IgnoreParenCasts(); +if (auto *UnresolvedExpr = dyn_cast(CalleeExpr)) { + auto Name = UnresolvedExpr->getName(); + if (!Name.isIdentifier()) +return; + FnName = Name.getAsStri
[clang] [alpha.webkit.RetainPtrCtorAdoptChecker] An assortment of small enhancements (PR #135329)
https://github.com/rniwa closed https://github.com/llvm/llvm-project/pull/135329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support ptr to ptr and union in webkit member checker (PR #137565)
https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/137565 None >From 9d6c807a5d7b853876132be0668357f6945978af Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Sun, 20 Apr 2025 18:38:31 -0700 Subject: [PATCH 1/2] [RawPtrRefMemberChecker] Make RawPtrRefMemberChecker consistent with other checkers Refactor RawPtrRefMemberChecker so that each subclass override isUnsafePtr like other WebKit checkers instead of overriding isPtrCompatible. --- .../WebKit/RawPtrRefMemberChecker.cpp | 98 +-- 1 file changed, 45 insertions(+), 53 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp index 10b9749319a57..209073e3ccc3a 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp @@ -38,9 +38,7 @@ class RawPtrRefMemberChecker RawPtrRefMemberChecker(const char *description) : Bug(this, description, "WebKit coding guidelines") {} - virtual std::optional - isPtrCompatible(const clang::QualType, - const clang::CXXRecordDecl *R) const = 0; + virtual std::optional isUnsafePtr(QualType) const = 0; virtual const char *typeName() const = 0; virtual const char *invariant() const = 0; @@ -93,22 +91,30 @@ class RawPtrRefMemberChecker if (!MemberType) continue; - if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) { -std::optional IsCompatible = isPtrCompatible(QT, MemberCXXRD); -if (IsCompatible && *IsCompatible) - reportBug(Member, MemberType, MemberCXXRD, RD); - } else { -std::optional IsCompatible = isPtrCompatible(QT, nullptr); -auto *PointeeType = MemberType->getPointeeType().getTypePtrOrNull(); -if (IsCompatible && *IsCompatible) { - auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); - if (auto *ObjCType = dyn_cast_or_null(Desugared)) -reportBug(Member, MemberType, ObjCType->getDecl(), RD); -} - } + auto IsUnsafePtr = isUnsafePtr(QT); + if (!IsUnsafePtr || !*IsUnsafePtr) +continue; + + if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) +reportBug(Member, MemberType, MemberCXXRD, RD); + else if (auto* ObjCDecl = getObjCDecl(MemberType)) +reportBug(Member, MemberType, ObjCDecl, RD); } } + ObjCInterfaceDecl* getObjCDecl(const Type *TypePtr) const { +auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull(); +if (!PointeeType) + return nullptr; +auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); +if (!Desugared) + return nullptr; +auto *ObjCType = dyn_cast(Desugared); +if (!ObjCType) + return nullptr; +return ObjCType->getDecl(); + } + void visitObjCDecl(const ObjCContainerDecl *CD) const { if (BR->getSourceManager().isInSystemHeader(CD->getLocation())) return; @@ -138,19 +144,15 @@ class RawPtrRefMemberChecker const Type *IvarType = QT.getTypePtrOrNull(); if (!IvarType) return; -if (auto *IvarCXXRD = IvarType->getPointeeCXXRecordDecl()) { - std::optional IsCompatible = isPtrCompatible(QT, IvarCXXRD); - if (IsCompatible && *IsCompatible) -reportBug(Ivar, IvarType, IvarCXXRD, CD); -} else { - std::optional IsCompatible = isPtrCompatible(QT, nullptr); - auto *PointeeType = IvarType->getPointeeType().getTypePtrOrNull(); - if (IsCompatible && *IsCompatible) { -auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); -if (auto *ObjCType = dyn_cast_or_null(Desugared)) - reportBug(Ivar, IvarType, ObjCType->getDecl(), CD); - } -} + +auto IsUnsafePtr = isUnsafePtr(QT); +if (!IsUnsafePtr || !*IsUnsafePtr) + return; + +if (auto *MemberCXXRD = IvarType->getPointeeCXXRecordDecl()) + reportBug(Ivar, IvarType, MemberCXXRD, CD); +else if (auto* ObjCDecl = getObjCDecl(IvarType)) + reportBug(Ivar, IvarType, ObjCDecl, CD); } void visitObjCPropertyDecl(const ObjCContainerDecl *CD, @@ -161,19 +163,15 @@ class RawPtrRefMemberChecker const Type *PropType = QT.getTypePtrOrNull(); if (!PropType) return; -if (auto *PropCXXRD = PropType->getPointeeCXXRecordDecl()) { - std::optional IsCompatible = isPtrCompatible(QT, PropCXXRD); - if (IsCompatible && *IsCompatible) -reportBug(PD, PropType, PropCXXRD, CD); -} else { - std::optional IsCompatible = isPtrCompatible(QT, nullptr); - auto *PointeeType = PropType->getPointeeType().getTypePtrOrNull(); - if (IsCompatible && *IsCompatible) { -auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); -if (auto *ObjCType = dyn_cast_or_null(Desugared)) - reportBug(PD, PropType, ObjCType->getDecl(), CD); - } -} +
[clang] Support ptr to ptr and union in webkit member checker (PR #137565)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: Ryosuke Niwa (rniwa) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/137565.diff 5 Files Affected: - (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp (+67-61) - (modified) clang/test/Analysis/Checkers/WebKit/unchecked-members.cpp (+24-2) - (modified) clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp (+26-4) - (modified) clang/test/Analysis/Checkers/WebKit/unretained-members-arc.mm (+27) - (modified) clang/test/Analysis/Checkers/WebKit/unretained-members.mm (+31-3) ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp index 10b9749319a57..b5395ca7e34ff 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp @@ -38,9 +38,7 @@ class RawPtrRefMemberChecker RawPtrRefMemberChecker(const char *description) : Bug(this, description, "WebKit coding guidelines") {} - virtual std::optional - isPtrCompatible(const clang::QualType, - const clang::CXXRecordDecl *R) const = 0; + virtual std::optional isUnsafePtr(QualType) const = 0; virtual const char *typeName() const = 0; virtual const char *invariant() const = 0; @@ -87,26 +85,44 @@ class RawPtrRefMemberChecker if (shouldSkipDecl(RD)) return; -for (auto *Member : RD->fields()) { - auto QT = Member->getType(); - const Type *MemberType = QT.getTypePtrOrNull(); - if (!MemberType) -continue; - - if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) { -std::optional IsCompatible = isPtrCompatible(QT, MemberCXXRD); -if (IsCompatible && *IsCompatible) - reportBug(Member, MemberType, MemberCXXRD, RD); - } else { -std::optional IsCompatible = isPtrCompatible(QT, nullptr); -auto *PointeeType = MemberType->getPointeeType().getTypePtrOrNull(); -if (IsCompatible && *IsCompatible) { - auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); - if (auto *ObjCType = dyn_cast_or_null(Desugared)) -reportBug(Member, MemberType, ObjCType->getDecl(), RD); -} - } +for (auto *Member : RD->fields()) + visitMember(Member, RD); + } + + void visitMember(const FieldDecl* Member, const RecordDecl *RD) const { +auto QT = Member->getType(); +const Type *MemberType = QT.getTypePtrOrNull(); + +while (MemberType) { + auto IsUnsafePtr = isUnsafePtr(QT); + if (IsUnsafePtr && *IsUnsafePtr) +break; + if (!MemberType->isPointerType()) +return; + QT = MemberType->getPointeeType(); + MemberType = QT.getTypePtrOrNull(); } + +if (!MemberType) + return; + +if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) + reportBug(Member, MemberType, MemberCXXRD, RD); +else if (auto* ObjCDecl = getObjCDecl(MemberType)) + reportBug(Member, MemberType, ObjCDecl, RD); + } + + ObjCInterfaceDecl* getObjCDecl(const Type *TypePtr) const { +auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull(); +if (!PointeeType) + return nullptr; +auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); +if (!Desugared) + return nullptr; +auto *ObjCType = dyn_cast(Desugared); +if (!ObjCType) + return nullptr; +return ObjCType->getDecl(); } void visitObjCDecl(const ObjCContainerDecl *CD) const { @@ -138,19 +154,15 @@ class RawPtrRefMemberChecker const Type *IvarType = QT.getTypePtrOrNull(); if (!IvarType) return; -if (auto *IvarCXXRD = IvarType->getPointeeCXXRecordDecl()) { - std::optional IsCompatible = isPtrCompatible(QT, IvarCXXRD); - if (IsCompatible && *IsCompatible) -reportBug(Ivar, IvarType, IvarCXXRD, CD); -} else { - std::optional IsCompatible = isPtrCompatible(QT, nullptr); - auto *PointeeType = IvarType->getPointeeType().getTypePtrOrNull(); - if (IsCompatible && *IsCompatible) { -auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); -if (auto *ObjCType = dyn_cast_or_null(Desugared)) - reportBug(Ivar, IvarType, ObjCType->getDecl(), CD); - } -} + +auto IsUnsafePtr = isUnsafePtr(QT); +if (!IsUnsafePtr || !*IsUnsafePtr) + return; + +if (auto *MemberCXXRD = IvarType->getPointeeCXXRecordDecl()) + reportBug(Ivar, IvarType, MemberCXXRD, CD); +else if (auto* ObjCDecl = getObjCDecl(IvarType)) + reportBug(Ivar, IvarType, ObjCDecl, CD); } void visitObjCPropertyDecl(const ObjCContainerDecl *CD, @@ -161,19 +173,15 @@ class RawPtrRefMemberChecker const Type *PropType = QT.getTypePtrOrNull(); if (!PropType) return; -if (auto *PropCXXRD = PropType->getPointeeCXXRecordDecl()) { -
[clang] [RawPtrRefMemberChecker] Make RawPtrRefMemberChecker consistent with other checkers (PR #137559)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/137559 >From 9d6c807a5d7b853876132be0668357f6945978af Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Sun, 20 Apr 2025 18:38:31 -0700 Subject: [PATCH 1/2] [RawPtrRefMemberChecker] Make RawPtrRefMemberChecker consistent with other checkers Refactor RawPtrRefMemberChecker so that each subclass override isUnsafePtr like other WebKit checkers instead of overriding isPtrCompatible. --- .../WebKit/RawPtrRefMemberChecker.cpp | 98 +-- 1 file changed, 45 insertions(+), 53 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp index 10b9749319a57..209073e3ccc3a 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp @@ -38,9 +38,7 @@ class RawPtrRefMemberChecker RawPtrRefMemberChecker(const char *description) : Bug(this, description, "WebKit coding guidelines") {} - virtual std::optional - isPtrCompatible(const clang::QualType, - const clang::CXXRecordDecl *R) const = 0; + virtual std::optional isUnsafePtr(QualType) const = 0; virtual const char *typeName() const = 0; virtual const char *invariant() const = 0; @@ -93,22 +91,30 @@ class RawPtrRefMemberChecker if (!MemberType) continue; - if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) { -std::optional IsCompatible = isPtrCompatible(QT, MemberCXXRD); -if (IsCompatible && *IsCompatible) - reportBug(Member, MemberType, MemberCXXRD, RD); - } else { -std::optional IsCompatible = isPtrCompatible(QT, nullptr); -auto *PointeeType = MemberType->getPointeeType().getTypePtrOrNull(); -if (IsCompatible && *IsCompatible) { - auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); - if (auto *ObjCType = dyn_cast_or_null(Desugared)) -reportBug(Member, MemberType, ObjCType->getDecl(), RD); -} - } + auto IsUnsafePtr = isUnsafePtr(QT); + if (!IsUnsafePtr || !*IsUnsafePtr) +continue; + + if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) +reportBug(Member, MemberType, MemberCXXRD, RD); + else if (auto* ObjCDecl = getObjCDecl(MemberType)) +reportBug(Member, MemberType, ObjCDecl, RD); } } + ObjCInterfaceDecl* getObjCDecl(const Type *TypePtr) const { +auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull(); +if (!PointeeType) + return nullptr; +auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); +if (!Desugared) + return nullptr; +auto *ObjCType = dyn_cast(Desugared); +if (!ObjCType) + return nullptr; +return ObjCType->getDecl(); + } + void visitObjCDecl(const ObjCContainerDecl *CD) const { if (BR->getSourceManager().isInSystemHeader(CD->getLocation())) return; @@ -138,19 +144,15 @@ class RawPtrRefMemberChecker const Type *IvarType = QT.getTypePtrOrNull(); if (!IvarType) return; -if (auto *IvarCXXRD = IvarType->getPointeeCXXRecordDecl()) { - std::optional IsCompatible = isPtrCompatible(QT, IvarCXXRD); - if (IsCompatible && *IsCompatible) -reportBug(Ivar, IvarType, IvarCXXRD, CD); -} else { - std::optional IsCompatible = isPtrCompatible(QT, nullptr); - auto *PointeeType = IvarType->getPointeeType().getTypePtrOrNull(); - if (IsCompatible && *IsCompatible) { -auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); -if (auto *ObjCType = dyn_cast_or_null(Desugared)) - reportBug(Ivar, IvarType, ObjCType->getDecl(), CD); - } -} + +auto IsUnsafePtr = isUnsafePtr(QT); +if (!IsUnsafePtr || !*IsUnsafePtr) + return; + +if (auto *MemberCXXRD = IvarType->getPointeeCXXRecordDecl()) + reportBug(Ivar, IvarType, MemberCXXRD, CD); +else if (auto* ObjCDecl = getObjCDecl(IvarType)) + reportBug(Ivar, IvarType, ObjCDecl, CD); } void visitObjCPropertyDecl(const ObjCContainerDecl *CD, @@ -161,19 +163,15 @@ class RawPtrRefMemberChecker const Type *PropType = QT.getTypePtrOrNull(); if (!PropType) return; -if (auto *PropCXXRD = PropType->getPointeeCXXRecordDecl()) { - std::optional IsCompatible = isPtrCompatible(QT, PropCXXRD); - if (IsCompatible && *IsCompatible) -reportBug(PD, PropType, PropCXXRD, CD); -} else { - std::optional IsCompatible = isPtrCompatible(QT, nullptr); - auto *PointeeType = PropType->getPointeeType().getTypePtrOrNull(); - if (IsCompatible && *IsCompatible) { -auto *Desugared = PointeeType->getUnqualifiedDesugaredType(); -if (auto *ObjCType = dyn_cast_or_null(Desugared)) - reportBug(PD, PropType, ObjCType->getDecl(), CD); - } -} + +a
[clang] Support ptr to ptr and union in webkit member checker (PR #137565)
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 HEAD~1 HEAD --extensions cpp -- clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp clang/test/Analysis/Checkers/WebKit/unchecked-members.cpp clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp index b5395ca7e..d1a4f203d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp @@ -89,7 +89,7 @@ public: visitMember(Member, RD); } - void visitMember(const FieldDecl* Member, const RecordDecl *RD) const { + void visitMember(const FieldDecl *Member, const RecordDecl *RD) const { auto QT = Member->getType(); const Type *MemberType = QT.getTypePtrOrNull(); @@ -108,11 +108,11 @@ public: if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) reportBug(Member, MemberType, MemberCXXRD, RD); -else if (auto* ObjCDecl = getObjCDecl(MemberType)) +else if (auto *ObjCDecl = getObjCDecl(MemberType)) reportBug(Member, MemberType, ObjCDecl, RD); } - ObjCInterfaceDecl* getObjCDecl(const Type *TypePtr) const { + ObjCInterfaceDecl *getObjCDecl(const Type *TypePtr) const { auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull(); if (!PointeeType) return nullptr; @@ -161,7 +161,7 @@ public: if (auto *MemberCXXRD = IvarType->getPointeeCXXRecordDecl()) reportBug(Ivar, IvarType, MemberCXXRD, CD); -else if (auto* ObjCDecl = getObjCDecl(IvarType)) +else if (auto *ObjCDecl = getObjCDecl(IvarType)) reportBug(Ivar, IvarType, ObjCDecl, CD); } @@ -180,7 +180,7 @@ public: if (auto *MemberCXXRD = PropType->getPointeeCXXRecordDecl()) reportBug(PD, PropType, MemberCXXRD, CD); -else if (auto* ObjCDecl = getObjCDecl(PropType)) +else if (auto *ObjCDecl = getObjCDecl(PropType)) reportBug(PD, PropType, ObjCDecl, CD); } `` https://github.com/llvm/llvm-project/pull/137565 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Add container field to remote index Refs grpc method (PR #71605)
tdupes wrote: done https://github.com/llvm/llvm-project/pull/71605 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] f3a61f6 - [clang][NFC] Convert `LookupResult::AmbiguityKind` to scoped enum
Author: Vlad Serebrennikov Date: 2025-04-28T08:22:57+03:00 New Revision: f3a61f61eef53ecc0b59d14c52396df4f47ee5e8 URL: https://github.com/llvm/llvm-project/commit/f3a61f61eef53ecc0b59d14c52396df4f47ee5e8 DIFF: https://github.com/llvm/llvm-project/commit/f3a61f61eef53ecc0b59d14c52396df4f47ee5e8.diff LOG: [clang][NFC] Convert `LookupResult::AmbiguityKind` to scoped enum Added: Modified: clang/include/clang/Sema/Lookup.h clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaLookup.cpp Removed: diff --git a/clang/include/clang/Sema/Lookup.h b/clang/include/clang/Sema/Lookup.h index b0a08a05ac6a0..41a206b7f52b3 100644 --- a/clang/include/clang/Sema/Lookup.h +++ b/clang/include/clang/Sema/Lookup.h @@ -36,6 +36,79 @@ namespace clang { class CXXBasePaths; +enum class LookupAmbiguityKind { + /// Name lookup results in an ambiguity because multiple + /// entities that meet the lookup criteria were found in + /// subobjects of diff erent types. For example: + /// @code + /// struct A { void f(int); } + /// struct B { void f(double); } + /// struct C : A, B { }; + /// void test(C c) { + /// c.f(0); // error: A::f and B::f come from subobjects of diff erent + /// // types. overload resolution is not performed. + /// } + /// @endcode + AmbiguousBaseSubobjectTypes, + + /// Name lookup results in an ambiguity because multiple + /// nonstatic entities that meet the lookup criteria were found + /// in diff erent subobjects of the same type. For example: + /// @code + /// struct A { int x; }; + /// struct B : A { }; + /// struct C : A { }; + /// struct D : B, C { }; + /// int test(D d) { + /// return d.x; // error: 'x' is found in two A subobjects (of B and C) + /// } + /// @endcode + AmbiguousBaseSubobjects, + + /// Name lookup results in an ambiguity because multiple definitions + /// of entity that meet the lookup criteria were found in diff erent + /// declaration contexts. + /// @code + /// namespace A { + /// int i; + /// namespace B { int i; } + /// int test() { + /// using namespace B; + /// return i; // error 'i' is found in namespace A and A::B + ///} + /// } + /// @endcode + AmbiguousReference, + + /// Name lookup results in an ambiguity because multiple placeholder + /// variables were found in the same scope. + /// @code + /// void f() { + ///int _ = 0; + ///int _ = 0; + ///return _; // ambiguous use of placeholder variable + /// } + /// @endcode + AmbiguousReferenceToPlaceholderVariable, + + /// Name lookup results in an ambiguity because an entity with a + /// tag name was hidden by an entity with an ordinary name from + /// a diff erent context. + /// @code + /// namespace A { struct Foo {}; } + /// namespace B { void Foo(); } + /// namespace C { + /// using namespace A; + /// using namespace B; + /// } + /// void test() { + /// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a + /// // diff erent namespace + /// } + /// @endcode + AmbiguousTagHiding +}; + /// Represents the results of name lookup. /// /// An instance of the LookupResult class captures the results of a @@ -73,79 +146,6 @@ class LookupResult { Ambiguous }; - enum AmbiguityKind { -/// Name lookup results in an ambiguity because multiple -/// entities that meet the lookup criteria were found in -/// subobjects of diff erent types. For example: -/// @code -/// struct A { void f(int); } -/// struct B { void f(double); } -/// struct C : A, B { }; -/// void test(C c) { -/// c.f(0); // error: A::f and B::f come from subobjects of diff erent -/// // types. overload resolution is not performed. -/// } -/// @endcode -AmbiguousBaseSubobjectTypes, - -/// Name lookup results in an ambiguity because multiple -/// nonstatic entities that meet the lookup criteria were found -/// in diff erent subobjects of the same type. For example: -/// @code -/// struct A { int x; }; -/// struct B : A { }; -/// struct C : A { }; -/// struct D : B, C { }; -/// int test(D d) { -/// return d.x; // error: 'x' is found in two A subobjects (of B and C) -/// } -/// @endcode -AmbiguousBaseSubobjects, - -/// Name lookup results in an ambiguity because multiple definitions -/// of entity that meet the lookup criteria were found in diff erent -/// declaration contexts. -/// @code -/// namespace A { -/// int i; -/// namespace B { int i; } -/// int test() { -/// using namespace B; -/// return i; // error 'i' is found in namespace A and A::B -///} -/// } -/// @endcode -AmbiguousReference, - -/// Name lookup results in an ambiguity because multiple placeholder -/// variables were found in the same scope. -/// @cod
[clang] [clang-format] Add OneLineFormatOffRegex option (PR #137577)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/137577 >From ce33e11aedf297e9cfb5e20efb4ce316886e6cb1 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 27 Apr 2025 21:18:03 -0700 Subject: [PATCH] [clang-format] Add OneLineFormatOffRegex option Close #54334 --- clang/docs/ClangFormatStyleOptions.rst | 23 +++ clang/docs/ReleaseNotes.rst| 1 + clang/include/clang/Format/Format.h| 22 +++ clang/lib/Format/Format.cpp| 1 + clang/lib/Format/FormatTokenLexer.cpp | 34 ++ clang/unittests/Format/ConfigParseTest.cpp | 1 + clang/unittests/Format/FormatTest.cpp | 76 ++ 7 files changed, 158 insertions(+) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 3f8a5f49313b2..f1343ee6ee516 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -5195,6 +5195,29 @@ the configuration (without a prefix: ``Auto``). Add a space in front of an Objective-C protocol list, i.e. use ``Foo `` instead of ``Foo``. +.. _OneLineFormatOffRegex: + +**OneLineFormatOffRegex** (``String``) :versionbadge:`clang-format 21` :ref:`¶ ` + A regular expression that describes markers for turning formatting off for + one line. If it matches a line comment that is the first/only token of a + line, clang-format skips the next line. Otherwise, clang-format skips the + line that contains a matched token. + + .. code-block:: c++ + + // OneLineFormatOffRegex: ^(// NOLINT|logger$) + // results in the output below: + int a; + int b ; // NOLINT + int c; + // NOLINTNEXTLINE + int d ; + int e; + s = "// NOLINT"; + logger() ; + logger2(); + my_logger(); + .. _PPIndentWidth: **PPIndentWidth** (``Integer``) :versionbadge:`clang-format 13` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 3724c8cbc70fe..b22b3f13659ce 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -692,6 +692,7 @@ clang-format top of the file. - Add ``EnumTrailingComma`` option for inserting/removing commas at the end of ``enum`` enumerator lists. +- Add ``OneLineFormatOffRegex`` option for turning formatting off for one line. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index f6ceef08b46da..e5606a8a2a419 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -3654,6 +3654,27 @@ struct FormatStyle { /// \version 3.7 bool ObjCSpaceBeforeProtocolList; + /// A regular expression that describes markers for turning formatting off for + /// one line. If it matches a line comment that is the first/only token of a + /// line, clang-format skips the next line. Otherwise, clang-format skips the + /// line that contains a matched token. + /// \code + ///// OneLineFormatOffRegex: ^(// NOLINT|logger$) + ///// results in the output below: + ///int a; + ///int b ; // NOLINT + ///int c; + ///// NOLINTNEXTLINE + ///int d ; + ///int e; + ///s = "// NOLINT"; + ///logger() ; + ///logger2(); + ///my_logger(); + /// \endcode + /// \version 21 + std::string OneLineFormatOffRegex; + /// Different ways to try to fit all constructor initializers on a line. enum PackConstructorInitializersStyle : int8_t { /// Always put each constructor initializer on its own line. @@ -5399,6 +5420,7 @@ struct FormatStyle { ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder && ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty && ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList && + OneLineFormatOffRegex == R.OneLineFormatOffRegex && PackConstructorInitializers == R.PackConstructorInitializers && PenaltyBreakAssignment == R.PenaltyBreakAssignment && PenaltyBreakBeforeFirstCallParameter == diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 5a1c3f556b331..2f4b64ef4f5fe 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1100,6 +1100,7 @@ template <> struct MappingTraits { IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); IO.mapOptional("ObjCSpaceBeforeProtocolList", Style.ObjCSpaceBeforeProtocolList); +IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex); IO.mapOptional("PackConstructorInitializers", Style.PackConstructorInitializers); IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment); diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index a4c94ac411fe0..58991f9681c97 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -83,8 +83,42 @@ For
[clang] 268f0d4 - [ASTMatchers] Simplify isDefaultedHelper (NFC) (#137571)
Author: Kazu Hirata Date: 2025-04-27T21:50:45-07:00 New Revision: 268f0d4ebe47d73c361f8f2bce051d58994a33bc URL: https://github.com/llvm/llvm-project/commit/268f0d4ebe47d73c361f8f2bce051d58994a33bc DIFF: https://github.com/llvm/llvm-project/commit/268f0d4ebe47d73c361f8f2bce051d58994a33bc.diff LOG: [ASTMatchers] Simplify isDefaultedHelper (NFC) (#137571) We can use "constexpt if" to combine the two variants of functions. - Co-authored-by: Jakub Kuderski Added: Modified: clang/include/clang/ASTMatchers/ASTMatchersInternal.h Removed: diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index 8290645768aa9..71dfc49b7fcca 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -871,14 +871,11 @@ IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, return End; } -template ::value> - * = nullptr> -inline bool isDefaultedHelper(const T *) { +template inline bool isDefaultedHelper(const T *FD) { + if constexpr (std::is_base_of_v) +return FD->isDefaulted(); return false; } -inline bool isDefaultedHelper(const FunctionDecl *FD) { - return FD->isDefaulted(); -} // Metafunction to determine if type T has a member called getDecl. template ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/137571 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `lldb-aarch64-ubuntu` running on `linaro-lldb-aarch64-ubuntu` while building `clang` at step 6 "test". Full details are available at: https://lab.llvm.org/buildbot/#/builders/59/builds/16764 Here is the relevant piece of the build log for the reference ``` Step 6 (test) failure: build (failure) ... UNSUPPORTED: lldb-api :: tools/lldb-server/TestGdbRemoteFork.py (1207 of 2151) UNSUPPORTED: lldb-api :: tools/lldb-server/TestGdbRemoteForkNonStop.py (1208 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteAttach.py (1209 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteCompletion.py (1210 of 2151) UNSUPPORTED: lldb-api :: tools/lldb-server/TestGdbRemoteForkResume.py (1211 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteExitCode.py (1212 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteHostInfo.py (1213 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteModuleInfo.py (1214 of 2151) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteAuxvSupport.py (1215 of 2151) UNRESOLVED: lldb-api :: tools/lldb-dap/variables/TestDAP_variables.py (1216 of 2151) TEST 'lldb-api :: tools/lldb-dap/variables/TestDAP_variables.py' FAILED Script: -- /usr/bin/python3.10 /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/dotest.py -u CXXFLAGS -u CFLAGS --env LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib --env LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/include --env LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin --arch aarch64 --build-dir /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex --lldb-module-cache-dir /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api --clang-module-cache-dir /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api --executable /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/lldb --compiler /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/clang --dsymutil /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/dsymutil --make /usr/bin/gmake --llvm-tools-dir /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin --lldb-obj-root /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/tools/lldb --lldb-libs-dir /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/tools/lldb-dap/variables -p TestDAP_variables.py -- Exit Code: 1 Command Output (stdout): -- lldb version 21.0.0git (https://github.com/llvm/llvm-project.git revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc) clang revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc llvm revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 'debugserver', 'objc'] -- Command Output (stderr): -- UNSUPPORTED: LLDB (/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: test_darwin_dwarf_missing_obj (TestDAP_variables.TestDAP_variables) (requires one of macosx, darwin, ios, tvos, watchos, bridgeos, iphonesimulator, watchsimulator, appletvsimulator) UNSUPPORTED: LLDB (/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: test_darwin_dwarf_missing_obj_with_symbol_ondemand_enabled (TestDAP_variables.TestDAP_variables) (requires one of macosx, darwin, ios, tvos, watchos, bridgeos, iphonesimulator, watchsimulator, appletvsimulator) = DEBUG ADAPTER PROTOCOL LOGS = 1745816583.113421679 --> (stdin/stdout) {"command":"initialize","type":"request","arguments":{"adapterID":"lldb-native","clientID":"vscode","columnsStartAt1":true,"linesStartAt1":true,"locale":"en-us","pathFormat":"path","supportsRunInTerminalRequest":true,"supportsVariablePaging":true,"supportsVariableType":true,"supportsStartDebuggingRequest":true,"supportsProgressReporting":true,"$__lldb_sourceInitFile":false},"seq":1} 1745816583.115541935 <-- (stdin/stdout) {"body":{"$__lldb_version":"lldb version 21.0.0git (https://github.com/llvm/llvm-project.git revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc)\n clang revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc\n llvm revision 268f0d4ebe47d73c361f8f2bce051d58994a33bc","completionTriggerCharacters":["."," ","\t"],"exceptionBreakpointFilters":[{"default":false,"filter":"cpp_catch","label":"C++ Catch"},{"default":false,"filter":"cpp_throw","label":"C++ Throw"},{"default":false,"filter":"objc_catch","label":"Objective-C Catch"},{"default":false,"filter":"objc_throw","label":"Objective-C Throw"}],"supportTerminateDebuggee":true,"supportsBreakpointLocationsRequest":true,"supportsCancelRequest":true,"supportsCompletionsRequest":true,"supportsConditionalBreakpoints":true,"supportsConfigurationDoneRequest":true,"supportsDataB
[clang] a764358 - [clang][NFC] Convert DeclUpdateKind to scoped enum
Author: Vlad Serebrennikov Date: 2025-04-28T08:05:46+03:00 New Revision: a764358a9d86e9169bea895c8efbb61cc37ec788 URL: https://github.com/llvm/llvm-project/commit/a764358a9d86e9169bea895c8efbb61cc37ec788 DIFF: https://github.com/llvm/llvm-project/commit/a764358a9d86e9169bea895c8efbb61cc37ec788.diff LOG: [clang][NFC] Convert DeclUpdateKind to scoped enum Added: Modified: clang/include/clang/Serialization/ASTWriter.h clang/lib/Serialization/ASTCommon.h clang/lib/Serialization/ASTReaderDecl.cpp clang/lib/Serialization/ASTWriter.cpp clang/lib/Serialization/ASTWriterDecl.cpp Removed: diff --git a/clang/include/clang/Serialization/ASTWriter.h b/clang/include/clang/Serialization/ASTWriter.h index bdf3aca0637c8..9f0570eddc34e 100644 --- a/clang/include/clang/Serialization/ASTWriter.h +++ b/clang/include/clang/Serialization/ASTWriter.h @@ -75,6 +75,10 @@ class StoredDeclsList; class SwitchCase; class Token; +namespace serialization { +enum class DeclUpdateKind; +} // namespace serialization + namespace SrcMgr { class FileInfo; } // namespace SrcMgr @@ -374,8 +378,7 @@ class ASTWriter : public ASTDeserializationListener, /// An update to a Decl. class DeclUpdate { -/// A DeclUpdateKind. -unsigned Kind; +serialization::DeclUpdateKind Kind; union { const Decl *Dcl; void *Type; @@ -386,18 +389,21 @@ class ASTWriter : public ASTDeserializationListener, }; public: -DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {} -DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {} -DeclUpdate(unsigned Kind, QualType Type) +DeclUpdate(serialization::DeclUpdateKind Kind) : Kind(Kind), Dcl(nullptr) {} +DeclUpdate(serialization::DeclUpdateKind Kind, const Decl *Dcl) +: Kind(Kind), Dcl(Dcl) {} +DeclUpdate(serialization::DeclUpdateKind Kind, QualType Type) : Kind(Kind), Type(Type.getAsOpaquePtr()) {} -DeclUpdate(unsigned Kind, SourceLocation Loc) +DeclUpdate(serialization::DeclUpdateKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc.getRawEncoding()) {} -DeclUpdate(unsigned Kind, unsigned Val) : Kind(Kind), Val(Val) {} -DeclUpdate(unsigned Kind, Module *M) : Kind(Kind), Mod(M) {} -DeclUpdate(unsigned Kind, const Attr *Attribute) - : Kind(Kind), Attribute(Attribute) {} - -unsigned getKind() const { return Kind; } +DeclUpdate(serialization::DeclUpdateKind Kind, unsigned Val) +: Kind(Kind), Val(Val) {} +DeclUpdate(serialization::DeclUpdateKind Kind, Module *M) +: Kind(Kind), Mod(M) {} +DeclUpdate(serialization::DeclUpdateKind Kind, const Attr *Attribute) +: Kind(Kind), Attribute(Attribute) {} + +serialization::DeclUpdateKind getKind() const { return Kind; } const Decl *getDecl() const { return Dcl; } QualType getType() const { return QualType::getFromOpaquePtr(Type); } diff --git a/clang/lib/Serialization/ASTCommon.h b/clang/lib/Serialization/ASTCommon.h index 7c9ec884ea049..ed6b8d00115ea 100644 --- a/clang/lib/Serialization/ASTCommon.h +++ b/clang/lib/Serialization/ASTCommon.h @@ -22,26 +22,26 @@ namespace clang { namespace serialization { -enum DeclUpdateKind { - UPD_CXX_ADDED_IMPLICIT_MEMBER, - UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, - UPD_CXX_ADDED_FUNCTION_DEFINITION, - UPD_CXX_ADDED_VAR_DEFINITION, - UPD_CXX_POINT_OF_INSTANTIATION, - UPD_CXX_INSTANTIATED_CLASS_DEFINITION, - UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, - UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, - UPD_CXX_RESOLVED_DTOR_DELETE, - UPD_CXX_RESOLVED_EXCEPTION_SPEC, - UPD_CXX_DEDUCED_RETURN_TYPE, - UPD_DECL_MARKED_USED, - UPD_MANGLING_NUMBER, - UPD_STATIC_LOCAL_NUMBER, - UPD_DECL_MARKED_OPENMP_THREADPRIVATE, - UPD_DECL_MARKED_OPENMP_ALLOCATE, - UPD_DECL_MARKED_OPENMP_DECLARETARGET, - UPD_DECL_EXPORTED, - UPD_ADDED_ATTR_TO_RECORD +enum class DeclUpdateKind { + CXXAddedImplicitMember, + CXXAddedAnonymousNamespace, + CXXAddedFunctionDefinition, + CXXAddedVarDefinition, + CXXPointOfInstantiation, + CXXInstantiatedClassDefinition, + CXXInstantiatedDefaultArgument, + CXXInstantiatedDefaultMemberInitializer, + CXXResolvedDtorDelete, + CXXResolvedExceptionSpec, + CXXDeducedReturnType, + DeclMarkedUsed, + ManglingNumber, + StaticLocalNumber, + DeclMarkedOpenMPThreadPrivate, + DeclMarkedOpenMPAllocate, + DeclMarkedOpenMPDeclareTarget, + DeclExported, + AddedAttrToRecord }; TypeIdx TypeIdxFromBuiltin(const BuiltinType *BT); diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp index 0f54aa5c5e062..b1bec20b40390 100644 --- a/clang/lib/Serialization/ASTReaderDecl.cpp +++ b/clang/lib/Serialization/ASTReaderDecl.cpp @@ -4689,7 +4689,7 @@ static void forAllLaterRedecls(DeclT *D, Fn F) { void ASTDeclReader::UpdateDecl(Decl *D) { while (Record.getIdx() < Record.s
[clang] [ASTMatchers] Simplify isDefaultedHelper (NFC) (PR #137571)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `clang-m68k-linux-cross` running on `suse-gary-m68k-cross` while building `clang` at step 5 "ninja check 1". Full details are available at: https://lab.llvm.org/buildbot/#/builders/27/builds/9242 Here is the relevant piece of the build log for the reference ``` Step 5 (ninja check 1) failure: stage 1 checked (failure) ... [57/190] Building CXX object tools/clang/unittests/ASTMatchers/Dynamic/CMakeFiles/DynamicASTMatchersTests.dir/ParserTest.cpp.o [58/190] Building CXX object tools/clang/unittests/ASTMatchers/Dynamic/CMakeFiles/DynamicASTMatchersTests.dir/RegistryTest.cpp.o [59/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTExprTest.cpp.o [60/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTContextParentMapTest.cpp.o [61/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterFixtures.cpp.o [62/190] Building CXX object tools/clang/unittests/Analysis/FlowSensitive/CMakeFiles/ClangAnalysisFlowSensitiveTests.dir/TypeErasedDataflowAnalysisTest.cpp.o [63/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTDumperTest.cpp.o [64/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterObjCTest.cpp.o [65/190] Building CXX object tools/clang/tools/extra/unittests/clang-tidy/CMakeFiles/ClangTidyTests.dir/OverlappingReplacementsTest.cpp.o [66/190] Building CXX object tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterTest.cpp.o FAILED: tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterTest.cpp.o /usr/bin/c++ -DGTEST_HAS_RTTI=0 -DLLVM_BUILD_STATIC -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/tools/clang/unittests/AST -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/unittests/AST -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/tools/clang/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/llvm/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/third-party/unittest/googletest/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/third-party/unittest/googlemock/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-maybe-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual -fno-strict-aliasing -O3 -DNDEBUG -std=c++17 -Wno-variadic-macros -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -Wno-suggest-override -MD -MT tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterTest.cpp.o -MF tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterTest.cpp.o.d -o tools/clang/unittests/AST/CMakeFiles/ASTTests.dir/ASTImporterTest.cpp.o -c /var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/unittests/AST/ASTImporterTest.cpp c++: fatal error: Killed signal terminated program cc1plus compilation terminated. [67/190] Building CXX object tools/clang/unittests/Analysis/FlowSensitive/CMakeFiles/ClangAnalysisFlowSensitiveTests.dir/TransferTest.cpp.o FAILED: tools/clang/unittests/Analysis/FlowSensitive/CMakeFiles/ClangAnalysisFlowSensitiveTests.dir/TransferTest.cpp.o /usr/bin/c++ -DGTEST_HAS_RTTI=0 -DLLVM_BUILD_STATIC -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/tools/clang/unittests/Analysis/FlowSensitive -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/unittests/Analysis/FlowSensitive -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/tools/clang/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/stage1/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/llvm/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/third-party/unittest/googletest/include -I/var/lib/buildbot/workers/suse-gary-m68k-cross/c
[clang] 98eeedd - [clang][NFC] Convert `NumLVComputationKindBits` to a constant
Author: Vlad Serebrennikov Date: 2025-04-28T08:09:41+03:00 New Revision: 98eeedd4a100600dd91cda14e0096483403c408b URL: https://github.com/llvm/llvm-project/commit/98eeedd4a100600dd91cda14e0096483403c408b DIFF: https://github.com/llvm/llvm-project/commit/98eeedd4a100600dd91cda14e0096483403c408b.diff LOG: [clang][NFC] Convert `NumLVComputationKindBits` to a constant Added: Modified: clang/lib/AST/Linkage.h Removed: diff --git a/clang/lib/AST/Linkage.h b/clang/lib/AST/Linkage.h index e4dcb5e53261c..4aaf0c99a1662 100644 --- a/clang/lib/AST/Linkage.h +++ b/clang/lib/AST/Linkage.h @@ -40,7 +40,7 @@ struct LVComputationKind { LLVM_PREFERRED_TYPE(bool) unsigned IgnoreAllVisibility : 1; - enum { NumLVComputationKindBits = 3 }; + static constexpr int NumLVComputationKindBits = 3; explicit LVComputationKind(NamedDecl::ExplicitVisibilityKind EK) : ExplicitKind(EK), IgnoreExplicitVisibility(false), ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Add container field to remote index Refs grpc method (PR #71605)
https://github.com/tdupes updated https://github.com/llvm/llvm-project/pull/71605 >From 66fe31636d68c7200515a5d3a9e60d20334b60dd Mon Sep 17 00:00:00 2001 From: dup Date: Fri, 3 Nov 2023 09:03:24 -0700 Subject: [PATCH] Add container field to remote index Refs grpc method --- clang-tools-extra/clangd/index/YAMLSerialization.cpp | 1 + clang-tools-extra/clangd/index/remote/Index.proto | 1 + .../clangd/index/remote/marshalling/Marshalling.cpp | 4 .../clangd/unittests/remote/MarshallingTests.cpp | 1 + 4 files changed, 7 insertions(+) diff --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp index 214a847b5eddb..495d8a2ff487a 100644 --- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp +++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp @@ -319,6 +319,7 @@ template <> struct MappingTraits { MappingNormalization NKind(IO, R.Kind); IO.mapRequired("Kind", NKind->Kind); IO.mapRequired("Location", R.Location); +IO.mapOptional("Container", R.Container); } }; diff --git a/clang-tools-extra/clangd/index/remote/Index.proto b/clang-tools-extra/clangd/index/remote/Index.proto index 3e39724e32086..d274f6458164a 100644 --- a/clang-tools-extra/clangd/index/remote/Index.proto +++ b/clang-tools-extra/clangd/index/remote/Index.proto @@ -81,6 +81,7 @@ message Symbol { message Ref { optional SymbolLocation location = 1; optional uint32 kind = 2; + optional string container = 3; } message SymbolInfo { diff --git a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp index d8d3b64a5ac18..aa607926a6d51 100644 --- a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp +++ b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp @@ -203,6 +203,9 @@ llvm::Expected Marshaller::fromProtobuf(const Ref &Message) { return Location.takeError(); Result.Location = *Location; Result.Kind = static_cast(Message.kind()); + auto ContainerID = SymbolID::fromStr(Message.container()); + if (ContainerID) +Result.Container = *ContainerID; return Result; } @@ -340,6 +343,7 @@ llvm::Expected Marshaller::toProtobuf(const clangd::Ref &From) { if (!Location) return Location.takeError(); *Result.mutable_location() = *Location; + Result.set_container(From.Container.str()); return Result; } diff --git a/clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp b/clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp index a2b31698a059a..85e79eae331bc 100644 --- a/clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp +++ b/clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp @@ -223,6 +223,7 @@ TEST(RemoteMarshallingTest, RefSerialization) { Location.FileURI = testPathURI( "llvm-project/llvm/clang-tools-extra/clangd/Protocol.h", Strings); Ref.Location = Location; + Ref.Container = llvm::cantFail(SymbolID::fromStr("0001")); Marshaller ProtobufMarshaller(testPath("llvm-project/"), testPath("llvm-project/")); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] dae63e2 - Reland [clang] Handle instantiated members to determine visibility (#136128) (#136689)
Author: Andrew Savonichev Date: 2025-04-28T15:49:54+09:00 New Revision: dae63e2c0ff1b7d64e186fe72e06a80ef895402c URL: https://github.com/llvm/llvm-project/commit/dae63e2c0ff1b7d64e186fe72e06a80ef895402c DIFF: https://github.com/llvm/llvm-project/commit/dae63e2c0ff1b7d64e186fe72e06a80ef895402c.diff LOG: Reland [clang] Handle instantiated members to determine visibility (#136128) (#136689) As reported in issue #103477, visibility of instantiated member functions used to be ignored when calculating visibility of a specialization. This patch modifies `getLVForClassMember` to look up for a source template for an instantiated member, and changes `mergeTemplateLV` to apply it. A similar issue was reported in #31462, but it seems that `extern` declaration with visibility prevents the function from being emitted as hidden. This behavior seems correct, even though GCC emits it as with default visibility instead. Both tests from #103477 and #31462 are added as LIT tests `test72` and `test73` respectively. Added: Modified: clang/docs/ReleaseNotes.rst clang/lib/AST/Decl.cpp clang/test/CodeGenCXX/visibility.cpp Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index eb2e8f2b8a6c0..3105d8b481560 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -470,6 +470,7 @@ Bug Fixes in This Version - Fixed a crash when ``#embed`` appears as a part of a failed constant evaluation. The crashes were happening during diagnostics emission due to unimplemented statement printer. (#GH132641) +- Fixed visibility calculation for template functions. (#GH103477) Bug Fixes to Compiler Builtins ^^ diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index 1d9208f0e1c72..61d497999b669 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -400,9 +400,9 @@ void LinkageComputer::mergeTemplateLV( FunctionTemplateDecl *temp = specInfo->getTemplate(); // Merge information from the template declaration. LinkageInfo tempLV = getLVForDecl(temp, computation); - // The linkage of the specialization should be consistent with the - // template declaration. - LV.setLinkage(tempLV.getLinkage()); + // The linkage and visibility of the specialization should be + // consistent with the template declaration. + LV.mergeMaybeWithVisibility(tempLV, considerVisibility); // Merge information from the template parameters. LinkageInfo paramsLV = @@ -1051,6 +1051,13 @@ LinkageComputer::getLVForClassMember(const NamedDecl *D, if (const auto *redeclTemp = dyn_cast(temp)) { if (isExplicitMemberSpecialization(redeclTemp)) { explicitSpecSuppressor = temp->getTemplatedDecl(); + } else if (const RedeclarableTemplateDecl *from = + redeclTemp->getInstantiatedFromMemberTemplate()) { +// If no explicit visibility is specified yet, and this is an +// instantiated member of a template, look up visibility there +// as well. +LinkageInfo fromLV = from->getLinkageAndVisibility(); +LV.mergeMaybeWithVisibility(fromLV, considerVisibility); } } } diff --git a/clang/test/CodeGenCXX/visibility.cpp b/clang/test/CodeGenCXX/visibility.cpp index b4c6fdcbcdf33..442e2a5aaa2b3 100644 --- a/clang/test/CodeGenCXX/visibility.cpp +++ b/clang/test/CodeGenCXX/visibility.cpp @@ -1457,13 +1457,49 @@ namespace test71 { // CHECK-LABEL: declare hidden noundef i32 @_ZN6test713fooIiE3zedEv( // CHECK-LABEL: define linkonce_odr noundef i32 @_ZN6test713fooIiE3barIiEET_v( // CHECK-LABEL: define linkonce_odr hidden noundef i64 @_ZN6test713fooIlE3zedEv( - // CHECK-LABEL: define linkonce_odr noundef i32 @_ZN6test713fooIlE3barIiEET_v( + // CHECK-LABEL: define linkonce_odr hidden noundef i32 @_ZN6test713fooIlE3barIiEET_v( // CHECK-HIDDEN-LABEL: declare hidden noundef i32 @_ZN6test713fooIiE3zedEv( // CHECK-HIDDEN-LABEL: define linkonce_odr noundef i32 @_ZN6test713fooIiE3barIiEET_v( // CHECK-HIDDEN-LABEL: define linkonce_odr hidden noundef i64 @_ZN6test713fooIlE3zedEv( // CHECK-HIDDEN-LABEL: define linkonce_odr hidden noundef i32 @_ZN6test713fooIlE3barIiEET_v( } +// https://github.com/llvm/llvm-project/issues/103477 +namespace test72 { + template + struct t { +template +static HIDDEN void bar() {} + }; + + void test() { + t::bar<1>(); + } + // CHECK-LABEL: define linkonce_odr hidden void @_ZN6test721tIcE3barILi1EEEvv( + // CHECK-HIDDEN-LABEL: define linkonce_odr hidden void @_ZN6test721tIcE3barILi1EEEvv( +} + +// https://github.com/llvm/llvm-project/issues/31462 +namespace test73 { + template struct s { +template +__attribute__((__visibility__("hidden"))) U should_not_be_exported(); + }; + + template template U s::should_not_be_exported() { +return U(); + } + + extern template struct _
[clang] f5ba3d0 - [clang] Fix computeTypeLinkageInfo for dependent member pointers (#136689)
Author: Andrew Savonichev Date: 2025-04-28T15:49:54+09:00 New Revision: f5ba3d0c6d413e46fa962be80cfb37857e35b9ab URL: https://github.com/llvm/llvm-project/commit/f5ba3d0c6d413e46fa962be80cfb37857e35b9ab DIFF: https://github.com/llvm/llvm-project/commit/f5ba3d0c6d413e46fa962be80cfb37857e35b9ab.diff LOG: [clang] Fix computeTypeLinkageInfo for dependent member pointers (#136689) MemberPointerType may refer to a dependent class (qualifier), for which getMostRecentCXXRecordDecl returns NULL. It seems that the compiler never executed this code path before patch #136128 where the issue was reported. LIT tests 74 and 75 are reduced from Chromium and LLVM libc test harness as reported in #136128. Function member (test74): MemberPointerType 'type-parameter-0-0 (type-parameter-0-1::*)(void)' dependent |-TemplateTypeParmType 'type-parameter-0-1' dependent depth 0 index 1 `-FunctionProtoType 'type-parameter-0-0 (void)' dependent cdecl `-TemplateTypeParmType 'type-parameter-0-0' dependent depth 0 index 0 Template parameter (test75): MemberPointerType 'type-parameter-0-1 type-parameter-0-0::*' dependent |-TemplateTypeParmType 'type-parameter-0-0' dependent depth 0 index 0 `-TemplateTypeParmType 'type-parameter-0-1' dependent depth 0 index 1 Added: Modified: clang/lib/AST/Type.cpp clang/test/CodeGenCXX/visibility.cpp Removed: diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp index 111a642173418..d298f1cff73cf 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -4793,8 +4793,12 @@ LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { return computeTypeLinkageInfo(cast(T)->getPointeeType()); case Type::MemberPointer: { const auto *MPT = cast(T); -LinkageInfo LV = -getDeclLinkageAndVisibility(MPT->getMostRecentCXXRecordDecl()); +LinkageInfo LV; +if (auto *D = MPT->getMostRecentCXXRecordDecl()) { + LV.merge(getDeclLinkageAndVisibility(D)); +} else if (auto *Ty = MPT->getQualifier()->getAsType()) { + LV.merge(computeTypeLinkageInfo(Ty)); +} LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); return LV; } diff --git a/clang/test/CodeGenCXX/visibility.cpp b/clang/test/CodeGenCXX/visibility.cpp index e1061f3dbd18f..b4c6fdcbcdf33 100644 --- a/clang/test/CodeGenCXX/visibility.cpp +++ b/clang/test/CodeGenCXX/visibility.cpp @@ -1463,3 +1463,40 @@ namespace test71 { // CHECK-HIDDEN-LABEL: define linkonce_odr hidden noundef i64 @_ZN6test713fooIlE3zedEv( // CHECK-HIDDEN-LABEL: define linkonce_odr hidden noundef i32 @_ZN6test713fooIlE3barIiEET_v( } + +namespace test74 { + template struct T; + template + struct T { +template +static __attribute__((__visibility__("hidden"))) void Invoke(M) { +} + }; + + struct C; + void (C::*MM)(); + + void Fun() { +T::Invoke(0); + } + // CHECK-LABEL: define linkonce_odr void @_ZN6test741TIMNS_1CEFvvEE6InvokeIiEEvT_( + // CHECK-HIDDEN-LABEL: define linkonce_odr hidden void @_ZN6test741TIMNS_1CEFvvEE6InvokeIiEEvT_( +} + +namespace test75 { + template struct T; + template + struct T { +template +static __attribute__((__visibility__("hidden"))) +void Invoke(M) { +} + }; + + struct A; + void Fun() { +T::Invoke(0); + } + // CHECK-LABEL: define linkonce_odr void @_ZN6test751TIMNS_1AEFvvEE6InvokeIiEEvT_( + // CHECK-HIDDEN-LABEL: define linkonce_odr hidden void @_ZN6test751TIMNS_1AEFvvEE6InvokeIiEEvT_( +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reland [clang] Handle instantiated members to determine visibility (#136128) (PR #136689)
asavonic wrote: Merged as f5ba3d0c and dae63e2c. https://github.com/llvm/llvm-project/pull/136689 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [PseudoProbe] Support emitting to COFF object (PR #123870)
https://github.com/HaohaiWen updated https://github.com/llvm/llvm-project/pull/123870 >From 7c531922f20bf284a5cd83b20e94cb624ef031d2 Mon Sep 17 00:00:00 2001 From: Haohai Wen Date: Thu, 9 Jan 2025 15:29:33 +0800 Subject: [PATCH 1/3] [COFF] Preserve UniqueID used to create MCSectionCOFF This UniqueID can be used later to create associative section. e.g. A .pseudo_probe associated to the section of the corresponding function. --- llvm/include/llvm/MC/MCSectionCOFF.h | 9 +++-- llvm/lib/MC/MCContext.cpp| 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/llvm/include/llvm/MC/MCSectionCOFF.h b/llvm/include/llvm/MC/MCSectionCOFF.h index 97540d985dbd1..9c79c27f2a915 100644 --- a/llvm/include/llvm/MC/MCSectionCOFF.h +++ b/llvm/include/llvm/MC/MCSectionCOFF.h @@ -47,16 +47,19 @@ class MCSectionCOFF final : public MCSection { /// section (Characteristics & IMAGE_SCN_LNK_COMDAT) != 0 mutable int Selection; + unsigned UniqueID; + private: friend class MCContext; // The storage of Name is owned by MCContext's COFFUniquingMap. MCSectionCOFF(StringRef Name, unsigned Characteristics, -MCSymbol *COMDATSymbol, int Selection, MCSymbol *Begin) +MCSymbol *COMDATSymbol, int Selection, unsigned UniqueID, +MCSymbol *Begin) : MCSection(SV_COFF, Name, Characteristics & COFF::IMAGE_SCN_CNT_CODE, Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA, Begin), Characteristics(Characteristics), COMDATSymbol(COMDATSymbol), -Selection(Selection) { +Selection(Selection), UniqueID(UniqueID) { assert((Characteristics & 0x00F0) == 0 && "alignment must not be set upon section creation"); } @@ -72,6 +75,8 @@ class MCSectionCOFF final : public MCSection { void setSelection(int Selection) const; + unsigned getUniqueID() const { return UniqueID; } + void printSwitchToSection(const MCAsmInfo &MAI, const Triple &T, raw_ostream &OS, uint32_t Subsection) const override; diff --git a/llvm/lib/MC/MCContext.cpp b/llvm/lib/MC/MCContext.cpp index 46222fcaa5b15..56aba5de4445e 100644 --- a/llvm/lib/MC/MCContext.cpp +++ b/llvm/lib/MC/MCContext.cpp @@ -718,7 +718,7 @@ MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, StringRef CachedName = Iter->first.SectionName; MCSymbol *Begin = getOrCreateSectionSymbol(Section); MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( - CachedName, Characteristics, COMDATSymbol, Selection, Begin); + CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin); Iter->second = Result; auto *F = allocInitialFragment(*Result); Begin->setFragment(F); >From 5c201436acb13e3d0893893eabd6e128ccdff346 Mon Sep 17 00:00:00 2001 From: Haohai Wen Date: Tue, 21 Jan 2025 11:44:50 +0800 Subject: [PATCH 2/3] [PseudoProbe] Support emitting to COFF object Support emitting pseudo probe to .pseudo_probe and .pseudo_probe_desc COFF sections. --- clang/include/clang/Driver/Options.td | 2 +- clang/test/Driver/cl-options.c| 1 + .../llvm/Target/TargetLoweringObjectFile.h| 3 + .../CodeGen/TargetLoweringObjectFileImpl.cpp | 24 +- llvm/lib/MC/MCAsmStreamer.cpp | 3 +- llvm/lib/MC/MCContext.cpp | 8 + llvm/lib/MC/MCObjectFileInfo.cpp | 81 -- llvm/lib/Target/TargetLoweringObjectFile.cpp | 27 ++ .../pseudo-probe-callee-profile-mismatch.ll | 4 +- .../SampleProfile/pseudo-probe-dangle.ll | 2 +- .../SampleProfile/pseudo-probe-dangle2.ll | 2 +- .../SampleProfile/pseudo-probe-desc-guid.ll | 2 +- .../SampleProfile/pseudo-probe-eh.ll | 2 +- .../SampleProfile/pseudo-probe-emit-inline.ll | 73 -- .../SampleProfile/pseudo-probe-emit.ll| 233 +- .../SampleProfile/pseudo-probe-icp-factor.ll | 2 +- .../SampleProfile/pseudo-probe-inline.ll | 2 +- .../SampleProfile/pseudo-probe-instsched.ll | 2 +- .../SampleProfile/pseudo-probe-invoke.ll | 4 +- .../pseudo-probe-missing-probe.ll | 2 +- .../pseudo-probe-no-debug-info.ll | 2 +- .../SampleProfile/pseudo-probe-peep.ll| 2 +- .../pseudo-probe-profile-mismatch-error.ll| 2 +- .../pseudo-probe-profile-mismatch-thinlto.ll | 2 +- .../pseudo-probe-profile-mismatch.ll | 4 +- .../pseudo-probe-selectionDAG.ll | 2 +- .../SampleProfile/pseudo-probe-slotindex.ll | 4 +- ...pseudo-probe-stale-profile-matching-LCS.ll | 4 +- ...pseudo-probe-stale-profile-matching-lto.ll | 4 +- .../pseudo-probe-stale-profile-matching.ll| 4 +- ...-probe-stale-profile-renaming-recursive.ll | 4 +- .../pseudo-probe-stale-profile-renaming.ll| 4 +- .../pseudo-probe-stale-profile-toplev-func.ll | 4 +- .../SampleProfile/pseudo-probe-two
[clang] [clang][bytecode] Fix two small builtin_constant_p cases (PR #137587)
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/137587 Only accept string literals if we're pointing to the first index and do accept complex literals. >From 2005584f52d7fa2bd964eed80303a8cc1a6dda4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= Date: Mon, 28 Apr 2025 08:50:44 +0200 Subject: [PATCH] [clang][bytecode] Fix two small builtin_constant_p cases Only accept string literals if we're pointing to the first index and do accept complex literals. --- clang/lib/AST/ByteCode/Interp.cpp | 5 - clang/test/AST/ByteCode/builtin-constant-p.cpp | 15 +-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp index 37111343178dd..dfc00ffc297e1 100644 --- a/clang/lib/AST/ByteCode/Interp.cpp +++ b/clang/lib/AST/ByteCode/Interp.cpp @@ -321,8 +321,11 @@ bool CheckBCPResult(InterpState &S, const Pointer &Ptr) { if (Ptr.isTypeidPointer()) return true; + if (Ptr.getType()->isAnyComplexType()) +return true; + if (const Expr *Base = Ptr.getDeclDesc()->asExpr()) -return isa(Base); +return isa(Base) && Ptr.getIndex() == 0; return false; } diff --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp b/clang/test/AST/ByteCode/builtin-constant-p.cpp index f5b16761bfdc9..9f5521590833d 100644 --- a/clang/test/AST/ByteCode/builtin-constant-p.cpp +++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp @@ -1,5 +1,5 @@ -// RUN: %clang_cc1 -std=c++20 -fexperimental-new-constant-interpreter -verify=expected,both %s -// RUN: %clang_cc1 -std=c++20 -verify=ref,both %s +// RUN: %clang_cc1 -std=c++20 -verify=expected,both %s -fexperimental-new-constant-interpreter +// RUN: %clang_cc1 -std=c++20 -verify=ref,both %s using intptr_t = __INTPTR_TYPE__; @@ -129,3 +129,14 @@ void g() { const float f = __builtin_is_constant_evaluated(); static_assert(fold(f == 0.0f)); } + +void test17(void) { +#define ASSERT(...) { enum { folded = (__VA_ARGS__) }; int arr[folded ? 1 : -1]; } +#define T(...) ASSERT(__builtin_constant_p(__VA_ARGS__)) +#define F(...) ASSERT(!__builtin_constant_p(__VA_ARGS__)) + + T(3i + 5); + T("string literal"); + F("string literal" + 1); // both-warning {{adding}} \ + // both-note {{use array indexing}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Fix two small builtin_constant_p cases (PR #137587)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Timm Baeder (tbaederr) Changes Only accept string literals if we're pointing to the first index and do accept complex literals. --- Full diff: https://github.com/llvm/llvm-project/pull/137587.diff 2 Files Affected: - (modified) clang/lib/AST/ByteCode/Interp.cpp (+4-1) - (modified) clang/test/AST/ByteCode/builtin-constant-p.cpp (+13-2) ``diff diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp index 37111343178dd..dfc00ffc297e1 100644 --- a/clang/lib/AST/ByteCode/Interp.cpp +++ b/clang/lib/AST/ByteCode/Interp.cpp @@ -321,8 +321,11 @@ bool CheckBCPResult(InterpState &S, const Pointer &Ptr) { if (Ptr.isTypeidPointer()) return true; + if (Ptr.getType()->isAnyComplexType()) +return true; + if (const Expr *Base = Ptr.getDeclDesc()->asExpr()) -return isa(Base); +return isa(Base) && Ptr.getIndex() == 0; return false; } diff --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp b/clang/test/AST/ByteCode/builtin-constant-p.cpp index f5b16761bfdc9..9f5521590833d 100644 --- a/clang/test/AST/ByteCode/builtin-constant-p.cpp +++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp @@ -1,5 +1,5 @@ -// RUN: %clang_cc1 -std=c++20 -fexperimental-new-constant-interpreter -verify=expected,both %s -// RUN: %clang_cc1 -std=c++20 -verify=ref,both %s +// RUN: %clang_cc1 -std=c++20 -verify=expected,both %s -fexperimental-new-constant-interpreter +// RUN: %clang_cc1 -std=c++20 -verify=ref,both %s using intptr_t = __INTPTR_TYPE__; @@ -129,3 +129,14 @@ void g() { const float f = __builtin_is_constant_evaluated(); static_assert(fold(f == 0.0f)); } + +void test17(void) { +#define ASSERT(...) { enum { folded = (__VA_ARGS__) }; int arr[folded ? 1 : -1]; } +#define T(...) ASSERT(__builtin_constant_p(__VA_ARGS__)) +#define F(...) ASSERT(!__builtin_constant_p(__VA_ARGS__)) + + T(3i + 5); + T("string literal"); + F("string literal" + 1); // both-warning {{adding}} \ + // both-note {{use array indexing}} +} `` https://github.com/llvm/llvm-project/pull/137587 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] default clause replaced by otherwise clause for metadirective in OpenMP 5.2 (PR #128640)
@@ -2759,6 +2759,18 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( OpenMPClauseKind CKind = Tok.isAnnotation() ? OMPC_unknown : getOpenMPClauseKind(PP.getSpelling(Tok)); + // Check if the clause is unrecognized. + if (CKind == OMPC_unknown) { +Diag(Tok, diag::err_omp_unknown_clause) +<< PP.getSpelling(Tok) << "metadirective"; ravurvi20 wrote: @alexey-bataev I have addressed it and modified the error messages. Could please take a look at it again. https://github.com/llvm/llvm-project/pull/128640 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Split out and disable tests that break relative rpaths (PR #137411)
compnerd wrote: > > I wonder if we can do this check statically instead. > > I'm not sure I follow, what do you mean by "statically" in this context? Well, if this is less about ensuring the loader does the right thing and more about the encoding, we could simply check that the value for `DT_RPATH` or `DT_RUNPATH` is correct. That can be done by simply strategically inspecting the binary rather than executing the target. https://github.com/llvm/llvm-project/pull/137411 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
@@ -0,0 +1,748 @@ +//===--===// +// +// 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 "ConflictingGlobalAccesses.h" + +#include "clang/AST/RecursiveASTVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +using AccessKind = uint8_t; +static constexpr AccessKind AkRead = 0; +static constexpr AccessKind AkWrite = 1; +static constexpr AccessKind AkUncheckedRead = 2; +static constexpr AccessKind AkUncheckedWrite = 3; + +static constexpr uint8_t AkCount = 4; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArray represents one field inside a global struct/union system. +// The FieldIndexArray can be thought of as a path inside a tree. +using FieldIndex = uint16_t; +static constexpr FieldIndex FiUnion = 0x8000; + +// Note: This bit signals whether the field is a *field of* a struct or a +// union, not whether the type of the field itself is a struct or a union. +using FieldIndexArray = SmallVector; + +/// One traversal recurses into one side of a binary expression or one +/// parameter of a function call. At least two of these traversals are used to +/// find conflicting accesses. +/// +/// A TraversalResult represents one traversal. +struct TraversalResult { + int IndexCreated; // We use indices to keep track of which +// traversal we are in currently. The current +// index is stored in GlobalRWVisitor with the +// name TraversalIndex. + SourceLocation Loc[AkCount]; + TraversalResultKind Kind; + + TraversalResult(); + TraversalResult(int Index, SourceLocation Loc, AccessKind Access); + void addNewAccess(SourceLocation Loc, AccessKind Access); +}; + +/// The result of a number of traversals. +class TraversalAggregation { + DeclarationName DeclName; // The name of the global variable being checked. + + // We only store the result of two traversals as two conflicting accesses + // are enough to detect undefined behavior. The two stored TraversalResults + // have different traversal indices. + // + // Note: Sometimes multiple traversals are merged into one + // TraversalResult. + TraversalResult MainPart, OtherPart; + // Pairings that are not reportable: Read-Read, Read-Write, + // Read-UncheckedRead, Write-Write, UncheckedRead-UncheckedRead. + +public: + TraversalAggregation(); + TraversalAggregation(DeclarationName Name, SourceLocation Loc, + AccessKind Access, int Index); + void addGlobalRW(SourceLocation Loc, AccessKind Access, int Index); + DeclarationName getDeclName() const; + + bool isValid() const; + + // If there is a conflict and that conflict isn't reported by -Wunsequenced + // then we report the conflict. + bool shouldBeReported() const; + bool hasConflictingOperations() const; + +private: + bool hasTwoAccesses() const; + bool isReportedByWunsequenced() const; +}; + +/// The ObjectAccessTree stores the TraversalAggregations of one global +/// struct/union. Because each field can be handled as a single variable, the +/// tree stores one TraversalAggregation for every field. +/// +/// Note: structs, classes, and unions are called objects in the code. +struct ObjectAccessTree { + using FieldMap = llvm::DenseMap>; + TraversalAggregation OwnAccesses; + + // In a union, new fields should inherit from UnionTemporalAccesses + // instead of OwnAccesses. That's because an access to a field of a union is + // also an access to every other field of the same union. + TraversalAggregation UnionTemporalAccesses; + + // We try to be lazy and only store fields that are actually accessed. + FieldMap Fields; + bool IsUnion; + + ObjectAccessTree(TraversalAggregation Own); + + void addFieldToAll(SourceLocation Loc, AccessKind Access, int Index); + void addFieldToAllExcept(uint16_t ExceptIndex, SourceLocation Loc, + AccessKind Access, int Index); +}; + +/// This object is the root of all ObjectAccessTrees. +class ObjectTraversalAggregation { + DeclarationName
[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)
https://github.com/emtwelve edited https://github.com/llvm/llvm-project/pull/123609 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)
@@ -0,0 +1,144 @@ +//===-- TargetVerifier.cpp - LLVM IR Target Verifier *- 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 file defines target verifier interfaces that can be used for some +/ validation of input to the system, and for checking that transformations +/ haven't done something bad. In contrast to the Verifier or Lint, the +/ TargetVerifier looks for constructions invalid to a particular target +/ machine. +/ +/ To see what specifically is checked, look at TargetVerifier.cpp or an +/ individual backend's TargetVerifier. +/ +/===--===// + +#include "llvm/Target/TargetVerifier.h" +#include "llvm/Target/TargetVerify/AMDGPUTargetVerifier.h" + +#include "llvm/InitializePasses.h" +#include "llvm/Analysis/UniformityAnalysis.h" +#include "llvm/Analysis/PostDominators.h" +#include "llvm/Support/Debug.h" +#include "llvm/IR/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/IntrinsicsAMDGPU.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" + +namespace llvm { + +bool TargetVerify::run(Function &F) { + if (TT.isAMDGPU()) { +AMDGPUTargetVerify TV(Mod); +TV.run(F); + +dbgs() << TV.MessagesStr.str(); +if (!TV.MessagesStr.str().empty()) { + TV.IsValid = false; + return false; +} +return true; + } + report_fatal_error("Target has no verification method\n"); +} + +bool TargetVerify::run(Function &F, FunctionAnalysisManager &AM) { + if (TT.isAMDGPU()) { +auto *UA = &AM.getResult(F); +auto *DT = &AM.getResult(F); +auto *PDT = &AM.getResult(F); + +AMDGPUTargetVerify TV(Mod, DT, PDT, UA); +TV.run(F); + +dbgs() << TV.MessagesStr.str(); +if (!TV.MessagesStr.str().empty()) { + TV.IsValid = false; + return false; +} +return true; + } + report_fatal_error("Target has no verification method\n"); +} + +PreservedAnalyses TargetVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { + auto TT = F.getParent()->getTargetTriple(); + + if (TT.isAMDGPU()) { +auto *Mod = F.getParent(); + +auto UA = &AM.getResult(F); +auto *DT = &AM.getResult(F); +auto *PDT = &AM.getResult(F); + +AMDGPUTargetVerify TV(Mod, DT, PDT, UA); emtwelve wrote: That is correct. We aren't allowed to put state that changes in Module, so I resorted to checking PreservedAnalyses. It seems to work in this way, and adding the other classes to check doesn't change anything. All of them can be checked through this call somehow. I'm looking for another way to do this. https://github.com/llvm/llvm-project/pull/123609 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)
https://github.com/emtwelve deleted https://github.com/llvm/llvm-project/pull/123609 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added Conflicting Global Accesses checker (PR #130421)
https://github.com/ConcreteCactus updated https://github.com/llvm/llvm-project/pull/130421 >From 7b0272121336a36b68e8e2782bb2b6e7007c4c1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= Date: Fri, 22 Nov 2024 21:43:04 +0100 Subject: [PATCH] [clang-tidy] Added Conflicting Global Accesses checker This checker attempts to detect unsequenced accesses to global variables. It recurses into function calls in the same translation unit, and can handle fields on global structs/unions. --- .../bugprone/BugproneTidyModule.cpp | 3 + .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../ConflictingGlobalAccessesCheck.cpp| 825 ++ .../bugprone/ConflictingGlobalAccessesCheck.h | 35 + .../clang-tidy/cert/CERTTidyModule.cpp| 6 + .../clang-tidy/utils/ExecutionVisitor.h | 190 clang-tools-extra/docs/ReleaseNotes.rst | 14 + .../bugprone/conflicting-global-accesses.rst | 72 ++ .../docs/clang-tidy/checks/list.rst | 3 + .../bugprone/conflicting-global-accesses.cpp | 599 + 10 files changed, 1748 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.h create mode 100644 clang-tools-extra/clang-tidy/utils/ExecutionVisitor.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/conflicting-global-accesses.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/conflicting-global-accesses.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index b780a85bdf3fe..aa966a2278ca9 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -20,6 +20,7 @@ #include "CastingThroughVoidCheck.h" #include "ChainedComparisonCheck.h" #include "ComparePointerToMemberVirtualFunctionCheck.h" +#include "ConflictingGlobalAccessesCheck.h" #include "CopyConstructorInitCheck.h" #include "CrtpConstructorAccessibilityCheck.h" #include "DanglingHandleCheck.h" @@ -127,6 +128,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-chained-comparison"); CheckFactories.registerCheck( "bugprone-compare-pointer-to-member-virtual-function"); +CheckFactories.registerCheck( +"bugprone-conflicting-global-accesses"); CheckFactories.registerCheck( "bugprone-copy-constructor-init"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index e310ea9c94543..f04adca18a5ca 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -16,6 +16,7 @@ add_clang_library(clangTidyBugproneModule STATIC CastingThroughVoidCheck.cpp ChainedComparisonCheck.cpp ComparePointerToMemberVirtualFunctionCheck.cpp + ConflictingGlobalAccessesCheck.cpp CopyConstructorInitCheck.cpp CrtpConstructorAccessibilityCheck.cpp DanglingHandleCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp new file mode 100644 index 0..f48822ee8153b --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccessesCheck.cpp @@ -0,0 +1,825 @@ +//===--===// +// +// 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 "ConflictingGlobalAccessesCheck.h" + +#include "../utils/ExecutionVisitor.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +// An AccesKind represents one access to a global variable. +// +// The unchecked versions represent reads/writes that are not handled by +// -Wunsequenced. (e.g. accesses inside functions). +enum AccessKind : uint8_t { + AkRead = 0, + AkWrite, + AkUncheckedRead, + AkUncheckedWrite, + AkLast +}; + +static constexpr uint8_t AkCount = AkLast; + +// The TraversalResultKind represents a set of accesses. +// Bits are corresponding to the AccessKind enum values. +using TraversalResultKind = uint8_t; +static constexpr TraversalResultKind TrInvalid = 0; +static constexpr TraversalResultKind TrRead = 1 << AkRead; +static constexpr TraversalResultKind TrWrite = 1 << AkWrite; +static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite; + +// To represent fields in structs or unions we use numbered FieldIndices. The +// FieldIndexArra
[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)
https://github.com/jofrn edited https://github.com/llvm/llvm-project/pull/123609 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)
@@ -0,0 +1,144 @@ +//===-- TargetVerifier.cpp - LLVM IR Target Verifier *- 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 file defines target verifier interfaces that can be used for some +/ validation of input to the system, and for checking that transformations +/ haven't done something bad. In contrast to the Verifier or Lint, the +/ TargetVerifier looks for constructions invalid to a particular target +/ machine. +/ +/ To see what specifically is checked, look at TargetVerifier.cpp or an +/ individual backend's TargetVerifier. +/ +/===--===// + +#include "llvm/Target/TargetVerifier.h" +#include "llvm/Target/TargetVerify/AMDGPUTargetVerifier.h" + +#include "llvm/InitializePasses.h" +#include "llvm/Analysis/UniformityAnalysis.h" +#include "llvm/Analysis/PostDominators.h" +#include "llvm/Support/Debug.h" +#include "llvm/IR/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/IntrinsicsAMDGPU.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" + +namespace llvm { + +bool TargetVerify::run(Function &F) { + if (TT.isAMDGPU()) { +AMDGPUTargetVerify TV(Mod); +TV.run(F); + +dbgs() << TV.MessagesStr.str(); +if (!TV.MessagesStr.str().empty()) { + TV.IsValid = false; + return false; +} +return true; + } + report_fatal_error("Target has no verification method\n"); +} + +bool TargetVerify::run(Function &F, FunctionAnalysisManager &AM) { + if (TT.isAMDGPU()) { +auto *UA = &AM.getResult(F); +auto *DT = &AM.getResult(F); +auto *PDT = &AM.getResult(F); + +AMDGPUTargetVerify TV(Mod, DT, PDT, UA); +TV.run(F); + +dbgs() << TV.MessagesStr.str(); +if (!TV.MessagesStr.str().empty()) { + TV.IsValid = false; + return false; +} +return true; + } + report_fatal_error("Target has no verification method\n"); +} + +PreservedAnalyses TargetVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { + auto TT = F.getParent()->getTargetTriple(); + + if (TT.isAMDGPU()) { +auto *Mod = F.getParent(); + +auto UA = &AM.getResult(F); +auto *DT = &AM.getResult(F); +auto *PDT = &AM.getResult(F); + +AMDGPUTargetVerify TV(Mod, DT, PDT, UA); jofrn wrote: That is correct. We aren't allowed to put state that changes in Module, so I resorted to checking PreservedAnalyses. It seems to work in this way, and adding the other classes to check doesn't change anything. All of them can be checked through this call somehow, but I'm looking for another way to do this. https://github.com/llvm/llvm-project/pull/123609 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Diagnose heap-allocated array elem pointers... (PR #137523)
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/137523 ... as "pointer to subobject". >From af8eadcf3930667b5b6b215df8312c21e9f4381a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= Date: Sun, 27 Apr 2025 17:33:13 +0200 Subject: [PATCH] [clang][bytecode] Diagnose heap-allocated array elem pointers... ... as "pointer to subobject". --- clang/lib/AST/ByteCode/EvaluationResult.cpp | 3 ++- clang/test/AST/ByteCode/new-delete.cpp | 4 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/clang/lib/AST/ByteCode/EvaluationResult.cpp b/clang/lib/AST/ByteCode/EvaluationResult.cpp index d603e08c7bb4d..f59612bf00015 100644 --- a/clang/lib/AST/ByteCode/EvaluationResult.cpp +++ b/clang/lib/AST/ByteCode/EvaluationResult.cpp @@ -230,8 +230,9 @@ bool EvaluationResult::checkReturnValue(InterpState &S, const Context &Ctx, assert(B->getDescriptor()); assert(B->getDescriptor()->asExpr()); + bool IsSubobj = !Ptr.isRoot() || Ptr.isArrayElement(); S.FFDiag(Info, diag::note_constexpr_dynamic_alloc) - << Ptr.getType()->isReferenceType() << !Ptr.isRoot(); + << Ptr.getType()->isReferenceType() << IsSubobj; S.Note(B->getDescriptor()->asExpr()->getExprLoc(), diag::note_constexpr_dynamic_alloc_here); return false; diff --git a/clang/test/AST/ByteCode/new-delete.cpp b/clang/test/AST/ByteCode/new-delete.cpp index e1b81e9a7963e..3de527c881680 100644 --- a/clang/test/AST/ByteCode/new-delete.cpp +++ b/clang/test/AST/ByteCode/new-delete.cpp @@ -619,6 +619,10 @@ namespace std { } } +constexpr int *escape = std::allocator().allocate(3); // both-error {{constant expression}} \ + // both-note {{pointer to subobject of heap-allocated}} \ + // both-note {{heap allocation performed here}} + /// Specialization for float, using operator new/delete. namespace std { using size_t = decltype(sizeof(0)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Diagnose heap-allocated array elem pointers... (PR #137523)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Timm Baeder (tbaederr) Changes ... as "pointer to subobject". --- Full diff: https://github.com/llvm/llvm-project/pull/137523.diff 2 Files Affected: - (modified) clang/lib/AST/ByteCode/EvaluationResult.cpp (+2-1) - (modified) clang/test/AST/ByteCode/new-delete.cpp (+4) ``diff diff --git a/clang/lib/AST/ByteCode/EvaluationResult.cpp b/clang/lib/AST/ByteCode/EvaluationResult.cpp index d603e08c7bb4d..f59612bf00015 100644 --- a/clang/lib/AST/ByteCode/EvaluationResult.cpp +++ b/clang/lib/AST/ByteCode/EvaluationResult.cpp @@ -230,8 +230,9 @@ bool EvaluationResult::checkReturnValue(InterpState &S, const Context &Ctx, assert(B->getDescriptor()); assert(B->getDescriptor()->asExpr()); + bool IsSubobj = !Ptr.isRoot() || Ptr.isArrayElement(); S.FFDiag(Info, diag::note_constexpr_dynamic_alloc) - << Ptr.getType()->isReferenceType() << !Ptr.isRoot(); + << Ptr.getType()->isReferenceType() << IsSubobj; S.Note(B->getDescriptor()->asExpr()->getExprLoc(), diag::note_constexpr_dynamic_alloc_here); return false; diff --git a/clang/test/AST/ByteCode/new-delete.cpp b/clang/test/AST/ByteCode/new-delete.cpp index e1b81e9a7963e..3de527c881680 100644 --- a/clang/test/AST/ByteCode/new-delete.cpp +++ b/clang/test/AST/ByteCode/new-delete.cpp @@ -619,6 +619,10 @@ namespace std { } } +constexpr int *escape = std::allocator().allocate(3); // both-error {{constant expression}} \ + // both-note {{pointer to subobject of heap-allocated}} \ + // both-note {{heap allocation performed here}} + /// Specialization for float, using operator new/delete. namespace std { using size_t = decltype(sizeof(0)); `` https://github.com/llvm/llvm-project/pull/137523 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Do not pass any file when listing checks in run_clang_ti… (PR #137286)
https://github.com/HerrCai0907 approved this pull request. https://github.com/llvm/llvm-project/pull/137286 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [llvm] [X86] Implement disabling APX relocations and EPGR/NDD instrs for relocations (PR #136660)
https://github.com/fzou1 edited https://github.com/llvm/llvm-project/pull/136660 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits