[clang] [libcxx] [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (PR #78707)
https://github.com/huixie90 updated
https://github.com/llvm/llvm-project/pull/78707
>From 0dc5bf91516e2138ed73b602cb17943ef6bcc878 Mon Sep 17 00:00:00 2001
From: Hui
Date: Fri, 19 Jan 2024 12:33:43 +
Subject: [PATCH 1/8] [libc++] fix _Atomic c11 compare exchange does not update
expected results
---
clang/lib/CodeGen/CGAtomic.cpp | 61 +-
1 file changed, 37 insertions(+), 24 deletions(-)
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 4a3446abcc78f..01d02c2dbed45 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -376,6 +376,7 @@ bool AtomicInfo::emitMemSetZeroIfNecessary() const {
static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
Address Dest, Address Ptr,
Address Val1, Address Val2,
+ Address ExpectedResult,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
llvm::AtomicOrdering FailureOrder,
@@ -411,9 +412,17 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
CGF.Builder.SetInsertPoint(StoreExpectedBB);
// Update the memory at Expected with Old's value.
- auto *I = CGF.Builder.CreateStore(Old, Val1);
- CGF.addInstToCurrentSourceAtom(I, Old);
+ llvm::Type *ExpectedType = ExpectedResult.getElementType();
+ uint64_t OriginalSizeInBits =
CGF.CGM.getDataLayout().getTypeSizeInBits(ExpectedType);
+ if (OriginalSizeInBits / 8 == Size) {
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ } else {
+// How to just store N bytes to ExpectedResult ?
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ }
// Finally, branch to the exit point.
CGF.Builder.CreateBr(ContinueBB);
@@ -428,6 +437,7 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
bool IsWeak, Address Dest, Address Ptr,
Address Val1, Address Val2,
+Address ExpectedResult,
llvm::Value *FailureOrderVal,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
@@ -458,7 +468,7 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// success argument". This condition has been lifted and the only
// precondition is 31.7.2.18. Effectively treat this as a DR and skip
// language version checks.
-emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size,
SuccessOrder,
+emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
FailureOrder, Scope);
return;
}
@@ -483,17 +493,17 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// Emit all the different atomics
CGF.Builder.SetInsertPoint(MonotonicBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder, llvm::AtomicOrdering::Monotonic,
Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(AcquireBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::Acquire, Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(SeqCstBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::SequentiallyConsistent, Scope);
CGF.Builder.CreateBr(ContBB);
@@ -526,6 +536,7 @@ static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy
&Builder,
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
Address Ptr, Address Val1, Address Val2,
+ Address ExpectedResult,
llvm::Value *IsWeak, llvm::Value *FailureOrder,
uint64_t Size, llvm::AtomicOrdering Order,
llvm::SyncScope::ID Scope) {
@@ -542,13 +553,13 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr
*E, Address Dest,
case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
-FailureO
[clang] [libcxx] [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (PR #78707)
@@ -0,0 +1,70 @@ +//===--===// +// +// 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 +// +//===--===// + +// https://github.com/llvm/llvm-project/issues/30023 +// compare exchange does not work with types of which the size is not a power of 2 + +// XFAIL: clang-20, clang-21, apple-clang-15, apple-clang-16, apple-clang-17 huixie90 wrote: Discussed with @ldionne offline. We agreed to `UNSUPPORTED: clang-22` as suggested with a TODO. once libc++'s CI's docker image is updated with clang with this patch, we can re-enable the test https://github.com/llvm/llvm-project/pull/78707 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] VectorExprEvaluator::VisitCallExpr / InterpretBuiltin - allow AVX/AVX512 subvector extraction intrinsics to be used in constexpr #157712 (PR #162836)
https://github.com/RKSimon auto_merge_enabled https://github.com/llvm/llvm-project/pull/162836 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxx] [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (PR #78707)
https://github.com/huixie90 updated
https://github.com/llvm/llvm-project/pull/78707
>From 0dc5bf91516e2138ed73b602cb17943ef6bcc878 Mon Sep 17 00:00:00 2001
From: Hui
Date: Fri, 19 Jan 2024 12:33:43 +
Subject: [PATCH 01/10] [libc++] fix _Atomic c11 compare exchange does not
update expected results
---
clang/lib/CodeGen/CGAtomic.cpp | 61 +-
1 file changed, 37 insertions(+), 24 deletions(-)
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 4a3446abcc78f..01d02c2dbed45 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -376,6 +376,7 @@ bool AtomicInfo::emitMemSetZeroIfNecessary() const {
static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
Address Dest, Address Ptr,
Address Val1, Address Val2,
+ Address ExpectedResult,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
llvm::AtomicOrdering FailureOrder,
@@ -411,9 +412,17 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
CGF.Builder.SetInsertPoint(StoreExpectedBB);
// Update the memory at Expected with Old's value.
- auto *I = CGF.Builder.CreateStore(Old, Val1);
- CGF.addInstToCurrentSourceAtom(I, Old);
+ llvm::Type *ExpectedType = ExpectedResult.getElementType();
+ uint64_t OriginalSizeInBits =
CGF.CGM.getDataLayout().getTypeSizeInBits(ExpectedType);
+ if (OriginalSizeInBits / 8 == Size) {
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ } else {
+// How to just store N bytes to ExpectedResult ?
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ }
// Finally, branch to the exit point.
CGF.Builder.CreateBr(ContinueBB);
@@ -428,6 +437,7 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
bool IsWeak, Address Dest, Address Ptr,
Address Val1, Address Val2,
+Address ExpectedResult,
llvm::Value *FailureOrderVal,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
@@ -458,7 +468,7 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// success argument". This condition has been lifted and the only
// precondition is 31.7.2.18. Effectively treat this as a DR and skip
// language version checks.
-emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size,
SuccessOrder,
+emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
FailureOrder, Scope);
return;
}
@@ -483,17 +493,17 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// Emit all the different atomics
CGF.Builder.SetInsertPoint(MonotonicBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder, llvm::AtomicOrdering::Monotonic,
Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(AcquireBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::Acquire, Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(SeqCstBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::SequentiallyConsistent, Scope);
CGF.Builder.CreateBr(ContBB);
@@ -526,6 +536,7 @@ static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy
&Builder,
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
Address Ptr, Address Val1, Address Val2,
+ Address ExpectedResult,
llvm::Value *IsWeak, llvm::Value *FailureOrder,
uint64_t Size, llvm::AtomicOrdering Order,
llvm::SyncScope::ID Scope) {
@@ -542,13 +553,13 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr
*E, Address Dest,
case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
-Failur
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
@@ -683,61 +690,8 @@ void WhitespaceManager::alignConsecutiveMacros() {
return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
};
- unsigned MinColumn = 0;
-
- // Start and end of the token sequence we're processing.
- unsigned StartOfSequence = 0;
- unsigned EndOfSequence = 0;
-
- // Whether a matching token has been found on the current line.
- bool FoundMatchOnLine = false;
-
- // Whether the current line consists only of comments
- bool LineIsComment = true;
-
- unsigned I = 0;
- for (unsigned E = Changes.size(); I != E; ++I) {
-if (Changes[I].NewlinesBefore != 0) {
- EndOfSequence = I;
-
- // Whether to break the alignment sequence because of an empty line.
- bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
-!Style.AlignConsecutiveMacros.AcrossEmptyLines;
-
- // Whether to break the alignment sequence because of a line without a
- // match.
- bool NoMatchBreak =
- !FoundMatchOnLine &&
- !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
-
- if (EmptyLineBreak || NoMatchBreak) {
-AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
- }
-
- // A new line starts, re-initialize line status tracking bools.
- FoundMatchOnLine = false;
- LineIsComment = true;
-}
-
-if (Changes[I].Tok->isNot(tok::comment))
- LineIsComment = false;
-
-if (!AlignMacrosMatches(Changes[I]))
- continue;
-
-FoundMatchOnLine = true;
-
-if (StartOfSequence == 0)
- StartOfSequence = I;
-
-unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
-MinColumn = std::max(MinColumn, ChangeMinColumn);
- }
-
- EndOfSequence = I;
- AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
+ AlignTokens(
owenca wrote:
`/*SimpleCheck=*/true` instead?
https://github.com/llvm/llvm-project/pull/164120
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/164120 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
@@ -536,14 +540,17 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
if (CurrentChange.Tok->isNot(tok::comment))
LineIsComment = false;
-if (CurrentChange.Tok->is(tok::comma)) {
- ++CommasBeforeMatch;
-} else if (CurrentChange.indentAndNestingLevel() > IndentAndNestingLevel) {
- // Call AlignTokens recursively, skipping over this scope block.
- unsigned StoppedAt =
- AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
- i = StoppedAt - 1;
- continue;
+if (!SimpleCheck) {
+ if (CurrentChange.Tok->is(tok::comma)) {
+++CommasBeforeMatch;
+ } else if (CurrentChange.indentAndNestingLevel() >
+ IndentAndNestingLevel) {
+// Call AlignTokens recursively, skipping over this scope block.
+unsigned StoppedAt =
owenca wrote:
```suggestion
const auto StoppedAt =
```
https://github.com/llvm/llvm-project/pull/164120
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Do not warn on UTF-16 -> UTF-32 conversions. (PR #163927)
https://github.com/cor3ntin closed https://github.com/llvm/llvm-project/pull/163927 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 3a15687 - [Clang] Do not warn on UTF-16 -> UTF-32 conversions. (#163927)
Author: Corentin Jabot
Date: 2025-10-19T09:26:22+02:00
New Revision: 3a15687d1c789ebac04bf394ec31f95331c74bf8
URL:
https://github.com/llvm/llvm-project/commit/3a15687d1c789ebac04bf394ec31f95331c74bf8
DIFF:
https://github.com/llvm/llvm-project/commit/3a15687d1c789ebac04bf394ec31f95331c74bf8.diff
LOG: [Clang] Do not warn on UTF-16 -> UTF-32 conversions. (#163927)
UTF-16 to UTF-16 conversions seems widespread,
and lone surrogate have a distinct representation in UTF-32.
Lets not warn on this case to make the warning easier to adopt. This
follows SG-16 guideline
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3695r2.html#changes-since-r1
Fixes #163719
Added:
Modified:
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaCXX/warn-implicit-unicode-conversions.cpp
Removed:
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 652527a88b160..ef1be23dcf277 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -12309,13 +12309,20 @@ static void
DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
SourceLocation CC) {
assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()
&&
Source != Target);
+
+ // Lone surrogates have a distinct representation in UTF-32.
+ // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
+ // so don't warn on such conversion.
+ if (Source->isChar16Type() && Target->isChar32Type())
+return;
+
Expr::EvalResult Result;
if (E->EvaluateAsInt(Result, S.getASTContext(), Expr::SE_AllowSideEffects,
S.isConstantEvaluatedContext())) {
llvm::APSInt Value(32);
Value = Result.Val.getInt();
bool IsASCII = Value <= 0x7F;
-bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0x);
+bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0x);
bool ConversionPreservesSemantics =
IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
diff --git a/clang/test/SemaCXX/warn-implicit-unicode-conversions.cpp
b/clang/test/SemaCXX/warn-implicit-unicode-conversions.cpp
index fcff006d0e028..f17f20ca25295 100644
--- a/clang/test/SemaCXX/warn-implicit-unicode-conversions.cpp
+++ b/clang/test/SemaCXX/warn-implicit-unicode-conversions.cpp
@@ -14,7 +14,7 @@ void test(char8_t u8, char16_t u16, char32_t u32) {
c16(u32); // expected-warning {{implicit conversion from 'char32_t' to
'char16_t' may lose precision and change the meaning of the represented code
unit}}
c32(u8); // expected-warning {{implicit conversion from 'char8_t' to
'char32_t' may change the meaning of the represented code unit}}
-c32(u16); // expected-warning {{implicit conversion from 'char16_t' to
'char32_t' may change the meaning of the represented code unit}}
+c32(u16);
c32(u32);
@@ -30,7 +30,7 @@ void test(char8_t u8, char16_t u16, char32_t u32) {
c16(char32_t(0x7f));
c16(char32_t(0x80));
c16(char32_t(0xD7FF));
-c16(char32_t(0xD800)); // expected-warning {{implicit conversion from
'char32_t' to 'char16_t' changes the meaning of the code unit '<0xD800>'}}
+c16(char32_t(0xD800));
c16(char32_t(0xE000));
c16(char32_t(U'🐉')); // expected-warning {{implicit conversion from
'char32_t' to 'char16_t' changes the meaning of the code point '🐉'}}
@@ -44,8 +44,8 @@ void test(char8_t u8, char16_t u16, char32_t u32) {
c32(char16_t(0x80));
c32(char16_t(0xD7FF));
-c32(char16_t(0xD800)); // expected-warning {{implicit conversion from
'char16_t' to 'char32_t' changes the meaning of the code unit '<0xD800>'}}
-c32(char16_t(0xDFFF)); // expected-warning {{implicit conversion from
'char16_t' to 'char32_t' changes the meaning of the code unit '<0xDFFF>'}}
+c32(char16_t(0xD800));
+c32(char16_t(0xDFFF));
c32(char16_t(0xE000));
c32(char16_t(u'☕'));
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Consider reachability for file-scope warnings on initializers (PR #163885)
@@ -581,3 +581,28 @@ bool
Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
return !trailingComma;
}
+
+ExprResult Parser::ParseInitializer(Decl *DeclForInitializer) {
+ // Set DeclForInitializer for file-scope variables.
+ // For constexpr references, set it to suppress runtime warnings.
+ // For non-constexpr references, don't set it to avoid evaluation issues
+ // with self-referencing initializers. Local variables (including local
+ // constexpr) should emit runtime warnings.
+ if (DeclForInitializer && !Actions.ExprEvalContexts.empty()) {
+if (auto *VD = dyn_cast(DeclForInitializer);
+VD && VD->isFileVarDecl()) {
+ if (!VD->getType()->isReferenceType() || VD->isConstexpr()) {
+Actions.ExprEvalContexts.back().DeclForInitializer = VD;
+ }
cor3ntin wrote:
```suggestion
if (auto *VD = dyn_cast(DeclForInitializer);
VD && VD->isFileVarDecl() && (!VD->getType()->isReferenceType() ||
VD->isConstexpr()))
Actions.ExprEvalContexts.back().DeclForInitializer = VD;
```
https://github.com/llvm/llvm-project/pull/163885
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Consider reachability for file-scope warnings on initializers (PR #163885)
@@ -13727,6 +13734,16 @@ void Sema::DiagnoseUniqueObjectDuplication(const
VarDecl *VD) {
}
void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
+ // RAII helper to ensure DeclForInitializer is cleared on all exit paths
+ struct ClearDeclForInitializer {
+Sema &S;
+ClearDeclForInitializer(Sema &S) : S(S) {}
+~ClearDeclForInitializer() {
+ if (!S.ExprEvalContexts.empty())
+S.ExprEvalContexts.back().DeclForInitializer = nullptr;
+}
+ } Clearer(*this);
cor3ntin wrote:
It would be simpler to use `make_scope_exit` here
https://github.com/llvm/llvm-project/pull/163885
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Consider reachability for file-scope warnings on initializers (PR #163885)
@@ -6750,6 +6750,11 @@ class Sema final : public SemaBase {
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
+/// Declaration for initializer if one is currently being
+/// parsed. Used when an expression has a possibly unreachable
+/// diagnostic to reference the declaration as a whole.
+VarDecl *DeclForInitializer = nullptr;
cor3ntin wrote:
Would that be ever different from ManglingContextDecl? Can we reuse that?
https://github.com/llvm/llvm-project/pull/163885
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Consider reachability for file-scope warnings on initializers (PR #163885)
@@ -581,3 +581,28 @@ bool
Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
return !trailingComma;
}
+
+ExprResult Parser::ParseInitializer(Decl *DeclForInitializer) {
+ // Set DeclForInitializer for file-scope variables.
+ // For constexpr references, set it to suppress runtime warnings.
+ // For non-constexpr references, don't set it to avoid evaluation issues
+ // with self-referencing initializers. Local variables (including local
+ // constexpr) should emit runtime warnings.
+ if (DeclForInitializer && !Actions.ExprEvalContexts.empty()) {
+if (auto *VD = dyn_cast(DeclForInitializer);
+VD && VD->isFileVarDecl()) {
+ if (!VD->getType()->isReferenceType() || VD->isConstexpr()) {
+Actions.ExprEvalContexts.back().DeclForInitializer = VD;
+ }
cor3ntin wrote:
I think we should set `DeclForInitializer` unconditionally, and check if it's a
non-constexpr ref in `MarkDeclarationsReferencedInExpr`
https://github.com/llvm/llvm-project/pull/163885
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Consider reachability for file-scope warnings on initializers (PR #163885)
@@ -116,6 +126,10 @@ class AnalysisBasedWarnings {
Policy &getPolicyOverrides() { return PolicyOverrides; }
void PrintStats() const;
+
+ void
+ EmitPossiblyUnreachableDiags(AnalysisDeclContext &AC,
+ SmallVector PUDs);
cor3ntin wrote:
This could be a static function in AnalysisBasedWarnings.cpp to avoid forward
references of AnalysisDeclContext in Sema.
https://github.com/llvm/llvm-project/pull/163885
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] vTableClassNameForType: return correct VTableClass name for Type::ObjCObjectPointer, Type::Pointer (PR #163850)
n2h9 wrote: I have just walked through this code in debugger, and looks like when we throw pointer to int, we do not reach this case ``` case Type::ObjCObjectPointer: case Type::Pointer: return "_ZTVN10__cxxabiv119__pointer_type_infoE"; ``` we reach it if we throw pointer to object. But in that case I receive `error: ClangIR code gen Not Yet Implemented: buildTypeInfo: Pointer` let me check how to handle this :blush: https://github.com/llvm/llvm-project/pull/163850 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] vTableClassNameForType: return correct VTableClass name for Type::ObjCObjectPointer, Type::Pointer (PR #163850)
https://github.com/n2h9 converted_to_draft https://github.com/llvm/llvm-project/pull/163850 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Apply DeMorgan to overloaded operator in the 'readability-simplify-boolean-expr' check (PR #164141)
@@ -829,22 +829,22 @@ static bool flipDemorganSide(SmallVectorImpl
&Fixes,
const ASTContext &Ctx, const Expr *E,
std::optional OuterBO);
-/// Inverts \p BinOp, Removing \p Parens if they exist and are safe to remove.
-/// returns \c true if there is any issue building the Fixes, \c false
-/// otherwise.
-static bool
-flipDemorganBinaryOperator(SmallVectorImpl &Fixes,
- const ASTContext &Ctx, const BinaryOperator *BinOp,
- std::optional OuterBO,
- const ParenExpr *Parens = nullptr) {
- switch (BinOp->getOpcode()) {
+/// Inverts \p BO, \p LHS, and \p RHS, Removing \p Parens if they exist and are
+/// safe to remove. returns \c true if there is any issue building the Fixes,
\c
+/// false otherwise.
+static bool flipDemorganBinaryOperator(
+SmallVectorImpl &Fixes, const ASTContext &Ctx,
+BinaryOperatorKind BO, const Expr *LHS, const Expr *RHS, SourceRange Range,
vbvictor wrote:
Could we give a more meaningful name for `Range`? From where to where this
range is
https://github.com/llvm/llvm-project/pull/164141
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] VectorExprEvaluator::VisitCallExpr / InterpretBuiltin - allow AVX/AVX512 subvector extraction intrinsics to be used in constexpr #157712 (PR #162836)
https://github.com/RKSimon updated
https://github.com/llvm/llvm-project/pull/162836
>From 3128a37fa669b00235b06f577dd5bf8354b2265e Mon Sep 17 00:00:00 2001
From: SeongjaeP
Date: Thu, 9 Oct 2025 14:25:24 +0900
Subject: [PATCH 01/12] Apply style fixes and rebase onto upstream
---
clang/lib/AST/ExprConstant.cpp | 75 ++
1 file changed, 75 insertions(+)
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 35a866ea5010f..5ac7837aa0fe3 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11769,6 +11769,81 @@ bool VectorExprEvaluator::VisitCallExpr(const CallExpr
*E) {
return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
});
+
+ case X86::BI__builtin_ia32_extract128i256:
+ case X86::BI__builtin_ia32_vextractf128_pd256:
+ case X86::BI__builtin_ia32_vextractf128_ps256:
+ case X86::BI__builtin_ia32_vextractf128_si256: {
+APValue SourceVec, SourceImm;
+if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
+!EvaluateAsRValue(Info, E->getArg(1), SourceImm))
+ return false;
+
+if (!SourceVec.isVector())
+ return false;
+
+const auto *RetVT = E->getType()->castAs();
+if (!RetVT) return false;
+
+unsigned RetLen = RetVT->getNumElements();
+unsigned SrcLen = SourceVec.getVectorLength();
+if (SrcLen != RetLen * 2)
+ return false;
+
+unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
+
+SmallVector ResultElements;
+ResultElements.reserve(RetLen);
+
+for (unsigned I = 0; I < RetLen; I++)
+ ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
+
+return Success(APValue(ResultElements.data(), RetLen), E);
+ }
+
+ case X86::BI__builtin_ia32_extracti32x4_256_mask:
+ case X86::BI__builtin_ia32_extractf32x4_256_mask:
+ case X86::BI__builtin_ia32_extracti32x4_mask:
+ case X86::BI__builtin_ia32_extractf32x4_mask:
+ case X86::BI__builtin_ia32_extracti32x8_mask:
+ case X86::BI__builtin_ia32_extractf32x8_mask:
+ case X86::BI__builtin_ia32_extracti64x2_256_mask:
+ case X86::BI__builtin_ia32_extractf64x2_256_mask:
+ case X86::BI__builtin_ia32_extracti64x2_512_mask:
+ case X86::BI__builtin_ia32_extractf64x2_512_mask:
+ case X86::BI__builtin_ia32_extracti64x4_mask:
+ case X86::BI__builtin_ia32_extractf64x4_mask:{
+APValue SourceVec, MergeVec;
+APSInt Imm, MaskImm;
+
+if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
+ !EvaluateInteger(E->getArg(1), Imm, Info) ||
+ !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
+ !EvaluateInteger(E->getArg(3), MaskImm, Info))
+return false;
+
+const auto *RetVT = E->getType()->castAs();
+unsigned RetLen = RetVT->getNumElements();
+
+if (!SourceVec.isVector() || !MergeVec.isVector()) return false;
+unsigned SrcLen = SourceVec.getVectorLength();
+if (!SrcLen || !RetLen || (SrcLen % RetLen) != 0) return false;
+
+unsigned Lanes = SrcLen / RetLen;
+unsigned Lane = static_cast(Imm.getZExtValue() % Lanes);
+unsigned Base = Lane * RetLen;
+uint64_t Mask = MaskImm.getZExtValue();
+
+SmallVector ResultElements;
+ResultElements.reserve(RetLen);
+for (unsigned I = 0; I < RetLen; ++I) {
+ if ((Mask >> I) & 1)
+ResultElements.push_back(SourceVec.getVectorElt(Base + I));
+ else
+ResultElements.push_back(MergeVec.getVectorElt(I));
+}
+return Success(APValue(ResultElements.data(), ResultElements.size()), E);
+ }
case clang::X86::BI__builtin_ia32_pavgb128:
case clang::X86::BI__builtin_ia32_pavgw128:
>From d6b83cc0817fb596393f8f72f0f8bd6d99669f4e Mon Sep 17 00:00:00 2001
From: SeongjaeP
Date: Fri, 26 Sep 2025 11:20:04 +0900
Subject: [PATCH 02/12] Refactoring and Test Pass
---
clang/test/CodeGen/X86/avx2-builtins.c | 2 ++
1 file changed, 2 insertions(+)
diff --git a/clang/test/CodeGen/X86/avx2-builtins.c
b/clang/test/CodeGen/X86/avx2-builtins.c
index 55f18f947b96f..de33b72995f5c 100644
--- a/clang/test/CodeGen/X86/avx2-builtins.c
+++ b/clang/test/CodeGen/X86/avx2-builtins.c
@@ -466,6 +466,8 @@ __m128i test0_mm256_extracti128_si256_0(__m256i a) {
// CHECK: shufflevector <4 x i64> %{{.*}}, <4 x i64> poison, <2 x i32>
return _mm256_extracti128_si256(a, 0);
}
+TEST_CONSTEXPR(match_m128i(_mm256_extracti128_si256(((__m256i){1ULL, 2ULL,
3ULL, 4ULL}), 0),
+ 1ULL, 2ULL));
__m128i test1_mm256_extracti128_si256_1(__m256i a) {
// CHECK-LABEL: test1_mm256_extracti128_si256
>From 7525eecb29aaa916d0192a34ced9b3b6b3226458 Mon Sep 17 00:00:00 2001
From: seongjaep
Date: Fri, 10 Oct 2025 20:55:43 +0900
Subject: [PATCH 03/12] Add Constexpr
---
clang/include/clang/Basic/BuiltinsX86.td | 14 +++---
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/clang/include/clang/Basic/BuiltinsX86.td
b/clang
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 4/N (PR #164158)
https://github.com/vbvictor created
https://github.com/llvm/llvm-project/pull/164158
Continue https://github.com/llvm/llvm-project/pull/153885.
>From b071fadcd81db36a006c13ef904bfcf8b12ca6d9 Mon Sep 17 00:00:00 2001
From: Victor Baranov
Date: Sun, 19 Oct 2025 15:30:44 +0300
Subject: [PATCH] [clang-tidy][NFC] Fix
llvm-prefer-static-over-anonymous-namespace warnings 4/N
---
.../abseil/FasterStrsplitDelimiterCheck.cpp | 8 +++
.../bugprone/ChainedComparisonCheck.cpp | 4 ++--
.../bugprone/DanglingHandleCheck.cpp | 16 +-
.../bugprone/SizeofExpressionCheck.cpp| 6 ++---
.../bugprone/StringConstructorCheck.cpp | 5 ++---
.../google/GlobalVariableDeclarationCheck.cpp | 5 +++--
.../llvmlibc/InlineFunctionDeclCheck.cpp | 6 +
.../clang-tidy/misc/UnusedParametersCheck.cpp | 8 +++
.../modernize/RedundantVoidArgCheck.cpp | 22 ---
.../modernize/UseStdNumbersCheck.cpp | 14 ++--
.../clang-tidy/performance/EnumSizeCheck.cpp | 5 ++---
.../readability/AvoidConstParamsInDecls.cpp | 5 +
.../readability/RedundantSmartptrGetCheck.cpp | 4 +---
.../readability/SimplifyBooleanExprCheck.cpp | 9 +++-
.../clang-tidy/utils/ExprSequence.cpp | 14 +---
.../clang-tidy/utils/IncludeSorter.cpp| 18 +++
16 files changed, 60 insertions(+), 89 deletions(-)
diff --git
a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
index 13d566087688f..d9f6551739d9e 100644
--- a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
@@ -20,8 +20,10 @@ namespace {
AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
-std::optional makeCharacterLiteral(const StringLiteral *Literal,
-const ASTContext &Context) {
+} // anonymous namespace
+
+static std::optional
+makeCharacterLiteral(const StringLiteral *Literal, const ASTContext &Context) {
assert(Literal->getLength() == 1 &&
"Only single character string should be matched");
assert(Literal->getCharByteWidth() == 1 &&
@@ -53,8 +55,6 @@ std::optional makeCharacterLiteral(const
StringLiteral *Literal,
return Result;
}
-} // anonymous namespace
-
void FasterStrsplitDelimiterCheck::registerMatchers(MatchFinder *Finder) {
// Binds to one character string literals.
const auto SingleChar =
diff --git a/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
index 6af535f712d71..3d3fc785b71f4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
@@ -51,6 +51,8 @@ struct ChainedComparisonData {
void extract(const CXXOperatorCallExpr *Op);
};
+} // namespace
+
void ChainedComparisonData::add(const Expr *Operand) {
if (!Name.empty())
Name += ' ';
@@ -111,8 +113,6 @@ void ChainedComparisonData::extract(const Expr *Op) {
}
}
-} // namespace
-
void ChainedComparisonCheck::registerMatchers(MatchFinder *Finder) {
const auto OperatorMatcher = expr(anyOf(
binaryOperator(isComparisonOperator(),
diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index 5b741e8c35b9a..9f8e885c91fff 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -17,9 +17,7 @@ using namespace clang::tidy::matchers;
namespace clang::tidy::bugprone {
-namespace {
-
-ast_matchers::internal::BindableMatcher
+static ast_matchers::internal::BindableMatcher
handleFrom(const ast_matchers::internal::Matcher &IsAHandle,
const ast_matchers::internal::Matcher &Arg) {
return expr(
@@ -31,7 +29,7 @@ handleFrom(const ast_matchers::internal::Matcher
&IsAHandle,
on(Arg;
}
-ast_matchers::internal::Matcher handleFromTemporaryValue(
+static ast_matchers::internal::Matcher handleFromTemporaryValue(
const ast_matchers::internal::Matcher &IsAHandle) {
const auto TemporaryExpr = anyOf(
@@ -49,22 +47,22 @@ ast_matchers::internal::Matcher
handleFromTemporaryValue(
return handleFrom(IsAHandle, anyOf(TemporaryExpr, TemporaryTernary));
}
-ast_matchers::internal::Matcher isASequence() {
+static ast_matchers::internal::Matcher isASequence() {
return hasAnyName("::std::deque", "::std::forward_list", "::std::list",
"::std::vector");
}
-ast_matchers::internal::Matcher isASet() {
+static ast_matchers::internal::Matcher isASet() {
return hasAnyName("::std::set", "::std::multiset", "::std::unordered_set",
"::std::unordered_multiset");
}
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 4/N (PR #164158)
llvmbot wrote:
@llvm/pr-subscribers-clang-tidy
@llvm/pr-subscribers-clang-tools-extra
Author: Baranov Victor (vbvictor)
Changes
Continue https://github.com/llvm/llvm-project/pull/153885.
---
Patch is 21.81 KiB, truncated to 20.00 KiB below, full version:
https://github.com/llvm/llvm-project/pull/164158.diff
16 Files Affected:
- (modified)
clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp (+4-4)
- (modified) clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
(+2-2)
- (modified) clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
(+6-10)
- (modified) clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
(+3-3)
- (modified) clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
(+2-3)
- (modified)
clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.cpp (+3-2)
- (modified) clang-tools-extra/clang-tidy/llvmlibc/InlineFunctionDeclCheck.cpp
(+1-5)
- (modified) clang-tools-extra/clang-tidy/misc/UnusedParametersCheck.cpp (+3-5)
- (modified) clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp
(+9-13)
- (modified) clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
(+7-7)
- (modified) clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp (+2-3)
- (modified)
clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp (+1-4)
- (modified)
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp (+1-3)
- (modified)
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp (+3-6)
- (modified) clang-tools-extra/clang-tidy/utils/ExprSequence.cpp (+5-9)
- (modified) clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp (+8-10)
``diff
diff --git
a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
index 13d566087688f..d9f6551739d9e 100644
--- a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
@@ -20,8 +20,10 @@ namespace {
AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
-std::optional makeCharacterLiteral(const StringLiteral *Literal,
-const ASTContext &Context) {
+} // anonymous namespace
+
+static std::optional
+makeCharacterLiteral(const StringLiteral *Literal, const ASTContext &Context) {
assert(Literal->getLength() == 1 &&
"Only single character string should be matched");
assert(Literal->getCharByteWidth() == 1 &&
@@ -53,8 +55,6 @@ std::optional makeCharacterLiteral(const
StringLiteral *Literal,
return Result;
}
-} // anonymous namespace
-
void FasterStrsplitDelimiterCheck::registerMatchers(MatchFinder *Finder) {
// Binds to one character string literals.
const auto SingleChar =
diff --git a/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
index 6af535f712d71..3d3fc785b71f4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp
@@ -51,6 +51,8 @@ struct ChainedComparisonData {
void extract(const CXXOperatorCallExpr *Op);
};
+} // namespace
+
void ChainedComparisonData::add(const Expr *Operand) {
if (!Name.empty())
Name += ' ';
@@ -111,8 +113,6 @@ void ChainedComparisonData::extract(const Expr *Op) {
}
}
-} // namespace
-
void ChainedComparisonCheck::registerMatchers(MatchFinder *Finder) {
const auto OperatorMatcher = expr(anyOf(
binaryOperator(isComparisonOperator(),
diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index 5b741e8c35b9a..9f8e885c91fff 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -17,9 +17,7 @@ using namespace clang::tidy::matchers;
namespace clang::tidy::bugprone {
-namespace {
-
-ast_matchers::internal::BindableMatcher
+static ast_matchers::internal::BindableMatcher
handleFrom(const ast_matchers::internal::Matcher &IsAHandle,
const ast_matchers::internal::Matcher &Arg) {
return expr(
@@ -31,7 +29,7 @@ handleFrom(const ast_matchers::internal::Matcher
&IsAHandle,
on(Arg;
}
-ast_matchers::internal::Matcher handleFromTemporaryValue(
+static ast_matchers::internal::Matcher handleFromTemporaryValue(
const ast_matchers::internal::Matcher &IsAHandle) {
const auto TemporaryExpr = anyOf(
@@ -49,22 +47,22 @@ ast_matchers::internal::Matcher
handleFromTemporaryValue(
return handleFrom(IsAHandle, anyOf(TemporaryExpr, TemporaryTernary));
}
-ast_matchers::internal::Matcher isASequence() {
+static ast_matchers::internal::Matcher isASequence() {
return hasAnyName("::std::
[clang-tools-extra] [clang-tools-extra][Unittest] Fix wrong reference to CMake configuration variable (PR #164147)
https://github.com/mstorsjo approved this pull request. LGTM, thanks! https://github.com/llvm/llvm-project/pull/164147 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [polly] [Unittest][Cygwin] Set $PATH when running unittests (PR #163947)
https://github.com/mstorsjo approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/163947 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Add support for atomic test-and-set and atomic clear (PR #164162)
https://github.com/Lancern created
https://github.com/llvm/llvm-project/pull/164162
This patch adds support for the following atomic builtin functions:
- `__atomic_test_and_set`
- `__atomic_clear`
>From 57e1b095244131e723f52f415bd18e7e0d6c1ab9 Mon Sep 17 00:00:00 2001
From: Sirui Mu
Date: Sun, 19 Oct 2025 22:00:49 +0800
Subject: [PATCH] [CIR] Add support for atomic test-and-set and atomic clear
This patch adds support for the following atomic builtin functions:
- `__atomic_test_and_set`
- `__atomic_clear`
---
clang/include/clang/CIR/Dialect/IR/CIROps.td | 62
clang/lib/CIR/CodeGen/CIRGenAtomic.cpp| 26 +--
.../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 40 +++
clang/test/CIR/CodeGen/atomic.c | 70 +++
4 files changed, 194 insertions(+), 4 deletions(-)
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index e0163a4fecd5f..5a3dfec6e015c 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -4554,4 +4554,66 @@ def CIR_AtomicCmpXchgOp : CIR_Op<"atomic.cmpxchg", [
}];
}
+def CIR_AtomicTestAndSetOp : CIR_Op<"atomic.test_and_set"> {
+ let summary = "Atomic test and set";
+ let description = [{
+C/C++ atomic test and set operation. Implements the builtin function
+`__atomic_test_and_set`.
+
+The operation takes as its only operand a pointer to an 8-bit signed
+integer. The operation atomically set the integer to an implementation-
+defined non-zero "set" value. The result of the operation is a boolean
value
+indicating whether the previous value of the integer was the "set" value.
+
+Example:
+```mlir
+ %res = cir.atomic.test_and_set seq_cst %ptr : !cir.ptr -> !cir.bool
+```
+ }];
+
+ let arguments = (ins
+Arg, "", [MemRead, MemWrite]>:$ptr,
+Arg:$mem_order,
+OptionalAttr:$alignment,
+UnitAttr:$is_volatile
+ );
+
+ let results = (outs CIR_BoolType:$result);
+
+ let assemblyFormat = [{
+$mem_order $ptr
+(`volatile` $is_volatile^)?
+`:` qualified(type($ptr)) `->` qualified(type($result)) attr-dict
+ }];
+}
+
+def CIR_AtomicClearOp : CIR_Op<"atomic.clear"> {
+ let summary = "Atomic clear";
+ let description = [{
+C/C++ atomic clear operation. Implements the builtin function
+`__atomic_clear`.
+
+The operation takes as its only operand a pointer to an 8-bit signed
+integer. The operation atomically sets the integer to zero.
+
+Example:
+```mlir
+ cir.atomic.clear seq_cst %ptr : !cir.ptr
+```
+ }];
+
+ let arguments = (ins
+Arg, "", [MemRead, MemWrite]>:$ptr,
+Arg:$mem_order,
+OptionalAttr:$alignment,
+UnitAttr:$is_volatile
+ );
+
+ let assemblyFormat = [{
+$mem_order $ptr
+(`volatile` $is_volatile^)?
+`:` qualified(type($ptr)) attr-dict
+ }];
+}
+
#endif // CLANG_CIR_DIALECT_IR_CIROPS_TD
diff --git a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
index a9983f882e28c..67ca60c971e04 100644
--- a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
@@ -407,6 +407,23 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr
*expr, Address dest,
opName = cir::AtomicXchgOp::getOperationName();
break;
+ case AtomicExpr::AO__atomic_test_and_set: {
+auto op = cir::AtomicTestAndSetOp::create(
+builder, loc, ptr.getPointer(), order,
+builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+expr->isVolatile());
+builder.createStore(loc, op, dest);
+return;
+ }
+
+ case AtomicExpr::AO__atomic_clear: {
+cir::AtomicClearOp::create(
+builder, loc, ptr.getPointer(), order,
+builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+expr->isVolatile());
+return;
+ }
+
case AtomicExpr::AO__opencl_atomic_init:
case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
@@ -502,10 +519,6 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr
*expr, Address dest,
case AtomicExpr::AO__c11_atomic_fetch_nand:
case AtomicExpr::AO__atomic_fetch_nand:
case AtomicExpr::AO__scoped_atomic_fetch_nand:
-
- case AtomicExpr::AO__atomic_test_and_set:
-
- case AtomicExpr::AO__atomic_clear:
cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: expr op NYI");
return;
}
@@ -581,6 +594,8 @@ RValue CIRGenFunction::emitAtomicExpr(AtomicExpr *e) {
case AtomicExpr::AO__atomic_load_n:
case AtomicExpr::AO__c11_atomic_load:
+ case AtomicExpr::AO__atomic_test_and_set:
+ case AtomicExpr::AO__atomic_clear:
break;
case AtomicExpr::AO__atomic_load:
@@ -640,6 +655,9 @@ RValue CIRGenFunction::emitAtomicExpr(AtomicExpr *e) {
dest = atomics.castToAtomicIntPointer(dest);
} else if (e->isCmpXChg()) {
dest = createMemTemp(resultTy, getLoc(e->getSourceRange()),
"cmpxchg.bool");
+ } else if (e->getOp() =
[clang] [C++][Modules] Import declaration should in global module fragment, module interface or module implementation (PR #164106)
https://github.com/hubert-reinterpretcast edited https://github.com/llvm/llvm-project/pull/164106 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Add support for atomic test-and-set and atomic clear (PR #164162)
llvmbot wrote:
@llvm/pr-subscribers-clangir
Author: Sirui Mu (Lancern)
Changes
This patch adds support for the following atomic builtin functions:
- `__atomic_test_and_set`
- `__atomic_clear`
---
Full diff: https://github.com/llvm/llvm-project/pull/164162.diff
4 Files Affected:
- (modified) clang/include/clang/CIR/Dialect/IR/CIROps.td (+62)
- (modified) clang/lib/CIR/CodeGen/CIRGenAtomic.cpp (+22-4)
- (modified) clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp (+40)
- (modified) clang/test/CIR/CodeGen/atomic.c (+70)
``diff
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index e0163a4fecd5f..5a3dfec6e015c 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -4554,4 +4554,66 @@ def CIR_AtomicCmpXchgOp : CIR_Op<"atomic.cmpxchg", [
}];
}
+def CIR_AtomicTestAndSetOp : CIR_Op<"atomic.test_and_set"> {
+ let summary = "Atomic test and set";
+ let description = [{
+C/C++ atomic test and set operation. Implements the builtin function
+`__atomic_test_and_set`.
+
+The operation takes as its only operand a pointer to an 8-bit signed
+integer. The operation atomically set the integer to an implementation-
+defined non-zero "set" value. The result of the operation is a boolean
value
+indicating whether the previous value of the integer was the "set" value.
+
+Example:
+```mlir
+ %res = cir.atomic.test_and_set seq_cst %ptr : !cir.ptr -> !cir.bool
+```
+ }];
+
+ let arguments = (ins
+Arg, "", [MemRead, MemWrite]>:$ptr,
+Arg:$mem_order,
+OptionalAttr:$alignment,
+UnitAttr:$is_volatile
+ );
+
+ let results = (outs CIR_BoolType:$result);
+
+ let assemblyFormat = [{
+$mem_order $ptr
+(`volatile` $is_volatile^)?
+`:` qualified(type($ptr)) `->` qualified(type($result)) attr-dict
+ }];
+}
+
+def CIR_AtomicClearOp : CIR_Op<"atomic.clear"> {
+ let summary = "Atomic clear";
+ let description = [{
+C/C++ atomic clear operation. Implements the builtin function
+`__atomic_clear`.
+
+The operation takes as its only operand a pointer to an 8-bit signed
+integer. The operation atomically sets the integer to zero.
+
+Example:
+```mlir
+ cir.atomic.clear seq_cst %ptr : !cir.ptr
+```
+ }];
+
+ let arguments = (ins
+Arg, "", [MemRead, MemWrite]>:$ptr,
+Arg:$mem_order,
+OptionalAttr:$alignment,
+UnitAttr:$is_volatile
+ );
+
+ let assemblyFormat = [{
+$mem_order $ptr
+(`volatile` $is_volatile^)?
+`:` qualified(type($ptr)) attr-dict
+ }];
+}
+
#endif // CLANG_CIR_DIALECT_IR_CIROPS_TD
diff --git a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
index a9983f882e28c..67ca60c971e04 100644
--- a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
@@ -407,6 +407,23 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr
*expr, Address dest,
opName = cir::AtomicXchgOp::getOperationName();
break;
+ case AtomicExpr::AO__atomic_test_and_set: {
+auto op = cir::AtomicTestAndSetOp::create(
+builder, loc, ptr.getPointer(), order,
+builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+expr->isVolatile());
+builder.createStore(loc, op, dest);
+return;
+ }
+
+ case AtomicExpr::AO__atomic_clear: {
+cir::AtomicClearOp::create(
+builder, loc, ptr.getPointer(), order,
+builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+expr->isVolatile());
+return;
+ }
+
case AtomicExpr::AO__opencl_atomic_init:
case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
@@ -502,10 +519,6 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr
*expr, Address dest,
case AtomicExpr::AO__c11_atomic_fetch_nand:
case AtomicExpr::AO__atomic_fetch_nand:
case AtomicExpr::AO__scoped_atomic_fetch_nand:
-
- case AtomicExpr::AO__atomic_test_and_set:
-
- case AtomicExpr::AO__atomic_clear:
cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: expr op NYI");
return;
}
@@ -581,6 +594,8 @@ RValue CIRGenFunction::emitAtomicExpr(AtomicExpr *e) {
case AtomicExpr::AO__atomic_load_n:
case AtomicExpr::AO__c11_atomic_load:
+ case AtomicExpr::AO__atomic_test_and_set:
+ case AtomicExpr::AO__atomic_clear:
break;
case AtomicExpr::AO__atomic_load:
@@ -640,6 +655,9 @@ RValue CIRGenFunction::emitAtomicExpr(AtomicExpr *e) {
dest = atomics.castToAtomicIntPointer(dest);
} else if (e->isCmpXChg()) {
dest = createMemTemp(resultTy, getLoc(e->getSourceRange()),
"cmpxchg.bool");
+ } else if (e->getOp() == AtomicExpr::AO__atomic_test_and_set) {
+dest = createMemTemp(resultTy, getLoc(e->getSourceRange()),
+ "test_and_set.bool");
} else if (!resultTy->isVoidType()) {
dest = atomics.createTempAlloca();
if (shouldCastToIntPtrTy)
diff --git a/clang
[clang] 2272726 - Reapply "[Clang] Make rewrite-includes-bom.c work with internal shell"
Author: Aiden Grossman Date: 2025-10-19T13:05:58-07:00 New Revision: 227272662a02151ad401c0881da46250944dc3e3 URL: https://github.com/llvm/llvm-project/commit/227272662a02151ad401c0881da46250944dc3e3 DIFF: https://github.com/llvm/llvm-project/commit/227272662a02151ad401c0881da46250944dc3e3.diff LOG: Reapply "[Clang] Make rewrite-includes-bom.c work with internal shell" This reverts commit 354ad556e17358db2b22507e3ef07ba39991b189. This was reverted previously for causing test failures on MacOS. It turns out that od -t x1 prints two spaces between hexadecimal representations of bytes rather than one like on other *nix systems. This reland updates the original patch to match any number of whitespace characters in between the bytes rather than just a single space. Added: Modified: clang/test/Frontend/rewrite-includes-bom.c Removed: diff --git a/clang/test/Frontend/rewrite-includes-bom.c b/clang/test/Frontend/rewrite-includes-bom.c index caa431ad9aaff..46a6c3062a55a 100644 --- a/clang/test/Frontend/rewrite-includes-bom.c +++ b/clang/test/Frontend/rewrite-includes-bom.c @@ -1,8 +1,7 @@ -// RUN: grep -q $'^\xEF\xBB\xBF' %S/Inputs/rewrite-includes-bom.h +// RUN: cat %S/Inputs/rewrite-includes-bom.h | od -t x1 | grep -q 'ef\s*bb\s*bf' // RUN: %clang_cc1 -E -frewrite-includes -I %S/Inputs %s -o %t.c -// RUN: ! grep -q $'\xEF\xBB\xBF' %t.c +// RUN: cat %t.c | od -t x1 | not grep -q 'ef\s*bb\s*bf' // RUN: %clang_cc1 -fsyntax-only -verify %t.c // expected-no-diagnostics -// REQUIRES: shell #include "rewrite-includes-bom.h" ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ea3dbb8 - [Clang] Disable rewrite-includes-bom.c on Windows
Author: Aiden Grossman Date: 2025-10-19T20:38:46Z New Revision: ea3dbb8b0061a7e44cba92b6e4e4486c4a416d65 URL: https://github.com/llvm/llvm-project/commit/ea3dbb8b0061a7e44cba92b6e4e4486c4a416d65 DIFF: https://github.com/llvm/llvm-project/commit/ea3dbb8b0061a7e44cba92b6e4e4486c4a416d65.diff LOG: [Clang] Disable rewrite-includes-bom.c on Windows This was failing on https://lab.llvm.org/buildbot/#/builders/46/builds/25073. This test seems to have always had portability problems looking at the commit history. The most recent patch I landed to touch this enabled it on Windows again, so we are not disabling coverage that was there before. Added: Modified: clang/test/Frontend/rewrite-includes-bom.c Removed: diff --git a/clang/test/Frontend/rewrite-includes-bom.c b/clang/test/Frontend/rewrite-includes-bom.c index 46a6c3062a55a..27bf470ba1fd1 100644 --- a/clang/test/Frontend/rewrite-includes-bom.c +++ b/clang/test/Frontend/rewrite-includes-bom.c @@ -3,5 +3,6 @@ // RUN: cat %t.c | od -t x1 | not grep -q 'ef\s*bb\s*bf' // RUN: %clang_cc1 -fsyntax-only -verify %t.c // expected-no-diagnostics +// UNSUPPORTED: system-windows #include "rewrite-includes-bom.h" ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Simplify AlignMacroMatches (PR #164122)
@@ -656,7 +656,6 @@ void WhitespaceManager::alignConsecutiveMacros() {
auto AlignMacrosMatches = [](const Change &C) {
const FormatToken *Current = C.Tok;
HazardyKnusperkeks wrote:
Would make this one stand out, and I don't think that's necessary, All changes
have tokens, don't they?
https://github.com/llvm/llvm-project/pull/164122
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
https://github.com/HazardyKnusperkeks updated
https://github.com/llvm/llvm-project/pull/164120
From 25469d96008d17f370d6372539f4ed5b8a151e5c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?=
Date: Sat, 18 Oct 2025 21:58:35 +0200
Subject: [PATCH 1/2] [clang-format] Reuse AlignTokens for aligning macros
Fixes #52985.
This leaves aligning short case statements with its own logic. But that
is harder to port, because it aligns even with no content of the right
hand side of the :.
---
clang/lib/Format/WhitespaceManager.cpp | 88 ++
clang/unittests/Format/FormatTest.cpp | 5 ++
2 files changed, 26 insertions(+), 67 deletions(-)
diff --git a/clang/lib/Format/WhitespaceManager.cpp
b/clang/lib/Format/WhitespaceManager.cpp
index 7348a3af8cf95..9f4b38830a4f9 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -432,7 +432,11 @@ AlignTokenSequence(const FormatStyle &Style, unsigned
Start, unsigned End,
// right-justified. It is used to align compound assignments like `+=` and `=`.
// When RightJustify and ACS.PadOperators are true, operators in each block to
// be aligned will be padded on the left to the same length before aligning.
-template
+//
+// The simple check will not look at the indentaion and nesting level to
recurse
+// into the line for alignment. It will also not count the commas. This is e.g.
+// for aligning macro definitions.
+template
static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
SmallVector
&Changes,
unsigned StartAt,
@@ -465,9 +469,9 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
// Measure the scope level (i.e. depth of (), [], {}) of the first token, and
// abort when we hit any token in a higher scope than the starting one.
- auto IndentAndNestingLevel = StartAt < Changes.size()
- ? Changes[StartAt].indentAndNestingLevel()
- : std::tuple();
+ const auto IndentAndNestingLevel =
+ StartAt < Changes.size() ? Changes[StartAt].indentAndNestingLevel()
+ : std::tuple();
// Keep track of the number of commas before the matching tokens, we will
only
// align a sequence of matching tokens if they are preceded by the same
number
@@ -536,14 +540,17 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
if (CurrentChange.Tok->isNot(tok::comment))
LineIsComment = false;
-if (CurrentChange.Tok->is(tok::comma)) {
- ++CommasBeforeMatch;
-} else if (CurrentChange.indentAndNestingLevel() > IndentAndNestingLevel) {
- // Call AlignTokens recursively, skipping over this scope block.
- unsigned StoppedAt =
- AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
- i = StoppedAt - 1;
- continue;
+if (!SimpleCheck) {
+ if (CurrentChange.Tok->is(tok::comma)) {
+++CommasBeforeMatch;
+ } else if (CurrentChange.indentAndNestingLevel() >
+ IndentAndNestingLevel) {
+// Call AlignTokens recursively, skipping over this scope block.
+unsigned StoppedAt =
+AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
+i = StoppedAt - 1;
+continue;
+ }
}
if (!Matches(CurrentChange))
@@ -683,61 +690,8 @@ void WhitespaceManager::alignConsecutiveMacros() {
return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
};
- unsigned MinColumn = 0;
-
- // Start and end of the token sequence we're processing.
- unsigned StartOfSequence = 0;
- unsigned EndOfSequence = 0;
-
- // Whether a matching token has been found on the current line.
- bool FoundMatchOnLine = false;
-
- // Whether the current line consists only of comments
- bool LineIsComment = true;
-
- unsigned I = 0;
- for (unsigned E = Changes.size(); I != E; ++I) {
-if (Changes[I].NewlinesBefore != 0) {
- EndOfSequence = I;
-
- // Whether to break the alignment sequence because of an empty line.
- bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
-!Style.AlignConsecutiveMacros.AcrossEmptyLines;
-
- // Whether to break the alignment sequence because of a line without a
- // match.
- bool NoMatchBreak =
- !FoundMatchOnLine &&
- !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
-
- if (EmptyLineBreak || NoMatchBreak) {
-AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
- }
-
- // A new line starts, re-initialize line status tracking bools.
- FoundMatchOnLine = false;
- LineIsComment = true;
-}
-
-if (Changes[I].Tok->isNot(tok::comment))
- LineIsComment = false;
-
-if (!AlignMacrosMatches(Changes[I]))
- continue;
-
-
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
@@ -683,61 +690,8 @@ void WhitespaceManager::alignConsecutiveMacros() {
return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
};
- unsigned MinColumn = 0;
-
- // Start and end of the token sequence we're processing.
- unsigned StartOfSequence = 0;
- unsigned EndOfSequence = 0;
-
- // Whether a matching token has been found on the current line.
- bool FoundMatchOnLine = false;
-
- // Whether the current line consists only of comments
- bool LineIsComment = true;
-
- unsigned I = 0;
- for (unsigned E = Changes.size(); I != E; ++I) {
-if (Changes[I].NewlinesBefore != 0) {
- EndOfSequence = I;
-
- // Whether to break the alignment sequence because of an empty line.
- bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
-!Style.AlignConsecutiveMacros.AcrossEmptyLines;
-
- // Whether to break the alignment sequence because of a line without a
- // match.
- bool NoMatchBreak =
- !FoundMatchOnLine &&
- !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
-
- if (EmptyLineBreak || NoMatchBreak) {
-AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
- }
-
- // A new line starts, re-initialize line status tracking bools.
- FoundMatchOnLine = false;
- LineIsComment = true;
-}
-
-if (Changes[I].Tok->isNot(tok::comment))
- LineIsComment = false;
-
-if (!AlignMacrosMatches(Changes[I]))
- continue;
-
-FoundMatchOnLine = true;
-
-if (StartOfSequence == 0)
- StartOfSequence = I;
-
-unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
-MinColumn = std::max(MinColumn, ChangeMinColumn);
- }
-
- EndOfSequence = I;
- AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
+ AlignTokens(
HazardyKnusperkeks wrote:
Yeah, renamed that option.
https://github.com/llvm/llvm-project/pull/164120
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
@@ -536,14 +540,17 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
if (CurrentChange.Tok->isNot(tok::comment))
LineIsComment = false;
-if (CurrentChange.Tok->is(tok::comma)) {
- ++CommasBeforeMatch;
-} else if (CurrentChange.indentAndNestingLevel() > IndentAndNestingLevel) {
- // Call AlignTokens recursively, skipping over this scope block.
- unsigned StoppedAt =
- AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
- i = StoppedAt - 1;
- continue;
+if (!SimpleCheck) {
+ if (CurrentChange.Tok->is(tok::comma)) {
+++CommasBeforeMatch;
+ } else if (CurrentChange.indentAndNestingLevel() >
+ IndentAndNestingLevel) {
+// Call AlignTokens recursively, skipping over this scope block.
+unsigned StoppedAt =
HazardyKnusperkeks wrote:
I just added the if, but can change that.
https://github.com/llvm/llvm-project/pull/164120
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
https://github.com/HazardyKnusperkeks auto_merge_enabled https://github.com/llvm/llvm-project/pull/164120 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Simplify AlignMacroMatches (PR #164122)
https://github.com/HazardyKnusperkeks updated
https://github.com/llvm/llvm-project/pull/164122
From ff688c7e3829f769cfd20f2482e90b07e54618c8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?=
Date: Sat, 18 Oct 2025 22:11:47 +0200
Subject: [PATCH 1/2] [clang-format][NFC] Simplify AlignMacroMatches
Just return early based on the SpacedRequiredBefore.
---
clang/lib/Format/WhitespaceManager.cpp | 28 --
1 file changed, 13 insertions(+), 15 deletions(-)
diff --git a/clang/lib/Format/WhitespaceManager.cpp
b/clang/lib/Format/WhitespaceManager.cpp
index 7348a3af8cf95..03a1e9a6bd80b 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -656,7 +656,6 @@ void WhitespaceManager::alignConsecutiveMacros() {
auto AlignMacrosMatches = [](const Change &C) {
const FormatToken *Current = C.Tok;
-unsigned SpacesRequiredBefore = 1;
if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
return false;
@@ -665,22 +664,21 @@ void WhitespaceManager::alignConsecutiveMacros() {
// If token is a ")", skip over the parameter list, to the
// token that precedes the "("
-if (Current->is(tok::r_paren) && Current->MatchingParen) {
- Current = Current->MatchingParen->Previous;
- SpacesRequiredBefore = 0;
-}
-
-if (!Current || Current->isNot(tok::identifier))
- return false;
-
-if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
+if (const auto *MatchingParen = Current->MatchingParen;
+Current->is(tok::r_paren) && MatchingParen) {
+ // For a macro function, 0 spaces are required between the
+ // identifier and the lparen that opens the parameter list.
+ if (MatchingParen->SpacesRequiredBefore > 0)
+return false;
+ Current = MatchingParen->Previous;
+} else if (Current->Next->SpacesRequiredBefore != 1) {
+ // For a simple macro, 1 space is required between the
+ // identifier and the first token of the defined value.
return false;
+}
-// For a macro function, 0 spaces are required between the
-// identifier and the lparen that opens the parameter list.
-// For a simple macro, 1 space is required between the
-// identifier and the first token of the defined value.
-return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
+return Current && Current->is(tok::identifier) && Current->Previous &&
+ Current->Previous->is(tok::pp_define);
};
unsigned MinColumn = 0;
From b4c06a4a867871fea45bce340037628d956112ef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?=
Date: Sun, 19 Oct 2025 22:44:28 +0200
Subject: [PATCH 2/2] Address review
---
clang/lib/Format/WhitespaceManager.cpp | 11 ++-
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/clang/lib/Format/WhitespaceManager.cpp
b/clang/lib/Format/WhitespaceManager.cpp
index 03a1e9a6bd80b..ecc8ec024a8dc 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -664,12 +664,14 @@ void WhitespaceManager::alignConsecutiveMacros() {
// If token is a ")", skip over the parameter list, to the
// token that precedes the "("
-if (const auto *MatchingParen = Current->MatchingParen;
-Current->is(tok::r_paren) && MatchingParen) {
+if (Current->is(tok::r_paren)) {
+ const auto *MatchingParen = Current->MatchingParen;
// For a macro function, 0 spaces are required between the
// identifier and the lparen that opens the parameter list.
- if (MatchingParen->SpacesRequiredBefore > 0)
+ if (!MatchingParen || MatchingParen->SpacesRequiredBefore > 0 ||
+ !MatchingParen->Previous) {
return false;
+ }
Current = MatchingParen->Previous;
} else if (Current->Next->SpacesRequiredBefore != 1) {
// For a simple macro, 1 space is required between the
@@ -677,8 +679,7 @@ void WhitespaceManager::alignConsecutiveMacros() {
return false;
}
-return Current && Current->is(tok::identifier) && Current->Previous &&
- Current->Previous->is(tok::pp_define);
+return Current->endsSequence(tok::identifier, tok::pp_define);
};
unsigned MinColumn = 0;
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Emit warnings from user headers by default (PR #164165)
@@ -133,13 +133,15 @@ file, if any.
static cl::opt HeaderFilter("header-filter", desc(R"(
Regular expression matching the names of the
headers to output diagnostics from. Diagnostics
-from the main file of each translation unit are
-always displayed.
+from the main file and all non-system headers
+of each translation unit are always displayed.
+Set this option to an empty string to disable
+diagnostics from non-system headers.
localspook wrote:
This wording is a bit confusing to me. Warnings from non-system headers are
*not* always displayed, the point is that you can disable them with this
option, right? Something like this seems more accurate to me:
```suggestion
from the main file of each translation unit
are always displayed. Diagnostics from
non-system headers it includes are displayed
by default, but can be disabled with this option.
```
(Also applies in other places where the wording is repeated)
https://github.com/llvm/llvm-project/pull/164165
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen] Emit `llvm.tbaa.errno` metadata during module creation (PR #125258)
nikic wrote: Reverse ping https://github.com/llvm/llvm-project/pull/125258 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Emit CIR builtins: coroAlloc, coroBegin, and coroSize (PR #164180)
llvmbot wrote:
@llvm/pr-subscribers-clang
Author: None (Andres-Salamanca)
Changes
This PR adds support for emitting the builtins coroAlloc, coroBegin, and
coroSize.
---
Full diff: https://github.com/llvm/llvm-project/pull/164180.diff
6 Files Affected:
- (modified) clang/include/clang/CIR/MissingFeatures.h (+1-3)
- (modified) clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp (+10-4)
- (modified) clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp (+78-3)
- (modified) clang/lib/CIR/CodeGen/CIRGenFunction.h (+3)
- (modified) clang/lib/CIR/CodeGen/CIRGenModule.h (+2)
- (modified) clang/test/CIR/CodeGen/coro-task.cpp (+18-1)
``diff
diff --git a/clang/include/clang/CIR/MissingFeatures.h
b/clang/include/clang/CIR/MissingFeatures.h
index 090cf35c2d279..7956ba797f837 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -149,11 +149,9 @@ struct MissingFeatures {
static bool zeroSizeRecordMembers() { return false; }
// Coroutines
- static bool coroAllocBuiltinCall() { return false; }
- static bool coroBeginBuiltinCall() { return false; }
static bool coroEndBuiltinCall() { return false; }
- static bool coroSizeBuiltinCall() { return false; }
static bool coroutineFrame() { return false; }
+ static bool emitBodyAndFallthrough() { return false; }
// Various handling of deferred processing in CIRGenModule.
static bool cgmRelease() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
index ea31871806bd7..92ede62cac630 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
@@ -449,10 +449,16 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl
&gd, unsigned builtinID,
}
case Builtin::BI__builtin_coro_free:
case Builtin::BI__builtin_coro_size: {
-cgm.errorNYI(e->getSourceRange(),
- "BI__builtin_coro_free, BI__builtin_coro_size NYI");
-assert(!cir::MissingFeatures::coroSizeBuiltinCall());
-return getUndefRValue(e->getType());
+GlobalDecl gd{fd};
+mlir::Type ty = cgm.getTypes().getFunctionType(
+cgm.getTypes().arrangeGlobalDeclaration(gd));
+const auto *nd = cast(gd.getDecl());
+cir::FuncOp fnOp =
+cgm.getOrCreateCIRFunction(nd->getName(), ty, gd, /*ForVTable=*/false,
+ /*DontDefer=*/false);
+fnOp.setBuiltin(true);
+return emitCall(e->getCallee()->getType(), CIRGenCallee::forDirect(fnOp),
e,
+returnValue);
}
}
diff --git a/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
b/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
index c25cce4ab33b3..86b4e43ea2998 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
@@ -15,6 +15,7 @@
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "clang/CIR/MissingFeatures.h"
using namespace clang;
using namespace clang::CIRGen;
@@ -23,6 +24,9 @@ struct clang::CIRGen::CGCoroData {
// Stores the __builtin_coro_id emitted in the function so that we can supply
// it as the first argument to other builtins.
cir::CallOp coroId = nullptr;
+
+ // Stores the result of __builtin_coro_begin call.
+ mlir::Value coroBegin = nullptr;
};
// Defining these here allows to keep CGCoroData private to this file.
@@ -63,6 +67,48 @@ cir::CallOp
CIRGenFunction::emitCoroIDBuiltinCall(mlir::Location loc,
nullPtr, nullPtr, nullPtr});
}
+cir::CallOp CIRGenFunction::emitCoroAllocBuiltinCall(mlir::Location loc) {
+ cir::BoolType boolTy = builder.getBoolTy();
+ cir::IntType int32Ty = builder.getUInt32Ty();
+
+ mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroAlloc);
+
+ cir::FuncOp fnOp;
+ if (!builtin) {
+fnOp = cgm.createCIRBuiltinFunction(loc, cgm.builtinCoroAlloc,
+cir::FuncType::get({int32Ty}, boolTy),
+/*FD=*/nullptr);
+assert(fnOp && "should always succeed");
+ } else {
+fnOp = cast(builtin);
+ }
+
+ return builder.createCallOp(
+ loc, fnOp, mlir::ValueRange{curCoro.data->coroId.getResult()});
+}
+
+cir::CallOp
+CIRGenFunction::emitCoroBeginBuiltinCall(mlir::Location loc,
+ mlir::Value coroframeAddr) {
+ cir::IntType int32Ty = builder.getUInt32Ty();
+ mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroBegin);
+
+ cir::FuncOp fnOp;
+ if (!builtin) {
+fnOp = cgm.createCIRBuiltinFunction(
+loc, cgm.builtinCoroBegin,
+cir::FuncType::get({int32Ty, VoidPtrTy}, VoidPtrTy),
+/*FD=*/nullptr);
+assert(fnOp && "should always succeed");
+ } else {
+fnOp = cast(builtin);
+ }
+
+ return builder.createCallOp(
+ loc, fnOp,
+ mlir::ValueRange{curCoro.data->coroId.getResult(), coroframeAddr});
+}
+
mlir::Logi
[clang] [CIR] Emit CIR builtins: coroAlloc, coroBegin, and coroSize (PR #164180)
https://github.com/Andres-Salamanca created
https://github.com/llvm/llvm-project/pull/164180
This PR adds support for emitting the builtins coroAlloc, coroBegin, and
coroSize.
>From 3e24f4b1e5b1d15f34e38755ebe7c44ec09b9fba Mon Sep 17 00:00:00 2001
From: Andres Salamanca
Date: Sun, 19 Oct 2025 16:03:51 -0500
Subject: [PATCH] [CIR] Emit CIR builtins: coroAlloc, coroBegin, and coroSize
---
clang/include/clang/CIR/MissingFeatures.h | 4 +-
clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp | 14 ++--
clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp | 81 ++-
clang/lib/CIR/CodeGen/CIRGenFunction.h| 3 +
clang/lib/CIR/CodeGen/CIRGenModule.h | 2 +
clang/test/CIR/CodeGen/coro-task.cpp | 19 +-
6 files changed, 112 insertions(+), 11 deletions(-)
diff --git a/clang/include/clang/CIR/MissingFeatures.h
b/clang/include/clang/CIR/MissingFeatures.h
index 090cf35c2d279..7956ba797f837 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -149,11 +149,9 @@ struct MissingFeatures {
static bool zeroSizeRecordMembers() { return false; }
// Coroutines
- static bool coroAllocBuiltinCall() { return false; }
- static bool coroBeginBuiltinCall() { return false; }
static bool coroEndBuiltinCall() { return false; }
- static bool coroSizeBuiltinCall() { return false; }
static bool coroutineFrame() { return false; }
+ static bool emitBodyAndFallthrough() { return false; }
// Various handling of deferred processing in CIRGenModule.
static bool cgmRelease() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
index ea31871806bd7..92ede62cac630 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
@@ -449,10 +449,16 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl
&gd, unsigned builtinID,
}
case Builtin::BI__builtin_coro_free:
case Builtin::BI__builtin_coro_size: {
-cgm.errorNYI(e->getSourceRange(),
- "BI__builtin_coro_free, BI__builtin_coro_size NYI");
-assert(!cir::MissingFeatures::coroSizeBuiltinCall());
-return getUndefRValue(e->getType());
+GlobalDecl gd{fd};
+mlir::Type ty = cgm.getTypes().getFunctionType(
+cgm.getTypes().arrangeGlobalDeclaration(gd));
+const auto *nd = cast(gd.getDecl());
+cir::FuncOp fnOp =
+cgm.getOrCreateCIRFunction(nd->getName(), ty, gd, /*ForVTable=*/false,
+ /*DontDefer=*/false);
+fnOp.setBuiltin(true);
+return emitCall(e->getCallee()->getType(), CIRGenCallee::forDirect(fnOp),
e,
+returnValue);
}
}
diff --git a/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
b/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
index c25cce4ab33b3..86b4e43ea2998 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCoroutine.cpp
@@ -15,6 +15,7 @@
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "clang/CIR/MissingFeatures.h"
using namespace clang;
using namespace clang::CIRGen;
@@ -23,6 +24,9 @@ struct clang::CIRGen::CGCoroData {
// Stores the __builtin_coro_id emitted in the function so that we can supply
// it as the first argument to other builtins.
cir::CallOp coroId = nullptr;
+
+ // Stores the result of __builtin_coro_begin call.
+ mlir::Value coroBegin = nullptr;
};
// Defining these here allows to keep CGCoroData private to this file.
@@ -63,6 +67,48 @@ cir::CallOp
CIRGenFunction::emitCoroIDBuiltinCall(mlir::Location loc,
nullPtr, nullPtr, nullPtr});
}
+cir::CallOp CIRGenFunction::emitCoroAllocBuiltinCall(mlir::Location loc) {
+ cir::BoolType boolTy = builder.getBoolTy();
+ cir::IntType int32Ty = builder.getUInt32Ty();
+
+ mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroAlloc);
+
+ cir::FuncOp fnOp;
+ if (!builtin) {
+fnOp = cgm.createCIRBuiltinFunction(loc, cgm.builtinCoroAlloc,
+cir::FuncType::get({int32Ty}, boolTy),
+/*FD=*/nullptr);
+assert(fnOp && "should always succeed");
+ } else {
+fnOp = cast(builtin);
+ }
+
+ return builder.createCallOp(
+ loc, fnOp, mlir::ValueRange{curCoro.data->coroId.getResult()});
+}
+
+cir::CallOp
+CIRGenFunction::emitCoroBeginBuiltinCall(mlir::Location loc,
+ mlir::Value coroframeAddr) {
+ cir::IntType int32Ty = builder.getUInt32Ty();
+ mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroBegin);
+
+ cir::FuncOp fnOp;
+ if (!builtin) {
+fnOp = cgm.createCIRBuiltinFunction(
+loc, cgm.builtinCoroBegin,
+cir::FuncType::get({int32Ty, VoidPtrTy}, VoidPtrTy),
+/*FD=*/nullptr);
+assert(fnOp && "should always succeed");
+ } else {
+fnOp = cast(builtin);
+ }
+
+ r
[clang] [NFC][doc] Mark P1857R3 as partial implemented (PR #164095)
@@ -926,7 +926,14 @@ C++20 implementation status https://wg21.link/p1857r3";>P1857R3 -No + + +>Clang 21(Partial) +The restriction 'A module directive may only appear as +the first preprocessing tokens in a file' was supported +in clang-21. hubert-reinterpretcast wrote: Note: Clang versions are referenced as "Clang" (and not as clang- ) elsewhere in this file. ```suggestion The restriction that "[a] module directive may only appear as the first preprocessing tokens in a file" is enforced starting in Clang 21. ``` https://github.com/llvm/llvm-project/pull/164095 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][doc] Mark P1857R3 as partial implemented (PR #164095)
https://github.com/hubert-reinterpretcast edited https://github.com/llvm/llvm-project/pull/164095 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][doc] Mark P1857R3 as partial implemented (PR #164095)
https://github.com/hubert-reinterpretcast approved this pull request. LGTM once comments are addressed. https://github.com/llvm/llvm-project/pull/164095 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Add new option to specify functions `SecuritySyntaxChecker` warns about. (PR #164184)
https://github.com/stemil01 created
https://github.com/llvm/llvm-project/pull/164184
Addresses #103038.
Currently, the list of functions for which `SecuritySyntaxChecker` emits
warnings is fixed. This patch adds a new command-line option `Warn`, which
allows users to provide a space-separated list of function names to mark as
explicitly insecure.
There is a separate commit for `clang-format` style changes since they affect
the existing formatting of `Checkers.td` file.
>From 7287d963eb30f38c42fce35f9fe6f6a126b2ade2 Mon Sep 17 00:00:00 2001
From: stemil01
Date: Sun, 19 Oct 2025 20:36:59 +0200
Subject: [PATCH 1/2] [clang][analyzer] Add new option to specify functions
`SecuritySyntaxChecker` warns about
---
.../clang/StaticAnalyzer/Checkers/Checkers.td | 8 +++
.../Checkers/CheckSecuritySyntaxOnly.cpp | 58 +++
clang/test/Analysis/analyzer-config.c | 1 +
3 files changed, 56 insertions(+), 11 deletions(-)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index ffae3b9310979..7b47993ca16c1 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -841,6 +841,14 @@ let ParentPackage = InsecureAPI in {
def SecuritySyntaxChecker : Checker<"SecuritySyntaxChecker">,
HelpText<"Base of various security function related checkers">,
+ CheckerOptions<[
+CmdLineOption
+ ]>,
Documentation,
Hidden;
diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
index 5e75c1c4a3abd..5415e19431ca5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -74,13 +74,14 @@ class WalkAST : public StmtVisitor {
const bool CheckRand;
const ChecksFilter &filter;
+ llvm::StringSet<> WarnFunctions;
public:
- WalkAST(BugReporter &br, AnalysisDeclContext* ac,
- const ChecksFilter &f)
- : BR(br), AC(ac), II_setid(),
-CheckRand(isArc4RandomAvailable(BR.getContext())),
-filter(f) {}
+ WalkAST(BugReporter &br, AnalysisDeclContext *ac, const ChecksFilter &f,
+ llvm::StringSet<> wf)
+ : BR(br), AC(ac), II_setid(),
+CheckRand(isArc4RandomAvailable(BR.getContext())), filter(f),
+WarnFunctions(wf) {}
// Statement visitor methods.
void VisitCallExpr(CallExpr *CE);
@@ -101,6 +102,7 @@ class WalkAST : public StmtVisitor {
void checkLoopConditionForFloat(const ForStmt *FS);
void checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_custom(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
@@ -175,12 +177,10 @@ void WalkAST::VisitCallExpr(CallExpr *CE) {
.Case("rand_r", &WalkAST::checkCall_rand)
.Case("random", &WalkAST::checkCall_random)
.Case("vfork", &WalkAST::checkCall_vfork)
- .Default(nullptr);
+ .Default(&WalkAST::checkCall_custom);
- // If the callee isn't defined, it is not of security concern.
// Check and evaluate the call.
- if (evalFunction)
-(this->*evalFunction)(CE, FD);
+ (this->*evalFunction)(CE, FD);
// Recurse and check children.
VisitChildren(CE);
@@ -542,6 +542,29 @@ void WalkAST::checkCall_getpw(const CallExpr *CE, const
FunctionDecl *FD) {
CELoc, CE->getCallee()->getSourceRange());
}
+//===--===//
+// Check: Any use of a function from the user-provided list.
+//===--===//
+
+void WalkAST::checkCall_custom(const CallExpr *CE, const FunctionDecl *FD) {
+ IdentifierInfo *II = FD->getIdentifier();
+ if (!II) // if no identifier, not a simple C function
+return;
+ StringRef Name = II->getName();
+ Name.consume_front("__builtin_");
+
+ if (!(this->WarnFunctions.contains(Name)))
+return;
+
+ // Issue a warning.
+ std::string Msg = ("Call to user-defined function '" + Name + "'.").str();
+ PathDiagnosticLocation CELoc =
+ PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
+ BR.EmitBasicReport(AC->getDecl(), filter.checkName_getpw,
+ "User-provided function to be warned about", "Security",
+ Msg, CELoc, CE->getCallee()->getSourceRange());
+}
+
//===--===//
// Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp().
// CWE-377: Insecure Temporary File
@@ -1075,17 +1098,30 @@ namespace {
class SecuritySynta
[clang] [clang][analyzer] Add new option to specify functions `SecuritySyntaxChecker` warns about. (PR #164184)
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/164184 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Mark `_lstrcatA`, `_strcpyA`, and `_strdup` as insecure on Windows in `SecuritySyntaxChecker` (PR #164183)
https://github.com/stemil01 edited https://github.com/llvm/llvm-project/pull/164183 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Mark `_lstrcatA`, `_strcpyA`, and `_strdup` as insecure on Windows in `SecuritySyntaxChecker` (PR #164183)
https://github.com/stemil01 created
https://github.com/llvm/llvm-project/pull/164183
Addresses issue #103038.
Some of the functions mentioned in that issue are already covered or do not
exist under the specified names. Therefore, this patch adds only the three
functions listed above.
There is a separate commit for `clang-format` style changes since they seem to
be inconsistent with the rest of `Checkers.td` file.
>From 792f9858a51e65a597e53560c77ab02b952229e4 Mon Sep 17 00:00:00 2001
From: stemil01
Date: Sun, 19 Oct 2025 20:36:12 +0200
Subject: [PATCH 1/2] [clang][analyzer] Mark `lstrcatA`, `lstrcpyA`, and
`_strdup` as insecure on Windows in `SecuritySyntaxChecker`
---
.../clang/StaticAnalyzer/Checkers/Checkers.td | 15 ++
.../Checkers/CheckSecuritySyntaxOnly.cpp | 217 +-
2 files changed, 230 insertions(+), 2 deletions(-)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index ffae3b9310979..4e11872186ac3 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -869,6 +869,16 @@ def getpw : Checker<"getpw">,
Dependencies<[SecuritySyntaxChecker]>,
Documentation;
+def lstrcatA : Checker<"lstrcatA">,
+ HelpText<"Warn on uses of the 'lstrcatA' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+def lstrcpyA : Checker<"lstrcpyA">,
+ HelpText<"Warn on uses of the 'lstrcpyA' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
def mktemp : Checker<"mktemp">,
HelpText<"Warn on uses of the 'mktemp' function">,
Dependencies<[SecuritySyntaxChecker]>,
@@ -890,6 +900,11 @@ def strcpy : Checker<"strcpy">,
Dependencies<[SecuritySyntaxChecker]>,
Documentation;
+def strdup : Checker<"strdup">,
+ HelpText<"Warn on uses of the '_strdup' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
def vfork : Checker<"vfork">,
HelpText<"Warn on uses of the 'vfork' function">,
Dependencies<[SecuritySyntaxChecker]>,
diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
index 5e75c1c4a3abd..c97f4fb18e1c6 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -10,14 +10,19 @@
//
//===--===//
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
+#include "clang/AST/TypeBase.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Basic/TargetInfo.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
-#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/raw_ostream.h"
@@ -40,9 +45,12 @@ struct ChecksFilter {
bool check_bzero = false;
bool check_gets = false;
bool check_getpw = false;
+ bool check_lstrcatA = false;
+ bool check_lstrcpyA = false;
bool check_mktemp = false;
bool check_mkstemp = false;
bool check_strcpy = false;
+ bool check_strdup = false;
bool check_DeprecatedOrUnsafeBufferHandling = false;
bool check_rand = false;
bool check_vfork = false;
@@ -55,9 +63,12 @@ struct ChecksFilter {
CheckerNameRef checkName_bzero;
CheckerNameRef checkName_gets;
CheckerNameRef checkName_getpw;
+ CheckerNameRef checkName_lstrcatA;
+ CheckerNameRef checkName_lstrcpyA;
CheckerNameRef checkName_mktemp;
CheckerNameRef checkName_mkstemp;
CheckerNameRef checkName_strcpy;
+ CheckerNameRef checkName_strdup;
CheckerNameRef checkName_DeprecatedOrUnsafeBufferHandling;
CheckerNameRef checkName_rand;
CheckerNameRef checkName_vfork;
@@ -104,9 +115,12 @@ class WalkAST : public StmtVisitor {
void checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_lstrcatA(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_lstrcpyA(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_strdup(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
void che
[clang] [clang][analyzer] Mark `_lstrcatA`, `_strcpyA`, and `_strdup` as insecure on Windows in `SecuritySyntaxChecker` (PR #164183)
llvmbot wrote:
@llvm/pr-subscribers-clang-static-analyzer-1
Author: Stefan Milenkovic (stemil01)
Changes
Addresses issue #103038.
Some of the functions mentioned in that issue are already covered or do not
exist under the specified names. Therefore, this patch adds only the three
functions listed above.
There is a separate commit for `clang-format` style changes since they seem to
be inconsistent with the rest of `Checkers.td` file.
---
Full diff: https://github.com/llvm/llvm-project/pull/164183.diff
2 Files Affected:
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+15)
- (modified) clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
(+215-2)
``diff
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index ffae3b9310979..547a6c9360fee 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -869,6 +869,16 @@ def getpw : Checker<"getpw">,
Dependencies<[SecuritySyntaxChecker]>,
Documentation;
+def lstrcatA : Checker<"lstrcatA">,
+ HelpText<"Warn on uses of the 'lstrcatA' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+def lstrcpyA : Checker<"lstrcpyA">,
+ HelpText<"Warn on uses of the 'lstrcpyA' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
def mktemp : Checker<"mktemp">,
HelpText<"Warn on uses of the 'mktemp' function">,
Dependencies<[SecuritySyntaxChecker]>,
@@ -890,6 +900,11 @@ def strcpy : Checker<"strcpy">,
Dependencies<[SecuritySyntaxChecker]>,
Documentation;
+def strdup : Checker<"strdup">,
+ HelpText<"Warn on uses of the '_strdup' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
def vfork : Checker<"vfork">,
HelpText<"Warn on uses of the 'vfork' function">,
Dependencies<[SecuritySyntaxChecker]>,
diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
index 5e75c1c4a3abd..c97f4fb18e1c6 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -10,14 +10,19 @@
//
//===--===//
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
+#include "clang/AST/TypeBase.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Basic/TargetInfo.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
-#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/raw_ostream.h"
@@ -40,9 +45,12 @@ struct ChecksFilter {
bool check_bzero = false;
bool check_gets = false;
bool check_getpw = false;
+ bool check_lstrcatA = false;
+ bool check_lstrcpyA = false;
bool check_mktemp = false;
bool check_mkstemp = false;
bool check_strcpy = false;
+ bool check_strdup = false;
bool check_DeprecatedOrUnsafeBufferHandling = false;
bool check_rand = false;
bool check_vfork = false;
@@ -55,9 +63,12 @@ struct ChecksFilter {
CheckerNameRef checkName_bzero;
CheckerNameRef checkName_gets;
CheckerNameRef checkName_getpw;
+ CheckerNameRef checkName_lstrcatA;
+ CheckerNameRef checkName_lstrcpyA;
CheckerNameRef checkName_mktemp;
CheckerNameRef checkName_mkstemp;
CheckerNameRef checkName_strcpy;
+ CheckerNameRef checkName_strdup;
CheckerNameRef checkName_DeprecatedOrUnsafeBufferHandling;
CheckerNameRef checkName_rand;
CheckerNameRef checkName_vfork;
@@ -104,9 +115,12 @@ class WalkAST : public StmtVisitor {
void checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_lstrcatA(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_lstrcpyA(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
+ void checkCall_strdup(const CallExpr *CE, const FunctionDecl *FD);
void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
void checkDeprecatedOrUnsafeBufferHandling(cons
[clang] [clang][analyzer] Mark `_lstrcatA`, `_strcpyA`, and `_strdup` as insecure on Windows in `SecuritySyntaxChecker` (PR #164183)
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/164183 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Add new option to specify functions `SecuritySyntaxChecker` warns about. (PR #164184)
llvmbot wrote:
@llvm/pr-subscribers-clang-static-analyzer-1
Author: Stefan Milenkovic (stemil01)
Changes
Addresses #103038.
Currently, the list of functions for which `SecuritySyntaxChecker` emits
warnings is fixed. This patch adds a new command-line option `Warn`, which
allows users to provide a space-separated list of function names to mark as
explicitly insecure.
There is a separate commit for `clang-format` style changes since they affect
the existing formatting of `Checkers.td` file.
---
Full diff: https://github.com/llvm/llvm-project/pull/164184.diff
3 Files Affected:
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+77-67)
- (modified) clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
(+47-11)
- (modified) clang/test/Analysis/analyzer-config.c (+1)
``diff
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index ffae3b9310979..da8985ce44c0c 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -839,79 +839,89 @@ def PaddingChecker : Checker<"Padding">,
let ParentPackage = InsecureAPI in {
-def SecuritySyntaxChecker : Checker<"SecuritySyntaxChecker">,
- HelpText<"Base of various security function related checkers">,
- Documentation,
- Hidden;
-
-def bcmp : Checker<"bcmp">,
- HelpText<"Warn on uses of the 'bcmp' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def bcopy : Checker<"bcopy">,
- HelpText<"Warn on uses of the 'bcopy' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def bzero : Checker<"bzero">,
- HelpText<"Warn on uses of the 'bzero' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def gets : Checker<"gets">,
- HelpText<"Warn on uses of the 'gets' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def getpw : Checker<"getpw">,
- HelpText<"Warn on uses of the 'getpw' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def mktemp : Checker<"mktemp">,
- HelpText<"Warn on uses of the 'mktemp' function">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
-
-def mkstemp : Checker<"mkstemp">,
- HelpText<"Warn when 'mkstemp' is passed fewer than 6 X's in the format "
- "string">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
+ def SecuritySyntaxChecker
+ : Checker<"SecuritySyntaxChecker">,
+HelpText<"Base of various security function related checkers">,
+CheckerOptions<[CmdLineOption<
+String, "Warn",
+"List of space-separated function name to be warned about. "
+"Defaults to an empty list.",
+"", InAlpha>]>,
+Documentation,
+Hidden;
+
+ def bcmp : Checker<"bcmp">,
+ HelpText<"Warn on uses of the 'bcmp' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def bcopy : Checker<"bcopy">,
+ HelpText<"Warn on uses of the 'bcopy' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def bzero : Checker<"bzero">,
+ HelpText<"Warn on uses of the 'bzero' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def gets : Checker<"gets">,
+ HelpText<"Warn on uses of the 'gets' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def getpw : Checker<"getpw">,
+ HelpText<"Warn on uses of the 'getpw' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def mktemp : Checker<"mktemp">,
+ HelpText<"Warn on uses of the 'mktemp' function">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
+
+ def mkstemp
+ : Checker<"mkstemp">,
+HelpText<"Warn when 'mkstemp' is passed fewer than 6 X's in the format
"
+ "string">,
+Dependencies<[SecuritySyntaxChecker]>,
+Documentation;
-def rand : Checker<"rand">,
- HelpText<"Warn on uses of the 'rand', 'random', and related functions">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
+ def rand
+ : Checker<"rand">,
+HelpText<"Warn on uses of the 'rand', 'random', and related
functions">,
+Dependencies<[SecuritySyntaxChecker]>,
+Documentation;
-def strcpy : Checker<"strcpy">,
- HelpText<"Warn on uses of the 'strcpy' and 'strcat' functions">,
- Dependencies<[SecuritySyntaxChecker]>,
- Documentation;
+ def strcpy : Checker<"strcpy">,
+ HelpText<"Warn on uses of the 'strcpy' and 'strcat' functions">,
+ Dependencies<[SecuritySyntaxChecker]>,
+ Documentation;
-def vfork : Checker<"vfork">,
- HelpText<"Warn on uses of the 'vfork' funct
[clang] [C++20][Modules] Implement P1857R3 Modules Dependency Discovery (PR #107168)
@@ -986,6 +989,14 @@ def warn_module_conflict : Warning<
InGroup;
// C++20 modules
+def err_pp_module_name_is_macro : Error<
+ "%select{module|partition}0 name component %1 cannot be a object-like
macro">;
+def err_pp_module_expected_ident : Error<
+ "expected %select{identifier after '.' in |}0module name">;
hubert-reinterpretcast wrote:
> We have a utility function `isNextPPTokenOneOf`, let me try. but it's
> disabled macro expansion.
If you mean that it determines what the next token is without trying to expand
that token (if it is a macro name), then that's exactly what we want for the
`(` restriction. It's the `;`/`[` check that needs to be done after macro
expansion.
https://github.com/llvm/llvm-project/pull/107168
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[compiler-rt] [libcxx] [libcxxabi] [libunwind] [runtimes][PAC] Harden unwinding when possible (PR #143230)
https://github.com/kovdan01 requested changes to this pull request. @ojhunt Thanks for tons of fixes! We have one more usage of unions in libunwind.cpp which is technically UB. I've proposed a fix for this. See commit a29af825c71d70e83445cd4214f7145642201506 from my branch [ptrauth-unwinding-2025-10-19](https://github.com/kovdan01/llvm-project/commits/ptrauth-unwinding-2025-10-19/) As soon as this is addressed, I have no other objections from my side regarding this PR. Thanks for a great work! https://github.com/llvm/llvm-project/pull/143230 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[compiler-rt] [libcxx] [libcxxabi] [libunwind] [runtimes][PAC] Harden unwinding when possible (PR #143230)
@@ -118,22 +118,62 @@ _LIBUNWIND_HIDDEN int __unw_set_reg(unw_cursor_t *cursor,
unw_regnum_t regNum,
typedef LocalAddressSpace::pint_t pint_t;
AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
if (co->validReg(regNum)) {
-co->setReg(regNum, (pint_t)value);
// special case altering IP to re-find info (being called by personality
// function)
if (regNum == UNW_REG_IP) {
unw_proc_info_t info;
// First, get the FDE for the old location and then update it.
co->getInfo(&info);
- co->setInfoBasedOnIPRegister(false);
+
+ pint_t sp = (pint_t)co->getReg(UNW_REG_SP);
+
+#if defined(_LIBUNWIND_TARGET_AARCH64_AUTHENTICATED_UNWINDING)
+ {
+// It is only valid to set the IP within the current function.
+// This is important for ptrauth, otherwise the IP cannot be correctly
+// signed.
+// We re-sign to a more usable form and then use it directly.
+union {
kovdan01 wrote:
Please avoid using unions here as well since reading from `authenticated_value`
while `opaque_value` was the last assigned member is UB in C++.
I've prepared a fix which works on my side. You are welcome to just apply that
if you are happy with the fix implementation. See commit
a29af825c71d70e83445cd4214f7145642201506 from my branch
[ptrauth-unwinding-2025-10-19](https://github.com/kovdan01/llvm-project/commits/ptrauth-unwinding-2025-10-19/)
https://github.com/llvm/llvm-project/pull/143230
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[compiler-rt] [libcxx] [libcxxabi] [libunwind] [runtimes][PAC] Harden unwinding when possible (PR #143230)
https://github.com/kovdan01 edited https://github.com/llvm/llvm-project/pull/143230 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Add new option to specify functions `SecuritySyntaxChecker` warns about. (PR #164184)
https://github.com/stemil01 edited https://github.com/llvm/llvm-project/pull/164184 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[compiler-rt] [libcxx] [libcxxabi] [libunwind] [runtimes][PAC] Harden unwinding when possible (PR #143230)
@@ -22,7 +22,6 @@ #include "dwarf2.h" #include "libunwind_ext.h" - kovdan01 wrote: Nit: unintended formatting change https://github.com/llvm/llvm-project/pull/143230 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Add new option to specify functions `SecuritySyntaxChecker` warns about (PR #164184)
https://github.com/stemil01 edited https://github.com/llvm/llvm-project/pull/164184 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][PAC][NFC] Provide addition support macros to ptrauth.h (PR #161027)
kovdan01 wrote: @ojhunt Can we consider this PR obsolete and close it since we no longer use this union approach and things are already (almost) fixed in the main unwinding PR #143230? https://github.com/llvm/llvm-project/pull/161027 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] dd6a6ba - [clang-format] Reuse AlignTokens for aligning macros (#164120)
Author: Björn Schäpers
Date: 2025-10-20T00:04:42+02:00
New Revision: dd6a6bac708235fe2ed80670cd873258430264c2
URL:
https://github.com/llvm/llvm-project/commit/dd6a6bac708235fe2ed80670cd873258430264c2
DIFF:
https://github.com/llvm/llvm-project/commit/dd6a6bac708235fe2ed80670cd873258430264c2.diff
LOG: [clang-format] Reuse AlignTokens for aligning macros (#164120)
Fixes #52985.
This leaves aligning short case statements with its own logic. But that
is harder to port, because it aligns even with no content of the right
hand side of the :.
Added:
Modified:
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
Removed:
diff --git a/clang/lib/Format/WhitespaceManager.cpp
b/clang/lib/Format/WhitespaceManager.cpp
index 92612946ce87d..aae2f3e6439cc 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -432,7 +432,11 @@ AlignTokenSequence(const FormatStyle &Style, unsigned
Start, unsigned End,
// right-justified. It is used to align compound assignments like `+=` and `=`.
// When RightJustify and ACS.PadOperators are true, operators in each block to
// be aligned will be padded on the left to the same length before aligning.
-template
+//
+// The simple check will not look at the indentaion and nesting level to
recurse
+// into the line for alignment. It will also not count the commas. This is e.g.
+// for aligning macro definitions.
+template
static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
SmallVector
&Changes,
unsigned StartAt,
@@ -465,9 +469,9 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
// Measure the scope level (i.e. depth of (), [], {}) of the first token, and
// abort when we hit any token in a higher scope than the starting one.
- auto IndentAndNestingLevel = StartAt < Changes.size()
- ? Changes[StartAt].indentAndNestingLevel()
- : std::tuple();
+ const auto IndentAndNestingLevel =
+ StartAt < Changes.size() ? Changes[StartAt].indentAndNestingLevel()
+ : std::tuple();
// Keep track of the number of commas before the matching tokens, we will
only
// align a sequence of matching tokens if they are preceded by the same
number
@@ -536,14 +540,17 @@ static unsigned AlignTokens(const FormatStyle &Style, F
&&Matches,
if (CurrentChange.Tok->isNot(tok::comment))
LineIsComment = false;
-if (CurrentChange.Tok->is(tok::comma)) {
- ++CommasBeforeMatch;
-} else if (CurrentChange.indentAndNestingLevel() > IndentAndNestingLevel) {
- // Call AlignTokens recursively, skipping over this scope block.
- unsigned StoppedAt =
- AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
- i = StoppedAt - 1;
- continue;
+if (!SimpleCheck) {
+ if (CurrentChange.Tok->is(tok::comma)) {
+++CommasBeforeMatch;
+ } else if (CurrentChange.indentAndNestingLevel() >
+ IndentAndNestingLevel) {
+// Call AlignTokens recursively, skipping over this scope block.
+const auto StoppedAt =
+AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
+i = StoppedAt - 1;
+continue;
+ }
}
if (!Matches(CurrentChange))
@@ -683,61 +690,8 @@ void WhitespaceManager::alignConsecutiveMacros() {
return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
};
- unsigned MinColumn = 0;
-
- // Start and end of the token sequence we're processing.
- unsigned StartOfSequence = 0;
- unsigned EndOfSequence = 0;
-
- // Whether a matching token has been found on the current line.
- bool FoundMatchOnLine = false;
-
- // Whether the current line consists only of comments
- bool LineIsComment = true;
-
- unsigned I = 0;
- for (unsigned E = Changes.size(); I != E; ++I) {
-if (Changes[I].NewlinesBefore != 0) {
- EndOfSequence = I;
-
- // Whether to break the alignment sequence because of an empty line.
- bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
-!Style.AlignConsecutiveMacros.AcrossEmptyLines;
-
- // Whether to break the alignment sequence because of a line without a
- // match.
- bool NoMatchBreak =
- !FoundMatchOnLine &&
- !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
-
- if (EmptyLineBreak || NoMatchBreak) {
-AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
- AlignMacrosMatches, Changes);
- }
-
- // A new line starts, re-initialize line status tracking bools.
- FoundMatchOnLine = false;
- LineIsComment = true;
-}
-
-if (Changes[I].Tok->isNot(tok::comment))
- LineIsComme
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
https://github.com/HazardyKnusperkeks auto_merge_disabled https://github.com/llvm/llvm-project/pull/164120 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Reuse AlignTokens for aligning macros (PR #164120)
https://github.com/HazardyKnusperkeks closed https://github.com/llvm/llvm-project/pull/164120 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Simplify AlignMacroMatches (PR #164122)
=?utf-8?q?Björn_Schäpers?=
Message-ID:
In-Reply-To:
@@ -656,7 +656,6 @@ void WhitespaceManager::alignConsecutiveMacros() {
auto AlignMacrosMatches = [](const Change &C) {
const FormatToken *Current = C.Tok;
owenca wrote:
This is unique in that a local pointer is initialized to a member of the
parameter at the start of the lambda and must remain nonnull till the end after
being possibly moved. So the assert would serve as a precondition validation.
https://github.com/llvm/llvm-project/pull/164122
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Simplify AlignMacroMatches (PR #164122)
=?utf-8?q?Bj=C3=B6rn_Sch=C3=A4pers?= Message-ID: In-Reply-To: https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/164122 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ARM][KCFI] Add backend support for Kernel Control-Flow Integrity (PR #163698)
@@ -530,6 +534,9 @@ void ARMPassConfig::addPreEmitPass() {
}
void ARMPassConfig::addPreEmitPass2() {
+ // Unpack KCFI bundles before AsmPrinter
+ addPass(createUnpackMachineBundles(nullptr));
davemgreen wrote:
There is already a UnpackMachineBundles in addPreEmitPass, can it be reused?
https://github.com/llvm/llvm-project/pull/163698
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ARM][KCFI] Add backend support for Kernel Control-Flow Integrity (PR #163698)
@@ -6535,6 +6535,15 @@ def CMP_SWAP_64 : PseudoInst<(outs GPRPair:$Rd,
GPRPair:$addr_temp_out),
def : Pat<(atomic_fence (timm), 0), (MEMBARRIER)>;
+//===--===//
+// KCFI check pseudo-instruction.
+//===--===//
+let isPseudo = 1 in {
davemgreen wrote:
Does this need isPseudo = 1 if it is a PseudoInst?
https://github.com/llvm/llvm-project/pull/163698
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ARM][KCFI] Add backend support for Kernel Control-Flow Integrity (PR #163698)
@@ -0,0 +1,191 @@ +; RUN: llc -mtriple=thumbv6m-none-eabi < %s | FileCheck %s davemgreen wrote: I would recommend update_llc_test_checks wherever it is sensible to use it. https://github.com/llvm/llvm-project/pull/163698 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Give empty template parameter mapping an empty MLTAL (PR #164051)
@@ -564,12 +564,17 @@ ExprResult
ConstraintSatisfactionChecker::EvaluateAtomicConstraint(
std::optional
ConstraintSatisfactionChecker::SubstitutionInTemplateArguments(
const NormalizedConstraintWithParamMapping &Constraint,
-MultiLevelTemplateArgumentList MLTAL,
-llvm::SmallVector &SubstitutedOuterMost) {
+const MultiLevelTemplateArgumentList &MLTAL,
+llvm::SmallVector &SubstitutedOutermost) {
zyn0217 wrote:
They are?
https://github.com/llvm/llvm-project/commit/9beea6e3a66dce9ed2086d5fbc1fb74b69b56a09
Of course I can merge them separately if you want.
https://github.com/llvm/llvm-project/pull/164051
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Add VTable class name for array types (PR #164155)
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/164155 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Add VTable class name for array types (PR #164155)
https://github.com/MihailMihov created
https://github.com/llvm/llvm-project/pull/164155
This PR adds the VTable name `_ZTVN10__cxxabiv117__array_type_infoE` for
`Type::ConstantArray`, `Type::IncompleteArray` and `Type::VariableArray` in
`ItaniumRTTIBuilder::BuildVTablePointer`.
issue #163601
>From f66918c58a081aee14099e24b3d7af68ab4e23b6 Mon Sep 17 00:00:00 2001
From: Mihail Mihov
Date: Sun, 19 Oct 2025 11:22:07 +0200
Subject: [PATCH] [CIR] Add VTable class name for array types
---
clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
b/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
index c184d4a4b1d97..b3045a5661734 100644
--- a/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
@@ -941,9 +941,7 @@ const char *vTableClassNameForType(const CIRGenModule &cgm,
const Type *ty) {
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
-cgm.errorNYI("VTableClassNameForType: __array_type_info");
-break;
-
+return "_ZTVN10__cxxabiv117__array_type_infoE";
case Type::FunctionNoProto:
case Type::FunctionProto:
cgm.errorNYI("VTableClassNameForType: __function_type_info");
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Add VTable class name for array types (PR #164155)
MihailMihov wrote: Currently there is no test for this, as I'm not sure how to test it. In the linked issue, `throw` was suggested, but I don't think that can work for arrays as they always go through the array-to-pointer conversion. `typeid` can't be used in the tests and I think it's not implemented in CIR. The only thing that might work is try/catch. I think [this](https://godbolt.org/z/5f1KnK6oj) would be a correct test for `Type::ConstantArray`, but `try` is not yet upstreamed and I don't think that same idea can be applied for `Type::IncompleteArray` or `Type::VariableArray`. https://github.com/llvm/llvm-project/pull/164155 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] Draft, do not review (PR #164156)
https://github.com/localspook updated
https://github.com/llvm/llvm-project/pull/164156
>From 5a22a1db87a1d45ef95e33944a87a101769fe8e2 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:03 -0700
Subject: [PATCH 1/4] [clang][Sema] Attempt to parse delayed templates at the
end of the TU
---
clang/lib/Sema/Sema.cpp | 11 +++
1 file changed, 11 insertions(+)
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 39fa25f66f3b7..8e0ad9325e2af 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1251,6 +1251,17 @@ void Sema::ActOnEndOfTranslationUnit() {
if (LateTemplateParserCleanup)
LateTemplateParserCleanup(OpaqueParser);
+if (LangOpts.DelayedTemplateParsing) {
+ // Try to parse any templates that have been delayed and never
+ // instantiated so that their bodies are available for static
+ // analysis tools to analyze.
+ Diags.setSuppressAllDiagnostics(true);
+ for (auto &[Decl, Template] : LateParsedTemplateMap)
+if (Decl->isLateTemplateParsed())
+ LateTemplateParser(OpaqueParser, *Template);
+ Diags.setSuppressAllDiagnostics(false);
+}
+
CheckDelayedMemberExceptionSpecs();
} else {
// If we are building a TU prefix for serialization, it is safe to transfer
>From 29502017417e78599fbb92526e166a5f5457b583 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:26 -0700
Subject: [PATCH 2/4] Fix clang-tidy tests that break
---
.../cppcoreguidelines/pro-type-member-init-delayed.cpp | 9 -
.../checkers/modernize/use-equals-default-delayed.cpp| 9 -
2 files changed, 18 deletions(-)
delete mode 100644
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
index d3436ba6c1211..93bf4993f7b8b 100644
---
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
+++
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
@@ -21,12 +21,3 @@ struct PositiveFieldAfterConstructor {
};
// Explicit instantiation.
template class PositiveFieldAfterConstructor;
-
-// This declaration isn't used and won't be parsed 'delayed-template-parsing'.
-// The body of the declaration is 'null' and may cause crash if not handled
-// properly by checkers.
-template
-struct UnusedDelayedConstructor {
- UnusedDelayedConstructor() {}
- int F;
-};
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
deleted file mode 100644
index f39efd8452f79..0
---
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-// RUN: clang-tidy %s -checks=-*,modernize-use-equals-default -- -std=c++11
-fdelayed-template-parsing -fexceptions | count 0
-// Note: this test expects no diagnostics, but FileCheck cannot handle that,
-// hence the use of | count 0.
-// FIXME: Make the test work in all language modes.
-
-template
-struct S {
- S& operator=(const S&) { return *this; }
-};
>From 9e2f12d65baf460dcb9850fc171bcf5091c363b7 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 02:36:34 -0700
Subject: [PATCH 3/4] Migrate clang-tidy tests away from
`-fno-delayed-template-parsing`
---
.../clang-tidy/checkers/bugprone/branch-clone.cpp | 2 +-
.../bugprone/crtp-constructor-accessibility.cpp| 2 +-
.../clang-tidy/checkers/bugprone/infinite-loop.cpp | 2 +-
.../bugprone/move-forwarding-reference.cpp | 2 +-
.../bugprone/return-const-ref-from-parameter.cpp | 2 +-
.../checkers/bugprone/sizeof-expression.cpp| 3 +--
.../bugprone/string-integer-assignment.cpp | 2 +-
.../bugprone/switch-missing-default-case.cpp | 2 +-
.../bugprone/unhandled-self-assignment.cpp | 2 +-
.../clang-tidy/checkers/bugprone/unused-raii.cpp | 2 +-
.../checkers/bugprone/use-after-move.cpp | 4 ++--
.../checkers/cppcoreguidelines/init-variables.cpp | 2 +-
.../missing-std-forward-custom-function.cpp| 2 +-
.../cppcoreguidelines/missing-std-forward.cpp | 2 +-
.../cppcoreguidelines/no-suspend-with-lock.cpp | 2 +-
.../pro-type-member-init-cxx20.cpp | 2 +-
.../pro-type-member-init-cxx98.cpp | 2 +-
.../pro-type-member-init-delayed.cpp | 2 +-
.../cppcoreguidelines/pro-type-member-init.cpp | 2 +-
...e-reference-param-not-moved-custom-function.cpp | 2 +-
.../rvalue-reference-param-not-moved.cpp | 10 +-
.../prefer-static-over-anonymous-namespace.cpp | 6 +++---
.../misc/const-correctness-
[clang] [clang-tools-extra] Draft, do not review (PR #164156)
https://github.com/localspook created
https://github.com/llvm/llvm-project/pull/164156
None
>From 5a22a1db87a1d45ef95e33944a87a101769fe8e2 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:03 -0700
Subject: [PATCH 1/3] [clang][Sema] Attempt to parse delayed templates at the
end of the TU
---
clang/lib/Sema/Sema.cpp | 11 +++
1 file changed, 11 insertions(+)
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 39fa25f66f3b7..8e0ad9325e2af 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1251,6 +1251,17 @@ void Sema::ActOnEndOfTranslationUnit() {
if (LateTemplateParserCleanup)
LateTemplateParserCleanup(OpaqueParser);
+if (LangOpts.DelayedTemplateParsing) {
+ // Try to parse any templates that have been delayed and never
+ // instantiated so that their bodies are available for static
+ // analysis tools to analyze.
+ Diags.setSuppressAllDiagnostics(true);
+ for (auto &[Decl, Template] : LateParsedTemplateMap)
+if (Decl->isLateTemplateParsed())
+ LateTemplateParser(OpaqueParser, *Template);
+ Diags.setSuppressAllDiagnostics(false);
+}
+
CheckDelayedMemberExceptionSpecs();
} else {
// If we are building a TU prefix for serialization, it is safe to transfer
>From 29502017417e78599fbb92526e166a5f5457b583 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:26 -0700
Subject: [PATCH 2/3] Fix clang-tidy tests that break
---
.../cppcoreguidelines/pro-type-member-init-delayed.cpp | 9 -
.../checkers/modernize/use-equals-default-delayed.cpp| 9 -
2 files changed, 18 deletions(-)
delete mode 100644
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
index d3436ba6c1211..93bf4993f7b8b 100644
---
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
+++
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
@@ -21,12 +21,3 @@ struct PositiveFieldAfterConstructor {
};
// Explicit instantiation.
template class PositiveFieldAfterConstructor;
-
-// This declaration isn't used and won't be parsed 'delayed-template-parsing'.
-// The body of the declaration is 'null' and may cause crash if not handled
-// properly by checkers.
-template
-struct UnusedDelayedConstructor {
- UnusedDelayedConstructor() {}
- int F;
-};
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
deleted file mode 100644
index f39efd8452f79..0
---
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-// RUN: clang-tidy %s -checks=-*,modernize-use-equals-default -- -std=c++11
-fdelayed-template-parsing -fexceptions | count 0
-// Note: this test expects no diagnostics, but FileCheck cannot handle that,
-// hence the use of | count 0.
-// FIXME: Make the test work in all language modes.
-
-template
-struct S {
- S& operator=(const S&) { return *this; }
-};
>From 9e2f12d65baf460dcb9850fc171bcf5091c363b7 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 02:36:34 -0700
Subject: [PATCH 3/3] Migrate clang-tidy tests away from
`-fno-delayed-template-parsing`
---
.../clang-tidy/checkers/bugprone/branch-clone.cpp | 2 +-
.../bugprone/crtp-constructor-accessibility.cpp| 2 +-
.../clang-tidy/checkers/bugprone/infinite-loop.cpp | 2 +-
.../bugprone/move-forwarding-reference.cpp | 2 +-
.../bugprone/return-const-ref-from-parameter.cpp | 2 +-
.../checkers/bugprone/sizeof-expression.cpp| 3 +--
.../bugprone/string-integer-assignment.cpp | 2 +-
.../bugprone/switch-missing-default-case.cpp | 2 +-
.../bugprone/unhandled-self-assignment.cpp | 2 +-
.../clang-tidy/checkers/bugprone/unused-raii.cpp | 2 +-
.../checkers/bugprone/use-after-move.cpp | 4 ++--
.../checkers/cppcoreguidelines/init-variables.cpp | 2 +-
.../missing-std-forward-custom-function.cpp| 2 +-
.../cppcoreguidelines/missing-std-forward.cpp | 2 +-
.../cppcoreguidelines/no-suspend-with-lock.cpp | 2 +-
.../pro-type-member-init-cxx20.cpp | 2 +-
.../pro-type-member-init-cxx98.cpp | 2 +-
.../pro-type-member-init-delayed.cpp | 2 +-
.../cppcoreguidelines/pro-type-member-init.cpp | 2 +-
...e-reference-param-not-moved-custom-function.cpp | 2 +-
.../rvalue-reference-param-not-moved.cpp | 10 +-
.../prefer-static-over-anonymous-namespace.cpp | 6 +++---
.../misc/const-correc
[clang] [libcxx] [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (PR #78707)
https://github.com/huixie90 updated
https://github.com/llvm/llvm-project/pull/78707
>From 0dc5bf91516e2138ed73b602cb17943ef6bcc878 Mon Sep 17 00:00:00 2001
From: Hui
Date: Fri, 19 Jan 2024 12:33:43 +
Subject: [PATCH 1/9] [libc++] fix _Atomic c11 compare exchange does not update
expected results
---
clang/lib/CodeGen/CGAtomic.cpp | 61 +-
1 file changed, 37 insertions(+), 24 deletions(-)
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 4a3446abcc78f..01d02c2dbed45 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -376,6 +376,7 @@ bool AtomicInfo::emitMemSetZeroIfNecessary() const {
static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
Address Dest, Address Ptr,
Address Val1, Address Val2,
+ Address ExpectedResult,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
llvm::AtomicOrdering FailureOrder,
@@ -411,9 +412,17 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
CGF.Builder.SetInsertPoint(StoreExpectedBB);
// Update the memory at Expected with Old's value.
- auto *I = CGF.Builder.CreateStore(Old, Val1);
- CGF.addInstToCurrentSourceAtom(I, Old);
+ llvm::Type *ExpectedType = ExpectedResult.getElementType();
+ uint64_t OriginalSizeInBits =
CGF.CGM.getDataLayout().getTypeSizeInBits(ExpectedType);
+ if (OriginalSizeInBits / 8 == Size) {
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ } else {
+// How to just store N bytes to ExpectedResult ?
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ }
// Finally, branch to the exit point.
CGF.Builder.CreateBr(ContinueBB);
@@ -428,6 +437,7 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
bool IsWeak, Address Dest, Address Ptr,
Address Val1, Address Val2,
+Address ExpectedResult,
llvm::Value *FailureOrderVal,
uint64_t Size,
llvm::AtomicOrdering SuccessOrder,
@@ -458,7 +468,7 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// success argument". This condition has been lifted and the only
// precondition is 31.7.2.18. Effectively treat this as a DR and skip
// language version checks.
-emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size,
SuccessOrder,
+emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
FailureOrder, Scope);
return;
}
@@ -483,17 +493,17 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// Emit all the different atomics
CGF.Builder.SetInsertPoint(MonotonicBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder, llvm::AtomicOrdering::Monotonic,
Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(AcquireBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::Acquire, Scope);
CGF.Builder.CreateBr(ContBB);
CGF.Builder.SetInsertPoint(SeqCstBB);
- emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
+ emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
Size, SuccessOrder,
llvm::AtomicOrdering::SequentiallyConsistent, Scope);
CGF.Builder.CreateBr(ContBB);
@@ -526,6 +536,7 @@ static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy
&Builder,
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
Address Ptr, Address Val1, Address Val2,
+ Address ExpectedResult,
llvm::Value *IsWeak, llvm::Value *FailureOrder,
uint64_t Size, llvm::AtomicOrdering Order,
llvm::SyncScope::ID Scope) {
@@ -542,13 +553,13 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr
*E, Address Dest,
case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
-FailureO
[clang] [clang-tools-extra] Draft, do not review (PR #164156)
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 origin/main HEAD --extensions cpp -- clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/crtp-constructor-accessibility.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/move-forwarding-reference.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/string-integer-assignment.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/switch-missing-default-case.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-raii.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/use-after-move.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward-custom-function.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/no-suspend-with-lock.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-cxx20.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-cxx98.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved-custom-function.cpp clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp clang-tools-extra/test/clang-tidy/checkers/llvm/prefer-static-over-anonymous-namespace.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-allowed-types.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-cxx17.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-pointers-values.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-pointers.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-values.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-transform-pointer-as-values.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-transform-values.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-unaligned.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values-before-cxx23.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-wrong-config.cpp clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner-wrong-config.cpp clang-tools-extra/test/clang-tidy/checkers/misc/unconventional-assign-operator-cxx17.cpp clang-tools-extra/test/clang-tidy/checkers/misc/unconventional-assign-operator.cpp clang-tools-extra/test/clang-tidy/checkers/misc/unused-parameters.cpp clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls-cxx17.cpp clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/pass-by-value.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/redundant-void-arg-delayed.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints-first-greatergreater.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-constraints.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx20.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr-basic.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-scope-lock-warn-on-using-and-typedef-false.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock-warn-on-single-locks-false.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-trailing-return-type-transform-lambdas-cxx14.cpp clang-tools-extra/test/clang-tid
[clang-tools-extra] f5ae102 - [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 3/N (#164085)
Author: Baranov Victor
Date: 2025-10-19T14:33:17+03:00
New Revision: f5ae102745bd5c2abf7b9bcdc1f7e765951c648b
URL:
https://github.com/llvm/llvm-project/commit/f5ae102745bd5c2abf7b9bcdc1f7e765951c648b
DIFF:
https://github.com/llvm/llvm-project/commit/f5ae102745bd5c2abf7b9bcdc1f7e765951c648b.diff
LOG: [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings
3/N (#164085)
Continue https://github.com/llvm/llvm-project/pull/153885.
Added:
Modified:
clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
clang-tools-extra/clang-tidy/android/CloexecCheck.h
clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp
clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
Removed:
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
index cd83423adae05..48c54c0ae02c3 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
@@ -16,12 +16,13 @@ using namespace clang::ast_matchers;
namespace clang::tidy::android {
-namespace {
// Helper function to form the correct string mode for Type3.
// Build the replace text. If it's string constant, add directly in the
// end of the string. Else, add .
-std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM,
- const LangOptions &LangOpts, char Mode) {
+static std::string buildFixMsgForStringFlag(const Expr *Arg,
+const SourceManager &SM,
+const LangOptions &LangOpts,
+char Mode) {
if (Arg->getBeginLoc().isMacroID())
return (Lexer::getSourceText(
CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
@@ -32,11 +33,6 @@ std::string buildFixMsgForStringFlag(const Expr *Arg, const
SourceManager &SM,
StringRef SR = cast(Arg->IgnoreParenCasts())->getString();
return ("\"" + SR + Twine(Mode) + "\"").str();
}
-} // namespace
-
-const char *CloexecCheck::FuncDeclBindingStr = "funcDecl";
-
-const char *CloexecCheck::FuncBindingStr = "func";
void CloexecCheck::registerMatchersImpl(
MatchFinder *Finder, internal::Matcher Function) {
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
index 79f7ab3354d8d..b2b59f5be1b9a 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
@@ -89,10 +89,10 @@ class CloexecCheck : public ClangTidyCheck {
int N) const;
/// Binding name of the FuncDecl of a function call.
- static const char *FuncDeclBindingStr;
+ static constexpr char FuncDeclBindingStr[] = "funcDecl";
/// Binding name of the function call expression.
- static const char *FuncBindingStr;
+ static constexpr char FuncBindingStr[] = "func";
};
} // namespace clang::tidy::android
diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
index 86af5cbd94374..c262b1c05b047 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
@@ -245,12 +245,10 @@ struct OptionEnumMapping<
namespace bugprone {
-namespace {
-
/// Returns if a function is declared inside a system header.
/// These functions are considered to be "standard" (system-provided) library
/// functions.
-bool isStandardFunction(const FunctionDecl *FD) {
+static bool isStandardFunction(const FunctionDecl *FD) {
// Find a possible redeclaration in system header.
// FIXME: Looking at the canonical declaration is not the most exact way
// to do this.
@@ -284,7 +282,7 @@ bool isStandardFunction(const FunctionDecl *FD) {
/// Check if a statement is "C++-only".
/// This includes all statements that have a class name with "CXX" prefix
/// and every other statement that is declared in file ExprCXX.h.
-bool isCXXOnlyStmt(const Stmt *S) {
+static bool isCXXOnlyStmt(const Stmt *S) {
StringRef Name = S->getStmtClassName();
if (Name.starts_with("CXX"))
return true;
@@ -304,7 +302,8 @@ bool isCXXOnlyStmt(const Stmt *S) {
/// called from \p Calle
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 3/N (PR #164085)
https://github.com/vbvictor closed https://github.com/llvm/llvm-project/pull/164085 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] fd073a3 - [clang] separate recursive instantiation check from CodeSynthesisContext (#162224)
Author: Matheus Izvekov
Date: 2025-10-19T14:49:40-03:00
New Revision: fd073a3fbaf0b05fae61cca5def80ce0adaeadb3
URL:
https://github.com/llvm/llvm-project/commit/fd073a3fbaf0b05fae61cca5def80ce0adaeadb3
DIFF:
https://github.com/llvm/llvm-project/commit/fd073a3fbaf0b05fae61cca5def80ce0adaeadb3.diff
LOG: [clang] separate recursive instantiation check from CodeSynthesisContext
(#162224)
This makes pushing / popping CodeSynthesisContexts much cheaper, as it
delegates to another class this functionality which is not actually
needed in most cases.
It also converts a bunch of these uses into just asserts.
This improves compiler performance a little bit:
https://github.com/user-attachments/assets/ed1f7f39-e85e-481d-938f-e227c62994be";
/>
Some diagnostics changes, because we avoid printing redundant context
notes.
Added:
Modified:
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
clang/test/SemaTemplate/instantiate-self.cpp
Removed:
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index add4c1596ab86..cb21335ede075 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13007,6 +13007,37 @@ class Sema final : public SemaBase {
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
+ using InstantiatingSpecializationsKey = llvm::PointerIntPair;
+
+ struct RecursiveInstGuard {
+enum class Kind {
+ Template,
+ DefaultArgument,
+ ExceptionSpec,
+};
+
+RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
+: S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
+ auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
+ if (!Created)
+Key = {};
+}
+
+~RecursiveInstGuard() {
+ if (Key.getOpaqueValue()) {
+[[maybe_unused]] bool Erased =
+S.InstantiatingSpecializations.erase(Key);
+assert(Erased);
+ }
+}
+
+operator bool() const { return Key.getOpaqueValue() == nullptr; }
+
+ private:
+Sema &S;
+Sema::InstantiatingSpecializationsKey Key;
+ };
+
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
@@ -13368,14 +13399,9 @@ class Sema final : public SemaBase {
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
-/// Determine whether we are already instantiating this
-/// specialization in some surrounding active instantiation.
-bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
-
private:
Sema &SemaRef;
bool Invalid;
-bool AlreadyInstantiating;
InstantiatingTemplate(Sema &SemaRef,
CodeSynthesisContext::SynthesisKind Kind,
@@ -13505,7 +13531,7 @@ class Sema final : public SemaBase {
SmallVector CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
- llvm::DenseSet> InstantiatingSpecializations;
+ llvm::DenseSet InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
@@ -13780,6 +13806,14 @@ class Sema final : public SemaBase {
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK, bool Complain = true);
+private:
+ bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
+CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern,
+const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain);
+
+public:
/// Instantiate the definition of an enum from a given pattern.
///
/// \param PointOfInstantiation The point of instantiation within the
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 038f39633760d..7f858050db13e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -639,15 +639,8 @@ Sema::InstantiatingTemplate::InstantiatingTemplate(
}
Invalid = SemaRef.pushCodeSynthesisContext(Inst);
- if (!Invalid) {
-AlreadyInstantiating =
-!Inst.Entity
-? false
-: !SemaRef.InstantiatingSpecializations
- .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
- .second;
+ if (!Invalid)
atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
- }
}
Sema::Insta
[clang] [clang] separate recursive instantiation check from CodeSynthesisContext (PR #162224)
https://github.com/mizvekov closed https://github.com/llvm/llvm-project/pull/162224 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] separate recursive instantiation check from CodeSynthesisContext (PR #162224)
@@ -3554,12 +3543,26 @@ namespace clang {
}
}
-bool
-Sema::InstantiateClass(SourceLocation PointOfInstantiation,
- CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
- const MultiLevelTemplateArgumentList &TemplateArgs,
- TemplateSpecializationKind TSK,
- bool Complain) {
+bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
+CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern,
+const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain) {
+#ifndef NDEBUG
+ RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
+ RecursiveInstGuard::Kind::Template);
+ assert(!AlreadyInstantiating && "should have been caught by caller");
+#endif
+
+ return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
+ TemplateArgs, TSK, Complain);
+}
+
+bool Sema::InstantiateClassImpl(
+SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain) {
h-vetinari wrote:
If the only difference between `Sema::InstantiateClass` and
`Sema::InstantiateClassImpl` is a debug check that gets compiled out, is that
really a strong enough reason to split the function? Or are there other plans
to let these two diverge some more?
https://github.com/llvm/llvm-project/pull/162224
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] separate recursive instantiation check from CodeSynthesisContext (PR #162224)
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 4 "build stage 1". Full details are available at: https://lab.llvm.org/buildbot/#/builders/27/builds/17725 Here is the relevant piece of the build log for the reference ``` Step 4 (build stage 1) failure: 'ninja' (failure) ... [101/294] Building CXX object tools/clang/lib/Frontend/CMakeFiles/obj.clangFrontend.dir/ASTUnit.cpp.o [102/294] Building CXX object tools/clang/lib/Frontend/CMakeFiles/obj.clangFrontend.dir/CompilerInstance.cpp.o [103/294] Building CXX object tools/clang/lib/Serialization/CMakeFiles/obj.clangSerialization.dir/ASTReaderDecl.cpp.o [104/294] Building CXX object tools/clang/lib/Parse/CMakeFiles/obj.clangParse.dir/Parser.cpp.o [105/294] Building CXX object tools/clang/lib/Parse/CMakeFiles/obj.clangParse.dir/ParseStmt.cpp.o [106/294] Building CXX object tools/clang/lib/Parse/CMakeFiles/obj.clangParse.dir/ParsePragma.cpp.o [107/294] Building CXX object tools/llvm-config/CMakeFiles/llvm-config.dir/llvm-config.cpp.o [108/294] Building CXX object tools/clang/lib/Serialization/CMakeFiles/obj.clangSerialization.dir/ASTWriterStmt.cpp.o [109/294] Building CXX object tools/clang/lib/Frontend/CMakeFiles/obj.clangFrontend.dir/InterfaceStubFunctionsConsumer.cpp.o [110/294] Building CXX object tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/SemaExpr.cpp.o FAILED: tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/SemaExpr.cpp.o /usr/bin/c++ -DCLANG_EXPORTS -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GLIBCXX_USE_CXX11_ABI=1 -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/lib/Sema -I/var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/lib/Sema -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 -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-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-dangling-reference -Wno-redundant-move -Wno-pessimizing-move -Wno-array-bounds -Wno-stringop-overread -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 -O3 -DNDEBUG -std=c++17 -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -MD -MT tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/SemaExpr.cpp.o -MF tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/SemaExpr.cpp.o.d -o tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/SemaExpr.cpp.o -c /var/lib/buildbot/workers/suse-gary-m68k-cross/clang-m68k-linux-cross/llvm/clang/lib/Sema/SemaExpr.cpp c++: fatal error: Killed signal terminated program cc1plus compilation terminated. [111/294] Building CXX object tools/clang/lib/Tooling/DependencyScanning/CMakeFiles/obj.clangDependencyScanning.dir/DependencyScanningTool.cpp.o [112/294] Building CXX object tools/clang/lib/Tooling/DependencyScanning/CMakeFiles/obj.clangDependencyScanning.dir/DependencyScanningWorker.cpp.o [113/294] Building CXX object tools/clang/lib/Frontend/Rewrite/CMakeFiles/obj.clangRewriteFrontend.dir/FrontendActions.cpp.o [114/294] Building CXX object tools/clang/lib/StaticAnalyzer/Frontend/CMakeFiles/obj.clangStaticAnalyzerFrontend.dir/ModelInjector.cpp.o [115/294] Building CXX object tools/clang/tools/libclang/CMakeFiles/libclang.dir/CIndexCodeCompletion.cpp.o [116/294] Building CXX object tools/clang/lib/Interpreter/CMakeFiles/obj.clangInterpreter.dir/CodeCompletion.cpp.o [117/294] Building CXX object tools/clang/lib/Interpreter/CMakeFiles/obj.clangInterpreter.dir/IncrementalAction.cpp.o [118/294] Building CXX object tools/clang/lib/Interpreter/CMakeFiles/obj.clangInterpreter.dir/IncrementalParser.cpp.o [119/294] Building CXX object tools/clang/lib/Tooling/DependencyScanning/CMakeFiles/obj.clangDependencyScanning.dir/ModuleDepCollector.cpp.o [120/294] Building CXX object tools/clang/lib/Index/CMakeFiles/obj.clangIndex.dir/IndexingAction.cpp.o [121/294] Building CXX object tools/clang/tools/c-index-test/CMakeFiles/c-index-test.dir/core_main.cpp.o [122/294] Building CXX object tools/clang/lib/Interpreter/CMakeFiles/obj.clangInterpreter.dir/Interpreter.cpp.o [123/294] Building CXX object tools/clang/lib/Interpreter/CMakeFiles/obj.clangInterpreter.dir/InterpreterUtils.cpp.o [124/29
[clang] [NFC][doc] Mark P1857R3 as partial implemented (PR #164095)
@@ -926,7 +926,14 @@ C++20 implementation status https://wg21.link/p1857r3";>P1857R3 -No + + +>Clang 21(Partial) h-vetinari wrote: ```suggestion Clang 21 (Partial) ``` https://github.com/llvm/llvm-project/pull/164095 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] CompoundLiteralExpr for Aggregate types (PR #164172)
llvmbot wrote:
@llvm/pr-subscribers-clangir
Author: Amr Hesham (AmrDeveloper)
Changes
Upstream support the CompoundLiteralExpr for Aggregate types
---
Full diff: https://github.com/llvm/llvm-project/pull/164172.diff
3 Files Affected:
- (modified) clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp (+29-3)
- (modified) clang/lib/CIR/CodeGen/CIRGenValue.h (+2)
- (modified) clang/test/CIR/CodeGen/struct.cpp (+19)
``diff
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
index 901b937e4e3e7..1a4114d009ffe 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
@@ -180,9 +180,35 @@ class AggExprEmitter : public StmtVisitor {
cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter:
VisitStringLiteral");
}
void VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
-cgf.cgm.errorNYI(e->getSourceRange(),
- "AggExprEmitter: VisitCompoundLiteralExpr");
+if (dest.isPotentiallyAliased() &&
+e->getType().isPODType(cgf.getContext())) {
+ cgf.cgm.errorNYI(e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr PODType");
+ return;
+}
+
+AggValueSlot slot =
+ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
+
+// Block-scope compound literals are destroyed at the end of the enclosing
+// scope in C.
+bool destruct =
+!cgf.getLangOpts().CPlusPlus && !slot.isExternallyDestructed();
+if (destruct) {
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr setExternallyDestructed");
+ return;
+}
+
+cgf.emitAggExpr(e->getInitializer(), slot);
+
+if (destruct && e->getType().isDestructedType())
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr destructed type");
}
+
void VisitPredefinedExpr(const PredefinedExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"AggExprEmitter: VisitPredefinedExpr");
@@ -550,7 +576,7 @@ void
AggExprEmitter::emitNullInitializationToLValue(mlir::Location loc,
return;
}
-cgf.cgm.errorNYI("emitStoreThroughBitfieldLValue");
+cgf.emitStoreThroughBitfieldLValue(RValue::get(null), lv);
return;
}
diff --git a/clang/lib/CIR/CodeGen/CIRGenValue.h
b/clang/lib/CIR/CodeGen/CIRGenValue.h
index c05142e9853ba..f83a952d26065 100644
--- a/clang/lib/CIR/CodeGen/CIRGenValue.h
+++ b/clang/lib/CIR/CodeGen/CIRGenValue.h
@@ -390,6 +390,8 @@ class AggValueSlot {
IsZeroed_t isZeroed() const { return IsZeroed_t(zeroedFlag); }
+ IsAliased_t isPotentiallyAliased() const { return IsAliased_t(aliasedFlag); }
+
RValue asRValue() const {
if (isIgnored())
return RValue::getIgnored();
diff --git a/clang/test/CIR/CodeGen/struct.cpp
b/clang/test/CIR/CodeGen/struct.cpp
index 263799f8a5deb..9ec8849602a56 100644
--- a/clang/test/CIR/CodeGen/struct.cpp
+++ b/clang/test/CIR/CodeGen/struct.cpp
@@ -280,3 +280,22 @@ void bin_comma() {
// OGCG: define{{.*}} void @_Z9bin_commav()
// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
+
+void compound_literal_expr() { CompleteS a = (CompleteS){}; }
+
+// CIR: %[[A_ADDR:.*]] = cir.alloca !rec_CompleteS, !cir.ptr,
["a", init]
+// CIR: %[[A_ELEM_0_PTR:.*]] = cir.get_member %[[A_ADDR]][0] {name = "a"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s32i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_0_PTR]] : !s32i,
!cir.ptr
+// CIR: %[[A_ELEM_1_PTR:.*]] = cir.get_member %[[A_ADDR]][1] {name = "b"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s8i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_1_PTR]] : !s8i, !cir.ptr
+
+// LLVM: %[[A_ADDR:.*]] = alloca %struct.CompleteS, i64 1, align 4
+// LLVM: %[[A_ELEM_0_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 0
+// LLVM: store i32 0, ptr %[[A_ELEM_0_PTR]], align 4
+// LLVM: %[[A_ELEM_1_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 1
+// LLVM: store i8 0, ptr %[[A_ELEM_1_PTR]], align 4
+
+// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
+// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
``
https://github.com/llvm/llvm-project/pull/164172
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] CompoundLiteralExpr for Aggregate types (PR #164172)
llvmbot wrote:
@llvm/pr-subscribers-clang
Author: Amr Hesham (AmrDeveloper)
Changes
Upstream support the CompoundLiteralExpr for Aggregate types
---
Full diff: https://github.com/llvm/llvm-project/pull/164172.diff
3 Files Affected:
- (modified) clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp (+29-3)
- (modified) clang/lib/CIR/CodeGen/CIRGenValue.h (+2)
- (modified) clang/test/CIR/CodeGen/struct.cpp (+19)
``diff
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
index 901b937e4e3e7..1a4114d009ffe 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
@@ -180,9 +180,35 @@ class AggExprEmitter : public StmtVisitor {
cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter:
VisitStringLiteral");
}
void VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
-cgf.cgm.errorNYI(e->getSourceRange(),
- "AggExprEmitter: VisitCompoundLiteralExpr");
+if (dest.isPotentiallyAliased() &&
+e->getType().isPODType(cgf.getContext())) {
+ cgf.cgm.errorNYI(e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr PODType");
+ return;
+}
+
+AggValueSlot slot =
+ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
+
+// Block-scope compound literals are destroyed at the end of the enclosing
+// scope in C.
+bool destruct =
+!cgf.getLangOpts().CPlusPlus && !slot.isExternallyDestructed();
+if (destruct) {
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr setExternallyDestructed");
+ return;
+}
+
+cgf.emitAggExpr(e->getInitializer(), slot);
+
+if (destruct && e->getType().isDestructedType())
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr destructed type");
}
+
void VisitPredefinedExpr(const PredefinedExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"AggExprEmitter: VisitPredefinedExpr");
@@ -550,7 +576,7 @@ void
AggExprEmitter::emitNullInitializationToLValue(mlir::Location loc,
return;
}
-cgf.cgm.errorNYI("emitStoreThroughBitfieldLValue");
+cgf.emitStoreThroughBitfieldLValue(RValue::get(null), lv);
return;
}
diff --git a/clang/lib/CIR/CodeGen/CIRGenValue.h
b/clang/lib/CIR/CodeGen/CIRGenValue.h
index c05142e9853ba..f83a952d26065 100644
--- a/clang/lib/CIR/CodeGen/CIRGenValue.h
+++ b/clang/lib/CIR/CodeGen/CIRGenValue.h
@@ -390,6 +390,8 @@ class AggValueSlot {
IsZeroed_t isZeroed() const { return IsZeroed_t(zeroedFlag); }
+ IsAliased_t isPotentiallyAliased() const { return IsAliased_t(aliasedFlag); }
+
RValue asRValue() const {
if (isIgnored())
return RValue::getIgnored();
diff --git a/clang/test/CIR/CodeGen/struct.cpp
b/clang/test/CIR/CodeGen/struct.cpp
index 263799f8a5deb..9ec8849602a56 100644
--- a/clang/test/CIR/CodeGen/struct.cpp
+++ b/clang/test/CIR/CodeGen/struct.cpp
@@ -280,3 +280,22 @@ void bin_comma() {
// OGCG: define{{.*}} void @_Z9bin_commav()
// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
+
+void compound_literal_expr() { CompleteS a = (CompleteS){}; }
+
+// CIR: %[[A_ADDR:.*]] = cir.alloca !rec_CompleteS, !cir.ptr,
["a", init]
+// CIR: %[[A_ELEM_0_PTR:.*]] = cir.get_member %[[A_ADDR]][0] {name = "a"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s32i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_0_PTR]] : !s32i,
!cir.ptr
+// CIR: %[[A_ELEM_1_PTR:.*]] = cir.get_member %[[A_ADDR]][1] {name = "b"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s8i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_1_PTR]] : !s8i, !cir.ptr
+
+// LLVM: %[[A_ADDR:.*]] = alloca %struct.CompleteS, i64 1, align 4
+// LLVM: %[[A_ELEM_0_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 0
+// LLVM: store i32 0, ptr %[[A_ELEM_0_PTR]], align 4
+// LLVM: %[[A_ELEM_1_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 1
+// LLVM: store i8 0, ptr %[[A_ELEM_1_PTR]], align 4
+
+// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
+// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
``
https://github.com/llvm/llvm-project/pull/164172
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] only convert dependency filename to native form when MS-compatible (PR #160903)
https://github.com/ZhongRuoyu updated
https://github.com/llvm/llvm-project/pull/160903
>From 181c4d65060405cdba484c18ae09b3fe1255414d Mon Sep 17 00:00:00 2001
From: Ruoyu Zhong
Date: Fri, 26 Sep 2025 23:17:32 +0800
Subject: [PATCH] [Clang] only convert dependency filename to native form when
MS-compatible
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Currently, llvm::sys::path::native is called unconditionally when
generating dependency filenames. This is correct on Windows, where
backslashes are valid path separators, but can be incorrect on
non-Windows platforms when the Clang invocation is not MS-compatible
(-fno-ms-compatibility), because in that case backslashes in the
filename are converted by llvm::sys::path::native to forward slashes,
while they should be treated as ordinary characters.
This fixes the following inconsistency on non-Windows platforms (notice
how the dependency output always converts the backslash to a forward
slash, assuming it's a path separator, while the actual include
directive treats it as an ordinary character when -fno-ms-compatibility
is set):
$ tree
.
└── foo
├── a
│ └── b.h
└── a\b.h
3 directories, 2 files
$ cat foo/a/b.h
#warning a/b.h
$ cat foo/a\\b.h
#warning a\\b.h
$ echo '#include "foo/a\\b.h"' | clang -c -xc - -fms-compatibility -o
/dev/null
In file included from :1:
./foo/a/b.h:1:2: warning: a/b.h [-W#warnings]
1 | #warning a/b.h
| ^
1 warning generated.
$ echo '#include "foo/a\\b.h"' | clang -xc - -fms-compatibility -M -MG
-.o: foo/a/b.h
$ echo '#include "foo/a\\b.h"' | clang -c -xc - -fno-ms-compatibility -o
/dev/null
In file included from :1:
./foo/a\b.h:1:2: warning: a\\b.h [-W#warnings]
1 | #warning a\\b.h
| ^
1 warning generated.
$ echo '#include "foo/a\\b.h"' | clang -xc - -fno-ms-compatibility -M -MG
-.o: foo/a/b.h
Signed-off-by: Ruoyu Zhong
---
clang/include/clang/Frontend/Utils.h | 4 +++
clang/lib/Frontend/DependencyFile.cpp | 25 +--
.../dependency-gen-posix-ms-compatible.c | 17 +
3 files changed, 39 insertions(+), 7 deletions(-)
create mode 100644 clang/test/Frontend/dependency-gen-posix-ms-compatible.c
diff --git a/clang/include/clang/Frontend/Utils.h
b/clang/include/clang/Frontend/Utils.h
index 49fd920d1ec43..8fe63d7c2141b 100644
--- a/clang/include/clang/Frontend/Utils.h
+++ b/clang/include/clang/Frontend/Utils.h
@@ -118,6 +118,9 @@ class DependencyFileGenerator : public DependencyCollector {
void outputDependencyFile(llvm::raw_ostream &OS);
private:
+ void outputDependencyFilename(llvm::raw_ostream &OS,
+StringRef Filename) const;
+
void outputDependencyFile(DiagnosticsEngine &Diags);
std::string OutputFile;
@@ -128,6 +131,7 @@ class DependencyFileGenerator : public DependencyCollector {
bool SeenMissingHeader;
bool IncludeModuleFiles;
DependencyOutputFormat OutputFormat;
+ bool MSCompatible;
unsigned InputFileIndex;
};
diff --git a/clang/lib/Frontend/DependencyFile.cpp
b/clang/lib/Frontend/DependencyFile.cpp
index 15fa7de35df97..fc5b7949afa22 100644
--- a/clang/lib/Frontend/DependencyFile.cpp
+++ b/clang/lib/Frontend/DependencyFile.cpp
@@ -223,7 +223,7 @@ DependencyFileGenerator::DependencyFileGenerator(
PhonyTarget(Opts.UsePhonyTargets),
AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
SeenMissingHeader(false),
IncludeModuleFiles(Opts.IncludeModuleFiles),
- OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
+ OutputFormat(Opts.OutputFormat), MSCompatible(false), InputFileIndex(0) {
for (const auto &ExtraDep : Opts.ExtraDeps) {
if (addDependency(ExtraDep.first))
++InputFileIndex;
@@ -235,6 +235,8 @@ void
DependencyFileGenerator::attachToPreprocessor(Preprocessor &PP) {
if (AddMissingHeaderDeps)
PP.SetSuppressIncludeNotFoundError(true);
+ MSCompatible = PP.getLangOpts().MicrosoftExt;
+
DependencyCollector::attachToPreprocessor(PP);
}
@@ -312,11 +314,20 @@ void
DependencyFileGenerator::finishedMainFile(DiagnosticsEngine &Diags) {
/// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
///
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
/// for Windows file-naming info.
-static void PrintFilename(raw_ostream &OS, StringRef Filename,
- DependencyOutputFormat OutputFormat) {
- // Convert filename to platform native path
+///
+/// Whether backslashes in the filename are treated as path separators or
+/// ordinary characters depends on whether the Clang invocation is
MS-compatible
+/// (-fms-compatibility). If it is, backslashes are treated as path separators,
+/// and are converted to the native path separator (backslash on Windows,
+/// forward slash on other platforms); if not, backslash
[clang] b2574c9 - [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (#78707)
Author: Hui
Date: 2025-10-19T19:25:00+01:00
New Revision: b2574c9dad487be92605316efd929738a5f6d851
URL:
https://github.com/llvm/llvm-project/commit/b2574c9dad487be92605316efd929738a5f6d851
DIFF:
https://github.com/llvm/llvm-project/commit/b2574c9dad487be92605316efd929738a5f6d851.diff
LOG: [clang] [libc++] fix _Atomic c11 compare exchange does not update expected
results (#78707)
fixes #30023
The issue is that for compare exchange builtin, if the type's size is
not power of 2, it creates a temporary of size power of 2, then emit the
compare exchange operation. And later, the results of the compare
exchange operation has two components: 1. a boolean whether or not the
exchange happens. 2. the old value
we are supposed to write the old value into user's "expected" value.
However, in case the type is not power of 2, what we actually wrote to
is the temporary that was created.
The fix is to pass the "expected" address all the way down so it can
wrote to the correct address
Added:
clang/test/CodeGenCXX/builtin-atomic-compare_exchange.cpp
libcxx/test/std/atomics/atomics.types.generic/cas_non_power_of_2.pass.cpp
Modified:
clang/lib/CodeGen/CGAtomic.cpp
clang/test/CodeGen/c11atomics-ios.c
Removed:
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index d95dab3a19fea..5bf1816fd96a3 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -374,10 +374,9 @@ bool AtomicInfo::emitMemSetZeroIfNecessary() const {
}
static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
- Address Dest, Address Ptr,
- Address Val1, Address Val2,
- uint64_t Size,
- llvm::AtomicOrdering SuccessOrder,
+ Address Dest, Address Ptr, Address Val1,
+ Address Val2, Address ExpectedResult,
+ uint64_t Size, llvm::AtomicOrdering SuccessOrder,
llvm::AtomicOrdering FailureOrder,
llvm::SyncScope::ID Scope) {
// Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
@@ -411,8 +410,30 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
CGF.Builder.SetInsertPoint(StoreExpectedBB);
// Update the memory at Expected with Old's value.
- auto *I = CGF.Builder.CreateStore(Old, Val1);
- CGF.addInstToCurrentSourceAtom(I, Old);
+ llvm::Type *ExpectedType = ExpectedResult.getElementType();
+ const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
+ uint64_t ExpectedSizeInBytes = DL.getTypeStoreSize(ExpectedType);
+
+ if (ExpectedSizeInBytes == Size) {
+// Sizes match: store directly
+auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
+CGF.addInstToCurrentSourceAtom(I, Old);
+ } else {
+// store only the first ExpectedSizeInBytes bytes of Old
+llvm::Type *OldType = Old->getType();
+
+// Allocate temporary storage for Old value
+Address OldTmp =
+CGF.CreateTempAlloca(OldType, Ptr.getAlignment(), "old.tmp");
+
+// Store Old into this temporary
+auto *I = CGF.Builder.CreateStore(Old, OldTmp);
+CGF.addInstToCurrentSourceAtom(I, Old);
+
+// Perform memcpy for first ExpectedSizeInBytes bytes
+CGF.Builder.CreateMemCpy(ExpectedResult, OldTmp, ExpectedSizeInBytes,
+ /*isVolatile=*/false);
+ }
// Finally, branch to the exit point.
CGF.Builder.CreateBr(ContinueBB);
@@ -425,13 +446,11 @@ static void emitAtomicCmpXchg(CodeGenFunction &CGF,
AtomicExpr *E, bool IsWeak,
/// Given an ordering required on success, emit all possible cmpxchg
/// instructions to cope with the provided (but possibly only dynamically
known)
/// FailureOrder.
-static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
-bool IsWeak, Address Dest, Address Ptr,
-Address Val1, Address Val2,
-llvm::Value *FailureOrderVal,
-uint64_t Size,
-llvm::AtomicOrdering SuccessOrder,
-llvm::SyncScope::ID Scope) {
+static void emitAtomicCmpXchgFailureSet(
+CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak, Address Dest, Address
Ptr,
+Address Val1, Address Val2, Address ExpectedResult,
+llvm::Value *FailureOrderVal, uint64_t Size,
+llvm::AtomicOrdering SuccessOrder, llvm::SyncScope::ID Scope) {
llvm::AtomicOrdering FailureOrder;
if (llvm::ConstantInt *FO = dyn_cast(FailureOrderVal)) {
auto FOS = FO->getSExtValue();
@@ -458,8 +477,8 @@ static void emitAtomicCmpXchgFailureSet(CodeGenFunction
&CGF, AtomicExpr *E,
// succ
[clang] [CIR] CompoundLiteralExpr for Aggregate types (PR #164172)
https://github.com/AmrDeveloper created
https://github.com/llvm/llvm-project/pull/164172
Upstream support the CompoundLiteralExpr for Aggregate types
>From 4509f800a08d11eb5463da05b73962715978e685 Mon Sep 17 00:00:00 2001
From: Amr Hesham
Date: Sun, 19 Oct 2025 20:26:54 +0200
Subject: [PATCH] [CIR] CompoundLiteralExpr for Aggregate types
---
clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp | 32 +--
clang/lib/CIR/CodeGen/CIRGenValue.h | 2 ++
clang/test/CIR/CodeGen/struct.cpp | 19 +++
3 files changed, 50 insertions(+), 3 deletions(-)
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
index 901b937e4e3e7..1a4114d009ffe 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
@@ -180,9 +180,35 @@ class AggExprEmitter : public StmtVisitor {
cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter:
VisitStringLiteral");
}
void VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
-cgf.cgm.errorNYI(e->getSourceRange(),
- "AggExprEmitter: VisitCompoundLiteralExpr");
+if (dest.isPotentiallyAliased() &&
+e->getType().isPODType(cgf.getContext())) {
+ cgf.cgm.errorNYI(e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr PODType");
+ return;
+}
+
+AggValueSlot slot =
+ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
+
+// Block-scope compound literals are destroyed at the end of the enclosing
+// scope in C.
+bool destruct =
+!cgf.getLangOpts().CPlusPlus && !slot.isExternallyDestructed();
+if (destruct) {
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr setExternallyDestructed");
+ return;
+}
+
+cgf.emitAggExpr(e->getInitializer(), slot);
+
+if (destruct && e->getType().isDestructedType())
+ cgf.cgm.errorNYI(
+ e->getSourceRange(),
+ "AggExprEmitter: VisitCompoundLiteralExpr destructed type");
}
+
void VisitPredefinedExpr(const PredefinedExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"AggExprEmitter: VisitPredefinedExpr");
@@ -550,7 +576,7 @@ void
AggExprEmitter::emitNullInitializationToLValue(mlir::Location loc,
return;
}
-cgf.cgm.errorNYI("emitStoreThroughBitfieldLValue");
+cgf.emitStoreThroughBitfieldLValue(RValue::get(null), lv);
return;
}
diff --git a/clang/lib/CIR/CodeGen/CIRGenValue.h
b/clang/lib/CIR/CodeGen/CIRGenValue.h
index c05142e9853ba..f83a952d26065 100644
--- a/clang/lib/CIR/CodeGen/CIRGenValue.h
+++ b/clang/lib/CIR/CodeGen/CIRGenValue.h
@@ -390,6 +390,8 @@ class AggValueSlot {
IsZeroed_t isZeroed() const { return IsZeroed_t(zeroedFlag); }
+ IsAliased_t isPotentiallyAliased() const { return IsAliased_t(aliasedFlag); }
+
RValue asRValue() const {
if (isIgnored())
return RValue::getIgnored();
diff --git a/clang/test/CIR/CodeGen/struct.cpp
b/clang/test/CIR/CodeGen/struct.cpp
index 263799f8a5deb..9ec8849602a56 100644
--- a/clang/test/CIR/CodeGen/struct.cpp
+++ b/clang/test/CIR/CodeGen/struct.cpp
@@ -280,3 +280,22 @@ void bin_comma() {
// OGCG: define{{.*}} void @_Z9bin_commav()
// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
+
+void compound_literal_expr() { CompleteS a = (CompleteS){}; }
+
+// CIR: %[[A_ADDR:.*]] = cir.alloca !rec_CompleteS, !cir.ptr,
["a", init]
+// CIR: %[[A_ELEM_0_PTR:.*]] = cir.get_member %[[A_ADDR]][0] {name = "a"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s32i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_0_PTR]] : !s32i,
!cir.ptr
+// CIR: %[[A_ELEM_1_PTR:.*]] = cir.get_member %[[A_ADDR]][1] {name = "b"} :
!cir.ptr -> !cir.ptr
+// CIR: %[[CONST_0:.*]] = cir.const #cir.int<0> : !s8i
+// CIR: cir.store{{.*}} %[[CONST_0]], %[[A_ELEM_1_PTR]] : !s8i, !cir.ptr
+
+// LLVM: %[[A_ADDR:.*]] = alloca %struct.CompleteS, i64 1, align 4
+// LLVM: %[[A_ELEM_0_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 0
+// LLVM: store i32 0, ptr %[[A_ELEM_0_PTR]], align 4
+// LLVM: %[[A_ELEM_1_PTR:.*]] = getelementptr %struct.CompleteS, ptr
%[[A_ADDR]], i32 0, i32 1
+// LLVM: store i8 0, ptr %[[A_ELEM_1_PTR]], align 4
+
+// OGCG: %[[A_ADDR:.*]] = alloca %struct.CompleteS, align 4
+// OGCG: call void @llvm.memset.p0.i64(ptr align 4 %[[A_ADDR]], i8 0, i64 8,
i1 false)
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxx] [clang] [libc++] fix _Atomic c11 compare exchange does not update expected results (PR #78707)
https://github.com/huixie90 closed https://github.com/llvm/llvm-project/pull/78707 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [llvm] [ADT] Prepare for deprecation of StringSwitch cases with 4+ args. NFC. (PR #164173)
https://github.com/kuhar created
https://github.com/llvm/llvm-project/pull/164173
Update `.Cases` and `.CasesLower` with 4+ args to use the `initializer_list`
overload. The deprecation of these functions will come in a separate PR.
For more context, see: https://github.com/llvm/llvm-project/pull/163405.
>From b06d53db357a5620abed42dcb79e1d2ada19178c Mon Sep 17 00:00:00 2001
From: Jakub Kuderski
Date: Sun, 19 Oct 2025 14:30:03 -0400
Subject: [PATCH] [ADT] Prepare for deprecation of StringSwitch cases with 4+
args. NFC.
Update `.Cases` and `.CasesLower` with 4+ args to use the
`initializer_list` overload. The deprecation of these functions will
come in a separate PR.
For more context, see: https://github.com/llvm/llvm-project/pull/163405.
---
clang/lib/Basic/Targets/Mips.cpp | 10
clang/lib/Driver/ToolChains/Arch/Mips.cpp | 6 ++---
clang/lib/Driver/ToolChains/Darwin.cpp| 14 +--
clang/lib/Frontend/FrontendAction.cpp | 2 +-
clang/lib/Lex/PPLexerChange.cpp | 2 +-
clang/lib/Sema/SemaChecking.cpp | 12 +-
clang/lib/Sema/SemaExpr.cpp | 2 +-
clang/lib/Sema/SemaInit.cpp | 11 +
clang/lib/Sema/SemaStmtAttr.cpp | 2 +-
.../utils/TableGen/ClangOptionDocEmitter.cpp | 23 ++-
lld/ELF/ScriptParser.cpp | 10
llvm/include/llvm/ADT/StringSwitch.h | 2 ++
llvm/lib/MC/MCParser/MasmParser.cpp | 2 +-
.../Target/RISCV/MCA/RISCVCustomBehaviour.cpp | 2 +-
llvm/lib/TargetParser/ARMTargetParser.cpp | 8 +++
llvm/unittests/ADT/StringSwitchTest.cpp | 8 +++
16 files changed, 60 insertions(+), 56 deletions(-)
diff --git a/clang/lib/Basic/Targets/Mips.cpp b/clang/lib/Basic/Targets/Mips.cpp
index de6ccff64f4eb..a999d1410d254 100644
--- a/clang/lib/Basic/Targets/Mips.cpp
+++ b/clang/lib/Basic/Targets/Mips.cpp
@@ -68,11 +68,11 @@ void MipsTargetInfo::fillValidCPUList(
unsigned MipsTargetInfo::getISARev() const {
return llvm::StringSwitch(getCPU())
- .Cases("mips32", "mips64", 1)
- .Cases("mips32r2", "mips64r2", "octeon", "octeon+", 2)
- .Cases("mips32r3", "mips64r3", 3)
- .Cases("mips32r5", "mips64r5", "p5600", 5)
- .Cases("mips32r6", "mips64r6", "i6400", "i6500", 6)
+ .Cases({"mips32", "mips64"}, 1)
+ .Cases({"mips32r2", "mips64r2", "octeon", "octeon+"}, 2)
+ .Cases({"mips32r3", "mips64r3"}, 3)
+ .Cases({"mips32r5", "mips64r5", "p5600"}, 5)
+ .Cases({"mips32r6", "mips64r6", "i6400", "i6500"}, 6)
.Default(0);
}
diff --git a/clang/lib/Driver/ToolChains/Arch/Mips.cpp
b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
index bac8681921877..227c6a0d3d202 100644
--- a/clang/lib/Driver/ToolChains/Arch/Mips.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
@@ -482,9 +482,9 @@ bool mips::isFPXXDefault(const llvm::Triple &Triple,
StringRef CPUName,
return false;
return llvm::StringSwitch(CPUName)
- .Cases("mips2", "mips3", "mips4", "mips5", true)
- .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
- .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
+ .Cases({"mips2", "mips3", "mips4", "mips5"}, true)
+ .Cases({"mips32", "mips32r2", "mips32r3", "mips32r5"}, true)
+ .Cases({"mips64", "mips64r2", "mips64r3", "mips64r5"}, true)
.Default(false);
}
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp
b/clang/lib/Driver/ToolChains/Darwin.cpp
index d2356ebdfa86c..cc5bcd1816c52 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -51,15 +51,15 @@ llvm::Triple::ArchType
darwin::getArchTypeForMachOArchName(StringRef Str) {
// translation.
return llvm::StringSwitch(Str)
- .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
- .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
+ .Cases({"i386", "i486", "i486SX", "i586", "i686"}, llvm::Triple::x86)
+ .Cases({"pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4"},
llvm::Triple::x86)
- .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
+ .Cases({"x86_64", "x86_64h"}, llvm::Triple::x86_64)
// This is derived from the driver.
- .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
- .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
- .Cases("armv7s", "xscale", llvm::Triple::arm)
- .Cases("arm64", "arm64e", llvm::Triple::aarch64)
+ .Cases({"arm", "armv4t", "armv5", "armv6", "armv6m"}, llvm::Triple::arm)
+ .Cases({"armv7", "armv7em", "armv7k", "armv7m"}, llvm::Triple::arm)
+ .Cases({"armv7s", "xscale"}, llvm::Triple::arm)
+ .Cases({"arm64", "arm64e"}, llvm::Triple::aarch64)
.Case("arm64_32", llvm::Triple::aarch64_32)
.Case("r600", llvm::Triple::r600)
.Case("amdgcn", llvm::Triple::amdgcn)
diff --git a/clang/lib/F
[clang] f072036 - [clang-format][NFC] Annotate attribute squares more effectively (#164052)
Author: owenca
Date: 2025-10-19T11:38:08-07:00
New Revision: f0720363d39746c906647a23147f17185f5c1433
URL:
https://github.com/llvm/llvm-project/commit/f0720363d39746c906647a23147f17185f5c1433
DIFF:
https://github.com/llvm/llvm-project/commit/f0720363d39746c906647a23147f17185f5c1433.diff
LOG: [clang-format][NFC] Annotate attribute squares more effectively (#164052)
Annotate left/right attribute squares distinctively and only annotate
the outer pair of C++ attribute squares.
Added:
Modified:
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/DefinitionBlockSeparator.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp
Removed:
diff --git a/clang/lib/Format/ContinuationIndenter.cpp
b/clang/lib/Format/ContinuationIndenter.cpp
index 26a95421775f3..37c10c66503bb 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -433,7 +433,7 @@ bool ContinuationIndenter::mustBreak(const LineState
&State) {
}
if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeLSquare) && Style.isCpp() &&
// FIXME: This is a temporary workaround for the case where
clang-format
// sets BreakBeforeParameter to avoid bin packing and this creates a
// completely unnecessary line break after a template type that isn't
@@ -1374,7 +1374,8 @@ unsigned ContinuationIndenter::getNewLineColumn(const
LineState &State) {
}
if (Current.is(TT_LambdaArrow) &&
Previous.isOneOf(tok::kw_noexcept, tok::kw_mutable, tok::kw_constexpr,
- tok::kw_consteval, tok::kw_static, TT_AttributeSquare))
{
+ tok::kw_consteval, tok::kw_static,
+ TT_AttributeRSquare)) {
return ContinuationIndent;
}
if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
@@ -1499,9 +1500,10 @@ unsigned ContinuationIndenter::getNewLineColumn(const
LineState &State) {
Current.isNot(tok::l_paren) &&
!Current.endsSequence(TT_StartOfName, TT_AttributeMacro,
TT_PointerOrReference)) ||
-PreviousNonComment->isOneOf(
-TT_AttributeRParen, TT_AttributeSquare,
TT_FunctionAnnotationRParen,
-TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
+PreviousNonComment->isOneOf(TT_AttributeRParen, TT_AttributeRSquare,
+TT_FunctionAnnotationRParen,
+TT_JavaAnnotation,
+TT_LeadingJavaAnnotation))) ||
(!Style.IndentWrappedFunctionNames &&
NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
{
return std::max(CurrentState.LastSpace, CurrentState.Indent);
diff --git a/clang/lib/Format/DefinitionBlockSeparator.cpp
b/clang/lib/Format/DefinitionBlockSeparator.cpp
index 3f4ce5fa3a428..855f2efad1e53 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -169,7 +169,7 @@ void DefinitionBlockSeparator::separateBlocks(
}
}
- if (Style.isCSharp() && OperateLine->First->is(TT_AttributeSquare))
+ if (Style.isCSharp() && OperateLine->First->is(TT_AttributeLSquare))
return true;
return false;
};
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f015d27bed6af..6f3d24aefc1ca 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -30,9 +30,10 @@ namespace format {
TYPE(ArraySubscriptLSquare)
\
TYPE(AttributeColon)
\
TYPE(AttributeLParen)
\
+ TYPE(AttributeLSquare)
\
TYPE(AttributeMacro)
\
TYPE(AttributeRParen)
\
- TYPE(AttributeSquare)
\
+ TYPE(AttributeRSquare)
\
TYPE(BinaryOperator)
\
TYPE(BitFieldColon)
\
TYPE(BlockComment)
\
diff --git a/clang/lib/Format/TokenAnnotator.cpp
b/clang/lib/Format/TokenAnnotator.cpp
index 778d2ca938bdd..c97a9e81eb59e 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/Toke
[clang] [lld] [llvm] [ADT] Prepare for deprecation of StringSwitch cases with 4+ args. NFC. (PR #164173)
https://github.com/kuhar updated
https://github.com/llvm/llvm-project/pull/164173
>From b06d53db357a5620abed42dcb79e1d2ada19178c Mon Sep 17 00:00:00 2001
From: Jakub Kuderski
Date: Sun, 19 Oct 2025 14:30:03 -0400
Subject: [PATCH 1/2] [ADT] Prepare for deprecation of StringSwitch cases with
4+ args. NFC.
Update `.Cases` and `.CasesLower` with 4+ args to use the
`initializer_list` overload. The deprecation of these functions will
come in a separate PR.
For more context, see: https://github.com/llvm/llvm-project/pull/163405.
---
clang/lib/Basic/Targets/Mips.cpp | 10
clang/lib/Driver/ToolChains/Arch/Mips.cpp | 6 ++---
clang/lib/Driver/ToolChains/Darwin.cpp| 14 +--
clang/lib/Frontend/FrontendAction.cpp | 2 +-
clang/lib/Lex/PPLexerChange.cpp | 2 +-
clang/lib/Sema/SemaChecking.cpp | 12 +-
clang/lib/Sema/SemaExpr.cpp | 2 +-
clang/lib/Sema/SemaInit.cpp | 11 +
clang/lib/Sema/SemaStmtAttr.cpp | 2 +-
.../utils/TableGen/ClangOptionDocEmitter.cpp | 23 ++-
lld/ELF/ScriptParser.cpp | 10
llvm/include/llvm/ADT/StringSwitch.h | 2 ++
llvm/lib/MC/MCParser/MasmParser.cpp | 2 +-
.../Target/RISCV/MCA/RISCVCustomBehaviour.cpp | 2 +-
llvm/lib/TargetParser/ARMTargetParser.cpp | 8 +++
llvm/unittests/ADT/StringSwitchTest.cpp | 8 +++
16 files changed, 60 insertions(+), 56 deletions(-)
diff --git a/clang/lib/Basic/Targets/Mips.cpp b/clang/lib/Basic/Targets/Mips.cpp
index de6ccff64f4eb..a999d1410d254 100644
--- a/clang/lib/Basic/Targets/Mips.cpp
+++ b/clang/lib/Basic/Targets/Mips.cpp
@@ -68,11 +68,11 @@ void MipsTargetInfo::fillValidCPUList(
unsigned MipsTargetInfo::getISARev() const {
return llvm::StringSwitch(getCPU())
- .Cases("mips32", "mips64", 1)
- .Cases("mips32r2", "mips64r2", "octeon", "octeon+", 2)
- .Cases("mips32r3", "mips64r3", 3)
- .Cases("mips32r5", "mips64r5", "p5600", 5)
- .Cases("mips32r6", "mips64r6", "i6400", "i6500", 6)
+ .Cases({"mips32", "mips64"}, 1)
+ .Cases({"mips32r2", "mips64r2", "octeon", "octeon+"}, 2)
+ .Cases({"mips32r3", "mips64r3"}, 3)
+ .Cases({"mips32r5", "mips64r5", "p5600"}, 5)
+ .Cases({"mips32r6", "mips64r6", "i6400", "i6500"}, 6)
.Default(0);
}
diff --git a/clang/lib/Driver/ToolChains/Arch/Mips.cpp
b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
index bac8681921877..227c6a0d3d202 100644
--- a/clang/lib/Driver/ToolChains/Arch/Mips.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
@@ -482,9 +482,9 @@ bool mips::isFPXXDefault(const llvm::Triple &Triple,
StringRef CPUName,
return false;
return llvm::StringSwitch(CPUName)
- .Cases("mips2", "mips3", "mips4", "mips5", true)
- .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
- .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
+ .Cases({"mips2", "mips3", "mips4", "mips5"}, true)
+ .Cases({"mips32", "mips32r2", "mips32r3", "mips32r5"}, true)
+ .Cases({"mips64", "mips64r2", "mips64r3", "mips64r5"}, true)
.Default(false);
}
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp
b/clang/lib/Driver/ToolChains/Darwin.cpp
index d2356ebdfa86c..cc5bcd1816c52 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -51,15 +51,15 @@ llvm::Triple::ArchType
darwin::getArchTypeForMachOArchName(StringRef Str) {
// translation.
return llvm::StringSwitch(Str)
- .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
- .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
+ .Cases({"i386", "i486", "i486SX", "i586", "i686"}, llvm::Triple::x86)
+ .Cases({"pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4"},
llvm::Triple::x86)
- .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
+ .Cases({"x86_64", "x86_64h"}, llvm::Triple::x86_64)
// This is derived from the driver.
- .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
- .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
- .Cases("armv7s", "xscale", llvm::Triple::arm)
- .Cases("arm64", "arm64e", llvm::Triple::aarch64)
+ .Cases({"arm", "armv4t", "armv5", "armv6", "armv6m"}, llvm::Triple::arm)
+ .Cases({"armv7", "armv7em", "armv7k", "armv7m"}, llvm::Triple::arm)
+ .Cases({"armv7s", "xscale"}, llvm::Triple::arm)
+ .Cases({"arm64", "arm64e"}, llvm::Triple::aarch64)
.Case("arm64_32", llvm::Triple::aarch64_32)
.Case("r600", llvm::Triple::r600)
.Case("amdgcn", llvm::Triple::amdgcn)
diff --git a/clang/lib/Frontend/FrontendAction.cpp
b/clang/lib/Frontend/FrontendAction.cpp
index 1b63c40a6efd7..0daa20a87dd7d 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -629,7 +629,7 @@ stat
[clang] [clang-format][NFC] Annotate attribute squares more effectively (PR #164052)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/164052 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] Draft, do not review (PR #164156)
https://github.com/localspook updated
https://github.com/llvm/llvm-project/pull/164156
>From 5a22a1db87a1d45ef95e33944a87a101769fe8e2 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:03 -0700
Subject: [PATCH 1/5] [clang][Sema] Attempt to parse delayed templates at the
end of the TU
---
clang/lib/Sema/Sema.cpp | 11 +++
1 file changed, 11 insertions(+)
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 39fa25f66f3b7..8e0ad9325e2af 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1251,6 +1251,17 @@ void Sema::ActOnEndOfTranslationUnit() {
if (LateTemplateParserCleanup)
LateTemplateParserCleanup(OpaqueParser);
+if (LangOpts.DelayedTemplateParsing) {
+ // Try to parse any templates that have been delayed and never
+ // instantiated so that their bodies are available for static
+ // analysis tools to analyze.
+ Diags.setSuppressAllDiagnostics(true);
+ for (auto &[Decl, Template] : LateParsedTemplateMap)
+if (Decl->isLateTemplateParsed())
+ LateTemplateParser(OpaqueParser, *Template);
+ Diags.setSuppressAllDiagnostics(false);
+}
+
CheckDelayedMemberExceptionSpecs();
} else {
// If we are building a TU prefix for serialization, it is safe to transfer
>From 29502017417e78599fbb92526e166a5f5457b583 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:26 -0700
Subject: [PATCH 2/5] Fix clang-tidy tests that break
---
.../cppcoreguidelines/pro-type-member-init-delayed.cpp | 9 -
.../checkers/modernize/use-equals-default-delayed.cpp| 9 -
2 files changed, 18 deletions(-)
delete mode 100644
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
index d3436ba6c1211..93bf4993f7b8b 100644
---
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
+++
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
@@ -21,12 +21,3 @@ struct PositiveFieldAfterConstructor {
};
// Explicit instantiation.
template class PositiveFieldAfterConstructor;
-
-// This declaration isn't used and won't be parsed 'delayed-template-parsing'.
-// The body of the declaration is 'null' and may cause crash if not handled
-// properly by checkers.
-template
-struct UnusedDelayedConstructor {
- UnusedDelayedConstructor() {}
- int F;
-};
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
deleted file mode 100644
index f39efd8452f79..0
---
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-// RUN: clang-tidy %s -checks=-*,modernize-use-equals-default -- -std=c++11
-fdelayed-template-parsing -fexceptions | count 0
-// Note: this test expects no diagnostics, but FileCheck cannot handle that,
-// hence the use of | count 0.
-// FIXME: Make the test work in all language modes.
-
-template
-struct S {
- S& operator=(const S&) { return *this; }
-};
>From 9e2f12d65baf460dcb9850fc171bcf5091c363b7 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 02:36:34 -0700
Subject: [PATCH 3/5] Migrate clang-tidy tests away from
`-fno-delayed-template-parsing`
---
.../clang-tidy/checkers/bugprone/branch-clone.cpp | 2 +-
.../bugprone/crtp-constructor-accessibility.cpp| 2 +-
.../clang-tidy/checkers/bugprone/infinite-loop.cpp | 2 +-
.../bugprone/move-forwarding-reference.cpp | 2 +-
.../bugprone/return-const-ref-from-parameter.cpp | 2 +-
.../checkers/bugprone/sizeof-expression.cpp| 3 +--
.../bugprone/string-integer-assignment.cpp | 2 +-
.../bugprone/switch-missing-default-case.cpp | 2 +-
.../bugprone/unhandled-self-assignment.cpp | 2 +-
.../clang-tidy/checkers/bugprone/unused-raii.cpp | 2 +-
.../checkers/bugprone/use-after-move.cpp | 4 ++--
.../checkers/cppcoreguidelines/init-variables.cpp | 2 +-
.../missing-std-forward-custom-function.cpp| 2 +-
.../cppcoreguidelines/missing-std-forward.cpp | 2 +-
.../cppcoreguidelines/no-suspend-with-lock.cpp | 2 +-
.../pro-type-member-init-cxx20.cpp | 2 +-
.../pro-type-member-init-cxx98.cpp | 2 +-
.../pro-type-member-init-delayed.cpp | 2 +-
.../cppcoreguidelines/pro-type-member-init.cpp | 2 +-
...e-reference-param-not-moved-custom-function.cpp | 2 +-
.../rvalue-reference-param-not-moved.cpp | 10 +-
.../prefer-static-over-anonymous-namespace.cpp | 6 +++---
.../misc/const-correctness-
[clang] [clang-tools-extra] Draft, do not review (PR #164156)
https://github.com/localspook updated
https://github.com/llvm/llvm-project/pull/164156
>From 5a22a1db87a1d45ef95e33944a87a101769fe8e2 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:03 -0700
Subject: [PATCH 1/5] [clang][Sema] Attempt to parse delayed templates at the
end of the TU
---
clang/lib/Sema/Sema.cpp | 11 +++
1 file changed, 11 insertions(+)
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 39fa25f66f3b7..8e0ad9325e2af 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1251,6 +1251,17 @@ void Sema::ActOnEndOfTranslationUnit() {
if (LateTemplateParserCleanup)
LateTemplateParserCleanup(OpaqueParser);
+if (LangOpts.DelayedTemplateParsing) {
+ // Try to parse any templates that have been delayed and never
+ // instantiated so that their bodies are available for static
+ // analysis tools to analyze.
+ Diags.setSuppressAllDiagnostics(true);
+ for (auto &[Decl, Template] : LateParsedTemplateMap)
+if (Decl->isLateTemplateParsed())
+ LateTemplateParser(OpaqueParser, *Template);
+ Diags.setSuppressAllDiagnostics(false);
+}
+
CheckDelayedMemberExceptionSpecs();
} else {
// If we are building a TU prefix for serialization, it is safe to transfer
>From 29502017417e78599fbb92526e166a5f5457b583 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 00:46:26 -0700
Subject: [PATCH 2/5] Fix clang-tidy tests that break
---
.../cppcoreguidelines/pro-type-member-init-delayed.cpp | 9 -
.../checkers/modernize/use-equals-default-delayed.cpp| 9 -
2 files changed, 18 deletions(-)
delete mode 100644
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
index d3436ba6c1211..93bf4993f7b8b 100644
---
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
+++
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init-delayed.cpp
@@ -21,12 +21,3 @@ struct PositiveFieldAfterConstructor {
};
// Explicit instantiation.
template class PositiveFieldAfterConstructor;
-
-// This declaration isn't used and won't be parsed 'delayed-template-parsing'.
-// The body of the declaration is 'null' and may cause crash if not handled
-// properly by checkers.
-template
-struct UnusedDelayedConstructor {
- UnusedDelayedConstructor() {}
- int F;
-};
diff --git
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
deleted file mode 100644
index f39efd8452f79..0
---
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-delayed.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-// RUN: clang-tidy %s -checks=-*,modernize-use-equals-default -- -std=c++11
-fdelayed-template-parsing -fexceptions | count 0
-// Note: this test expects no diagnostics, but FileCheck cannot handle that,
-// hence the use of | count 0.
-// FIXME: Make the test work in all language modes.
-
-template
-struct S {
- S& operator=(const S&) { return *this; }
-};
>From 9e2f12d65baf460dcb9850fc171bcf5091c363b7 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin
Date: Sun, 19 Oct 2025 02:36:34 -0700
Subject: [PATCH 3/5] Migrate clang-tidy tests away from
`-fno-delayed-template-parsing`
---
.../clang-tidy/checkers/bugprone/branch-clone.cpp | 2 +-
.../bugprone/crtp-constructor-accessibility.cpp| 2 +-
.../clang-tidy/checkers/bugprone/infinite-loop.cpp | 2 +-
.../bugprone/move-forwarding-reference.cpp | 2 +-
.../bugprone/return-const-ref-from-parameter.cpp | 2 +-
.../checkers/bugprone/sizeof-expression.cpp| 3 +--
.../bugprone/string-integer-assignment.cpp | 2 +-
.../bugprone/switch-missing-default-case.cpp | 2 +-
.../bugprone/unhandled-self-assignment.cpp | 2 +-
.../clang-tidy/checkers/bugprone/unused-raii.cpp | 2 +-
.../checkers/bugprone/use-after-move.cpp | 4 ++--
.../checkers/cppcoreguidelines/init-variables.cpp | 2 +-
.../missing-std-forward-custom-function.cpp| 2 +-
.../cppcoreguidelines/missing-std-forward.cpp | 2 +-
.../cppcoreguidelines/no-suspend-with-lock.cpp | 2 +-
.../pro-type-member-init-cxx20.cpp | 2 +-
.../pro-type-member-init-cxx98.cpp | 2 +-
.../pro-type-member-init-delayed.cpp | 2 +-
.../cppcoreguidelines/pro-type-member-init.cpp | 2 +-
...e-reference-param-not-moved-custom-function.cpp | 2 +-
.../rvalue-reference-param-not-moved.cpp | 10 +-
.../prefer-static-over-anonymous-namespace.cpp | 6 +++---
.../misc/const-correctness-
[clang] [clang-tools-extra] Draft for CI feedback, do not review (PR #164156)
https://github.com/localspook edited https://github.com/llvm/llvm-project/pull/164156 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 3/N (PR #164085)
https://github.com/vbvictor updated
https://github.com/llvm/llvm-project/pull/164085
>From 64d7d69ca3bd9d78dd0b2c3522919dbe4d13e3ab Mon Sep 17 00:00:00 2001
From: Victor Baranov
Date: Sat, 18 Oct 2025 16:44:01 +0300
Subject: [PATCH 1/2] [clang-tidy][NFC] Fix
llvm-prefer-static-over-anonymous-namespace warnings 3/N
---
.../clang-tidy/android/CloexecCheck.cpp | 12 +++--
.../clang-tidy/android/CloexecCheck.h | 4 +--
.../bugprone/SignalHandlerCheck.cpp | 19 +++--
.../misc/RedundantExpressionCheck.cpp | 6 +++--
.../misc/UniqueptrResetReleaseCheck.cpp | 9 +++
.../clang-tidy/modernize/UseNullptrCheck.cpp | 20 +-
.../performance/FasterStringFindCheck.cpp | 7 ++---
.../InefficientVectorOperationCheck.cpp | 6 ++---
.../readability/DuplicateIncludeCheck.cpp | 4 +--
...onsistentDeclarationParameterNameCheck.cpp | 27 ++-
.../readability/RedundantSmartptrGetCheck.cpp | 17 ++--
11 files changed, 66 insertions(+), 65 deletions(-)
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
index cd83423adae05..48c54c0ae02c3 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
@@ -16,12 +16,13 @@ using namespace clang::ast_matchers;
namespace clang::tidy::android {
-namespace {
// Helper function to form the correct string mode for Type3.
// Build the replace text. If it's string constant, add directly in the
// end of the string. Else, add .
-std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM,
- const LangOptions &LangOpts, char Mode) {
+static std::string buildFixMsgForStringFlag(const Expr *Arg,
+const SourceManager &SM,
+const LangOptions &LangOpts,
+char Mode) {
if (Arg->getBeginLoc().isMacroID())
return (Lexer::getSourceText(
CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
@@ -32,11 +33,6 @@ std::string buildFixMsgForStringFlag(const Expr *Arg, const
SourceManager &SM,
StringRef SR = cast(Arg->IgnoreParenCasts())->getString();
return ("\"" + SR + Twine(Mode) + "\"").str();
}
-} // namespace
-
-const char *CloexecCheck::FuncDeclBindingStr = "funcDecl";
-
-const char *CloexecCheck::FuncBindingStr = "func";
void CloexecCheck::registerMatchersImpl(
MatchFinder *Finder, internal::Matcher Function) {
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
index 79f7ab3354d8d..b2b59f5be1b9a 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
@@ -89,10 +89,10 @@ class CloexecCheck : public ClangTidyCheck {
int N) const;
/// Binding name of the FuncDecl of a function call.
- static const char *FuncDeclBindingStr;
+ static constexpr char FuncDeclBindingStr[] = "funcDecl";
/// Binding name of the function call expression.
- static const char *FuncBindingStr;
+ static constexpr char FuncBindingStr[] = "func";
};
} // namespace clang::tidy::android
diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
index 86af5cbd94374..c262b1c05b047 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
@@ -245,12 +245,10 @@ struct OptionEnumMapping<
namespace bugprone {
-namespace {
-
/// Returns if a function is declared inside a system header.
/// These functions are considered to be "standard" (system-provided) library
/// functions.
-bool isStandardFunction(const FunctionDecl *FD) {
+static bool isStandardFunction(const FunctionDecl *FD) {
// Find a possible redeclaration in system header.
// FIXME: Looking at the canonical declaration is not the most exact way
// to do this.
@@ -284,7 +282,7 @@ bool isStandardFunction(const FunctionDecl *FD) {
/// Check if a statement is "C++-only".
/// This includes all statements that have a class name with "CXX" prefix
/// and every other statement that is declared in file ExprCXX.h.
-bool isCXXOnlyStmt(const Stmt *S) {
+static bool isCXXOnlyStmt(const Stmt *S) {
StringRef Name = S->getStmtClassName();
if (Name.starts_with("CXX"))
return true;
@@ -304,7 +302,8 @@ bool isCXXOnlyStmt(const Stmt *S) {
/// called from \p Caller, get a \c CallExpr of the corresponding function
call.
/// It is unspecified which call is found if multiple calls exist, but the
order
/// should be deterministic (depend only on the AST).
-Expr *findCallExpr(const CallGraphNode *Caller, const CallGraphNode *Callee) {
+static Expr *findCa
[clang-tools-extra] cb79d8f - [clang-tidy][NFC] Fix miscellaneous clang-tidy warnings over codebase (#164096)
Author: Baranov Victor
Date: 2025-10-19T14:19:06+03:00
New Revision: cb79d8f77c12dedbbd32cf5fe94f9651582795d3
URL:
https://github.com/llvm/llvm-project/commit/cb79d8f77c12dedbbd32cf5fe94f9651582795d3
DIFF:
https://github.com/llvm/llvm-project/commit/cb79d8f77c12dedbbd32cf5fe94f9651582795d3.diff
LOG: [clang-tidy][NFC] Fix miscellaneous clang-tidy warnings over codebase
(#164096)
Co-authored-by: Victor Chernyakin
Added:
Modified:
clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
clang-tools-extra/clang-tidy/llvm/UseNewMLIROpBuilderCheck.cpp
clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp
Removed:
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index b752a9beb0e34..21455db7c7e7b 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -154,6 +154,7 @@ template <> struct
ScalarEnumerationTraits {
}
};
template <> struct SequenceElementTraits {
+ // NOLINTNEXTLINE(readability-identifier-naming) Defined by YAMLTraits.h
static const bool flow = false;
};
template <> struct MappingTraits {
@@ -165,6 +166,7 @@ template <> struct
MappingTraits {
}
};
template <> struct SequenceElementTraits {
+ // NOLINTNEXTLINE(readability-identifier-naming) Defined by YAMLTraits.h
static const bool flow = false;
};
template <> struct MappingTraits {
diff --git a/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp
b/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp
index 6aad3c6b191ed..e90cdd00eb1fe 100644
--- a/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp
@@ -215,13 +215,13 @@ bool UnrollLoopsCheck::hasLargeNumIterations(const Stmt
*Statement,
break;
case (BO_MulAssign):
Iterations =
- 1 + (std::log((double)EndValue) - std::log((double)InitValue)) /
- std::log((double)ConstantValue);
+ 1 + ((std::log((double)EndValue) - std::log((double)InitValue)) /
+ std::log((double)ConstantValue));
break;
case (BO_DivAssign):
Iterations =
- 1 + (std::log((double)InitValue) - std::log((double)EndValue)) /
- std::log((double)ConstantValue);
+ 1 + ((std::log((double)InitValue) - std::log((double)EndValue)) /
+ std::log((double)ConstantValue));
break;
default:
// All other operators are not handled; assume large bounds.
diff --git
a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
index d8207b30f1b5e..b4ee35154f5f0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
@@ -1074,7 +1074,7 @@ approximateStandardConversionSequence(const TheCheck
&Check, QualType From,
WorkType = To;
}
- if (Ctx.hasSameType(WorkType, To)) {
+ if (ASTContext::hasSameType(WorkType, To)) {
LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Reached 'To' type.\n");
return {Ctx.getCommonSugaredType(WorkType, To)};
}
diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index cdb6a088b9d0a..cf55dd718f532 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -424,7 +424,7 @@ void SizeofExpressionCheck::check(const
MatchFinder::MatchResult &Result) {
"suspicious usage of 'sizeof(array)/sizeof(...)';"
" denominator
diff ers from the size of array elements")
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
-} else if (NumTy && DenomTy && Ctx.hasSameType(NumTy, DenomTy) &&
+} else if (NumTy && DenomTy && ASTContext::hasSameType(NumTy, DenomTy) &&
!NumTy->isDependentType()) {
// Dependent type should not be compared.
diag(E->getOperatorLoc(),
@@ -433,7 +433,7 @@ void Sizeof
[clang-tools-extra] [clang-tidy][NFC] Fix miscellaneous clang-tidy warnings over codebase (PR #164096)
https://github.com/vbvictor closed https://github.com/llvm/llvm-project/pull/164096 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 3/N (PR #164085)
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 origin/main HEAD --extensions h,cpp --
clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
clang-tools-extra/clang-tidy/android/CloexecCheck.h
clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp
clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
--diff_from_common_commit
``
:warning:
The reproduction instructions above might return results for more than one PR
in a stack if you are using a stacked PR workflow. You can limit the results by
changing `origin/main` to the base branch/commit you want to compare against.
:warning:
View the diff from clang-format here.
``diff
diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
index 0e8ed33da..6baa12a8b 100644
--- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -808,7 +808,8 @@ static bool isSameRawIdentifierToken(const Token &T1, const
Token &T2,
StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
}
-static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, const SourceManager
&SM) {
+static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T,
+ const SourceManager &SM) {
return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
}
``
https://github.com/llvm/llvm-project/pull/164085
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][NFC] Fix llvm-prefer-static-over-anonymous-namespace warnings 3/N (PR #164085)
https://github.com/vbvictor updated
https://github.com/llvm/llvm-project/pull/164085
>From 64d7d69ca3bd9d78dd0b2c3522919dbe4d13e3ab Mon Sep 17 00:00:00 2001
From: Victor Baranov
Date: Sat, 18 Oct 2025 16:44:01 +0300
Subject: [PATCH 1/3] [clang-tidy][NFC] Fix
llvm-prefer-static-over-anonymous-namespace warnings 3/N
---
.../clang-tidy/android/CloexecCheck.cpp | 12 +++--
.../clang-tidy/android/CloexecCheck.h | 4 +--
.../bugprone/SignalHandlerCheck.cpp | 19 +++--
.../misc/RedundantExpressionCheck.cpp | 6 +++--
.../misc/UniqueptrResetReleaseCheck.cpp | 9 +++
.../clang-tidy/modernize/UseNullptrCheck.cpp | 20 +-
.../performance/FasterStringFindCheck.cpp | 7 ++---
.../InefficientVectorOperationCheck.cpp | 6 ++---
.../readability/DuplicateIncludeCheck.cpp | 4 +--
...onsistentDeclarationParameterNameCheck.cpp | 27 ++-
.../readability/RedundantSmartptrGetCheck.cpp | 17 ++--
11 files changed, 66 insertions(+), 65 deletions(-)
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
index cd83423adae05..48c54c0ae02c3 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp
@@ -16,12 +16,13 @@ using namespace clang::ast_matchers;
namespace clang::tidy::android {
-namespace {
// Helper function to form the correct string mode for Type3.
// Build the replace text. If it's string constant, add directly in the
// end of the string. Else, add .
-std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM,
- const LangOptions &LangOpts, char Mode) {
+static std::string buildFixMsgForStringFlag(const Expr *Arg,
+const SourceManager &SM,
+const LangOptions &LangOpts,
+char Mode) {
if (Arg->getBeginLoc().isMacroID())
return (Lexer::getSourceText(
CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
@@ -32,11 +33,6 @@ std::string buildFixMsgForStringFlag(const Expr *Arg, const
SourceManager &SM,
StringRef SR = cast(Arg->IgnoreParenCasts())->getString();
return ("\"" + SR + Twine(Mode) + "\"").str();
}
-} // namespace
-
-const char *CloexecCheck::FuncDeclBindingStr = "funcDecl";
-
-const char *CloexecCheck::FuncBindingStr = "func";
void CloexecCheck::registerMatchersImpl(
MatchFinder *Finder, internal::Matcher Function) {
diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
index 79f7ab3354d8d..b2b59f5be1b9a 100644
--- a/clang-tools-extra/clang-tidy/android/CloexecCheck.h
+++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.h
@@ -89,10 +89,10 @@ class CloexecCheck : public ClangTidyCheck {
int N) const;
/// Binding name of the FuncDecl of a function call.
- static const char *FuncDeclBindingStr;
+ static constexpr char FuncDeclBindingStr[] = "funcDecl";
/// Binding name of the function call expression.
- static const char *FuncBindingStr;
+ static constexpr char FuncBindingStr[] = "func";
};
} // namespace clang::tidy::android
diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
index 86af5cbd94374..c262b1c05b047 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
@@ -245,12 +245,10 @@ struct OptionEnumMapping<
namespace bugprone {
-namespace {
-
/// Returns if a function is declared inside a system header.
/// These functions are considered to be "standard" (system-provided) library
/// functions.
-bool isStandardFunction(const FunctionDecl *FD) {
+static bool isStandardFunction(const FunctionDecl *FD) {
// Find a possible redeclaration in system header.
// FIXME: Looking at the canonical declaration is not the most exact way
// to do this.
@@ -284,7 +282,7 @@ bool isStandardFunction(const FunctionDecl *FD) {
/// Check if a statement is "C++-only".
/// This includes all statements that have a class name with "CXX" prefix
/// and every other statement that is declared in file ExprCXX.h.
-bool isCXXOnlyStmt(const Stmt *S) {
+static bool isCXXOnlyStmt(const Stmt *S) {
StringRef Name = S->getStmtClassName();
if (Name.starts_with("CXX"))
return true;
@@ -304,7 +302,8 @@ bool isCXXOnlyStmt(const Stmt *S) {
/// called from \p Caller, get a \c CallExpr of the corresponding function
call.
/// It is unspecified which call is found if multiple calls exist, but the
order
/// should be deterministic (depend only on the AST).
-Expr *findCallExpr(const CallGraphNode *Caller, const CallGraphNode *Callee) {
+static Expr *findCa
[clang] [clang] Reland: separate recursive instantiation check from CodeSynthesisContext (PR #164177)
llvmbot wrote:
@llvm/pr-subscribers-clang
Author: Matheus Izvekov (mizvekov)
Changes
This makes pushing / popping CodeSynthesisContexts much cheaper, as it
delegates to another class this functionality which is not actually needed in
most cases.
It also converts a bunch of these uses into just asserts.
This improves compiler performance a little bit:
Some diagnostics change a little bit, because we avoid printing a redundant
context notes.
This relands #162224 with no changes, turns out the buildbot failure
was unrelated.
---
Full diff: https://github.com/llvm/llvm-project/pull/164177.diff
5 Files Affected:
- (modified) clang/include/clang/Sema/Sema.h (+40-6)
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+49-38)
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+24-12)
- (modified) clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp (+4-3)
- (modified) clang/test/SemaTemplate/instantiate-self.cpp (+25-3)
``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index add4c1596ab86..cb21335ede075 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13007,6 +13007,37 @@ class Sema final : public SemaBase {
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
+ using InstantiatingSpecializationsKey = llvm::PointerIntPair;
+
+ struct RecursiveInstGuard {
+enum class Kind {
+ Template,
+ DefaultArgument,
+ ExceptionSpec,
+};
+
+RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
+: S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
+ auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
+ if (!Created)
+Key = {};
+}
+
+~RecursiveInstGuard() {
+ if (Key.getOpaqueValue()) {
+[[maybe_unused]] bool Erased =
+S.InstantiatingSpecializations.erase(Key);
+assert(Erased);
+ }
+}
+
+operator bool() const { return Key.getOpaqueValue() == nullptr; }
+
+ private:
+Sema &S;
+Sema::InstantiatingSpecializationsKey Key;
+ };
+
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
@@ -13368,14 +13399,9 @@ class Sema final : public SemaBase {
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
-/// Determine whether we are already instantiating this
-/// specialization in some surrounding active instantiation.
-bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
-
private:
Sema &SemaRef;
bool Invalid;
-bool AlreadyInstantiating;
InstantiatingTemplate(Sema &SemaRef,
CodeSynthesisContext::SynthesisKind Kind,
@@ -13505,7 +13531,7 @@ class Sema final : public SemaBase {
SmallVector CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
- llvm::DenseSet> InstantiatingSpecializations;
+ llvm::DenseSet InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
@@ -13780,6 +13806,14 @@ class Sema final : public SemaBase {
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK, bool Complain = true);
+private:
+ bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
+CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern,
+const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain);
+
+public:
/// Instantiate the definition of an enum from a given pattern.
///
/// \param PointOfInstantiation The point of instantiation within the
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 038f39633760d..7f858050db13e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -639,15 +639,8 @@ Sema::InstantiatingTemplate::InstantiatingTemplate(
}
Invalid = SemaRef.pushCodeSynthesisContext(Inst);
- if (!Invalid) {
-AlreadyInstantiating =
-!Inst.Entity
-? false
-: !SemaRef.InstantiatingSpecializations
- .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
- .second;
+ if (!Invalid)
atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
- }
}
Sema::InstantiatingTemplate::InstantiatingTemplate(
@@ -902,13 +895,6 @@ void Sema::popCodeSynthesisContext() {
void Sema::InstantiatingTemplate::Clear() {
if (!Invalid) {
-if (!AlreadyInstantiating) {
- a
[clang] 63ca2fd - [clang] Reland: separate recursive instantiation check from CodeSynthesisContext (#164177)
Author: Matheus Izvekov
Date: 2025-10-19T16:45:50-03:00
New Revision: 63ca2fd7a16f532a95e53780220d2eae0debb8d9
URL:
https://github.com/llvm/llvm-project/commit/63ca2fd7a16f532a95e53780220d2eae0debb8d9
DIFF:
https://github.com/llvm/llvm-project/commit/63ca2fd7a16f532a95e53780220d2eae0debb8d9.diff
LOG: [clang] Reland: separate recursive instantiation check from
CodeSynthesisContext (#164177)
This makes pushing / popping CodeSynthesisContexts much cheaper, as it
delegates to another class this functionality which is not actually
needed in most cases.
It also converts a bunch of these uses into just asserts.
This improves compiler performance a little bit:
Some diagnostics change a little bit, because we avoid printing a
redundant context notes.
This relands #162224 with no changes, turns out the buildbot failure was
unrelated.
Added:
Modified:
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
clang/test/SemaTemplate/instantiate-self.cpp
Removed:
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index add4c1596ab86..cb21335ede075 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13007,6 +13007,37 @@ class Sema final : public SemaBase {
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
+ using InstantiatingSpecializationsKey = llvm::PointerIntPair;
+
+ struct RecursiveInstGuard {
+enum class Kind {
+ Template,
+ DefaultArgument,
+ ExceptionSpec,
+};
+
+RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
+: S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
+ auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
+ if (!Created)
+Key = {};
+}
+
+~RecursiveInstGuard() {
+ if (Key.getOpaqueValue()) {
+[[maybe_unused]] bool Erased =
+S.InstantiatingSpecializations.erase(Key);
+assert(Erased);
+ }
+}
+
+operator bool() const { return Key.getOpaqueValue() == nullptr; }
+
+ private:
+Sema &S;
+Sema::InstantiatingSpecializationsKey Key;
+ };
+
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
@@ -13368,14 +13399,9 @@ class Sema final : public SemaBase {
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
-/// Determine whether we are already instantiating this
-/// specialization in some surrounding active instantiation.
-bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
-
private:
Sema &SemaRef;
bool Invalid;
-bool AlreadyInstantiating;
InstantiatingTemplate(Sema &SemaRef,
CodeSynthesisContext::SynthesisKind Kind,
@@ -13505,7 +13531,7 @@ class Sema final : public SemaBase {
SmallVector CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
- llvm::DenseSet> InstantiatingSpecializations;
+ llvm::DenseSet InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
@@ -13780,6 +13806,14 @@ class Sema final : public SemaBase {
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK, bool Complain = true);
+private:
+ bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
+CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern,
+const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain);
+
+public:
/// Instantiate the definition of an enum from a given pattern.
///
/// \param PointOfInstantiation The point of instantiation within the
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 038f39633760d..7f858050db13e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -639,15 +639,8 @@ Sema::InstantiatingTemplate::InstantiatingTemplate(
}
Invalid = SemaRef.pushCodeSynthesisContext(Inst);
- if (!Invalid) {
-AlreadyInstantiating =
-!Inst.Entity
-? false
-: !SemaRef.InstantiatingSpecializations
- .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
- .second;
+ if (!Invalid)
atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
[clang] [clang] Reland: separate recursive instantiation check from CodeSynthesisContext (PR #164177)
https://github.com/mizvekov closed https://github.com/llvm/llvm-project/pull/164177 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Reland: separate recursive instantiation check from CodeSynthesisContext (PR #164177)
https://github.com/mizvekov created
https://github.com/llvm/llvm-project/pull/164177
This makes pushing / popping CodeSynthesisContexts much cheaper, as it
delegates to another class this functionality which is not actually needed in
most cases.
It also converts a bunch of these uses into just asserts.
This improves compiler performance a little bit:
Some diagnostics change a little bit, because we avoid printing a redundant
context notes.
This relands #162224 with no changes, turns out the buildbot failure was
unrelated.
>From 1b754878654c8c06ea978342e7fc7249ae07fbbf Mon Sep 17 00:00:00 2001
From: Matheus Izvekov
Date: Sun, 5 Oct 2025 22:25:52 -0300
Subject: [PATCH] [clang] Reland: separate recursive instantiation check from
CodeSynthesisContext
This makes pushing / popping CodeSynthesisContexts much cheaper,
as it delegates to another class this functionality which is not
actually needed in most cases.
It also converts a bunch of these uses into just asserts.
This improves compiler performance a little bit:
Some diagnostics change a little bit, because we avoid printing
a redundant context notes.
This relands #162224 with no changes, turns out the buildbot failure was
unrelated.
---
clang/include/clang/Sema/Sema.h | 46 --
clang/lib/Sema/SemaTemplateInstantiate.cpp| 87 +++
.../lib/Sema/SemaTemplateInstantiateDecl.cpp | 36 +---
.../test/SemaCXX/libstdcxx_pair_swap_hack.cpp | 7 +-
clang/test/SemaTemplate/instantiate-self.cpp | 28 +-
5 files changed, 142 insertions(+), 62 deletions(-)
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index add4c1596ab86..cb21335ede075 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13007,6 +13007,37 @@ class Sema final : public SemaBase {
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
+ using InstantiatingSpecializationsKey = llvm::PointerIntPair;
+
+ struct RecursiveInstGuard {
+enum class Kind {
+ Template,
+ DefaultArgument,
+ ExceptionSpec,
+};
+
+RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
+: S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
+ auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
+ if (!Created)
+Key = {};
+}
+
+~RecursiveInstGuard() {
+ if (Key.getOpaqueValue()) {
+[[maybe_unused]] bool Erased =
+S.InstantiatingSpecializations.erase(Key);
+assert(Erased);
+ }
+}
+
+operator bool() const { return Key.getOpaqueValue() == nullptr; }
+
+ private:
+Sema &S;
+Sema::InstantiatingSpecializationsKey Key;
+ };
+
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
@@ -13368,14 +13399,9 @@ class Sema final : public SemaBase {
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
-/// Determine whether we are already instantiating this
-/// specialization in some surrounding active instantiation.
-bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
-
private:
Sema &SemaRef;
bool Invalid;
-bool AlreadyInstantiating;
InstantiatingTemplate(Sema &SemaRef,
CodeSynthesisContext::SynthesisKind Kind,
@@ -13505,7 +13531,7 @@ class Sema final : public SemaBase {
SmallVector CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
- llvm::DenseSet> InstantiatingSpecializations;
+ llvm::DenseSet InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
@@ -13780,6 +13806,14 @@ class Sema final : public SemaBase {
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK, bool Complain = true);
+private:
+ bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
+CXXRecordDecl *Instantiation,
+CXXRecordDecl *Pattern,
+const MultiLevelTemplateArgumentList &TemplateArgs,
+TemplateSpecializationKind TSK, bool Complain);
+
+public:
/// Instantiate the definition of an enum from a given pattern.
///
/// \param PointOfInstantiation The point of instantiation within the
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 038f39633760d..7f858050db13e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -639,15 +639,8 @@ Sema::InstantiatingTemplate::InstantiatingTemplate(
}
Inva
