[clang] ExprEngine::performTrivialCopy triggers checkLocation (PR #129016)
https://github.com/T-Gruber updated https://github.com/llvm/llvm-project/pull/129016 >From 79d8f061476c6ba21bf48f55597eaaef345c2e80 Mon Sep 17 00:00:00 2001 From: "tobias.gruber" Date: Wed, 26 Feb 2025 18:00:21 +0100 Subject: [PATCH 1/5] Trigger checkLocation for RHS of copy construction --- .../lib/StaticAnalyzer/Core/ExprEngineCXX.cpp | 250 +- 1 file changed, 121 insertions(+), 129 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp index f7020da2e6da2..fbb5e316bb068 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp @@ -69,6 +69,7 @@ void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, assert(ThisRD); SVal V = Call.getArgSVal(0); + const Expr *VExpr = Call.getArgExpr(0); // If the value being copied is not unknown, load from its location to get // an aggregate rvalue. @@ -76,7 +77,11 @@ void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, V = Pred->getState()->getSVal(*L); else assert(V.isUnknownOrUndef()); - evalBind(Dst, CallExpr, Pred, ThisVal, V, true); + + ExplodedNodeSet Tmp; + evalLocation(Tmp, CallExpr, VExpr, Pred, Pred->getState(), V, true); + for (ExplodedNode *N : Tmp) +evalBind(Dst, CallExpr, N, ThisVal, V, true); PostStmt PS(CallExpr, LCtx); for (ExplodedNode *N : Dst) { @@ -141,10 +146,9 @@ SVal ExprEngine::computeObjectUnderConstruction( if (Init->isBaseInitializer()) { const auto *ThisReg = cast(ThisVal.getAsRegion()); const CXXRecordDecl *BaseClass = - Init->getBaseClass()->getAsCXXRecordDecl(); -const auto *BaseReg = - MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg, - Init->isBaseVirtual()); +Init->getBaseClass()->getAsCXXRecordDecl(); +const auto *BaseReg = MRMgr.getCXXBaseObjectRegion( +BaseClass, ThisReg, Init->isBaseVirtual()); return SVB.makeLoc(BaseReg); } if (Init->isDelegatingInitializer()) @@ -183,7 +187,7 @@ SVal ExprEngine::computeObjectUnderConstruction( return loc::MemRegionVal(R); } - return V; + return V; } // TODO: Detect when the allocator returns a null pointer. // Constructor shall not be called in this case. @@ -405,99 +409,99 @@ ProgramStateRef ExprEngine::updateObjectsUnderConstruction( case ConstructionContext::SimpleVariableKind: { const auto *DSCC = cast(CC); return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V); -} -case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: -case ConstructionContext::SimpleConstructorInitializerKind: { - const auto *ICC = cast(CC); - const auto *Init = ICC->getCXXCtorInitializer(); - // Base and delegating initializers handled above - assert(Init->isAnyMemberInitializer() && - "Base and delegating initializers should have been handled by" - "computeObjectUnderConstruction()"); - return addObjectUnderConstruction(State, Init, LCtx, V); -} -case ConstructionContext::NewAllocatedObjectKind: { + } + case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: + case ConstructionContext::SimpleConstructorInitializerKind: { +const auto *ICC = cast(CC); +const auto *Init = ICC->getCXXCtorInitializer(); +// Base and delegating initializers handled above +assert(Init->isAnyMemberInitializer() && + "Base and delegating initializers should have been handled by" + "computeObjectUnderConstruction()"); +return addObjectUnderConstruction(State, Init, LCtx, V); + } + case ConstructionContext::NewAllocatedObjectKind: { +return State; + } + case ConstructionContext::SimpleReturnedValueKind: + case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { +const StackFrameContext *SFC = LCtx->getStackFrame(); +const LocationContext *CallerLCtx = SFC->getParent(); +if (!CallerLCtx) { + // No extra work is necessary in top frame. return State; } -case ConstructionContext::SimpleReturnedValueKind: -case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { - const StackFrameContext *SFC = LCtx->getStackFrame(); - const LocationContext *CallerLCtx = SFC->getParent(); - if (!CallerLCtx) { -// No extra work is necessary in top frame. -return State; - } - auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] - .getAs(); - assert(RTC && "Could not have had a target region without it"); - if (isa(CallerLCtx)) { -// Unwrap block invocation contexts. They're mostly part of -// the current stack frame. -CallerLCtx = CallerLCtx->getParent(); -assert(!isa(CallerLCtx)); - } - - r
[clang] [clang] Fix ASTWriter crash after merging named enums (PR #114240)
https://github.com/michael-jabbour-sonarsource updated https://github.com/llvm/llvm-project/pull/114240 >From cc3cf25da67c9f8b9edabb318c6011cad9bd2f58 Mon Sep 17 00:00:00 2001 From: Michael Jabbour Date: Tue, 29 Oct 2024 11:16:09 +0100 Subject: [PATCH 1/8] [NFC] Factor out RetireNodesFromMergedDecl --- clang/include/clang/Sema/Sema.h | 6 ++ clang/lib/Sema/SemaDecl.cpp | 27 +++ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 93d98e1cbb9c8..70bbb882eb2b1 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -4034,6 +4034,12 @@ class Sema final : public SemaBase { void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); + /// RetireNodesFromMergedDecl - We have just merged the decl 'New' by making + /// another definition visible. + /// This method performs any necessary cleanup on the parser state to discard + /// child nodes from newly parsed decl we are retiring. + void RetireNodesFromMergedDecl(Scope *S, Decl *New); + /// MergeFunctionDecl - We just parsed a function 'New' from /// declarator D which has the same name and scope as a previous /// declaration 'Old'. Figure out how to resolve this situation, diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index f8e5f3c6d309d..54c4c5f4e5395 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -2551,18 +2551,7 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, // Make the old tag definition visible. makeMergedDefinitionVisible(Hidden); - // If this was an unscoped enumeration, yank all of its enumerators - // out of the scope. - if (isa(NewTag)) { -Scope *EnumScope = getNonFieldDeclScope(S); -for (auto *D : NewTag->decls()) { - auto *ED = cast(D); - assert(EnumScope->isDeclScope(ED)); - EnumScope->RemoveDecl(ED); - IdResolver.RemoveDecl(ED); - ED->getLexicalDeclContext()->removeDecl(ED); -} - } + RetireNodesFromMergedDecl(S, NewTag); } } @@ -2639,6 +2628,20 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, notePreviousDefinition(Old, New->getLocation()); } +void Sema::RetireNodesFromMergedDecl(Scope *S, Decl *New) { + // If this was an unscoped enumeration, yank all of its enumerators + // out of the scope. + if (auto *ED = dyn_cast(New); ED) { +Scope *EnumScope = getNonFieldDeclScope(S); +for (auto *ECD : ED->enumerators()) { + assert(EnumScope->isDeclScope(ECD)); + EnumScope->RemoveDecl(ECD); + IdResolver.RemoveDecl(ECD); + ECD->getLexicalDeclContext()->removeDecl(ECD); +} + } +} + /// DeclhasAttr - returns true if decl Declaration already has the target /// attribute. static bool DeclHasAttr(const Decl *D, const Attr *A) { >From f07904ae5468658a3e7e4a649cd183734479d6cc Mon Sep 17 00:00:00 2001 From: Michael Jabbour Date: Tue, 29 Oct 2024 12:07:29 +0100 Subject: [PATCH 2/8] Drop enumerators when merging named enums This fixes a crash in ASTWriter when the stale IdResolver entries are used when writing the identifier table. assert(DeclIDs.contains(D) && "Declaration not emitted!"); --- clang/include/clang/Sema/Sema.h | 2 +- clang/lib/Parse/ParseDecl.cpp | 2 +- clang/lib/Parse/ParseDeclCXX.cpp| 3 +- clang/lib/Sema/SemaDecl.cpp | 6 ++- clang/test/Modules/modules-merge-enum.m | 52 + 5 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 clang/test/Modules/modules-merge-enum.m diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 70bbb882eb2b1..d53bcf63dd1bd 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -3910,7 +3910,7 @@ class Sema final : public SemaBase { /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. - bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody); + bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 31984453487ae..750301a9155d7 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -5645,7 +5645,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl; ParseEnumBody(StartLoc, D); if (SkipBody.CheckSameAsPrevious && -!Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) { +!Actions.ActOnDuplicateDefinition(getCurScope(), TagDecl, SkipBody)) { DS.SetTypeSpecE
[clang] [WebAssembly] Generate __clang_call_terminate for Emscripten EH (PR #129020)
https://github.com/aheejin created https://github.com/llvm/llvm-project/pull/129020 When an exception thrown ends up calling `std::terminate`, for example, because an exception is thrown within a `noexcept` function or an exception is thrown from `__cxa_end_catch` during handling the previous exception, the libc++abi spec says we are supposed to call `__cxa_begin_catch` before `std::terminate`: https://libcxxabi.llvm.org/spec.html > When the personality routine encounters a termination condition, it will > call `__cxa_begin_catch()` to mark the exception as handled and then call > `terminate()`, which shall not return to its caller. The default Itanium ABI generates a call to `__clang_call_terminate()`, which is a function that calls `__cxa_begin_catch` and then `std::terminate`: ```ll define void @__clang_call_terminate(ptr noundef %0) { %2 = call ptr @__cxa_begin_catch(ptr %0) call void @_ZSt9terminatev() unreachable } ``` But we replaced this with just a call to `std::terminate` in https://github.com/llvm/llvm-project/commit/561abd83ffecc8d4ba8fcbbbcadb31efc55985c2 because this caused some tricky transformation problems for Wasm EH. The detailed explanation why is in the commit description, but the summary is for Wasm EH it needed a `try` with both `catch` and `catch_all` and it was tricky to deal with. But that commit replaced `__clang_call_terminate` with `std::terminate` for all Wasm programs and not only the ones that use Wasm EH. So Emscripten EH was also affected by that commit. Emscripten EH is not able to catch foreign exceptions anyway, so this is unnecessary compromise. This makes we use `__clang_call_terminate` as in the default Itanium EH for Emscripten EH. We may later fix Wasm EH too but that requires more efforts in the backend. Related issue: https://github.com/emscripten-core/emscripten/issues/23720 >From 92861b903905d4f3d2fa39772033282b2dbad758 Mon Sep 17 00:00:00 2001 From: Heejin Ahn Date: Thu, 27 Feb 2025 03:09:45 + Subject: [PATCH] [WebAssembly] Generate __clang_call_terminate for Emscripten EH When an exception thrown ends up calling `std::terminate`, for example, because an exception is thrown within a `noexcept` function or an exception is thrown from `__cxa_end_catch` during handling the previous exception, the libc++abi spec says we are supposed to call `__cxa_begin_catch` before `std::terminate`: https://libcxxabi.llvm.org/spec.html > When the personality routine encounters a termination condition, it > will call `__cxa_begin_catch()` to mark the exception as handled and > then call `terminate()`, which shall not return to its caller. The default Itanium ABI generates a call to `__clang_call_terminate()`, which is a function that calls `__cxa_begin_catch` and then `std::terminate`: ```ll define void @__clang_call_terminate(ptr noundef %0) { %2 = call ptr @__cxa_begin_catch(ptr %0) call void @_ZSt9terminatev() unreachable } ``` But we replaced this with just a call to `std::terminate` in https://github.com/llvm/llvm-project/commit/561abd83ffecc8d4ba8fcbbbcadb31efc55985c2 because this caused some tricky transformation problems for Wasm EH. The detailed explanation why is in the commit description, but the summary is for Wasm EH it needs a `try` with both `catch` and `catch_all` and it was tricky to deal with. But that commit replaced `__clang_call_terminate` with `std::terminate` for all Wasm programs and not only the ones that use Wasm EH. So Emscripten EH was also affected by that commit. Emscripten EH is not able to catch foreign exceptions anyway, so this is unnecessary compromise. This makes we use `__clang_call_terminate` as in the default Itanium EH for Emscripten EH. We may later fix Wasm EH too but that requires more efforts in the backend. Related issue: https://github.com/emscripten-core/emscripten/issues/23720 --- clang/lib/CodeGen/ItaniumCXXABI.cpp | 9 +++-- clang/test/CodeGenCXX/wasm-eh.cpp| 12 clang/test/CodeGenCXX/wasm-em-eh.cpp | 13 + 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGenCXX/wasm-em-eh.cpp diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp b/clang/lib/CodeGen/ItaniumCXXABI.cpp index bcd171724c41d..f3ffa0b2e84c1 100644 --- a/clang/lib/CodeGen/ItaniumCXXABI.cpp +++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -5150,9 +5150,14 @@ WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on // the violating exception to mark it handled, but it is currently hard to do // with wasm EH instruction structure with catch/catch_all, we just call - // std::terminate and ignore the violating exception as in CGCXXABI. + // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH + // and calls __clang_call_terminate only in Emscripten EH. // TODO Consider code transformation that makes calling __clang_call_termina
[clang] [WebAssembly] Generate __clang_call_terminate for Emscripten EH (PR #129020)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Heejin Ahn (aheejin) Changes When an exception thrown ends up calling `std::terminate`, for example, because an exception is thrown within a `noexcept` function or an exception is thrown from `__cxa_end_catch` during handling the previous exception, the libc++abi spec says we are supposed to call `__cxa_begin_catch` before `std::terminate`: https://libcxxabi.llvm.org/spec.html > When the personality routine encounters a termination condition, it will call `__cxa_begin_catch()` to mark the exception as handled and then call `terminate()`, which shall not return to its caller. The default Itanium ABI generates a call to `__clang_call_terminate()`, which is a function that calls `__cxa_begin_catch` and then `std::terminate`: ```ll define void @__clang_call_terminate(ptr noundef %0) { %2 = call ptr @__cxa_begin_catch(ptr %0) call void @_ZSt9terminatev() unreachable } ``` But we replaced this with just a call to `std::terminate` in https://github.com/llvm/llvm-project/commit/561abd83ffecc8d4ba8fcbbbcadb31efc55985c2 because this caused some tricky transformation problems for Wasm EH. The detailed explanation why is in the commit description, but the summary is for Wasm EH it needed a `try` with both `catch` and `catch_all` and it was tricky to deal with. But that commit replaced `__clang_call_terminate` with `std::terminate` for all Wasm programs and not only the ones that use Wasm EH. So Emscripten EH was also affected by that commit. Emscripten EH is not able to catch foreign exceptions anyway, so this is unnecessary compromise. This makes we use `__clang_call_terminate` as in the default Itanium EH for Emscripten EH. We may later fix Wasm EH too but that requires more efforts in the backend. Related issue: https://github.com/emscripten-core/emscripten/issues/23720 --- Full diff: https://github.com/llvm/llvm-project/pull/129020.diff 3 Files Affected: - (modified) clang/lib/CodeGen/ItaniumCXXABI.cpp (+7-2) - (modified) clang/test/CodeGenCXX/wasm-eh.cpp (+12) - (added) clang/test/CodeGenCXX/wasm-em-eh.cpp (+13) ``diff diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp b/clang/lib/CodeGen/ItaniumCXXABI.cpp index bcd171724c41d..f3ffa0b2e84c1 100644 --- a/clang/lib/CodeGen/ItaniumCXXABI.cpp +++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -5150,9 +5150,14 @@ WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on // the violating exception to mark it handled, but it is currently hard to do // with wasm EH instruction structure with catch/catch_all, we just call - // std::terminate and ignore the violating exception as in CGCXXABI. + // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH + // and calls __clang_call_terminate only in Emscripten EH. // TODO Consider code transformation that makes calling __clang_call_terminate - // possible. + // in Wasm EH possible. + if (Exn && !EHPersonality::get(CGF).isWasmPersonality()) { +assert(CGF.CGM.getLangOpts().CPlusPlus); +return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn); + } return CGCXXABI::emitTerminateForUnexpectedException(CGF, Exn); } diff --git a/clang/test/CodeGenCXX/wasm-eh.cpp b/clang/test/CodeGenCXX/wasm-eh.cpp index 9dc15633bfed9..e8797794e7c1e 100644 --- a/clang/test/CodeGenCXX/wasm-eh.cpp +++ b/clang/test/CodeGenCXX/wasm-eh.cpp @@ -6,6 +6,9 @@ // RUN: %clang_cc1 %s -triple wasm32-unknown-unknown -fms-extensions -fexceptions -fcxx-exceptions -mllvm -wasm-enable-eh -exception-model=wasm -target-feature +exception-handling -emit-llvm -o - -std=c++11 | FileCheck %s // RUN: %clang_cc1 %s -triple wasm64-unknown-unknown -fms-extensions -fexceptions -fcxx-exceptions -mllvm -wasm-enable-eh -exception-model=wasm -target-feature +exception-handling -emit-llvm -o - -std=c++11 | FileCheck %s +// Test code generation for Wasm EH using WebAssembly EH proposal. +// (https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/Exceptions.md) + void may_throw(); void dont_throw() noexcept; @@ -381,6 +384,15 @@ void test8() { // CHECK: unreachable +void noexcept_throw() noexcept { + throw 3; +} + +// CATCH-LABEL: define void @_Z14noexcept_throwv() +// CHECK: %{{.*}} = cleanuppad within none [] +// CHECK-NEXT: call void @_ZSt9terminatev() + + // RUN: %clang_cc1 %s -triple wasm32-unknown-unknown -fms-extensions -fexceptions -fcxx-exceptions -exception-model=wasm -target-feature +exception-handling -emit-llvm -o - -std=c++11 2>&1 | FileCheck %s --check-prefix=WARNING-DEFAULT // RUN: %clang_cc1 %s -triple wasm32-unknown-unknown -fms-extensions -fexceptions -fcxx-exceptions -exception-model=wasm -target-feature +exception-handling -Wwasm-exception-spec -emit-llvm -o - -std=c++11 2>&1 | FileCheck %s --check-prefix=WARNING-ON // RUN: %clang_
[clang] [clang][LoongArch] Add OHOS target (PR #127555)
https://github.com/SixWeining approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/127555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Reapply [CaptureTracking][FunctionAttrs] Add support for CaptureInfo (#125880) (PR #128020)
https://github.com/nikic edited https://github.com/llvm/llvm-project/pull/128020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] APFloat: Fix maxnum and minnum with sNaN (PR #112854)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `sanitizer-aarch64-linux-bootstrap-msan` running on `sanitizer-buildbot10` while building `llvm` at step 2 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/94/builds/4769 Here is the relevant piece of the build log for the reference ``` Step 2 (annotate) failure: 'python ../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py' (failure) ... llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using lld-link: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/lld-link llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using ld64.lld: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld64.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using wasm-ld: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/wasm-ld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using ld.lld: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using lld-link: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/lld-link llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using ld64.lld: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld64.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:512: note: using wasm-ld: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/wasm-ld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/main.py:72: note: The test suite configuration requested an individual test timeout of 0 seconds but a timeout of 900 seconds was requested on the command line. Forcing timeout to be 900 seconds. -- Testing: 86746 tests, 72 workers -- Testing: 0.. 10.. 20.. 30.. 40.. 50.. 60.. FAIL: LLVM :: Other/spirv-sim/constant.spv (62112 of 86746) TEST 'LLVM :: Other/spirv-sim/constant.spv' FAILED Exit Code: 139 Command Output (stderr): -- RUN: at line 1 has no command after substitutions RUN: at line 2: '/usr/bin/python3' /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/spirv-sim/spirv-sim.py --function=a --wave=1 --expects=2 -i /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/test/Other/spirv-sim/constant.spv + /usr/bin/python3 /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/spirv-sim/spirv-sim.py --function=a --wave=1 --expects=2 -i /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/test/Other/spirv-sim/constant.spv RUN: at line 3: '/usr/bin/python3' /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/spirv-sim/spirv-sim.py --function=b --wave=1 --expects=1 -i /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/test/Other/spirv-sim/constant.spv + /usr/bin/python3 /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/spirv-sim/spirv-sim.py --function=b --wave=1 --expects=1 -i /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/test/Other/spirv-sim/constant.spv /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/test/Other/spirv-sim/Output/constant.spv.script: line 3: 3606190 Segmentation fault (core dumped) '/usr/bin/python3' /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/spirv-sim/spirv-sim.py --function=b --wave=1 --expects=1 -i /home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/test/Other/spirv-sim/constant.spv -- Testing: 0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. Slowest Tests: -- 128.08s: Clang :: Driver/fsanitize.c 99.87s: Clang :: Preprocessor/riscv-target-features.c 85.65s: Clang :: Driver/arm-cortex-cpus-2.c 85.56s: Clang :: Driver/arm-cortex-cpus-1.c 83.63s: Clang :: OpenMP/target_defaultmap_codegen_01.cpp 83.38s: Clang :: OpenMP/target_update_codegen.cpp 81.39s: LLVM :: CodeGen/AMDGPU/memintrinsic-unroll.ll 72.92s: Clang :: Preprocessor/aarch64-target-features.c 72.76s: Clang :: Preprocessor/arm-target-features.c 70.48s: LLVM :: CodeGen/AMDGPU/sched-group-barrier-pipeline-solver.mir 67.55s: LLVM :: MC/Mips/mips-jump-pc-region.s 65.31s: Clang :: Driver/clang_f_opts.c 60.78s: Clang :: Preprocessor/pre
[clang] Mark union member destructors referenced (PR #128866)
https://github.com/momo5502 updated https://github.com/llvm/llvm-project/pull/128866 >From 484ff7a53ab700fda30ee90f739bb2573f41c851 Mon Sep 17 00:00:00 2001 From: Maurice Heumann Date: Wed, 26 Feb 2025 08:37:04 +0100 Subject: [PATCH 1/2] Mark union member destructors referenced --- clang/lib/Sema/SemaDeclCXX.cpp | 6 -- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index 664d48ccbc382..ce7927dedd96b 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -5764,7 +5764,7 @@ Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl) { // Ignore dependent contexts. Also ignore unions, since their members never // have destructors implicitly called. - if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) + if (ClassDecl->isDependentContext() /*|| ClassDecl->isUnion()*/) return; // FIXME: all the access-control diagnostics are positioned on the @@ -5793,8 +5793,10 @@ Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, if (FieldClassDecl->hasIrrelevantDestructor()) continue; // The destructor for an implicit anonymous union member is never invoked. -if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) +if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) { + MarkBaseAndMemberDestructorsReferenced(Location, FieldClassDecl); continue; +} CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); // Dtor might still be missing, e.g because it's invalid. >From 9918e933eb5bde3a24148e9aeb94688ea49d3353 Mon Sep 17 00:00:00 2001 From: Maurice Heumann Date: Wed, 26 Feb 2025 14:31:47 +0100 Subject: [PATCH 2/2] Instantiate initialized field destructors --- clang/include/clang/Sema/Sema.h | 2 + clang/lib/Sema/SemaDeclCXX.cpp | 86 +++-- 2 files changed, 51 insertions(+), 37 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 476abe86cb2d2..6d3879985c6ce 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5432,6 +5432,8 @@ class Sema final : public SemaBase { void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); + void MarkFieldDestructorReferenced(SourceLocation Loc, FieldDecl *Field); + /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index ce7927dedd96b..aa1f4460718a2 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -5451,10 +5451,19 @@ bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, NumInitializers * sizeof(CXXCtorInitializer*)); Constructor->setCtorInitializers(baseOrMemberInitializers); +SourceLocation Location = Constructor->getLocation(); + +for (CXXCtorInitializer *Initializer : Info.AllToInit) { + FieldDecl *Field = Initializer->getAnyMember(); + if (Field) { +MarkFieldDestructorReferenced(Location, Field); + } +} + // Constructors implicitly reference the base and member // destructors. -MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), - Constructor->getParent()); +// MarkBaseAndMemberDestructorsReferenced(Location, +// Constructor->getParent()); } return HadError; @@ -5759,6 +5768,43 @@ void Sema::ActOnMemInitializers(Decl *ConstructorDecl, DiagnoseUninitializedFields(*this, Constructor); } + +void Sema::MarkFieldDestructorReferenced(SourceLocation Location, + FieldDecl *Field) { + if (Field->isInvalidDecl()) +return; + + // Don't destroy incomplete or zero-length arrays. + if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) +return; + + QualType FieldType = Context.getBaseElementType(Field->getType()); + + const RecordType *RT = FieldType->getAs(); + if (!RT) +return; + + CXXRecordDecl *FieldClassDecl = cast(RT->getDecl()); + if (FieldClassDecl->isInvalidDecl()) +return; + if (FieldClassDecl->hasIrrelevantDestructor()) +return; + // The destructor for an implicit anonymous union member is never invoked. + if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) +return; + + CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); + // Dtor might still be missing, e.g because it's invalid. + if (!Dtor) +return; + CheckDestructorAccess(Field->getLocation(), Dtor, +
[clang] [Driver] Teach Barmetal toolchain about GCC installation(1/3) (PR #121829)
@@ -110,20 +111,93 @@ static std::string computeBaseSysRoot(const Driver &D, bool IncludeTriple) { return std::string(SysRootDir); } +// GCC sysroot here means form sysroot from either --gcc-install-dir, or from +// --gcc-toolchain or if the toolchain is installed alongside clang in +// bin/../ directory if it is not explicitly specified on the +// command line through `--sysroot` option. libc here will be newlib. +std::string BareMetal::computeGCCSysRoot() const { + if (!getDriver().SysRoot.empty()) +return getDriver().SysRoot; + + SmallString<128> SysRootDir; + if (GCCInstallation.isValid()) { +StringRef LibDir = GCCInstallation.getParentLibPath(); +StringRef TripleStr = GCCInstallation.getTriple().str(); +llvm::sys::path::append(SysRootDir, LibDir, "..", TripleStr); + } else { +// Use the triple as provided to the driver. Unlike the parsed triple +// this has not been normalized to always contain every field. +llvm::sys::path::append(SysRootDir, getDriver().Dir, "..", +getDriver().getTargetTriple()); petrhosek wrote: I understand that this is copied as-is from `RISCVToolchain`, but it's quite confusing for this to be inside the method called `computeGCCSysroot` when it is not in fact a GCC sysroot, it's the sysroot installed alongside Clang. https://github.com/llvm/llvm-project/pull/121829 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] Correct lowering of `fp128` intrinsics (PR #76558)
https://github.com/tgross35 updated https://github.com/llvm/llvm-project/pull/76558 >From 31405591b5661156348ec7a45e66eb43e0ace15b Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 11 Aug 2023 22:16:01 -0400 Subject: [PATCH 1/6] [IR] Add a test for `f128` libcall lowering (nfc) `f128` intrinsic functions sometimes lower to `long double` library calls when they instead need to be `f128` versions. Add a test demonstrating current behavior. --- .../CodeGen/Generic/f128-math-lowering.ll | 328 ++ 1 file changed, 328 insertions(+) create mode 100644 llvm/test/CodeGen/Generic/f128-math-lowering.ll diff --git a/llvm/test/CodeGen/Generic/f128-math-lowering.ll b/llvm/test/CodeGen/Generic/f128-math-lowering.ll new file mode 100644 index 0..dfbd1eaeda109 --- /dev/null +++ b/llvm/test/CodeGen/Generic/f128-math-lowering.ll @@ -0,0 +1,328 @@ +; RUN: llc < %s -mtriple=aarch64-unknown-none -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=i686-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=riscv32 -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=s390x-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-S390X +; RUN: llc < %s -mtriple=x86_64-unknown -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-NOTLD +; RUN: llc < %s -mtriple=x86_64-unknown-linux-musl -verify-machineinstrs | FileCheck %s --check-prefix=CHECK-USELD +; +; REQUIRES: aarch64-registered-target +; REQUIRES: riscv-registered-target +; REQUIRES: systemz-registered-target +; REQUIRES: x86-registered-target +; +; Verify that fp128 intrinsics only lower to `long double` calls (e.g. `sinl`) +; on platforms where `f128` and `long double` have the same layout, and +; otherwise lower to `f128` versions (e.g. `sinf128`). +; +; Targets include: +; * x86, x64 (80-bit long double) +; * aarch64 (long double == f128) +; * riscv32 (long double == f64) +; * s390x (long double == f128, hardware support) +; * A couple assorted environments for x86 +; +; FIXME: only targets where long double is `f128` should be using `USELD`, all +; others need to be NOTLD. PowerPC should be added but it currently emits an +; interesting blend of both (e.g. `acosl` but `ceilf128`). + +define fp128 @test_acosf128(fp128 %a) { +; CHECK-LABEL: test_acosf128: +; CHECK-NOTLD: acosf128 +; CHECK-USELD: acosl +; CHECK-S390X: acosl +start: + %0 = tail call fp128 @llvm.acos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_asinf128(fp128 %a) { +; CHECK-LABEL: test_asinf128: +; CHECK-NOTLD: asinf128 +; CHECK-USELD: asinl +; CHECK-S390X: asinl +start: + %0 = tail call fp128 @llvm.asin.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_atanf128(fp128 %a) { +; CHECK-LABEL: test_atanf128: +; CHECK-NOTLD: atanf128 +; CHECK-USELD: atanl +; CHECK-S390X: atanl +start: + %0 = tail call fp128 @llvm.atan.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_ceilf128(fp128 %a) { +; CHECK-LABEL: test_ceilf128: +; CHECK-NOTLD: ceilf128 +; CHECK-USELD: ceill +; CHECK-S390X: ceill +start: + %0 = tail call fp128 @llvm.ceil.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_copysignf128(fp128 %a, fp128 %b) { +; copysign should always get lowered to assembly +; CHECK-LABEL: test_copysignf128: +; CHECK-NOT:copysignl +; CHECK-NOT:copysignf128 +start: + %0 = tail call fp128 @llvm.copysign.f128(fp128 %a, fp128 %b) + ret fp128 %0 +} + +define fp128 @test_cosf128(fp128 %a) { +; CHECK-LABEL: test_cosf128: +; CHECK-NOTLD: cosf128 +; CHECK-USELD: cosl +; CHECK-S390X: cosl +start: + %0 = tail call fp128 @llvm.cos.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp10f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp10f128 +; CHECK-USELD: exp10l +; CHECK-S390X: exp10l +start: + %0 = tail call fp128 @llvm.exp10.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_exp2f128(fp128 %a) { +; CHECK-LABEL: test_exp2f128: +; CHECK-NOTLD: exp2f128 +; CHECK-USELD: exp2l +; CHECK-S390X: exp2l +start: + %0 = tail call fp128 @llvm.exp2.f128(fp128 %a) + ret fp128 %0 +} + + +define fp128 @test_expf128(fp128 %a) { +; CHECK-LABEL: test_expf128: +; CHECK-NOTLD: expf128 +; CHECK-USELD: expl +; CHECK-S390X: expl +start: + %0 = tail call fp128 @llvm.exp.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_fabsf128(fp128 %a) { +; fabs should always get lowered to assembly +; CHECK-LABEL: test_fabsf128: +; CHECK-NOT:fabsl +; CHECK-NOT:fabsf128 +start: + %0 = tail call fp128 @llvm.fabs.f128(fp128 %a) + ret fp128 %0 +} + +define fp128 @test_floorf128(fp128 %a) { +; CHECK-LABEL: test
[clang] [Driver] Teach Barmetal toolchain about GCC installation(1/3) (PR #121829)
@@ -97,7 +97,8 @@ static bool findRISCVMultilibs(const Driver &D, return false; } -static std::string computeBaseSysRoot(const Driver &D, bool IncludeTriple) { +static std::string computeInstalledToolchainSysRoot(const Driver &D, petrhosek wrote: Can we avoid renaming this method? That doesn't seem to be necessary and it only creates unnecessary churn. https://github.com/llvm/llvm-project/pull/121829 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Teach Barmetal toolchain about GCC installation(1/3) (PR #121829)
@@ -110,20 +111,93 @@ static std::string computeBaseSysRoot(const Driver &D, bool IncludeTriple) { return std::string(SysRootDir); } +// GCC sysroot here means form sysroot from either --gcc-install-dir, or from +// --gcc-toolchain or if the toolchain is installed alongside clang in +// bin/../ directory if it is not explicitly specified on the +// command line through `--sysroot` option. libc here will be newlib. +std::string BareMetal::computeGCCSysRoot() const { + if (!getDriver().SysRoot.empty()) +return getDriver().SysRoot; petrhosek wrote: This check shouldn't be necessary. https://github.com/llvm/llvm-project/pull/121829 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Teach Barmetal toolchain about GCC installation(1/3) (PR #121829)
@@ -110,20 +111,93 @@ static std::string computeBaseSysRoot(const Driver &D, bool IncludeTriple) { return std::string(SysRootDir); } +// GCC sysroot here means form sysroot from either --gcc-install-dir, or from +// --gcc-toolchain or if the toolchain is installed alongside clang in +// bin/../ directory if it is not explicitly specified on the +// command line through `--sysroot` option. libc here will be newlib. +std::string BareMetal::computeGCCSysRoot() const { petrhosek wrote: I'd consider inlining this method into `computeSysRoot`, I think that would actually help with readability. https://github.com/llvm/llvm-project/pull/121829 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Add special handling of mfloat8 in initializer lists (PR #125097)
https://github.com/paulwalker-arm approved this pull request. https://github.com/llvm/llvm-project/pull/125097 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Clang: emit llvm.minnum and llvm.maxnum with nsz always (PR #113133)
arsenm wrote: We should also have new builtins for the raw minnum / maxnum intrinsics (plus elementwise) to not get the nsz https://github.com/llvm/llvm-project/pull/113133 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 741d7fa - [Clang][Sema] Add special handling of mfloat8 in initializer lists (#125097)
Author: Lukacma Date: 2025-02-27T11:32:02Z New Revision: 741d7fab4e6c00dea5a38ba202ea80e03b71c59d URL: https://github.com/llvm/llvm-project/commit/741d7fab4e6c00dea5a38ba202ea80e03b71c59d DIFF: https://github.com/llvm/llvm-project/commit/741d7fab4e6c00dea5a38ba202ea80e03b71c59d.diff LOG: [Clang][Sema] Add special handling of mfloat8 in initializer lists (#125097) This patch fixes assertion failures in clang, caused by unique properties of _mfp8 type, namely it not being either scalar or vector type and it not being either integer or float type. Added: clang/test/CodeGen/AArch64/fp8-init-list.c Modified: clang/lib/AST/ExprConstant.cpp clang/lib/Sema/SemaInit.cpp Removed: diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 6ccb6e23f8d2f..ef1d763009453 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -11172,6 +11172,11 @@ VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { QualType EltTy = VT->getElementType(); SmallVector Elements; + // MFloat8 type doesn't have constants and thus constant folding + // is impossible. + if (EltTy->isMFloat8Type()) +return false; + // The number of initializers can be less than the number of // vector elements. For OpenCL, this can be due to nested vector // initialization. For GCC compatibility, missing trailing elements diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp index 340e51adf190d..925af06894f72 100644 --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -1590,7 +1590,8 @@ void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, } else { assert((ElemType->isRecordType() || ElemType->isVectorType() || -ElemType->isOpenCLSpecificType()) && "Unexpected type"); +ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) && + "Unexpected type"); // C99 6.7.8p13: // diff --git a/clang/test/CodeGen/AArch64/fp8-init-list.c b/clang/test/CodeGen/AArch64/fp8-init-list.c new file mode 100644 index 0..8b4b31a71c46a --- /dev/null +++ b/clang/test/CodeGen/AArch64/fp8-init-list.c @@ -0,0 +1,59 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 + +// RUN: %clang_cc1-triple aarch64-none-linux-gnu -target-feature +neon -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -x c++ -triple aarch64-none-linux-gnu -target-feature +neon -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX + +// RUN: %clang_cc1-triple aarch64-none-linux-gnu -target-feature +neon -O2 -Werror -Wall -S -o /dev/null %s + +// REQUIRES: aarch64-registered-target + +#include + +// CHECK-LABEL: define dso_local <8 x i8> @vector_init_test( +// CHECK-SAME: <1 x i8> [[X:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:[[VECINIT14:%.*]] = shufflevector <1 x i8> [[X]], <1 x i8> poison, <8 x i32> zeroinitializer +// CHECK-NEXT:ret <8 x i8> [[VECINIT14]] +// +// CHECK-CXX-LABEL: define dso_local <8 x i8> @_Z16vector_init_testu6__mfp8( +// CHECK-CXX-SAME: <1 x i8> [[X:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-CXX-NEXT: [[ENTRY:.*:]] +// CHECK-CXX-NEXT:[[VECINIT14:%.*]] = shufflevector <1 x i8> [[X]], <1 x i8> poison, <8 x i32> zeroinitializer +// CHECK-CXX-NEXT:ret <8 x i8> [[VECINIT14]] +// +mfloat8x8_t vector_init_test(__mfp8 x) { + return (mfloat8x8_t) {x, x, x, x, x, x, x, x}; +} + +struct S { +__mfp8 x; +}; + +struct S s; + +// CHECK-LABEL: define dso_local void @f( +// CHECK-SAME: <1 x i8> [[X:%.*]]) local_unnamed_addr #[[ATTR1:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:store <1 x i8> [[X]], ptr @s, align 1, !tbaa [[TBAA2:![0-9]+]] +// CHECK-NEXT:ret void +// +// CHECK-CXX-LABEL: define dso_local void @_Z1fu6__mfp8( +// CHECK-CXX-SAME: <1 x i8> [[X:%.*]]) local_unnamed_addr #[[ATTR1:[0-9]+]] { +// CHECK-CXX-NEXT: [[ENTRY:.*:]] +// CHECK-CXX-NEXT:store <1 x i8> [[X]], ptr @s, align 1, !tbaa [[TBAA2:![0-9]+]] +// CHECK-CXX-NEXT:ret void +// +void f(__mfp8 x) { +s = (struct S){x}; +} +//. +// CHECK: [[TBAA2]] = !{[[META3:![0-9]+]], [[META3]], i64 0} +// CHECK: [[META3]] = !{!"__mfp8", [[META4:![0-9]+]], i64 0} +// CHECK: [[META4]] = !{!"omnipotent char", [[META5:![0-9]+]], i64 0} +// CHECK: [[META5]] = !{!"Simple C/C++ TBAA"} +//. +// CHECK-CXX: [[TBAA2]] = !{[[META3:![0-9]+]], [[META3]], i64 0} +// CHECK-CXX: [[META3]] = !{!"__mfp8", [[META4:![0-9]+]], i64 0} +// CHECK-CXX: [[META4]] = !{!"omnipotent char", [[META5:![0-9]+]], i64 0} +// CHECK-CXX: [[META5]] = !{!"Simple C++ TBAA"} +//. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-
[clang] [Clang][Sema] Add special handling of mfloat8 in initializer lists (PR #125097)
https://github.com/Lukacma closed https://github.com/llvm/llvm-project/pull/125097 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
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 dc79c66f2c6cc2773e38735660d8e0aaedf9702c 5bbd811547440e56eb3c2ed387833b41ce6232e3 --extensions cpp -- clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp `` View the diff from clang-format here. ``diff diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index 2667099b52..f7a19cd72d 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,8 +215,8 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; - -// FIXME: This check specifically handles `CXXNullPtrLiteralExpr`, but + +// FIXME: This check specifically handles `CXXNullPtrLiteralExpr`, but // a more general solution might be needed. if (Function->getName() == "find") { const unsigned ValueArgIndex = 2; @@ -227,7 +227,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { if (isa(ValueExpr)) return; } - + auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), `` https://github.com/llvm/llvm-project/pull/127162 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Instantiate destructors for initialized anonymous union fields (PR #128866)
https://github.com/momo5502 ready_for_review https://github.com/llvm/llvm-project/pull/128866 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
https://github.com/frasercrmck updated https://github.com/llvm/llvm-project/pull/128748 >From f827260918c81053d833db6fe81039b7c0990a2f Mon Sep 17 00:00:00 2001 From: Fraser Cormack Date: Tue, 25 Feb 2025 12:27:06 + Subject: [PATCH 1/3] [libclc] Move sqrt to CLC library This is fairly straightforward for most targets. AMDGPU provides its own implementation of sqrt for double types. This commit moves this into the implementation of CLC sqrt. It uses weak linkage on the 'default' CLC sqrt to allow AMDGPU to only override the builtin for the types it cares about. Since we don't yet have CLC ldexp, and AMDGPU prefers the builtin anyway, it also uses __builtin_ldexp. There are no changes to the codegen for any AMDGPU target. There is some minor code movement on NVIDIA targets. --- libclc/CMakeLists.txt | 1 + libclc/amdgpu/lib/SOURCES | 1 - libclc/clc/include/clc/float/definitions.h| 4 +- .../include/clc}/math/clc_sqrt.h | 10 +++-- libclc/clc/lib/amdgpu/SOURCES | 1 + .../lib/amdgpu/math/clc_sqrt_fp64.cl} | 42 +++ libclc/clc/lib/generic/SOURCES| 1 + .../lib => clc/lib/generic}/math/clc_sqrt.cl | 12 ++ .../lib/generic/math/clc_sqrt.inc}| 16 --- libclc/generic/lib/SOURCES| 1 - libclc/generic/lib/math/clc_hypot.cl | 5 ++- libclc/generic/lib/math/sqrt.cl | 8 ++-- 12 files changed, 47 insertions(+), 55 deletions(-) rename libclc/{generic/include => clc/include/clc}/math/clc_sqrt.h (60%) create mode 100644 libclc/clc/lib/amdgpu/SOURCES rename libclc/{amdgpu/lib/math/sqrt.cl => clc/lib/amdgpu/math/clc_sqrt_fp64.cl} (64%) rename libclc/{generic/lib => clc/lib/generic}/math/clc_sqrt.cl (80%) rename libclc/{generic/lib/math/clc_sqrt_impl.inc => clc/lib/generic/math/clc_sqrt.inc} (80%) diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt index fb5f3638bc4e4..8f076be1599db 100644 --- a/libclc/CMakeLists.txt +++ b/libclc/CMakeLists.txt @@ -29,6 +29,7 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS # CLC internal libraries clc/lib/generic/SOURCES; clc/lib/amdgcn/SOURCES; + clc/lib/amdgpu/SOURCES; clc/lib/clspv/SOURCES; clc/lib/spirv/SOURCES; ) diff --git a/libclc/amdgpu/lib/SOURCES b/libclc/amdgpu/lib/SOURCES index 24f099d049cd3..d7782a2ae14dc 100644 --- a/libclc/amdgpu/lib/SOURCES +++ b/libclc/amdgpu/lib/SOURCES @@ -10,4 +10,3 @@ math/half_log2.cl math/half_recip.cl math/half_rsqrt.cl math/half_sqrt.cl -math/sqrt.cl diff --git a/libclc/clc/include/clc/float/definitions.h b/libclc/clc/include/clc/float/definitions.h index 618d02ab1c090..82ae90155be1d 100644 --- a/libclc/clc/include/clc/float/definitions.h +++ b/libclc/clc/include/clc/float/definitions.h @@ -1,7 +1,6 @@ #define MAXFLOAT 0x1.fep127f #define HUGE_VALF __builtin_huge_valf() #define INFINITY __builtin_inff() -#define NAN __builtin_nanf("") #define FLT_DIG 6 #define FLT_MANT_DIG 24 @@ -13,6 +12,7 @@ #define FLT_MAX MAXFLOAT #define FLT_MIN 0x1.0p-126f #define FLT_EPSILON 0x1.0p-23f +#define FLT_NAN __builtin_nanf("") #define FP_ILOGB0 (-2147483647 - 1) #define FP_ILOGBNAN 2147483647 @@ -46,6 +46,7 @@ #define DBL_MAX 0x1.fp1023 #define DBL_MIN 0x1.0p-1022 #define DBL_EPSILON 0x1.0p-52 +#define DBL_NAN __builtin_nan("") #define M_E 0x1.5bf0a8b145769p+1 #define M_LOG2E 0x1.71547652b82fep+0 @@ -80,6 +81,7 @@ #define HALF_MAX 0x1.ffcp15h #define HALF_MIN 0x1.0p-14h #define HALF_EPSILON 0x1.0p-10h +#define HALF_NAN __builtin_nanf16("") #define M_LOG2E_H 0x1.714p+0h diff --git a/libclc/generic/include/math/clc_sqrt.h b/libclc/clc/include/clc/math/clc_sqrt.h similarity index 60% rename from libclc/generic/include/math/clc_sqrt.h rename to libclc/clc/include/clc/math/clc_sqrt.h index 90a7c575c9bad..c16edf196d9f6 100644 --- a/libclc/generic/include/math/clc_sqrt.h +++ b/libclc/clc/include/clc/math/clc_sqrt.h @@ -1,8 +1,12 @@ -#include -#include +#ifndef __CLC_MATH_CLC_SQRT_H__ +#define __CLC_MATH_CLC_SQRT_H__ -#define __CLC_FUNCTION __clc_sqrt #define __CLC_BODY +#define __CLC_FUNCTION __clc_sqrt + #include + #undef __CLC_BODY #undef __CLC_FUNCTION + +#endif // __CLC_MATH_CLC_SQRT_H__ diff --git a/libclc/clc/lib/amdgpu/SOURCES b/libclc/clc/lib/amdgpu/SOURCES new file mode 100644 index 0..fd64a862021e8 --- /dev/null +++ b/libclc/clc/lib/amdgpu/SOURCES @@ -0,0 +1 @@ +math/clc_sqrt_fp64.cl diff --git a/libclc/amdgpu/lib/math/sqrt.cl b/libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl similarity index 64% rename from libclc/amdgpu/lib/math/sqrt.cl rename to libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl index 17d77e50d44d3..9ce48ae8b3122 100644 --- a/libclc/amdgpu/lib/math/sqrt.cl +++ b/libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl @@ -20,52 +20,42 @@ * THE SOFTWARE. */ -#include "math/clc_sqrt.h" -#include #include - -_CLC_DEFINE_UNARY_BUILTIN(float, s
[clang] [Sema] Instantiate destructors for initialized anonymous union fields (PR #128866)
https://github.com/momo5502 edited https://github.com/llvm/llvm-project/pull/128866 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Instantiate destructors for initialized anonymous union fields (PR #128866)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Maurice Heumann (momo5502) Changes Initializing fields, that are part of an anonymous union, in a constructor, requires their destructors to be instantiated. This fixes #93251 --- Full diff: https://github.com/llvm/llvm-project/pull/128866.diff 3 Files Affected: - (modified) clang/include/clang/Sema/Sema.h (+2) - (modified) clang/lib/Sema/SemaDeclCXX.cpp (+52-35) - (added) clang/test/SemaCXX/union-member-destructor.cpp (+14) ``diff diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 476abe86cb2d2..6d3879985c6ce 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5432,6 +5432,8 @@ class Sema final : public SemaBase { void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); + void MarkFieldDestructorReferenced(SourceLocation Loc, FieldDecl *Field); + /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index 664d48ccbc382..842c4a866fc88 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -5451,10 +5451,23 @@ bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, NumInitializers * sizeof(CXXCtorInitializer*)); Constructor->setCtorInitializers(baseOrMemberInitializers); +SourceLocation Location = Constructor->getLocation(); + +for (CXXCtorInitializer *Initializer : Info.AllToInit) { + FieldDecl *Field = Initializer->getAnyMember(); + if (!Field) +continue; + + RecordDecl *FieldRecordDecl = Field->getParent(); + if (!FieldRecordDecl->isUnion() || + !FieldRecordDecl->isAnonymousStructOrUnion()) +continue; + + MarkFieldDestructorReferenced(Location, Field); +} // Constructors implicitly reference the base and member // destructors. -MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), - Constructor->getParent()); +MarkBaseAndMemberDestructorsReferenced(Location, Constructor->getParent()); } return HadError; @@ -5759,6 +5772,42 @@ void Sema::ActOnMemInitializers(Decl *ConstructorDecl, DiagnoseUninitializedFields(*this, Constructor); } +void Sema::MarkFieldDestructorReferenced(SourceLocation Location, + FieldDecl *Field) { + if (Field->isInvalidDecl()) +return; + + // Don't destroy incomplete or zero-length arrays. + if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) +return; + + QualType FieldType = Context.getBaseElementType(Field->getType()); + + const RecordType *RT = FieldType->getAs(); + if (!RT) +return; + + CXXRecordDecl *FieldClassDecl = cast(RT->getDecl()); + if (FieldClassDecl->isInvalidDecl()) +return; + if (FieldClassDecl->hasIrrelevantDestructor()) +return; + // The destructor for an implicit anonymous union member is never invoked. + if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) +return; + + CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); + // Dtor might still be missing, e.g because it's invalid. + if (!Dtor) +return; + CheckDestructorAccess(Field->getLocation(), Dtor, +PDiag(diag::err_access_dtor_field) +<< Field->getDeclName() << FieldType); + + MarkFunctionReferenced(Location, Dtor); + DiagnoseUseOfDecl(Dtor, Location); +} + void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl) { @@ -5774,39 +5823,7 @@ Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, // Non-static data members. for (auto *Field : ClassDecl->fields()) { -if (Field->isInvalidDecl()) - continue; - -// Don't destroy incomplete or zero-length arrays. -if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) - continue; - -QualType FieldType = Context.getBaseElementType(Field->getType()); - -const RecordType* RT = FieldType->getAs(); -if (!RT) - continue; - -CXXRecordDecl *FieldClassDecl = cast(RT->getDecl()); -if (FieldClassDecl->isInvalidDecl()) - continue; -if (FieldClassDecl->hasIrrelevantDestructor()) - continue; -// The destructor for an implicit anonymous union member is never invoked. -if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) - continue; - -CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); -// Dtor might still be missing, e.g because it's invalid. -if (!Dtor) - continue;
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
@@ -185,13 +185,11 @@ class CheckerManager { StringRef OptionName, StringRef ExpectedValueDesc) const; - using CheckerRef = CheckerBase *; using CheckerTag = const void *; - using CheckerDtor = CheckerFn; -//===--===// -// Checker registration. -//===--===// + //===--===// + // Checker registration. + //===--===// NagyDonat wrote: I think I'll indent this comment and the other analogous headings to satisfy `git-clang-format`. I don't want to remove them because I feel that visible headers like this are _very_ useful when I want to quickly understand the architecture of a large cumbersome class. https://github.com/llvm/llvm-project/pull/128887 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
@@ -21,19 +21,17 @@ */ #if __CLC_FPSIZE == 64 -#define __CLC_NAN __builtin_nan("") -#define ZERO 0.0 +#define __CLC_NAN DBL_NAN #elif __CLC_FPSIZE == 32 -#define __CLC_NAN NAN -#define ZERO 0.0f +#define __CLC_NAN FLT_NAN #elif __CLC_FPSIZE == 16 -#define __CLC_NAN (half)NAN -#define ZERO 0.0h +#define __CLC_NAN HALF_NAN #endif -_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE __clc_sqrt(__CLC_GENTYPE val) { - return val < ZERO ? __CLC_NAN : __clc_llvm_intr_sqrt(val); +__attribute__((weak)) _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE +__clc_sqrt(__CLC_GENTYPE val) { + return val < __CLC_FP_LIT(0.0) ? (__CLC_GENTYPE)__CLC_NAN + : __builtin_elementwise_sqrt(val); frasercrmck wrote: Removed the pre-filtering. Will update the PR description https://github.com/llvm/llvm-project/pull/128748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
https://github.com/frasercrmck edited https://github.com/llvm/llvm-project/pull/128748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
https://github.com/arsenm approved this pull request. https://github.com/llvm/llvm-project/pull/128748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] use constant evaluation context for constexpr if conditions (PR #123667)
@@ -2203,8 +2203,18 @@ Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, return ParseCXXCondition(nullptr, Loc, CK, MissingOK); } -// Parse the expression. -ExprResult Expr = ParseExpression(); // expression +ExprResult Expr; +{ + EnterExpressionEvaluationContext Eval( + Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated, + /*LambdaContextDecl=*/nullptr, + /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other, + /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf); + + // Parse the expression. + Expr = ParseExpression(); // expression +} zyn0217 wrote: ```suggestion ExprResult Expr = [&] { EnterExpressionEvaluationContext Eval( Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated, /*LambdaContextDecl=*/nullptr, /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other, /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf); // Parse the expression. return ParseExpression(); // expression }(); ``` https://github.com/llvm/llvm-project/pull/123667 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
https://github.com/frasercrmck edited https://github.com/llvm/llvm-project/pull/128748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 556e4db - [clang-tidy] Fix performance-move-const-arg false negative in ternary… (#128402)
Author: David Rivera Date: 2025-02-27T19:35:10+08:00 New Revision: 556e4dbdcdfc88bc52b43324c4b3af0100c75cc4 URL: https://github.com/llvm/llvm-project/commit/556e4dbdcdfc88bc52b43324c4b3af0100c75cc4 DIFF: https://github.com/llvm/llvm-project/commit/556e4dbdcdfc88bc52b43324c4b3af0100c75cc4.diff LOG: [clang-tidy] Fix performance-move-const-arg false negative in ternary… (#128402) This PR aims to fix `performance-move-const-arg` #126515 ## Changes Enhanced the `performance-move-arg` check in Clang-Tidy to detect cases where `std::move` is used in **ternary operator expressions which was not being matched therefore being tagged as a false negative** ## Testing - A new mock class has been where the changes have been tested & all tests pass I'd appreciate any feedback since this is my first time contributing to LLVM. Added: Modified: clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/checkers/performance/move-const-arg.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp b/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp index 421ce003975bc..703ad162f99cf 100644 --- a/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp @@ -44,6 +44,10 @@ void MoveConstArgCheck::registerMatchers(MatchFinder *Finder) { unless(isInTemplateInstantiation())) .bind("call-move"); + // Match ternary expressions where either branch contains std::move + auto TernaryWithMoveMatcher = + conditionalOperator(hasDescendant(MoveCallMatcher)); + Finder->addMatcher( expr(anyOf( castExpr(hasSourceExpression(MoveCallMatcher)), @@ -58,13 +62,15 @@ void MoveConstArgCheck::registerMatchers(MatchFinder *Finder) { qualType(rValueReferenceType()).bind("invocation-parm-type"); // Matches respective ParmVarDecl for a CallExpr or CXXConstructExpr. auto ArgumentWithParamMatcher = forEachArgumentWithParam( - MoveCallMatcher, parmVarDecl(anyOf(hasType(ConstTypeParmMatcher), - hasType(RValueTypeParmMatcher))) - .bind("invocation-parm")); + anyOf(MoveCallMatcher, TernaryWithMoveMatcher), + parmVarDecl( + anyOf(hasType(ConstTypeParmMatcher), hasType(RValueTypeParmMatcher))) + .bind("invocation-parm")); // Matches respective types of arguments for a CallExpr or CXXConstructExpr // and it works on calls through function pointers as well. auto ArgumentWithParamTypeMatcher = forEachArgumentWithParamType( - MoveCallMatcher, anyOf(ConstTypeParmMatcher, RValueTypeParmMatcher)); + anyOf(MoveCallMatcher, TernaryWithMoveMatcher), + anyOf(ConstTypeParmMatcher, RValueTypeParmMatcher)); Finder->addMatcher( invocation(anyOf(ArgumentWithParamMatcher, ArgumentWithParamTypeMatcher)) diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 2dcefa2ddec83..b87ea491b3ad1 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -120,6 +120,10 @@ Changes in existing checks tolerating fix-it breaking compilation when functions is used as pointers to avoid matching usage of functions within the current compilation unit. +- Improved :doc:`performance-move-const-arg + ` check by fixing false negatives + on ternary operators calling ``std::move``. + Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/move-const-arg.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/move-const-arg.cpp index 8e325b0ae6ca3..e616cbe78bc3a 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/performance/move-const-arg.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/performance/move-const-arg.cpp @@ -560,3 +560,26 @@ struct Result { // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: passing result of std::move() as a const reference argument; no move will actually happen [performance-move-const-arg] }; } // namespace GH111450 + +namespace GH126515 { + +struct TernaryMoveCall { +TernaryMoveCall(); +TernaryMoveCall(const TernaryMoveCall&); +TernaryMoveCall operator=(const TernaryMoveCall&); + +void TernaryCheckTriviallyCopyable(const char * c) {} + +void testTernaryMove() { + TernaryMoveCall t1; + TernaryMoveCall other(false ? TernaryMoveCall() : TernaryMoveCall(std::move(t1)) ); + // CHECK-MESSAGES: :[[@LINE-1]]:69: warning: passing result of std::move() as a const reference argument; no move will actually happen [performance-move-const-arg] + // CHECK-MESSAGES: :[[@LINE-11]]:8: note: 'TernaryMoveCall' is not move assignable/constructible + + const char* a = "a"; + TernaryCheckTriviallyCo
[clang-tools-extra] [clang-tidy] Fix performance-move-const-arg false negative in ternary… (PR #128402)
https://github.com/HerrCai0907 closed https://github.com/llvm/llvm-project/pull/128402 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Clang: emit llvm.minnum and llvm.maxnum with nsz always (PR #113133)
arsenm wrote: > nsz is missing for `__builtin_elementwise_min`. I am working on it. I'm not sure that's a good idea. For fmin/fmax it seems OK, but this doesn't take the libm name https://github.com/llvm/llvm-project/pull/113133 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 7b263fa - [CLANG]Update svget, svset, svcreate, svundef to have FP8 variants (#126754)
Author: Virginia Cangelosi Date: 2025-02-27T11:36:08Z New Revision: 7b263faf165df7dc647acae435cf9c47bdee4d1f URL: https://github.com/llvm/llvm-project/commit/7b263faf165df7dc647acae435cf9c47bdee4d1f DIFF: https://github.com/llvm/llvm-project/commit/7b263faf165df7dc647acae435cf9c47bdee4d1f.diff LOG: [CLANG]Update svget, svset, svcreate, svundef to have FP8 variants (#126754) This adds FP8 variants to svget, svset, svcreate and svundef under arm_sve.td Added: Modified: clang/include/clang/Basic/arm_sve.td clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_create2.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_create3.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_create4.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_get2.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_get3.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_get4.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_set2.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_set3.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_set4.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_undef.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_undef2.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_undef3.c clang/test/CodeGen/AArch64/sve-intrinsics/acle_sve_undef4.c Removed: diff --git a/clang/include/clang/Basic/arm_sve.td b/clang/include/clang/Basic/arm_sve.td index b20383e72e66a..3afbba51bd138 100644 --- a/clang/include/clang/Basic/arm_sve.td +++ b/clang/include/clang/Basic/arm_sve.td @@ -1303,14 +1303,14 @@ def SVZIP2Q_BF16 : SInst<"svzip2q[_{d}]", "ddd", "b", MergeNone, "aarc // Vector creation -def SVUNDEF_1 : SInst<"svundef_{d}", "dv", "csilUcUsUiUlhfd", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; -def SVUNDEF_2 : SInst<"svundef2_{d}", "2v", "csilUcUsUiUlhfd", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; -def SVUNDEF_3 : SInst<"svundef3_{d}", "3v", "csilUcUsUiUlhfd", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; -def SVUNDEF_4 : SInst<"svundef4_{d}", "4v", "csilUcUsUiUlhfd", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; +def SVUNDEF_1 : SInst<"svundef_{d}", "dv", "csilUcUsUiUlhfdm", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; +def SVUNDEF_2 : SInst<"svundef2_{d}", "2v", "csilUcUsUiUlhfdm", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; +def SVUNDEF_3 : SInst<"svundef3_{d}", "3v", "csilUcUsUiUlhfdm", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; +def SVUNDEF_4 : SInst<"svundef4_{d}", "4v", "csilUcUsUiUlhfdm", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; -def SVCREATE_2 : SInst<"svcreate2[_{d}]", "2dd", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; -def SVCREATE_3 : SInst<"svcreate3[_{d}]", "3ddd", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; -def SVCREATE_4 : SInst<"svcreate4[_{d}]", "4", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; +def SVCREATE_2 : SInst<"svcreate2[_{d}]", "2dd", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; +def SVCREATE_3 : SInst<"svcreate3[_{d}]", "3ddd", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; +def SVCREATE_4 : SInst<"svcreate4[_{d}]", "4", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleCreate, VerifyRuntimeMode]>; let SVETargetGuard = "sve,bf16", SMETargetGuard = "sme,bf16" in { def SVUNDEF_1_BF16 : SInst<"svundef_{d}", "dv", "b", MergeNone, "", [IsUndef, VerifyRuntimeMode]>; @@ -1330,13 +1330,13 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = "sme2" in { // Vector insertion and extraction -def SVGET_2 : SInst<"svget2[_{d}]", "d2i", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_1>]>; -def SVGET_3 : SInst<"svget3[_{d}]", "d3i", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_2>]>; -def SVGET_4 : SInst<"svget4[_{d}]", "d4i", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_3>]>; +def SVGET_2 : SInst<"svget2[_{d}]", "d2i", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_1>]>; +def SVGET_3 : SInst<"svget3[_{d}]", "d3i", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_2>]>; +def SVGET_4 : SInst<"svget4[_{d}]", "d4i", "csilUcUsUiUlhfdm", MergeNone, "", [IsTupleGet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_3>]>; -def SVSET_2 : SInst<"svset2[_{d}]", "22id", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleSet, VerifyRuntimeMode], [ImmCheck<1, ImmCheck0_1>]>; -def SVSET_3 : SInst<"svset3[_{d}]", "33id", "csilUcUsUiUlhfd", MergeNone, "", [IsTupleSet, VerifyRuntimeMo
[clang] [CLANG]Update svget, svset, svcreate, svundef to have FP8 variants (PR #126754)
https://github.com/Lukacma closed https://github.com/llvm/llvm-project/pull/126754 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix performance-move-const-arg false negative in ternary… (PR #128402)
github-actions[bot] wrote: @RiverDave Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/128402 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 56762b7 - [clang-tidy] Add new check bugprone-unintended-char-ostream-output (#127720)
Author: Congcong Cai Date: 2025-02-27T19:36:24+08:00 New Revision: 56762b7ace0596404e5ae271f278cf7540b374f2 URL: https://github.com/llvm/llvm-project/commit/56762b7ace0596404e5ae271f278cf7540b374f2 DIFF: https://github.com/llvm/llvm-project/commit/56762b7ace0596404e5ae271f278cf7540b374f2.diff LOG: [clang-tidy] Add new check bugprone-unintended-char-ostream-output (#127720) It wants to find unintended character output from `uint8_t` and `int8_t` to an ostream. e.g. ```c++ uint8_t v = 9; std::cout << v; ``` - Co-authored-by: whisperity Added: clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-cast-type.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp Modified: clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/docs/clang-tidy/checks/list.rst Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index c5f0b5b28418f..0a3376949b6e5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -90,6 +90,7 @@ #include "UndelegatedConstructorCheck.h" #include "UnhandledExceptionAtNewCheck.h" #include "UnhandledSelfAssignmentCheck.h" +#include "UnintendedCharOstreamOutputCheck.h" #include "UniquePtrArrayMismatchCheck.h" #include "UnsafeFunctionsCheck.h" #include "UnusedLocalNonTrivialVariableCheck.h" @@ -147,6 +148,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-incorrect-enable-if"); CheckFactories.registerCheck( "bugprone-incorrect-enable-shared-from-this"); +CheckFactories.registerCheck( +"bugprone-unintended-char-ostream-output"); CheckFactories.registerCheck( "bugprone-return-const-ref-from-parameter"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index cad6b456fc268..dab139b77c770 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -29,6 +29,7 @@ add_clang_library(clangTidyBugproneModule STATIC InaccurateEraseCheck.cpp IncorrectEnableIfCheck.cpp IncorrectEnableSharedFromThisCheck.cpp + UnintendedCharOstreamOutputCheck.cpp ReturnConstRefFromParameterCheck.cpp SuspiciousStringviewDataUsageCheck.cpp SwitchMissingDefaultCaseCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp new file mode 100644 index 0..7250e4ccb8c69 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp @@ -0,0 +1,91 @@ +//===--- UnintendedCharOstreamOutputCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnintendedCharOstreamOutputCheck.h" +#include "clang/AST/Type.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { + +// check if the type is unsigned char or signed char +AST_MATCHER(Type, isNumericChar) { + return Node.isSpecificBuiltinType(BuiltinType::SChar) || + Node.isSpecificBuiltinType(BuiltinType::UChar); +} + +// check if the type is char +AST_MATCHER(Type, isChar) { + return Node.isSpecificBuiltinType(BuiltinType::Char_S) || + Node.isSpecificBuiltinType(BuiltinType::Char_U); +} + +} // namespace + +UnintendedCharOstreamOutputCheck::UnintendedCharOstreamOutputCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")) { +} +void UnintendedCharOstreamOutputCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + if (CastTypeName.has_value()) +Options.store(Opts, "CastTypeName", CastTypeName.value()); +} + +void UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) { + auto BasicOstream = + cxxRecordDecl(hasName("::std:
[clang-tools-extra] [clang-tidy] Add new check bugprone-unintended-char-ostream-output (PR #127720)
https://github.com/HerrCai0907 closed https://github.com/llvm/llvm-project/pull/127720 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Propagate qualifiers during derived-to-base conversion (PR #127824)
https://github.com/antoniofrighetto updated https://github.com/llvm/llvm-project/pull/127824 >From aebd5455e9cf583b9f5a29c68d5217f49c7a49b5 Mon Sep 17 00:00:00 2001 From: Antonio Frighetto Date: Wed, 19 Feb 2025 16:47:18 +0100 Subject: [PATCH 1/3] [clang][Sema] Propagate qualifiers during derived-to-base conversion When accessing a field member through a derived-to-base conversion, ensure qualifiers are propagated to the base class subobject. Fixes: https://github.com/llvm/llvm-project/issues/127683. --- clang/docs/ReleaseNotes.rst | 2 ++ clang/lib/Sema/SemaExpr.cpp | 6 ++-- clang/test/CodeGenCXX/derived-to-base.cpp | 25 ++ .../SemaCXX/derived-to-base-cv-qualifiers.cpp | 34 +++ 4 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 clang/test/SemaCXX/derived-to-base-cv-qualifiers.cpp diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 62a64ff57599d..c96c79c8e6d6c 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -171,6 +171,8 @@ Bug Fixes to C++ Support - The initialization kind of elements of structured bindings direct-list-initialized from an array is corrected to direct-initialization. - Clang no longer crashes when a coroutine is declared ``[[noreturn]]``. (#GH127327) +- Clang was previously coalescing volatile writes to members of volatile base class subobjects. + The issue has been addressed by propagating qualifiers during derived-to-base conversions in the AST. (#GH127824) Bug Fixes to AST Handling ^ diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index fad15bf95c415..c4d18609316ab 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -3107,8 +3107,10 @@ Sema::PerformObjectMemberConversion(Expr *From, /*IgnoreAccess=*/true)) return ExprError(); - return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, - VK, &BasePath); + DestType = Context.getQualifiedType(DestType, FromType.getQualifiers()); + + return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK, + &BasePath); } bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, diff --git a/clang/test/CodeGenCXX/derived-to-base.cpp b/clang/test/CodeGenCXX/derived-to-base.cpp index c8dbd5bf5cb05..c09a12b728bbb 100644 --- a/clang/test/CodeGenCXX/derived-to-base.cpp +++ b/clang/test/CodeGenCXX/derived-to-base.cpp @@ -46,4 +46,29 @@ namespace test3 { } } +// Ensure volatile is preserved during derived-to-base conversion. +namespace PR127683 { + +struct Base { + int Val; +}; + +struct Derived : Base { }; + +volatile Derived Obj; + +// CHECK-LABEL: define void @_ZN8PR12768319test_volatile_storeEv() +// CHECK: store volatile i32 0, ptr @_ZN8PR1276833ObjE, align 4 +void test_volatile_store() { + Obj.Val = 0; +} + +// CHECK-LABEL: define void @_ZN8PR12768318test_volatile_loadEv() +// CHECK: %0 = load volatile i32, ptr @_ZN8PR1276833ObjE, align 4 +void test_volatile_load() { + [[maybe_unused]] int Val = Obj.Val; +} + +} + // CHECK: attributes [[NUW]] = { mustprogress noinline nounwind{{.*}} } diff --git a/clang/test/SemaCXX/derived-to-base-cv-qualifiers.cpp b/clang/test/SemaCXX/derived-to-base-cv-qualifiers.cpp new file mode 100644 index 0..02a5bf8f6cecf --- /dev/null +++ b/clang/test/SemaCXX/derived-to-base-cv-qualifiers.cpp @@ -0,0 +1,34 @@ +// RUN: %clang_cc1 -std=c++20 -fsyntax-only -ast-dump %s | FileCheck %s + +// Ensure volatile is preserved during derived-to-base conversion. +namespace PR127683 { + +struct Base { + int Val; +}; + +struct Derived : Base { }; + +volatile Derived Obj; + +// CHECK: |-FunctionDecl {{.*}} test_volatile_store 'void ()' +// CHECK-NEXT: `-CompoundStmt {{.*}} +// CHECK-NEXT: `-BinaryOperator {{.*}} 'volatile int' lvalue '=' +// CHECK-NEXT: |-MemberExpr {{.*}} 'volatile int' lvalue .Val +// CHECK-NEXT: | `-ImplicitCastExpr {{.*}} 'volatile PR127683::Base' lvalue +void test_volatile_store() { + Obj.Val = 0; +} + +// CHECK: `-FunctionDecl {{.*}} test_volatile_load 'void ()' +// CHECK-NEXT: `-CompoundStmt {{.*}} +// CHECK-NEXT: `-DeclStmt {{.*}} +// CHECK-NEXT: `-VarDecl {{.*}} Val 'int' cinit +// CHECK-NEXT: |-ImplicitCastExpr {{.*}} 'int' +// CHECK-NEXT: | `-MemberExpr {{.*}} 'volatile int' lvalue .Val +// CHECK-NEXT: | `-ImplicitCastExpr {{.*}} 'volatile PR127683::Base' lvalue +void test_volatile_load() { + [[maybe_unused]] int Val = Obj.Val; +} + +} >From 8646973726cc1639794f42f696e8d8af27c4bfa0 Mon Sep 17 00:00:00 2001 From: Antonio Frighetto Date: Sat, 22 Feb 2025 16:42:36 +0100 Subject: [PATCH 2/3] !fixup fix ci issue --- clang/lib/Sema/SemaExpr.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaExpr.c
[clang] [clang][Sema] Propagate qualifiers during derived-to-base conversion (PR #127824)
@@ -3107,8 +3107,12 @@ Sema::PerformObjectMemberConversion(Expr *From, /*IgnoreAccess=*/true)) return ExprError(); - return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, - VK, &BasePath); + Qualifiers FromTypeQuals = FromType.getQualifiers(); antoniofrighetto wrote: Added, thanks! https://github.com/llvm/llvm-project/pull/127824 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clang-tidy] fix fp when modifying variant by ``operator[]`` with template in parameters (PR #128407)
HerrCai0907 wrote: ping https://github.com/llvm/llvm-project/pull/128407 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
https://github.com/ilya-biryukov commented: I had another round, left a few more comments, mostly NITs. I feel we should definitely get rid of `getQualifiedNameAsString` calls, though. There's a few more lines left, I'll get to them soon. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1505,23 +1741,51 @@ class DataInvocationGadget : public WarningGadget { const ExplicitCastExpr *Op; public: - DataInvocationGadget(const MatchFinder::MatchResult &Result) + DataInvocationGadget(const MatchResult &Result) : WarningGadget(Kind::DataInvocation), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::DataInvocation; } - static Matcher matcher() { + static bool checkCallExpr(const CXXMemberCallExpr *call) { ilya-biryukov wrote: NITS: - let's keep this function private - let's rename to something a bit more descriptive, e.g. `isDataFunction` https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1561,56 +1825,70 @@ class UnsafeLibcFunctionCallGadget : public WarningGadget { } WarnedFunKind = OTHERS; public: - UnsafeLibcFunctionCallGadget(const MatchFinder::MatchResult &Result) + UnsafeLibcFunctionCallGadget(const MatchResult &Result) : WarningGadget(Kind::UnsafeLibcFunctionCall), -Call(Result.Nodes.getNodeAs(Tag)) { -if (Result.Nodes.getNodeAs(UnsafeSprintfTag)) +Call(Result.getNodeAs(Tag)) { +if (Result.getNodeAs(UnsafeSprintfTag)) WarnedFunKind = SPRINTF; -else if (auto *E = Result.Nodes.getNodeAs(UnsafeStringTag)) { +else if (auto *E = Result.getNodeAs(UnsafeStringTag)) { WarnedFunKind = STRING; UnsafeArg = E; -} else if (Result.Nodes.getNodeAs(UnsafeSizedByTag)) { +} else if (Result.getNodeAs(UnsafeSizedByTag)) { WarnedFunKind = SIZED_BY; UnsafeArg = Call->getArg(0); -} else if (Result.Nodes.getNodeAs(UnsafeVaListTag)) +} else if (Result.getNodeAs(UnsafeVaListTag)) WarnedFunKind = VA_LIST; } - static Matcher matcher(const UnsafeBufferUsageHandler *Handler) { ilya-biryukov wrote: Note to self: review this. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1505,23 +1741,51 @@ class DataInvocationGadget : public WarningGadget { const ExplicitCastExpr *Op; public: - DataInvocationGadget(const MatchFinder::MatchResult &Result) + DataInvocationGadget(const MatchResult &Result) : WarningGadget(Kind::DataInvocation), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::DataInvocation; } - static Matcher matcher() { + static bool checkCallExpr(const CXXMemberCallExpr *call) { +if (!call) + return false; +auto *callee = call->getDirectCallee(); +if (!callee || !isa(callee)) + return false; +auto *method = cast(callee); +if (method->getNameAsString() == "data" && +(method->getParent()->getQualifiedNameAsString() == "std::span" || + method->getParent()->getQualifiedNameAsString() == "std::array" || + method->getParent()->getQualifiedNameAsString() == "std::vector")) + return true; +return false; + } -Matcher callExpr = cxxMemberCallExpr(callee( -cxxMethodDecl(hasName("data"), - ofClass(anyOf(hasName("std::span"), hasName("std::array"), -hasName("std::vector")); -return stmt( -explicitCastExpr(anyOf(has(callExpr), has(parenExpr(has(callExpr) -.bind(OpTag)); + static bool matches(const Stmt *S, const ASTContext &Ctx, + MatchResult &Result) { +auto *CE = dyn_cast(S); +if (!CE) + return false; +for (auto *child : CE->children()) { ilya-biryukov wrote: NIT: Use `Child` per LLVM's naming. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1711,25 +2008,38 @@ class PointerDereferenceGadget : public FixableGadget { const UnaryOperator *Op = nullptr; public: - PointerDereferenceGadget(const MatchFinder::MatchResult &Result) + PointerDereferenceGadget(const MatchResult &Result) : FixableGadget(Kind::PointerDereference), -BaseDeclRefExpr( -Result.Nodes.getNodeAs(BaseDeclRefExprTag)), -Op(Result.Nodes.getNodeAs(OperatorTag)) {} +BaseDeclRefExpr(Result.getNodeAs(BaseDeclRefExprTag)), +Op(Result.getNodeAs(OperatorTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::PointerDereference; } - static Matcher matcher() { -auto Target = -unaryOperator( -hasOperatorName("*"), -has(expr(ignoringParenImpCasts( -declRefExpr(toSupportedVariable()).bind(BaseDeclRefExprTag) -.bind(OperatorTag); - -return expr(isInUnspecifiedLvalueContext(Target)); + static bool matches(const Stmt *S, llvm::SmallVector &Results) { ilya-biryukov wrote: NIT: it's better to accept `llvm::SmallVectorImpl`, it allows to pass small vectors of arbitrary sizes from the outside. (it's a common pattern in LLVM that's useful to be aware of) https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1505,23 +1741,51 @@ class DataInvocationGadget : public WarningGadget { const ExplicitCastExpr *Op; public: - DataInvocationGadget(const MatchFinder::MatchResult &Result) + DataInvocationGadget(const MatchResult &Result) : WarningGadget(Kind::DataInvocation), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::DataInvocation; } - static Matcher matcher() { + static bool checkCallExpr(const CXXMemberCallExpr *call) { +if (!call) + return false; +auto *callee = call->getDirectCallee(); +if (!callee || !isa(callee)) + return false; +auto *method = cast(callee); +if (method->getNameAsString() == "data" && +(method->getParent()->getQualifiedNameAsString() == "std::span" || + method->getParent()->getQualifiedNameAsString() == "std::array" || + method->getParent()->getQualifiedNameAsString() == "std::vector")) + return true; +return false; + } -Matcher callExpr = cxxMemberCallExpr(callee( -cxxMethodDecl(hasName("data"), - ofClass(anyOf(hasName("std::span"), hasName("std::array"), -hasName("std::vector")); -return stmt( -explicitCastExpr(anyOf(has(callExpr), has(parenExpr(has(callExpr) -.bind(OpTag)); + static bool matches(const Stmt *S, const ASTContext &Ctx, + MatchResult &Result) { +auto *CE = dyn_cast(S); +if (!CE) + return false; +for (auto *child : CE->children()) { + if (auto *MCE = dyn_cast(child); + MCE && checkCallExpr(MCE)) { +Result.addNode(OpTag, DynTypedNode::create(*CE)); +return true; + } + if (auto *paren = dyn_cast(child)) { ilya-biryukov wrote: `ParenExpr` always has a single child, just call `getSubExpr`. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1636,24 +1914,33 @@ class ULCArraySubscriptGadget : public FixableGadget { const ArraySubscriptExpr *Node; public: - ULCArraySubscriptGadget(const MatchFinder::MatchResult &Result) + ULCArraySubscriptGadget(const MatchResult &Result) : FixableGadget(Kind::ULCArraySubscript), -Node(Result.Nodes.getNodeAs(ULCArraySubscriptTag)) { +Node(Result.getNodeAs(ULCArraySubscriptTag)) { assert(Node != nullptr && "Expecting a non-null matching result"); } static bool classof(const Gadget *G) { return G->getKind() == Kind::ULCArraySubscript; } - static Matcher matcher() { -auto ArrayOrPtr = anyOf(hasPointerType(), hasArrayType()); -auto BaseIsArrayOrPtrDRE = hasBase( -ignoringParenImpCasts(declRefExpr(ArrayOrPtr, toSupportedVariable(; -auto Target = -arraySubscriptExpr(BaseIsArrayOrPtrDRE).bind(ULCArraySubscriptTag); - -return expr(isInUnspecifiedLvalueContext(Target)); + static bool matches(const Stmt *S, llvm::SmallVector &Results) { +bool Found = false; +findStmtsInUnspecifiedLvalueContext(S, [&Found, &Results](const Expr *E) { + const auto *ASE = dyn_cast(E); + if (!ASE) +return; + const auto *DRE = + dyn_cast(ASE->getBase()->IgnoreParenImpCasts()); + if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)) || ilya-biryukov wrote: NIT: maybe replace with ` !(hasPointerType(*DRE) || hasArrayType(*DRE))`? it has less negations and (IMO) a little easier to follow https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1505,23 +1741,51 @@ class DataInvocationGadget : public WarningGadget { const ExplicitCastExpr *Op; public: - DataInvocationGadget(const MatchFinder::MatchResult &Result) + DataInvocationGadget(const MatchResult &Result) : WarningGadget(Kind::DataInvocation), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::DataInvocation; } - static Matcher matcher() { + static bool checkCallExpr(const CXXMemberCallExpr *call) { +if (!call) + return false; +auto *callee = call->getDirectCallee(); +if (!callee || !isa(callee)) + return false; +auto *method = cast(callee); +if (method->getNameAsString() == "data" && +(method->getParent()->getQualifiedNameAsString() == "std::span" || ilya-biryukov wrote: `getQualifiedNameAsString` is a code smell as it will unnecessarily allocate memory for the string output. This code could easily be rewritten to (meta-code, but get the idea): ```cpp Parent->IsInStdNamespace() && Parent->Name in {"span", "array", "vector"} ``` Could we do that? https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1460,30 +1694,32 @@ class UnsafeBufferUsageAttrGadget : public WarningGadget { DeclUseList getClaimedVarUseSites() const override { return {}; } }; -/// A call of a constructor that performs unchecked buffer operations -/// over one of its pointer parameters, or constructs a class object that will -/// perform buffer operations that depend on the correctness of the parameters. +// A call of a constructor that performs unchecked buffer operations +// over one of its pointer parameters, or constructs a class object that will +// perform buffer operations that depend on the correctness of the parameters. class UnsafeBufferUsageCtorAttrGadget : public WarningGadget { constexpr static const char *const OpTag = "cxx_construct_expr"; const CXXConstructExpr *Op; public: - UnsafeBufferUsageCtorAttrGadget(const MatchFinder::MatchResult &Result) + UnsafeBufferUsageCtorAttrGadget(const MatchResult &Result) : WarningGadget(Kind::UnsafeBufferUsageCtorAttr), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::UnsafeBufferUsageCtorAttr; } - static Matcher matcher() { -auto HasUnsafeCtorDecl = -hasDeclaration(cxxConstructorDecl(hasAttr(attr::UnsafeBufferUsage))); -// std::span(ptr, size) ctor is handled by SpanTwoParamConstructorGadget. -auto HasTwoParamSpanCtorDecl = SpanTwoParamConstructorGadget::matcher(); -return stmt( -cxxConstructExpr(HasUnsafeCtorDecl, unless(HasTwoParamSpanCtorDecl)) -.bind(OpTag)); + static bool matches(const Stmt *S, const ASTContext &Ctx, + MatchResult &Result) { +const auto *CE = dyn_cast(S); +if (!CE || !CE->getConstructor()->hasAttr()) + return false; +MatchResult tmp; ilya-biryukov wrote: NIT: per LLVM naming style, use `Tmp`. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1460,30 +1694,32 @@ class UnsafeBufferUsageAttrGadget : public WarningGadget { DeclUseList getClaimedVarUseSites() const override { return {}; } }; -/// A call of a constructor that performs unchecked buffer operations -/// over one of its pointer parameters, or constructs a class object that will -/// perform buffer operations that depend on the correctness of the parameters. +// A call of a constructor that performs unchecked buffer operations +// over one of its pointer parameters, or constructs a class object that will +// perform buffer operations that depend on the correctness of the parameters. class UnsafeBufferUsageCtorAttrGadget : public WarningGadget { constexpr static const char *const OpTag = "cxx_construct_expr"; const CXXConstructExpr *Op; public: - UnsafeBufferUsageCtorAttrGadget(const MatchFinder::MatchResult &Result) + UnsafeBufferUsageCtorAttrGadget(const MatchResult &Result) : WarningGadget(Kind::UnsafeBufferUsageCtorAttr), -Op(Result.Nodes.getNodeAs(OpTag)) {} +Op(Result.getNodeAs(OpTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::UnsafeBufferUsageCtorAttr; } - static Matcher matcher() { -auto HasUnsafeCtorDecl = -hasDeclaration(cxxConstructorDecl(hasAttr(attr::UnsafeBufferUsage))); -// std::span(ptr, size) ctor is handled by SpanTwoParamConstructorGadget. ilya-biryukov wrote: Could you keep this comment? https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1238,27 +1413,36 @@ class SpanTwoParamConstructorGadget : public WarningGadget { const CXXConstructExpr *Ctor; // the span constructor expression public: - SpanTwoParamConstructorGadget(const MatchFinder::MatchResult &Result) + SpanTwoParamConstructorGadget(const MatchResult &Result) : WarningGadget(Kind::SpanTwoParamConstructor), -Ctor(Result.Nodes.getNodeAs( -SpanTwoParamConstructorTag)) {} +Ctor(Result.getNodeAs(SpanTwoParamConstructorTag)) {} static bool classof(const Gadget *G) { return G->getKind() == Kind::SpanTwoParamConstructor; } - static Matcher matcher() { -auto HasTwoParamSpanCtorDecl = hasDeclaration( -cxxConstructorDecl(hasDeclContext(isInStdNamespace()), hasName("span"), - parameterCountIs(2))); - -return stmt(cxxConstructExpr(HasTwoParamSpanCtorDecl, - unless(isSafeSpanTwoParamConstruct())) -.bind(SpanTwoParamConstructorTag)); + static bool matches(const Stmt *S, const ASTContext &Ctx, + MatchResult &Result) { +const auto *CE = dyn_cast(S); +if (!CE) + return false; +const auto *CDecl = CE->getConstructor(); +const auto *DCtx = CDecl->getDeclContext(); ilya-biryukov wrote: NIT: Use `getParent()` instead, it will return a `CXXRecordDecl`, will allow to avoid the cast below and is generally more readable. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
https://github.com/ilya-biryukov edited https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1901,28 +2238,37 @@ class UUCAddAssignGadget : public FixableGadget { const Expr *Offset = nullptr; public: - UUCAddAssignGadget(const MatchFinder::MatchResult &Result) + UUCAddAssignGadget(const MatchResult &Result) : FixableGadget(Kind::UUCAddAssign), -Node(Result.Nodes.getNodeAs(UUCAddAssignTag)), -Offset(Result.Nodes.getNodeAs(OffsetTag)) { +Node(Result.getNodeAs(UUCAddAssignTag)), +Offset(Result.getNodeAs(OffsetTag)) { assert(Node != nullptr && "Expecting a non-null matching result"); } static bool classof(const Gadget *G) { return G->getKind() == Kind::UUCAddAssign; } - static Matcher matcher() { -// clang-format off -return stmt(isInUnspecifiedUntypedContext(expr(ignoringImpCasts( -binaryOperator(hasOperatorName("+="), - hasLHS( -declRefExpr( - hasPointerType(), - toSupportedVariable())), - hasRHS(expr().bind(OffsetTag))) -.bind(UUCAddAssignTag); -// clang-format on + static bool matches(const Stmt *S, llvm::SmallVector &Results) { +bool Found = false; +findStmtsInUnspecifiedUntypedContext(S, [&Found, &Results](const Stmt *S) { + const auto *E = dyn_cast(S); + if (!E) +return; + const auto *BO = dyn_cast(E->IgnoreImpCasts()); + if (!BO || BO->getOpcode() != BO_AddAssign) +return; + const auto *DRE = dyn_cast(BO->getLHS()); + if (!DRE || !hasPointerType(*DRE) || !isSupportedVariable(*DRE) || + !isa(BO->getRHS())) ilya-biryukov wrote: `RHS` is always an expression, so this check is redundant. Just remove it. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
https://github.com/ilya-biryukov deleted https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] e3f5269 - [NFC] [C++20] [Modules] Add a test for no transitive changes
Author: Chuanqi Xu Date: 2025-02-27T18:51:39+08:00 New Revision: e3f52690c796baca241a6771d897adc6670a1ed8 URL: https://github.com/llvm/llvm-project/commit/e3f52690c796baca241a6771d897adc6670a1ed8 DIFF: https://github.com/llvm/llvm-project/commit/e3f52690c796baca241a6771d897adc6670a1ed8.diff LOG: [NFC] [C++20] [Modules] Add a test for no transitive changes Added: clang/test/Modules/no-transitive-source-location-change-2.cppm Modified: Removed: diff --git a/clang/test/Modules/no-transitive-source-location-change-2.cppm b/clang/test/Modules/no-transitive-source-location-change-2.cppm new file mode 100644 index 0..f16b945a04d69 --- /dev/null +++ b/clang/test/Modules/no-transitive-source-location-change-2.cppm @@ -0,0 +1,66 @@ +// Testing that adding a new line in a module interface unit won't cause the BMI +// of consuming module unit changes. +// +// RUN: rm -rf %t +// RUN: split-file %s %t +// +// RUN: %clang_cc1 -std=c++20 %t/A.part.cppm -emit-reduced-module-interface -o %t/A-part.pcm +// +// RUN: %clang_cc1 -std=c++20 %t/A.cppm -emit-reduced-module-interface -o %t/A.v0.pcm \ +// RUN: -fprebuilt-module-path=%t +// RUN: %clang_cc1 -std=c++20 %t/A.v1.cppm -emit-reduced-module-interface -o %t/A.v1.pcm \ +// RUN: -fprebuilt-module-path=%t +// +// The BMI may not be the same since the source location diff ers. +// RUN: not diff %t/A.pcm %t/A.v1.pcm &> /dev/null +// +// The BMI of B shouldn't change since all the locations remain the same. +// RUN: %clang_cc1 -std=c++20 %t/B.cppm -emit-reduced-module-interface -fmodule-file=A=%t/A.v0.pcm \ +// RUN: -o %t/B.pcm -fprebuilt-module-path=%t +// RUN: %clang_cc1 -std=c++20 %t/B.cppm -emit-reduced-module-interface -fmodule-file=A=%t/A.v1.pcm \ +// RUN: -o %t/B.v1.pcm -fprebuilt-module-path=%t +// RUN: diff %t/B.v1.pcm %t/B.pcm &> /dev/null +// +// The BMI of C may change since the locations for instantiations changes. +// RUN: %clang_cc1 -std=c++20 %t/C.cppm -emit-reduced-module-interface -fmodule-file=A=%t/A.v0.pcm \ +// RUN: -o %t/C.pcm -fprebuilt-module-path=%t +// RUN: %clang_cc1 -std=c++20 %t/C.cppm -emit-reduced-module-interface -fmodule-file=A=%t/A.v1.pcm \ +// RUN: -o %t/C.v1.pcm -fprebuilt-module-path=%t +// RUN: diff %t/C.v1.pcm %t/C.pcm &> /dev/null + +//--- A.part.cppm +export module A:part; +export template +struct C { +T func() { +return T(43); +} +}; +export int funcA() { +return 43; +} + +//--- A.cppm +export module A; +export import :part; + +//--- A.v1.cppm +export module A; + +export import :part; + +//--- B.cppm +export module B; +import A; + +export int funcB() { +return funcA(); +} + +//--- C.cppm +export module C; +import A; +export inline void testD() { +C c; +c.func(); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1636,24 +1914,33 @@ class ULCArraySubscriptGadget : public FixableGadget { const ArraySubscriptExpr *Node; public: - ULCArraySubscriptGadget(const MatchFinder::MatchResult &Result) + ULCArraySubscriptGadget(const MatchResult &Result) : FixableGadget(Kind::ULCArraySubscript), -Node(Result.Nodes.getNodeAs(ULCArraySubscriptTag)) { +Node(Result.getNodeAs(ULCArraySubscriptTag)) { assert(Node != nullptr && "Expecting a non-null matching result"); } static bool classof(const Gadget *G) { return G->getKind() == Kind::ULCArraySubscript; } - static Matcher matcher() { -auto ArrayOrPtr = anyOf(hasPointerType(), hasArrayType()); -auto BaseIsArrayOrPtrDRE = hasBase( -ignoringParenImpCasts(declRefExpr(ArrayOrPtr, toSupportedVariable(; -auto Target = -arraySubscriptExpr(BaseIsArrayOrPtrDRE).bind(ULCArraySubscriptTag); - -return expr(isInUnspecifiedLvalueContext(Target)); + static bool matches(const Stmt *S, llvm::SmallVector &Results) { +bool Found = false; +findStmtsInUnspecifiedLvalueContext(S, [&Found, &Results](const Expr *E) { + const auto *ASE = dyn_cast(E); + if (!ASE) +return; + const auto *DRE = + dyn_cast(ASE->getBase()->IgnoreParenImpCasts()); + if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)) || + !isSupportedVariable(*DRE)) +return; + MatchResult R; + R.addNode(ULCArraySubscriptTag, DynTypedNode::create(*ASE)); + Results.emplace_back(R); ilya-biryukov wrote: NIT: `std::move(R)` for efficiency. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Mark union member destructors referenced (PR #128866)
https://github.com/momo5502 updated https://github.com/llvm/llvm-project/pull/128866 >From 9234ac6c96f83977c32f2e90ebb553975dc209a5 Mon Sep 17 00:00:00 2001 From: Maurice Heumann Date: Wed, 26 Feb 2025 14:31:47 +0100 Subject: [PATCH] Instantiate destructors from initialized anonymous union fields --- clang/include/clang/Sema/Sema.h | 2 + clang/lib/Sema/SemaDeclCXX.cpp| 87 +++ .../test/SemaCXX/union-member-destructor.cpp | 14 +++ 3 files changed, 68 insertions(+), 35 deletions(-) create mode 100644 clang/test/SemaCXX/union-member-destructor.cpp diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 476abe86cb2d2..6d3879985c6ce 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5432,6 +5432,8 @@ class Sema final : public SemaBase { void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); + void MarkFieldDestructorReferenced(SourceLocation Loc, FieldDecl *Field); + /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index 664d48ccbc382..842c4a866fc88 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -5451,10 +5451,23 @@ bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, NumInitializers * sizeof(CXXCtorInitializer*)); Constructor->setCtorInitializers(baseOrMemberInitializers); +SourceLocation Location = Constructor->getLocation(); + +for (CXXCtorInitializer *Initializer : Info.AllToInit) { + FieldDecl *Field = Initializer->getAnyMember(); + if (!Field) +continue; + + RecordDecl *FieldRecordDecl = Field->getParent(); + if (!FieldRecordDecl->isUnion() || + !FieldRecordDecl->isAnonymousStructOrUnion()) +continue; + + MarkFieldDestructorReferenced(Location, Field); +} // Constructors implicitly reference the base and member // destructors. -MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), - Constructor->getParent()); +MarkBaseAndMemberDestructorsReferenced(Location, Constructor->getParent()); } return HadError; @@ -5759,6 +5772,42 @@ void Sema::ActOnMemInitializers(Decl *ConstructorDecl, DiagnoseUninitializedFields(*this, Constructor); } +void Sema::MarkFieldDestructorReferenced(SourceLocation Location, + FieldDecl *Field) { + if (Field->isInvalidDecl()) +return; + + // Don't destroy incomplete or zero-length arrays. + if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) +return; + + QualType FieldType = Context.getBaseElementType(Field->getType()); + + const RecordType *RT = FieldType->getAs(); + if (!RT) +return; + + CXXRecordDecl *FieldClassDecl = cast(RT->getDecl()); + if (FieldClassDecl->isInvalidDecl()) +return; + if (FieldClassDecl->hasIrrelevantDestructor()) +return; + // The destructor for an implicit anonymous union member is never invoked. + if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) +return; + + CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); + // Dtor might still be missing, e.g because it's invalid. + if (!Dtor) +return; + CheckDestructorAccess(Field->getLocation(), Dtor, +PDiag(diag::err_access_dtor_field) +<< Field->getDeclName() << FieldType); + + MarkFunctionReferenced(Location, Dtor); + DiagnoseUseOfDecl(Dtor, Location); +} + void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl) { @@ -5774,39 +5823,7 @@ Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, // Non-static data members. for (auto *Field : ClassDecl->fields()) { -if (Field->isInvalidDecl()) - continue; - -// Don't destroy incomplete or zero-length arrays. -if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) - continue; - -QualType FieldType = Context.getBaseElementType(Field->getType()); - -const RecordType* RT = FieldType->getAs(); -if (!RT) - continue; - -CXXRecordDecl *FieldClassDecl = cast(RT->getDecl()); -if (FieldClassDecl->isInvalidDecl()) - continue; -if (FieldClassDecl->hasIrrelevantDestructor()) - continue; -// The destructor for an implicit anonymous union member is never invoked. -if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) - continue; - -CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
[clang] [Sema] Instantiate destructors for initialized anonymous union fields (PR #128866)
https://github.com/momo5502 edited https://github.com/llvm/llvm-project/pull/128866 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Optimize -Wunsafe-buffer-usage. (PR #125492)
@@ -1460,30 +1694,32 @@ class UnsafeBufferUsageAttrGadget : public WarningGadget { DeclUseList getClaimedVarUseSites() const override { return {}; } }; -/// A call of a constructor that performs unchecked buffer operations -/// over one of its pointer parameters, or constructs a class object that will -/// perform buffer operations that depend on the correctness of the parameters. +// A call of a constructor that performs unchecked buffer operations ilya-biryukov wrote: LLVM uses Doxygen comments, so we should keep the tripple `///` to avoid changing the outputs. https://github.com/llvm/llvm-project/pull/125492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] 285b411 - [libclc] Move sqrt to CLC library (#128748)
Author: Fraser Cormack Date: 2025-02-27T12:30:24Z New Revision: 285b411e4635e8db2526d653488ee54dad2bff34 URL: https://github.com/llvm/llvm-project/commit/285b411e4635e8db2526d653488ee54dad2bff34 DIFF: https://github.com/llvm/llvm-project/commit/285b411e4635e8db2526d653488ee54dad2bff34.diff LOG: [libclc] Move sqrt to CLC library (#128748) This is fairly straightforward for most targets. We use the element-wise sqrt builtin by default. We also remove a legacy pre-filtering of the input argument, which the intrinsic now officially handles. AMDGPU provides its own implementation of sqrt for double types. This commit moves this into the implementation of CLC sqrt. It uses weak linkage on the 'default' CLC sqrt to allow AMDGPU to only override the builtin for the types it cares about. Added: libclc/clc/include/clc/math/clc_sqrt.h libclc/clc/lib/amdgpu/SOURCES libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl libclc/clc/lib/generic/math/clc_sqrt.cl libclc/clc/lib/generic/math/clc_sqrt.inc Modified: libclc/CMakeLists.txt libclc/amdgpu/lib/SOURCES libclc/clc/include/clc/float/definitions.h libclc/clc/lib/generic/SOURCES libclc/generic/lib/SOURCES libclc/generic/lib/math/clc_hypot.cl libclc/generic/lib/math/sqrt.cl Removed: libclc/amdgpu/lib/math/sqrt.cl libclc/generic/include/math/clc_sqrt.h libclc/generic/lib/math/clc_sqrt.cl libclc/generic/lib/math/clc_sqrt_impl.inc diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt index fb5f3638bc4e4..8f076be1599db 100644 --- a/libclc/CMakeLists.txt +++ b/libclc/CMakeLists.txt @@ -29,6 +29,7 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS # CLC internal libraries clc/lib/generic/SOURCES; clc/lib/amdgcn/SOURCES; + clc/lib/amdgpu/SOURCES; clc/lib/clspv/SOURCES; clc/lib/spirv/SOURCES; ) diff --git a/libclc/amdgpu/lib/SOURCES b/libclc/amdgpu/lib/SOURCES index 24f099d049cd3..d7782a2ae14dc 100644 --- a/libclc/amdgpu/lib/SOURCES +++ b/libclc/amdgpu/lib/SOURCES @@ -10,4 +10,3 @@ math/half_log2.cl math/half_recip.cl math/half_rsqrt.cl math/half_sqrt.cl -math/sqrt.cl diff --git a/libclc/clc/include/clc/float/definitions.h b/libclc/clc/include/clc/float/definitions.h index 618d02ab1c090..82ae90155be1d 100644 --- a/libclc/clc/include/clc/float/definitions.h +++ b/libclc/clc/include/clc/float/definitions.h @@ -1,7 +1,6 @@ #define MAXFLOAT 0x1.fep127f #define HUGE_VALF __builtin_huge_valf() #define INFINITY __builtin_inff() -#define NAN __builtin_nanf("") #define FLT_DIG 6 #define FLT_MANT_DIG 24 @@ -13,6 +12,7 @@ #define FLT_MAX MAXFLOAT #define FLT_MIN 0x1.0p-126f #define FLT_EPSILON 0x1.0p-23f +#define FLT_NAN __builtin_nanf("") #define FP_ILOGB0 (-2147483647 - 1) #define FP_ILOGBNAN 2147483647 @@ -46,6 +46,7 @@ #define DBL_MAX 0x1.fp1023 #define DBL_MIN 0x1.0p-1022 #define DBL_EPSILON 0x1.0p-52 +#define DBL_NAN __builtin_nan("") #define M_E 0x1.5bf0a8b145769p+1 #define M_LOG2E 0x1.71547652b82fep+0 @@ -80,6 +81,7 @@ #define HALF_MAX 0x1.ffcp15h #define HALF_MIN 0x1.0p-14h #define HALF_EPSILON 0x1.0p-10h +#define HALF_NAN __builtin_nanf16("") #define M_LOG2E_H 0x1.714p+0h diff --git a/libclc/generic/include/math/clc_sqrt.h b/libclc/clc/include/clc/math/clc_sqrt.h similarity index 60% rename from libclc/generic/include/math/clc_sqrt.h rename to libclc/clc/include/clc/math/clc_sqrt.h index 90a7c575c9bad..c16edf196d9f6 100644 --- a/libclc/generic/include/math/clc_sqrt.h +++ b/libclc/clc/include/clc/math/clc_sqrt.h @@ -1,8 +1,12 @@ -#include -#include +#ifndef __CLC_MATH_CLC_SQRT_H__ +#define __CLC_MATH_CLC_SQRT_H__ -#define __CLC_FUNCTION __clc_sqrt #define __CLC_BODY +#define __CLC_FUNCTION __clc_sqrt + #include + #undef __CLC_BODY #undef __CLC_FUNCTION + +#endif // __CLC_MATH_CLC_SQRT_H__ diff --git a/libclc/clc/lib/amdgpu/SOURCES b/libclc/clc/lib/amdgpu/SOURCES new file mode 100644 index 0..fd64a862021e8 --- /dev/null +++ b/libclc/clc/lib/amdgpu/SOURCES @@ -0,0 +1 @@ +math/clc_sqrt_fp64.cl diff --git a/libclc/amdgpu/lib/math/sqrt.cl b/libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl similarity index 64% rename from libclc/amdgpu/lib/math/sqrt.cl rename to libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl index 17d77e50d44d3..c5614659eb5ce 100644 --- a/libclc/amdgpu/lib/math/sqrt.cl +++ b/libclc/clc/lib/amdgpu/math/clc_sqrt_fp64.cl @@ -20,52 +20,43 @@ * THE SOFTWARE. */ -#include "math/clc_sqrt.h" -#include #include - -_CLC_DEFINE_UNARY_BUILTIN(float, sqrt, __clc_sqrt, float) - -#ifdef cl_khr_fp16 - -#pragma OPENCL EXTENSION cl_khr_fp16 : enable -_CLC_DEFINE_UNARY_BUILTIN(half, sqrt, __clc_sqrt, half) - -#endif +#include +#include +#include #ifdef cl_khr_fp64 #pragma OPENCL EXTENSION cl_khr_fp64 : enable #ifdef __AMDGCN__ - #define __clc_builtin_rsq __builtin_amdgcn_rsq +#define __clc_builtin_rsq __buil
[libclc] [libclc] Move sqrt to CLC library (PR #128748)
https://github.com/frasercrmck closed https://github.com/llvm/llvm-project/pull/128748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
@@ -201,24 +199,24 @@ class CheckerManager { template CHECKER *registerChecker(AT &&... Args) { CheckerTag tag = getTag(); -CheckerRef &ref = CheckerTags[tag]; -assert(!ref && "Checker already registered, use getChecker!"); - -CHECKER *checker = new CHECKER(std::forward(Args)...); -checker->Name = CurrentCheckerName; -CheckerDtors.push_back(CheckerDtor(checker, destruct)); NagyDonat wrote: Thanks for spotting this, my change indeed left `destruct` as dead code. I'm removing it in https://github.com/llvm/llvm-project/pull/128887/commits/9f4a8a8d3bf50d29e7bd67f5a9b4142bbe068abc https://github.com/llvm/llvm-project/pull/128887 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
https://github.com/NagyDonat updated https://github.com/llvm/llvm-project/pull/128887 From 76f8417b8b46e7d036d98fa92890469654158e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Wed, 26 Feb 2025 15:41:46 +0100 Subject: [PATCH 1/5] [NFC][analyzer] Simplify ownership of checker objects Previously checker objects were created by raw `new` calls, which necessitated managing and calling their destructors explicitly. This commit refactors this convoluted logic by introducing `unique_ptr`s that to manage the ownership of these objects automatically. This change can be thought of as stand-alone code quality improvement; but I also have a secondary motivation that I'm planning further changes in the checker registration/initialization process (to formalize our tradition of multi-part checker) and this commit "prepares the ground" for those changes. --- .../StaticAnalyzer/Core/CheckerManager.h | 40 +-- .../Frontend/CreateCheckerManager.cpp | 5 ++- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h index de40b96614dbc..b48a75630fe9b 100644 --- a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h @@ -185,13 +185,11 @@ class CheckerManager { StringRef OptionName, StringRef ExpectedValueDesc) const; - using CheckerRef = CheckerBase *; using CheckerTag = const void *; - using CheckerDtor = CheckerFn; -//===--===// -// Checker registration. -//===--===// + //===--===// + // Checker registration. + //===--===// /// Used to register checkers. /// All arguments are automatically passed through to the checker @@ -201,24 +199,24 @@ class CheckerManager { template CHECKER *registerChecker(AT &&... Args) { CheckerTag tag = getTag(); -CheckerRef &ref = CheckerTags[tag]; -assert(!ref && "Checker already registered, use getChecker!"); - -CHECKER *checker = new CHECKER(std::forward(Args)...); -checker->Name = CurrentCheckerName; -CheckerDtors.push_back(CheckerDtor(checker, destruct)); -CHECKER::_register(checker, *this); -ref = checker; -return checker; +std::unique_ptr &Ref = CheckerTags[tag]; +assert(!Ref && "Checker already registered, use getChecker!"); + +std::unique_ptr Checker = +std::make_unique(std::forward(Args)...); +Checker->Name = CurrentCheckerName; +CHECKER::_register(Checker.get(), *this); +Ref = std::move(Checker); +return static_cast(Ref.get()); } template CHECKER *getChecker() { -CheckerTag tag = getTag(); -assert(CheckerTags.count(tag) != 0 && - "Requested checker is not registered! Maybe you should add it as a " - "dependency in Checkers.td?"); -return static_cast(CheckerTags[tag]); +CheckerTag Tag = getTag(); +std::unique_ptr &Ref = CheckerTags[Tag]; +assert(Ref && "Requested checker is not registered! Maybe you should add it" + " as a dependency in Checkers.td?"); +return static_cast(Ref.get()); } template bool isRegisteredChecker() { @@ -622,9 +620,7 @@ class CheckerManager { template static void *getTag() { static int tag; return &tag; } - llvm::DenseMap CheckerTags; - - std::vector CheckerDtors; + llvm::DenseMap> CheckerTags; struct DeclCheckerInfo { CheckDeclFunc CheckFn; diff --git a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp index f60221ad7587e..35dd255fce898 100644 --- a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp @@ -10,6 +10,7 @@ // //===--===// +#include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" #include @@ -41,8 +42,8 @@ CheckerManager::CheckerManager(AnalyzerOptions &AOptions, } CheckerManager::~CheckerManager() { - for (const auto &CheckerDtor : CheckerDtors) -CheckerDtor(); + // This is declared here to ensure that the destructors of `CheckerBase` and + // `CheckerRegistryData` are available. } } // namespace ento From 38774503663f74ca1c8b36d7ed1b55c10f9edd5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Thu, 27 Feb 2025 14:00:10 +0100 Subject: [PATCH 2/5] Set destructor to '= default' instead of using empty body
[libclc] [libclc] Move rsqrt to the CLC library (PR #129045)
https://github.com/frasercrmck created https://github.com/llvm/llvm-project/pull/129045 This also adds missing half variants to certain targets. It also optimizes some targets' implementations to perform the operation directly in vector types, as opposed to scalarizing. >From 4efd607ca71b91847c9271740df7aab4534fe01b Mon Sep 17 00:00:00 2001 From: Fraser Cormack Date: Thu, 27 Feb 2025 12:48:25 + Subject: [PATCH 1/2] [libclc] Move rsqrt to the CLC library This also adds missing half variants to certain targets. It also optimizes some targets' implementations to perform the operation directly in vector types, as opposed to scalarizing. --- libclc/CMakeLists.txt | 1 + libclc/clc/include/clc/math/clc_rsqrt.h | 12 + libclc/clc/lib/generic/SOURCES| 1 + libclc/clc/lib/generic/math/clc_rsqrt.cl | 27 +++ libclc/clc/lib/generic/math/clc_rsqrt.inc | 4 +++ libclc/clc/lib/r600/SOURCES | 2 ++ .../clc/lib/r600/math/clc_rsqrt_override.cl | 20 ++ libclc/generic/lib/math/rsqrt.cl | 23 +++- libclc/r600/lib/SOURCES | 1 - libclc/r600/lib/math/rsqrt.cl | 22 --- 10 files changed, 71 insertions(+), 42 deletions(-) create mode 100644 libclc/clc/include/clc/math/clc_rsqrt.h create mode 100644 libclc/clc/lib/generic/math/clc_rsqrt.cl create mode 100644 libclc/clc/lib/generic/math/clc_rsqrt.inc create mode 100644 libclc/clc/lib/r600/SOURCES create mode 100644 libclc/clc/lib/r600/math/clc_rsqrt_override.cl delete mode 100644 libclc/r600/lib/math/rsqrt.cl diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt index 8f076be1599db..cc1abda7d7fce 100644 --- a/libclc/CMakeLists.txt +++ b/libclc/CMakeLists.txt @@ -31,6 +31,7 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS clc/lib/amdgcn/SOURCES; clc/lib/amdgpu/SOURCES; clc/lib/clspv/SOURCES; + clc/lib/r600/SOURCES; clc/lib/spirv/SOURCES; ) diff --git a/libclc/clc/include/clc/math/clc_rsqrt.h b/libclc/clc/include/clc/math/clc_rsqrt.h new file mode 100644 index 0..f05ef73074d26 --- /dev/null +++ b/libclc/clc/include/clc/math/clc_rsqrt.h @@ -0,0 +1,12 @@ +#ifndef __CLC_MATH_CLC_RSQRT_H__ +#define __CLC_MATH_CLC_RSQRT_H__ + +#define __CLC_BODY +#define __CLC_FUNCTION __clc_rsqrt + +#include + +#undef __CLC_BODY +#undef __CLC_FUNCTION + +#endif // __CLC_MATH_CLC_RSQRT_H__ diff --git a/libclc/clc/lib/generic/SOURCES b/libclc/clc/lib/generic/SOURCES index 97c504d21aa88..206c7c18ce1a1 100644 --- a/libclc/clc/lib/generic/SOURCES +++ b/libclc/clc/lib/generic/SOURCES @@ -33,6 +33,7 @@ math/clc_nan.cl math/clc_nextafter.cl math/clc_rint.cl math/clc_round.cl +math/clc_rsqrt.cl math/clc_sqrt.cl math/clc_sw_fma.cl math/clc_trunc.cl diff --git a/libclc/clc/lib/generic/math/clc_rsqrt.cl b/libclc/clc/lib/generic/math/clc_rsqrt.cl new file mode 100644 index 0..18282e44f6dc6 --- /dev/null +++ b/libclc/clc/lib/generic/math/clc_rsqrt.cl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2014,2015 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#define __CLC_BODY +#include diff --git a/libclc/clc/lib/generic/math/clc_rsqrt.inc b/libclc/clc/lib/generic/math/clc_rsqrt.inc new file mode 100644 index 0..a4d2146887876 --- /dev/null +++ b/libclc/clc/lib/generic/math/clc_rsqrt.inc @@ -0,0 +1,4 @@ +__attribute__((weak)) _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE +__clc_rsqrt(__CLC_GENTYPE val) { + return __CLC_FP_LIT(1.0) / __clc_sqrt(val); +} diff --git a/libclc/clc/lib/r600/SOURCES b/libclc/clc/lib/r600/SOURCES new file mode 100644 index 0..9185bcf7f390e --- /dev/null +++ b/libclc/clc/lib/r600/SOURCES @@ -0,0 +1,2 @@ +math/clc_rsqrt_override.cl + diff --git a/libclc/clc/lib/r600/math/clc_rsqrt_override.cl b/libclc/clc/lib/r600/math/cl
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
https://github.com/NagyDonat updated https://github.com/llvm/llvm-project/pull/128887 From 76f8417b8b46e7d036d98fa92890469654158e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Wed, 26 Feb 2025 15:41:46 +0100 Subject: [PATCH 1/4] [NFC][analyzer] Simplify ownership of checker objects Previously checker objects were created by raw `new` calls, which necessitated managing and calling their destructors explicitly. This commit refactors this convoluted logic by introducing `unique_ptr`s that to manage the ownership of these objects automatically. This change can be thought of as stand-alone code quality improvement; but I also have a secondary motivation that I'm planning further changes in the checker registration/initialization process (to formalize our tradition of multi-part checker) and this commit "prepares the ground" for those changes. --- .../StaticAnalyzer/Core/CheckerManager.h | 40 +-- .../Frontend/CreateCheckerManager.cpp | 5 ++- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h index de40b96614dbc..b48a75630fe9b 100644 --- a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h @@ -185,13 +185,11 @@ class CheckerManager { StringRef OptionName, StringRef ExpectedValueDesc) const; - using CheckerRef = CheckerBase *; using CheckerTag = const void *; - using CheckerDtor = CheckerFn; -//===--===// -// Checker registration. -//===--===// + //===--===// + // Checker registration. + //===--===// /// Used to register checkers. /// All arguments are automatically passed through to the checker @@ -201,24 +199,24 @@ class CheckerManager { template CHECKER *registerChecker(AT &&... Args) { CheckerTag tag = getTag(); -CheckerRef &ref = CheckerTags[tag]; -assert(!ref && "Checker already registered, use getChecker!"); - -CHECKER *checker = new CHECKER(std::forward(Args)...); -checker->Name = CurrentCheckerName; -CheckerDtors.push_back(CheckerDtor(checker, destruct)); -CHECKER::_register(checker, *this); -ref = checker; -return checker; +std::unique_ptr &Ref = CheckerTags[tag]; +assert(!Ref && "Checker already registered, use getChecker!"); + +std::unique_ptr Checker = +std::make_unique(std::forward(Args)...); +Checker->Name = CurrentCheckerName; +CHECKER::_register(Checker.get(), *this); +Ref = std::move(Checker); +return static_cast(Ref.get()); } template CHECKER *getChecker() { -CheckerTag tag = getTag(); -assert(CheckerTags.count(tag) != 0 && - "Requested checker is not registered! Maybe you should add it as a " - "dependency in Checkers.td?"); -return static_cast(CheckerTags[tag]); +CheckerTag Tag = getTag(); +std::unique_ptr &Ref = CheckerTags[Tag]; +assert(Ref && "Requested checker is not registered! Maybe you should add it" + " as a dependency in Checkers.td?"); +return static_cast(Ref.get()); } template bool isRegisteredChecker() { @@ -622,9 +620,7 @@ class CheckerManager { template static void *getTag() { static int tag; return &tag; } - llvm::DenseMap CheckerTags; - - std::vector CheckerDtors; + llvm::DenseMap> CheckerTags; struct DeclCheckerInfo { CheckDeclFunc CheckFn; diff --git a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp index f60221ad7587e..35dd255fce898 100644 --- a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp @@ -10,6 +10,7 @@ // //===--===// +#include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" #include @@ -41,8 +42,8 @@ CheckerManager::CheckerManager(AnalyzerOptions &AOptions, } CheckerManager::~CheckerManager() { - for (const auto &CheckerDtor : CheckerDtors) -CheckerDtor(); + // This is declared here to ensure that the destructors of `CheckerBase` and + // `CheckerRegistryData` are available. } } // namespace ento From 38774503663f74ca1c8b36d7ed1b55c10f9edd5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Thu, 27 Feb 2025 14:00:10 +0100 Subject: [PATCH 2/4] Set destructor to '= default' instead of using empty body
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
@@ -41,8 +42,8 @@ CheckerManager::CheckerManager(AnalyzerOptions &AOptions, } CheckerManager::~CheckerManager() { NagyDonat wrote: Good suggestion, I didn't know that `= default` works with out-of-line declarations. https://github.com/llvm/llvm-project/pull/128887 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] Simplify ownership of checker objects (PR #128887)
https://github.com/NagyDonat updated https://github.com/llvm/llvm-project/pull/128887 From 76f8417b8b46e7d036d98fa92890469654158e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Wed, 26 Feb 2025 15:41:46 +0100 Subject: [PATCH 1/6] [NFC][analyzer] Simplify ownership of checker objects Previously checker objects were created by raw `new` calls, which necessitated managing and calling their destructors explicitly. This commit refactors this convoluted logic by introducing `unique_ptr`s that to manage the ownership of these objects automatically. This change can be thought of as stand-alone code quality improvement; but I also have a secondary motivation that I'm planning further changes in the checker registration/initialization process (to formalize our tradition of multi-part checker) and this commit "prepares the ground" for those changes. --- .../StaticAnalyzer/Core/CheckerManager.h | 40 +-- .../Frontend/CreateCheckerManager.cpp | 5 ++- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h index de40b96614dbc..b48a75630fe9b 100644 --- a/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h @@ -185,13 +185,11 @@ class CheckerManager { StringRef OptionName, StringRef ExpectedValueDesc) const; - using CheckerRef = CheckerBase *; using CheckerTag = const void *; - using CheckerDtor = CheckerFn; -//===--===// -// Checker registration. -//===--===// + //===--===// + // Checker registration. + //===--===// /// Used to register checkers. /// All arguments are automatically passed through to the checker @@ -201,24 +199,24 @@ class CheckerManager { template CHECKER *registerChecker(AT &&... Args) { CheckerTag tag = getTag(); -CheckerRef &ref = CheckerTags[tag]; -assert(!ref && "Checker already registered, use getChecker!"); - -CHECKER *checker = new CHECKER(std::forward(Args)...); -checker->Name = CurrentCheckerName; -CheckerDtors.push_back(CheckerDtor(checker, destruct)); -CHECKER::_register(checker, *this); -ref = checker; -return checker; +std::unique_ptr &Ref = CheckerTags[tag]; +assert(!Ref && "Checker already registered, use getChecker!"); + +std::unique_ptr Checker = +std::make_unique(std::forward(Args)...); +Checker->Name = CurrentCheckerName; +CHECKER::_register(Checker.get(), *this); +Ref = std::move(Checker); +return static_cast(Ref.get()); } template CHECKER *getChecker() { -CheckerTag tag = getTag(); -assert(CheckerTags.count(tag) != 0 && - "Requested checker is not registered! Maybe you should add it as a " - "dependency in Checkers.td?"); -return static_cast(CheckerTags[tag]); +CheckerTag Tag = getTag(); +std::unique_ptr &Ref = CheckerTags[Tag]; +assert(Ref && "Requested checker is not registered! Maybe you should add it" + " as a dependency in Checkers.td?"); +return static_cast(Ref.get()); } template bool isRegisteredChecker() { @@ -622,9 +620,7 @@ class CheckerManager { template static void *getTag() { static int tag; return &tag; } - llvm::DenseMap CheckerTags; - - std::vector CheckerDtors; + llvm::DenseMap> CheckerTags; struct DeclCheckerInfo { CheckDeclFunc CheckFn; diff --git a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp index f60221ad7587e..35dd255fce898 100644 --- a/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp @@ -10,6 +10,7 @@ // //===--===// +#include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" #include @@ -41,8 +42,8 @@ CheckerManager::CheckerManager(AnalyzerOptions &AOptions, } CheckerManager::~CheckerManager() { - for (const auto &CheckerDtor : CheckerDtors) -CheckerDtor(); + // This is declared here to ensure that the destructors of `CheckerBase` and + // `CheckerRegistryData` are available. } } // namespace ento From 38774503663f74ca1c8b36d7ed1b55c10f9edd5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Thu, 27 Feb 2025 14:00:10 +0100 Subject: [PATCH 2/6] Set destructor to '= default' instead of using empty body
[libclc] [libclc] Move rsqrt to the CLC library (PR #129045)
@@ -0,0 +1,4 @@ +__attribute__((weak)) _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE +__clc_rsqrt(__CLC_GENTYPE val) { + return __CLC_FP_LIT(1.0) / __clc_sqrt(val); arsenm wrote: For this to work as you want, probably needs to directly use the sqrt builtin (or really, we should enable fast contract throughout the entire library and disable it in the handful of locations that are not OK with it) https://github.com/llvm/llvm-project/pull/129045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Move rsqrt to the CLC library (PR #129045)
@@ -0,0 +1,4 @@ +__attribute__((weak)) _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE +__clc_rsqrt(__CLC_GENTYPE val) { + return __CLC_FP_LIT(1.0) / __clc_sqrt(val); arsenm wrote: ```suggestion __clc_rsqrt(__CLC_GENTYPE val) { #pragma clang fp contract(fast) return __CLC_FP_LIT(1.0) / __clc_sqrt(val); ``` https://github.com/llvm/llvm-project/pull/129045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Coroutines] Mark parameter allocas with coro.outside.frame metadata (PR #127653)
https://github.com/zmodem updated https://github.com/llvm/llvm-project/pull/127653 >From cde82a27139c39406a9afb5b471fa527e52e5bca Mon Sep 17 00:00:00 2001 From: Hans Wennborg Date: Tue, 18 Feb 2025 15:27:37 +0100 Subject: [PATCH 1/7] [Coroutines] Mark parameter allocas with coro.outside.frame metadata Parameters to a coroutine get copied (moved) to coroutine-local instances which code inside the coroutine then uses. The original parameters should not be part of the frame. Normally CoroSplit figures that out by itself, but for [[clang::trivial_abi]] parameters which, get destructed at the end of the ramp function, it does not (see bug), causing use-after-free's if the frame is destroyed before the end of the ramp (as happens if it doesn't suspend). Since Clang knows these should never be part of the frame, use metadata to make it so. Fixes #127499 --- clang/lib/CodeGen/CGCoroutine.cpp| 10 + clang/test/CodeGenCoroutines/coro-params.cpp | 39 +++- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/clang/lib/CodeGen/CGCoroutine.cpp b/clang/lib/CodeGen/CGCoroutine.cpp index 9abf2e8c9190d..cdc61676524b4 100644 --- a/clang/lib/CodeGen/CGCoroutine.cpp +++ b/clang/lib/CodeGen/CGCoroutine.cpp @@ -855,6 +855,16 @@ void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) { // Create parameter copies. We do it before creating a promise, since an // evolution of coroutine TS may allow promise constructor to observe // parameter copies. +for (const ParmVarDecl *Parm : FnArgs) { + // If the original param is in an alloca, exclude it from the coroutine + // frame. The parameter copy will be part of the frame. + Address ParmAddr = GetAddrOfLocalVar(Parm); + if (auto *ParmAlloca = + dyn_cast(ParmAddr.getBasePointer())) { +ParmAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame, +llvm::MDNode::get(CGM.getLLVMContext(), {})); + } +} for (auto *PM : S.getParamMoves()) { EmitStmt(PM); ParamReplacer.addCopy(cast(PM)); diff --git a/clang/test/CodeGenCoroutines/coro-params.cpp b/clang/test/CodeGenCoroutines/coro-params.cpp index b318f2f52ac09..9e640fb2c5c62 100644 --- a/clang/test/CodeGenCoroutines/coro-params.cpp +++ b/clang/test/CodeGenCoroutines/coro-params.cpp @@ -59,13 +59,22 @@ struct MoveAndCopy { ~MoveAndCopy(); }; -void consume(int,int,int) noexcept; +struct [[clang::trivial_abi]] TrivialABI { + int val; + TrivialABI(MoveAndCopy&&) noexcept; + ~TrivialABI(); +}; + +void consume(int,int,int,int) noexcept; // TODO: Add support for CopyOnly params -// CHECK: define{{.*}} void @_Z1fi8MoveOnly11MoveAndCopy(i32 noundef %val, ptr noundef %[[MoParam:.+]], ptr noundef %[[McParam:.+]]) #0 personality ptr @__gxx_personality_v0 -void f(int val, MoveOnly moParam, MoveAndCopy mcParam) { +// CHECK: define{{.*}} void @_Z1fi8MoveOnly11MoveAndCopy10TrivialABI(i32 noundef %val, ptr noundef %[[MoParam:.+]], ptr noundef %[[McParam:.+]], i32 %[[TrivialParam:.+]]) #0 personality ptr @__gxx_personality_v0 +void f(int val, MoveOnly moParam, MoveAndCopy mcParam, TrivialABI trivialParam) { + // CHECK: %[[TrivialAlloca:.+]] = alloca %struct.TrivialABI, + // CHECK-SAME: !coro.outside.frame // CHECK: %[[MoCopy:.+]] = alloca %struct.MoveOnly, // CHECK: %[[McCopy:.+]] = alloca %struct.MoveAndCopy, + // CHECK: %[[TrivialCopy:.+]] = alloca %struct.TrivialABI, // CHECK: store i32 %val, ptr %[[ValAddr:.+]] // CHECK: call ptr @llvm.coro.begin( @@ -73,25 +82,33 @@ void f(int val, MoveOnly moParam, MoveAndCopy mcParam) { // CHECK-NEXT: call void @llvm.lifetime.start.p0( // CHECK-NEXT: call void @_ZN11MoveAndCopyC1EOS_(ptr {{[^,]*}} %[[McCopy]], ptr noundef nonnull align 4 dereferenceable(4) %[[McParam]]) # // CHECK-NEXT: call void @llvm.lifetime.start.p0( - // CHECK-NEXT: invoke void @_ZNSt16coroutine_traitsIJvi8MoveOnly11MoveAndCopyEE12promise_typeC1Ev( + // CHECK-NEXT: call void @llvm.memcpy + // CHECK-SAME: %[[TrivialCopy]] + // CHECK-SAME: %[[TrivialAlloca]] + // CHECK-NEXT: call void @llvm.lifetime.start.p0( + // CHECK-NEXT: invoke void @_ZNSt16coroutine_traitsIJvi8MoveOnly11MoveAndCopy10TrivialABIEE12promise_typeC1Ev( // CHECK: call void @_ZN14suspend_always12await_resumeEv( // CHECK: %[[IntParam:.+]] = load i32, ptr %{{.*}} // CHECK: %[[MoGep:.+]] = getelementptr inbounds nuw %struct.MoveOnly, ptr %[[MoCopy]], i32 0, i32 0 // CHECK: %[[MoVal:.+]] = load i32, ptr %[[MoGep]] - // CHECK: %[[McGep:.+]] = getelementptr inbounds nuw %struct.MoveAndCopy, ptr %[[McCopy]], i32 0, i32 0 + // CHECK: %[[McGep:.+]] = getelementptr inbounds nuw %struct.MoveAndCopy, ptr %[[McCopy]], i32 0, i32 0 // CHECK: %[[McVal:.+]] = load i32, ptr %[[McGep]] - // CHECK: call void @_Z7consumeiii(i32 noundef %[[IntParam]], i32 noundef %[[MoVal]], i32 noundef %[[McVal]]) + // CHECK: %[[TrivialGep:.+]] = getelemen
[clang] [llvm] [Coroutines] Mark parameter allocas with coro.outside.frame metadata (PR #127653)
zmodem wrote: The discussion seems to be stalling. I'll try to summarize. There seem to be two major questions: 1. Whether the front-end should explicitly mark some allocas as not belonging in the coroutine frame, or whether we should enhance CoroSplit to infer it automatically. I think explicitly marking the allocas is the best solution for the current bug (https://github.com/llvm/llvm-project/issues/127499), as well as the previous bug (https://github.com/llvm/llvm-project/issues/49843) which already adopted this approach. Based on @efriedma-quic's most recent comment, I think he's also in favor of this approach(?): > So it's not really a question of "improving" the existing algorithm; we need markers in the IR, like coro_outside_frame, and the algorithm should be based on that. I don't think @rnk expressed an opinion on this question yet. @ChuanqiXu9 has argued in favor of the approach from https://github.com/llvm/llvm-project/pull/127524 instead: making CoroSplit treat allocas referenced after the `coro.end` intrinsic as belonging outside the frame. 2. If we do use explicit markers for the allocas, how should that be done? Currently, `coro.outside.frame` metadata on the allocas is used for this. @efriedma-quic pointed out metadata must never be required for correctness, and we all agree this current state is bad. I've proposed using an intrinsic. @rnk has suggested that we could put an explicit field on the alloca instruction, similar to `inalloca`. @ChuanqiXu9 has raised concerns about an intrinsic blocking optimization. --- I'm keen to unbreak our users here, as well as implementing the proper long-term solution. Since there is some disagreement, maybe we shouldn't do it all at once. I've rolled back my PR to just use the existing metadata. While that's not a complete solution, it should be a strict improvement: it fixes the immediate issue using the existing mechanism. I'd like to go ahead and land this. I will follow up with a PR to remove the metadata, and we can continue discussing there. https://github.com/llvm/llvm-project/pull/127653 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 879ef53b6a79f649dd1854c50d55cd6798a06dec Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 13 ++ clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../checkers/modernize/use-ranges.cpp | 26 --- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..f7a19cd72d500 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,19 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; + +// FIXME: This check specifically handles `CXXNullPtrLiteralExpr`, but +// a more general solution might be needed. +if (Function->getName() == "find") { + const unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) +return; +} + auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 6b8fe22242417..4fdb5aa367c68 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -109,6 +109,10 @@ Changes in existing checks - Improved :doc:`misc-redundant-expression ` check by providing additional examples and fixing some macro related false positives. + +- Improved :doc:`modernize-use-ranges + ` check by updating suppress + warnings logic for ``nullptr`` in ``std::find``. Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..5aa026038b1cd 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,25 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + std::vector> K; + + // Expect to have no check messages + std::find(K.begin(), K.end(), nullptr); + + std::find(K.begin(), K.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(K, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +87,15 @@ void Positives() { void Reverse(){ std::vector I, J; + std::vector> K; + + // Expect to have no check messages + std::find(K.rbegin(), K.rend(), nullptr); + + std::find(K.rbegin(), K.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(K), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
StarOne01 wrote: @AaronBallman https://github.com/llvm/llvm-project/pull/123495 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
https://github.com/pzzp updated https://github.com/llvm/llvm-project/pull/126481 >From ad5d0ba6d6fdacf89c9fd132bfb4a8d733781f03 Mon Sep 17 00:00:00 2001 From: pzzp Date: Fri, 28 Feb 2025 10:46:12 +0800 Subject: [PATCH] [llvm:ir] Add support for constant data exceeding 4GiB --- clang/lib/CodeGen/CGExprConstant.cpp | 8 +++ llvm/include/llvm/IR/Constants.h | 16 +++--- llvm/lib/Analysis/TargetTransformInfo.cpp | 2 +- llvm/lib/Analysis/ValueTracking.cpp | 2 +- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp | 8 +++ llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp| 6 +++--- .../SelectionDAG/SelectionDAGBuilder.cpp | 2 +- llvm/lib/IR/AsmWriter.cpp | 2 +- llvm/lib/IR/Constants.cpp | 21 +-- llvm/lib/Target/TargetLoweringObjectFile.cpp | 4 ++-- llvm/lib/Target/X86/X86MCInstLower.cpp| 2 +- 11 files changed, 36 insertions(+), 37 deletions(-) diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index ee5874b26f534..c713abb53d89d 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -364,14 +364,14 @@ bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) { // FIXME: If possible, split into two ConstantDataSequentials at Hint. CharUnits ElemSize = getSize(CDS->getElementType()); replace(Elems, Index, Index + 1, -llvm::map_range(llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { +llvm::map_range(llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return CDS->getElementAsConstant(Elem); })); replace(Offsets, Index, Index + 1, llvm::map_range( -llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { return Offset + Elem * ElemSize; })); +llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return Offset + Elem * ElemSize; })); return true; } diff --git a/llvm/include/llvm/IR/Constants.h b/llvm/include/llvm/IR/Constants.h index 676d59e3fcb08..a50217078d0ed 100644 --- a/llvm/include/llvm/IR/Constants.h +++ b/llvm/include/llvm/IR/Constants.h @@ -617,34 +617,34 @@ class ConstantDataSequential : public ConstantData { /// If this is a sequential container of integers (of any size), return the /// specified element in the low bits of a uint64_t. - uint64_t getElementAsInteger(unsigned i) const; + uint64_t getElementAsInteger(uint64_t i) const; /// If this is a sequential container of integers (of any size), return the /// specified element as an APInt. - APInt getElementAsAPInt(unsigned i) const; + APInt getElementAsAPInt(uint64_t i) const; /// If this is a sequential container of floating point type, return the /// specified element as an APFloat. - APFloat getElementAsAPFloat(unsigned i) const; + APFloat getElementAsAPFloat(uint64_t i) const; /// If this is an sequential container of floats, return the specified element /// as a float. - float getElementAsFloat(unsigned i) const; + float getElementAsFloat(uint64_t i) const; /// If this is an sequential container of doubles, return the specified /// element as a double. - double getElementAsDouble(unsigned i) const; + double getElementAsDouble(uint64_t i) const; /// Return a Constant for a specified index's element. /// Note that this has to compute a new constant to return, so it isn't as /// efficient as getElementAsInteger/Float/Double. - Constant *getElementAsConstant(unsigned i) const; + Constant *getElementAsConstant(uint64_t i) const; /// Return the element type of the array/vector. Type *getElementType() const; /// Return the number of elements in the array or vector. - unsigned getNumElements() const; + uint64_t getNumElements() const; /// Return the size (in bytes) of each element in the array/vector. /// The size of the elements is known to be a multiple of one byte. @@ -684,7 +684,7 @@ class ConstantDataSequential : public ConstantData { } private: - const char *getElementPointer(unsigned Elt) const; + const char *getElementPointer(uint64_t Elt) const; }; //===--===// diff --git a/llvm/lib/Analysis/TargetTransformInfo.cpp b/llvm/lib/Analysis/TargetTransformInfo.cpp index 1c54395909f10..28ec4cfec8b8c 100644 --- a/llvm/lib/Analysis/TargetTransformInfo.cpp +++ b/llvm/lib/Analysis/TargetTransformInfo.cpp @@ -918,7 +918,7 @@ TargetTransformInfo::getOperandInfo(const Value *V) { } else if (const auto *CDS = dyn_cast(V)) { OpInfo = OK_NonUniformConstantValue; bool AllPow2 = true, AllNegPow2 = true; -for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) { +for
[clang] [Clang][OpenCL] Wrap image functions with the macro (PR #129171)
https://github.com/vmustya updated https://github.com/llvm/llvm-project/pull/129171 >From 98ae8631af5d672fc7a86c19f2b84c2efb6ceea0 Mon Sep 17 00:00:00 2001 From: Victor Mustya Date: Thu, 27 Feb 2025 17:28:36 -0800 Subject: [PATCH 1/2] [Clang][OpenCL] Wrap image functions with the macro According to the OpenCL C 3.0 spec, the image functions are optional. If they are supported, the `__opencl_c_images` macro is defined. This patch wraps the image functions with the macro. Without the wrapping, the frontend emit errors, when a user tries to disable the images support. --- clang/lib/Headers/opencl-c.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h index 20719b74b6b8d..d77cf3c7b2faa 100644 --- a/clang/lib/Headers/opencl-c.h +++ b/clang/lib/Headers/opencl-c.h @@ -15082,6 +15082,7 @@ half16 __ovld __cnfn shuffle2(half16, half16, ushort16); #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable #endif //cl_khr_gl_msaa_sharing +#if defined(__opencl_c_images) /** * Use the coordinate (coord.xy) to do an element lookup in * the 2D image object specified by image. @@ -16143,6 +16144,8 @@ int __ovld __cnfn get_image_num_samples(read_write image2d_array_msaa_depth_t); #endif //defined(__opencl_c_read_write_images) #endif +#endif // defined(__opencl_c_images) + // OpenCL v2.0 s6.13.15 - Work-group Functions #if defined(__opencl_c_work_group_collective_functions) >From 1145dc35c481875e3994f9367070f564606db464 Mon Sep 17 00:00:00 2001 From: Victor Mustya Date: Thu, 27 Feb 2025 18:47:18 -0800 Subject: [PATCH 2/2] Enable images for OpenCL C 1.2 --- clang/lib/Headers/opencl-c-base.h | 4 1 file changed, 4 insertions(+) diff --git a/clang/lib/Headers/opencl-c-base.h b/clang/lib/Headers/opencl-c-base.h index b6bcf32c09c08..1c66342f82808 100644 --- a/clang/lib/Headers/opencl-c-base.h +++ b/clang/lib/Headers/opencl-c-base.h @@ -55,6 +55,10 @@ #endif // defined(__SPIR__) || defined(__SPIRV__) #endif // (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200) +#if (__OPENCL_C_VERSION__ == 120) +#define __opencl_c_images 1 +#endif // (__OPENCL_C_VERSION__ == 120) + // Define feature macros for OpenCL C 2.0 #if (__OPENCL_CPP_VERSION__ == 100 || __OPENCL_C_VERSION__ == 200) #define __opencl_c_pipes 1 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Always pass `fp128` arguments indirectly on Windows (PR #115052)
https://github.com/tgross35 edited https://github.com/llvm/llvm-project/pull/115052 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] default clause replaced by otherwise clause for metadirective in OpenMP 5.2 (PR #128640)
ravurvi20 wrote: Previous commit was reverted due to a failing test case, which has been resolved now. Parsing changes have been approved in the previous PR. [125648](https://github.com/llvm/llvm-project/pull/125648) https://github.com/llvm/llvm-project/pull/128640 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [SystemZ] Add header guard macros to vecintrin.h (PR #129170)
https://github.com/jonathan-albrecht-ibm created https://github.com/llvm/llvm-project/pull/129170 Add header guard macros to clang/lib/Headers/vecintrin.h. Found while compiling the latest numpy with clang 19 on s390x which ends up including vecintrin.h twice. The gcc version of this file has header guards so numpy compiles fine with gcc. I'd like if this could also make it into a clang 19 release if possible. @uweigand, could you have a look at this? >From cc856687f5a61c320b9ee6adf6bd3ede82da8d10 Mon Sep 17 00:00:00 2001 From: Jonathan Albrecht Date: Fri, 21 Feb 2025 15:27:33 -0500 Subject: [PATCH] [SystemZ] Add header guard macros to vecintrin.h Signed-off-by: Jonathan Albrecht --- clang/lib/Headers/vecintrin.h | 5 + 1 file changed, 5 insertions(+) diff --git a/clang/lib/Headers/vecintrin.h b/clang/lib/Headers/vecintrin.h index a14c39f9f7313..338ea51ce8863 100644 --- a/clang/lib/Headers/vecintrin.h +++ b/clang/lib/Headers/vecintrin.h @@ -7,6 +7,9 @@ *===---=== */ +#ifndef _VECINTRIN_H +#define _VECINTRIN_H + #if defined(__s390x__) && defined(__VEC__) #define __ATTRS_ai __attribute__((__always_inline__)) @@ -12861,3 +12864,5 @@ vec_search_string_until_zero_cc(__vector unsigned int __a, #error "Use -fzvector to enable vector extensions" #endif + +#endif /* _VECINTRIN_H */ ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 80f34e2 - [clang-format] Change BracedInitializerIndentWidth to int (#128988)
Author: Owen Pan Date: 2025-02-27T20:18:02-08:00 New Revision: 80f34e2716e8e69347ae16da5fff7114442db310 URL: https://github.com/llvm/llvm-project/commit/80f34e2716e8e69347ae16da5fff7114442db310 DIFF: https://github.com/llvm/llvm-project/commit/80f34e2716e8e69347ae16da5fff7114442db310.diff LOG: [clang-format] Change BracedInitializerIndentWidth to int (#128988) Fixes #108526 Added: Modified: clang/docs/ClangFormatStyleOptions.rst clang/include/clang/Format/Format.h clang/lib/Format/ContinuationIndenter.cpp clang/lib/Format/Format.cpp clang/unittests/Format/ConfigParseTest.cpp Removed: diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index d157c07c9cef8..9ecac68ae72bf 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -2582,9 +2582,9 @@ the configuration (without a prefix: ``Auto``). .. _BracedInitializerIndentWidth: -**BracedInitializerIndentWidth** (``Unsigned``) :versionbadge:`clang-format 17` :ref:`¶ ` +**BracedInitializerIndentWidth** (``Integer``) :versionbadge:`clang-format 17` :ref:`¶ ` The number of columns to use to indent the contents of braced init lists. - If unset, ``ContinuationIndentWidth`` is used. + If unset or negative, ``ContinuationIndentWidth`` is used. .. code-block:: c++ diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 46fb1d52701b3..fec47a248abb4 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -1289,7 +1289,7 @@ struct FormatStyle { BitFieldColonSpacingStyle BitFieldColonSpacing; /// The number of columns to use to indent the contents of braced init lists. - /// If unset, ``ContinuationIndentWidth`` is used. + /// If unset or negative, ``ContinuationIndentWidth`` is used. /// \code /// AlignAfterOpenBracket: AlwaysBreak /// BracedInitializerIndentWidth: 2 @@ -1319,7 +1319,7 @@ struct FormatStyle { /// } /// \endcode /// \version 17 - std::optional BracedInitializerIndentWidth; + int BracedInitializerIndentWidth; /// Different ways to wrap braces after control statements. enum BraceWrappingAfterControlStatementStyle : int8_t { diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index d49128c2b40f8..972dceb697a8b 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -1921,9 +1921,9 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, NewIndent = Style.IndentWidth + std::min(State.Column, CurrentState.NestedBlockIndent); } else if (Current.is(tok::l_brace)) { - NewIndent = - CurrentState.LastSpace + Style.BracedInitializerIndentWidth.value_or( - Style.ContinuationIndentWidth); + const auto Width = Style.BracedInitializerIndentWidth; + NewIndent = CurrentState.LastSpace + + (Width < 0 ? Style.ContinuationIndentWidth : Width); } else { NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth; } diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 68ef119fb4d65..92678a031178a 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1512,7 +1512,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) { LLVMStyle.BinPackLongBracedList = true; LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack; LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both; - LLVMStyle.BracedInitializerIndentWidth = std::nullopt; + LLVMStyle.BracedInitializerIndentWidth = -1; LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false, /*AfterClass=*/false, /*AfterControlStatement=*/FormatStyle::BWACS_Never, diff --git a/clang/unittests/Format/ConfigParseTest.cpp b/clang/unittests/Format/ConfigParseTest.cpp index 9cd262960b724..273bab87b1ee1 100644 --- a/clang/unittests/Format/ConfigParseTest.cpp +++ b/clang/unittests/Format/ConfigParseTest.cpp @@ -265,9 +265,9 @@ TEST(ConfigParseTest, ParsesConfigurationIntegers) { Style.Language = FormatStyle::LK_Cpp; CHECK_PARSE_INT(AccessModifierOffset); + CHECK_PARSE_INT(BracedInitializerIndentWidth); CHECK_PARSE_INT(PPIndentWidth); - CHECK_PARSE_UNSIGNED(BracedInitializerIndentWidth); CHECK_PARSE_UNSIGNED(ColumnLimit); CHECK_PARSE_UNSIGNED(ConstructorInitializerIndentWidth); CHECK_PARSE_UNSIGNED(ContinuationIndentWidth); @@ -1441,8 +1441,10 @@ TEST(ConfigParseTest, GetStyleOfFile) { ASSERT_EQ(*Style9, SubSubStyle); // Test 9.8: use inheritance from a file without BasedOnStyle - ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, - llvm::MemoryBuffer::getMemBuf
[clang] [analyzer] Limit Store by region-store-binding-limit (PR #127602)
mikaelholmen wrote: Hello @balazs-benics-sonarsource The following starts crashing with this patch: ```clang --analyze bbi-104578.c``` It crashes with ``` clang: ../../clang/lib/StaticAnalyzer/Core/RegionStore.cpp:375: LimitedRegionBindingsRef LimitedRegionBindingsRef::addBinding(BindingKey, SVal) const: Assertion `NewBindingsLeft.value() != 0' failed. PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, preprocessed source, and associated run script. Stack dump: 0. Program arguments: build-all/bin/clang --analyze bbi-104578.c 1. parser at end of file 2. While analyzing stack: #0 Calling c 3. bbi-104578.c:5:3: Error evaluating statement 4. bbi-104578.c:5:3: Error evaluating statement #0 0x55dcb12b54f6 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (build-all/bin/clang+0x856b4f6) #1 0x55dcb12b2fde llvm::sys::RunSignalHandlers() (build-all/bin/clang+0x8568fde) #2 0x55dcb12b4834 llvm::sys::CleanupOnSignal(unsigned long) (build-all/bin/clang+0x856a834) #3 0x55dcb1215bfd CrashRecoverySignalHandler(int) CrashRecoveryContext.cpp:0:0 #4 0x7fa82a361d10 __restore_rt (/lib64/libpthread.so.0+0x12d10) #5 0x7fa827d0152f raise (/lib64/libc.so.6+0x4e52f) #6 0x7fa827cd4e65 abort (/lib64/libc.so.6+0x21e65) #7 0x7fa827cd4d39 _nl_load_domain.cold.0 (/lib64/libc.so.6+0x21d39) #8 0x7fa827cf9e86 (/lib64/libc.so.6+0x46e86) #9 0x55dcb34a2bf5 LimitedRegionBindingsRef::addBinding((anonymous namespace)::BindingKey, clang::ento::SVal) const RegionStore.cpp:0:0 #10 0x55dcb34a01f6 (anonymous namespace)::RegionStoreManager::bindArray(LimitedRegionBindingsRef const&, clang::ento::TypedValueRegion const*, clang::ento::SVal) RegionStore.cpp:0:0 #11 0x55dcb34a03e3 (anonymous namespace)::RegionStoreManager::bindArray(LimitedRegionBindingsRef const&, clang::ento::TypedValueRegion const*, clang::ento::SVal) RegionStore.cpp:0:0 #12 0x55dcb349fb68 (anonymous namespace)::RegionStoreManager::bind(LimitedRegionBindingsRef const&, clang::ento::Loc, clang::ento::SVal) RegionStore.cpp:0:0 #13 0x55dcb3494678 (anonymous namespace)::RegionStoreManager::Bind(void const*, clang::ento::Loc, clang::ento::SVal) RegionStore.cpp:0:0 #14 0x55dcb34609eb clang::ento::ProgramState::bindLoc(clang::ento::Loc, clang::ento::SVal, clang::LocationContext const*, bool) const (build-all/bin/clang+0xa7169eb) #15 0x55dcb340dea2 clang::ento::ExprEngine::processPointerEscapedOnBind(llvm::IntrusiveRefCntPtr, llvm::ArrayRef>, clang::LocationContext const*, clang::ento::PointerEscapeKind, clang::ento::CallEvent const*) (build-all/bin/clang+0xa6c3ea2) #16 0x55dcb3403650 clang::ento::ExprEngine::evalBind(clang::ento::ExplodedNodeSet&, clang::Stmt const*, clang::ento::ExplodedNode*, clang::ento::SVal, clang::ento::SVal, bool, clang::ProgramPoint const*) (build-all/bin/clang+0xa6b9650) #17 0x55dcb341e195 clang::ento::ExprEngine::VisitDeclStmt(clang::DeclStmt const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (build-all/bin/clang+0xa6d4195) #18 0x55dcb340261b clang::ento::ExprEngine::Visit(clang::Stmt const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (build-all/bin/clang+0xa6b861b) #19 0x55dcb33fe863 clang::ento::ExprEngine::ProcessStmt(clang::Stmt const*, clang::ento::ExplodedNode*) (build-all/bin/clang+0xa6b4863) #20 0x55dcb33fe555 clang::ento::ExprEngine::processCFGElement(clang::CFGElement, clang::ento::ExplodedNode*, unsigned int, clang::ento::NodeBuilderContext*) (build-all/bin/clang+0xa6b4555) #21 0x55dcb33e06b0 clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*, unsigned int, clang::ento::ExplodedNode*) (build-all/bin/clang+0xa6966b0) #22 0x55dcb33dfd1b clang::ento::CoreEngine::dispatchWorkItem(clang::ento::ExplodedNode*, clang::ProgramPoint, clang::ento::WorkListUnit const&) (build-all/bin/clang+0xa695d1b) #23 0x55dcb33df36d clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext const*, unsigned int, llvm::IntrusiveRefCntPtr) (build-all/bin/clang+0xa69536d) #24 0x55dcb313d2c7 (anonymous namespace)::AnalysisConsumer::HandleCode(clang::Decl*, unsigned int, clang::ento::ExprEngine::InliningModes, llvm::DenseSet>*) AnalysisConsumer.cpp:0:0 #25 0x55dcb313b70b (anonymous namespace)::AnalysisConsumer::HandleTranslationUnit(clang::ASTContext&) AnalysisConsumer.cpp:0:0 #26 0x55dcb34f6029 clang::ParseAST(clang::Sema&, bool, bool) (build-all/bin/clang+0xa7ac029) #27 0x55dcb20b15e4 clang::FrontendAction::Execute() (build-all/bin/clang+0x93675e4) #28 0x55dcb201a1cd clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (build-all/bin/clang+0x92d01cd) #29 0x55dcb21b37c5 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (build-all/bin/clang+0x94697c5) #30 0x55dcae7a9626 cc1_main(llvm::ArrayRef, char const*, void*) (build-all/bin/clang+0x5a5f626
[clang] [llvm] [X86][CodeGen] - Use shift operators instead of built-ins for SSE emulation of MMX intrinsics. (PR #129197)
pawan-nirpal-031 wrote: @e-kud @phoebewang @mahesh-attarde @arsenm could you please review. https://github.com/llvm/llvm-project/pull/129197 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Check for uninitialized use in lambda within CXXOperatorCallExpr (PR #129198)
https://github.com/zhaohuiw42 updated https://github.com/llvm/llvm-project/pull/129198 >From e52e53f5756172f02b8075f0480ee12f4eef9add Mon Sep 17 00:00:00 2001 From: zhaohui Date: Fri, 28 Feb 2025 14:12:39 +0800 Subject: [PATCH] [Clang] Check for uninitialized use in lambda within CXXOperatorCallExpr --- clang/lib/Sema/SemaDecl.cpp | 22 ++ clang/test/SemaCXX/uninitialized.cpp | 4 2 files changed, 26 insertions(+) diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 285bd27a35a76..ad93b4a858543 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -12597,6 +12597,12 @@ namespace { bool isRecordType; bool isPODType; bool isReferenceType; +// Tracks whether the current expression is being visited within a +// CXXOperatorCallExpr. This flag is set to true when entering a +// CXXOperatorCallExpr and reset to false upon exit. It is used to detect +// when a LambdaExpr is an operand of an operator call, enabling special +// handling of its capture initializations. +bool isInCXXOperatorCall; bool isInitList; llvm::SmallVector InitFieldIndex; @@ -12609,6 +12615,7 @@ namespace { isPODType = false; isRecordType = false; isReferenceType = false; + isInCXXOperatorCall = false; isInitList = false; if (ValueDecl *VD = dyn_cast(OrigDecl)) { isPODType = VD->getType().isPODType(S.Context); @@ -12796,6 +12803,7 @@ namespace { } void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { + isInCXXOperatorCall = true; Expr *Callee = E->getCallee(); if (isa(Callee)) @@ -12804,6 +12812,20 @@ namespace { Visit(Callee); for (auto Arg: E->arguments()) HandleValue(Arg->IgnoreParenImpCasts()); + isInCXXOperatorCall = false; +} + +void VisitLambdaExpr(LambdaExpr *E) { + if (isInCXXOperatorCall) { +for (const auto &init : E->capture_inits()) { + if (DeclRefExpr *DRE = dyn_cast(init)) +HandleDeclRefExpr(DRE); + else +Visit(init); +} +return; + } + Inherited::VisitLambdaExpr(E); } void VisitUnaryOperator(UnaryOperator *E) { diff --git a/clang/test/SemaCXX/uninitialized.cpp b/clang/test/SemaCXX/uninitialized.cpp index 4af2c998f082e..654d955b3cc72 100644 --- a/clang/test/SemaCXX/uninitialized.cpp +++ b/clang/test/SemaCXX/uninitialized.cpp @@ -892,6 +892,10 @@ namespace lambdas { return a1.x; }); A a2([&] { return a2.x; }); // ok +A a3([=]{ return a3.x; }()); // expected-warning{{variable 'a3' is uninitialized when used within its own initialization}} +A a4([&]{ return a4.x; }()); // expected-warning{{variable 'a4' is uninitialized when used within its own initialization}} +A a5([&]{ return a5; }()); // expected-warning{{variable 'a5' is uninitialized when used within its own initialization}} +A a6([&]{ return a5.x; }()); // ok } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Xqccmp Code Generation (PR #128815)
lenary wrote: @topperc the two useful changes since you last reviewed are: - Adding a Release Note - Changing the conditions around frame pointers to ensure we don't emit a `add s0, sp, -` (as before), but that we do emit the `.cfi_def_cfa s0, 0` which informs dwarf/cfi that the way to calculate the CFA is with `s0` (the usual way when `hasFP(MF) == true`). https://github.com/llvm/llvm-project/pull/128815 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenCL] Wrap image functions with the macro (PR #129177)
llvmbot wrote: @llvm/pr-subscribers-backend-x86 Author: Victor Mustya (vmustya) Changes According to the OpenCL C spec, the image functions are optional. For OpenCL C 1.2, the image functions are guarded by the `__IMAGE_SUPPORT__` macro. For the OpenCL C 3.0 and later, the `__opencl_c_images` macro is used. --- Full diff: https://github.com/llvm/llvm-project/pull/129177.diff 1 Files Affected: - (modified) clang/lib/Headers/opencl-c.h (+3) ``diff diff --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h index 20719b74b6b8d..8d8ef497cec49 100644 --- a/clang/lib/Headers/opencl-c.h +++ b/clang/lib/Headers/opencl-c.h @@ -15082,6 +15082,7 @@ half16 __ovld __cnfn shuffle2(half16, half16, ushort16); #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable #endif //cl_khr_gl_msaa_sharing +#if (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) /** * Use the coordinate (coord.xy) to do an element lookup in * the 2D image object specified by image. @@ -16143,6 +16144,8 @@ int __ovld __cnfn get_image_num_samples(read_write image2d_array_msaa_depth_t); #endif //defined(__opencl_c_read_write_images) #endif +#endif // (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) + // OpenCL v2.0 s6.13.15 - Work-group Functions #if defined(__opencl_c_work_group_collective_functions) `` https://github.com/llvm/llvm-project/pull/129177 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenCL] Wrap image functions with the macro (PR #129177)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Victor Mustya (vmustya) Changes According to the OpenCL C spec, the image functions are optional. For OpenCL C 1.2, the image functions are guarded by the `__IMAGE_SUPPORT__` macro. For the OpenCL C 3.0 and later, the `__opencl_c_images` macro is used. --- Full diff: https://github.com/llvm/llvm-project/pull/129177.diff 1 Files Affected: - (modified) clang/lib/Headers/opencl-c.h (+3) ``diff diff --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h index 20719b74b6b8d..8d8ef497cec49 100644 --- a/clang/lib/Headers/opencl-c.h +++ b/clang/lib/Headers/opencl-c.h @@ -15082,6 +15082,7 @@ half16 __ovld __cnfn shuffle2(half16, half16, ushort16); #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable #endif //cl_khr_gl_msaa_sharing +#if (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) /** * Use the coordinate (coord.xy) to do an element lookup in * the 2D image object specified by image. @@ -16143,6 +16144,8 @@ int __ovld __cnfn get_image_num_samples(read_write image2d_array_msaa_depth_t); #endif //defined(__opencl_c_read_write_images) #endif +#endif // (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) + // OpenCL v2.0 s6.13.15 - Work-group Functions #if defined(__opencl_c_work_group_collective_functions) `` https://github.com/llvm/llvm-project/pull/129177 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenCL] Wrap image functions with the macro (PR #129177)
https://github.com/vmustya created https://github.com/llvm/llvm-project/pull/129177 According to the OpenCL C spec, the image functions are optional. For OpenCL C 1.2, the image functions are guarded by the `__IMAGE_SUPPORT__` macro. For the OpenCL C 3.0 and later, the `__opencl_c_images` macro is used. >From 781a2a826cc7ebb29d91c8b7143affe7c94cac24 Mon Sep 17 00:00:00 2001 From: Victor Mustya Date: Thu, 27 Feb 2025 17:28:36 -0800 Subject: [PATCH] [Clang][OpenCL] Wrap image functions with the macro According to the OpenCL C spec, the image functions are optional. For OpenCL C 1.2, the image functions are guarded by the `__IMAGE_SUPPORT__` macro. For the OpenCL C 3.0 and later, the `__opencl_c_images` macro is used. --- clang/lib/Headers/opencl-c.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h index 20719b74b6b8d..8d8ef497cec49 100644 --- a/clang/lib/Headers/opencl-c.h +++ b/clang/lib/Headers/opencl-c.h @@ -15082,6 +15082,7 @@ half16 __ovld __cnfn shuffle2(half16, half16, ushort16); #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable #endif //cl_khr_gl_msaa_sharing +#if (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) /** * Use the coordinate (coord.xy) to do an element lookup in * the 2D image object specified by image. @@ -16143,6 +16144,8 @@ int __ovld __cnfn get_image_num_samples(read_write image2d_array_msaa_depth_t); #endif //defined(__opencl_c_read_write_images) #endif +#endif // (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__)) + // OpenCL v2.0 s6.13.15 - Work-group Functions #if defined(__opencl_c_work_group_collective_functions) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clang-tidy] [dataflow] Cache reference accessors for `bugprone-unchecked-optional-access` (PR #128437)
jvoung wrote: > Updated release notes. Not sure if I need to update > `clang-tidy/checks/bugprone/unchecked-optional-access.rst`. For me it looks > like current `Exception: accessor methods` section covers my fix as well. Agreed that the "`Exception: accessor methods` section covers" your fix as well, so no need to update. Thank you! https://github.com/llvm/llvm-project/pull/128437 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
@@ -617,15 +617,15 @@ class ConstantDataSequential : public ConstantData { /// If this is a sequential container of integers (of any size), return the /// specified element in the low bits of a uint64_t. - uint64_t getElementAsInteger(unsigned i) const; + uint64_t getElementAsInteger(uint64_t i) const; /// If this is a sequential container of integers (of any size), return the /// specified element as an APInt. APInt getElementAsAPInt(unsigned i) const; pzzp wrote: Done! ✨ https://github.com/llvm/llvm-project/pull/126481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream global variable linkage types (PR #129072)
https://github.com/dkolsen-pgi edited https://github.com/llvm/llvm-project/pull/129072 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Change BracedInitializerIndentWidth to int (PR #128988)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/128988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ARM] Introduce -mtp=auto and make it the default (PR #128901)
@@ -42,4 +42,4 @@ // RUN: %clang --target=armv7-linux -### -S %s 2>&1 | \ // RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s -// ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-tpidruro" +// ARMv7_THREAD_POINTER_NON: "-target-feature" "+read-tp-tpidruro" Zhenhang1213 wrote: OK https://github.com/llvm/llvm-project/pull/128901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 170b573 - [Driver] [C++20] [Modules] Warning for the surprising useless case for reduced BMI
Author: Chuanqi Xu Date: 2025-02-28T13:36:29+08:00 New Revision: 170b5736824bd4f70a7bf9dd0028b997d85ba76f URL: https://github.com/llvm/llvm-project/commit/170b5736824bd4f70a7bf9dd0028b997d85ba76f DIFF: https://github.com/llvm/llvm-project/commit/170b5736824bd4f70a7bf9dd0028b997d85ba76f.diff LOG: [Driver] [C++20] [Modules] Warning for the surprising useless case for reduced BMI Found in downstream. I didn't realize the output file for precompile and reduced BMI refers to the same location. Then the generating process of reduced BMI is basically a waste of time. Added: Modified: clang/include/clang/Basic/DiagnosticDriverKinds.td clang/lib/Driver/ToolChains/Clang.cpp clang/test/Driver/module-fgen-reduced-bmi.cppm Removed: diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index 8f532a63f9e04..058fecd4e91ef 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -563,6 +563,11 @@ def err_test_module_file_extension_format : Error< def err_drv_module_output_with_multiple_arch : Error< "option '-fmodule-output' cannot be used with multiple arch options">; +def err_drv_reduced_module_output_overrided : Warning< + "the implicit output of reduced BMI may be overrided by the output file specified by '--precompile'. " + "please consider use '-fmodule-output=' to specify the output file for reduced BMI explicitly">, + InGroup>; + def warn_drv_delayed_template_parsing_after_cxx20 : Warning< "-fdelayed-template-parsing is deprecated after C++20">, InGroup>; diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 86db3f7678436..4ebbd241d2f0b 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -4250,10 +4250,18 @@ static bool RenderModulesOptions(Compilation &C, const Driver &D, if (Args.hasArg(options::OPT_fmodule_output_EQ)) Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ); -else +else { + if (Args.hasArg(options::OPT__precompile) && + (!Args.hasArg(options::OPT_o) || + Args.getLastArg(options::OPT_o)->getValue() == + getCXX20NamedModuleOutputPath(Args, Input.getBaseInput( { +D.Diag(diag::err_drv_reduced_module_output_overrided); + } + CmdArgs.push_back(Args.MakeArgString( "-fmodule-output=" + getCXX20NamedModuleOutputPath(Args, Input.getBaseInput(; +} } // Noop if we see '-fmodules-reduced-bmi' with other translation diff --git a/clang/test/Driver/module-fgen-reduced-bmi.cppm b/clang/test/Driver/module-fgen-reduced-bmi.cppm index 7329c12941d73..9bdd4c9f6682f 100644 --- a/clang/test/Driver/module-fgen-reduced-bmi.cppm +++ b/clang/test/Driver/module-fgen-reduced-bmi.cppm @@ -48,6 +48,14 @@ // RUN: %clang -std=c++20 Hello.cppm --precompile -fmodules-reduced-bmi \ // RUN: -o Hello.full.pcm -### 2>&1 | FileCheck Hello.cppm \ // RUN: --check-prefix=CHECK-EMIT-MODULE-INTERFACE + +// RUN: %clang -std=c++20 Hello.cppm --precompile -fmodules-reduced-bmi \ +// RUN: -### 2>&1 | FileCheck Hello.cppm \ +// RUN: --check-prefix=CHECK-OVERRIDE-WARN + +// RUN: %clang -std=c++20 Hello.cppm --precompile -fmodules-reduced-bmi \ +// RUN: -o Hello.pcm -### 2>&1 | FileCheck Hello.cppm \ +// RUN:--check-prefix=CHECK-OVERRIDE-WARN // // RUN: %clang -std=c++20 Hello.cc -fmodules-reduced-bmi -Wall -Werror \ // RUN: -c -o Hello.o -### 2>&1 | FileCheck Hello.cc @@ -74,6 +82,8 @@ export module Hello; // flag. // CHECK-EMIT-MODULE-INTERFACE: -emit-module-interface +// CHECK-OVERRIDE-WARN: warning: the implicit output of reduced BMI may be overrided by the output file specified by '--precompile'. {{.*}}-Wreduced-bmi-output-overrided + // NO_WARN-NOT: warning //--- Hello.cc ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Offload] Always consider `flto` on for AMDGPU (PR #129118)
shiltian wrote: We do have some framework teams that are still using non-LTO (or non-gpu-rdc) build. https://github.com/llvm/llvm-project/pull/129118 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ARM] Introduce -mtp=auto and make it the default (PR #128901)
https://github.com/Zhenhang1213 updated https://github.com/llvm/llvm-project/pull/128901 >From 1f3fed728a5c4fd11fba92d57ac79522e790cd82 Mon Sep 17 00:00:00 2001 From: Austin Date: Thu, 27 Feb 2025 00:11:56 +0800 Subject: [PATCH] [ARM] Introduce -mtp=auto and make it the default This adds a new value auto to the possible values of the existing -mtp= clang option which controls how the thread pointer is found. auto means the same as soft if the target architecture doesn't support a hardware thread pointer at all; otherwise it means the same as cp15. This behavior is the default in gcc version 4.1.0 and later. The new auto option is therefore also the default in clang, so this change aligns clang with gcc. Fixes #123864. --- clang/docs/ReleaseNotes.rst | 4 clang/include/clang/Driver/Options.td| 2 +- clang/lib/Driver/ToolChains/Arch/ARM.cpp | 17 ++--- clang/lib/Driver/ToolChains/Arch/ARM.h | 1 + clang/test/Driver/arm-thread-pointer.c | 6 +- 5 files changed, 21 insertions(+), 9 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 307edf77ebb58..b74feda157ecc 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -122,6 +122,10 @@ Deprecated Compiler Flags Modified Compiler Flags --- +- The ARM AArch32 ``-mtp`` option accepts and defaults to ``auto``, a value of ``auto`` uses the best available method of providing the frame pointer supported by the hardware. This matches + the behavior of ``-mtp`` in gcc. This changes the default behavior for ARM targets that provide the ``TPIDRURO`` register as this will be used instead of a call to the ``__aeabi_read_tp``. + Programs that use ``__aeabi_read_tp`` but do not use the ``TPIDRURO`` register must use ``-mtp=soft``. Fixes #123864 + Removed Compiler Flags - diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index e521cbf678d93..2bd6076bea5d4 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -4711,7 +4711,7 @@ def mexecute_only : Flag<["-"], "mexecute-only">, Group, def mno_execute_only : Flag<["-"], "mno-execute-only">, Group, HelpText<"Allow generation of data access to code sections (ARM only)">; let Flags = [TargetSpecific] in { -def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft,cp15,tpidrurw,tpidruro,tpidrprw,el0,el1,el2,el3,tpidr_el0,tpidr_el1,tpidr_el2,tpidr_el3,tpidrro_el0">, +def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft,cp15,tpidrurw,tpidruro,tpidrprw,el0,el1,el2,el3,tpidr_el0,tpidr_el1,tpidr_el2,tpidr_el3,tpidrro_el0,auto">, HelpText<"Thread pointer access method. " "For AArch32: 'soft' uses a function call, or 'tpidrurw', 'tpidruro' or 'tpidrprw' use the three CP15 registers. 'cp15' is an alias for 'tpidruro'. " "For AArch64: 'tpidr_el0', 'tpidr_el1', 'tpidr_el2', 'tpidr_el3' or 'tpidrro_el0' use the five system registers. 'elN' is an alias for 'tpidr_elN'.">; diff --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp b/clang/lib/Driver/ToolChains/Arch/ARM.cpp index 3aee540d501be..8a431d2b22739 100644 --- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp +++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp @@ -215,14 +215,15 @@ bool arm::isHardTPSupported(const llvm::Triple &Triple) { // Select mode for reading thread pointer (-mtp=soft/cp15). arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args, const llvm::Triple &Triple, bool ForAS) { - if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) { + Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ); + if ((A && A->getValue() != "auto")) { arm::ReadTPMode ThreadPointer = llvm::StringSwitch(A->getValue()) .Case("cp15", ReadTPMode::TPIDRURO) .Case("tpidrurw", ReadTPMode::TPIDRURW) .Case("tpidruro", ReadTPMode::TPIDRURO) .Case("tpidrprw", ReadTPMode::TPIDRPRW) -.Case("soft", ReadTPMode::Soft) +.Case("soft", ReadTPMode::Soft) .Default(ReadTPMode::Invalid); if ((ThreadPointer == ReadTPMode::TPIDRURW || ThreadPointer == ReadTPMode::TPIDRURO || @@ -239,7 +240,7 @@ arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args, D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args); return ReadTPMode::Invalid; } - return ReadTPMode::Soft; + return (isHardTPSupported(Triple) ? ReadTPMode::TPIDRURO : ReadTPMode::Soft); } void arm::setArchNameInTriple(const Driver &D, const ArgList &Args, @@ -574,12 +575,14 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver &D, A->ignoreTargetSpecific(); } - if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRURW) + arm::ReadTPMode TPMode = getReadTPMode(D, Args, Triple, ForAS); + + if (TPMode == ReadTPMode::TPIDRURW) Feature
[clang-tools-extra] 440ea3e - [clangd] Reduce superfluous rename conflicts (#121515)
Author: Ujan RoyBandyopadhyay Date: 2025-02-27T13:06:03-06:00 New Revision: 440ea3ecdcd4aaf9d6c7d729fe7bc695365aed52 URL: https://github.com/llvm/llvm-project/commit/440ea3ecdcd4aaf9d6c7d729fe7bc695365aed52 DIFF: https://github.com/llvm/llvm-project/commit/440ea3ecdcd4aaf9d6c7d729fe7bc695365aed52.diff LOG: [clangd] Reduce superfluous rename conflicts (#121515) This commit adds a namespace check to the code for detecting name collisions, allowing `bar` to be renamed to `foo` in the following snippet: ```c typedef struct foo {} Foo; Foo bar; ``` Previously, such a rename would fail because a declaration for `foo` already exists in the same scope. Added: Modified: clang-tools-extra/clangd/refactor/Rename.cpp clang-tools-extra/clangd/unittests/RenameTests.cpp Removed: diff --git a/clang-tools-extra/clangd/refactor/Rename.cpp b/clang-tools-extra/clangd/refactor/Rename.cpp index c85e13dbdfe97..b7894b8918eed 100644 --- a/clang-tools-extra/clangd/refactor/Rename.cpp +++ b/clang-tools-extra/clangd/refactor/Rename.cpp @@ -338,7 +338,8 @@ const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx, for (const auto &Child : DS->getDeclGroup()) if (const auto *ND = dyn_cast(Child)) if (ND != &RenamedDecl && ND->getDeclName().isIdentifier() && -ND->getName() == Name) +ND->getName() == Name && +ND->getIdentifierNamespace() & RenamedDecl.getIdentifierNamespace()) return ND; return nullptr; }; @@ -380,7 +381,9 @@ const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx, // Also check if there is a name collision with function arguments. if (const auto *Function = ScopeParent->get()) for (const auto *Parameter : Function->parameters()) -if (Parameter->getName() == NewName) +if (Parameter->getName() == NewName && +Parameter->getIdentifierNamespace() & +RenamedDecl.getIdentifierNamespace()) return Parameter; return nullptr; } @@ -405,7 +408,9 @@ const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx, if (const auto *EnclosingFunction = Parent->get()) { // Check for conflicts with other arguments. for (const auto *Parameter : EnclosingFunction->parameters()) - if (Parameter != &RenamedDecl && Parameter->getName() == NewName) + if (Parameter != &RenamedDecl && Parameter->getName() == NewName && + Parameter->getIdentifierNamespace() & + RenamedDecl.getIdentifierNamespace()) return Parameter; // FIXME: We don't modify all references to function parameters when // renaming from forward declaration now, so using a name colliding with @@ -450,7 +455,8 @@ const NamedDecl *lookupSiblingsWithinContext(ASTContext &Ctx, } // Lookup may contain the RenameDecl itself, exclude it. for (const auto *D : LookupResult) -if (D->getCanonicalDecl() != RenamedDecl.getCanonicalDecl()) +if (D->getCanonicalDecl() != RenamedDecl.getCanonicalDecl() && +D->getIdentifierNamespace() & RenamedDecl.getIdentifierNamespace()) return D; return nullptr; } diff --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp b/clang-tools-extra/clangd/unittests/RenameTests.cpp index 15866f43affa0..65558440e36e3 100644 --- a/clang-tools-extra/clangd/unittests/RenameTests.cpp +++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp @@ -1269,6 +1269,39 @@ TEST(RenameTest, Renameable) { )cpp", "conflict", !HeaderFile, "Conflict"}, + {R"cpp( +struct conflict {}; +enum v^ar {}; + )cpp", + "conflict", !HeaderFile, "conflict"}, + + {R"cpp( +struct conflict {}; +int [[v^ar]]; + )cpp", + nullptr, !HeaderFile, "conflict"}, + + {R"cpp( +enum conflict {}; +int [[v^ar]]; + )cpp", + nullptr, !HeaderFile, "conflict"}, + + {R"cpp( +void func(int conflict) { + struct [[t^ag]] {}; +} + )cpp", + nullptr, !HeaderFile, "conflict"}, + + {R"cpp( +void func(void) { + struct conflict {}; + int [[v^ar]]; +} + )cpp", + nullptr, !HeaderFile, "conflict"}, + {R"cpp( void func(int); void [[o^therFunc]](double); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Reduce superfluous rename conflicts (PR #121515)
https://github.com/llvm-beanz closed https://github.com/llvm/llvm-project/pull/121515 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream basic alloca and load support (PR #128792)
https://github.com/bcardosolopes approved this pull request. LGTM if Erich has no further comments https://github.com/llvm/llvm-project/pull/128792 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream global variable linkage types (PR #129072)
@@ -0,0 +1,119 @@ +//===- CIROpsEnumsDialect.h - MLIR Dialect for CIR --*- C++ bcardosolopes wrote: TIL https://github.com/llvm/llvm-project/pull/129072 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream global variable linkage types (PR #129072)
https://github.com/bcardosolopes commented: Great to see this PR Morris! You should also add CIR <-> CIR tests for the linkage types, incubator has some of them. https://github.com/llvm/llvm-project/pull/129072 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream global variable linkage types (PR #129072)
@@ -0,0 +1,11 @@ +// Linkage types of global variables +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o - | FileCheck %s + +int ; bcardosolopes wrote: This new tests uses_this_convention and while the existing-uses-this, I suggest you-keep-this-uniform. https://github.com/llvm/llvm-project/pull/129072 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream basic alloca and load support (PR #128792)
https://github.com/erichkeane approved this pull request. https://github.com/llvm/llvm-project/pull/128792 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits