[clang] [CodeGen] Avoid repeated hash lookup (NFC) (PR #108735)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/108735 None >From 244ac0c6799d4cd1afb4134fbbd711e4250b96d4 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Fri, 13 Sep 2024 21:27:55 -0700 Subject: [PATCH] [CodeGen] Avoid repeated hash lookup (NFC) --- clang/lib/CodeGen/CGOpenMPRuntime.cpp | 7 +-- 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index 807f9881f53f40..7a94c4d522d0c3 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -7815,12 +7815,7 @@ class MappableExprsHandler { const Expr *VarRef = nullptr, bool ForDeviceAddr = false) { if (SkipVarSet.contains(D)) return; - auto It = Info.find(D); - if (It == Info.end()) -It = Info - .insert(std::make_pair( - D, SmallVector, 4>(Total))) - .first; + auto It = Info.try_emplace(D, Total).first; It->second[Kind].emplace_back( L, MapType, MapModifiers, MotionModifiers, ReturnDevicePointer, IsImplicit, Mapper, VarRef, ForDeviceAddr); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Avoid repeated hash lookup (NFC) (PR #108735)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/108735.diff 1 Files Affected: - (modified) clang/lib/CodeGen/CGOpenMPRuntime.cpp (+1-6) ``diff diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index 807f9881f53f40..7a94c4d522d0c3 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -7815,12 +7815,7 @@ class MappableExprsHandler { const Expr *VarRef = nullptr, bool ForDeviceAddr = false) { if (SkipVarSet.contains(D)) return; - auto It = Info.find(D); - if (It == Info.end()) -It = Info - .insert(std::make_pair( - D, SmallVector, 4>(Total))) - .first; + auto It = Info.try_emplace(D, Total).first; It->second[Kind].emplace_back( L, MapType, MapModifiers, MotionModifiers, ReturnDevicePointer, IsImplicit, Mapper, VarRef, ForDeviceAddr); `` https://github.com/llvm/llvm-project/pull/108735 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [TableGen] Avoid repeated hash lookups (NFC) (PR #108736)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/108736 None >From 38db9c4e0d85afd6ece4ca91221205492d374d12 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Fri, 13 Sep 2024 21:32:36 -0700 Subject: [PATCH] [TableGen] Avoid repeated hash lookups (NFC) --- clang/utils/TableGen/ClangAttrEmitter.cpp | 6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index 9b2249ac90bc5c..637484149d4438 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -203,12 +203,11 @@ static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records, // If this attribute has already been handled, it does not need to be // handled again. -if (Seen.find(AN) != Seen.end()) { +if (!Seen.insert(AN).second) { if (Dupes) Dupes->push_back(std::make_pair(AN, Attr)); continue; } -Seen.insert(AN); } else AN = NormalizeAttrName(Attr->getName()).str(); @@ -1824,10 +1823,9 @@ CreateSemanticSpellings(const std::vector &Spellings, // reserved namespace, we may have inadvertently created duplicate // enumerant names. These duplicates are not considered part of the // semantic spelling, and can be elided. -if (Uniques.find(EnumName) != Uniques.end()) +if (!Uniques.insert(EnumName).second) continue; -Uniques.insert(EnumName); if (I != Spellings.begin()) Ret += ",\n"; // Duplicate spellings are not considered part of the semantic spelling ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [TableGen] Avoid repeated hash lookups (NFC) (PR #108736)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/108736.diff 1 Files Affected: - (modified) clang/utils/TableGen/ClangAttrEmitter.cpp (+2-4) ``diff diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index 9b2249ac90bc5c..637484149d4438 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -203,12 +203,11 @@ static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records, // If this attribute has already been handled, it does not need to be // handled again. -if (Seen.find(AN) != Seen.end()) { +if (!Seen.insert(AN).second) { if (Dupes) Dupes->push_back(std::make_pair(AN, Attr)); continue; } -Seen.insert(AN); } else AN = NormalizeAttrName(Attr->getName()).str(); @@ -1824,10 +1823,9 @@ CreateSemanticSpellings(const std::vector &Spellings, // reserved namespace, we may have inadvertently created duplicate // enumerant names. These duplicates are not considered part of the // semantic spelling, and can be elided. -if (Uniques.find(EnumName) != Uniques.end()) +if (!Uniques.insert(EnumName).second) continue; -Uniques.insert(EnumName); if (I != Spellings.begin()) Ret += ",\n"; // Duplicate spellings are not considered part of the semantic spelling `` https://github.com/llvm/llvm-project/pull/108736 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #108738)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/108738 None >From 21dcd68cb908289a77470e8c8878452d25b99200 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Fri, 13 Sep 2024 21:29:51 -0700 Subject: [PATCH] [Frontend] Avoid repeated hash lookups (NFC) --- clang/lib/Frontend/Rewrite/RewriteObjC.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp index 9db6ddbf0b8908..fd5e8dc5298950 100644 --- a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -4111,9 +4111,8 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag) { std::string S; - if (CopyDestroyCache.count(flag)) + if (!CopyDestroyCache.insert(flag).second) return S; - CopyDestroyCache.insert(flag); S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #108738)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/108738.diff 1 Files Affected: - (modified) clang/lib/Frontend/Rewrite/RewriteObjC.cpp (+1-2) ``diff diff --git a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp index 9db6ddbf0b8908..fd5e8dc5298950 100644 --- a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -4111,9 +4111,8 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag) { std::string S; - if (CopyDestroyCache.count(flag)) + if (!CopyDestroyCache.insert(flag).second) return S; - CopyDestroyCache.insert(flag); S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; `` https://github.com/llvm/llvm-project/pull/108738 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [CGData][ThinLTO] Global Outlining with Two-CodeGen Rounds (PR #90933)
https://github.com/kyulee-com updated https://github.com/llvm/llvm-project/pull/90933 >From 95709740e820c0efddb1fdb53436a03194a1b88e Mon Sep 17 00:00:00 2001 From: Kyungwoo Lee Date: Fri, 26 Apr 2024 20:02:52 -0700 Subject: [PATCH 1/2] [ThinLTO][NFC] Prep for two-codegen rounds --- clang/lib/CodeGen/BackendUtil.cpp | 8 ++-- llvm/include/llvm/LTO/LTOBackend.h | 1 + llvm/lib/LTO/LTO.cpp | 75 -- llvm/lib/LTO/LTOBackend.cpp| 6 ++- 4 files changed, 49 insertions(+), 41 deletions(-) diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 7fa69420298160..a1909d45b4d944 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -1286,10 +1286,10 @@ static void runThinLTOBackend( Conf.CGFileType = getCodeGenFileType(Action); break; } - if (Error E = - thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, - ModuleToDefinedGVSummaries[M->getModuleIdentifier()], - /* ModuleMap */ nullptr, CGOpts.CmdArgs)) { + if (Error E = thinBackend( + Conf, -1, AddStream, *M, *CombinedIndex, ImportList, + ModuleToDefinedGVSummaries[M->getModuleIdentifier()], + /* ModuleMap */ nullptr, Conf.CodeGenOnly, CGOpts.CmdArgs)) { handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; }); diff --git a/llvm/include/llvm/LTO/LTOBackend.h b/llvm/include/llvm/LTO/LTOBackend.h index de89f4bb10dff2..8516398510d4b8 100644 --- a/llvm/include/llvm/LTO/LTOBackend.h +++ b/llvm/include/llvm/LTO/LTOBackend.h @@ -56,6 +56,7 @@ Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector *ModuleMap, + bool CodeGenOnly, const std::vector &CmdArgs = std::vector()); Error finalizeOptimizationRemarks( diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp index 5d9a5cbd18f156..400e34527b6c87 100644 --- a/llvm/lib/LTO/LTO.cpp +++ b/llvm/lib/LTO/LTO.cpp @@ -1474,7 +1474,8 @@ class InProcessThinBackend : public ThinBackendProc { return MOrErr.takeError(); return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex, - ImportList, DefinedGlobals, &ModuleMap); + ImportList, DefinedGlobals, &ModuleMap, + Conf.CodeGenOnly); }; auto ModuleID = BM.getModuleIdentifier(); @@ -1840,45 +1841,49 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache, TimeTraceScopeExit.release(); - std::unique_ptr BackendProc = - ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, - AddStream, Cache); - auto &ModuleMap = ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap; - auto ProcessOneModule = [&](int I) -> Error { -auto &Mod = *(ModuleMap.begin() + I); -// Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for -// combined module and parallel code generation partitions. -return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I, - Mod.second, ImportLists[Mod.first], - ExportLists[Mod.first], ResolvedODR[Mod.first], - ThinLTO.ModuleMap); + auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error { +auto ProcessOneModule = [&](int I) -> Error { + auto &Mod = *(ModuleMap.begin() + I); + // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for + // combined module and parallel code generation partitions. + return BackendProcess->start( + RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second, + ImportLists[Mod.first], ExportLists[Mod.first], + ResolvedODR[Mod.first], ThinLTO.ModuleMap); +}; + +if (BackendProcess->getThreadCount() == 1) { + // Process the modules in the order they were provided on the + // command-line. It is important for this codepath to be used for + // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists + // ThinLTO objects in the same order as the inputs, which otherwise would + // affect the final link order. + for (int I = 0, E = ModuleMap.size(); I != E; ++I) +if (Error E = ProcessOneModule(I)) + return E; +} else { + // When executing in parallel, process largest bitsize modules first to + // improve parallelism, and avoid starving the thread pool near the end. + // This saves about 15 sec on a 36-core machine while link `clang.exe` + // (out of 100 sec). + std::vector ModulesVec; + ModulesVec.reserve(ModuleMap.size()); + for
[clang] [llvm] [CGData][ThinLTO] Global Outlining with Two-CodeGen Rounds (PR #90933)
https://github.com/kyulee-com updated https://github.com/llvm/llvm-project/pull/90933 >From c1a0219457a3c162d7fa6b9d70750ba7a040d9f2 Mon Sep 17 00:00:00 2001 From: Kyungwoo Lee Date: Fri, 26 Apr 2024 20:02:52 -0700 Subject: [PATCH 1/2] [ThinLTO][NFC] Prep for two-codegen rounds --- clang/lib/CodeGen/BackendUtil.cpp | 8 ++-- llvm/include/llvm/LTO/LTOBackend.h | 1 + llvm/lib/LTO/LTO.cpp | 75 -- llvm/lib/LTO/LTOBackend.cpp| 6 ++- 4 files changed, 49 insertions(+), 41 deletions(-) diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 7fa69420298160..a1909d45b4d944 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -1286,10 +1286,10 @@ static void runThinLTOBackend( Conf.CGFileType = getCodeGenFileType(Action); break; } - if (Error E = - thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, - ModuleToDefinedGVSummaries[M->getModuleIdentifier()], - /* ModuleMap */ nullptr, CGOpts.CmdArgs)) { + if (Error E = thinBackend( + Conf, -1, AddStream, *M, *CombinedIndex, ImportList, + ModuleToDefinedGVSummaries[M->getModuleIdentifier()], + /* ModuleMap */ nullptr, Conf.CodeGenOnly, CGOpts.CmdArgs)) { handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; }); diff --git a/llvm/include/llvm/LTO/LTOBackend.h b/llvm/include/llvm/LTO/LTOBackend.h index de89f4bb10dff2..8516398510d4b8 100644 --- a/llvm/include/llvm/LTO/LTOBackend.h +++ b/llvm/include/llvm/LTO/LTOBackend.h @@ -56,6 +56,7 @@ Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector *ModuleMap, + bool CodeGenOnly, const std::vector &CmdArgs = std::vector()); Error finalizeOptimizationRemarks( diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp index a88124dacfaefd..f4c25f80811a85 100644 --- a/llvm/lib/LTO/LTO.cpp +++ b/llvm/lib/LTO/LTO.cpp @@ -1473,7 +1473,8 @@ class InProcessThinBackend : public ThinBackendProc { return MOrErr.takeError(); return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex, - ImportList, DefinedGlobals, &ModuleMap); + ImportList, DefinedGlobals, &ModuleMap, + Conf.CodeGenOnly); }; auto ModuleID = BM.getModuleIdentifier(); @@ -1839,45 +1840,49 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache, TimeTraceScopeExit.release(); - std::unique_ptr BackendProc = - ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, - AddStream, Cache); - auto &ModuleMap = ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap; - auto ProcessOneModule = [&](int I) -> Error { -auto &Mod = *(ModuleMap.begin() + I); -// Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for -// combined module and parallel code generation partitions. -return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I, - Mod.second, ImportLists[Mod.first], - ExportLists[Mod.first], ResolvedODR[Mod.first], - ThinLTO.ModuleMap); + auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error { +auto ProcessOneModule = [&](int I) -> Error { + auto &Mod = *(ModuleMap.begin() + I); + // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for + // combined module and parallel code generation partitions. + return BackendProcess->start( + RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second, + ImportLists[Mod.first], ExportLists[Mod.first], + ResolvedODR[Mod.first], ThinLTO.ModuleMap); +}; + +if (BackendProcess->getThreadCount() == 1) { + // Process the modules in the order they were provided on the + // command-line. It is important for this codepath to be used for + // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists + // ThinLTO objects in the same order as the inputs, which otherwise would + // affect the final link order. + for (int I = 0, E = ModuleMap.size(); I != E; ++I) +if (Error E = ProcessOneModule(I)) + return E; +} else { + // When executing in parallel, process largest bitsize modules first to + // improve parallelism, and avoid starving the thread pool near the end. + // This saves about 15 sec on a 36-core machine while link `clang.exe` + // (out of 100 sec). + std::vector ModulesVec; + ModulesVec.reserve(ModuleMap.size()); + for
[clang] [llvm] [CGData][ThinLTO][NFC] Prep for two-codegen rounds (PR #90934)
https://github.com/kyulee-com updated https://github.com/llvm/llvm-project/pull/90934 >From c1a0219457a3c162d7fa6b9d70750ba7a040d9f2 Mon Sep 17 00:00:00 2001 From: Kyungwoo Lee Date: Fri, 26 Apr 2024 20:02:52 -0700 Subject: [PATCH] [ThinLTO][NFC] Prep for two-codegen rounds --- clang/lib/CodeGen/BackendUtil.cpp | 8 ++-- llvm/include/llvm/LTO/LTOBackend.h | 1 + llvm/lib/LTO/LTO.cpp | 75 -- llvm/lib/LTO/LTOBackend.cpp| 6 ++- 4 files changed, 49 insertions(+), 41 deletions(-) diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 7fa69420298160..a1909d45b4d944 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -1286,10 +1286,10 @@ static void runThinLTOBackend( Conf.CGFileType = getCodeGenFileType(Action); break; } - if (Error E = - thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, - ModuleToDefinedGVSummaries[M->getModuleIdentifier()], - /* ModuleMap */ nullptr, CGOpts.CmdArgs)) { + if (Error E = thinBackend( + Conf, -1, AddStream, *M, *CombinedIndex, ImportList, + ModuleToDefinedGVSummaries[M->getModuleIdentifier()], + /* ModuleMap */ nullptr, Conf.CodeGenOnly, CGOpts.CmdArgs)) { handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; }); diff --git a/llvm/include/llvm/LTO/LTOBackend.h b/llvm/include/llvm/LTO/LTOBackend.h index de89f4bb10dff2..8516398510d4b8 100644 --- a/llvm/include/llvm/LTO/LTOBackend.h +++ b/llvm/include/llvm/LTO/LTOBackend.h @@ -56,6 +56,7 @@ Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector *ModuleMap, + bool CodeGenOnly, const std::vector &CmdArgs = std::vector()); Error finalizeOptimizationRemarks( diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp index a88124dacfaefd..f4c25f80811a85 100644 --- a/llvm/lib/LTO/LTO.cpp +++ b/llvm/lib/LTO/LTO.cpp @@ -1473,7 +1473,8 @@ class InProcessThinBackend : public ThinBackendProc { return MOrErr.takeError(); return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex, - ImportList, DefinedGlobals, &ModuleMap); + ImportList, DefinedGlobals, &ModuleMap, + Conf.CodeGenOnly); }; auto ModuleID = BM.getModuleIdentifier(); @@ -1839,45 +1840,49 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache, TimeTraceScopeExit.release(); - std::unique_ptr BackendProc = - ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, - AddStream, Cache); - auto &ModuleMap = ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap; - auto ProcessOneModule = [&](int I) -> Error { -auto &Mod = *(ModuleMap.begin() + I); -// Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for -// combined module and parallel code generation partitions. -return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I, - Mod.second, ImportLists[Mod.first], - ExportLists[Mod.first], ResolvedODR[Mod.first], - ThinLTO.ModuleMap); + auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error { +auto ProcessOneModule = [&](int I) -> Error { + auto &Mod = *(ModuleMap.begin() + I); + // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for + // combined module and parallel code generation partitions. + return BackendProcess->start( + RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second, + ImportLists[Mod.first], ExportLists[Mod.first], + ResolvedODR[Mod.first], ThinLTO.ModuleMap); +}; + +if (BackendProcess->getThreadCount() == 1) { + // Process the modules in the order they were provided on the + // command-line. It is important for this codepath to be used for + // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists + // ThinLTO objects in the same order as the inputs, which otherwise would + // affect the final link order. + for (int I = 0, E = ModuleMap.size(); I != E; ++I) +if (Error E = ProcessOneModule(I)) + return E; +} else { + // When executing in parallel, process largest bitsize modules first to + // improve parallelism, and avoid starving the thread pool near the end. + // This saves about 15 sec on a 36-core machine while link `clang.exe` + // (out of 100 sec). + std::vector ModulesVec; + ModulesVec.reserve(ModuleMap.size()); + for (aut
[clang] [llvm] [CGData][ThinLTO] Global Outlining with Two-CodeGen Rounds (PR #90933)
https://github.com/kyulee-com edited https://github.com/llvm/llvm-project/pull/90933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][TableGen] Support specifying address space in clang builtin prototypes (PR #108497)
vikramRH wrote: Gentle ping @AaronBallman , @philnik777 , @fpetrogalli :) https://github.com/llvm/llvm-project/pull/108497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86][test] Avoid writing to a potentially write-protected dir (PR #108525)
https://github.com/MalaySanghi closed https://github.com/llvm/llvm-project/pull/108525 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86][test] Avoid writing to a potentially write-protected dir (PR #108525)
MalaySanghi wrote: > I have submitted it as > [a41bb71](https://github.com/llvm/llvm-project/commit/a41bb71f2216cef08ab04f1d730ae1701c145f3c) > (with 3 files). Sorry for the race, but I want it working :) Apologies for missing that file and thanks for taking this up. https://github.com/llvm/llvm-project/pull/108525 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #108738)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/108738 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [TableGen] Avoid repeated hash lookups (NFC) (PR #108736)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/108736 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Avoid repeated hash lookup (NFC) (PR #108735)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/108735 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix regression in AlwaysBreak for-await (PR #108634)
https://github.com/owenca approved this pull request. https://github.com/llvm/llvm-project/pull/108634 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix regression in BAS_AlwaysBreak for-await (PR #108634)
https://github.com/owenca edited https://github.com/llvm/llvm-project/pull/108634 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Avoid repeated hash lookup (NFC) (PR #108735)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/108735 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] cc96ce8 - [CodeGen] Avoid repeated hash lookup (NFC) (#108735)
Author: Kazu Hirata Date: 2024-09-15T01:20:29-07:00 New Revision: cc96ce831cda8f70897926fdce6a83519fe5b31e URL: https://github.com/llvm/llvm-project/commit/cc96ce831cda8f70897926fdce6a83519fe5b31e DIFF: https://github.com/llvm/llvm-project/commit/cc96ce831cda8f70897926fdce6a83519fe5b31e.diff LOG: [CodeGen] Avoid repeated hash lookup (NFC) (#108735) Added: Modified: clang/lib/CodeGen/CGOpenMPRuntime.cpp Removed: diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index 807f9881f53f40..7a94c4d522d0c3 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -7815,12 +7815,7 @@ class MappableExprsHandler { const Expr *VarRef = nullptr, bool ForDeviceAddr = false) { if (SkipVarSet.contains(D)) return; - auto It = Info.find(D); - if (It == Info.end()) -It = Info - .insert(std::make_pair( - D, SmallVector, 4>(Total))) - .first; + auto It = Info.try_emplace(D, Total).first; It->second[Kind].emplace_back( L, MapType, MapModifiers, MotionModifiers, ReturnDevicePointer, IsImplicit, Mapper, VarRef, ForDeviceAddr); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 56f061f - [TableGen] Avoid repeated hash lookups (NFC) (#108736)
Author: Kazu Hirata Date: 2024-09-15T01:20:37-07:00 New Revision: 56f061f71b66a01a7f89069873f9c6dcda82b044 URL: https://github.com/llvm/llvm-project/commit/56f061f71b66a01a7f89069873f9c6dcda82b044 DIFF: https://github.com/llvm/llvm-project/commit/56f061f71b66a01a7f89069873f9c6dcda82b044.diff LOG: [TableGen] Avoid repeated hash lookups (NFC) (#108736) Added: Modified: clang/utils/TableGen/ClangAttrEmitter.cpp Removed: diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index 9b2249ac90bc5c..637484149d4438 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -203,12 +203,11 @@ static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records, // If this attribute has already been handled, it does not need to be // handled again. -if (Seen.find(AN) != Seen.end()) { +if (!Seen.insert(AN).second) { if (Dupes) Dupes->push_back(std::make_pair(AN, Attr)); continue; } -Seen.insert(AN); } else AN = NormalizeAttrName(Attr->getName()).str(); @@ -1824,10 +1823,9 @@ CreateSemanticSpellings(const std::vector &Spellings, // reserved namespace, we may have inadvertently created duplicate // enumerant names. These duplicates are not considered part of the // semantic spelling, and can be elided. -if (Uniques.find(EnumName) != Uniques.end()) +if (!Uniques.insert(EnumName).second) continue; -Uniques.insert(EnumName); if (I != Spellings.begin()) Ret += ",\n"; // Duplicate spellings are not considered part of the semantic spelling ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [git-clang-format] Fix: make the tool backward compatible (PR #108721)
owenca wrote: Why do we need to make newer versions of git-clang-format "compatible" with older versions of clang-format? Shouldn't both be from the same LLVM release? https://github.com/llvm/llvm-project/pull/108721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [TableGen] Avoid repeated hash lookups (NFC) (PR #108736)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/108736 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #108738)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/108738 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ba7a0b7 - [Frontend] Avoid repeated hash lookups (NFC) (#108738)
Author: Kazu Hirata Date: 2024-09-15T01:21:00-07:00 New Revision: ba7a0b725c67e9c3a31f5ffedb6fbe4c5237ac56 URL: https://github.com/llvm/llvm-project/commit/ba7a0b725c67e9c3a31f5ffedb6fbe4c5237ac56 DIFF: https://github.com/llvm/llvm-project/commit/ba7a0b725c67e9c3a31f5ffedb6fbe4c5237ac56.diff LOG: [Frontend] Avoid repeated hash lookups (NFC) (#108738) Added: Modified: clang/lib/Frontend/Rewrite/RewriteObjC.cpp Removed: diff --git a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp index 9db6ddbf0b8908..fd5e8dc5298950 100644 --- a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -4111,9 +4111,8 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag) { std::string S; - if (CopyDestroyCache.count(flag)) + if (!CopyDestroyCache.insert(flag).second) return S; - CopyDestroyCache.insert(flag); S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in annotating StartOfName (PR #99791)
owenca wrote: > That is very unfortunate. It means one will either get different results for > the clang-format versions, one disables the formatting, or works around it by > sth. Like Q_EMIT(something()->mySignal()). Or wait for the next release (in this case 19.1.0, which is just around the corner). https://github.com/llvm/llvm-project/pull/99791 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [llvm] [FMV][AArch64] Unify ls64, ls64_v and ls64_accdata. (PR #108024)
@@ -73,8 +73,6 @@ enum CPUFeatures { FEAT_SSBS, FEAT_SSBS2, FEAT_BTI, - FEAT_LS64, - FEAT_LS64_V, Wilco1 wrote: Yes, that's a way to keep backwards compatibility with older ABIs. However we can't break this ABI every compiler release (except perhaps this one time). https://github.com/llvm/llvm-project/pull/108024 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
https://github.com/HerrCai0907 created https://github.com/llvm/llvm-project/pull/108743 Fixes: #82970 Detecting dependiences with `varDecl` is too strict. It will ignore the `bingingDecl`. This patch wants to use `valueDecl` to match more cases including `bingingDecl`. >From b81896cc8c5bef064b7ea3564c2ddd40948e49fb Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sun, 15 Sep 2024 17:00:35 +0800 Subject: [PATCH] [clang-tidy] fix false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer Fixes: #82970 Detecting dependiences with `varDecl` is too strict. It will ignore the `bingingDecl`. This patch wants to use `valueDecl` to match more cases including `bingingDecl`. --- .../PreferMemberInitializerCheck.cpp | 2 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 .../cppcoreguidelines/prefer-member-initializer.cpp | 11 +++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp index e516b71088425b..593a4f85d13091 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp @@ -83,7 +83,7 @@ static void updateAssignmentLevel( memberExpr(hasObjectExpression(cxxThisExpr()), member(fieldDecl(indexNotLessThan(Field->getFieldIndex(); auto DeclMatcher = declRefExpr( - to(varDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); + to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher, hasDescendant(MemberMatcher), hasDescendant(DeclMatcher))), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 88b92830fda6b4..9d3dce5ab5c4ff 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,10 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cppcoreguidelines-prefer-member-initializer + ` check to avoid + false positive when member initialization depends on structured binging variable. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp index e784a350c48f5a..fa4307dec02308 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp @@ -639,3 +639,14 @@ struct S3 { T M; }; } + +namespace GH82970 { +struct InitFromBingingDecl { + int m; + InitFromBingingDecl() { +struct { int i; } a; +auto [n] = a; +m = n; + } +}; +} // namespace GH82970 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Congcong Cai (HerrCai0907) Changes Fixes: #82970 Detecting dependiences with `varDecl` is too strict. It will ignore the `bingingDecl`. This patch wants to use `valueDecl` to match more cases including `bingingDecl`. --- Full diff: https://github.com/llvm/llvm-project/pull/108743.diff 3 Files Affected: - (modified) clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp (+1-1) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp (+11) ``diff diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp index e516b71088425b..593a4f85d13091 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp @@ -83,7 +83,7 @@ static void updateAssignmentLevel( memberExpr(hasObjectExpression(cxxThisExpr()), member(fieldDecl(indexNotLessThan(Field->getFieldIndex(); auto DeclMatcher = declRefExpr( - to(varDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); + to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher, hasDescendant(MemberMatcher), hasDescendant(DeclMatcher))), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 88b92830fda6b4..9d3dce5ab5c4ff 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,10 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cppcoreguidelines-prefer-member-initializer + ` check to avoid + false positive when member initialization depends on structured binging variable. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp index e784a350c48f5a..fa4307dec02308 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp @@ -639,3 +639,14 @@ struct S3 { T M; }; } + +namespace GH82970 { +struct InitFromBingingDecl { + int m; + InitFromBingingDecl() { +struct { int i; } a; +auto [n] = a; +m = n; + } +}; +} // namespace GH82970 `` https://github.com/llvm/llvm-project/pull/108743 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Convert AMDGPUResourceUsageAnalysis pass from Module to MF pass (PR #102913)
@@ -0,0 +1,225 @@ +//===- AMDGPUMCResourceInfo.cpp --- MC Resource Info --===// +// +// 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 +// +//===--===// +// +/// \file +/// \brief MC infrastructure to propagate the function level resource usage +/// info. +/// +//===--===// + +#include "AMDGPUMCResourceInfo.h" +#include "Utils/AMDGPUBaseInfo.h" +#include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/MC/MCContext.h" +#include "llvm/MC/MCSymbol.h" + +using namespace llvm; + +MCSymbol *MCResourceInfo::getSymbol(StringRef FuncName, ResourceInfoKind RIK, +MCContext &OutContext) { + auto GOCS = [this, FuncName, &OutContext](StringRef Suffix) { +return OutContext.getOrCreateSymbol(FuncName + Twine(Suffix)); + }; + switch (RIK) { + case RIK_NumVGPR: +return GOCS(".num_vgpr"); + case RIK_NumAGPR: +return GOCS(".num_agpr"); + case RIK_NumSGPR: +return GOCS(".numbered_sgpr"); + case RIK_PrivateSegSize: +return GOCS(".private_seg_size"); + case RIK_UsesVCC: +return GOCS(".uses_vcc"); + case RIK_UsesFlatScratch: +return GOCS(".uses_flat_scratch"); + case RIK_HasDynSizedStack: +return GOCS(".has_dyn_sized_stack"); + case RIK_HasRecursion: +return GOCS(".has_recursion"); + case RIK_HasIndirectCall: +return GOCS(".has_indirect_call"); + } + llvm_unreachable("Unexpected ResourceInfoKind."); +} + +const MCExpr *MCResourceInfo::getSymRefExpr(StringRef FuncName, +ResourceInfoKind RIK, +MCContext &Ctx) { + return MCSymbolRefExpr::create(getSymbol(FuncName, RIK, Ctx), Ctx); +} + +void MCResourceInfo::assignMaxRegs(MCContext &OutContext) { + // Assign expression to get the max register use to the max_num_Xgpr symbol. + MCSymbol *MaxVGPRSym = getMaxVGPRSymbol(OutContext); + MCSymbol *MaxAGPRSym = getMaxAGPRSymbol(OutContext); + MCSymbol *MaxSGPRSym = getMaxSGPRSymbol(OutContext); + + auto assignMaxRegSym = [this, &OutContext](MCSymbol *Sym, int32_t RegCount) { +const MCExpr *MaxExpr = MCConstantExpr::create(RegCount, OutContext); +Sym->setVariableValue(MaxExpr); + }; + + assignMaxRegSym(MaxVGPRSym, MaxVGPR); + assignMaxRegSym(MaxAGPRSym, MaxAGPR); + assignMaxRegSym(MaxSGPRSym, MaxSGPR); +} + +void MCResourceInfo::finalize(MCContext &OutContext) { + assert(!Finalized && "Cannot finalize ResourceInfo again."); + Finalized = true; + assignMaxRegs(OutContext); +} + +MCSymbol *MCResourceInfo::getMaxVGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_vgpr"); +} + +MCSymbol *MCResourceInfo::getMaxAGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_agpr"); +} + +MCSymbol *MCResourceInfo::getMaxSGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_sgpr"); +} arsenm wrote: I wonder if these should be placed in a custom section. In any case, we will eventually need custom linker logic to deal with this https://github.com/llvm/llvm-project/pull/102913 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Convert AMDGPUResourceUsageAnalysis pass from Module to MF pass (PR #102913)
@@ -0,0 +1,225 @@ +//===- AMDGPUMCResourceInfo.cpp --- MC Resource Info --===// +// +// 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 +// +//===--===// +// +/// \file +/// \brief MC infrastructure to propagate the function level resource usage +/// info. +/// +//===--===// + +#include "AMDGPUMCResourceInfo.h" +#include "Utils/AMDGPUBaseInfo.h" +#include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/MC/MCContext.h" +#include "llvm/MC/MCSymbol.h" + +using namespace llvm; + +MCSymbol *MCResourceInfo::getSymbol(StringRef FuncName, ResourceInfoKind RIK, +MCContext &OutContext) { + auto GOCS = [this, FuncName, &OutContext](StringRef Suffix) { +return OutContext.getOrCreateSymbol(FuncName + Twine(Suffix)); + }; + switch (RIK) { + case RIK_NumVGPR: +return GOCS(".num_vgpr"); + case RIK_NumAGPR: +return GOCS(".num_agpr"); + case RIK_NumSGPR: +return GOCS(".numbered_sgpr"); + case RIK_PrivateSegSize: +return GOCS(".private_seg_size"); + case RIK_UsesVCC: +return GOCS(".uses_vcc"); + case RIK_UsesFlatScratch: +return GOCS(".uses_flat_scratch"); + case RIK_HasDynSizedStack: +return GOCS(".has_dyn_sized_stack"); + case RIK_HasRecursion: +return GOCS(".has_recursion"); + case RIK_HasIndirectCall: +return GOCS(".has_indirect_call"); + } + llvm_unreachable("Unexpected ResourceInfoKind."); +} + +const MCExpr *MCResourceInfo::getSymRefExpr(StringRef FuncName, +ResourceInfoKind RIK, +MCContext &Ctx) { + return MCSymbolRefExpr::create(getSymbol(FuncName, RIK, Ctx), Ctx); +} + +void MCResourceInfo::assignMaxRegs(MCContext &OutContext) { + // Assign expression to get the max register use to the max_num_Xgpr symbol. + MCSymbol *MaxVGPRSym = getMaxVGPRSymbol(OutContext); + MCSymbol *MaxAGPRSym = getMaxAGPRSymbol(OutContext); + MCSymbol *MaxSGPRSym = getMaxSGPRSymbol(OutContext); + + auto assignMaxRegSym = [this, &OutContext](MCSymbol *Sym, int32_t RegCount) { +const MCExpr *MaxExpr = MCConstantExpr::create(RegCount, OutContext); +Sym->setVariableValue(MaxExpr); + }; + + assignMaxRegSym(MaxVGPRSym, MaxVGPR); + assignMaxRegSym(MaxAGPRSym, MaxAGPR); + assignMaxRegSym(MaxSGPRSym, MaxSGPR); +} + +void MCResourceInfo::finalize(MCContext &OutContext) { + assert(!Finalized && "Cannot finalize ResourceInfo again."); + Finalized = true; + assignMaxRegs(OutContext); +} + +MCSymbol *MCResourceInfo::getMaxVGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_vgpr"); +} + +MCSymbol *MCResourceInfo::getMaxAGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_agpr"); +} + +MCSymbol *MCResourceInfo::getMaxSGPRSymbol(MCContext &OutContext) { + return OutContext.getOrCreateSymbol("max_num_sgpr"); +} + +void MCResourceInfo::assignResourceInfoExpr( +int64_t LocalValue, ResourceInfoKind RIK, AMDGPUMCExpr::VariantKind Kind, +const MachineFunction &MF, const SmallVectorImpl &Callees, +MCContext &OutContext) { + const MCConstantExpr *LocalConstExpr = + MCConstantExpr::create(LocalValue, OutContext); + const MCExpr *SymVal = LocalConstExpr; + if (!Callees.empty()) { +SmallVector ArgExprs; +// Avoid recursive symbol assignment. +SmallPtrSet Seen; +ArgExprs.push_back(LocalConstExpr); +const Function &F = MF.getFunction(); +Seen.insert(&F); + +for (const Function *Callee : Callees) { + if (Seen.contains(Callee)) +continue; + Seen.insert(Callee); arsenm wrote: Should combine these by seeing if the insert succeeded https://github.com/llvm/llvm-project/pull/102913 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Convert AMDGPUResourceUsageAnalysis pass from Module to MF pass (PR #102913)
@@ -40,12 +42,19 @@ class AMDGPUAsmPrinter final : public AsmPrinter { AMDGPUResourceUsageAnalysis *ResourceUsage; + MCResourceInfo RI; + SIProgramInfo CurrentProgramInfo; std::unique_ptr HSAMetadataStream; MCCodeEmitter *DumpCodeInstEmitter = nullptr; + // validateMCResourceInfo cannot recompute parts of the occupancy as it does + // for other metadata to validate (e.g., NumSGPRs) so a map is necessary if we + // really want to track and validate the occupancy. arsenm wrote: I don't see why this is the case https://github.com/llvm/llvm-project/pull/102913 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Change CF intrinsics lowering to reconverge on predecessors. (PR #92809)
https://github.com/arsenm closed https://github.com/llvm/llvm-project/pull/92809 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Change CF intrinsics lowering to reconverge on predecessors. (PR #92809)
arsenm wrote: Replaced by #108596 https://github.com/llvm/llvm-project/pull/92809 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] handle invalid close location in static assert declaration (PR #108701)
https://github.com/a-tarasyuk updated https://github.com/llvm/llvm-project/pull/108701 >From cbe06cf33277f904fe002db90d428a55b777ff5d Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sat, 14 Sep 2024 17:02:01 +0300 Subject: [PATCH 1/3] [Clang] handle invalid close location in static assert declaration --- clang/docs/ReleaseNotes.rst| 2 +- clang/lib/Parse/ParseDeclCXX.cpp | 3 ++- clang/test/SemaCXX/static-assert-cxx26.cpp | 3 +++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 79b154ef1aef5e..27dde935ad19b9 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -388,7 +388,7 @@ Bug Fixes to C++ Support - Fixed a crash in the typo correction of an invalid CTAD guide. (#GH107887) - Fixed a crash when clang tries to subtitute parameter pack while retaining the parameter pack. #GH63819, #GH107560 - +- Fix a crash when a static assert declaration has an invalid close location. (#GH108687) Bug Fixes to AST Handling ^ diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp index 6370da1fab0042..6f0f5a0311bc18 100644 --- a/clang/lib/Parse/ParseDeclCXX.cpp +++ b/clang/lib/Parse/ParseDeclCXX.cpp @@ -1109,7 +1109,8 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd) { } } - T.consumeClose(); + if (T.consumeClose()) +return nullptr; DeclEnd = Tok.getLocation(); ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert, TokName); diff --git a/clang/test/SemaCXX/static-assert-cxx26.cpp b/clang/test/SemaCXX/static-assert-cxx26.cpp index 7d896d8b365b74..95ffa8cd68cf7c 100644 --- a/clang/test/SemaCXX/static-assert-cxx26.cpp +++ b/clang/test/SemaCXX/static-assert-cxx26.cpp @@ -415,3 +415,6 @@ static_assert( // expected-note@-1 {{read of dereferenced one-past-the-end pointer is not allowed in a constant expression}} ); } + +static_assert(true, "" // expected-note {{to match this '('}} + // expected-error {{expected ')'}} >From 77063cc64c5047144c2fa0291c38248401d33164 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 15 Sep 2024 00:51:21 +0300 Subject: [PATCH 2/3] add test to cover c++2a compliance --- clang/test/SemaCXX/static-assert-cxx20.cpp | 5 + 1 file changed, 5 insertions(+) create mode 100644 clang/test/SemaCXX/static-assert-cxx20.cpp diff --git a/clang/test/SemaCXX/static-assert-cxx20.cpp b/clang/test/SemaCXX/static-assert-cxx20.cpp new file mode 100644 index 00..479fd14dc5bfad --- /dev/null +++ b/clang/test/SemaCXX/static-assert-cxx20.cpp @@ -0,0 +1,5 @@ +// RUN: %clang_cc1 -std=c++2a -triple=x86_64-linux -fsyntax-only %s -verify + +static_assert(true, "" // expected-warning {{'static_assert' with a user-generated message is a C++26 extension}} \ + // expected-note {{to match this '('}} + // expected-error {{expected ')'}} >From f807d212aebbac2fb31dc25fbac0b1ccc2f46570 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 15 Sep 2024 14:34:04 +0300 Subject: [PATCH 3/3] move tests from SemaXXX to Parser --- clang/test/Parser/static_assert.cpp| 6 ++ clang/test/SemaCXX/static-assert-cxx20.cpp | 5 - clang/test/SemaCXX/static-assert-cxx26.cpp | 3 --- 3 files changed, 6 insertions(+), 8 deletions(-) create mode 100644 clang/test/Parser/static_assert.cpp delete mode 100644 clang/test/SemaCXX/static-assert-cxx20.cpp diff --git a/clang/test/Parser/static_assert.cpp b/clang/test/Parser/static_assert.cpp new file mode 100644 index 00..4fe7d3cda7b214 --- /dev/null +++ b/clang/test/Parser/static_assert.cpp @@ -0,0 +1,6 @@ +// RUN: %clang_cc1 -fsyntax-only -triple=x86_64-linux -std=c++2a -verify=cxx2a %s +// RUN: %clang_cc1 -fsyntax-only -triple=x86_64-linux -std=c++2c -verify=cxx2c %s + +static_assert(true, "" // cxx2a-warning {{'static_assert' with a user-generated message is a C++26 extension}} \ + // cxx2a-note {{to match this '('}} cxx2c-note {{to match this '('}} + // cxx2a-error {{expected ')'}} cxx2c-error {{expected ')'}} diff --git a/clang/test/SemaCXX/static-assert-cxx20.cpp b/clang/test/SemaCXX/static-assert-cxx20.cpp deleted file mode 100644 index 479fd14dc5bfad..00 --- a/clang/test/SemaCXX/static-assert-cxx20.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// RUN: %clang_cc1 -std=c++2a -triple=x86_64-linux -fsyntax-only %s -verify - -static_assert(true, "" // expected-warning {{'static_assert' with a user-generated message is a C++26 extension}} \ - // expected-note {{to match this '('}} - // expected-error {{expected ')'}} diff --git a/clang/test/SemaCXX/static-assert-cxx26.cpp b/clang/test/SemaCXX/static-assert-cxx26.cpp index 95ffa8cd68cf7c..7d896d8b365b74 100644 --- a/clang/test/SemaCXX/static-assert-cxx26.cpp +++ b/clang/test/Se
[clang] [git-clang-format] Fix: make the tool backward compatible (PR #108721)
edenreich wrote: Because I was trying to use this tool with the current stable release of clang-format, and it's currently broken? IDK, or I just wait for the next release of clang-format before I can consider using git-clang-format 🤷♂️ https://github.com/llvm/llvm-project/pull/108721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [git-clang-format] Fix: make the tool backward compatible (PR #108721)
https://github.com/edenreich closed https://github.com/llvm/llvm-project/pull/108721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a56ca1a - [clang][codegen] Fix possible crash when setting TBAA metadata on FP math libcalls (#108575)
Author: Benjamin Maxwell Date: 2024-09-15T13:41:26+01:00 New Revision: a56ca1a0fb248c6f38b5841323a74673748f43ea URL: https://github.com/llvm/llvm-project/commit/a56ca1a0fb248c6f38b5841323a74673748f43ea DIFF: https://github.com/llvm/llvm-project/commit/a56ca1a0fb248c6f38b5841323a74673748f43ea.diff LOG: [clang][codegen] Fix possible crash when setting TBAA metadata on FP math libcalls (#108575) There's currently no code path that can reach this crash, but: ``` Instruction *Inst = cast(Call.getScalarVal()); ``` fails if the call returns `void`. This could happen if a builtin for something like `void sincos(double, double*, double*)` is added to clang. Instead, use the `llvm::CallBase` returned from `EmitCall()` to set the TBAA metadata, which should exist no matter the return type. Added: Modified: clang/lib/CodeGen/CGBuiltin.cpp Removed: diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index a52e880a764252..a76cd5f9a6f47d 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -690,8 +690,10 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E, llvm::Constant *calleeValue) { CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD)); + llvm::CallBase *callOrInvoke = nullptr; RValue Call = - CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot()); + CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot(), + /*Chain=*/nullptr, &callOrInvoke); if (unsigned BuiltinID = FD->getBuiltinID()) { // Check whether a FP math builtin function, such as BI__builtin_expf @@ -705,8 +707,7 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, // Emit "int" TBAA metadata on FP math libcalls. clang::QualType IntTy = Context.IntTy; TBAAAccessInfo TBAAInfo = CGF.CGM.getTBAAAccessInfo(IntTy); - Instruction *Inst = cast(Call.getScalarVal()); - CGF.CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo); + CGF.CGM.DecorateInstructionWithTBAA(callOrInvoke, TBAAInfo); } } return Call; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][codegen] Fix possible crash when setting TBAA metadata on FP math libcalls (PR #108575)
https://github.com/MacDue closed https://github.com/llvm/llvm-project/pull/108575 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Infer amdgpu-no-flat-scratch-init attribute in AMDGPUAttributor (PR #94647)
@@ -434,6 +434,15 @@ struct AAAMDAttributesFunction : public AAAMDAttributes { indicatePessimisticFixpoint(); return; } + +for (Instruction &I : instructions(F)) { + if (isa(I) && arsenm wrote: For a nightmare of an edge case, addrspacecasts from private to flat can exist somewhere in constant expressions. For now, as long as addrspace(5) globals are forbidden, this would only be valid with literal addresses. I'm not sure how defined we should consider that case. But if you follow along with the queue pointer handling, it will work. It already has to handle the 3->0 case in constant expressions https://github.com/llvm/llvm-project/pull/94647 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Infer amdgpu-no-flat-scratch-init attribute in AMDGPUAttributor (PR #94647)
@@ -678,6 +690,37 @@ struct AAAMDAttributesFunction : public AAAMDAttributes { return !A.checkForAllCallLikeInstructions(DoesNotRetrieve, *this, UsedAssumedInformation); } + + // Returns true if FlatScratchInit is needed, i.e., no-flat-scratch-init is + // not to be set. + bool needFlatScratchInit(Attributor &A) { +assert(isAssumed(FLAT_SCRATCH_INIT)); // only called if the bit is still set + +// This is called on each callee; false means callee shouldn't have +// no-flat-scratch-init. +auto CheckForNoFlatScratchInit = [&](Instruction &I) { + const auto &CB = cast(I); + const Function *Callee = CB.getCalledFunction(); + + // Callee == 0 for inline asm or indirect call with known callees. + // In the latter case, updateImpl() already checked the callees and we + // know their FLAT_SCRATCH_INIT bit is set. + // If function has indirect call with unknown callees, the bit is + // already removed in updateImpl() and execution won't reach here. + if (!Callee) +return true; + else arsenm wrote: No else after return https://github.com/llvm/llvm-project/pull/94647 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Infer amdgpu-no-flat-scratch-init attribute in AMDGPUAttributor (PR #94647)
@@ -678,6 +690,37 @@ struct AAAMDAttributesFunction : public AAAMDAttributes { return !A.checkForAllCallLikeInstructions(DoesNotRetrieve, *this, UsedAssumedInformation); } + + // Returns true if FlatScratchInit is needed, i.e., no-flat-scratch-init is + // not to be set. + bool needFlatScratchInit(Attributor &A) { +assert(isAssumed(FLAT_SCRATCH_INIT)); // only called if the bit is still set + +// This is called on each callee; false means callee shouldn't have +// no-flat-scratch-init. +auto CheckForNoFlatScratchInit = [&](Instruction &I) { + const auto &CB = cast(I); arsenm wrote: I would hope FroAllCallLikeInstructions would have a CallBase typed argument to begin with https://github.com/llvm/llvm-project/pull/94647 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] handle invalid close location in static assert declaration (PR #108701)
a-tarasyuk wrote: @zyn0217 Thanks for the detailed feedback. I considered handling it earlier and skipping the validation of the closing parenthesis, but I was concerned the message `"expected ';' after 'static_assert'"` might not be accurate in this case., I assumed `""` is a valid string, even if the next token is invalid - it doesn't make this string itself invalid. ```cpp static_assert(true, "" // expected ';' after 'static_assert' // expected ')' // to match this '(' ``` https://github.com/llvm/llvm-project/pull/108701 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CGData] Clang Options (PR #90304)
https://github.com/kyulee-com edited https://github.com/llvm/llvm-project/pull/90304 ___ 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 false positive that floating point variable only used in increment expr in cert-flp30-c (PR #108706)
@@ -111,6 +111,9 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cert-flp30-c` check to + fix false positive that floating point variable only used in increment expr. EugeneZelenko wrote: `expression`? https://github.com/llvm/llvm-project/pull/108706 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Allow user defined conversion implicit cast to _Complex types in constant expressions (PR #108758)
https://github.com/MitalAshok created https://github.com/llvm/llvm-project/pull/108758 This already worked with `-fexperimental-new-constant-interpreter` Fixes #108750 >From 0a6b4e83318af66888f6297549a806b5d81e4933 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Sun, 15 Sep 2024 15:48:59 +0100 Subject: [PATCH] [Clang] Allow user defined conversion implicit cast to _Complex types in constant expressions --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/AST/ExprConstant.cpp | 2 +- clang/test/AST/ByteCode/complex.cpp | 12 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 485b75049927fe..ec6c71a7bdc38b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -388,6 +388,7 @@ Bug Fixes to C++ Support - Fixed a crash in the typo correction of an invalid CTAD guide. (#GH107887) - Fixed a crash when clang tries to subtitute parameter pack while retaining the parameter pack. #GH63819, #GH107560 +- Implicit user-defined conversions to ``_Complex`` extension types now work in constant expressions. (#GH108750) Bug Fixes to AST Handling diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 4af7752d3b238b..717e7fabaa901e 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -15344,11 +15344,11 @@ bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { case CK_NoOp: case CK_LValueToRValueBitCast: case CK_HLSLArrayRValue: + case CK_UserDefinedConversion: return ExprEvaluatorBaseTy::VisitCastExpr(E); case CK_Dependent: case CK_LValueBitCast: - case CK_UserDefinedConversion: return Error(E); case CK_FloatingRealToComplex: { diff --git a/clang/test/AST/ByteCode/complex.cpp b/clang/test/AST/ByteCode/complex.cpp index dc93c786dac7ae..3d0cb47f4fab2a 100644 --- a/clang/test/AST/ByteCode/complex.cpp +++ b/clang/test/AST/ByteCode/complex.cpp @@ -420,3 +420,15 @@ namespace ComplexConstexpr { static_assert(__imag test6 == 6, ""); static_assert(&__imag test6 == &__real test6 + 1, ""); } + +namespace Casts { + struct UserDefinedConversion { +double val[2]; +constexpr operator _Complex double() const { return { val[0], val[1] }; }; + }; + + constexpr _Complex double zero = UserDefinedConversion{}; + static_assert(zero == 0.0 + 0.0j, ""); + constexpr _Complex double three_four = UserDefinedConversion{3, 4}; + static_assert(three_four == 3.0 + 4.0j, ""); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Allow user defined conversion implicit cast to _Complex types in constant expressions (PR #108758)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Mital Ashok (MitalAshok) Changes This already worked with `-fexperimental-new-constant-interpreter` Fixes #108750 --- Full diff: https://github.com/llvm/llvm-project/pull/108758.diff 3 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+1) - (modified) clang/lib/AST/ExprConstant.cpp (+1-1) - (modified) clang/test/AST/ByteCode/complex.cpp (+12) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 485b75049927fe..ec6c71a7bdc38b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -388,6 +388,7 @@ Bug Fixes to C++ Support - Fixed a crash in the typo correction of an invalid CTAD guide. (#GH107887) - Fixed a crash when clang tries to subtitute parameter pack while retaining the parameter pack. #GH63819, #GH107560 +- Implicit user-defined conversions to ``_Complex`` extension types now work in constant expressions. (#GH108750) Bug Fixes to AST Handling diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 4af7752d3b238b..717e7fabaa901e 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -15344,11 +15344,11 @@ bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { case CK_NoOp: case CK_LValueToRValueBitCast: case CK_HLSLArrayRValue: + case CK_UserDefinedConversion: return ExprEvaluatorBaseTy::VisitCastExpr(E); case CK_Dependent: case CK_LValueBitCast: - case CK_UserDefinedConversion: return Error(E); case CK_FloatingRealToComplex: { diff --git a/clang/test/AST/ByteCode/complex.cpp b/clang/test/AST/ByteCode/complex.cpp index dc93c786dac7ae..3d0cb47f4fab2a 100644 --- a/clang/test/AST/ByteCode/complex.cpp +++ b/clang/test/AST/ByteCode/complex.cpp @@ -420,3 +420,15 @@ namespace ComplexConstexpr { static_assert(__imag test6 == 6, ""); static_assert(&__imag test6 == &__real test6 + 1, ""); } + +namespace Casts { + struct UserDefinedConversion { +double val[2]; +constexpr operator _Complex double() const { return { val[0], val[1] }; }; + }; + + constexpr _Complex double zero = UserDefinedConversion{}; + static_assert(zero == 0.0 + 0.0j, ""); + constexpr _Complex double three_four = UserDefinedConversion{3, 4}; + static_assert(three_four == 3.0 + 4.0j, ""); +} `` https://github.com/llvm/llvm-project/pull/108758 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][NFC] declare internal linkage function static (PR #108759)
https://github.com/HerrCai0907 created https://github.com/llvm/llvm-project/pull/108759 Detected by `misc-use-internal-linkage` >From 3e4add8033e9ca6d3c4b5fb062a6370a07e71381 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sun, 15 Sep 2024 21:18:01 +0800 Subject: [PATCH] [clang][NFC] declare internal linkage function static Detected by `misc-use-internal-linkage` --- clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp | 1 + .../Checkers/RetainCountChecker/RetainCountDiagnostics.cpp | 5 +++-- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp | 4 ++-- .../lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp | 6 +++--- clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp| 4 ++-- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp| 2 +- clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp | 7 --- clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp| 6 +++--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp | 4 ++-- 9 files changed, 21 insertions(+), 18 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp index 5240352a9bd2f9..2107b9c4f5b323 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp @@ -22,6 +22,7 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "llvm/ADT/StringSet.h" +#include "Move.h" using namespace clang; using namespace ento; diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp index f73c9007c18380..456132ef0a0a22 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp @@ -635,8 +635,9 @@ class VarBindingsCollector : public StoreManager::BindingsHandler { }; } // namespace -Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, -const ExplodedNode *Node, SymbolRef Sym) { +static Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, + const ExplodedNode *Node, + SymbolRef Sym) { Bindings Result; VarBindingsCollector Collector{Sym, Result}; while (Result.empty() && Node) { diff --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp index 505020d4bb39fa..321388ad857f44 100644 --- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp @@ -241,7 +241,7 @@ bool SmartPtrModeling::isBoolConversionMethod(const CallEvent &Call) const { constexpr llvm::StringLiteral BASIC_OSTREAM_NAMES[] = {"basic_ostream"}; -bool isStdBasicOstream(const Expr *E) { +static bool isStdBasicOstream(const Expr *E) { const auto *RD = E->getType()->getAsCXXRecordDecl(); return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES); } @@ -250,7 +250,7 @@ static bool isStdFunctionCall(const CallEvent &Call) { return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace(); } -bool isStdOstreamOperatorCall(const CallEvent &Call) { +static bool isStdOstreamOperatorCall(const CallEvent &Call) { if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call)) return false; const auto *FC = dyn_cast(&Call); diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index 5394c2257514dc..1d58e1b02785d6 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -305,7 +305,7 @@ static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) { return nullptr; } -const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { +const static MemRegion *getOriginBaseRegion(const MemRegion *Reg) { Reg = Reg->getBaseRegion(); while (const auto *SymReg = dyn_cast(Reg)) { const auto *OriginReg = SymReg->getSymbol()->getOriginRegion(); @@ -316,7 +316,7 @@ const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { return Reg; } -std::optional printReferrer(const MemRegion *Referrer) { +static std::optional printReferrer(const MemRegion *Referrer) { assert(Referrer); const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) { if (isa(Space)) @@ -354,7 +354,7 @@ std::optional printReferrer(const MemRegion *Referrer) { /// Check whether \p Region refers to a freshly minted symbol after an opaque /// function call. -bool isInvalidatedSymbolRegion(const MemRegion *Region) { +static bool isInvalidatedSymbolRegion(const MemRegion *Region) { const auto *SymReg = Re
[clang] [clang][NFC] declare internal linkage function static (PR #108759)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: Congcong Cai (HerrCai0907) Changes Detected by `misc-use-internal-linkage` --- Full diff: https://github.com/llvm/llvm-project/pull/108759.diff 9 Files Affected: - (modified) clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp (+1) - (modified) clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp (+3-2) - (modified) clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp (+2-2) - (modified) clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp (+3-3) - (modified) clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp (+2-2) - (modified) clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp (+1-1) - (modified) clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (+4-3) - (modified) clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp (+3-3) - (modified) clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (+2-2) ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp index 5240352a9bd2f9..2107b9c4f5b323 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp @@ -22,6 +22,7 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "llvm/ADT/StringSet.h" +#include "Move.h" using namespace clang; using namespace ento; diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp index f73c9007c18380..456132ef0a0a22 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp @@ -635,8 +635,9 @@ class VarBindingsCollector : public StoreManager::BindingsHandler { }; } // namespace -Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, -const ExplodedNode *Node, SymbolRef Sym) { +static Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, + const ExplodedNode *Node, + SymbolRef Sym) { Bindings Result; VarBindingsCollector Collector{Sym, Result}; while (Result.empty() && Node) { diff --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp index 505020d4bb39fa..321388ad857f44 100644 --- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp @@ -241,7 +241,7 @@ bool SmartPtrModeling::isBoolConversionMethod(const CallEvent &Call) const { constexpr llvm::StringLiteral BASIC_OSTREAM_NAMES[] = {"basic_ostream"}; -bool isStdBasicOstream(const Expr *E) { +static bool isStdBasicOstream(const Expr *E) { const auto *RD = E->getType()->getAsCXXRecordDecl(); return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES); } @@ -250,7 +250,7 @@ static bool isStdFunctionCall(const CallEvent &Call) { return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace(); } -bool isStdOstreamOperatorCall(const CallEvent &Call) { +static bool isStdOstreamOperatorCall(const CallEvent &Call) { if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call)) return false; const auto *FC = dyn_cast(&Call); diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index 5394c2257514dc..1d58e1b02785d6 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -305,7 +305,7 @@ static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) { return nullptr; } -const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { +const static MemRegion *getOriginBaseRegion(const MemRegion *Reg) { Reg = Reg->getBaseRegion(); while (const auto *SymReg = dyn_cast(Reg)) { const auto *OriginReg = SymReg->getSymbol()->getOriginRegion(); @@ -316,7 +316,7 @@ const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { return Reg; } -std::optional printReferrer(const MemRegion *Referrer) { +static std::optional printReferrer(const MemRegion *Referrer) { assert(Referrer); const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) { if (isa(Space)) @@ -354,7 +354,7 @@ std::optional printReferrer(const MemRegion *Referrer) { /// Check whether \p Region refers to a freshly minted symbol after an opaque /// function call. -bool isInvalidatedSymbolRegion(const MemRegion *Region) { +static bool isInvalidatedSymbolRegion(const MemRegion *Region) { const auto *SymReg = Region->getAs(); if (!SymReg) return false; diff --git a/clang/lib/StaticAnalyzer/Checkers
[clang] [clang][NFC] declare internal linkage function static (PR #108759)
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 9fc789d922ddf1c849f62bdfbe034f3cd9354967 3e4add8033e9ca6d3c4b5fb062a6370a07e71381 --extensions cpp -- clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp index 2107b9c4f5..52416e2139 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp @@ -12,6 +12,7 @@ // //===--===// +#include "Move.h" #include "clang/AST/Attr.h" #include "clang/AST/ExprCXX.h" #include "clang/Driver/DriverDiagnostic.h" @@ -22,7 +23,6 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "llvm/ADT/StringSet.h" -#include "Move.h" using namespace clang; using namespace ento; `` https://github.com/llvm/llvm-project/pull/108759 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][NFC] declare internal linkage function static (PR #108759)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/108759 >From cf770d55592adb41d072caa5f1aca7cd739d6e2b Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sun, 15 Sep 2024 21:18:01 +0800 Subject: [PATCH] [clang][NFC] declare internal linkage function static Detected by `misc-use-internal-linkage` --- clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp | 1 + .../Checkers/RetainCountChecker/RetainCountDiagnostics.cpp | 5 +++-- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp | 4 ++-- .../lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp | 6 +++--- clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp| 4 ++-- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp| 2 +- clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp | 7 --- clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp| 6 +++--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp | 4 ++-- 9 files changed, 21 insertions(+), 18 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp index 5240352a9bd2f9..2107b9c4f5b323 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp @@ -22,6 +22,7 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "llvm/ADT/StringSet.h" +#include "Move.h" using namespace clang; using namespace ento; diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp index f73c9007c18380..456132ef0a0a22 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp @@ -635,8 +635,9 @@ class VarBindingsCollector : public StoreManager::BindingsHandler { }; } // namespace -Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, -const ExplodedNode *Node, SymbolRef Sym) { +static Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, + const ExplodedNode *Node, + SymbolRef Sym) { Bindings Result; VarBindingsCollector Collector{Sym, Result}; while (Result.empty() && Node) { diff --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp index 505020d4bb39fa..321388ad857f44 100644 --- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp @@ -241,7 +241,7 @@ bool SmartPtrModeling::isBoolConversionMethod(const CallEvent &Call) const { constexpr llvm::StringLiteral BASIC_OSTREAM_NAMES[] = {"basic_ostream"}; -bool isStdBasicOstream(const Expr *E) { +static bool isStdBasicOstream(const Expr *E) { const auto *RD = E->getType()->getAsCXXRecordDecl(); return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES); } @@ -250,7 +250,7 @@ static bool isStdFunctionCall(const CallEvent &Call) { return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace(); } -bool isStdOstreamOperatorCall(const CallEvent &Call) { +static bool isStdOstreamOperatorCall(const CallEvent &Call) { if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call)) return false; const auto *FC = dyn_cast(&Call); diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index 5394c2257514dc..d8c52941b19366 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -305,7 +305,7 @@ static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) { return nullptr; } -const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { +static const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { Reg = Reg->getBaseRegion(); while (const auto *SymReg = dyn_cast(Reg)) { const auto *OriginReg = SymReg->getSymbol()->getOriginRegion(); @@ -316,7 +316,7 @@ const MemRegion *getOriginBaseRegion(const MemRegion *Reg) { return Reg; } -std::optional printReferrer(const MemRegion *Referrer) { +static std::optional printReferrer(const MemRegion *Referrer) { assert(Referrer); const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) { if (isa(Space)) @@ -354,7 +354,7 @@ std::optional printReferrer(const MemRegion *Referrer) { /// Check whether \p Region refers to a freshly minted symbol after an opaque /// function call. -bool isInvalidatedSymbolRegion(const MemRegion *Region) { +static bool isInvalidatedSymbolRegion(const MemRegion *Region) { const auto *SymReg = Region->getAs(); if (!SymReg) return
[clang] [Clang] Allow user defined conversion implicit cast to _Complex types in constant expressions (PR #108758)
https://github.com/philnik777 approved this pull request. https://github.com/llvm/llvm-project/pull/108758 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix evaluation of the unsigned enumeration values, #108766 (PR #108769)
https://github.com/fursov created https://github.com/llvm/llvm-project/pull/108769 If the type of an enumeration is not native (e.g. uint8_t) but is unsigned then evaluation of the value might get wrong: for values bigger than half of type range the return value will be negative. This happens because for non-native enum types the TypeKind is ELABORATED. To get the real integer type, the conversion to canonical type is required before the enum_value() function can decide about type being signed or unsigned. This is fix for ticket #108766: https://github.com/llvm/llvm-project/issues/108766 >From 800010fabe3160e701ff58f7789dd9e01c80451f Mon Sep 17 00:00:00 2001 From: Dmitry Fursov Date: Sun, 15 Sep 2024 18:14:48 +0300 Subject: [PATCH] Fix evaluation of the unsigned enumeration values If the type of an enumeration is not native (e.g. uint8_t) but is unsigned then evaluation of the value might get wrong: for values bigger than half of type range the return value will be negative. This happens because for non-native enum types the TypeKind is ELABORATED. To get the real integer type, the conversion to canonical type is required before the enum_value() function can decide about type being signed or unsigned. --- clang/bindings/python/clang/cindex.py | 2 ++ .../python/tests/cindex/test_cursor.py| 19 +++ 2 files changed, 21 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 4da99e899e7f7c..c582c82ce50789 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -1952,6 +1952,8 @@ def enum_value(self): underlying_type = self.type if underlying_type.kind == TypeKind.ENUM: underlying_type = underlying_type.get_declaration().enum_type +if underlying_type.kind == TypeKind.ELABORATED: +underlying_type = underlying_type.get_canonical() if underlying_type.kind in ( TypeKind.CHAR_U, TypeKind.UCHAR, diff --git a/clang/bindings/python/tests/cindex/test_cursor.py b/clang/bindings/python/tests/cindex/test_cursor.py index 7476947bde2ea6..61a7bc1414f235 100644 --- a/clang/bindings/python/tests/cindex/test_cursor.py +++ b/clang/bindings/python/tests/cindex/test_cursor.py @@ -570,6 +570,25 @@ def test_enum_values_cpp(self): self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) self.assertEqual(ham.enum_value, 0x100) +def test_enum_values_on_elaborated_type(self): +tu = get_tu( +"using myUType = unsigned char; enum TEST : myUType { SPAM = 1, HAM = 0xff;", lang="cpp" +) +enum = get_cursor(tu, "TEST") +self.assertIsNotNone(enum) + +self.assertEqual(enum.kind, CursorKind.ENUM_DECL) + +enum_constants = list(enum.get_children()) +self.assertEqual(len(enum_constants), 2) + +spam, ham = enum_constants + +self.assertEqual(spam.kind, CursorKind.ENUM_CONSTANT_DECL) +self.assertEqual(spam.enum_value, 1) +self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) +self.assertEqual(ham.enum_value, 255) + def test_annotation_attribute(self): tu = get_tu( 'int foo (void) __attribute__ ((annotate("here be annotation attribute")));' ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix evaluation of the unsigned enumeration values, #108766 (PR #108769)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/108769 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix evaluation of the unsigned enumeration values, #108766 (PR #108769)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Dmitry Fursov (fursov) Changes If the type of an enumeration is not native (e.g. uint8_t) but is unsigned then evaluation of the value might get wrong: for values bigger than half of type range the return value will be negative. This happens because for non-native enum types the TypeKind is ELABORATED. To get the real integer type, the conversion to canonical type is required before the enum_value() function can decide about type being signed or unsigned. This is fix for ticket #108766: https://github.com/llvm/llvm-project/issues/108766 --- Full diff: https://github.com/llvm/llvm-project/pull/108769.diff 2 Files Affected: - (modified) clang/bindings/python/clang/cindex.py (+2) - (modified) clang/bindings/python/tests/cindex/test_cursor.py (+19) ``diff diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 4da99e899e7f7c..c582c82ce50789 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -1952,6 +1952,8 @@ def enum_value(self): underlying_type = self.type if underlying_type.kind == TypeKind.ENUM: underlying_type = underlying_type.get_declaration().enum_type +if underlying_type.kind == TypeKind.ELABORATED: +underlying_type = underlying_type.get_canonical() if underlying_type.kind in ( TypeKind.CHAR_U, TypeKind.UCHAR, diff --git a/clang/bindings/python/tests/cindex/test_cursor.py b/clang/bindings/python/tests/cindex/test_cursor.py index 7476947bde2ea6..61a7bc1414f235 100644 --- a/clang/bindings/python/tests/cindex/test_cursor.py +++ b/clang/bindings/python/tests/cindex/test_cursor.py @@ -570,6 +570,25 @@ def test_enum_values_cpp(self): self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) self.assertEqual(ham.enum_value, 0x100) +def test_enum_values_on_elaborated_type(self): +tu = get_tu( +"using myUType = unsigned char; enum TEST : myUType { SPAM = 1, HAM = 0xff;", lang="cpp" +) +enum = get_cursor(tu, "TEST") +self.assertIsNotNone(enum) + +self.assertEqual(enum.kind, CursorKind.ENUM_DECL) + +enum_constants = list(enum.get_children()) +self.assertEqual(len(enum_constants), 2) + +spam, ham = enum_constants + +self.assertEqual(spam.kind, CursorKind.ENUM_CONSTANT_DECL) +self.assertEqual(spam.enum_value, 1) +self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) +self.assertEqual(ham.enum_value, 255) + def test_annotation_attribute(self): tu = get_tu( 'int foo (void) __attribute__ ((annotate("here be annotation attribute")));' `` https://github.com/llvm/llvm-project/pull/108769 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add nuw attribute to GEPs (PR #105496)
TerrorJack wrote: This breaks wasm codegen: https://github.com/llvm/llvm-project/issues/108770 https://github.com/llvm/llvm-project/pull/105496 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Propagate elide safe context through [[clang::coro_must_await]] (PR #108474)
@@ -880,14 +898,12 @@ ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand, } auto *RD = Promise->getType()->getAsCXXRecordDecl(); - bool AwaitElidable = - isCoroAwaitElidableCall(Operand) && - isAttributedCoroAwaitElidable( - getCurFunctionDecl(/*AllowLambda=*/true)->getReturnType()); - - if (AwaitElidable) -if (auto *Call = dyn_cast(Operand->IgnoreImplicit())) - Call->setCoroElideSafe(); + + bool CurFnAwaitElidable = isAttributedCoroAwaitElidable( + getCurFunctionDecl(/*AllowLambda=*/true)->getReturnType()); yuxuanchen1997 wrote: This is not the piece of code that performs this check. See `applySafeElideContext`. But what you said is potentially a good point, we actually skipped checking two things: `operator co_await` on the callee return object, and the `await_transform`. As these operations may not be safe. The original intention was to make this a user's liability to ensure early caller destruction cannot happen in both customization points. It's not as granular as I'd like. With this patch, we are actually making it possible. `await_transform` and `operator co_await` here are just function calls whose arguments can be attributed with `[[clang::coro_must_await]]`. https://github.com/llvm/llvm-project/pull/108474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Propagate elide safe context through [[clang::coro_must_await]] (PR #108474)
@@ -8261,12 +8261,19 @@ def CoroAwaitElidableDoc : Documentation { The ``[[clang::coro_await_elidable]]`` is a class attribute which can be applied to a coroutine return type. -When a coroutine function that returns such a type calls another coroutine function, -the compiler performs heap allocation elision when the call to the coroutine function -is immediately co_awaited as a prvalue. In this case, the coroutine frame for the -callee will be a local variable within the enclosing braces in the caller's stack -frame. And the local variable, like other variables in coroutines, may be collected -into the coroutine frame, which may be allocated on the heap. +When a coroutine function returns such a type, a direct call expression therein +that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]`` +is said to be under a safe elide context if one of the following is true: yuxuanchen1997 wrote: > If I am reading the code correctly, it is not actually a requirement that the > containing / callee coroutine itself is also annotated as coro_await_elidable. It is required. See `CurFnAwaitElidable`. Your example call to `foo()` of `NonElidableTask` won't have any elisions because we don't control `NonElidableTask::Promise::await_transform`. https://github.com/llvm/llvm-project/pull/108474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[HIP] Use original file path for CUID" (PR #108771)
https://github.com/dyung created https://github.com/llvm/llvm-project/pull/108771 Reverts llvm/llvm-project#107734 The test modified in this commit, hip-cuid-hash.hip is failing on MacOS: - https://lab.llvm.org/buildbot/#/builders/190/builds/5764 - https://lab.llvm.org/buildbot/#/builders/23/builds/3020 >From f5d42938f209cb1f814ef8db78c7755fe31e2c5c Mon Sep 17 00:00:00 2001 From: dyung Date: Sun, 15 Sep 2024 09:37:28 -0700 Subject: [PATCH] Revert "[HIP] Use original file path for CUID (#107734)" This reverts commit 9fc789d922ddf1c849f62bdfbe034f3cd9354967. --- clang/lib/Driver/Driver.cpp | 5 - clang/test/Driver/hip-cuid-hash.hip | 12 +--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 758fd744fd46c2..efe398dd531da7 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -3034,7 +3034,10 @@ class OffloadingActionBuilder final { else if (UseCUID == CUID_Hash) { llvm::MD5 Hasher; llvm::MD5::MD5Result Hash; -Hasher.update(IA->getInputArg().getValue()); +SmallString<256> RealPath; +llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, + /*expand_tilde=*/true); +Hasher.update(RealPath); for (auto *A : Args) { if (A->getOption().matches(options::OPT_INPUT)) continue; diff --git a/clang/test/Driver/hip-cuid-hash.hip b/clang/test/Driver/hip-cuid-hash.hip index 6987a98470c6c7..103a1cbf26d50a 100644 --- a/clang/test/Driver/hip-cuid-hash.hip +++ b/clang/test/Driver/hip-cuid-hash.hip @@ -1,15 +1,13 @@ // Check CUID generated by hash. // The same CUID is generated for the same file with the same options. -// RUN: cd %S - // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=SAME -input-file %t.out @@ -18,15 +16,15 @@ // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=1 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=2 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=DIFF -input-file %t.out -// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:3c08c1ef86ef439d]]" +// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" // SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID]]" // DIFF: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[HIP] Use original file path for CUID" (PR #108771)
https://github.com/dyung closed https://github.com/llvm/llvm-project/pull/108771 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 4e09d7b - Revert "[HIP] Use original file path for CUID" (#108771)
Author: dyung Date: 2024-09-15T09:40:55-07:00 New Revision: 4e09d7bc2ce492c4fc281cfbaf8caa81a76a6a10 URL: https://github.com/llvm/llvm-project/commit/4e09d7bc2ce492c4fc281cfbaf8caa81a76a6a10 DIFF: https://github.com/llvm/llvm-project/commit/4e09d7bc2ce492c4fc281cfbaf8caa81a76a6a10.diff LOG: Revert "[HIP] Use original file path for CUID" (#108771) Reverts llvm/llvm-project#107734 The test modified in this commit, hip-cuid-hash.hip is failing on MacOS: - https://lab.llvm.org/buildbot/#/builders/190/builds/5764 - https://lab.llvm.org/buildbot/#/builders/23/builds/3020 Added: Modified: clang/lib/Driver/Driver.cpp clang/test/Driver/hip-cuid-hash.hip Removed: diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 758fd744fd46c2..efe398dd531da7 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -3034,7 +3034,10 @@ class OffloadingActionBuilder final { else if (UseCUID == CUID_Hash) { llvm::MD5 Hasher; llvm::MD5::MD5Result Hash; -Hasher.update(IA->getInputArg().getValue()); +SmallString<256> RealPath; +llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, + /*expand_tilde=*/true); +Hasher.update(RealPath); for (auto *A : Args) { if (A->getOption().matches(options::OPT_INPUT)) continue; diff --git a/clang/test/Driver/hip-cuid-hash.hip b/clang/test/Driver/hip-cuid-hash.hip index 6987a98470c6c7..103a1cbf26d50a 100644 --- a/clang/test/Driver/hip-cuid-hash.hip +++ b/clang/test/Driver/hip-cuid-hash.hip @@ -1,15 +1,13 @@ // Check CUID generated by hash. // The same CUID is generated for the same file with the same options. -// RUN: cd %S - // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=SAME -input-file %t.out @@ -18,15 +16,15 @@ // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=1 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=2 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=DIFF -input-file %t.out -// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:3c08c1ef86ef439d]]" +// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" // SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID]]" // DIFF: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[HIP] Use original file path for CUID" (PR #108771)
llvmbot wrote: @llvm/pr-subscribers-clang @llvm/pr-subscribers-clang-driver Author: None (dyung) Changes Reverts llvm/llvm-project#107734 The test modified in this commit, hip-cuid-hash.hip is failing on MacOS: - https://lab.llvm.org/buildbot/#/builders/190/builds/5764 - https://lab.llvm.org/buildbot/#/builders/23/builds/3020 --- Full diff: https://github.com/llvm/llvm-project/pull/108771.diff 2 Files Affected: - (modified) clang/lib/Driver/Driver.cpp (+4-1) - (modified) clang/test/Driver/hip-cuid-hash.hip (+5-7) ``diff diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 758fd744fd46c2..efe398dd531da7 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -3034,7 +3034,10 @@ class OffloadingActionBuilder final { else if (UseCUID == CUID_Hash) { llvm::MD5 Hasher; llvm::MD5::MD5Result Hash; -Hasher.update(IA->getInputArg().getValue()); +SmallString<256> RealPath; +llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, + /*expand_tilde=*/true); +Hasher.update(RealPath); for (auto *A : Args) { if (A->getOption().matches(options::OPT_INPUT)) continue; diff --git a/clang/test/Driver/hip-cuid-hash.hip b/clang/test/Driver/hip-cuid-hash.hip index 6987a98470c6c7..103a1cbf26d50a 100644 --- a/clang/test/Driver/hip-cuid-hash.hip +++ b/clang/test/Driver/hip-cuid-hash.hip @@ -1,15 +1,13 @@ // Check CUID generated by hash. // The same CUID is generated for the same file with the same options. -// RUN: cd %S - // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=SAME -input-file %t.out @@ -18,15 +16,15 @@ // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=1 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 +// RUN: %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1 // RUN: %clang -### -x hip --target=x86_64-unknown-linux-gnu -DX=2 --no-offload-new-driver \ // RUN: --offload-arch=gfx906 -c -nogpuinc -nogpulib -fuse-cuid=hash \ -// RUN: Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 +// RUN: %S/Inputs/../Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1 // RUN: FileCheck %s -check-prefixes=DIFF -input-file %t.out -// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:3c08c1ef86ef439d]]" +// SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" // SAME: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID]]" // DIFF: "-cc1"{{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]" `` https://github.com/llvm/llvm-project/pull/108771 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[HIP] Use original file path for CUID" (PR #108771)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `openmp-offload-amdgpu-runtime` running on `omp-vega20-0` while building `clang` at step 7 "Add check check-offload". Full details are available at: https://lab.llvm.org/buildbot/#/builders/30/builds/6211 Here is the relevant piece of the build log for the reference ``` Step 7 (Add check check-offload) failure: test (failure) TEST 'libomptarget :: amdgcn-amd-amdhsa :: sanitizer/kernel_crash_async.c' FAILED Exit Code: 1 Command Output (stdout): -- # RUN: at line 2 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang -fopenmp-I /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -nogpulib -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -fopenmp-targets=amdgcn-amd-amdhsa -O3 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c -o /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a # executed command: /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang -fopenmp -I /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -nogpulib -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -fopenmp-targets=amdgcn-amd-amdhsa -O3 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c -o /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a # note: command had no output on stdout or stderr # RUN: at line 3 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash env -u LLVM_DISABLE_SYMBOLIZATION OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp 2>&1 | /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c --check-prefixes=TRACE # executed command: /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash env -u LLVM_DISABLE_SYMBOLIZATION OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp # note: command had no output on stdout or stderr # executed command: /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c --check-prefixes=TRACE # note: command had no output on stdout or stderr # RUN: at line 4 /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp 2>&1 | /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c --check-prefixes=CHECK # executed command: /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash /home/ompworker/bbot/op
[clang] [Clang] Propagate elide safe context through [[clang::coro_must_await]] (PR #108474)
https://github.com/vogelsgesang edited https://github.com/llvm/llvm-project/pull/108474 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
https://github.com/carlosgalvezp updated https://github.com/llvm/llvm-project/pull/108083 >From cb4ea5f12c72dd547d6ae3e742e99d717289344e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= Date: Tue, 10 Sep 2024 13:46:51 + Subject: [PATCH] [clang-tidy] Create bugprone-bit-cast-pointers check To detect unsafe use of bit_cast. Otherwise, bit_cast bypasses all checks done by compilers and linters. Fixes #106987 --- .../bugprone/BitCastPointersCheck.cpp | 32 ++ .../bugprone/BitCastPointersCheck.h | 34 +++ .../bugprone/BugproneTidyModule.cpp | 3 ++ .../clang-tidy/bugprone/CMakeLists.txt| 1 + clang-tools-extra/docs/ReleaseNotes.rst | 6 +++ .../checks/bugprone/bit-cast-pointers.rst | 42 +++ .../checkers/bugprone/bit-cast-pointers.cpp | 34 +++ 7 files changed, 152 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/bit-cast-pointers.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/bit-cast-pointers.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp new file mode 100644 index 00..30c026fba150a5 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp @@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); +} + +void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x")) +diag(MatchedDecl->getBeginLoc(), + "do not use std::bit_cast on pointers; use it on values instead"); +} + +} // namespace clang::tidy::bugprone diff --git a/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h new file mode 100644 index 00..d7c23c187dae34 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h @@ -0,0 +1,34 @@ +//===--- BitCastPointersCheck.h - clang-tidy *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Warns about usage of ``std::bit_cast`` when the input and output types are +/// pointers. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/bit-cast-pointers.html +class BitCastPointersCheck : public ClangTidyCheck { +public: + BitCastPointersCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { +return LangOpts.CPlusPlus20; + } +}; + +} // namespace clang::tidy::bugprone + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 689eb92a3d8d17..931624224d784b 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -14,6 +14,7 @@ #include "AssertSideEffectCheck.h" #include "AssignmentInIfConditionCheck.h" #include "BadSig
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); carlosgalvezp wrote: Yes, that's correct. I think maybe this can be added as an extension in a follow-up patch if needed. Right now we cover the most common pitfall; if people want to workaround the check it will always be possible to do that one way or another. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); +} + +void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x")) +diag(MatchedDecl->getBeginLoc(), + "do not use std::bit_cast on pointers; use it on values instead"); carlosgalvezp wrote: I'm not sure I follow, how should I change the code? https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); +} + +void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x")) carlosgalvezp wrote: In general it's good practice to check for null pointers, it's done in many tidy checks and is cheap to do. Node that the `getNodeAs` can return a nullptr even if there is a match, but it was not possible to cast to the chosen type. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,34 @@ +//===--- BitCastPointersCheck.h - clang-tidy *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Warns about usage of ``std::bit_cast`` when the input and output types are +/// pointers. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/bit-cast-pointers.html +class BitCastPointersCheck : public ClangTidyCheck { +public: + BitCastPointersCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { +return LangOpts.CPlusPlus20; + } +}; carlosgalvezp wrote: I'm not familiar with traversal kinds, how should I change the code? What benefits would it bring? (Should the default traversal kind be changed in the add_new_check.py script?) https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
https://github.com/carlosgalvezp edited https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); 5chmidti wrote: Sounds good https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); +} + +void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x")) +diag(MatchedDecl->getBeginLoc(), + "do not use std::bit_cast on pointers; use it on values instead"); 5chmidti wrote: Steaming (`<<`) a source range into the diagnostic will underline the whole range: ``` 18:16: warning: do not use std::bit_cast on pointers; use it on values instead [bugprone-bit-cast-pointers] 18 | float bad = *std::bit_cast(&x); // UB, but looks safe due to std::bit_cast |^ ``` vs ``` 18:16: warning: do not use std::bit_cast on pointers; use it on values instead [bugprone-bit-cast-pointers] 18 | float bad = *std::bit_cast(&x); // UB, but looks safe due to std::bit_cast |^ ``` ```c++ diag(MatchedDecl->getBeginLoc(), "do not use std::bit_cast on pointers; use it on values instead") << MatchedDecl.getSourceRange(); ``` In case of FixItHint's, their replacement/deletion ranges are also highlighted in this way. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,32 @@ +//===--- BitCastPointersCheck.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 "BitCastPointersCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) { + auto IsPointerType = refersToType(qualType(isAnyPointer())); + Finder->addMatcher(callExpr(callee(functionDecl(allOf( + hasName("::std::bit_cast"), + hasTemplateArgument(0, IsPointerType), + hasTemplateArgument(1, IsPointerType) + .bind("x"), + this); +} + +void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x")) 5chmidti wrote: > Note that the `getNodeAs` can return a nullptr even if there is a match, but > it was not possible to cast to the chosen type. true > it's done in many tidy checks and is cheap to do I think some of the newer ones don't do that, but yes, it is cheap. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,34 @@ +//===--- BitCastPointersCheck.h - clang-tidy *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Warns about usage of ``std::bit_cast`` when the input and output types are +/// pointers. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/bit-cast-pointers.html +class BitCastPointersCheck : public ClangTidyCheck { +public: + BitCastPointersCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { +return LangOpts.CPlusPlus20; + } +}; 5chmidti wrote: Actually, if it were changed, template instantiations are ignored, so this shouldn't be done in this case, my bad. TLDR: The `IgnoreUnlessSpelledInSource` traversal will ignore everything that the compiler will have to generate. E.g., implicit casts, generated special member functions, template instantiations, lambda structs, This allows for simpler matchers because they may not have to consider implicit casts, but can also improve performance because less analysis will be done. > Should the default traversal kind be changed in the add_new_check.py script? IMO no, because the default case is checking everything and including every AST node. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)
@@ -0,0 +1,34 @@ +// RUN: %check_clang_tidy -std=c++20-or-later %s bugprone-bit-cast-pointers %t + +namespace std +{ +template +To bit_cast(From from) +{ + // Dummy implementation for the purpose of the test. + // We don't want to include to get std::memcpy. + To to{}; + return to; +} +} + +void pointer2pointer() +{ + int x{}; + float bad = *std::bit_cast(&x); // UB, but looks safe due to std::bit_cast + // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: do not use std::bit_cast on pointers; use it on values instead [bugprone-bit-cast-pointers] + float good = std::bit_cast(x); // Well-defined +} 5chmidti wrote: Could you add ```c++ using IntPtr = int*; using FloatPtr = float*; IntPtr i; float bad2 = *std::bit_cast(i); ``` to the test as well? It passes, but aliased types should be tested as well. https://github.com/llvm/llvm-project/pull/108083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [llvm] [X86] AMD Zen 5 Initial enablement (PR #107964)
https://github.com/RKSimon demilestoned https://github.com/llvm/llvm-project/pull/107964 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
@@ -10,6 +10,9 @@ modernize-avoid-c-arrays Finds C-style array types and recommend to use ``std::array<>`` / ``std::vector<>``. All types of C arrays are diagnosed. +For incomplete C-style array types appeared in parameters, It would be better to +use ``std::span`` / ``gsl::span`` as replacement. + 5chmidti wrote: `appearing in parameters, it` or even better IMO: `For parameters of incomplete C-style array type, it would` https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
@@ -72,11 +74,29 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) { void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) { const auto *ArrayType = Result.Nodes.getNodeAs("typeloc"); - + const bool IsInParam = + Result.Nodes.getNodeAs("param_decl") != nullptr; + const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType(); + enum class RecommendType { Array, Vector, Span }; + llvm::SmallVector RecommendTypes{}; + if (IsVLA) { +RecommendTypes.push_back("std::vector<>"); + } else if (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam) { +// in function parameter, we also don't know the size of +// IncompleteArrayType. +if (Result.Context->getLangOpts().CPlusPlus20) + RecommendTypes.push_back("std::span<>"); +else { + RecommendTypes.push_back("std::array<>"); + RecommendTypes.push_back("std::vector<>"); +} + } else { +RecommendTypes.push_back("std::array<>"); 5chmidti wrote: While you are here, could you wrap these in `'`? The current implementation didn't do this either https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
@@ -112,8 +112,9 @@ Changes in existing checks the offending code with ``reinterpret_cast``, to more clearly express intent. - Improved :doc:`modernize-avoid-c-arrays - ` check to suggest use std::span - as replacement of c array in C++20. + ` check to suggest using + ``std::span`` as replacement of incomplete C array in C++20 and ``std::vector`` + in the versions before C++20. 5chmidti wrote: What do you think about > to suggest using ``std::span`` as a replacement for parameters of incomplete > C array type in C++20 and ``std::array`` or ``std::vector`` before C++20. https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
https://github.com/5chmidti edited https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
https://github.com/5chmidti approved this pull request. LGTM, just small nits. But wait for others to approve as well https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
@@ -72,11 +74,29 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) { void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) { const auto *ArrayType = Result.Nodes.getNodeAs("typeloc"); - + const bool IsInParam = + Result.Nodes.getNodeAs("param_decl") != nullptr; + const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType(); + enum class RecommendType { Array, Vector, Span }; + llvm::SmallVector RecommendTypes{}; + if (IsVLA) { +RecommendTypes.push_back("std::vector<>"); + } else if (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam) { +// in function parameter, we also don't know the size of +// IncompleteArrayType. +if (Result.Context->getLangOpts().CPlusPlus20) + RecommendTypes.push_back("std::span<>"); +else { + RecommendTypes.push_back("std::array<>"); + RecommendTypes.push_back("std::vector<>"); +} + } else { +RecommendTypes.push_back("std::array<>"); + } + llvm::errs() << llvm::join(RecommendTypes, " or ") << "\n"; 5chmidti wrote: There is a leftover `llvm::errs` from debugging here. https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
https://github.com/5chmidti edited https://github.com/llvm/llvm-project/pull/108555 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [LLVM] Add IRNormalizer Pass (PR #68176)
justinfargnoli wrote: Ping @plotfi @nikic for review. https://github.com/llvm/llvm-project/pull/68176 ___ 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 false positive that floating point variable only used in increment expr in cert-flp30-c (PR #108706)
@@ -9,22 +9,33 @@ #include "FloatLoopCounter.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" using namespace clang::ast_matchers; namespace clang::tidy::cert { void FloatLoopCounter::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher( - forStmt(hasIncrement(expr(hasType(realFloatingPointType().bind("for"), - this); + Finder->addMatcher(forStmt(hasIncrement(forEachDescendant( + declRefExpr(hasType(realFloatingPointType()), + to(varDecl().bind("var"), + hasCondition(forEachDescendant(declRefExpr( + hasType(realFloatingPointType()), + to(varDecl(equalsBoundNode("var"))) + .bind("for"), + this); } void FloatLoopCounter::check(const MatchFinder::MatchResult &Result) { const auto *FS = Result.Nodes.getNodeAs("for"); - diag(FS->getInc()->getExprLoc(), "loop induction expression should not have " - "floating-point type"); + diag(FS->getInc()->getBeginLoc(), "loop induction expression should not have " +"floating-point type"); 5chmidti wrote: Thoughts on binding both `declRefExpr`s and streaming their source ranges into the diagnostic? ``` for (float val = 0.1f; val <= 1.0f; val += 0.1f) {} ~~~ ^~~ ``` (probably also changing the diag location to the `declRefExpr` in the increment as well) You could also add the name of the bound variable to the diagnostic https://github.com/llvm/llvm-project/pull/108706 ___ 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 false positive that floating point variable only used in increment expr in cert-flp30-c (PR #108706)
https://github.com/5chmidti approved this pull request. https://github.com/llvm/llvm-project/pull/108706 ___ 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 false positive that floating point variable only used in increment expr in cert-flp30-c (PR #108706)
@@ -111,6 +111,9 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cert-flp30-c` check to + fix false positive that floating point variable only used in increment expr. 5chmidti wrote: nit: `where a floating point variable is only` https://github.com/llvm/llvm-project/pull/108706 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
https://github.com/5chmidti edited https://github.com/llvm/llvm-project/pull/108743 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
https://github.com/5chmidti approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/108743 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
@@ -111,6 +111,10 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cppcoreguidelines-prefer-member-initializer + ` check to avoid + false positive when member initialization depends on structured binging variable. 5chmidti wrote: `on a structured binding variable` https://github.com/llvm/llvm-project/pull/108743 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 713a202 - [CGData] Clang Options (#90304)
Author: Kyungwoo Lee Date: 2024-09-15T16:04:42-07:00 New Revision: 713a2029578eb36a29793105948d8e4fe965da18 URL: https://github.com/llvm/llvm-project/commit/713a2029578eb36a29793105948d8e4fe965da18 DIFF: https://github.com/llvm/llvm-project/commit/713a2029578eb36a29793105948d8e4fe965da18.diff LOG: [CGData] Clang Options (#90304) This adds new Clang flags to support codegen (CG) data: - `-fcodegen-data-generate{=path}`: This flag passes `-codegen-data-generate` as a boolean to the LLVM backend, causing the raw CG data to be emitted into a custom section. Currently, for LLD MachO only, it also passes `--codegen-data-generate-path=` so that the indexed CG data file can be automatically produced at link time. For linkers that do not yet support this feature, `llvm-cgdata` can be used manually to merge this CG data in object files. - `-fcodegen-data-use{=path}`: This flag passes `-codegen-data-use-path=` to the LLVM backend, enabling the use of specified CG data to optimistically outline functions. - The default `` is set to `default.cgdata` when not specified. This depends on https://github.com/llvm/llvm-project/pull/108733. This is a patch for https://discourse.llvm.org/t/rfc-enhanced-machine-outliner-part-2-thinlto-nolto/78753. Added: clang/test/Driver/codegen-data.c Modified: clang/docs/UsersManual.rst clang/include/clang/Driver/Options.td clang/lib/Driver/ToolChains/CommonArgs.cpp clang/lib/Driver/ToolChains/Darwin.cpp Removed: diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst index f27fa4ace917ea..57d78f867bab6e 100644 --- a/clang/docs/UsersManual.rst +++ b/clang/docs/UsersManual.rst @@ -2410,6 +2410,39 @@ are listed below. link-time optimizations like whole program inter-procedural basic block reordering. +.. option:: -fcodegen-data-generate[=] + + Emit the raw codegen (CG) data into custom sections in the object file. + Currently, this option also combines the raw CG data from the object files + into an indexed CG data file specified by the , for LLD MachO only. + When the is not specified, `default.cgdata` is created. + The CG data file combines all the outlining instances that occurred locally + in each object file. + + .. code-block:: console + +$ clang -fuse-ld=lld -Oz -fcodegen-data-generate code.cc + + For linkers that do not yet support this feature, `llvm-cgdata` can be used + manually to merge this CG data in object files. + + .. code-block:: console + +$ clang -c -fuse-ld=lld -Oz -fcodegen-data-generate code.cc +$ llvm-cgdata --merge -o default.cgdata code.o + +.. option:: -fcodegen-data-use[=] + + Read the codegen data from the specified path to more effectively outline + functions across compilation units. When the is not specified, + `default.cgdata` is used. This option can create many identically outlined + functions that can be optimized by the conventional linker’s identical code + folding (ICF). + + .. code-block:: console + +$ clang -fuse-ld=lld -Oz -Wl,--icf=safe -fcodegen-data-use code.cc + Profile Guided Optimization --- diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index dc8bfc69e9889b..7f123335ce8cfa 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -1894,6 +1894,18 @@ def fprofile_selected_function_group : Visibility<[ClangOption, CC1Option]>, MetaVarName<"">, HelpText<"Partition functions into N groups using -fprofile-function-groups and select only functions in group i to be instrumented. The valid range is 0 to N-1 inclusive">, MarshallingInfoInt>; +def fcodegen_data_generate_EQ : Joined<["-"], "fcodegen-data-generate=">, +Group, Visibility<[ClangOption, CLOption]>, MetaVarName<"">, +HelpText<"Emit codegen data into the object file. LLD for MachO (currently) merges them into the specified .">; +def fcodegen_data_generate : Flag<["-"], "fcodegen-data-generate">, +Group, Visibility<[ClangOption, CLOption]>, Alias, AliasArgs<["default.cgdata"]>, +HelpText<"Emit codegen data into the object file. LLD for MachO (currently) merges them into default.cgdata.">; +def fcodegen_data_use_EQ : Joined<["-"], "fcodegen-data-use=">, +Group, Visibility<[ClangOption, CLOption]>, MetaVarName<"">, +HelpText<"Use codegen data read from the specified .">; +def fcodegen_data_use : Flag<["-"], "fcodegen-data-use">, +Group, Visibility<[ClangOption, CLOption]>, Alias, AliasArgs<["default.cgdata"]>, +HelpText<"Use codegen data read from default.cgdata to optimize the binary">; def fswift_async_fp_EQ : Joined<["-"], "fswift-async-fp=">, Group, Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption]>, diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp index f58b816a9709dd..502aba2ce4aa9c
[clang] [CGData] Clang Options (PR #90304)
https://github.com/kyulee-com closed https://github.com/llvm/llvm-project/pull/90304 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Add `[[hlsl::contained_type()]]` attribute (PR #108456)
https://github.com/bogner approved this pull request. https://github.com/llvm/llvm-project/pull/108456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Add `[[hlsl::contained_type()]]` attribute (PR #108456)
@@ -30,15 +29,15 @@ RWBuffer Buffer; // CHECK-NEXT: CXXRecordDecl 0x{{[0-9A-Fa-f]+}} <> implicit class RWBuffer definition // CHECK: FinalAttr 0x{{[0-9A-Fa-f]+}} <> Implicit final -// CHECK-NEXT: implicit h 'element_type * {{\[\[}}hlsl::resource_class(UAV)]]':'element_type *' +// CHECK-NEXT: implicit h 'element_type * {{\[\[}}hlsl::resource_class(UAV)]] {{\[\[}}hlsl::contained_type(element_type)]]':'element_type *' // CHECK-NEXT: HLSLResourceAttr 0x{{[0-9A-Fa-f]+}} <> Implicit TypedBuffer // CHECK: CXXMethodDecl 0x{{[0-9A-Fa-f]+}} <> operator[] 'element_type &const (unsigned int) const' // CHECK-NEXT: ParmVarDecl 0x{{[0-9A-Fa-f]+}} <> Idx 'unsigned int' // CHECK-NEXT: CompoundStmt 0x{{[0-9A-Fa-f]+}} <> // CHECK-NEXT: ReturnStmt 0x{{[0-9A-Fa-f]+}} <> // CHECK-NEXT: ArraySubscriptExpr 0x{{[0-9A-Fa-f]+}} <> 'element_type' lvalue -// CHECK-NEXT: MemberExpr 0x{{[0-9A-Fa-f]+}} <> 'element_type * {{\[\[}}hlsl::resource_class(UAV)]]':'element_type *' lvalue .h 0x{{[0-9A-Fa-f]+}} +// CHECK-NEXT: MemberExpr 0x{{[0-9A-Fa-f]+}} <> 'element_type * {{\[\[}}hlsl::resource_class(UAV)]] {{\[\[}}hlsl::contained_type(element_type)]]':'element_type *' lvalue .h 0x{{[0-9A-Fa-f]+}} bogner wrote: These checks are starting to get a little unwieldy with multiple attributes and the somewhat awkward `[[` escaping. I wonder whether these could all be made more readable with some use of `CHECK-SAME` and FileCheck's "LITERAL" modifier? I'm not sure if that will make it more readable or less though since it will necessitate splitting the checks across a few lines. https://github.com/llvm/llvm-project/pull/108456 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Add `[[hlsl::contained_type()]]` attribute (PR #108456)
https://github.com/bogner edited https://github.com/llvm/llvm-project/pull/108456 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/108743 >From b81896cc8c5bef064b7ea3564c2ddd40948e49fb Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sun, 15 Sep 2024 17:00:35 +0800 Subject: [PATCH 1/2] [clang-tidy] fix false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer Fixes: #82970 Detecting dependiences with `varDecl` is too strict. It will ignore the `bingingDecl`. This patch wants to use `valueDecl` to match more cases including `bingingDecl`. --- .../PreferMemberInitializerCheck.cpp | 2 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 .../cppcoreguidelines/prefer-member-initializer.cpp | 11 +++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp index e516b71088425b..593a4f85d13091 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp @@ -83,7 +83,7 @@ static void updateAssignmentLevel( memberExpr(hasObjectExpression(cxxThisExpr()), member(fieldDecl(indexNotLessThan(Field->getFieldIndex(); auto DeclMatcher = declRefExpr( - to(varDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); + to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher, hasDescendant(MemberMatcher), hasDescendant(DeclMatcher))), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 88b92830fda6b4..9d3dce5ab5c4ff 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,10 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cppcoreguidelines-prefer-member-initializer + ` check to avoid + false positive when member initialization depends on structured binging variable. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp index e784a350c48f5a..fa4307dec02308 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp @@ -639,3 +639,14 @@ struct S3 { T M; }; } + +namespace GH82970 { +struct InitFromBingingDecl { + int m; + InitFromBingingDecl() { +struct { int i; } a; +auto [n] = a; +m = n; + } +}; +} // namespace GH82970 >From 7e7febeaeb8a209e5dbd88acb754ec2a5925903a Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Mon, 16 Sep 2024 07:56:22 +0800 Subject: [PATCH 2/2] fix releasenote --- clang-tools-extra/docs/ReleaseNotes.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 9d3dce5ab5c4ff..aea428016159b8 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -113,7 +113,8 @@ Changes in existing checks - Improved :doc:`cppcoreguidelines-prefer-member-initializer ` check to avoid - false positive when member initialization depends on structured binging variable. + false positive when member initialization depends on a structured binging + variable. - Improved :doc:`modernize-use-std-format ` check to support replacing ___ 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 false positive that floating point variable only used in increment expr in cert-flp30-c (PR #108706)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/108706 >From 9fbbc1821c41a75a3a606f4a8bb0a7c43fe9dee3 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sat, 14 Sep 2024 23:25:36 +0800 Subject: [PATCH 1/2] [clang-tidy] fix false positive that floating point variable only used in increment expr in cert-flp30-c Fixes: #108049 cert-flp30-c only provides non-compliant example with normal loop. Essentially it wants to avoid that floating point variables are used as loop counters which are checked in condition expr and modified in increment expr. This patch wants to give more precise matcheres to identify this cases. --- .../clang-tidy/cert/FloatLoopCounter.cpp | 21 + clang-tools-extra/docs/ReleaseNotes.rst | 3 +++ .../test/clang-tidy/checkers/cert/flp30-c.c | 23 +-- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/clang-tools-extra/clang-tidy/cert/FloatLoopCounter.cpp b/clang-tools-extra/clang-tidy/cert/FloatLoopCounter.cpp index a9363837597867..ecaa078cc44fa5 100644 --- a/clang-tools-extra/clang-tidy/cert/FloatLoopCounter.cpp +++ b/clang-tools-extra/clang-tidy/cert/FloatLoopCounter.cpp @@ -9,22 +9,33 @@ #include "FloatLoopCounter.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" using namespace clang::ast_matchers; namespace clang::tidy::cert { void FloatLoopCounter::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher( - forStmt(hasIncrement(expr(hasType(realFloatingPointType().bind("for"), - this); + Finder->addMatcher(forStmt(hasIncrement(forEachDescendant( + declRefExpr(hasType(realFloatingPointType()), + to(varDecl().bind("var"), + hasCondition(forEachDescendant(declRefExpr( + hasType(realFloatingPointType()), + to(varDecl(equalsBoundNode("var"))) + .bind("for"), + this); } void FloatLoopCounter::check(const MatchFinder::MatchResult &Result) { const auto *FS = Result.Nodes.getNodeAs("for"); - diag(FS->getInc()->getExprLoc(), "loop induction expression should not have " - "floating-point type"); + diag(FS->getInc()->getBeginLoc(), "loop induction expression should not have " +"floating-point type"); + + if (!FS->getInc()->getType()->isRealFloatingType()) +if (const auto *V = Result.Nodes.getNodeAs("var")) + diag(V->getBeginLoc(), "floating-point type loop induction variable", + DiagnosticIDs::Note); } } // namespace clang::tidy::cert diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 88b92830fda6b4..12638ec66c913a 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,9 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cert-flp30-c` check to + fix false positive that floating point variable only used in increment expr. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cert/flp30-c.c b/clang-tools-extra/test/clang-tidy/checkers/cert/flp30-c.c index eee16bee3d82f4..b9985887a81c53 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cert/flp30-c.c +++ b/clang-tools-extra/test/clang-tidy/checkers/cert/flp30-c.c @@ -1,19 +1,28 @@ // RUN: %check_clang_tidy %s cert-flp30-c %t float g(void); +int c(float); +float f = 1.0f; + +void match(void) { -void func(void) { for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} - // CHECK-MESSAGES: :[[@LINE-1]]:37: warning: loop induction expression should not have floating-point type [cert-flp30-c] + // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: loop induction expression should not have floating-point type [cert-flp30-c] - float f = 1.0f; for (; f > 0; --f) {} - // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop induction expression + // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop induction expression should not have floating-point type [cert-flp30-c] - for (;;g()) {} - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: loop induction expression + for (float x = 0.0f; c(x); x = g()) {} + // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: loop induction expression should not have floating-point type [cert-flp30-c] - for (int i = 0; i < 10; i += 1.0f) {} + for (int i=0; i < 10 && f < 2.0f; f++, i++) {} + // CHECK-MESSAGES: :[[@LINE-1]]:37: warning: loop induction expression should not have floating-point type [cert-flp30-c] + // CHECK-MESSAGES: :5:1: note: floating-point type loop inductio
[clang-tools-extra] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays (PR #108555)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/108555 >From 35742b5f2f085b8f6626456cd0d21ebecbe8f831 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 12 Sep 2024 23:11:51 +0800 Subject: [PATCH 1/4] [clang-tidy]suggest use `std::span` as replacement of c array in C++20 for modernize-avoid-c-arrays --- .../modernize/AvoidCArraysCheck.cpp | 26 --- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/avoid-c-arrays-c++20.cpp| 7 + .../modernize/avoid-c-arrays-ignores-main.cpp | 6 ++--- .../avoid-c-arrays-ignores-strings.cpp| 4 +-- .../avoid-c-arrays-ignores-three-arg-main.cpp | 10 +++ .../checkers/modernize/avoid-c-arrays.cpp | 4 +-- 7 files changed, 46 insertions(+), 15 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-c++20.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp index 89790ea70cf229..9fd0259ed1aacf 100644 --- a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp @@ -9,6 +9,7 @@ #include "AvoidCArraysCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" using namespace clang::ast_matchers; @@ -38,6 +39,13 @@ AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) { return FD ? FD->isMain() : false; } +AST_MATCHER_P(clang::TypeLoc, alwaysTrue, + clang::ast_matchers::internal::Matcher, + InnerMatcher) { + InnerMatcher.matches(Node, Finder, Builder); + return true; +} + } // namespace AvoidCArraysCheck::AvoidCArraysCheck(StringRef Name, ClangTidyContext *Context) @@ -60,6 +68,7 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( typeLoc(hasValidBeginLoc(), hasType(arrayType()), + alwaysTrue(hasParent(parmVarDecl().bind("param_decl"))), unless(anyOf(hasParent(parmVarDecl(isArgvOfMain())), hasParent(varDecl(isExternC())), hasParent(fieldDecl( @@ -72,11 +81,22 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) { void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) { const auto *ArrayType = Result.Nodes.getNodeAs("typeloc"); - + bool const IsInParam = + Result.Nodes.getNodeAs("param_decl") != nullptr; + const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType(); + // in function parameter, we also don't know the size of IncompleteArrayType. + const bool IsUnknownSize = + IsVLA || (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam); + enum class RecommendType { Array, Vector, Span }; + const RecommendType RecommendType = + (IsInParam && Result.Context->getLangOpts().CPlusPlus20) + ? RecommendType::Span + : IsUnknownSize ? RecommendType::Vector + : RecommendType::Array; diag(ArrayType->getBeginLoc(), "do not declare %select{C-style|C VLA}0 arrays, use " - "%select{std::array<>|std::vector<>}0 instead") - << ArrayType->getTypePtr()->isVariableArrayType(); + "%select{std::array<>|std::vector<>|std::span<>}1 instead") + << IsVLA << static_cast(RecommendType); } } // namespace clang::tidy::modernize diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 1ad8cedc902cb5..c5a2b3c36d130f 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,10 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`modernize-avoid-c-arrays + ` check to suggest use std::span + as replacement of c array in C++20. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-c++20.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-c++20.cpp new file mode 100644 index 00..a9298245feaaeb --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-c++20.cpp @@ -0,0 +1,7 @@ +// RUN: %check_clang_tidy -std=c++20 %s modernize-avoid-c-arrays %t + +int foo(int data[], int size) { + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: do not declare C-style arrays, use std::span<> instead + int f4[] = {1, 2}; + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-main.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-main.cpp index 6549422f393aaa
[clang-tools-extra] 7deca85 - [clang-tidy] fix false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (#108743)
Author: Congcong Cai Date: 2024-09-16T09:04:32+08:00 New Revision: 7deca859e55faf9662c54a00b6e333826d717e19 URL: https://github.com/llvm/llvm-project/commit/7deca859e55faf9662c54a00b6e333826d717e19 DIFF: https://github.com/llvm/llvm-project/commit/7deca859e55faf9662c54a00b6e333826d717e19.diff LOG: [clang-tidy] fix false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (#108743) Fixes: #82970 Detecting dependiences with `varDecl` is too strict. It will ignore the `bingingDecl`. This patch wants to use `valueDecl` to match more cases including `bingingDecl`. Added: Modified: clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp index e516b71088425b..593a4f85d13091 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp @@ -83,7 +83,7 @@ static void updateAssignmentLevel( memberExpr(hasObjectExpression(cxxThisExpr()), member(fieldDecl(indexNotLessThan(Field->getFieldIndex(); auto DeclMatcher = declRefExpr( - to(varDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); + to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor); const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher, hasDescendant(MemberMatcher), hasDescendant(DeclMatcher))), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 88b92830fda6b4..aea428016159b8 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -111,6 +111,11 @@ Changes in existing checks ` check to suggest replacing the offending code with ``reinterpret_cast``, to more clearly express intent. +- Improved :doc:`cppcoreguidelines-prefer-member-initializer + ` check to avoid + false positive when member initialization depends on a structured binging + variable. + - Improved :doc:`modernize-use-std-format ` check to support replacing member function calls too. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp index e784a350c48f5a..fa4307dec02308 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp @@ -639,3 +639,14 @@ struct S3 { T M; }; } + +namespace GH82970 { +struct InitFromBingingDecl { + int m; + InitFromBingingDecl() { +struct { int i; } a; +auto [n] = a; +m = n; + } +}; +} // namespace GH82970 ___ 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 false positive when member initialization depends on structured binging variable in cppcoreguidelines-prefer-member-initializer (PR #108743)
https://github.com/HerrCai0907 closed https://github.com/llvm/llvm-project/pull/108743 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits