[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
https://github.com/ChuanqiXu9 created https://github.com/llvm/llvm-project/pull/114193 Reproducer: ``` //--- a.cppm export module a; int func(); static int a = func(); //--- a.cpp import a; ``` The `func()` should only execute once. However, before this patch we will somehow import `static int a` from a.cppm incorrectly and initialize that again. This is super bad and can introduce serious runtime behaviors. And also surprisingly, it looks like the root cause of the problem is simply some oversight choosing APIs. >From a0139db2a3be898f7d548e6796636419816dbca1 Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Wed, 30 Oct 2024 16:48:52 +0800 Subject: [PATCH] [C++20] [Modules] Fix the duplicated static initializer problem Reproducer: ``` //--- a.cppm export module a; int func(); static int a = func(); //--- a.cpp import a; ``` The `func()` should only execute once. However, before this patch we will somehow import `static int a` from a.cppm incorrectly and initialize that again. This is super bad and can introduce serious runtime behaviors. And also surprisingly, it looks like the root cause of the problem is simply some oversight choosing APIs. --- clang/lib/CodeGen/CodeGenModule.cpp| 4 ++-- clang/test/Modules/static-initializer.cppm | 18 ++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 clang/test/Modules/static-initializer.cppm diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 2bcca5e85bdfeb..ba376f9ecfacde 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -7146,8 +7146,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { // For C++ standard modules we are done - we will call the module // initializer for imported modules, and that will likewise call those for // any imports it has. -if (CXX20ModuleInits && Import->getImportedOwningModule() && -!Import->getImportedOwningModule()->isModuleMapModule()) +if (CXX20ModuleInits && Import->getImportedModule() && +Import->getImportedModule()->isNamedModule()) break; // For clang C++ module map modules the initializers for sub-modules are diff --git a/clang/test/Modules/static-initializer.cppm b/clang/test/Modules/static-initializer.cppm new file mode 100644 index 00..10d4854ee67fa6 --- /dev/null +++ b/clang/test/Modules/static-initializer.cppm @@ -0,0 +1,18 @@ +// RUN: rm -rf %t +// RUN: mkdir -p %t +// RUN: split-file %s %t +// +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cpp -fmodule-file=a=%t/a.pcm -emit-llvm -o - | FileCheck %t/a.cpp + +//--- a.cppm +export module a; +int func(); +static int a = func(); + +//--- a.cpp +import a; + +// CHECK-NOT: internal global +// CHECK-NOT: __cxx_global_var_init + ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Model more wide-character versions of string functions (PR #113908)
@@ -2524,8 +2625,33 @@ void CStringChecker::evalStdCopyCommon(CheckerContext &C, C.addTransition(State); } -void CStringChecker::evalMemset(CheckerContext &C, -const CallEvent &Call) const { +namespace { +CharUnits getSizeOfUnit(CharKind CK, CheckerContext &C) { + assert(CK == CK_Regular || CK == CK_Wide); + auto UnitType = + CK == CK_Regular ? C.getASTContext().CharTy : C.getASTContext().WCharTy; + + return C.getASTContext().getTypeSizeInChars(UnitType); +} + +SVal getCharValCast(CharKind CK, CheckerContext &C, ProgramStateRef State, +const Expr *CharE) { + const LocationContext *LCtx = C.getLocationContext(); + auto CharVal = State->getSVal(CharE, LCtx); + if (CK == CK_Regular) { +auto &svalBuilder = C.getSValBuilder(); +const auto &Ctx = C.getASTContext(); +// With the semantic of 'memset()', we should convert the CharVal to +// unsigned char. +return svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy); + } + return CharVal; +} + +} // namespace steakhal wrote: ```suggestion ``` https://github.com/llvm/llvm-project/pull/113908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reapply "[Clang][Sema] Refactor collection of multi-level template argument lists (#106585, #111173)" (PR #111852)
asmok-g wrote: Any updates on this ? This is blocking us in google. When do we expect the fix to be submitted ? https://github.com/llvm/llvm-project/pull/111852 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Update the lifetimebound example with up-to-date expected warning and change the sample code to be a fully working example (PR #113437)
@@ -3702,20 +3702,32 @@ user-declared functions. For example: .. code-block:: c++ +#include +#include + +using namespace std::literals; + // Returns m[key] if key is present, or default_value if not. template const U &get_or_default(const std::map &m [[clang::lifetimebound]], bricknerb wrote: I didn't change this one. However, it makes sense to me since the function returns either a reference to a value in the map or the default value so both could be referred to from the return value. https://github.com/llvm/llvm-project/pull/113437 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
ChuanqiXu9 wrote: Given the problem is very serious and the solution is pretty simple, I'd like to backport this to 19.x. https://github.com/llvm/llvm-project/pull/114193 ___ 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 a check for signed and unsigned integers comparison (PR #113144)
@@ -0,0 +1,165 @@ +//===--- UseIntegerSignComparisonCheck.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 "UseIntegerSignComparisonCheck.h" +#include "clang/AST/Expr.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; +using namespace clang::ast_matchers::internal; + +namespace clang::tidy::modernize { +UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), + IsQtApplication(Options.get("IsQtApplication", false)), + StringsMatchHeader(Options.get("StringsMatchHeader", "")) {} + +void UseIntegerSignComparisonCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IsQtApplication", IsQtApplication); + Options.store(Opts, "StringsMatchHeader", StringsMatchHeader); +} + +void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) { + const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression"); + const auto UnSignedIntCastExpr = + intCastExpression(false, "uIntCastExpression"); + + // Flag all operators "==", "<=", ">=", "<", ">", "!=" + // that are used between signed/unsigned + const auto CompareOperator = + expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="), + anyOf(allOf(hasLHS(SignedIntCastExpr), + hasRHS(UnSignedIntCastExpr)), +allOf(hasLHS(UnSignedIntCastExpr), + hasRHS(SignedIntCastExpr) + .bind("intComparison"); + + Finder->addMatcher(CompareOperator, this); +} + +BindableMatcher UseIntegerSignComparisonCheck::intCastExpression( +bool IsSigned, const std::string &CastBindName) const { + auto IntTypeExpr = expr(); + if (IsSigned) { +IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(; + } else { +IntTypeExpr = +expr(hasType(qualType(isInteger(), unless(isSignedInteger(); + } + + const auto ImplicitCastExpr = + implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName); + + const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr)); + const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr)); + const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr)); + + return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr, + StaticCastExpr, FunctionalCastExpr))); +} + +std::string +UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const { + switch (code) { + case BO_LT: +return std::string("cmp_less"); + case BO_GT: +return std::string("cmp_greater"); + case BO_LE: +return std::string("cmp_less_equal"); + case BO_GE: +return std::string("cmp_greater_equal"); + case BO_EQ: +return std::string("cmp_equal"); + case BO_NE: +return std::string("cmp_not_equal"); + default: +return {}; + } +} + +void UseIntegerSignComparisonCheck::registerPPCallbacks( +const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + IncludeInserter.registerPreprocessor(PP); +} + +void UseIntegerSignComparisonCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *SignedCastExpression = + Result.Nodes.getNodeAs("sIntCastExpression"); + const auto *UnSignedCastExpression = + Result.Nodes.getNodeAs("uIntCastExpression"); + assert(SignedCastExpression); + assert(UnSignedCastExpression); + + // Ignore the match if we know that the signed int value is not negative. + Expr::EvalResult EVResult; + if (!SignedCastExpression->isValueDependent() && + SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, +*Result.Context)) { +const llvm::APSInt SValue = EVResult.Val.getInt(); +if (SValue.isNonNegative()) + return; + } + + const auto *BinaryOp = + Result.Nodes.getNodeAs("intComparison"); + if (BinaryOp == nullptr) +return; + + const BinaryOperator::Opcode OpCode = BinaryOp->getOpcode(); + const Expr *LHS = BinaryOp->getLHS()->IgnoreParenImpCasts(); + const Expr *RHS = BinaryOp->getRHS()->IgnoreParenImpCasts(); qt-tatiana wrote: Not sure If I did everything 100% according the comment, but please see the change :) https://github.com/llvm/llvm-project/pull/113144 ___
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
llvmbot wrote: /pull-request llvm/llvm-project#114197 https://github.com/llvm/llvm-project/pull/114193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Initialize DeclaratorDecl.ExtInfo.TInfo to null (PR #114198)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Boaz Brickner (bricknerb) Changes I believe this has no effect current behavior but would make code safer in case we forget to initialize this. --- Full diff: https://github.com/llvm/llvm-project/pull/114198.diff 1 Files Affected: - (modified) clang/include/clang/AST/Decl.h (+1-1) ``diff diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index 7ff35d73df5997..8c39ef3d5a9fa6 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -737,7 +737,7 @@ class DeclaratorDecl : public ValueDecl { // qualifier, to be used for the (uncommon) case of out-of-line declarations // and constrained function decls. struct ExtInfo : public QualifierInfo { -TypeSourceInfo *TInfo; +TypeSourceInfo *TInfo = nullptr; Expr *TrailingRequiresClause = nullptr; }; `` https://github.com/llvm/llvm-project/pull/114198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Correctly initialize placeholder fields from their initializers (PR #114196)
llvmbot wrote: @llvm/pr-subscribers-clang Author: cor3ntin (cor3ntin) Changes We made the incorrect assumption that names of fields are unique when creating their default initializers. We fix that by keeping track of the instantiaation pattern for field decls that are placeholder vars, like we already do for unamed fields. Fixes #114069 --- Full diff: https://github.com/llvm/llvm-project/pull/114196.diff 8 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+1) - (modified) clang/include/clang/AST/ASTContext.h (+1-1) - (modified) clang/lib/AST/ASTContext.cpp (+6-3) - (modified) clang/lib/Sema/SemaExpr.cpp (+23-9) - (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+1-1) - (modified) clang/lib/Serialization/ASTReaderDecl.cpp (+2-1) - (modified) clang/lib/Serialization/ASTWriterDecl.cpp (+1-1) - (modified) clang/test/SemaCXX/cxx2c-placeholder-vars.cpp (+35-1) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 6085352dfafe6b..eea757b8334150 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -574,6 +574,7 @@ Bug Fixes to C++ Support (#GH95854). - Fixed an assertion failure when evaluating an invalid expression in an array initializer. (#GH112140) - Fixed an assertion failure in range calculations for conditional throw expressions. (#GH111854) +- Name independent data members were not correctly initialized from default member initializers. (#GH114069) Bug Fixes to AST Handling ^ diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index 07b4e36f3ef05e..aa3c3734cef166 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -1037,7 +1037,7 @@ class ASTContext : public RefCountedBase { void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern); - FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); + FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const; void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index 1c3f771f417ccf..7dd646c3a50b34 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -1583,14 +1583,17 @@ ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, InstantiatedFromUsingShadowDecl[Inst] = Pattern; } -FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { +FieldDecl * +ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const { return InstantiatedFromUnnamedFieldDecl.lookup(Field); } void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl) { - assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); - assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); + assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && + "Instantiated field decl is not unnamed"); + assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && + "Template field decl is not unnamed"); assert(!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"); diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index ff6616901016ab..a54100741ccdc9 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -5560,6 +5560,27 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, Init, InitializationContext->Context); } +static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx, +FieldDecl *Field) { + if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field)) +return Pattern; + auto *ParentRD = cast(Field->getParent()); + CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); + DeclContext::lookup_result Lookup = + ClassPattern->lookup(Field->getDeclName()); + FieldDecl *Found = nullptr; + for (auto *L : Lookup) { +if (FieldDecl *Pattern = dyn_cast(L)) { + assert(!Found && "Duplicated instantiation pattern for field decl"); + Found = Pattern; +#ifdef NDEBUG + break; +#endif +} + } + return Found; +} + ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { assert(Field->hasInClassInitializer()); @@ -5588,15 +5609,8 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { // Maybe we haven't instantiated the in-class initializer. Go check the // pattern FieldDecl to see if it has one. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { - CXXRecordDecl *ClassPattern = P
[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)
@@ -0,0 +1,165 @@ +//===--- UseIntegerSignComparisonCheck.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 "UseIntegerSignComparisonCheck.h" +#include "clang/AST/Expr.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; +using namespace clang::ast_matchers::internal; + +namespace clang::tidy::modernize { +UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), + IsQtApplication(Options.get("IsQtApplication", false)), + StringsMatchHeader(Options.get("StringsMatchHeader", "")) {} + +void UseIntegerSignComparisonCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IsQtApplication", IsQtApplication); + Options.store(Opts, "StringsMatchHeader", StringsMatchHeader); +} + +void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) { + const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression"); + const auto UnSignedIntCastExpr = + intCastExpression(false, "uIntCastExpression"); + + // Flag all operators "==", "<=", ">=", "<", ">", "!=" + // that are used between signed/unsigned + const auto CompareOperator = + expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="), qt-tatiana wrote: Again I am not sure if I did correctly, but I use: isInTemplateInstantiation(). Is it enough? Or is it still better to add isInstantiationDependent()? https://github.com/llvm/llvm-project/pull/113144 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)
momo5502 wrote: seems like nobody can review this. maybe you, @efriedma-quic, have time 😊 https://github.com/llvm/llvm-project/pull/113830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
ChuanqiXu9 wrote: /cherry-pick 259eaa6878ead1e2e7ef572a874dc3d885c1899b https://github.com/llvm/llvm-project/pull/114193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 259eaa6 - [C++20] [Modules] Fix the duplicated static initializer problem (#114193)
Author: Chuanqi Xu Date: 2024-10-30T17:27:04+08:00 New Revision: 259eaa6878ead1e2e7ef572a874dc3d885c1899b URL: https://github.com/llvm/llvm-project/commit/259eaa6878ead1e2e7ef572a874dc3d885c1899b DIFF: https://github.com/llvm/llvm-project/commit/259eaa6878ead1e2e7ef572a874dc3d885c1899b.diff LOG: [C++20] [Modules] Fix the duplicated static initializer problem (#114193) Reproducer: ``` //--- a.cppm export module a; int func(); static int a = func(); //--- a.cpp import a; ``` The `func()` should only execute once. However, before this patch we will somehow import `static int a` from a.cppm incorrectly and initialize that again. This is super bad and can introduce serious runtime behaviors. And also surprisingly, it looks like the root cause of the problem is simply some oversight choosing APIs. Added: clang/test/Modules/static-initializer.cppm Modified: clang/lib/CodeGen/CodeGenModule.cpp Removed: diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 2bcca5e85bdfeb..ba376f9ecfacde 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -7146,8 +7146,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { // For C++ standard modules we are done - we will call the module // initializer for imported modules, and that will likewise call those for // any imports it has. -if (CXX20ModuleInits && Import->getImportedOwningModule() && -!Import->getImportedOwningModule()->isModuleMapModule()) +if (CXX20ModuleInits && Import->getImportedModule() && +Import->getImportedModule()->isNamedModule()) break; // For clang C++ module map modules the initializers for sub-modules are diff --git a/clang/test/Modules/static-initializer.cppm b/clang/test/Modules/static-initializer.cppm new file mode 100644 index 00..10d4854ee67fa6 --- /dev/null +++ b/clang/test/Modules/static-initializer.cppm @@ -0,0 +1,18 @@ +// RUN: rm -rf %t +// RUN: mkdir -p %t +// RUN: split-file %s %t +// +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cpp -fmodule-file=a=%t/a.pcm -emit-llvm -o - | FileCheck %t/a.cpp + +//--- a.cppm +export module a; +int func(); +static int a = func(); + +//--- a.cpp +import a; + +// CHECK-NOT: internal global +// CHECK-NOT: __cxx_global_var_init + ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
https://github.com/ChuanqiXu9 closed https://github.com/llvm/llvm-project/pull/114193 ___ 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 a check for signed and unsigned integers comparison (PR #113144)
qt-tatiana wrote: Do you mean more templates and macros? There already were: // The code that triggers the check #define MAX_MACRO(a, b) (a < b) ? b : a template void TemplateFuncParameter(T val) { unsigned long uL = 0; if (val >= uL) return; } But anyway I updated existing ones (and also now templates are skipped by check) https://github.com/llvm/llvm-project/pull/113144 ___ 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 a check for signed and unsigned integers comparison (PR #113144)
https://github.com/qt-tatiana updated https://github.com/llvm/llvm-project/pull/113144 >From 34ee6f5836efe3acddbdd1c9810af358b8c4f981 Mon Sep 17 00:00:00 2001 From: Tatiana Borisova Date: Thu, 17 Oct 2024 18:00:08 +0200 Subject: [PATCH 1/5] [clang-tidy] Create a check for signed and unsigned integers comparison - modernize-use-integer-sign-comparison check performs comparisons between signed and unsigned integer types mathematically correct. If C++20 is supported the check replaces integers comparisons to std::cmp_{} functions and add include. - qt-integer-sign-comparison check works like an alias of modernize-use-integer-sign-comparison for C++20. If only C++17 is supported the check replaces integers comparisons to q20::cmp_{} functions and add include. The check assumes the analysed code is Qt-based code. - add qt module for qt-related checks. --- clang-tools-extra/clang-tidy/CMakeLists.txt | 2 + .../clang-tidy/ClangTidyForceLinker.h | 5 + .../clang-tidy/modernize/CMakeLists.txt | 1 + .../UseIntegerSignComparisonCheck.cpp | 169 ++ .../modernize/UseIntegerSignComparisonCheck.h | 46 + .../clang-tidy/qt/CMakeLists.txt | 26 +++ .../clang-tidy/qt/QtTidyModule.cpp| 46 + clang-tools-extra/docs/ReleaseNotes.rst | 17 ++ .../docs/clang-tidy/checks/list.rst | 3 + .../modernize/use-integer-sign-comparison.rst | 43 + .../checks/qt/IntegerCrossSignComparison.rst | 64 +++ clang-tools-extra/docs/clang-tidy/index.rst | 1 + .../modernize/use-integer-sign-comparison.cpp | 61 +++ .../qt/qt-integer-sign-comparison.cpp | 61 +++ 14 files changed, 545 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h create mode 100644 clang-tools-extra/clang-tidy/qt/CMakeLists.txt create mode 100644 clang-tools-extra/clang-tidy/qt/QtTidyModule.cpp create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst create mode 100644 clang-tools-extra/docs/clang-tidy/checks/qt/IntegerCrossSignComparison.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-integer-sign-comparison.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/qt/qt-integer-sign-comparison.cpp diff --git a/clang-tools-extra/clang-tidy/CMakeLists.txt b/clang-tools-extra/clang-tidy/CMakeLists.txt index 83a3236131dc93..56ef16a8fb37d6 100644 --- a/clang-tools-extra/clang-tidy/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/CMakeLists.txt @@ -75,6 +75,7 @@ add_subdirectory(objc) add_subdirectory(openmp) add_subdirectory(performance) add_subdirectory(portability) +add_subdirectory(qt) add_subdirectory(readability) add_subdirectory(zircon) set(ALL_CLANG_TIDY_CHECKS @@ -99,6 +100,7 @@ set(ALL_CLANG_TIDY_CHECKS clangTidyOpenMPModule clangTidyPerformanceModule clangTidyPortabilityModule + clangTidyQtModule clangTidyReadabilityModule clangTidyZirconModule ) diff --git a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h index adde9136ff1dd5..3c777f42520223 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h +++ b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h @@ -127,6 +127,11 @@ extern volatile int PortabilityModuleAnchorSource; static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination = PortabilityModuleAnchorSource; +// This anchor is used to force the linker to link the QtClangTidyModule. +extern volatile int QtClangTidyModuleAnchorSource; +static int LLVM_ATTRIBUTE_UNUSED QtClangTidyModuleAnchorDestination = +QtClangTidyModuleAnchorSource; + // This anchor is used to force the linker to link the ReadabilityModule. extern volatile int ReadabilityModuleAnchorSource; static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index c919d49b42873a..bab1167fb15ff2 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -36,6 +36,7 @@ add_clang_library(clangTidyModernizeModule STATIC UseEmplaceCheck.cpp UseEqualsDefaultCheck.cpp UseEqualsDeleteCheck.cpp + UseIntegerSignComparisonCheck.cpp UseNodiscardCheck.cpp UseNoexceptCheck.cpp UseNullptrCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp new file mode 100644 index 00..8f394a14a9b0c4 --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp @@ -0,0 +1,169 @@ +//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy --
[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)
@@ -0,0 +1,165 @@ +//===--- UseIntegerSignComparisonCheck.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 "UseIntegerSignComparisonCheck.h" +#include "clang/AST/Expr.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; +using namespace clang::ast_matchers::internal; + +namespace clang::tidy::modernize { +UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), + IsQtApplication(Options.get("IsQtApplication", false)), + StringsMatchHeader(Options.get("StringsMatchHeader", "")) {} + +void UseIntegerSignComparisonCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IsQtApplication", IsQtApplication); + Options.store(Opts, "StringsMatchHeader", StringsMatchHeader); +} + +void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) { + const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression"); + const auto UnSignedIntCastExpr = + intCastExpression(false, "uIntCastExpression"); + + // Flag all operators "==", "<=", ">=", "<", ">", "!=" + // that are used between signed/unsigned + const auto CompareOperator = + expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="), + anyOf(allOf(hasLHS(SignedIntCastExpr), + hasRHS(UnSignedIntCastExpr)), +allOf(hasLHS(UnSignedIntCastExpr), + hasRHS(SignedIntCastExpr) + .bind("intComparison"); + + Finder->addMatcher(CompareOperator, this); +} + +BindableMatcher UseIntegerSignComparisonCheck::intCastExpression( +bool IsSigned, const std::string &CastBindName) const { + auto IntTypeExpr = expr(); + if (IsSigned) { +IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(; + } else { +IntTypeExpr = +expr(hasType(qualType(isInteger(), unless(isSignedInteger(); + } + + const auto ImplicitCastExpr = + implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName); + + const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr)); + const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr)); + const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr)); + + return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr, + StaticCastExpr, FunctionalCastExpr))); +} + +std::string +UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const { + switch (code) { + case BO_LT: +return std::string("cmp_less"); + case BO_GT: +return std::string("cmp_greater"); + case BO_LE: +return std::string("cmp_less_equal"); + case BO_GE: +return std::string("cmp_greater_equal"); + case BO_EQ: +return std::string("cmp_equal"); + case BO_NE: +return std::string("cmp_not_equal"); + default: +return {}; + } +} + +void UseIntegerSignComparisonCheck::registerPPCallbacks( +const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + IncludeInserter.registerPreprocessor(PP); +} + +void UseIntegerSignComparisonCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *SignedCastExpression = + Result.Nodes.getNodeAs("sIntCastExpression"); + const auto *UnSignedCastExpression = + Result.Nodes.getNodeAs("uIntCastExpression"); + assert(SignedCastExpression); + assert(UnSignedCastExpression); + + // Ignore the match if we know that the signed int value is not negative. + Expr::EvalResult EVResult; + if (!SignedCastExpression->isValueDependent() && + SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, +*Result.Context)) { +const llvm::APSInt SValue = EVResult.Val.getInt(); +if (SValue.isNonNegative()) + return; + } + + const auto *BinaryOp = + Result.Nodes.getNodeAs("intComparison"); + if (BinaryOp == nullptr) +return; + + const BinaryOperator::Opcode OpCode = BinaryOp->getOpcode(); + const Expr *LHS = BinaryOp->getLHS()->IgnoreParenImpCasts(); + const Expr *RHS = BinaryOp->getRHS()->IgnoreParenImpCasts(); + if (LHS == nullptr || RHS == nullptr) +return; + + const StringRef LhsString(Lexer::getSourceText( + CharSourceRange::getTokenRange(LHS->getSourceRange()), +
[clang] [llvm] Fix KCFI types for generated functions with integer normalization (PR #104826)
Darksonn wrote: This [has landed in 19.1.3](https://discourse.llvm.org/t/llvm-19-1-3-relased/82829). Thanks! https://github.com/llvm/llvm-project/pull/104826 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Output an error when [[lifetimebound]] attribute is applied on a function implicit object parameter while the function returns void (PR #114203)
https://github.com/bricknerb created https://github.com/llvm/llvm-project/pull/114203 Fixes: https://github.com/llvm/llvm-project/issues/107556 >From 82d89b8b5d1e5faebefed57f3289eb43ad9f8d65 Mon Sep 17 00:00:00 2001 From: Boaz Brickner Date: Wed, 30 Oct 2024 11:24:07 +0100 Subject: [PATCH 1/2] [clang] Output an error when [[lifetimebound]] attribute is applied on a function implicit object parameter while the function returns void Fixes: #107556 --- clang/docs/ReleaseNotes.rst | 4 ++-- clang/include/clang/Basic/DiagnosticSemaKinds.td | 5 - clang/lib/Sema/SemaDecl.cpp | 8 +++- clang/test/SemaCXX/attr-lifetimebound.cpp| 3 +-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 920a2369f96435..5559875c0ebb7c 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -134,8 +134,8 @@ C++ Specific Potentially Breaking Changes unsigned operator""_udl_name(unsigned long long); - Clang will now produce an error diagnostic when [[clang::lifetimebound]] is - applied on a parameter of a function that returns void. This was previously - ignored and had no effect. (#GH107556) + applied on a parameter or an implicit object parameter of a function that + returns void. This was previously ignored and had no effect. (#GH107556) .. code-block:: c++ diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 9b9bdd7c800e37..681c2757b7c76d 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -10097,9 +10097,12 @@ def err_lifetimebound_no_object_param : Error< def err_lifetimebound_ctor_dtor : Error< "'lifetimebound' attribute cannot be applied to a " "%select{constructor|destructor}0">; -def err_lifetimebound_void_return_type : Error< +def err_lifetimebound_parameter_void_return_type : Error< "'lifetimebound' attribute cannot be applied to a parameter of a function " "that returns void">; +def err_lifetimebound_implicit_object_parameter_void_return_type : Error< + "'lifetimebound' attribute cannot be applied to an implicit object " + "parameter of a function that returns void">; // CHECK: returning address/reference of stack memory def warn_ret_stack_addr_ref : Warning< diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index f8e5f3c6d309d6..c09ff4d1975e24 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -6967,6 +6967,11 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { } else if (isa(MD) || isa(MD)) { S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) << isa(MD) << A->getRange(); +} else if (FD->getReturnType()->isVoidType()) { + S.Diag( + FD->getLocation(), + diag:: + err_lifetimebound_implicit_object_parameter_void_return_type); } } } @@ -6978,7 +6983,8 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { // only if the function returns a value. if (auto *A = P->getAttr()) { if (!isa(FD) && FD->getReturnType()->isVoidType()) { - S.Diag(A->getLocation(), diag::err_lifetimebound_void_return_type); + S.Diag(A->getLocation(), + diag::err_lifetimebound_parameter_void_return_type); } } } diff --git a/clang/test/SemaCXX/attr-lifetimebound.cpp b/clang/test/SemaCXX/attr-lifetimebound.cpp index 804d61fb62ca40..81e9193cf76a04 100644 --- a/clang/test/SemaCXX/attr-lifetimebound.cpp +++ b/clang/test/SemaCXX/attr-lifetimebound.cpp @@ -11,8 +11,7 @@ namespace usage_invalid { int *explicit_object(this A&) [[clang::lifetimebound]]; // expected-error {{explicit object member function has no implicit object parameter}} int not_function [[clang::lifetimebound]]; // expected-error {{only applies to parameters and implicit object parameters}} int [[clang::lifetimebound]] also_not_function; // expected-error {{cannot be applied to types}} -// FIXME: Should diagnose a void return type. -void void_return_member() [[clang::lifetimebound]]; +void void_return_member() [[clang::lifetimebound]]; // expected-error {{'lifetimebound' attribute cannot be applied to an implicit object parameter of a function that returns void}} }; int *attr_with_param(int ¶m [[clang::lifetimebound(42)]]); // expected-error {{takes no arguments}} } >From ae34279079f482c22eaa6c128c7e4df96ae11f5d Mon Sep 17 00:00:00 2001 From: Boaz Brickner Date: Wed, 30 Oct 2024 11:24:07 +0100 Subject: [PATCH 2/2] [clang] Output an error when [[lifetimebound]] attribute is applied on a function implicit object parameter while the function returns void Fixes: #107556 --- clang/docs/ReleaseNotes.rst | 4 ++-- clang/in
[clang] [clang] Output an error when [[lifetimebound]] attribute is applied on a function implicit object parameter while the function returns void (PR #114203)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Boaz Brickner (bricknerb) Changes Fixes: https://github.com/llvm/llvm-project/issues/107556 --- Full diff: https://github.com/llvm/llvm-project/pull/114203.diff 4 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+2-2) - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4-1) - (modified) clang/lib/Sema/SemaDecl.cpp (+7-1) - (modified) clang/test/SemaCXX/attr-lifetimebound.cpp (+1-2) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 6085352dfafe6b..61fc2ff5a9aeed 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -140,8 +140,8 @@ C++ Specific Potentially Breaking Changes unsigned operator""_udl_name(unsigned long long); - Clang will now produce an error diagnostic when [[clang::lifetimebound]] is - applied on a parameter of a function that returns void. This was previously - ignored and had no effect. (#GH107556) + applied on a parameter or an implicit object parameter of a function that + returns void. This was previously ignored and had no effect. (#GH107556) .. code-block:: c++ diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 34ff49d7238a7f..3168337acb621f 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -10101,9 +10101,12 @@ def err_lifetimebound_no_object_param : Error< def err_lifetimebound_ctor_dtor : Error< "'lifetimebound' attribute cannot be applied to a " "%select{constructor|destructor}0">; -def err_lifetimebound_void_return_type : Error< +def err_lifetimebound_parameter_void_return_type : Error< "'lifetimebound' attribute cannot be applied to a parameter of a function " "that returns void">; +def err_lifetimebound_implicit_object_parameter_void_return_type : Error< + "'lifetimebound' attribute cannot be applied to an implicit object " + "parameter of a function that returns void">; // CHECK: returning address/reference of stack memory def warn_ret_stack_addr_ref : Warning< diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index f8e5f3c6d309d6..c09ff4d1975e24 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -6967,6 +6967,11 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { } else if (isa(MD) || isa(MD)) { S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) << isa(MD) << A->getRange(); +} else if (FD->getReturnType()->isVoidType()) { + S.Diag( + FD->getLocation(), + diag:: + err_lifetimebound_implicit_object_parameter_void_return_type); } } } @@ -6978,7 +6983,8 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { // only if the function returns a value. if (auto *A = P->getAttr()) { if (!isa(FD) && FD->getReturnType()->isVoidType()) { - S.Diag(A->getLocation(), diag::err_lifetimebound_void_return_type); + S.Diag(A->getLocation(), + diag::err_lifetimebound_parameter_void_return_type); } } } diff --git a/clang/test/SemaCXX/attr-lifetimebound.cpp b/clang/test/SemaCXX/attr-lifetimebound.cpp index 804d61fb62ca40..81e9193cf76a04 100644 --- a/clang/test/SemaCXX/attr-lifetimebound.cpp +++ b/clang/test/SemaCXX/attr-lifetimebound.cpp @@ -11,8 +11,7 @@ namespace usage_invalid { int *explicit_object(this A&) [[clang::lifetimebound]]; // expected-error {{explicit object member function has no implicit object parameter}} int not_function [[clang::lifetimebound]]; // expected-error {{only applies to parameters and implicit object parameters}} int [[clang::lifetimebound]] also_not_function; // expected-error {{cannot be applied to types}} -// FIXME: Should diagnose a void return type. -void void_return_member() [[clang::lifetimebound]]; +void void_return_member() [[clang::lifetimebound]]; // expected-error {{'lifetimebound' attribute cannot be applied to an implicit object parameter of a function that returns void}} }; int *attr_with_param(int ¶m [[clang::lifetimebound(42)]]); // expected-error {{takes no arguments}} } `` https://github.com/llvm/llvm-project/pull/114203 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)
philnik777 wrote: > > The MSVC FE team hasn't expressed enthusiasm for adding ugly spellings. If > > I learn more I'll relay that info. > > Thank you for checking! Unfortunately, I think that's a reason for Clang to > not support it for the `msvc` vendor prefix either. What is the alternative? https://github.com/llvm/llvm-project/pull/113765 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Start moving X86Builtins.def to X86Builtins.td (PR #106005)
philnik777 wrote: @AaronBallman @RKSimon does this look good to you? https://github.com/llvm/llvm-project/pull/106005 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [LoongArch] Support amcas[_db].{b/h/w/d} instructions. (PR #114189)
llvmbot wrote: @llvm/pr-subscribers-clang-driver Author: None (tangaac) Changes Two options for clang: -mlamcas & -mno-lamcas. Enable or disable amcas[_db].{b/h} instructions. The default is -mno-lamcas. Only works on LoongArch64. --- Patch is 218.99 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/114189.diff 16 Files Affected: - (modified) clang/include/clang/Driver/Options.td (+4) - (modified) clang/lib/Basic/Targets/LoongArch.cpp (+6-1) - (modified) clang/lib/Basic/Targets/LoongArch.h (+2) - (modified) clang/lib/Driver/ToolChains/Arch/LoongArch.cpp (+9) - (modified) clang/test/Driver/loongarch-march.c (+4-4) - (added) clang/test/Driver/loongarch-mlamcas.c (+30) - (modified) clang/test/Preprocessor/init-loongarch.c (+17-8) - (modified) llvm/include/llvm/TargetParser/LoongArchTargetParser.def (+2-1) - (modified) llvm/include/llvm/TargetParser/LoongArchTargetParser.h (+4) - (modified) llvm/lib/Target/LoongArch/AsmParser/LoongArchAsmParser.cpp (+3-1) - (modified) llvm/lib/Target/LoongArch/LoongArch.td (+8-1) - (modified) llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp (+18-2) - (modified) llvm/lib/Target/LoongArch/LoongArchInstrInfo.td (+35-9) - (modified) llvm/lib/TargetParser/LoongArchTargetParser.cpp (+1) - (modified) llvm/test/CodeGen/LoongArch/ir-instruction/atomic-cmpxchg.ll (+174-1) - (added) llvm/test/CodeGen/LoongArch/ir-instruction/atomicrmw-lamcas.ll (+5025) ``diff diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 9d595984b63c4b..9a69251dbcef42 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -5414,6 +5414,10 @@ def mlam_bh : Flag<["-"], "mlam-bh">, Group, HelpText<"Enable amswap[_db].{b/h} and amadd[_db].{b/h}">; def mno_lam_bh : Flag<["-"], "mno-lam-bh">, Group, HelpText<"Disable amswap[_db].{b/h} and amadd[_db].{b/h}">; +def mlamcas : Flag<["-"], "mlamcas">, Group, + HelpText<"Enable amcas[_db].{b/h/w/d}">; +def mno_lamcas : Flag<["-"], "mno-lamcas">, Group, + HelpText<"Disable amcas[_db].{b/h/w/d}">; def mannotate_tablejump : Flag<["-"], "mannotate-tablejump">, Group, HelpText<"Enable annotate table jump instruction to correlate it with the jump table.">; def mno_annotate_tablejump : Flag<["-"], "mno-annotate-tablejump">, Group, diff --git a/clang/lib/Basic/Targets/LoongArch.cpp b/clang/lib/Basic/Targets/LoongArch.cpp index 07b22b35f603ce..e08b7a3d96f18b 100644 --- a/clang/lib/Basic/Targets/LoongArch.cpp +++ b/clang/lib/Basic/Targets/LoongArch.cpp @@ -205,7 +205,7 @@ void LoongArchTargetInfo::getTargetDefines(const LangOptions &Opts, // TODO: As more features of the V1.1 ISA are supported, a unified "v1.1" // arch feature set will be used to include all sub-features belonging to // the V1.1 ISA version. - if (HasFeatureFrecipe && HasFeatureLAM_BH) + if (HasFeatureFrecipe && HasFeatureLAM_BH && HasFeatureLAMCAS) Builder.defineMacro("__loongarch_arch", Twine('"') + "la64v1.1" + Twine('"')); else @@ -239,6 +239,9 @@ void LoongArchTargetInfo::getTargetDefines(const LangOptions &Opts, if (HasFeatureLAM_BH) Builder.defineMacro("__loongarch_lam_bh", Twine(1)); + if (HasFeatureLAMCAS) +Builder.defineMacro("__loongarch_lamcas", Twine(1)); + StringRef ABI = getABI(); if (ABI == "lp64d" || ABI == "lp64f" || ABI == "lp64s") Builder.defineMacro("__loongarch_lp64"); @@ -317,6 +320,8 @@ bool LoongArchTargetInfo::handleTargetFeatures( HasFeatureFrecipe = true; else if (Feature == "+lam-bh") HasFeatureLAM_BH = true; +else if (Feature == "+lamcas") + HasFeatureLAMCAS = true; } return true; } diff --git a/clang/lib/Basic/Targets/LoongArch.h b/clang/lib/Basic/Targets/LoongArch.h index 3585e9f7968b4b..824234ae858608 100644 --- a/clang/lib/Basic/Targets/LoongArch.h +++ b/clang/lib/Basic/Targets/LoongArch.h @@ -31,6 +31,7 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public TargetInfo { bool HasFeatureLASX; bool HasFeatureFrecipe; bool HasFeatureLAM_BH; + bool HasFeatureLAMCAS; public: LoongArchTargetInfo(const llvm::Triple &Triple, const TargetOptions &) @@ -41,6 +42,7 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public TargetInfo { HasFeatureLASX = false; HasFeatureFrecipe = false; HasFeatureLAM_BH = false; +HasFeatureLAMCAS = false; LongDoubleWidth = 128; LongDoubleAlign = 128; LongDoubleFormat = &llvm::APFloat::IEEEquad(); diff --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp index e69a5562137ccd..86124fa38d9100 100644 --- a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp +++ b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp @@ -269,6 +269,15 @@ void loongarch::getLoongArchTargetFeatures(const Driver &D, else Features.push_back("-lam-bh"
[clang] [clang] Add sincos builtin using `llvm.sincos` intrinsic (PR #114086)
https://github.com/MacDue updated https://github.com/llvm/llvm-project/pull/114086 >From 7fd19eefa1d1f61843fe1844a72e14c7f4bae03b Mon Sep 17 00:00:00 2001 From: Benjamin Maxwell Date: Mon, 9 Sep 2024 10:15:20 + Subject: [PATCH] [clang] Add sincos builtin using `llvm.sincos` intrinsic This registers `sincos[f|l]` as a clang builtin and updates GCBuiltin to emit the `llvm.sincos.*` intrinsic when `-fno-math-errno` is set. --- clang/include/clang/Basic/Builtins.td| 13 +++ clang/lib/CodeGen/CGBuiltin.cpp | 43 clang/test/CodeGen/AArch64/sincos.c | 33 ++ clang/test/CodeGen/X86/math-builtins.c | 35 +++ clang/test/OpenMP/declare_simd_aarch64.c | 4 +-- 5 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/AArch64/sincos.c diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td index 9bd67e0cefebc3..27eadf80d623e6 100644 --- a/clang/include/clang/Basic/Builtins.td +++ b/clang/include/clang/Basic/Builtins.td @@ -3562,6 +3562,19 @@ def Frexp : FPMathTemplate, LibBuiltin<"math.h"> { let AddBuiltinPrefixedAlias = 1; } +def Sincos : FPMathTemplate, GNULibBuiltin<"math.h"> { + let Spellings = ["sincos"]; + let Attributes = [NoThrow]; + let Prototype = "void(T, T*, T*)"; + let AddBuiltinPrefixedAlias = 1; +} + +def SincosF16F128 : F16F128MathTemplate, Builtin { + let Spellings = ["__builtin_sincos"]; + let Attributes = [FunctionWithBuiltinPrefix, NoThrow]; + let Prototype = "void(T, T*, T*)"; +} + def Ldexp : FPMathTemplate, LibBuiltin<"math.h"> { let Spellings = ["ldexp"]; let Attributes = [NoThrow, ConstIgnoringErrnoAndExceptions]; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 65d7f5c54a1913..331b367e63d91b 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -722,6 +722,38 @@ static Value *emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, return CGF.Builder.CreateExtractValue(Call, 0); } +static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, + llvm::Intrinsic::ID IntrinsicID) { + llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0)); + llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1)); + llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2)); + + llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()}); + llvm::Value *Call = CGF.Builder.CreateCall(F, Val); + + llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0); + llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1); + + QualType DestPtrType = E->getArg(1)->getType()->getPointeeType(); + LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType); + LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType); + + llvm::StoreInst *StoreSin = + CGF.Builder.CreateStore(SinResult, SinLV.getAddress()); + llvm::StoreInst *StoreCos = + CGF.Builder.CreateStore(CosResult, CosLV.getAddress()); + + // Mark the two stores as non-aliasing with eachother. The order of stores + // emitted by this builtin is arbitrary, enforcing a particular order will + // prevent optimizations later on. + llvm::MDBuilder MDHelper(CGF.getLLVMContext()); + MDNode *Domain = MDHelper.createAnonymousAliasScopeDomain(); + MDNode *AliasScope = MDHelper.createAnonymousAliasScope(Domain); + MDNode *AliasScopeList = MDNode::get(Call->getContext(), AliasScope); + StoreSin->setMetadata(LLVMContext::MD_alias_scope, AliasScopeList); + StoreCos->setMetadata(LLVMContext::MD_noalias, AliasScopeList); +} + /// EmitFAbs - Emit a call to @llvm.fabs(). static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) { Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType()); @@ -3094,6 +3126,17 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, return RValue::get(emitUnaryMaybeConstrainedFPBuiltin( *this, E, Intrinsic::sinh, Intrinsic::experimental_constrained_sinh)); +case Builtin::BIsincos: +case Builtin::BIsincosf: +case Builtin::BIsincosl: +case Builtin::BI__builtin_sincos: +case Builtin::BI__builtin_sincosf: +case Builtin::BI__builtin_sincosl: +case Builtin::BI__builtin_sincosf128: +case Builtin::BI__builtin_sincosf16: + emitSincosBuiltin(*this, E, Intrinsic::sincos); + return RValue::get(nullptr); + case Builtin::BIsqrt: case Builtin::BIsqrtf: case Builtin::BIsqrtl: diff --git a/clang/test/CodeGen/AArch64/sincos.c b/clang/test/CodeGen/AArch64/sincos.c new file mode 100644 index 00..240d921b2b7034 --- /dev/null +++ b/clang/test/CodeGen/AArch64/sincos.c @@ -0,0 +1,33 @@ +// RUN: %clang_cc1 -triple=aarch64-gnu-linux -emit-llvm %s -o - | FileCheck --check-prefix=NO-MATH-ERRNO %s +// RUN: %clang_cc1 -triple=aarch64-gnu-linux -emit-llvm -fmath-errno %s -o - | FileCheck --check-prefix=MATH-ERRN
[clang] [clang-format] Fix path expansion inside git-clang-format.bat (PR #114078)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `sanitizer-aarch64-linux-bootstrap-hwasan` running on `sanitizer-buildbot11` while building `clang` at step 2 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/55/builds/3186 Here is the relevant piece of the build log for the reference ``` Step 2 (annotate) failure: 'python ../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py' (failure) ... llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/lld-link llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld64.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/wasm-ld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld.lld: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/lld-link llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld64.lld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/wasm-ld llvm-lit: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/main.py:72: note: The test suite configuration requested an individual test timeout of 0 seconds but a timeout of 900 seconds was requested on the command line. Forcing timeout to be 900 seconds. -- Testing: 83258 tests, 48 workers -- Testing: 0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90. FAIL: lld :: ELF/allow-shlib-undefined.s (80935 of 83258) TEST 'lld :: ELF/allow-shlib-undefined.s' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 3: rm -rf /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp && split-file /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/lld/test/ELF/allow-shlib-undefined.s /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp && cd /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp + rm -rf /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp + split-file /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/lld/test/ELF/allow-shlib-undefined.s /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp + cd /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp RUN: at line 4: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 main.s -o main.o + /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 main.s -o main.o RUN: at line 5: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 def.s -o def.o + /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 def.s -o def.o RUN: at line 6: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 def-hidden.s -o def-hidden.o + /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 def-hidden.s -o def-hidden.o RUN: at line 7: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 ref.s -o ref.o + /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86_64 ref.s -o ref.o RUN: at line 8: /home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/llvm-mc -filetype=obj -triple=x86
[clang] [Clang] Correctly initialize placeholder fields from their initializers (PR #114196)
llvmbot wrote: @llvm/pr-subscribers-clang-modules Author: cor3ntin (cor3ntin) Changes We made the incorrect assumption that names of fields are unique when creating their default initializers. We fix that by keeping track of the instantiaation pattern for field decls that are placeholder vars, like we already do for unamed fields. Fixes #114069 --- Full diff: https://github.com/llvm/llvm-project/pull/114196.diff 8 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+1) - (modified) clang/include/clang/AST/ASTContext.h (+1-1) - (modified) clang/lib/AST/ASTContext.cpp (+6-3) - (modified) clang/lib/Sema/SemaExpr.cpp (+23-9) - (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+1-1) - (modified) clang/lib/Serialization/ASTReaderDecl.cpp (+2-1) - (modified) clang/lib/Serialization/ASTWriterDecl.cpp (+1-1) - (modified) clang/test/SemaCXX/cxx2c-placeholder-vars.cpp (+35-1) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 6085352dfafe6b..eea757b8334150 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -574,6 +574,7 @@ Bug Fixes to C++ Support (#GH95854). - Fixed an assertion failure when evaluating an invalid expression in an array initializer. (#GH112140) - Fixed an assertion failure in range calculations for conditional throw expressions. (#GH111854) +- Name independent data members were not correctly initialized from default member initializers. (#GH114069) Bug Fixes to AST Handling ^ diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index 07b4e36f3ef05e..aa3c3734cef166 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -1037,7 +1037,7 @@ class ASTContext : public RefCountedBase { void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern); - FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); + FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const; void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index 1c3f771f417ccf..7dd646c3a50b34 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -1583,14 +1583,17 @@ ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, InstantiatedFromUsingShadowDecl[Inst] = Pattern; } -FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { +FieldDecl * +ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const { return InstantiatedFromUnnamedFieldDecl.lookup(Field); } void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl) { - assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); - assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); + assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && + "Instantiated field decl is not unnamed"); + assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && + "Template field decl is not unnamed"); assert(!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"); diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index ff6616901016ab..a54100741ccdc9 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -5560,6 +5560,27 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, Init, InitializationContext->Context); } +static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx, +FieldDecl *Field) { + if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field)) +return Pattern; + auto *ParentRD = cast(Field->getParent()); + CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); + DeclContext::lookup_result Lookup = + ClassPattern->lookup(Field->getDeclName()); + FieldDecl *Found = nullptr; + for (auto *L : Lookup) { +if (FieldDecl *Pattern = dyn_cast(L)) { + assert(!Found && "Duplicated instantiation pattern for field decl"); + Found = Pattern; +#ifdef NDEBUG + break; +#endif +} + } + return Found; +} + ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { assert(Field->hasInClassInitializer()); @@ -5588,15 +5609,8 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { // Maybe we haven't instantiated the in-class initializer. Go check the // pattern FieldDecl to see if it has one. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { - CXXRecordDecl *ClassPatt
[clang] [Driver] Remove ignored Flag form of -fauto-profile/-fprofile-sample-use (PR #113528)
mikolaj-pirog wrote: > > Regarding the default filename extension, it doesn't have to be `.profdata` > > for `fprofile-sample-use`, it can be the `.afdo`, or any other extension > > deemed proper. `fprofile-sample-use` and `fprofile-use` would behave > > similarly then: they would look for a `default` file with appropriate > > extension, which seems like a reasonable behavior to me > > I respectively disagree. The sample PGO framework is quite different from > instrumentation PGO. There is no `-fprofile-sample-generate`. While the > naming `-fprofile-sample-use=` is similar to `-fprofile-use=`, it's a very > weak argument to have a default filename, when the filename in the wild has > many uses of very different extensions. > > The deployment experience has shown that we don't really need a default > filename. I see your reasoning and overall agree that approach of removing the flag option altogether is sensible https://github.com/llvm/llvm-project/pull/113528 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Provide default value for -fprofile-sample-use, -fprofile-auto (PR #112750)
https://github.com/mikolaj-pirog updated https://github.com/llvm/llvm-project/pull/112750 From 06472c56a4a916dc2fd7b29a0c137597bbda0504 Mon Sep 17 00:00:00 2001 From: "Pirog, Mikolaj Maciej" Date: Thu, 17 Oct 2024 10:17:09 -0700 Subject: [PATCH 1/2] Provide default value for -fprofile-sample-use --- clang/lib/Driver/ToolChains/Clang.cpp | 21 + 1 file changed, 21 insertions(+) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index d032fd7a59f330..61bbc946f80748 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -594,6 +594,8 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling(); auto *ProfileUseArg = getLastProfileUseArg(Args); + auto *ProfileSampleUseArg = Args.getLastArg( + options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ); if (PGOGenerateArg && ProfileUseArg) D.Diag(diag::err_drv_argument_not_allowed_with) @@ -677,6 +679,25 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, } } + if (ProfileSampleUseArg) { +if ((ProfileSampleUseArg->getOption().matches( + options::OPT_fprofile_sample_use) || + ProfileSampleUseArg->getOption().matches( + options::OPT_fprofile_sample_use_EQ))) { + SmallString<128> Path(ProfileSampleUseArg->getNumValues() == 0 +? "" +: ProfileSampleUseArg->getValue()); + if (Path.empty() || llvm::sys::fs::is_directory(Path)) +llvm::sys::path::append(Path, "default.profdata"); + + if (!llvm::sys::fs::exists(Path)) +D.Diag(diag::err_drv_no_such_file) << Path; + + CmdArgs.push_back( + Args.MakeArgString(Twine("-fprofile-sample-use=") + Path)); +} + } + bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage, options::OPT_fno_test_coverage, false) || Args.hasArg(options::OPT_coverage); From 8f0dc8adee1f1273ad1a64b68a8dc23df2a1e5d7 Mon Sep 17 00:00:00 2001 From: "Pirog, Mikolaj Maciej" Date: Fri, 18 Oct 2024 04:51:11 -0700 Subject: [PATCH 2/2] Fix tests and correct behaviour on -fno.. options --- clang/lib/Driver/ToolChains/Clang.cpp | 10 +- clang/test/Driver/clang_f_opts.c | 5 +++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 61bbc946f80748..727715b7d4d5aa 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -595,7 +595,15 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, auto *ProfileUseArg = getLastProfileUseArg(Args); auto *ProfileSampleUseArg = Args.getLastArg( - options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ); + options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, + options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, + options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); + + if (ProfileSampleUseArg && + (ProfileSampleUseArg->getOption().matches( + options::OPT_fno_profile_sample_use) || + ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) +ProfileSampleUseArg = nullptr; if (PGOGenerateArg && ProfileUseArg) D.Diag(diag::err_drv_argument_not_allowed_with) diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c index fd15552715cb35..4d6f13038763ed 100644 --- a/clang/test/Driver/clang_f_opts.c +++ b/clang/test/Driver/clang_f_opts.c @@ -71,8 +71,9 @@ // RUN: %clang -### -S -fauto-profile=%S/Inputs/file.prof -fno-auto-profile %s 2>&1 | FileCheck -check-prefix=CHECK-NO-AUTO-PROFILE %s // CHECK-NO-AUTO-PROFILE-NOT: "-fprofile-sample-use={{.*}}/file.prof" -// RUN: %clang -### -S -fauto-profile=%S/Inputs/file.prof -fno-profile-sample-use -fauto-profile %s 2>&1 | FileCheck -check-prefix=CHECK-AUTO-PROFILE %s -// RUN: %clang -### -S -fauto-profile=%S/Inputs/file.prof -fno-auto-profile -fprofile-sample-use %s 2>&1 | FileCheck -check-prefix=CHECK-AUTO-PROFILE %s +// RUN: not %clang -### -S -fauto-profile=%S/Inputs/file.prof -fno-profile-sample-use -fauto-profile %s 2>&1 | FileCheck -check-prefix=CHECK-AUTO-PROFILE-NO-DEFAULT %s +// RUN: not %clang -### -S -fauto-profile=%S/Inputs/file.prof -fno-auto-profile -fprofile-sample-use %s 2>&1 | FileCheck -check-prefix=CHECK-AUTO-PROFILE-NO-DEFAULT %s +// CHECK-AUTO-PROFILE-NO-DEFAULT: error: no such file or directory: 'default.profdata' // RUN: %clang -### -S -fprofile-generate %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-GENERATE-LLVM %s // RUN: %clang -### -S -fprofile-instr-generate %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-GENERATE %s ___
[clang] [clang] Initialize DeclaratorDecl.ExtInfo.TInfo to null (PR #114198)
https://github.com/bricknerb created https://github.com/llvm/llvm-project/pull/114198 I believe this has no effect current behavior but would make code safer in case we forget to initialize this. >From 647406c00b1b60b23c3fd4314a1e5b4baeb9e574 Mon Sep 17 00:00:00 2001 From: Boaz Brickner Date: Wed, 30 Oct 2024 10:36:57 +0100 Subject: [PATCH] [clang] Initialize DeclaratorDecl.ExtInfo.TInfo to null I believe this has no effect current behavior but would make code safer in case we forget to initialize this. --- clang/include/clang/AST/Decl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index 7ff35d73df5997..8c39ef3d5a9fa6 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -737,7 +737,7 @@ class DeclaratorDecl : public ValueDecl { // qualifier, to be used for the (uncommon) case of out-of-line declarations // and constrained function decls. struct ExtInfo : public QualifierInfo { -TypeSourceInfo *TInfo; +TypeSourceInfo *TInfo = nullptr; Expr *TrailingRequiresClause = nullptr; }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] convert path to Windows path if user is using a MSYS2 shell (PR #111526)
BLumia wrote: > > Isn't this a Python/MSYS2 bug? > > I'm not sure if it should be considered as a MSYS2 bug. I also created a discussion thread, see: https://github.com/msys2/MSYS2-packages/discussions/4982 https://github.com/llvm/llvm-project/pull/111526 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
llvmbot wrote: @llvm/pr-subscribers-clang-modules Author: Chuanqi Xu (ChuanqiXu9) Changes Reproducer: ``` //--- a.cppm export module a; int func(); static int a = func(); //--- a.cpp import a; ``` The `func()` should only execute once. However, before this patch we will somehow import `static int a` from a.cppm incorrectly and initialize that again. This is super bad and can introduce serious runtime behaviors. And also surprisingly, it looks like the root cause of the problem is simply some oversight choosing APIs. --- Full diff: https://github.com/llvm/llvm-project/pull/114193.diff 2 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+2-2) - (added) clang/test/Modules/static-initializer.cppm (+18) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 2bcca5e85bdfeb..ba376f9ecfacde 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -7146,8 +7146,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { // For C++ standard modules we are done - we will call the module // initializer for imported modules, and that will likewise call those for // any imports it has. -if (CXX20ModuleInits && Import->getImportedOwningModule() && -!Import->getImportedOwningModule()->isModuleMapModule()) +if (CXX20ModuleInits && Import->getImportedModule() && +Import->getImportedModule()->isNamedModule()) break; // For clang C++ module map modules the initializers for sub-modules are diff --git a/clang/test/Modules/static-initializer.cppm b/clang/test/Modules/static-initializer.cppm new file mode 100644 index 00..10d4854ee67fa6 --- /dev/null +++ b/clang/test/Modules/static-initializer.cppm @@ -0,0 +1,18 @@ +// RUN: rm -rf %t +// RUN: mkdir -p %t +// RUN: split-file %s %t +// +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cpp -fmodule-file=a=%t/a.pcm -emit-llvm -o - | FileCheck %t/a.cpp + +//--- a.cppm +export module a; +int func(); +static int a = func(); + +//--- a.cpp +import a; + +// CHECK-NOT: internal global +// CHECK-NOT: __cxx_global_var_init + `` https://github.com/llvm/llvm-project/pull/114193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] prevent setting default lexical access specifier for missing primary declarations (PR #112424)
@@ -39,7 +39,8 @@ bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl, AccessSpecifier LexicalAS) { if (!PrevMemberDecl) { // Use the lexical access specifier. -MemberDecl->setAccess(LexicalAS); a-tarasyuk wrote: @shafik thanks for the feedback. I've checked, and it seems safe to omit `Name` here, so I’ve removed it. https://github.com/llvm/llvm-project/pull/112424 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Remove ignored Flag form of -fauto-profile/-fprofile-sample-use (PR #113528)
@@ -1729,8 +1729,6 @@ defm gnu_inline_asm : BoolFOption<"gnu-inline-asm", "Disable GNU style inline asm">, PosFlag>; -def fprofile_sample_use : Flag<["-"], "fprofile-sample-use">, Group, -Visibility<[ClangOption, CLOption]>; def fno_profile_sample_use : Flag<["-"], "fno-profile-sample-use">, Group, HaohaiWen wrote: Why don't also remove -fno-profile-sample-use and just leave -fprofile-sample-use=. Is there any scenario to use -fno-profile-sample-use? https://github.com/llvm/llvm-project/pull/113528 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix path expansion inside git-clang-format.bat (PR #114078)
github-actions[bot] wrote: @MathiasMagnus Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/114078 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Update std symbols mapping (PR #113612)
https://github.com/kadircet approved this pull request. thanks a lot, lgtm! LMK if i should commit this for you https://github.com/llvm/llvm-project/pull/113612 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)
https://github.com/kadircet edited https://github.com/llvm/llvm-project/pull/113796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Update std symbols mapping (PR #113612)
@@ -115,15 +115,17 @@ static int initialize(Lang Language) { NSLen = 0; } -if (SymIndex >= 0 && -Mapping->SymbolNames[SymIndex].qualifiedName() == QName) { - // Not a new symbol, use the same index. +if (SymIndex > 0) { assert(llvm::none_of(llvm::ArrayRef(Mapping->SymbolNames, SymIndex), [&QName](const SymbolHeaderMapping::SymbolName &S) { return S.qualifiedName() == QName; }) && "The symbol has been added before, make sure entries in the .inc " "file are grouped by symbol name!"); +} +if (SymIndex >= 0 && +Mapping->SymbolNames[SymIndex].qualifiedName() == QName) { + // Not a new symbol, use the same index. kadircet wrote: nit: revert the mapping and get rid of the branch: ``` if (SymIndex < 0 || Mapping->SymbolNames[SymIndex].qualifiedName() != QName) { ... ++SymIndex } ``` https://github.com/llvm/llvm-project/pull/113612 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reapply "[Clang][Sema] Refactor collection of multi-level template argument lists (#106585, #111173)" (PR #111852)
sdkrystian wrote: @adam-smnk Should have the fix merged today https://github.com/llvm/llvm-project/pull/111852 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][AArch64] Include SME attributes in the name mangling of function types (PR #114209)
https://github.com/kmclaughlin-arm created https://github.com/llvm/llvm-project/pull/114209 Similar to arm_sve_vector_bits, the mangling of function types is implemented as a pseudo template if there are any SME attributes present, i.e. `__SME_ATTRS` For example, the following function: `void f(svint8_t (*fn)() __arm_streaming) { fn(); }` would be mangled as: `fP9__SME_ATTRSIFu10__SVInt8_tELj1ELj0ELj0EE` See https://github.com/ARM-software/abi-aa/pull/290 >From ff5b6defc0df704f63fffabc731bcd38a1e24d3b Mon Sep 17 00:00:00 2001 From: Kerry McLaughlin Date: Tue, 15 Oct 2024 15:22:56 + Subject: [PATCH] [Clang][AArch64] Include SME attributes in the name mangling of function types. Similar to arm_sve_vector_bits, the mangling of function types is implemented as a pseudo template if there are any SME attributes present, i.e. __SME_ATTRS For example, the following function: void f(svint8_t (*fn)() __arm_streaming) { fn(); } is mangled as: fP9__SME_ATTRSIFu10__SVInt8_tELj1ELj0ELj0EE See https://github.com/ARM-software/abi-aa/pull/290 --- clang/lib/AST/ItaniumMangle.cpp | 41 .../CodeGenCXX/aarch64-mangle-sme-atts.cpp| 65 +++ 2 files changed, 106 insertions(+) create mode 100644 clang/test/CodeGenCXX/aarch64-mangle-sme-atts.cpp diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp index b3e46508cf596d..2a015b4c45297e 100644 --- a/clang/lib/AST/ItaniumMangle.cpp +++ b/clang/lib/AST/ItaniumMangle.cpp @@ -575,6 +575,7 @@ class CXXNameMangler { static StringRef getCallingConvQualifierName(CallingConv CC); void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info); void mangleExtFunctionInfo(const FunctionType *T); + void mangleSMEAttrs(unsigned SMEAttrs); void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType, const FunctionDecl *FD = nullptr); void mangleNeonVectorType(const VectorType *T); @@ -3535,6 +3536,39 @@ void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { // FIXME: noreturn } +bool hasSharedState(unsigned SMEAttrs) { + switch (SMEAttrs) { + case FunctionType::ARM_In: + case FunctionType::ARM_Out: + case FunctionType::ARM_InOut: + case FunctionType::ARM_Preserves: +return true; + default: +return false; + } +} + +void CXXNameMangler::mangleSMEAttrs(unsigned SMEAttrs) { + if (!SMEAttrs) +return; + + // Streaming Mode + if (SMEAttrs & FunctionType::SME_PStateSMEnabledMask) +Out << "Lj1E"; + else if (SMEAttrs & FunctionType::SME_PStateSMCompatibleMask) +Out << "Lj2E"; + else +Out << "Lj0E"; + + // ZA & ZT0 State + Out << (hasSharedState(FunctionType::getArmZAState(SMEAttrs)) ? "Lj1E" +: "Lj0E"); + Out << (hasSharedState(FunctionType::getArmZT0State(SMEAttrs)) ? "Lj1E" + : "Lj0E"); + + return; +} + void CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { // Vendor-specific qualifiers are emitted in reverse alphabetical order. @@ -3572,6 +3606,11 @@ CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { // ::= [] F [Y] // [] E void CXXNameMangler::mangleType(const FunctionProtoType *T) { + unsigned SMEAttrs = T->getAArch64SMEAttributes(); + + if (SMEAttrs) +Out << "11__SME_ATTRSI"; + mangleExtFunctionInfo(T); // Mangle CV-qualifiers, if present. These are 'this' qualifiers, @@ -3605,6 +3644,8 @@ void CXXNameMangler::mangleType(const FunctionProtoType *T) { // Mangle the ref-qualifier, if present. mangleRefQualifier(T->getRefQualifier()); + mangleSMEAttrs(SMEAttrs); + Out << 'E'; } diff --git a/clang/test/CodeGenCXX/aarch64-mangle-sme-atts.cpp b/clang/test/CodeGenCXX/aarch64-mangle-sme-atts.cpp new file mode 100644 index 00..16d4111cdfaaa1 --- /dev/null +++ b/clang/test/CodeGenCXX/aarch64-mangle-sme-atts.cpp @@ -0,0 +1,65 @@ +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +sme -target-feature +sme2 %s -emit-llvm -o - | FileCheck %s + +typedef __attribute__((neon_vector_type(2))) int int32x2_t; + +// +// Streaming-Mode Attributes +// + +// CHECK: define dso_local void @_Z12fn_streamingP11__SME_ATTRSIFvvLj1ELj0ELj0EE( +void fn_streaming(void (*foo)() __arm_streaming) { foo(); } + +// CHECK: define dso_local void @_Z12fn_streamingP11__SME_ATTRSIFivLj2ELj0ELj0EE( +void fn_streaming(int (*foo)() __arm_streaming_compatible) { foo(); } + +// +// ZA Attributes +// + +// CHECK: define dso_local void @_Z15fn_za_preservedP11__SME_ATTRSIF11__Int32x2_tvLj0ELj1ELj0EE( +__arm_new("za") void fn_za_preserved(int32x2_t (*foo)() __arm_preserves("za")) { foo(); } + +// CHECK: define dso_local void @_Z8fn_za_inP11__SME_ATTRSIFvu13__SVFloat64_tLj0ELj1ELj0EES_( +__arm_new("za") void fn
[clang] [Clang] Fix crash with implicit int-to-pointer conversion (PR #114218)
https://github.com/ostannard created https://github.com/llvm/llvm-project/pull/114218 If an integer is passed to the pointer argument of the __atomic_test_and_set or __atomic_clear builtins with the int-conversion error disabled or downgraded, we crashed in codegen due to assuming that the type is always a pointer after skip[ping past implicit casts. Fixes #111293. >From 133a6c9aa6e5d1dab2750fa04299f63e4ec6cdd1 Mon Sep 17 00:00:00 2001 From: Oliver Stannard Date: Wed, 30 Oct 2024 11:00:12 + Subject: [PATCH] [Clang] Fix crash with implicit int-to-pointer conversion If an integer is passed to the pointer argument of the __atomic_test_and_set or __atomic_clear builtins with the int-conversion error disabled or downgraded, we crashed in codegen due to assuming that the type is always a pointer after skip[ping past implicit casts. Fixes #111293. --- clang/lib/CodeGen/CGBuiltin.cpp | 6 -- clang/test/CodeGen/atomic-ops.c | 10 +++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 65d7f5c54a1913..87955a2c158454 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -4928,8 +4928,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, // Look at the argument type to determine whether this is a volatile // operation. The parameter type is always volatile. QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType(); +QualType PointeeTy = PtrTy->getPointeeType(); bool Volatile = -PtrTy->castAs()->getPointeeType().isVolatileQualified(); +PointeeTy.isNull() ? false : PointeeTy.isVolatileQualified(); Address Ptr = EmitPointerWithAlignment(E->getArg(0)).withElementType(Int8Ty); @@ -5011,8 +5012,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, case Builtin::BI__atomic_clear: { QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType(); +QualType PointeeTy = PtrTy->getPointeeType(); bool Volatile = -PtrTy->castAs()->getPointeeType().isVolatileQualified(); +PointeeTy.isNull() ? false : PointeeTy.isVolatileQualified(); Address Ptr = EmitPointerWithAlignment(E->getArg(0)); Ptr = Ptr.withElementType(Int8Ty); diff --git a/clang/test/CodeGen/atomic-ops.c b/clang/test/CodeGen/atomic-ops.c index b6060dcc540f90..4c7d674836cd36 100644 --- a/clang/test/CodeGen/atomic-ops.c +++ b/clang/test/CodeGen/atomic-ops.c @@ -1,10 +1,10 @@ -// RUN: %clang_cc1 %s -emit-llvm -o - -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 | FileCheck %s +// RUN: %clang_cc1 %s -emit-llvm -o - -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion | FileCheck %s // REQUIRES: x86-registered-target // Also test serialization of atomic operations here, to avoid duplicating the // test. -// RUN: %clang_cc1 %s -emit-pch -o %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -// RUN: %clang_cc1 %s -include-pch %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -emit-pch -o %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion +// RUN: %clang_cc1 %s -include-pch %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion -emit-llvm -o - | FileCheck %s #ifndef ALREADY_INCLUDED #define ALREADY_INCLUDED @@ -310,10 +310,14 @@ void test_and_set(void) { __atomic_test_and_set(&flag1, memory_order_seq_cst); // CHECK: atomicrmw volatile xchg ptr @flag2, i8 1 acquire, align 1 __atomic_test_and_set(&flag2, memory_order_acquire); + // CHECK: atomicrmw xchg ptr inttoptr (i32 32768 to ptr), i8 1 acquire, align 1 + __atomic_test_and_set(0x8000, memory_order_acquire); // CHECK: store atomic volatile i8 0, ptr @flag2 release, align 1 __atomic_clear(&flag2, memory_order_release); // CHECK: store atomic i8 0, ptr @flag1 seq_cst, align 1 __atomic_clear(&flag1, memory_order_seq_cst); + // CHECK: store atomic i8 0, ptr inttoptr (i32 32768 to ptr) seq_cst, align 1 + __atomic_clear(0x8000, memory_order_seq_cst); } struct Sixteen { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix crash in __builtin_assume_aligned (PR #114217)
https://github.com/ostannard created https://github.com/llvm/llvm-project/pull/114217 The CodeGen for __builtin_assume_aligned assumes that the first argument is a pointer, so crashes if the int-conversion error is downgraded or disabled. Emit a non-downgradable error if the argument is not a pointer, like we currently do for __builtin_launder. Fixes #110914. >From a657d11051c95473727ca5e9f6a8e8ab195fe590 Mon Sep 17 00:00:00 2001 From: Oliver Stannard Date: Wed, 30 Oct 2024 12:01:56 + Subject: [PATCH] [Clang] Fix crash in __builtin_assume_aligned The CodeGen for __builtin_assume_aligned assumes that the first argument is a pointer, so crashes if the int-conversion error is downgraded or disabled. Emit a non-downgradable error if the argument is not a pointer, like we currently do for __builtin_launder. Fixes #110914. --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++ clang/lib/Sema/SemaChecking.cpp | 5 - clang/test/Sema/builtin-assume-aligned.c | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 34ff49d7238a7f..67ef5fcae142c2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -12271,6 +12271,8 @@ def warn_noderef_to_dereferenceable_pointer : Warning< def err_builtin_launder_invalid_arg : Error< "%select{non-pointer|function pointer|void pointer}0 argument to " "'__builtin_launder' is not allowed">; +def err_builtin_assume_aligned_invalid_arg : Error< + "non-pointer argument to '__builtin_assume_aligned' is not allowed">; def err_builtin_is_within_lifetime_invalid_arg : Error< "%select{non-|function }0pointer argument to '__builtin_is_within_lifetime' " diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3308b898a5b68f..f6f67895973cc7 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -5272,8 +5272,11 @@ bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) { { ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); -if (checkBuiltinArgument(*this, TheCall, 0)) +if (!FirstArgResult.get()->getType()->isPointerType()) { + Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg) + << TheCall->getSourceRange(); return true; +} /// In-place updation of FirstArg by checkBuiltinArgument is ignored. TheCall->setArg(0, FirstArgResult.get()); } diff --git a/clang/test/Sema/builtin-assume-aligned.c b/clang/test/Sema/builtin-assume-aligned.c index 33e85578451529..57378a3426524a 100644 --- a/clang/test/Sema/builtin-assume-aligned.c +++ b/clang/test/Sema/builtin-assume-aligned.c @@ -74,7 +74,7 @@ int test13(int *a) { } int test14(int *a, int b) { - a = (int *)__builtin_assume_aligned(b, 32); // expected-error {{incompatible integer to pointer conversion passing 'int' to parameter of type 'const void *}} + a = (int *)__builtin_assume_aligned(b, 32); // expected-error {{non-pointer argument to '__builtin_assume_aligned' is not allowed}} } int test15(int *b) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)
@@ -411,6 +411,11 @@ SYMBOL(_27, std::placeholders::, ) SYMBOL(_28, std::placeholders::, ) SYMBOL(_29, std::placeholders::, ) +SYMBOL(binary_search, std::ranges::, ) kadircet wrote: can you move this next to https://github.com/llvm/llvm-project/blob/2de1fc82861edbc484b7a1b82a37aa29d4b982de/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc#L363-L369 ? https://github.com/llvm/llvm-project/pull/113796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)
https://github.com/kadircet approved this pull request. thanks, lgtm! let me know if i should land this for you https://github.com/llvm/llvm-project/pull/113796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix crash with implicit int-to-pointer conversion (PR #114218)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Oliver Stannard (ostannard) Changes If an integer is passed to the pointer argument of the __atomic_test_and_set or __atomic_clear builtins with the int-conversion error disabled or downgraded, we crashed in codegen due to assuming that the type is always a pointer after skip[ping past implicit casts. Fixes #111293. --- Full diff: https://github.com/llvm/llvm-project/pull/114218.diff 2 Files Affected: - (modified) clang/lib/CodeGen/CGBuiltin.cpp (+4-2) - (modified) clang/test/CodeGen/atomic-ops.c (+7-3) ``diff diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 65d7f5c54a1913..87955a2c158454 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -4928,8 +4928,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, // Look at the argument type to determine whether this is a volatile // operation. The parameter type is always volatile. QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType(); +QualType PointeeTy = PtrTy->getPointeeType(); bool Volatile = -PtrTy->castAs()->getPointeeType().isVolatileQualified(); +PointeeTy.isNull() ? false : PointeeTy.isVolatileQualified(); Address Ptr = EmitPointerWithAlignment(E->getArg(0)).withElementType(Int8Ty); @@ -5011,8 +5012,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, case Builtin::BI__atomic_clear: { QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType(); +QualType PointeeTy = PtrTy->getPointeeType(); bool Volatile = -PtrTy->castAs()->getPointeeType().isVolatileQualified(); +PointeeTy.isNull() ? false : PointeeTy.isVolatileQualified(); Address Ptr = EmitPointerWithAlignment(E->getArg(0)); Ptr = Ptr.withElementType(Int8Ty); diff --git a/clang/test/CodeGen/atomic-ops.c b/clang/test/CodeGen/atomic-ops.c index b6060dcc540f90..4c7d674836cd36 100644 --- a/clang/test/CodeGen/atomic-ops.c +++ b/clang/test/CodeGen/atomic-ops.c @@ -1,10 +1,10 @@ -// RUN: %clang_cc1 %s -emit-llvm -o - -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 | FileCheck %s +// RUN: %clang_cc1 %s -emit-llvm -o - -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion | FileCheck %s // REQUIRES: x86-registered-target // Also test serialization of atomic operations here, to avoid duplicating the // test. -// RUN: %clang_cc1 %s -emit-pch -o %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -// RUN: %clang_cc1 %s -include-pch %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -emit-pch -o %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion +// RUN: %clang_cc1 %s -include-pch %t -ffreestanding -ffake-address-space-map -triple=i686-apple-darwin9 -Wno-error=int-conversion -emit-llvm -o - | FileCheck %s #ifndef ALREADY_INCLUDED #define ALREADY_INCLUDED @@ -310,10 +310,14 @@ void test_and_set(void) { __atomic_test_and_set(&flag1, memory_order_seq_cst); // CHECK: atomicrmw volatile xchg ptr @flag2, i8 1 acquire, align 1 __atomic_test_and_set(&flag2, memory_order_acquire); + // CHECK: atomicrmw xchg ptr inttoptr (i32 32768 to ptr), i8 1 acquire, align 1 + __atomic_test_and_set(0x8000, memory_order_acquire); // CHECK: store atomic volatile i8 0, ptr @flag2 release, align 1 __atomic_clear(&flag2, memory_order_release); // CHECK: store atomic i8 0, ptr @flag1 seq_cst, align 1 __atomic_clear(&flag1, memory_order_seq_cst); + // CHECK: store atomic i8 0, ptr inttoptr (i32 32768 to ptr) seq_cst, align 1 + __atomic_clear(0x8000, memory_order_seq_cst); } struct Sixteen { `` https://github.com/llvm/llvm-project/pull/114218 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AArch64] Add soft-float ABI (PR #84146)
ostannard wrote: Those two regressions turned out to be an existing bug, which previously only triggered with `-Wno-int-conversion`. They should be fixed by #114217 and #114218. https://github.com/llvm/llvm-project/pull/84146 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix crash in __builtin_assume_aligned (PR #114217)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Oliver Stannard (ostannard) Changes The CodeGen for __builtin_assume_aligned assumes that the first argument is a pointer, so crashes if the int-conversion error is downgraded or disabled. Emit a non-downgradable error if the argument is not a pointer, like we currently do for __builtin_launder. Fixes #110914. --- Full diff: https://github.com/llvm/llvm-project/pull/114217.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) - (modified) clang/lib/Sema/SemaChecking.cpp (+4-1) - (modified) clang/test/Sema/builtin-assume-aligned.c (+1-1) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 34ff49d7238a7f..67ef5fcae142c2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -12271,6 +12271,8 @@ def warn_noderef_to_dereferenceable_pointer : Warning< def err_builtin_launder_invalid_arg : Error< "%select{non-pointer|function pointer|void pointer}0 argument to " "'__builtin_launder' is not allowed">; +def err_builtin_assume_aligned_invalid_arg : Error< + "non-pointer argument to '__builtin_assume_aligned' is not allowed">; def err_builtin_is_within_lifetime_invalid_arg : Error< "%select{non-|function }0pointer argument to '__builtin_is_within_lifetime' " diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3308b898a5b68f..f6f67895973cc7 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -5272,8 +5272,11 @@ bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) { { ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); -if (checkBuiltinArgument(*this, TheCall, 0)) +if (!FirstArgResult.get()->getType()->isPointerType()) { + Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg) + << TheCall->getSourceRange(); return true; +} /// In-place updation of FirstArg by checkBuiltinArgument is ignored. TheCall->setArg(0, FirstArgResult.get()); } diff --git a/clang/test/Sema/builtin-assume-aligned.c b/clang/test/Sema/builtin-assume-aligned.c index 33e85578451529..57378a3426524a 100644 --- a/clang/test/Sema/builtin-assume-aligned.c +++ b/clang/test/Sema/builtin-assume-aligned.c @@ -74,7 +74,7 @@ int test13(int *a) { } int test14(int *a, int b) { - a = (int *)__builtin_assume_aligned(b, 32); // expected-error {{incompatible integer to pointer conversion passing 'int' to parameter of type 'const void *}} + a = (int *)__builtin_assume_aligned(b, 32); // expected-error {{non-pointer argument to '__builtin_assume_aligned' is not allowed}} } int test15(int *b) { `` https://github.com/llvm/llvm-project/pull/114217 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete unused clang-formatted-file.txt/ClangFormattedStatus.rst files (PR #109220)
https://github.com/AaronBallman approved this pull request. LGTM, thank you for the cleanup! https://github.com/llvm/llvm-project/pull/109220 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Index][USR][NFC] Allow customizing langopts for USR generation (PR #109574)
https://github.com/AaronBallman approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/109574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix for codegen Crash in Clang when using locator omp_all_memory with depobj construct (PR #114221)
https://github.com/chandraghale edited https://github.com/llvm/llvm-project/pull/114221 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] constexpr built-in fma function. (PR #113020)
@@ -549,6 +562,22 @@ static bool interp__builtin_fpclassify(InterpState &S, CodePtr OpPC, return true; } +static bool interp__builtin_fma(InterpState &S, CodePtr OpPC, +const InterpFrame *Frame, const Function *Func, +const CallExpr *Call) { + const Floating &X = getParam(Frame, 0); + const Floating &Y = getParam(Frame, 1); + const Floating &Z = getParam(Frame, 2); + Floating Result; + + llvm::RoundingMode RM = getActiveRoundingMode(S, Call); + Floating::mul(X, Y, RM, &Result); + Floating::add(Result, Z, RM, &Result); c8ef wrote: I'm not entirely sure about this either, thanks for pointing it out! Regarding the type, `Floating` is simply a wrapper for `APFloat`. https://github.com/llvm/llvm-project/pull/113020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
https://github.com/Xazax-hun approved this pull request. https://github.com/llvm/llvm-project/pull/114222 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)
philnik777 wrote: > I'm personally sympathetic, and would be ok with something that we know MSVC > won't step on (`__clang_msvc__` would be fine to me). As far as the > `no_unique_address`, I THINK we already get the double-underscore spelling of > that, don't we? I don't think we exclude the MSVC spellings from that. AFAICT you're only allowed to \_\_uglify\_\_ attributes with no namespace, `clang`, or `gnu`. At least clang 18 rejects `msvc::__no_unique_address__` with a warning: https://godbolt.org/z/zq89ssnh1 https://github.com/llvm/llvm-project/pull/113765 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] constexpr built-in fma function. (PR #113020)
@@ -549,6 +562,22 @@ static bool interp__builtin_fpclassify(InterpState &S, CodePtr OpPC, return true; } +static bool interp__builtin_fma(InterpState &S, CodePtr OpPC, +const InterpFrame *Frame, const Function *Func, +const CallExpr *Call) { + const Floating &X = getParam(Frame, 0); + const Floating &Y = getParam(Frame, 1); + const Floating &Z = getParam(Frame, 2); + Floating Result; + + llvm::RoundingMode RM = getActiveRoundingMode(S, Call); c8ef wrote: https://github.com/llvm/llvm-project/blob/61a456bd5ae88eeccc39b28a30be4eb03289446d/clang/lib/AST/ExprConstant.cpp#L2776-L2782 I actually obtained this from the old constant evaluator, but I'm not sure if it has the same rounding issue. https://github.com/llvm/llvm-project/pull/113020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
https://github.com/Xazax-hun commented: Makes sense for me. It would be nice if we had a minimal reproducer for a regression test instead of maintaining a large-ish test. https://github.com/llvm/llvm-project/pull/114222 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)
erichkeane wrote: > > > > > The MSVC FE team hasn't expressed enthusiasm for adding ugly > > > > > spellings. If I learn more I'll relay that info. > > > > > > > > > > > > Thank you for checking! Unfortunately, I think that's a reason for > > > > Clang to not support it for the `msvc` vendor prefix either. > > > > > > > > > What is the alternative? > > > > > > Can you get away with not using `[[msvc::no_unique_address]]`? If so, I'd > > go that route. > > No. We need it to have a reasonable ABI. > > If not, I'd say use the attribute with the non-ugly spelling and woe unto > > anyone defining `msvc` as a macro despite that being a perfectly valid > > thing for them to do. You could be "kind" and do > > ``` > > #ifdef msvc > > #error "Microsoft's vendor specific attribute prefix steals this identifier > > from the user's namespace, please file an issue with Microsoft if you see > > this diagnostic" > > #endif > > ``` > > > > > > > > > > > > > > > > > > > > > > > > or something along those lines. > > This steals both `msvc` and `no_unique_address` and does that on all > platforms, not just MSVC, so that's not exactly a thrilling solution. Would > defining a namespace like `__clang_msvc__` be an option? libc++ only cares > about Clang on MSVC targets, so it's pretty much irrelevant what MSVC does > for us. Adding an alias like `[[_Clang::__no_unique_address__]]` would also > work if that's more palatable. That'd have to be added to any msvc attributes > libc++ cares about of course (though currently that's only > `[[msvc::no_unique_address]]`). I'm personally sympathetic, and would be ok with something that we know MSVC won't step on (`__clang_msvc__` would be fine to me). As far as the `no_unique_address`, I THINK we already get the double-underscore spelling of that, don't we? I don't think we exclude the MSVC spellings from that. https://github.com/llvm/llvm-project/pull/113765 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
Xazax-hun wrote: > To me, simplifying a SymbolRef should never result in Unknown or Undef, > unless it was Unknown or Undef initially or, during simplification we > realized that it's a division by zero once we did the constant folding, etc. I understand that we might not be ready for this, but feels like at some point we should have this as a form of an assertion. I am not sure about the `Undef` part because there are many ways to get to undef during constant folding (signed overflows, division by zero, OOB access of an array, defer of an invalid pointer). Even if some of those cannot happen during the current simplification they might be modeled later. So, I think a simpler "the result can only be Unknown if the input was also Unknown" would make a lot of sense to me. https://github.com/llvm/llvm-project/pull/114222 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Bump Type::NumOfBuiltinTypeBits. NFCI. (PR #113559)
jayfoad wrote: > The community doesn't add new builtin types particularly often, so having > four leftover bits isn't actually that close to the limit for us. I guess "close" is subjective. > Is there a problem with keeping this change downstream until we get to the > limit in community? No, I was just trying to separate out some changes that seemed upstreamable. https://github.com/llvm/llvm-project/pull/113559 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Bump Type::NumOfBuiltinTypeBits. NFCI. (PR #113559)
https://github.com/jayfoad closed https://github.com/llvm/llvm-project/pull/113559 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)
philnik777 wrote: > > > > The MSVC FE team hasn't expressed enthusiasm for adding ugly spellings. > > > > If I learn more I'll relay that info. > > > > > > > > > Thank you for checking! Unfortunately, I think that's a reason for Clang > > > to not support it for the `msvc` vendor prefix either. > > > > > > What is the alternative? > > Can you get away with not using `[[msvc::no_unique_address]]`? If so, I'd go > that route. No. We need it to have a reasonable ABI. > If not, I'd say use the attribute with the non-ugly spelling and woe unto > anyone defining `msvc` as a macro despite that being a perfectly valid thing > for them to do. You could be "kind" and do > > ``` > #ifdef msvc > #error "Microsoft's vendor specific attribute prefix steals this identifier > from the user's namespace, please file an issue with Microsoft if you see > this diagnostic" > #endif > ``` > > or something along those lines. This steals both `msvc` and `no_unique_address` and does that on all platforms, not just MSVC, so that's not exactly a thrilling solution. Would defining a namespace like `__clang_msvc__` be an option? libc++ only cares about Clang on MSVC targets, so it's pretty much irrelevant what MSVC does for us. Adding an alias like `[[_Clang::__no_unique_address__]]` would also work if that's more palatable. That'd have to be added to any msvc attributes libc++ cares about of course (though currently that's only `[[msvc::no_unique_address]]`). https://github.com/llvm/llvm-project/pull/113765 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AST] Bump Type::NumOfBuiltinTypeBits. NFCI. (PR #113559)
https://github.com/AaronBallman commented: The community doesn't add new builtin types particularly often, so having four leftover bits isn't actually that close to the limit for us. Is there a problem with keeping this change downstream until we get to the limit in community? https://github.com/llvm/llvm-project/pull/113559 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [llvm] Reland "[FMV] Remove useless features according the latest ACLE spec." (PR #89232)
https://github.com/labrinea closed https://github.com/llvm/llvm-project/pull/89232 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Fix the duplicated static initializer problem (PR #114193)
https://github.com/ChuanqiXu9 milestoned https://github.com/llvm/llvm-project/pull/114193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: Balazs Benics (steakhal) Changes SValBuilder::getKnownValue, getMinValue, getMaxValue use SValBuilder::simplifySVal. simplifySVal does repeated simplification until a fixed-point is reached. A single step is done by SimpleSValBuilder::simplifySValOnce, using a Simplifier visitor. That will basically decompose SymSymExprs, and apply constant folding using the constraints we have in the State. Once it decomposes a SymSymExpr, it simplifies both sides and then uses the SValBuilder::evalBinOp to reconstruct the same - but now simpler - SymSymExpr, while applying some caching to remain performant. This decomposition, and then the subsequent re-composition poses new challenges to the SValBuilder::evalBinOp, which is built to handle expressions coming from real C/C++ code, thus applying some implicit assumptions. One previous assumption was that nobody would form an expression like "((int*)0) - q" (where q is an int pointer), because it doesn't really makes sense to write code like that. However, during simplification, we may end up with a call to evalBinOp similar to this. To me, simplifying a SymbolRef should never result in Unknown or Undef, unless it was Unknown or Undef initially or, during simplification we realized that it's a division by zero once we did the constant folding, etc. In the following case the simplified SVal should not become UnknownVal: ```c++ void top(char *p, char *q) { int diff = p - q; // diff: reg- reg
if (!p) // p: NULL simplify(diff); // diff after simplification should be: 0(loc) - reg} ``` Returning Unknown from the simplifySVal can weaken analysis precision in other places too, such as in SValBuilder::getKnownValue, getMinValue, or getMaxValue because we call simplifySVal before doing anything else. For nonloc::SymbolVals, this loss of precision is critical, because for those the SymbolRef carries an accurate type of the encoded computation, thus we should at least have a conservative upper or lower bound that we could return from getMinValue or getMaxValue - yet we would just return nullptr. ```c++ const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, SVal V) { return getConstValue(state, simplifySVal(state, V)); } const llvm::APSInt *SimpleSValBuilder::getMinValue(ProgramStateRef state, SVal V) { V = simplifySVal(state, V); if (const llvm::APSInt *Res = getConcreteValue(V)) return Res; if (SymbolRef Sym = V.getAsSymbol()) return state->getConstraintManager().getSymMinVal(state, Sym); return nullptr; } ``` For now, I don't plan to make the simplification bullet-proof, I'm just explaining why I made this change and what you need to look out for in the future if you see a similar issue. CPP-5750 --- Full diff: https://github.com/llvm/llvm-project/pull/114222.diff 3 Files Affected: - (modified) clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (+4-3) - (modified) clang/unittests/StaticAnalyzer/CMakeLists.txt (+1) - (added) clang/unittests/StaticAnalyzer/SValSimplifyerTest.cpp (+103) ``diff diff --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp index 45e48d435aca6a..229169f848e228 100644 --- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp +++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp @@ -860,11 +860,12 @@ SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, // If one of the operands is a symbol and the other is a constant, // build an expression for use by the constraint manager. if (SymbolRef rSym = rhs.getAsLocSymbol()) { - // We can only build expressions with symbols on the left, - // so we need a reversible operator. - if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp) + if (op == BO_Cmp) return UnknownVal(); + if (!BinaryOperator::isComparisonOp(op)) +return makeNonLoc(L.getValue(), op, rSym, resultTy); + op = BinaryOperator::reverseComparisonOp(op); return makeNonLoc(rSym, op, L.getValue(), resultTy); } diff --git a/clang/unittests/StaticAnalyzer/CMakeLists.txt b/clang/unittests/StaticAnalyzer/CMakeLists.txt index 5ef72cfaea4011..f5da86e5456030 100644 --- a/clang/unittests/StaticAnalyzer/CMakeLists.txt +++ b/clang/unittests/StaticAnalyzer/CMakeLists.txt @@ -20,6 +20,7 @@ add_clang_unittest(StaticAnalysisTests RegisterCustomCheckersTest.cpp StoreTest.cpp SymbolReaperTest.cpp + SValSimplifyerTest.cpp SValTest.cpp TestReturnValueUnderConstruction.cpp Z3CrosscheckOracleTest.cpp diff --git a/clang/unittests/StaticAnalyzer/SValSimplifyerTest.cpp b/clang/unittests/StaticAnalyzer/SValSimplifyerTest.cpp new file mode 100644 index 00..b3feb0e4cce231 --- /dev/null +++ b/clang/unittests/StaticA
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
https://github.com/steakhal created https://github.com/llvm/llvm-project/pull/114222 SValBuilder::getKnownValue, getMinValue, getMaxValue use SValBuilder::simplifySVal. simplifySVal does repeated simplification until a fixed-point is reached. A single step is done by SimpleSValBuilder::simplifySValOnce, using a Simplifier visitor. That will basically decompose SymSymExprs, and apply constant folding using the constraints we have in the State. Once it decomposes a SymSymExpr, it simplifies both sides and then uses the SValBuilder::evalBinOp to reconstruct the same - but now simpler - SymSymExpr, while applying some caching to remain performant. This decomposition, and then the subsequent re-composition poses new challenges to the SValBuilder::evalBinOp, which is built to handle expressions coming from real C/C++ code, thus applying some implicit assumptions. One previous assumption was that nobody would form an expression like "((int*)0) - q" (where q is an int pointer), because it doesn't really makes sense to write code like that. However, during simplification, we may end up with a call to evalBinOp similar to this. To me, simplifying a SymbolRef should never result in Unknown or Undef, unless it was Unknown or Undef initially or, during simplification we realized that it's a division by zero once we did the constant folding, etc. In the following case the simplified SVal should not become UnknownVal: ```c++ void top(char *p, char *q) { int diff = p - q; // diff: reg - reg if (!p) // p: NULL simplify(diff); // diff after simplification should be: 0(loc) - reg } ``` Returning Unknown from the simplifySVal can weaken analysis precision in other places too, such as in SValBuilder::getKnownValue, getMinValue, or getMaxValue because we call simplifySVal before doing anything else. For nonloc::SymbolVals, this loss of precision is critical, because for those the SymbolRef carries an accurate type of the encoded computation, thus we should at least have a conservative upper or lower bound that we could return from getMinValue or getMaxValue - yet we would just return nullptr. ```c++ const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, SVal V) { return getConstValue(state, simplifySVal(state, V)); } const llvm::APSInt *SimpleSValBuilder::getMinValue(ProgramStateRef state, SVal V) { V = simplifySVal(state, V); if (const llvm::APSInt *Res = getConcreteValue(V)) return Res; if (SymbolRef Sym = V.getAsSymbol()) return state->getConstraintManager().getSymMinVal(state, Sym); return nullptr; } ``` For now, I don't plan to make the simplification bullet-proof, I'm just explaining why I made this change and what you need to look out for in the future if you see a similar issue. CPP-5750 >From 37ef4f72d42b01e70795bb2fa86138f7fbdd8077 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Wed, 30 Oct 2024 13:56:40 +0100 Subject: [PATCH] [analyzer] EvalBinOpLL should return Unknown less often SValBuilder::getKnownValue, getMinValue, getMaxValue use SValBuilder::simplifySVal. simplifySVal does repeated simplification until a fixed-point is reached. A single step is done by SimpleSValBuilder::simplifySValOnce, using a Simplifier visitor. That will basically decompose SymSymExprs, and apply constant folding using the constraints we have in the State. Once it decomposes a SymSymExpr, it simplifies both sides and then uses the SValBuilder::evalBinOp to reconstruct the same - but now simpler - SymSymExpr, while applying some caching to remain performant. This decomposition, and then the subsequent re-composition poses new challenges to the SValBuilder::evalBinOp, which is built to handle expressions coming from real C/C++ code, thus applying some implicit assumptions. One previous assumption was that nobody would form an expression like "((int*)0) - q" (where q is an int pointer), because it doesn't really makes sense to write code like that. However, during simplification, we may end up with a call to evalBinOp similar to this. To me, simplifying a SymbolRef should never result in Unknown or Undef, unless it was Unknown or Undef initially or, during simplification we realized that it's a division by zero once we did the constant folding, etc. In the following case the simplified SVal should not become UnknownVal: ```c++ void top(char *p, char *q) { int diff = p - q; // diff: reg - reg if (!p) // p: NULL simplify(diff); // diff after simplification should be: 0(loc) - reg } ``` Returning Unknown from the simplifySVal can weaken analysis precision in other places too, such as in SValBuilder::getKnownValue, getMinValue, or getMaxValue because we call simplifySVal before doing anything else. For nonloc::SymbolVals, this loss of precision is critical, because for those the SymbolRef carries an accurate type of the encoded comput
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
steakhal wrote: @necto https://github.com/llvm/llvm-project/pull/114222 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Index][USR][NFC] Allow customizing langopts for USR generation (PR #109574)
Endilll wrote: > @Endilll Could you please help me reaching out to the right set of reviewers? Aaron noticed it faster 😄 https://github.com/llvm/llvm-project/pull/109574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] constexpr built-in fma function. (PR #113020)
AaronBallman wrote: > I suspect fma is not one of the functions we want to try to share, at least > not short-term. It's one of the core IEEE operations, LLVM has > APFloat::fusedMultiplyAdd since forever, and there's probably some weirdness > with dependencies if we try to share it because other operations use it. That's fair, I don't insist on sharing here, but it is something we should be planning for with the wider set of changes IMO. https://github.com/llvm/llvm-project/pull/113020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Start implementing __builtin_bit_cast (PR #112126)
Timm =?utf-8?q?Bäder?= Message-ID: In-Reply-To: AaronBallman wrote: There's a valid precommit CI failure: ``` TEST 'Clang :: AST/ByteCode/builtin-bit-cast.cpp' FAILED Exit Code: 1 Command Output (stdout): -- # RUN: at line 1 c:\ws\src\build\bin\clang.exe -cc1 -internal-isystem C:\ws\src\build\lib\clang\20\include -nostdsysteminc -verify=ref,both -std=c++2a -fsyntax-only C:\ws\src\clang\test\AST\ByteCode\builtin-bit-cast.cpp # executed command: 'c:\ws\src\build\bin\clang.exe' -cc1 -internal-isystem 'C:\ws\src\build\lib\clang\20\include' -nostdsysteminc -verify=ref,both -std=c++2a -fsyntax-only 'C:\ws\src\clang\test\AST\ByteCode\builtin-bit-cast.cpp' # .---command stderr # | error: 'both-error' diagnostics seen but not expected: # | File C:\ws\src\clang\test\AST\ByteCode\builtin-bit-cast.cpp Line 124: __builtin_bit_cast source size does not equal destination size (4 vs 8) # | 1 error generated. # `- # error: command failed with exit status: 1 -- ``` https://github.com/llvm/llvm-project/pull/112126 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Start moving X86Builtins.def to X86Builtins.td (PR #106005)
https://github.com/RKSimon approved this pull request. https://github.com/llvm/llvm-project/pull/106005 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)
AaronBallman wrote: > > > > > The MSVC FE team hasn't expressed enthusiasm for adding ugly > > > > > spellings. If I learn more I'll relay that info. > > > > > > > > > > > > Thank you for checking! Unfortunately, I think that's a reason for > > > > Clang to not support it for the `msvc` vendor prefix either. > > > > > > > > > What is the alternative? > > > > > > Can you get away with not using `[[msvc::no_unique_address]]`? If so, I'd > > go that route. > > No. We need it to have a reasonable ABI. > > If not, I'd say use the attribute with the non-ugly spelling and woe unto > > anyone defining `msvc` as a macro despite that being a perfectly valid > > thing for them to do. You could be "kind" and do > > ``` > > #ifdef msvc > > #error "Microsoft's vendor specific attribute prefix steals this identifier > > from the user's namespace, please file an issue with Microsoft if you see > > this diagnostic" > > #endif > > ``` > > > > > > > > > > > > > > > > > > > > > > > > or something along those lines. > > This steals both `msvc` and `no_unique_address` and does that on all > platforms, not just MSVC, so that's not exactly a thrilling solution. You can put guards in to only steal `msvc` on Microsoft's platform; there's no need to steal it everywhere. And `no_unique_address`... I was thinking that we already supported that with the underscores but it seems we don't: https://godbolt.org/z/fn5v19hx7 so that's unfortunate. > Would defining a namespace like `__clang_msvc__` be an option? It's an option, but not one I'm thrilled with. The point to vendor namespaces is that the vendor picks them and other vendors can be compatible. Do we want EDG to have to support `__clang_msvc__` as a prefix for Clang's compatibility with Microsoft? That seems... a bit silly when Microsoft could elect to provide a spelling that doesn't steal from the user's namespace. > libc++ only cares about Clang on MSVC targets, so it's pretty much irrelevant > what MSVC does for us. Adding an alias like > `[[_Clang::__no_unique_address__]]` would also work if that's more palatable. > That'd have to be added to any msvc attributes libc++ cares about of course > (though currently that's only `[[msvc::no_unique_address]]`). That's somewhat more palatable to me, but I'm still wondering whether we're making a mountain out of a mole hill with the vendor prefix: https://sourcegraph.com/search?q=context:global+%5E%23define%5Cs%2Bmsvc%5Cb&patternType=regexp&case=yes&sm=0 That said, the attribute name itself does seem to be an issue: https://sourcegraph.com/search?q=context:global+%5E%23define%5Cs%2Bno_unique_address%5Cb&patternType=regexp&case=yes&sm=0 So yeah, I think I'd be happier exposing `[[_Clang::__no_unique_address__]]` as an alias to the standard attribute, but I am wondering if @StephanTLavavej can maybe push back on the MSVC team a little bit regarding support for attribute usage in system headers. Both Clang and GCC already provide such a mechanism for exactly that reason, and I have to imagine Microsoft would want something similar so they can protect their own system headers. https://github.com/llvm/llvm-project/pull/113765 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5082638 - [Clang] Start moving X86Builtins.def to X86Builtins.td (#106005)
Author: Nikolas Klauser Date: 2024-10-30T14:23:35+01:00 New Revision: 508263824f4ef0c70f37523810e5f7d56bcfa653 URL: https://github.com/llvm/llvm-project/commit/508263824f4ef0c70f37523810e5f7d56bcfa653 DIFF: https://github.com/llvm/llvm-project/commit/508263824f4ef0c70f37523810e5f7d56bcfa653.diff LOG: [Clang] Start moving X86Builtins.def to X86Builtins.td (#106005) This starts moving `X86Builtins.def` to be a tablegen file. It's quite large, so I think it'd be good to move things in multiple steps to avoid a bunch of merge conflicts due to the amount of time this takes to complete. Added: clang/include/clang/Basic/BuiltinsX86.td Modified: clang/include/clang/Basic/BuiltinsBase.td clang/include/clang/Basic/BuiltinsX86.def clang/include/clang/Basic/CMakeLists.txt clang/include/clang/Basic/TargetBuiltins.h clang/lib/Basic/Targets/X86.cpp clang/utils/TableGen/ClangBuiltinsEmitter.cpp Removed: diff --git a/clang/include/clang/Basic/BuiltinsBase.td b/clang/include/clang/Basic/BuiltinsBase.td index 58dee22fc0a450..cff182f3f282cb 100644 --- a/clang/include/clang/Basic/BuiltinsBase.td +++ b/clang/include/clang/Basic/BuiltinsBase.td @@ -60,6 +60,10 @@ def ConstIgnoringExceptions : Attribute<"g">; // This function requires a specific header or an explicit declaration. def RequireDeclaration : Attribute<"h">; +// FIXME: Why is this not simply the min_vector_width attribute? +// Vector has to be at least N bits wide. +class RequiredVectorWidth : IndexedAttribute<"V", N>; + class PrintfFormat : IndexedAttribute<"p", I>; class VPrintfFormat : IndexedAttribute<"P", I>; class ScanfFormat : IndexedAttribute<"s", I>; diff --git a/clang/include/clang/Basic/BuiltinsX86.def b/clang/include/clang/Basic/BuiltinsX86.def index 4486eb73a11fa6..c93ea27f164e34 100644 --- a/clang/include/clang/Basic/BuiltinsX86.def +++ b/clang/include/clang/Basic/BuiltinsX86.def @@ -26,17 +26,6 @@ # define TARGET_HEADER_BUILTIN(ID, TYPE, ATTRS, HEADER, LANG, FEATURE) BUILTIN(ID, TYPE, ATTRS) #endif -// Undefined Values -// -TARGET_BUILTIN(__builtin_ia32_undef128, "V2d", "ncV:128:", "") -TARGET_BUILTIN(__builtin_ia32_undef256, "V4d", "ncV:256:", "") -TARGET_BUILTIN(__builtin_ia32_undef512, "V8d", "ncV:512:", "") - -// FLAGS -// -TARGET_BUILTIN(__builtin_ia32_readeflags_u32, "Ui", "n", "") -TARGET_BUILTIN(__builtin_ia32_writeeflags_u32, "vUi", "n", "") - // MMX // // All MMX instructions will be generated via builtins. Any MMX vector @@ -46,113 +35,8 @@ TARGET_BUILTIN(__builtin_ia32_writeeflags_u32, "vUi", "n", "") // argument and our prior approach of using a #define to the current built-in // doesn't work in the presence of re-declaration of _mm_prefetch for windows. TARGET_BUILTIN(_mm_prefetch, "vcC*i", "nc", "mmx") -TARGET_BUILTIN(__builtin_ia32_emms, "v", "n", "mmx") -TARGET_BUILTIN(__builtin_ia32_vec_ext_v4hi, "sV4sIi", "ncV:64:", "sse") -TARGET_BUILTIN(__builtin_ia32_vec_set_v4hi, "V4sV4ssIi", "ncV:64:", "sse") // SSE intrinsics. -TARGET_BUILTIN(__builtin_ia32_comieq, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_comilt, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_comile, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_comigt, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_comige, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_comineq, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomieq, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomilt, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomile, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomigt, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomige, "iV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_ucomineq, "iV4fV4f", "ncV:128:", "sse") - -TARGET_BUILTIN(__builtin_ia32_comisdeq, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_comisdlt, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_comisdle, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_comisdgt, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_comisdge, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_comisdneq, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdeq, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdlt, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdle, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdgt, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdge, "iV2dV2d", "ncV:128:", "sse2") -TARGET_BUILTIN(__builtin_ia32_ucomisdneq, "iV2dV2d", "ncV:128:", "sse2") - -TARGET_BUILTIN(__builtin_ia32_cmpeqps, "V4fV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_cmpltps, "V4fV4fV4f", "ncV:128:", "sse") -TARGET_BUILTIN(__builtin_ia32_cmpleps, "V4fV4
[clang] [Clang] Start moving X86Builtins.def to X86Builtins.td (PR #106005)
https://github.com/philnik777 closed https://github.com/llvm/llvm-project/pull/106005 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Start implementing __builtin_bit_cast (PR #112126)
Timm =?utf-8?q?Bäder?= , Timm =?utf-8?q?Bäder?= Message-ID: In-Reply-To: https://github.com/AaronBallman commented: This generally LGTM, but I'd like to see some tests for slightly more complicated situations, such as derived classes, classes with reference members, bitcasting a class with a virtual function, bitcasting a class with a virtual base, etc. https://github.com/llvm/llvm-project/pull/112126 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Start implementing __builtin_bit_cast (PR #112126)
Timm =?utf-8?q?Bäder?= , Timm =?utf-8?q?Bäder?= Message-ID: In-Reply-To: @@ -0,0 +1,399 @@ +// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only %s +// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple aarch64_be-linux-gnu %s +// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple powerpc64le-unknown-unknown -mabi=ieeelongdouble %s +// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple powerpc64-unknown-unknown -mabi=ieeelongdouble %s + +// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -fexperimental-new-constant-interpreter %s +// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple aarch64_be-linux-gnu -fexperimental-new-constant-interpreter %s +// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -fexperimental-new-constant-interpreter -triple powerpc64le-unknown-unknown -mabi=ieeelongdouble %s +// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -fexperimental-new-constant-interpreter -triple powerpc64-unknown-unknown -mabi=ieeelongdouble %s + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define LITTLE_END 1 +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +# define LITTLE_END 0 +#else +# error "huh?" +#endif + +typedef decltype(nullptr) nullptr_t; +typedef __INTPTR_TYPE__ intptr_t; + +static_assert(sizeof(int) == 4); +static_assert(sizeof(long long) == 8); + +template +constexpr To bit_cast(const From &from) { + static_assert(sizeof(To) == sizeof(From)); + return __builtin_bit_cast(To, from); +} + +template +constexpr bool check_round_trip(const Init &init) { + return bit_cast(bit_cast(init)) == init; +} + +template +constexpr Init round_trip(const Init &init) { + return bit_cast(bit_cast(init)); +} + +namespace std { +enum byte : unsigned char {}; +} // namespace std + +using uint8_t = unsigned char; + +template +struct bytes { + using size_t = unsigned int; + unsigned char d[N]; + + constexpr unsigned char &operator[](size_t index) { +if (index < N) + return d[index]; + } +}; + + +template +struct bits { + T : Pad; + T bits : N; + + constexpr bool operator==(const T& rhs) const { +return bits == rhs; + } +}; + +template +constexpr bool operator==(const struct bits& lhs, const struct bits& rhs) { + return lhs.bits == rhs.bits; +} + + +namespace simple { + constexpr int A = __builtin_bit_cast(int, 10); + static_assert(A == 10); + + static_assert(__builtin_bit_cast(unsigned, 1.0F) == 1065353216); + + struct Bytes { +char a, b, c, d; + }; + constexpr unsigned B = __builtin_bit_cast(unsigned, Bytes{10, 12, 13, 14}); + static_assert(B == (LITTLE_END ? 235736074 : 168561934)); + + + constexpr unsigned C = __builtin_bit_cast(unsigned, (_BitInt(32))12); + static_assert(C == 12); + + struct BitInts { +_BitInt(16) a; +_BitInt(16) b; + }; + constexpr unsigned D = __builtin_bit_cast(unsigned, BitInts{12, 13}); + static_assert(D == (LITTLE_END ? 851980 : 786445)); + + + + static_assert(__builtin_bit_cast(char, true) == 1); + + static_assert(check_round_trip((int)-1)); + static_assert(check_round_trip((int)0x12345678)); + static_assert(check_round_trip((int)0x87654321)); + static_assert(check_round_trip((int)0x0C05FEFE)); + // static_assert(round_trip((int)0x0C05FEFE)); + + + /// This works in GCC and in the bytecode interpreter, but the current interpreter + /// diagnoses it. + static_assert(__builtin_bit_cast(intptr_t, nullptr) == 0); // ref-error {{not an integral constant expression}} \ + // ref-note {{indeterminate value can only initialize an object}} +} + +namespace Fail { + constexpr int a = 1/0; // both-error {{must be initialized by a constant expression}} \ + // both-note {{division by zero}} \ + // both-note {{declared here}} + constexpr int b = __builtin_bit_cast(int, a); // both-error {{must be initialized by a constant expression}} \ +// both-note {{initializer of 'a' is not a constant expression}} +} + +namespace NullPtr { + constexpr nullptr_t N = __builtin_bit_cast(nullptr_t, (intptr_t)1u); + static_assert(N == nullptr); + static_assert(__builtin_bit_cast(nullptr_t, (_BitInt(sizeof(void*) * 8))12) == __builtin_bit_cast(nullptr_t, (unsigned _BitInt(sizeof(void*) * 8))0)); + static_assert(__builtin_bit_cast(nullptr_t, nullptr) == nullptr); +} + +namespace bitint { + constexpr _BitInt(sizeof(int) * 8) BI = ~0; + constexpr unsigned int I = __builtin_bit_cast(unsigned int, BI); + static_assert(I == ~0u, ""); + + constexpr _BitInt(sizeof(int) * 8) IB = __builtin_bit_cast(_BitInt(sizeof(int) * 8), I); // ref-error {{must be initialized by a constant expression}} \ + // ref-note {{constexpr bit cast involving type '_BitInt(32)' is
[clang] [analyzer] EvalBinOpLL should return Unknown less often (PR #114222)
steakhal wrote: > Makes sense for me. It would be nice if we had a minimal reproducer for a > regression test instead of maintaining a large-ish test. I wish I could add a LIT test instead. Out of the get min/max val, or getKnownValue APIs, only the latter is used slightly more broadly, where the callsites can't assume it should return a valid result. Still, these APIs are barely used. In my case I have additional context in my downstream checker, where I can make this assumption and I was surprised to see crashes. So I had no other options but to craft a unittest for this. https://github.com/llvm/llvm-project/pull/114222 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Index][USR][NFC] Allow customizing langopts for USR generation (PR #109574)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/109574 >From 643ad2cd6e788b6e62f22c980ed06abd192ded55 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Sun, 22 Sep 2024 12:04:33 +0200 Subject: [PATCH] [clang][Index][USR][NFC] Allow customizing langopts for USR generation This helps to produce USRs for custom LangOpts - that differ from the one associated with the given Decl. This can unlock usecases in tooling opportunities that we have downstream. This is NFC because existing calls will still result in the right overload, thus using the LangOpts associated with the ASTContext of the Decls and Types. --- clang/include/clang/Index/USRGeneration.h | 8 +++- clang/lib/Index/USRGeneration.cpp | 48 ++- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/clang/include/clang/Index/USRGeneration.h b/clang/include/clang/Index/USRGeneration.h index f89fc5cf49302c..61d267f3545a70 100644 --- a/clang/include/clang/Index/USRGeneration.h +++ b/clang/include/clang/Index/USRGeneration.h @@ -15,6 +15,7 @@ namespace clang { class ASTContext; class Decl; +class LangOptions; class MacroDefinitionRecord; class Module; class SourceLocation; @@ -30,6 +31,8 @@ static inline StringRef getUSRSpacePrefix() { /// Generate a USR for a Decl, including the USR prefix. /// \returns true if the results should be ignored, false otherwise. bool generateUSRForDecl(const Decl *D, SmallVectorImpl &Buf); +bool generateUSRForDecl(const Decl *D, SmallVectorImpl &Buf, +const LangOptions &LangOpts); /// Generate a USR fragment for an Objective-C class. void generateUSRForObjCClass(StringRef Cls, raw_ostream &OS, @@ -75,7 +78,10 @@ bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc, /// Generates a USR for a type. /// /// \return true on error, false on success. -bool generateUSRForType(QualType T, ASTContext &Ctx, SmallVectorImpl &Buf); +bool generateUSRForType(QualType T, ASTContext &Ctx, +SmallVectorImpl &Buf); +bool generateUSRForType(QualType T, ASTContext &Ctx, SmallVectorImpl &Buf, +const LangOptions &LangOpts); /// Generate a USR for a module, including the USR prefix. /// \returns true on error, false on success. diff --git a/clang/lib/Index/USRGeneration.cpp b/clang/lib/Index/USRGeneration.cpp index f00bc56429f1a7..1cfca8b6aaa368 100644 --- a/clang/lib/Index/USRGeneration.cpp +++ b/clang/lib/Index/USRGeneration.cpp @@ -62,20 +62,17 @@ namespace { class USRGenerator : public ConstDeclVisitor { SmallVectorImpl &Buf; llvm::raw_svector_ostream Out; - bool IgnoreResults; ASTContext *Context; - bool generatedLoc; + const LangOptions &LangOpts; + bool IgnoreResults = false; + bool generatedLoc = false; llvm::DenseMap TypeSubstitutions; public: - explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl &Buf) - : Buf(Buf), -Out(Buf), -IgnoreResults(false), -Context(Ctx), -generatedLoc(false) - { + USRGenerator(ASTContext *Ctx, SmallVectorImpl &Buf, + const LangOptions &LangOpts) + : Buf(Buf), Out(Buf), Context(Ctx), LangOpts(LangOpts) { // Add the USR space prefix. Out << getUSRSpacePrefix(); } @@ -246,14 +243,13 @@ void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) { } else Out << "@F@"; - PrintingPolicy Policy(Context->getLangOpts()); + PrintingPolicy Policy(LangOpts); // Forward references can have different template argument names. Suppress the // template argument names in constructors to make their USR more stable. Policy.SuppressTemplateArgsInCXXConstructors = true; D->getDeclName().print(Out, Policy); - ASTContext &Ctx = *Context; - if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) && + if ((!LangOpts.CPlusPlus || D->isExternC()) && !D->hasAttr()) return; @@ -657,9 +653,10 @@ bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) { return IgnoreResults; } -static void printQualifier(llvm::raw_ostream &Out, ASTContext &Ctx, NestedNameSpecifier *NNS) { +static void printQualifier(llvm::raw_ostream &Out, const LangOptions &LangOpts, + NestedNameSpecifier *NNS) { // FIXME: Encode the qualifier, don't just print it. - PrintingPolicy PO(Ctx.getLangOpts()); + PrintingPolicy PO(LangOpts); PO.SuppressTagKeyword = true; PO.SuppressUnwrittenScope = true; PO.ConstantArraySizeAsWritten = false; @@ -948,7 +945,7 @@ void USRGenerator::VisitType(QualType T) { } if (const DependentNameType *DNT = T->getAs()) { Out << '^'; - printQualifier(Out, Ctx, DNT->getQualifier()); + printQualifier(Out, LangOpts, DNT->getQualifier()); Out << ':' << DNT->getIdentifier()->getName(); return; } @@ -1090,7 +1087,7 @@ void USRGenerator::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl return; VisitDeclContext(D->getDeclContext()); Out <<
[clang] [NFC] Delete unused clang-formatted-file.txt/ClangFormattedStatus.rst files (PR #109220)
https://github.com/jurahul closed https://github.com/llvm/llvm-project/pull/109220 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Ignore previous partial specializations of member class templates explicitly specialized for a implicitly instantiated class template specialization (PR #113464)
https://github.com/sdkrystian updated https://github.com/llvm/llvm-project/pull/113464 >From 7542bda555601ed537dd9bacde65537021cf402d Mon Sep 17 00:00:00 2001 From: Krystian Stasiowski Date: Wed, 23 Oct 2024 10:28:23 -0400 Subject: [PATCH 1/5] [Clang][Sema] Ignore previous partial specializations of member class templates explicitly specialized for a implicitly instantiated class template specialization --- clang/lib/Sema/SemaTemplate.cpp | 13 + clang/lib/Sema/SemaTemplateInstantiate.cpp| 34 ++-- .../temp.spec.partial.member/p2.cpp | 53 +++ 3 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 clang/test/CXX/temp/temp.decls/temp.spec.partial/temp.spec.partial.member/p2.cpp diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index fcf05798d9c709..83e8447c0cdc0f 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -4383,6 +4383,19 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; +// C++ [temp.spec.partial.member]p2: +// If the primary member template is explicitly specialized for a given +// (implicit) specialization of the enclosing class template, the partial +// specializations of the member template are ignored for this +// specialization of the enclosing class template. If a partial +// specialization of the member template is explicitly specialized for a +// given (implicit) specialization of the enclosing class template, the +// primary member template and its other partial specializations are still +// considered for this specialization of the enclosing class template. +if (Template->isMemberSpecialization() && +!Partial->isMemberSpecialization()) + continue; + TemplateDeductionInfo Info(FailedCandidates.getLocation()); if (TemplateDeductionResult Result = diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp index dea97bfce532c9..6e1492f8cd447e 100644 --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -3978,11 +3978,23 @@ bool Sema::usesPartialOrExplicitSpecialization( return true; SmallVector PartialSpecs; - ClassTemplateSpec->getSpecializedTemplate() - ->getPartialSpecializations(PartialSpecs); - for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { + ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate(); + CTD->getPartialSpecializations(PartialSpecs); + for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) { +// C++ [temp.spec.partial.member]p2: +// If the primary member template is explicitly specialized for a given +// (implicit) specialization of the enclosing class template, the partial +// specializations of the member template are ignored for this +// specialization of the enclosing class template. If a partial +// specialization of the member template is explicitly specialized for a +// given (implicit) specialization of the enclosing class template, the +// primary member template and its other partial specializations are still +// considered for this specialization of the enclosing class template. +if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization()) + continue; + TemplateDeductionInfo Info(Loc); -if (DeduceTemplateArguments(PartialSpecs[I], +if (DeduceTemplateArguments(CTPSD, ClassTemplateSpec->getTemplateArgs().asArray(), Info) == TemplateDeductionResult::Success) return true; @@ -4027,6 +4039,20 @@ getPatternForClassTemplateSpecialization( TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; + // C++ [temp.spec.partial.member]p2: + // If the primary member template is explicitly specialized for a given + // (implicit) specialization of the enclosing class template, the + // partial specializations of the member template are ignored for this + // specialization of the enclosing class template. If a partial + // specialization of the member template is explicitly specialized for a + // given (implicit) specialization of the enclosing class template, the + // primary member template and its other partial specializations are + // still considered for this specialization of the enclosing class + // template. + if (Template->isMemberSpecialization() && + !Partial->isMemberSpecialization()) +continue; + TemplateDeductionInfo
[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `lldb-x86_64-debian` running on `lldb-x86_64-debian` while building `clang` at step 6 "test". Full details are available at: https://lab.llvm.org/buildbot/#/builders/162/builds/9362 Here is the relevant piece of the build log for the reference ``` Step 6 (test) failure: build (failure) ... PASS: lldb-api :: functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py (33 of 2698) PASS: lldb-api :: commands/gui/basic/TestGuiBasic.py (34 of 2698) PASS: lldb-api :: commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py (35 of 2698) PASS: lldb-api :: functionalities/load_unload/TestLoadUnload.py (36 of 2698) PASS: lldb-api :: commands/gui/viewlarge/TestGuiViewLarge.py (37 of 2698) PASS: lldb-api :: tools/lldb-server/TestGdbRemoteCompletion.py (38 of 2698) PASS: lldb-api :: lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py (39 of 2698) PASS: lldb-api :: commands/frame/recognizer/TestFrameRecognizer.py (40 of 2698) PASS: lldb-api :: types/TestIntegerTypeExpr.py (41 of 2698) PASS: lldb-api :: functionalities/process_save_core_minidump/TestProcessSaveCoreMinidump.py (42 of 2698) FAIL: lldb-api :: tools/lldb-dap/launch/TestDAP_launch.py (43 of 2698) TEST 'lldb-api :: tools/lldb-dap/launch/TestDAP_launch.py' FAILED Script: -- /usr/bin/python3 /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/API/dotest.py -u CXXFLAGS -u CFLAGS --env LLVM_LIBS_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/./lib --env LLVM_INCLUDE_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/include --env LLVM_TOOLS_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/./bin --arch x86_64 --build-dir /home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex --lldb-module-cache-dir /home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex/module-cache-lldb/lldb-api --clang-module-cache-dir /home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex/module-cache-clang/lldb-api --executable /home/worker/2.0.1/lldb-x86_64-debian/build/./bin/lldb --compiler /home/worker/2.0.1/lldb-x86_64-debian/build/./bin/clang --dsymutil /home/worker/2.0.1/lldb-x86_64-debian/build/./bin/dsymutil --make /usr/bin/make --llvm-tools-dir /home/worker/2.0.1/lldb-x86_64-debian/build/./bin --lldb-obj-root /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb --lldb-libs-dir /home/worker/2.0.1/lldb-x86_64-debian/build/./lib -t /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/API/tools/lldb-dap/launch -p TestDAP_launch.py -- Exit Code: 1 Command Output (stdout): -- lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 68daf7d27ecc085fe7347552736197db6453f71c) clang revision 68daf7d27ecc085fe7347552736197db6453f71c llvm revision 68daf7d27ecc085fe7347552736197db6453f71c Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 'debugserver', 'objc'] = DEBUG ADAPTER PROTOCOL LOGS = 1730297241.437439203 --> Content-Length: 344 { "arguments": { "adapterID": "lldb-native", "clientID": "vscode", "columnsStartAt1": true, "linesStartAt1": true, "locale": "en-us", "pathFormat": "path", "sourceInitFile": false, "supportsRunInTerminalRequest": true, "supportsStartDebuggingRequest": true, "supportsVariablePaging": true, "supportsVariableType": true }, "command": "initialize", "seq": 1, "type": "request" } 1730297241.439302206 <-- Content-Length: 1589 ``` https://github.com/llvm/llvm-project/pull/113796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)
https://github.com/c8ef closed https://github.com/llvm/llvm-project/pull/113796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 68daf7d - [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (#113796)
Author: c8ef Date: 2024-10-30T22:04:14+08:00 New Revision: 68daf7d27ecc085fe7347552736197db6453f71c URL: https://github.com/llvm/llvm-project/commit/68daf7d27ecc085fe7347552736197db6453f71c DIFF: https://github.com/llvm/llvm-project/commit/68daf7d27ecc085fe7347552736197db6453f71c.diff LOG: [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (#113796) Fixes #94459. This patch adds binary search related `std::ranges` symbols to the mapping. Added: Modified: clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc Removed: diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc b/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc index 0d351d688a3296..4d466013eeac3f 100644 --- a/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc +++ b/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc @@ -367,6 +367,11 @@ SYMBOL(any_cast, std::, ) SYMBOL(div, std::, ) SYMBOL(abort, std::, ) +SYMBOL(binary_search, std::ranges::, ) +SYMBOL(equal_range, std::ranges::, ) +SYMBOL(lower_bound, std::ranges::, ) +SYMBOL(upper_bound, std::ranges::, ) + // These are C symbols that are not under std namespace. SYMBOL(localtime_r, None, ) SYMBOL(localtime_r, None, ) ___ 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 a check for signed and unsigned integers comparison (PR #113144)
@@ -0,0 +1,68 @@ +.. title:: clang-tidy - qt-integer-sign-comparison + +qt-integer-sign-comparison += + +The qt-integer-sign-comparison check is an alias, please see +:doc:`modernize-use-integer-sign-comparison <../modernize/use-integer-sign-comparison>` +for more information. + +Examples of fixes created by the check: + +.. code-block:: c++ + +uint func(int bla) +{ +uint result; +if (result == bla) +return 0; + +return 1; +} + +in C++17 becomes + +.. code-block:: c++ + + + +uint func(int bla) +{ +uint result; +if (q20::cmp_equal(result, bla)) +return 0; + +return 1; +} + +in C++20 becomes + +.. code-block:: c++ + +#include + +uint func(int bla) +{ +uint result; +if (std::cmp_equal(result, bla)) +return 0; + +return 1; +} + +Options +--- + +.. option:: IncludeStyle + + A string specifying which include-style is used, `llvm` or `google`. Default + is `llvm`. + +.. option:: IsQtApplication + + When `true` (default `false`), then it is assumed that the code being analyzed EugeneZelenko wrote: Default should be separate statement at the end. https://github.com/llvm/llvm-project/pull/113144 ___ 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 a check for signed and unsigned integers comparison (PR #113144)
@@ -0,0 +1,68 @@ +.. title:: clang-tidy - qt-integer-sign-comparison + +qt-integer-sign-comparison += + +The qt-integer-sign-comparison check is an alias, please see +:doc:`modernize-use-integer-sign-comparison <../modernize/use-integer-sign-comparison>` +for more information. + +Examples of fixes created by the check: + +.. code-block:: c++ + +uint func(int bla) +{ +uint result; +if (result == bla) +return 0; + +return 1; +} + +in C++17 becomes + +.. code-block:: c++ + + + +uint func(int bla) +{ +uint result; +if (q20::cmp_equal(result, bla)) +return 0; + +return 1; +} + +in C++20 becomes + +.. code-block:: c++ + +#include + +uint func(int bla) +{ +uint result; +if (std::cmp_equal(result, bla)) +return 0; + +return 1; +} + +Options +--- + +.. option:: IncludeStyle + + A string specifying which include-style is used, `llvm` or `google`. Default + is `llvm`. + +.. option:: IsQtApplication + + When `true` (default `false`), then it is assumed that the code being analyzed + is the Qt-based code. + +.. option:: StringsMatchHeader + A string specifying a include header file to be added by fix-it. Default EugeneZelenko wrote: Please separate with newline. https://github.com/llvm/llvm-project/pull/113144 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
https://github.com/bricknerb edited https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
https://github.com/bricknerb edited https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
https://github.com/bricknerb edited https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
https://github.com/bricknerb edited https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
@@ -477,6 +485,100 @@ void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, setSeverity(Diag, Map, Loc); } +namespace { +class WarningsSpecialCaseList : public llvm::SpecialCaseList { bricknerb wrote: Yes, I think the current state is pretty bad so if you're willing to refactor (in a separate PR, could also be a followup), this would be great. I think WarningsSpecialCaseList::createOrDie() would be surprising and I assume future changes could be harder to make and/or make the API much less clear. https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [SYCL] The sycl_kernel_entry_point attribute. (PR #111389)
@@ -455,6 +455,174 @@ The SYCL kernel in the previous code sample meets these expectations. }]; } +def SYCLKernelEntryPointDocs : Documentation { + let Category = DocCatFunction; + let Content = [{ +The ``sycl_kernel_entry_point`` attribute facilitates the generation of an +offload kernel entry point, sometimes called a SYCL kernel caller function, +suitable for invoking a SYCL kernel on an offload device. The attribute is +intended for use in the implementation of SYCL kernel invocation functions +like the ``single_task`` and ``parallel_for`` member functions of the +``sycl::handler`` class specified in section 4.9.4, "Command group ``handler`` +class", of the SYCL 2020 specification. + +The attribute requires a single type argument that specifies a class type that +meets the requirements for a SYCL kernel name as described in section 5.2, +"Naming of kernels", of the SYCL 2020 specification. A unique kernel name type +is required for each function declared with the attribute. The attribute may +not first appear on a declaration that follows a definition of the function. + +The attribute only appertains to functions and only those that meet the +following requirements. + +* Has a ``void`` return type. +* Is not a non-static member function, constructor, or destructor. +* Is not a C variadic function. +* Is not a coroutine. +* Is not defined as deleted or as defaulted. +* Is not declared with the ``constexpr`` or ``consteval`` specifiers. +* Is not declared with the ``[[noreturn]]`` attribute. tahonermann wrote: No, we dropped the function template requirement as being unnecessary. This permits an implementation to declare single purpose kernels if desired. https://github.com/llvm/llvm-project/pull/111389 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC} Call base class method in DarwinAArch64TargetInfo::getOSDefines (PR #114241)
https://github.com/ahatanak updated https://github.com/llvm/llvm-project/pull/114241 >From 98fe1611486549221a1475188d6d19a2d2cc9d12 Mon Sep 17 00:00:00 2001 From: Akira Hatanaka Date: Wed, 30 Oct 2024 07:36:31 -0700 Subject: [PATCH] [NFC] Call base class method in DarwinAArch64TargetInfo::getOSDefines --- clang/lib/Basic/Targets/AArch64.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Basic/Targets/AArch64.cpp b/clang/lib/Basic/Targets/AArch64.cpp index a0f94d5d315480..e9c1917ccbf060 100644 --- a/clang/lib/Basic/Targets/AArch64.cpp +++ b/clang/lib/Basic/Targets/AArch64.cpp @@ -1716,7 +1716,7 @@ void DarwinAArch64TargetInfo::getOSDefines(const LangOptions &Opts, if (Triple.isArm64e()) Builder.defineMacro("__arm64e__", "1"); - getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion); + DarwinTargetInfo::getOSDefines(Opts, Triple, Builder); } TargetInfo::BuiltinVaListKind ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Tooling/Inclusion] Update std symbols mapping (PR #113612)
vvd170501 wrote: > thanks a lot, lgtm! > > LMK if i should commit this for you Yes, commit it please, I don't have the permissions. https://github.com/llvm/llvm-project/pull/113612 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add sincos builtin using `llvm.sincos` intrinsic (PR #114086)
@@ -722,6 +722,38 @@ static Value *emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, return CGF.Builder.CreateExtractValue(Call, 0); } +static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, + llvm::Intrinsic::ID IntrinsicID) { + llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0)); + llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1)); + llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2)); + + llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()}); + llvm::Value *Call = CGF.Builder.CreateCall(F, Val); + + llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0); + llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1); + + QualType DestPtrType = E->getArg(1)->getType()->getPointeeType(); + LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType); + LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType); + + llvm::StoreInst *StoreSin = + CGF.Builder.CreateStore(SinResult, SinLV.getAddress()); + llvm::StoreInst *StoreCos = + CGF.Builder.CreateStore(CosResult, CosLV.getAddress()); + + // Mark the two stores as non-aliasing with eachother. The order of stores arsenm wrote: Typo eachother https://github.com/llvm/llvm-project/pull/114086 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add sincos builtin using `llvm.sincos` intrinsic (PR #114086)
@@ -722,6 +722,36 @@ static Value *emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, return CGF.Builder.CreateExtractValue(Call, 0); } +static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, + llvm::Intrinsic::ID IntrinsicID) { + llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0)); + llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1)); + llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2)); + + llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()}); + llvm::Value *Call = CGF.Builder.CreateCall(F, Val); + + llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0); + llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1); + + QualType DestPtrType = E->getArg(1)->getType()->getPointeeType(); + LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType); + LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType); + + llvm::StoreInst *StoreSin = CGF.Builder.CreateStore(SinResult, SinLV.getAddress()); + llvm::StoreInst *StoreCos = CGF.Builder.CreateStore(CosResult, CosLV.getAddress()); + + // Mark the two stores as non-aliasing with eachother. The order of stores + // emitted by this builtin is arbitrary, enforcing a particular order will + // prevent optimizations later on. + llvm::MDBuilder MDHelper(CGF.getLLVMContext()); + MDNode* Domain = MDHelper.createAnonymousAliasScopeDomain(); + MDNode* AliasScope = MDHelper.createAnonymousAliasScope(Domain); + MDNode* AliasScopeList = MDNode::get(Call->getContext(), AliasScope); + StoreSin->setMetadata(LLVMContext::MD_alias_scope, AliasScopeList); + StoreCos->setMetadata(LLVMContext::MD_noalias, AliasScopeList); arsenm wrote: It would not be useful to use this with aliasing arguments. I think it's fine to assume they can be written in any order https://github.com/llvm/llvm-project/pull/114086 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix for codegen Crash in Clang when using locator omp_all_memory with depobj construct (PR #114221)
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/114221 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
@@ -477,6 +486,109 @@ void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, setSeverity(Diag, Map, Loc); } +namespace { +class WarningsSpecialCaseList : public llvm::SpecialCaseList { +public: + static std::unique_ptr + create(const llvm::MemoryBuffer &MB, std::string &Err) { +auto SCL = std::make_unique(); +if (!SCL->createInternal(&MB, Err)) + return nullptr; +return SCL; + } + + // Section names refer to diagnostic groups, which cover multiple individual + // diagnostics. Expand diagnostic groups here to individual diagnostics. + // A diagnostic can have multiple diagnostic groups associated with it, we let + // the last section take precedence in such cases. + void processSections(DiagnosticsEngine &Diags) { +// Drop the default section introduced by special case list, we only support +// exact diagnostic group names. +Sections.erase("*"); +// Make sure we iterate sections by their line numbers. +std::vector *>> +LineAndSectionEntry; +LineAndSectionEntry.reserve(Sections.size()); +for (const auto &Entry : Sections) { + LineAndSectionEntry.emplace_back( + Entry.second.SectionMatcher->Globs.at(Entry.first()).second, &Entry); bricknerb wrote: There are 3 first and second references, consider putting some in variables to make it easier to follow what this actually does. https://github.com/llvm/llvm-project/pull/112517 ___ 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 a check for signed and unsigned integers comparison (PR #113144)
https://github.com/qt-tatiana updated https://github.com/llvm/llvm-project/pull/113144 >From 34ee6f5836efe3acddbdd1c9810af358b8c4f981 Mon Sep 17 00:00:00 2001 From: Tatiana Borisova Date: Thu, 17 Oct 2024 18:00:08 +0200 Subject: [PATCH 1/6] [clang-tidy] Create a check for signed and unsigned integers comparison - modernize-use-integer-sign-comparison check performs comparisons between signed and unsigned integer types mathematically correct. If C++20 is supported the check replaces integers comparisons to std::cmp_{} functions and add include. - qt-integer-sign-comparison check works like an alias of modernize-use-integer-sign-comparison for C++20. If only C++17 is supported the check replaces integers comparisons to q20::cmp_{} functions and add include. The check assumes the analysed code is Qt-based code. - add qt module for qt-related checks. --- clang-tools-extra/clang-tidy/CMakeLists.txt | 2 + .../clang-tidy/ClangTidyForceLinker.h | 5 + .../clang-tidy/modernize/CMakeLists.txt | 1 + .../UseIntegerSignComparisonCheck.cpp | 169 ++ .../modernize/UseIntegerSignComparisonCheck.h | 46 + .../clang-tidy/qt/CMakeLists.txt | 26 +++ .../clang-tidy/qt/QtTidyModule.cpp| 46 + clang-tools-extra/docs/ReleaseNotes.rst | 17 ++ .../docs/clang-tidy/checks/list.rst | 3 + .../modernize/use-integer-sign-comparison.rst | 43 + .../checks/qt/IntegerCrossSignComparison.rst | 64 +++ clang-tools-extra/docs/clang-tidy/index.rst | 1 + .../modernize/use-integer-sign-comparison.cpp | 61 +++ .../qt/qt-integer-sign-comparison.cpp | 61 +++ 14 files changed, 545 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h create mode 100644 clang-tools-extra/clang-tidy/qt/CMakeLists.txt create mode 100644 clang-tools-extra/clang-tidy/qt/QtTidyModule.cpp create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst create mode 100644 clang-tools-extra/docs/clang-tidy/checks/qt/IntegerCrossSignComparison.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-integer-sign-comparison.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/qt/qt-integer-sign-comparison.cpp diff --git a/clang-tools-extra/clang-tidy/CMakeLists.txt b/clang-tools-extra/clang-tidy/CMakeLists.txt index 83a3236131dc93..56ef16a8fb37d6 100644 --- a/clang-tools-extra/clang-tidy/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/CMakeLists.txt @@ -75,6 +75,7 @@ add_subdirectory(objc) add_subdirectory(openmp) add_subdirectory(performance) add_subdirectory(portability) +add_subdirectory(qt) add_subdirectory(readability) add_subdirectory(zircon) set(ALL_CLANG_TIDY_CHECKS @@ -99,6 +100,7 @@ set(ALL_CLANG_TIDY_CHECKS clangTidyOpenMPModule clangTidyPerformanceModule clangTidyPortabilityModule + clangTidyQtModule clangTidyReadabilityModule clangTidyZirconModule ) diff --git a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h index adde9136ff1dd5..3c777f42520223 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h +++ b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h @@ -127,6 +127,11 @@ extern volatile int PortabilityModuleAnchorSource; static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination = PortabilityModuleAnchorSource; +// This anchor is used to force the linker to link the QtClangTidyModule. +extern volatile int QtClangTidyModuleAnchorSource; +static int LLVM_ATTRIBUTE_UNUSED QtClangTidyModuleAnchorDestination = +QtClangTidyModuleAnchorSource; + // This anchor is used to force the linker to link the ReadabilityModule. extern volatile int ReadabilityModuleAnchorSource; static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index c919d49b42873a..bab1167fb15ff2 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -36,6 +36,7 @@ add_clang_library(clangTidyModernizeModule STATIC UseEmplaceCheck.cpp UseEqualsDefaultCheck.cpp UseEqualsDeleteCheck.cpp + UseIntegerSignComparisonCheck.cpp UseNodiscardCheck.cpp UseNoexceptCheck.cpp UseNullptrCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp new file mode 100644 index 00..8f394a14a9b0c4 --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp @@ -0,0 +1,169 @@ +//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy --
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
@@ -477,6 +486,109 @@ void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, setSeverity(Diag, Map, Loc); } +namespace { +class WarningsSpecialCaseList : public llvm::SpecialCaseList { +public: + static std::unique_ptr + create(const llvm::MemoryBuffer &MB, std::string &Err) { +auto SCL = std::make_unique(); +if (!SCL->createInternal(&MB, Err)) + return nullptr; +return SCL; + } + + // Section names refer to diagnostic groups, which cover multiple individual + // diagnostics. Expand diagnostic groups here to individual diagnostics. + // A diagnostic can have multiple diagnostic groups associated with it, we let + // the last section take precedence in such cases. + void processSections(DiagnosticsEngine &Diags) { +// Drop the default section introduced by special case list, we only support +// exact diagnostic group names. +Sections.erase("*"); +// Make sure we iterate sections by their line numbers. +std::vector *>> +LineAndSectionEntry; +LineAndSectionEntry.reserve(Sections.size()); +for (const auto &Entry : Sections) { + LineAndSectionEntry.emplace_back( + Entry.second.SectionMatcher->Globs.at(Entry.first()).second, &Entry); bricknerb wrote: Are we confident Globs.at() will always succeed? https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] Introduce diagnostics suppression mappings (PR #112517)
@@ -477,6 +486,109 @@ void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, setSeverity(Diag, Map, Loc); } +namespace { +class WarningsSpecialCaseList : public llvm::SpecialCaseList { +public: + static std::unique_ptr + create(const llvm::MemoryBuffer &MB, std::string &Err) { +auto SCL = std::make_unique(); +if (!SCL->createInternal(&MB, Err)) + return nullptr; +return SCL; + } + + // Section names refer to diagnostic groups, which cover multiple individual + // diagnostics. Expand diagnostic groups here to individual diagnostics. + // A diagnostic can have multiple diagnostic groups associated with it, we let + // the last section take precedence in such cases. + void processSections(DiagnosticsEngine &Diags) { +// Drop the default section introduced by special case list, we only support +// exact diagnostic group names. +Sections.erase("*"); +// Make sure we iterate sections by their line numbers. +std::vector *>> +LineAndSectionEntry; +LineAndSectionEntry.reserve(Sections.size()); +for (const auto &Entry : Sections) { bricknerb wrote: Can we do const auto&[X,Y] here? https://github.com/llvm/llvm-project/pull/112517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add sincos builtin using `llvm.sincos` intrinsic (PR #114086)
https://github.com/MacDue updated https://github.com/llvm/llvm-project/pull/114086 >From 7fd19eefa1d1f61843fe1844a72e14c7f4bae03b Mon Sep 17 00:00:00 2001 From: Benjamin Maxwell Date: Mon, 9 Sep 2024 10:15:20 + Subject: [PATCH 1/2] [clang] Add sincos builtin using `llvm.sincos` intrinsic This registers `sincos[f|l]` as a clang builtin and updates GCBuiltin to emit the `llvm.sincos.*` intrinsic when `-fno-math-errno` is set. --- clang/include/clang/Basic/Builtins.td| 13 +++ clang/lib/CodeGen/CGBuiltin.cpp | 43 clang/test/CodeGen/AArch64/sincos.c | 33 ++ clang/test/CodeGen/X86/math-builtins.c | 35 +++ clang/test/OpenMP/declare_simd_aarch64.c | 4 +-- 5 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/AArch64/sincos.c diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td index 9bd67e0cefebc3..27eadf80d623e6 100644 --- a/clang/include/clang/Basic/Builtins.td +++ b/clang/include/clang/Basic/Builtins.td @@ -3562,6 +3562,19 @@ def Frexp : FPMathTemplate, LibBuiltin<"math.h"> { let AddBuiltinPrefixedAlias = 1; } +def Sincos : FPMathTemplate, GNULibBuiltin<"math.h"> { + let Spellings = ["sincos"]; + let Attributes = [NoThrow]; + let Prototype = "void(T, T*, T*)"; + let AddBuiltinPrefixedAlias = 1; +} + +def SincosF16F128 : F16F128MathTemplate, Builtin { + let Spellings = ["__builtin_sincos"]; + let Attributes = [FunctionWithBuiltinPrefix, NoThrow]; + let Prototype = "void(T, T*, T*)"; +} + def Ldexp : FPMathTemplate, LibBuiltin<"math.h"> { let Spellings = ["ldexp"]; let Attributes = [NoThrow, ConstIgnoringErrnoAndExceptions]; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 65d7f5c54a1913..331b367e63d91b 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -722,6 +722,38 @@ static Value *emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, return CGF.Builder.CreateExtractValue(Call, 0); } +static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, + llvm::Intrinsic::ID IntrinsicID) { + llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0)); + llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1)); + llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2)); + + llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()}); + llvm::Value *Call = CGF.Builder.CreateCall(F, Val); + + llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0); + llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1); + + QualType DestPtrType = E->getArg(1)->getType()->getPointeeType(); + LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType); + LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType); + + llvm::StoreInst *StoreSin = + CGF.Builder.CreateStore(SinResult, SinLV.getAddress()); + llvm::StoreInst *StoreCos = + CGF.Builder.CreateStore(CosResult, CosLV.getAddress()); + + // Mark the two stores as non-aliasing with eachother. The order of stores + // emitted by this builtin is arbitrary, enforcing a particular order will + // prevent optimizations later on. + llvm::MDBuilder MDHelper(CGF.getLLVMContext()); + MDNode *Domain = MDHelper.createAnonymousAliasScopeDomain(); + MDNode *AliasScope = MDHelper.createAnonymousAliasScope(Domain); + MDNode *AliasScopeList = MDNode::get(Call->getContext(), AliasScope); + StoreSin->setMetadata(LLVMContext::MD_alias_scope, AliasScopeList); + StoreCos->setMetadata(LLVMContext::MD_noalias, AliasScopeList); +} + /// EmitFAbs - Emit a call to @llvm.fabs(). static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) { Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType()); @@ -3094,6 +3126,17 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, return RValue::get(emitUnaryMaybeConstrainedFPBuiltin( *this, E, Intrinsic::sinh, Intrinsic::experimental_constrained_sinh)); +case Builtin::BIsincos: +case Builtin::BIsincosf: +case Builtin::BIsincosl: +case Builtin::BI__builtin_sincos: +case Builtin::BI__builtin_sincosf: +case Builtin::BI__builtin_sincosl: +case Builtin::BI__builtin_sincosf128: +case Builtin::BI__builtin_sincosf16: + emitSincosBuiltin(*this, E, Intrinsic::sincos); + return RValue::get(nullptr); + case Builtin::BIsqrt: case Builtin::BIsqrtf: case Builtin::BIsqrtl: diff --git a/clang/test/CodeGen/AArch64/sincos.c b/clang/test/CodeGen/AArch64/sincos.c new file mode 100644 index 00..240d921b2b7034 --- /dev/null +++ b/clang/test/CodeGen/AArch64/sincos.c @@ -0,0 +1,33 @@ +// RUN: %clang_cc1 -triple=aarch64-gnu-linux -emit-llvm %s -o - | FileCheck --check-prefix=NO-MATH-ERRNO %s +// RUN: %clang_cc1 -triple=aarch64-gnu-linux -emit-llvm -fmath-errno %s -o - | FileCheck --check-prefix=MATH-
[clang] [SYCL] The sycl_kernel_entry_point attribute. (PR #111389)
@@ -14296,6 +14296,31 @@ void ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap, } } +static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, + CanQualType KernelNameType, + const FunctionDecl *FD) { + return { KernelNameType, FD }; +} + +void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) { + assert(!FD->isInvalidDecl()); + assert(!FD->isDependentContext()); + + const auto *SKEPAttr = FD->getAttr(); + assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute"); + + CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName()); + auto IT = SYCLKernels.find(KernelNameType); + if (IT != SYCLKernels.end()) { +if (!declaresSameEntity(FD, IT->second.GetKernelEntryPointDecl())) + llvm::report_fatal_error("SYCL kernel name conflict"); erichkeane wrote: That is just not something we do in Clang, we use fatal error for situations where we SHOULD have handled it, but don't (yet). I believe this to be the wrong choice. https://github.com/llvm/llvm-project/pull/111389 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits