[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-04-17 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

@HighCommander4 Any chance to have a try on this patch? I'm looking forward to 
the feedback, thanks!

https://github.com/llvm/llvm-project/pull/86629
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-04-17 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

@rjmccall @dwblaikie ping

https://github.com/llvm/llvm-project/pull/75912
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [clang][NFC] Fix FieldDecl::isUnnamedBitfield() capitalization (PR #89048)

2024-04-17 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr closed 
https://github.com/llvm/llvm-project/pull/89048
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 3d56ea0 - [clang][NFC] Fix FieldDecl::isUnnamedBitfield() capitalization (#89048)

2024-04-17 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-04-18T07:39:29+02:00
New Revision: 3d56ea05b6c746a7144f643bef2ebd599f605b8b

URL: 
https://github.com/llvm/llvm-project/commit/3d56ea05b6c746a7144f643bef2ebd599f605b8b
DIFF: 
https://github.com/llvm/llvm-project/commit/3d56ea05b6c746a7144f643bef2ebd599f605b8b.diff

LOG: [clang][NFC] Fix FieldDecl::isUnnamedBitfield() capitalization (#89048)

We always capitalize bitfield as "BitField".

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp
clang/include/clang/AST/Decl.h
clang/lib/AST/APValue.cpp
clang/lib/AST/ASTContext.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclCXX.cpp
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/EvaluationResult.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/MicrosoftMangle.cpp
clang/lib/Analysis/FlowSensitive/ASTOps.cpp
clang/lib/Analysis/UninitializedValues.cpp
clang/lib/CodeGen/ABIInfoImpl.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprAgg.cpp
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/CodeGen/CGExprConstant.cpp
clang/lib/CodeGen/CodeGenTBAA.cpp
clang/lib/CodeGen/Targets/X86.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaInit.cpp
clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
clang/lib/StaticAnalyzer/Core/RegionStore.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
index 855c4a2efc373e..9c3c7cc70c187b 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -444,7 +444,7 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer(
 if (!F->hasInClassInitializer() &&
 utils::type_traits::isTriviallyDefaultConstructible(F->getType(),
 Context) &&
-!isEmpty(Context, F->getType()) && !F->isUnnamedBitfield() &&
+!isEmpty(Context, F->getType()) && !F->isUnnamedBitField() &&
 !AnyMemberHasInitPerUnion)
   FieldsToInit.insert(F);
   });

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 5134eb51a03226..93151024064b42 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -26,7 +26,7 @@ getAllNamedFields(const CXXRecordDecl *Record) {
   std::set Result;
   for (const auto *Field : Record->fields()) {
 // Static data members are not in this range.
-if (Field->isUnnamedBitfield())
+if (Field->isUnnamedBitField())
   continue;
 Result.insert(Field);
   }

diff  --git a/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp 
b/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp
index 1dde0490517852..4a9426ee7e8bbb 100644
--- a/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp
@@ -99,7 +99,7 @@ ExceptionSpecAnalyzer::analyzeRecord(const CXXRecordDecl 
*RecordDecl,
   }
 
   for (const auto *FDecl : RecordDecl->fields())
-if (!FDecl->isInvalidDecl() && !FDecl->isUnnamedBitfield()) {
+if (!FDecl->isInvalidDecl() && !FDecl->isUnnamedBitField()) {
   State Result = analyzeFieldDecl(FDecl, Kind);
   if (Result == State::Throwing || Result == State::Unknown)
 return Result;

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 91449ebcceec37..0a9c9e17d3f9f9 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3149,7 +3149,7 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
   bool isBitField() const { return BitField; }
 
   /// Determines whether this is an unnamed bitfield.
-  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
+  bool isUnnamedBitField() const { return isBitField() && !getDeclName(); }
 
   /// Determines whether this field is a
   /// representative for an anonymous struct or union. Such fields are

diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
index d8042321319a67..8c77b563657d90 100644
--- a/clang/lib/AST/APValue.cpp
+++ b/clang/lib/AST/APValue.cpp
@@ -908,7 +908,8 @@ void APValue::printPretty(raw_ostream , const 
PrintingPolicy ,
 for (const auto *FI : RD->fields()) {
   if (!First)
 Out << ", ";
-  if 

[clang] [clang] Distinguish unresolved templates in UnresolvedLookupExpr (PR #89019)

2024-04-17 Thread Younan Zhang via cfe-commits


@@ -186,3 +186,74 @@ class E {
 #endif
 template using D = int; // expected-note {{declared here}} 
 E ed; // expected-note {{instantiation of}}
+
+namespace non_functions {
+
+#if __cplusplus >= 201103L
+namespace PR88832 {
+template  struct O {
+  static const T v = 0;
+};
+
+struct P {
+  template  using I = typename O::v; // #TypeAlias
+};
+
+struct Q {
+  template  int foo() {
+return T::template I; // expected-error {{'P::I' is expected to be a 
non-type template, but instantiated to a type alias template}}
+// expected-note@#TypeAlias {{type alias template declared here}}

zyn0217 wrote:

> Can you add some more tests that involve an expression with this new type as 
> the argument to a function call?

Done. Thanks for the feedback.

https://github.com/llvm/llvm-project/pull/89019
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Distinguish unresolved templates in UnresolvedLookupExpr (PR #89019)

2024-04-17 Thread Younan Zhang via cfe-commits


@@ -186,3 +186,74 @@ class E {
 #endif
 template using D = int; // expected-note {{declared here}} 
 E ed; // expected-note {{instantiation of}}
+
+namespace non_functions {
+
+#if __cplusplus >= 201103L
+namespace PR88832 {
+template  struct O {
+  static const T v = 0;
+};
+
+struct P {
+  template  using I = typename O::v; // #TypeAlias
+};
+
+struct Q {
+  template  int foo() {
+return T::template I; // expected-error {{'P::I' is expected to be a 
non-type template, but instantiated to a type alias template}}
+// expected-note@#TypeAlias {{type alias template declared here}}

zyn0217 wrote:

I think this is more of a preference - subjectively, I feel like using markers 
makes the diagnostics concentrated, and one can see them in a somewhat 
consistent block without guessing what else notes/warnings an error diagnostic 
would also provide, though this looks a bit untidy. :(

https://github.com/llvm/llvm-project/pull/89019
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV][clang] Don't enable -mrelax-all for -O0 on RISC-V (PR #88538)

2024-04-17 Thread Fangrui Song via cfe-commits


@@ -1,4 +1,4 @@
-// XFAIL: target={{.*}}-aix{{.*}}
+// XFAIL: target={{.*}}-aix{{.*}}, target=riscv{{.*}}

MaskRay wrote:

This causes different behaviors with the default target triple, which is 
probably not perfect.

I think we can change the -mrelax-all check with an explicit target triple and 
then add a `--target=riscv64`.

https://github.com/llvm/llvm-project/pull/88538
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV][clang] Don't enable -mrelax-all for -O0 on RISC-V (PR #88538)

2024-04-17 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay approved this pull request.

I left a comment at 
https://github.com/llvm/llvm-project/issues/87127#issuecomment-2063027106

This is more about a weird -O0 -mrelax-all behavior that RISC-V now opts out, 
which is good on its own, even if the basis looks like a self-inflicted 
problem...

https://github.com/llvm/llvm-project/pull/88538
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov approved this pull request.

LGTM, Thanks!

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Distinguish unresolved templates in UnresolvedLookupExpr (PR #89019)

2024-04-17 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/89019

>From 89a5bbcc89c1e43ac7f2e60f3c234c2c42928c86 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 17 Apr 2024 12:24:56 +0800
Subject: [PATCH 1/3] [clang] Distinguish unresolved templates in
 UnresolvedLookupExpr

This patch revolves around the misuse of UnresolvedLookupExpr in
BuildTemplateIdExpr.

Basically, we build up an UnresolvedLookupExpr not only for function
overloads but for "unresolved" templates wherever we need an expression
for template decls. For example, a dependent VarTemplateDecl can be
wrapped with such an expression before template instantiation. (See
https://github.com/llvm/llvm-project/commit/617007240cbfb97c8ccf6d61b0c4ca0bb62d43c9)

Also, one important thing is that UnresolvedLookupExpr uses a "canonical"
QualType to describe the containing unresolved decls: a DependentTy is
for dependent expressions and an OverloadTy otherwise. Therefore, this
modeling for non-dependent templates leaves a problem in that the expression
is marked and perceived as if describing overload functions. The consumer then
expects functions for every such expression, although the fact is the reverse.
Hence, we run into crashes.

As to the patch, I added a new canonical type "UnresolvedTemplateTy" to
model these cases. Given that we have been using this model (intentionally or
accidentally) and it is pretty baked in throughout the code, I think
extending the role of UnresolvedLookupExpr is reasonable. Further, I added
some diagnostics for the direct occurrence of these expressions, which
are supposed to be ill-formed.

As a bonus, this patch also fixes some typos in the diagnostics and creates
RecoveryExprs rather than nothing in the hope of a better error-recovery
for clangd.

Fixes https://github.com/llvm/llvm-project/issues/88832
Fixes https://github.com/llvm/llvm-project/issues/63243
Fixes https://github.com/llvm/llvm-project/issues/48673
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/AST/ASTContext.h  |  3 +-
 clang/include/clang/AST/BuiltinTypes.def  |  3 +
 .../include/clang/Serialization/ASTBitCodes.h |  5 +-
 clang/lib/AST/ASTContext.cpp  |  3 +
 clang/lib/AST/NSAPI.cpp   |  1 +
 clang/lib/AST/Type.cpp|  3 +
 clang/lib/AST/TypeLoc.cpp |  1 +
 clang/lib/Sema/SemaExpr.cpp   | 19 +
 clang/lib/Sema/SemaTemplate.cpp   | 13 +++-
 clang/lib/Serialization/ASTCommon.cpp |  3 +
 clang/lib/Serialization/ASTReader.cpp |  3 +
 clang/test/SemaCXX/PR62533.cpp|  2 +-
 clang/test/SemaTemplate/template-id-expr.cpp  | 71 +++
 14 files changed, 125 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index efc32212f300cf..8c50988083faa6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -535,6 +535,7 @@ Bug Fixes to C++ Support
 - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329).
 - Fix a crash in requires expression with templated base class member 
function. Fixes (#GH84020).
 - Placement new initializes typedef array with correct size (#GH41441)
+- Fixed a misuse of ``UnresolvedLookupExpr`` for ill-formed templated 
expressions. Fixes (#GH48673), (#GH63243) and (#GH88832).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 28f8d67811f0a2..e9a22f04cfe764 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1116,7 +1116,8 @@ class ASTContext : public RefCountedBase {
   CanQualType BFloat16Ty;
   CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
   CanQualType VoidPtrTy, NullPtrTy;
-  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
+  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
+  UnknownAnyTy;
   CanQualType BuiltinFnTy;
   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
diff --git a/clang/include/clang/AST/BuiltinTypes.def 
b/clang/include/clang/AST/BuiltinTypes.def
index c04f6f6f127191..fd0cc10be8ebca 100644
--- a/clang/include/clang/AST/BuiltinTypes.def
+++ b/clang/include/clang/AST/BuiltinTypes.def
@@ -285,6 +285,9 @@ PLACEHOLDER_TYPE(Overload, OverloadTy)
 //   x->foo   # if only contains non-static members
 PLACEHOLDER_TYPE(BoundMember, BoundMemberTy)
 
+// The type of an unresolved template. Used in UnresolvedLookupExpr.
+PLACEHOLDER_TYPE(UnresolvedTemplate, UnresolvedTemplateTy)
+
 // The type of an expression which refers to a pseudo-object,
 // such as those introduced by Objective C's @property or
 // VS.NET's __property declarations.  A placeholder type.  The
diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 

[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

https://github.com/danix800 updated 
https://github.com/llvm/llvm-project/pull/89096

>From 0d6d52365a5d31045c347412c3a0fe8be7119006 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 00:33:29 +0800
Subject: [PATCH 1/5] [ASTImporter] Fix infinite recurse on return type
 declared inside body (#68775)

Lambda without trailing auto could has return type declared
inside the body too.
---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/lib/AST/ASTImporter.cpp   | 16 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 16 
 3 files changed, 24 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..7a623c6be72fd2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -545,6 +545,8 @@ Bug Fixes to AST Handling
 Miscellaneous Bug Fixes
 ^^^
 
+- Fixed an infinite recursion on return type declared inside body (#GH68775).
+
 Miscellaneous Clang Crashes Fixed
 ^
 
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 6aaa34c55ce307..3bbd6ebaf1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -695,7 +695,7 @@ namespace clang {
 // Returns true if the given function has a placeholder return type and
 // that type is declared inside the body of the function.
 // E.g. auto f() { struct X{}; return X(); }
-bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
+bool hasReturnTypeDeclaredInside(FunctionDecl *D);
   };
 
 template 
@@ -3649,19 +3649,15 @@ class IsTypeDeclaredInsideVisitor
 
 /// This function checks if the function has 'auto' return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
   QualType RetT = FromFPT->getReturnType();
-  if (isa(RetT.getTypePtr())) {
-FunctionDecl *Def = D->getDefinition();
-IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
-return Visitor.CheckType(RetT);
-  }
-
-  return false;
+  FunctionDecl *Def = D->getDefinition();
+  IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
+  return Visitor.CheckType(RetT);
 }
 
 ExplicitSpecifier
@@ -3811,7 +3807,7 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
+if (hasReturnTypeDeclaredInside(D)) {
   FromReturnTy = Importer.getFromContext().VoidTy;
   UsedDifferentProtoType = true;
 }
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index acc596fef87b76..3fac5514319c24 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -6721,6 +6721,22 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
LambdaInFunctionBody) {
   EXPECT_FALSE(FromL->isDependentLambda());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, LambdaReturnTypeDeclaredInside) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  void foo() {
+(void) []() {
+  struct X {};
+  return X();
+};
+  }
+  )",
+  Lang_CXX11, "", Lang_CXX11, "foo");
+  auto *ToLambda = FirstDeclMatcher().match(To, lambdaExpr());
+  EXPECT_TRUE(ToLambda);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
   Decl *FromTU = getTuDecl(
   R"(

>From 3f1d714a2aa4b236afe9bb1384be073fb155a2b8 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 08:56:56 +0800
Subject: [PATCH 2/5] Limit TypeVisitor checking to 'auto' and lambda
 definition only

1. Fix potential perf regression;
2. Fix comment.
---
 clang/lib/AST/ASTImporter.cpp | 16 
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3bbd6ebaf1..d98cb80c349db2 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3647,17 +3647,25 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
 bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = 

[clang] [clang] Distinguish unresolved templates in UnresolvedLookupExpr (PR #89019)

2024-04-17 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/89019

>From 89a5bbcc89c1e43ac7f2e60f3c234c2c42928c86 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 17 Apr 2024 12:24:56 +0800
Subject: [PATCH 1/2] [clang] Distinguish unresolved templates in
 UnresolvedLookupExpr

This patch revolves around the misuse of UnresolvedLookupExpr in
BuildTemplateIdExpr.

Basically, we build up an UnresolvedLookupExpr not only for function
overloads but for "unresolved" templates wherever we need an expression
for template decls. For example, a dependent VarTemplateDecl can be
wrapped with such an expression before template instantiation. (See
https://github.com/llvm/llvm-project/commit/617007240cbfb97c8ccf6d61b0c4ca0bb62d43c9)

Also, one important thing is that UnresolvedLookupExpr uses a "canonical"
QualType to describe the containing unresolved decls: a DependentTy is
for dependent expressions and an OverloadTy otherwise. Therefore, this
modeling for non-dependent templates leaves a problem in that the expression
is marked and perceived as if describing overload functions. The consumer then
expects functions for every such expression, although the fact is the reverse.
Hence, we run into crashes.

As to the patch, I added a new canonical type "UnresolvedTemplateTy" to
model these cases. Given that we have been using this model (intentionally or
accidentally) and it is pretty baked in throughout the code, I think
extending the role of UnresolvedLookupExpr is reasonable. Further, I added
some diagnostics for the direct occurrence of these expressions, which
are supposed to be ill-formed.

As a bonus, this patch also fixes some typos in the diagnostics and creates
RecoveryExprs rather than nothing in the hope of a better error-recovery
for clangd.

Fixes https://github.com/llvm/llvm-project/issues/88832
Fixes https://github.com/llvm/llvm-project/issues/63243
Fixes https://github.com/llvm/llvm-project/issues/48673
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/AST/ASTContext.h  |  3 +-
 clang/include/clang/AST/BuiltinTypes.def  |  3 +
 .../include/clang/Serialization/ASTBitCodes.h |  5 +-
 clang/lib/AST/ASTContext.cpp  |  3 +
 clang/lib/AST/NSAPI.cpp   |  1 +
 clang/lib/AST/Type.cpp|  3 +
 clang/lib/AST/TypeLoc.cpp |  1 +
 clang/lib/Sema/SemaExpr.cpp   | 19 +
 clang/lib/Sema/SemaTemplate.cpp   | 13 +++-
 clang/lib/Serialization/ASTCommon.cpp |  3 +
 clang/lib/Serialization/ASTReader.cpp |  3 +
 clang/test/SemaCXX/PR62533.cpp|  2 +-
 clang/test/SemaTemplate/template-id-expr.cpp  | 71 +++
 14 files changed, 125 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index efc32212f300cf..8c50988083faa6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -535,6 +535,7 @@ Bug Fixes to C++ Support
 - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329).
 - Fix a crash in requires expression with templated base class member 
function. Fixes (#GH84020).
 - Placement new initializes typedef array with correct size (#GH41441)
+- Fixed a misuse of ``UnresolvedLookupExpr`` for ill-formed templated 
expressions. Fixes (#GH48673), (#GH63243) and (#GH88832).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 28f8d67811f0a2..e9a22f04cfe764 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1116,7 +1116,8 @@ class ASTContext : public RefCountedBase {
   CanQualType BFloat16Ty;
   CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
   CanQualType VoidPtrTy, NullPtrTy;
-  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
+  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
+  UnknownAnyTy;
   CanQualType BuiltinFnTy;
   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
diff --git a/clang/include/clang/AST/BuiltinTypes.def 
b/clang/include/clang/AST/BuiltinTypes.def
index c04f6f6f127191..fd0cc10be8ebca 100644
--- a/clang/include/clang/AST/BuiltinTypes.def
+++ b/clang/include/clang/AST/BuiltinTypes.def
@@ -285,6 +285,9 @@ PLACEHOLDER_TYPE(Overload, OverloadTy)
 //   x->foo   # if only contains non-static members
 PLACEHOLDER_TYPE(BoundMember, BoundMemberTy)
 
+// The type of an unresolved template. Used in UnresolvedLookupExpr.
+PLACEHOLDER_TYPE(UnresolvedTemplate, UnresolvedTemplateTy)
+
 // The type of an expression which refers to a pseudo-object,
 // such as those introduced by Objective C's @property or
 // VS.NET's __property declarations.  A placeholder type.  The
diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 

[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

https://github.com/danix800 updated 
https://github.com/llvm/llvm-project/pull/89096

>From 0d6d52365a5d31045c347412c3a0fe8be7119006 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 00:33:29 +0800
Subject: [PATCH 1/4] [ASTImporter] Fix infinite recurse on return type
 declared inside body (#68775)

Lambda without trailing auto could has return type declared
inside the body too.
---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/lib/AST/ASTImporter.cpp   | 16 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 16 
 3 files changed, 24 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..7a623c6be72fd2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -545,6 +545,8 @@ Bug Fixes to AST Handling
 Miscellaneous Bug Fixes
 ^^^
 
+- Fixed an infinite recursion on return type declared inside body (#GH68775).
+
 Miscellaneous Clang Crashes Fixed
 ^
 
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 6aaa34c55ce307..3bbd6ebaf1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -695,7 +695,7 @@ namespace clang {
 // Returns true if the given function has a placeholder return type and
 // that type is declared inside the body of the function.
 // E.g. auto f() { struct X{}; return X(); }
-bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
+bool hasReturnTypeDeclaredInside(FunctionDecl *D);
   };
 
 template 
@@ -3649,19 +3649,15 @@ class IsTypeDeclaredInsideVisitor
 
 /// This function checks if the function has 'auto' return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
   QualType RetT = FromFPT->getReturnType();
-  if (isa(RetT.getTypePtr())) {
-FunctionDecl *Def = D->getDefinition();
-IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
-return Visitor.CheckType(RetT);
-  }
-
-  return false;
+  FunctionDecl *Def = D->getDefinition();
+  IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
+  return Visitor.CheckType(RetT);
 }
 
 ExplicitSpecifier
@@ -3811,7 +3807,7 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
+if (hasReturnTypeDeclaredInside(D)) {
   FromReturnTy = Importer.getFromContext().VoidTy;
   UsedDifferentProtoType = true;
 }
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index acc596fef87b76..3fac5514319c24 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -6721,6 +6721,22 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
LambdaInFunctionBody) {
   EXPECT_FALSE(FromL->isDependentLambda());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, LambdaReturnTypeDeclaredInside) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  void foo() {
+(void) []() {
+  struct X {};
+  return X();
+};
+  }
+  )",
+  Lang_CXX11, "", Lang_CXX11, "foo");
+  auto *ToLambda = FirstDeclMatcher().match(To, lambdaExpr());
+  EXPECT_TRUE(ToLambda);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
   Decl *FromTU = getTuDecl(
   R"(

>From 3f1d714a2aa4b236afe9bb1384be073fb155a2b8 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 08:56:56 +0800
Subject: [PATCH 2/4] Limit TypeVisitor checking to 'auto' and lambda
 definition only

1. Fix potential perf regression;
2. Fix comment.
---
 clang/lib/AST/ASTImporter.cpp | 16 
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3bbd6ebaf1..d98cb80c349db2 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3647,17 +3647,25 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
 bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = 

[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

https://github.com/danix800 updated 
https://github.com/llvm/llvm-project/pull/89096

>From 0d6d52365a5d31045c347412c3a0fe8be7119006 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 00:33:29 +0800
Subject: [PATCH 1/3] [ASTImporter] Fix infinite recurse on return type
 declared inside body (#68775)

Lambda without trailing auto could has return type declared
inside the body too.
---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/lib/AST/ASTImporter.cpp   | 16 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 16 
 3 files changed, 24 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..7a623c6be72fd2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -545,6 +545,8 @@ Bug Fixes to AST Handling
 Miscellaneous Bug Fixes
 ^^^
 
+- Fixed an infinite recursion on return type declared inside body (#GH68775).
+
 Miscellaneous Clang Crashes Fixed
 ^
 
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 6aaa34c55ce307..3bbd6ebaf1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -695,7 +695,7 @@ namespace clang {
 // Returns true if the given function has a placeholder return type and
 // that type is declared inside the body of the function.
 // E.g. auto f() { struct X{}; return X(); }
-bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
+bool hasReturnTypeDeclaredInside(FunctionDecl *D);
   };
 
 template 
@@ -3649,19 +3649,15 @@ class IsTypeDeclaredInsideVisitor
 
 /// This function checks if the function has 'auto' return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
   QualType RetT = FromFPT->getReturnType();
-  if (isa(RetT.getTypePtr())) {
-FunctionDecl *Def = D->getDefinition();
-IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
-return Visitor.CheckType(RetT);
-  }
-
-  return false;
+  FunctionDecl *Def = D->getDefinition();
+  IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
+  return Visitor.CheckType(RetT);
 }
 
 ExplicitSpecifier
@@ -3811,7 +3807,7 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
+if (hasReturnTypeDeclaredInside(D)) {
   FromReturnTy = Importer.getFromContext().VoidTy;
   UsedDifferentProtoType = true;
 }
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index acc596fef87b76..3fac5514319c24 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -6721,6 +6721,22 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
LambdaInFunctionBody) {
   EXPECT_FALSE(FromL->isDependentLambda());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, LambdaReturnTypeDeclaredInside) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  void foo() {
+(void) []() {
+  struct X {};
+  return X();
+};
+  }
+  )",
+  Lang_CXX11, "", Lang_CXX11, "foo");
+  auto *ToLambda = FirstDeclMatcher().match(To, lambdaExpr());
+  EXPECT_TRUE(ToLambda);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
   Decl *FromTU = getTuDecl(
   R"(

>From 3f1d714a2aa4b236afe9bb1384be073fb155a2b8 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 08:56:56 +0800
Subject: [PATCH 2/3] Limit TypeVisitor checking to 'auto' and lambda
 definition only

1. Fix potential perf regression;
2. Fix comment.
---
 clang/lib/AST/ASTImporter.cpp | 16 
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3bbd6ebaf1..d98cb80c349db2 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3647,17 +3647,25 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
 bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = 

[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-17 Thread Chris Copeland via cfe-commits

chrisnc wrote:

ping @ostannard 

https://github.com/llvm/llvm-project/pull/88287
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

danix800 wrote:

Got it! Thanks for these useful info!

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-04-17 Thread Jessica Paquette via cfe-commits


@@ -983,7 +979,7 @@ void CodeGenPGO::mapRegionCounters(const Decl *D) {
   // for most embedded applications. Setting a maximum value prevents the
   // bitmap footprint from growing too large without the user's knowledge. In
   // the future, this value could be adjusted with a command-line option.
-  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 6 : 0;
+  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 32767 : 0;

ornata wrote:

Also why 32767? Max signed 16-bit value? Is there a reason?

https://github.com/llvm/llvm-project/pull/82448
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-04-17 Thread Jessica Paquette via cfe-commits


@@ -2050,23 +2069,74 @@ struct CounterCoverageMappingBuilder
  subtractCounters(ParentCount, TrueCount));
   }
 
-  void createDecision(const BinaryOperator *E) {
+  void createOrCancelDecision(const BinaryOperator *E, unsigned Since) {
 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
 if (NumConds == 0)
   return;
 
+// Extract [ID, Conds] to construct the graph.
+llvm::SmallVector CondIDs(NumConds);
+for (const auto  : ArrayRef(SourceRegions).slice(Since)) {
+  if (SR.isMCDCBranch()) {

ornata wrote:

nit: can you use `make_filter_range` from `STLExtras`?

https://github.com/llvm/llvm-project/pull/82448
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-04-17 Thread Jessica Paquette via cfe-commits


@@ -190,18 +190,30 @@ class SourceMappingRegion {
 
   bool isBranch() const { return FalseCount.has_value(); }
 
+  bool isMCDCBranch() const {
+const auto *BranchParams = 
std::get_if();
+assert(BranchParams == nullptr || BranchParams->ID >= 0);
+return (BranchParams != nullptr);
+  }
+
+  const auto () const {
+return mcdc::getParams(MCDCParams);
+  }
+
   bool isMCDCDecision() const {
 const auto *DecisionParams =
 std::get_if();
-assert(!DecisionParams || DecisionParams->NumConditions > 0);
-return DecisionParams;
+assert(DecisionParams == nullptr || DecisionParams->NumConditions > 0);

ornata wrote:

Similar to the other comment, it would be nice if we could enforce at 
construction-time that MC/DC parameters have at least 1 condition.

https://github.com/llvm/llvm-project/pull/82448
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-04-17 Thread Jessica Paquette via cfe-commits


@@ -190,18 +190,30 @@ class SourceMappingRegion {
 
   bool isBranch() const { return FalseCount.has_value(); }
 
+  bool isMCDCBranch() const {
+const auto *BranchParams = 
std::get_if();
+assert(BranchParams == nullptr || BranchParams->ID >= 0);

ornata wrote:

I think it would be nice if this assert was not necessary. Is it possible to 
enforce that BranchParams->ID is never when we have MC/DC parameters?

https://github.com/llvm/llvm-project/pull/82448
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Matheus Izvekov via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

mizvekov wrote:

Also, this problem of the return type not being wrapped on an AutoType only 
happens on lambdas in *C++11*.

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Matheus Izvekov via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

mizvekov wrote:

No, you don't need to hunt for return statements.

You can just check on the CXXMethodDecl that it's FunctionProtoType has a 
trailing return (`hasTrailingReturn` method).
I think that should cover it for all cases.

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

https://github.com/danix800 edited 
https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

danix800 wrote:

Or does this mean to test `!FromFPT->hasTrailingReturn()`?

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin and frexp. (PR #88978)

2024-04-17 Thread Timm Baeder via cfe-commits


@@ -2922,7 +2922,7 @@ static bool handleFloatFloatBinOp(EvalInfo , const 
BinaryOperator *E,
   //   If during the evaluation of an expression, the result is not
   //   mathematically defined [...], the behavior is undefined.
   // FIXME: C++ rules require us to not conform to IEEE 754 here.
-  if (LHS.isNaN()) {
+  if (!Info.getLangOpts().CPlusPlus23 && LHS.isNaN()) {

tbaederr wrote:

Why this change? Is there a part of the standard we should quote in the comment 
above?

https://github.com/llvm/llvm-project/pull/88978
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin and frexp. (PR #88978)

2024-04-17 Thread Timm Baeder via cfe-commits


@@ -14547,6 +14547,18 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
   default:
 return false;
 
+  case Builtin::BI__builtin_frexpf:
+  case Builtin::BI__builtin_frexp: {
+LValue Pointer;
+if (!EvaluateFloat(E->getArg(0), Result, Info) ||
+!EvaluatePointer(E->getArg(1), Pointer, Info))
+  return false;
+llvm::RoundingMode RM =
+E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();

tbaederr wrote:

`getActiveRoundingMode()`?

https://github.com/llvm/llvm-project/pull/88978
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin and frexp. (PR #88978)

2024-04-17 Thread Timm Baeder via cfe-commits


@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -x c++ -triple x86_64-unknown-unknown -std=c++23 \
+// RUN: -emit-llvm -o - %s | FileCheck %s
+
+// RUN %clang_cc1 -x c++ -triple x86_64-linux-gnu -emit-llvm -o - %s \
+// RUN -std=c++23
+
+#define INFINITY ((float)(1e+300 * 1e+300))
+#define NAN  (-(float)(INFINITY * 0.0F))
+
+//constexpr double frexp ( double num, int* exp );
+//constexpr float foo ( float num, int* exp );
+
+int func()
+{
+  int i;
+
+  // fmin
+  constexpr double f1 = __builtin_fmin(15.24, 1.3);
+  constexpr double f2 = __builtin_fmin(-0.0, +0.0);
+  constexpr double f3 = __builtin_fmin(+0.0, -0.0);
+  constexpr float f4 = __builtin_fminf(NAN, NAN);
+  constexpr float f5 = __builtin_fminf(NAN, -1);
+  constexpr float f6 = __builtin_fminf(-INFINITY, 0);
+  constexpr float f7 = __builtin_fminf(INFINITY, 0);
+
+  // frexp
+  constexpr double f8 = __builtin_frexp(123.45, );
+  constexpr double f9 = __builtin_frexp(0.0, );
+  constexpr double f10 = __builtin_frexp(-0.0, );
+  constexpr double f11 = __builtin_frexpf(NAN, );
+  constexpr double f12 = __builtin_frexpf(-NAN, );
+  constexpr double f13 = __builtin_frexpf(INFINITY, );
+  constexpr double f14 = __builtin_frexpf(INFINITY, );
+
+  return 0;
+}

tbaederr wrote:

These all don't test the value of `i`, right?

https://github.com/llvm/llvm-project/pull/88978
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin and frexp. (PR #88978)

2024-04-17 Thread Timm Baeder via cfe-commits


@@ -14547,6 +14547,18 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
   default:
 return false;
 
+  case Builtin::BI__builtin_frexpf:

tbaederr wrote:

Not doing that is fine for now. 

https://github.com/llvm/llvm-project/pull/88978
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

danix800 wrote:

> Thanks, this works, but if we are going this way, why not also check the 
> lambda was defined without a return type?

Could you please give some direction on how to test **the lambda was defined 
without a return type**?

Does this mean that we need to check for possible `return` statements within 
lambda?

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] fix UB in aarch64 bfloat16 scalar conversion (PR #89062)

2024-04-17 Thread via cfe-commits

https://github.com/nihui updated https://github.com/llvm/llvm-project/pull/89062

>From 5b5e8e02205d1308987af17faa72ec54bab1892c Mon Sep 17 00:00:00 2001
From: nihui 
Date: Wed, 17 Apr 2024 20:04:00 +0800
Subject: [PATCH 1/2] fix UB in bfloat16 scalar conversion

---
 clang/include/clang/Basic/arm_neon.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/arm_neon.td 
b/clang/include/clang/Basic/arm_neon.td
index 6d655c39360d3b..6390ba3f9fe5e5 100644
--- a/clang/include/clang/Basic/arm_neon.td
+++ b/clang/include/clang/Basic/arm_neon.td
@@ -275,7 +275,7 @@ def OP_VCVT_BF16_F32_HI_A32
(call "vget_low", $p0))>;
 
 def OP_CVT_F32_BF16
-: Op<(bitcast "R", (op "<<", (bitcast "int32_t", $p0),
+: Op<(bitcast "R", (op "<<", (cast "int32_t", (bitcast "int16_t", $p0)),
  (literal "int32_t", "16")))>;
 
 
//===--===//

>From 1aff645c29e48187b643e317dbc302b91eb9f0b4 Mon Sep 17 00:00:00 2001
From: nihui 
Date: Thu, 18 Apr 2024 11:37:47 +0800
Subject: [PATCH 2/2] update test

---
 clang/test/CodeGen/arm-bf16-convert-intrinsics.c | 9 +
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/clang/test/CodeGen/arm-bf16-convert-intrinsics.c 
b/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
index f50eaf371028cd..0f2c5b2546fa35 100644
--- a/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
+++ b/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
@@ -426,11 +426,12 @@ bfloat16_t test_vcvth_bf16_f32(float32_t a) {
 // CHECK-NEXT:[[__REINT_I:%.*]] = alloca bfloat, align 2
 // CHECK-NEXT:[[__REINT1_I:%.*]] = alloca i32, align 4
 // CHECK-NEXT:store bfloat [[A:%.*]], ptr [[__REINT_I]], align 2
-// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[__REINT_I]], align 2
-// CHECK-NEXT:[[SHL_I:%.*]] = shl i32 [[TMP1]], 16
+// CHECK-NEXT:[[TMP0:%.*]] = load i16, ptr [[__REINT_I]], align 2
+// CHECK-NEXT:[[CONV_I:%.*]] = sext i16 [[TMP0]] to i32
+// CHECK-NEXT:[[SHL_I:%.*]] = shl i32 [[CONV_I]], 16
 // CHECK-NEXT:store i32 [[SHL_I]], ptr [[__REINT1_I]], align 4
-// CHECK-NEXT:[[TMP3:%.*]] = load float, ptr [[__REINT1_I]], align 4
-// CHECK-NEXT:ret float [[TMP3]]
+// CHECK-NEXT:[[TMP1:%.*]] = load float, ptr [[__REINT1_I]], align 4
+// CHECK-NEXT:ret float [[TMP1]]
 //
 float32_t test_vcvtah_f32_bf16(bfloat16_t a) {
   return vcvtah_f32_bf16(a);

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] fix UB in aarch64 bfloat16 scalar conversion (PR #89062)

2024-04-17 Thread via cfe-commits

https://github.com/nihui updated https://github.com/llvm/llvm-project/pull/89062

>From 05461899522816d2569fdab73b9eeda525524cc8 Mon Sep 17 00:00:00 2001
From: nihui 
Date: Wed, 17 Apr 2024 20:04:00 +0800
Subject: [PATCH 1/2] fix UB in bfloat16 scalar conversion

---
 clang/include/clang/Basic/arm_neon.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/arm_neon.td 
b/clang/include/clang/Basic/arm_neon.td
index 6d655c39360d3b..6390ba3f9fe5e5 100644
--- a/clang/include/clang/Basic/arm_neon.td
+++ b/clang/include/clang/Basic/arm_neon.td
@@ -275,7 +275,7 @@ def OP_VCVT_BF16_F32_HI_A32
(call "vget_low", $p0))>;
 
 def OP_CVT_F32_BF16
-: Op<(bitcast "R", (op "<<", (bitcast "int32_t", $p0),
+: Op<(bitcast "R", (op "<<", (cast "int32_t", (bitcast "int16_t", $p0)),
  (literal "int32_t", "16")))>;
 
 
//===--===//

>From aade75c3de9edeebfbb8aa5d0c939eaae13fc5a5 Mon Sep 17 00:00:00 2001
From: nihui 
Date: Thu, 18 Apr 2024 11:37:47 +0800
Subject: [PATCH 2/2] update test

---
 clang/test/CodeGen/arm-bf16-convert-intrinsics.c | 9 +
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/clang/test/CodeGen/arm-bf16-convert-intrinsics.c 
b/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
index f50eaf371028cd..0f2c5b2546fa35 100644
--- a/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
+++ b/clang/test/CodeGen/arm-bf16-convert-intrinsics.c
@@ -426,11 +426,12 @@ bfloat16_t test_vcvth_bf16_f32(float32_t a) {
 // CHECK-NEXT:[[__REINT_I:%.*]] = alloca bfloat, align 2
 // CHECK-NEXT:[[__REINT1_I:%.*]] = alloca i32, align 4
 // CHECK-NEXT:store bfloat [[A:%.*]], ptr [[__REINT_I]], align 2
-// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[__REINT_I]], align 2
-// CHECK-NEXT:[[SHL_I:%.*]] = shl i32 [[TMP1]], 16
+// CHECK-NEXT:[[TMP0:%.*]] = load i16, ptr [[__REINT_I]], align 2
+// CHECK-NEXT:[[CONV_I:%.*]] = sext i16 [[TMP0]] to i32
+// CHECK-NEXT:[[SHL_I:%.*]] = shl i32 [[CONV_I]], 16
 // CHECK-NEXT:store i32 [[SHL_I]], ptr [[__REINT1_I]], align 4
-// CHECK-NEXT:[[TMP3:%.*]] = load float, ptr [[__REINT1_I]], align 4
-// CHECK-NEXT:ret float [[TMP3]]
+// CHECK-NEXT:[[TMP1:%.*]] = load float, ptr [[__REINT1_I]], align 4
+// CHECK-NEXT:ret float [[TMP1]]
 //
 float32_t test_vcvtah_f32_bf16(bfloat16_t a) {
   return vcvtah_f32_bf16(a);

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] fix half && bfloat16 convert node expr codegen (PR #89051)

2024-04-17 Thread via cfe-commits

https://github.com/JinjinLi868 updated 
https://github.com/llvm/llvm-project/pull/89051

>From 8d0ed7653c21315c5c920114b3a2d7686e54b9ca Mon Sep 17 00:00:00 2001
From: Jinjin Li 
Date: Wed, 17 Apr 2024 16:44:50 +0800
Subject: [PATCH] [clang] Fix half && bfloat16 convert node expr codegen

Data type conversion between fp16 and bf16 will generate fptrunc
and fpextend nodes, but they are actually bitcast nodes.
---
 clang/lib/CodeGen/CGExprScalar.cpp|  11 +-
 .../test/CodeGen/X86/bfloat16-convert-half.c  | 109 ++
 2 files changed, 117 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/X86/bfloat16-convert-half.c

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1f18e0d5ba409a..da5a410f040d1b 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -1431,9 +1431,12 @@ Value *ScalarExprEmitter::EmitScalarCast(Value *Src, 
QualType SrcType,
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }
 
-  if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
+  if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy()))
+return Builder.CreateBitCast(Src, DstTy, "conv");
+  else if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
 return Builder.CreateFPTrunc(Src, DstTy, "conv");
-  return Builder.CreateFPExt(Src, DstTy, "conv");
+  else
+return Builder.CreateFPExt(Src, DstTy, "conv");
 }
 
 /// Emit a conversion from the specified type to the specified destination 
type,
@@ -1906,7 +1909,9 @@ Value 
*ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
   } else {
 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
"Unknown real conversion");
-if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
+if ((DstEltTy->is16bitFPTy() && SrcEltTy->is16bitFPTy()))
+  Res = Builder.CreateBitCast(Src, DstTy, "conv");
+else if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
   Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
 else
   Res = Builder.CreateFPExt(Src, DstTy, "conv");
diff --git a/clang/test/CodeGen/X86/bfloat16-convert-half.c 
b/clang/test/CodeGen/X86/bfloat16-convert-half.c
new file mode 100644
index 00..138793c242db16
--- /dev/null
+++ b/clang/test/CodeGen/X86/bfloat16-convert-half.c
@@ -0,0 +1,109 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 4
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -target-feature +fullbf16 
-S -emit-llvm %s -o - | FileCheck %s
+// CHECK-LABEL: define dso_local half @test_convert_from_bf16_to_fp16(
+// CHECK-SAME: bfloat noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca bfloat, align 2
+// CHECK-NEXT:store bfloat [[A]], ptr [[A_ADDR]], align 2
+// CHECK-NEXT:[[TMP0:%.*]] = load bfloat, ptr [[A_ADDR]], align 2
+// CHECK-NEXT:[[CONV:%.*]] = bitcast bfloat [[TMP0]] to half
+// CHECK-NEXT:ret half [[CONV]]
+//
+_Float16 test_convert_from_bf16_to_fp16(__bf16 a) {
+return (_Float16)a;
+}
+
+// CHECK-LABEL: define dso_local bfloat @test_convert_from_fp16_to_bf16(
+// CHECK-SAME: half noundef [[A:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca half, align 2
+// CHECK-NEXT:store half [[A]], ptr [[A_ADDR]], align 2
+// CHECK-NEXT:[[TMP0:%.*]] = load half, ptr [[A_ADDR]], align 2
+// CHECK-NEXT:[[CONV:%.*]] = bitcast half [[TMP0]] to bfloat
+// CHECK-NEXT:ret bfloat [[CONV]]
+//
+__bf16 test_convert_from_fp16_to_bf16(_Float16 a) {
+return (__bf16)a;
+}
+
+typedef _Float16 _Float162 __attribute__((ext_vector_type(2)));
+typedef _Float16 _Float164 __attribute__((ext_vector_type(4)));
+
+typedef __bf16 __bf162 __attribute__((ext_vector_type(2)));
+typedef __bf16 __bf164 __attribute__((ext_vector_type(4)));
+
+// CHECK-LABEL: define dso_local i32 @test_cast_from_fp162_to_bf162(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:[[IN_ADDR:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x half>, ptr [[IN]], align 4
+// CHECK-NEXT:store <2 x half> [[IN1]], ptr [[IN_ADDR]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load <2 x half>, ptr [[IN_ADDR]], align 4
+// CHECK-NEXT:[[CONV:%.*]] = bitcast <2 x half> [[TMP0]] to <2 x bfloat>
+// CHECK-NEXT:store <2 x bfloat> [[CONV]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[RETVAL]], align 4
+// CHECK-NEXT:ret i32 [[TMP1]]
+//
+__bf162 test_cast_from_fp162_to_bf162(_Float162 in) {
+  return __builtin_convertvector(in, __bf162);
+}
+
+// CHECK-LABEL: define dso_local double @test_cast_from_fp164_to_bf164(
+// CHECK-SAME: 

[clang] [llvm] [clang] Migrate clang-rename to OptTable parsing (PR #89167)

2024-04-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jordan Rupprecht (rupprecht)


Changes

Using OptTable to parse will allow including this tool in llvm-driver.

Because CommonOptionsParser is widely used and makes use of `cl::opt` flags, it 
needs to be refactored to handle both. The existing 
`CommonOptionsParser::create()` method should continue to work for downstream 
users. An additional overload allows a general function to be passed in, which 
can do arg parsing however it likes, as long as it returns the fields that 
CommonOptionsParser needs.

Many other simple `clang-*` tools can be similarly migrated after this.

---

Patch is 23.29 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/89167.diff


7 Files Affected:

- (modified) clang/include/clang/Tooling/CommonOptionsParser.h (+21-4) 
- (added) clang/include/clang/Tooling/CommonOptionsParser.td (+14) 
- (modified) clang/lib/Tooling/CommonOptionsParser.cpp (+75-52) 
- (modified) clang/tools/clang-rename/CMakeLists.txt (+7) 
- (modified) clang/tools/clang-rename/ClangRename.cpp (+136-46) 
- (added) clang/tools/clang-rename/Opts.td (+32) 
- (modified) utils/bazel/llvm-project-overlay/clang/BUILD.bazel (+19-2) 


``diff
diff --git a/clang/include/clang/Tooling/CommonOptionsParser.h 
b/clang/include/clang/Tooling/CommonOptionsParser.h
index 3c0480af377943..da1fd299a04836 100644
--- a/clang/include/clang/Tooling/CommonOptionsParser.h
+++ b/clang/include/clang/Tooling/CommonOptionsParser.h
@@ -86,6 +86,24 @@ class CommonOptionsParser {
  llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore,
  const char *Overview = nullptr);
 
+  struct Args {
+std::string BuildPath;
+std::vector SourcePaths;
+std::vector ArgsAfter;
+std::vector ArgsBefore;
+  };
+
+  using ArgParserCallback =
+  std::function(int , const char **argv)>;
+
+  /// A factory method that is similar to the above factory method, except
+  /// this does not force use of cl::opt argument parsing. The function passed
+  /// in is expected to handle argument parsing, and must return values needed
+  /// by CommonOptionsParser.
+  static llvm::Expected
+  create(int , const char **argv, ArgParserCallback ArgsCallback,
+ llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore);
+
   /// Returns a reference to the loaded compilations database.
   CompilationDatabase () {
 return *Compilations;
@@ -105,10 +123,9 @@ class CommonOptionsParser {
 private:
   CommonOptionsParser() = default;
 
-  llvm::Error init(int , const char **argv,
-   llvm::cl::OptionCategory ,
-   llvm::cl::NumOccurrencesFlag OccurrencesFlag,
-   const char *Overview);
+  llvm::Error
+  init(int , const char **argv, ArgParserCallback ArgsCallback,
+   llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore);
 
   std::unique_ptr Compilations;
   std::vector SourcePathList;
diff --git a/clang/include/clang/Tooling/CommonOptionsParser.td 
b/clang/include/clang/Tooling/CommonOptionsParser.td
new file mode 100644
index 00..0e79136a42bcb2
--- /dev/null
+++ b/clang/include/clang/Tooling/CommonOptionsParser.td
@@ -0,0 +1,14 @@
+include "llvm/Option/OptParser.td"
+
+multiclass Eq {
+  def NAME#_EQ : Joined<["--", "-"], name#"=">, HelpText;
+  def : Separate<["--", "-"], name>, Alias(NAME#_EQ)>;
+}
+
+defm build_path : Eq<"p", "Build path.">;
+defm extra_arg
+: Eq<"extra-arg",
+ "Additional argument to append to the compiler command line.">;
+defm extra_arg_before
+: Eq<"extra-arg-before",
+ "Additional argument to prepend to the compiler command line.">;
diff --git a/clang/lib/Tooling/CommonOptionsParser.cpp 
b/clang/lib/Tooling/CommonOptionsParser.cpp
index 59ef47cc0166ef..341a8ab46c50e7 100644
--- a/clang/lib/Tooling/CommonOptionsParser.cpp
+++ b/clang/lib/Tooling/CommonOptionsParser.cpp
@@ -57,13 +57,12 @@ void 
ArgumentsAdjustingCompilations::appendArgumentsAdjuster(
   Adjusters.push_back(std::move(Adjuster));
 }
 
-std::vector ArgumentsAdjustingCompilations::getCompileCommands(
-StringRef FilePath) const {
+std::vector
+ArgumentsAdjustingCompilations::getCompileCommands(StringRef FilePath) const {
   return adjustCommands(Compilations->getCompileCommands(FilePath));
 }
 
-std::vector
-ArgumentsAdjustingCompilations::getAllFiles() const {
+std::vector ArgumentsAdjustingCompilations::getAllFiles() const {
   return Compilations->getAllFiles();
 }
 
@@ -80,58 +79,32 @@ std::vector 
ArgumentsAdjustingCompilations::adjustCommands(
   return Commands;
 }
 
-llvm::Error CommonOptionsParser::init(
-int , const char **argv, cl::OptionCategory ,
-llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
-
-  static cl::opt BuildPath("p", cl::desc("Build path"),
-cl::Optional, cl::cat(Category),
-

[clang] [llvm] [clang] Migrate clang-rename to OptTable parsing (PR #89167)

2024-04-17 Thread Jordan Rupprecht via cfe-commits

https://github.com/rupprecht created 
https://github.com/llvm/llvm-project/pull/89167

Using OptTable to parse will allow including this tool in llvm-driver.

Because CommonOptionsParser is widely used and makes use of `cl::opt` flags, it 
needs to be refactored to handle both. The existing 
`CommonOptionsParser::create()` method should continue to work for downstream 
users. An additional overload allows a general function to be passed in, which 
can do arg parsing however it likes, as long as it returns the fields that 
CommonOptionsParser needs.

Many other simple `clang-*` tools can be similarly migrated after this.

>From cdea18b434d09f47343716adaa9af9deee895770 Mon Sep 17 00:00:00 2001
From: Jordan Rupprecht 
Date: Thu, 18 Apr 2024 02:49:01 +
Subject: [PATCH] [clang] Migrate clang-rename to OptTable parsing

Using OptTable to parse will allow including this tool in llvm-driver.

Because CommonOptionsParser is widely used and makes use of `cl::opt`
flags, it needs to be refactored to handle both. The existing
`CommonOptionsParser::create()` method should continue to work
for downstream users. An additional overload allows a general function
to be passed in, which can do arg parsing however it likes,
as long as it returns the fields that CommonOptionsParser needs.

Many other simple `clang-*` tools can be similarly migrated after this.
---
 .../clang/Tooling/CommonOptionsParser.h   |  25 ++-
 .../clang/Tooling/CommonOptionsParser.td  |  14 ++
 clang/lib/Tooling/CommonOptionsParser.cpp | 127 +++-
 clang/tools/clang-rename/CMakeLists.txt   |   7 +
 clang/tools/clang-rename/ClangRename.cpp  | 182 +-
 clang/tools/clang-rename/Opts.td  |  32 +++
 .../llvm-project-overlay/clang/BUILD.bazel|  21 +-
 7 files changed, 304 insertions(+), 104 deletions(-)
 create mode 100644 clang/include/clang/Tooling/CommonOptionsParser.td
 create mode 100644 clang/tools/clang-rename/Opts.td

diff --git a/clang/include/clang/Tooling/CommonOptionsParser.h 
b/clang/include/clang/Tooling/CommonOptionsParser.h
index 3c0480af377943..da1fd299a04836 100644
--- a/clang/include/clang/Tooling/CommonOptionsParser.h
+++ b/clang/include/clang/Tooling/CommonOptionsParser.h
@@ -86,6 +86,24 @@ class CommonOptionsParser {
  llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore,
  const char *Overview = nullptr);
 
+  struct Args {
+std::string BuildPath;
+std::vector SourcePaths;
+std::vector ArgsAfter;
+std::vector ArgsBefore;
+  };
+
+  using ArgParserCallback =
+  std::function(int , const char **argv)>;
+
+  /// A factory method that is similar to the above factory method, except
+  /// this does not force use of cl::opt argument parsing. The function passed
+  /// in is expected to handle argument parsing, and must return values needed
+  /// by CommonOptionsParser.
+  static llvm::Expected
+  create(int , const char **argv, ArgParserCallback ArgsCallback,
+ llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore);
+
   /// Returns a reference to the loaded compilations database.
   CompilationDatabase () {
 return *Compilations;
@@ -105,10 +123,9 @@ class CommonOptionsParser {
 private:
   CommonOptionsParser() = default;
 
-  llvm::Error init(int , const char **argv,
-   llvm::cl::OptionCategory ,
-   llvm::cl::NumOccurrencesFlag OccurrencesFlag,
-   const char *Overview);
+  llvm::Error
+  init(int , const char **argv, ArgParserCallback ArgsCallback,
+   llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore);
 
   std::unique_ptr Compilations;
   std::vector SourcePathList;
diff --git a/clang/include/clang/Tooling/CommonOptionsParser.td 
b/clang/include/clang/Tooling/CommonOptionsParser.td
new file mode 100644
index 00..0e79136a42bcb2
--- /dev/null
+++ b/clang/include/clang/Tooling/CommonOptionsParser.td
@@ -0,0 +1,14 @@
+include "llvm/Option/OptParser.td"
+
+multiclass Eq {
+  def NAME#_EQ : Joined<["--", "-"], name#"=">, HelpText;
+  def : Separate<["--", "-"], name>, Alias(NAME#_EQ)>;
+}
+
+defm build_path : Eq<"p", "Build path.">;
+defm extra_arg
+: Eq<"extra-arg",
+ "Additional argument to append to the compiler command line.">;
+defm extra_arg_before
+: Eq<"extra-arg-before",
+ "Additional argument to prepend to the compiler command line.">;
diff --git a/clang/lib/Tooling/CommonOptionsParser.cpp 
b/clang/lib/Tooling/CommonOptionsParser.cpp
index 59ef47cc0166ef..341a8ab46c50e7 100644
--- a/clang/lib/Tooling/CommonOptionsParser.cpp
+++ b/clang/lib/Tooling/CommonOptionsParser.cpp
@@ -57,13 +57,12 @@ void 
ArgumentsAdjustingCompilations::appendArgumentsAdjuster(
   Adjusters.push_back(std::move(Adjuster));
 }
 
-std::vector ArgumentsAdjustingCompilations::getCompileCommands(
-StringRef FilePath) const {
+std::vector
+ArgumentsAdjustingCompilations::getCompileCommands(StringRef FilePath) const {
  

[clang] f2695a1 - [C++20] [Modules] Avoid writing untouched DeclUpdates from GMF in

2024-04-17 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-04-18T11:00:28+08:00
New Revision: f2695a1c2f561da42b973187a254b6eeb7da76a9

URL: 
https://github.com/llvm/llvm-project/commit/f2695a1c2f561da42b973187a254b6eeb7da76a9
DIFF: 
https://github.com/llvm/llvm-project/commit/f2695a1c2f561da42b973187a254b6eeb7da76a9.diff

LOG: [C++20] [Modules] Avoid writing untouched DeclUpdates from GMF in
Reduced BMI

Mitigate https://github.com/llvm/llvm-project/issues/61447

The root cause of the above problem is that when we write a declaration,
we need to lookup all the redeclarations in the imported modules. Then
it will be pretty slow if there are too many redeclarations in different
modules. This patch doesn't solve the porblem.

What the patchs mitigated is, when we writing a named module, we shouldn't
write the declarations from GMF if it is unreferenced **in current
module unit**. The difference here is that, if the declaration is used
in the imported modules, we used to emit it as an update. But we
definitely want to avoid that after this patch.

For that reproducer in
https://github.com/llvm/llvm-project/issues/61447, it used to take 2.5s
to compile and now it only takes 0.49s to compile, which is a big win.

Added: 
clang/test/Modules/reduced-bmi-empty-module-purview.cppm

Modified: 
clang/include/clang/AST/ASTMutationListener.h
clang/include/clang/AST/Decl.h
clang/include/clang/Serialization/ASTWriter.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/Decl.cpp
clang/lib/Frontend/MultiplexConsumer.cpp
clang/lib/Sema/SemaModule.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTMutationListener.h 
b/clang/include/clang/AST/ASTMutationListener.h
index 8879f9f3229ff3..2c4ec2ce67f36b 100644
--- a/clang/include/clang/AST/ASTMutationListener.h
+++ b/clang/include/clang/AST/ASTMutationListener.h
@@ -27,6 +27,7 @@ namespace clang {
   class FunctionTemplateDecl;
   class Module;
   class NamedDecl;
+  class NamespaceDecl;
   class ObjCCategoryDecl;
   class ObjCContainerDecl;
   class ObjCInterfaceDecl;
@@ -35,6 +36,7 @@ namespace clang {
   class QualType;
   class RecordDecl;
   class TagDecl;
+  class TranslationUnitDecl;
   class ValueDecl;
   class VarDecl;
   class VarTemplateDecl;
@@ -147,6 +149,31 @@ class ASTMutationListener {
   virtual void AddedAttributeToRecord(const Attr *Attr,
   const RecordDecl *Record) {}
 
+  /// The parser find the named module declaration.
+  virtual void EnteringModulePurview() {}
+
+  /// An mangling number was added to a Decl
+  ///
+  /// \param D The decl that got a mangling number
+  ///
+  /// \param Number The mangling number that was added to the Decl
+  virtual void AddedManglingNumber(const Decl *D, unsigned Number) {}
+
+  /// An static local number was added to a Decl
+  ///
+  /// \param D The decl that got a static local number
+  ///
+  /// \param Number The static local number that was added to the Decl
+  virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number) {}
+
+  /// An anonymous namespace was added the translation unit decl
+  ///
+  /// \param TU The translation unit decl that got a new anonymous namespace
+  ///
+  /// \param AnonNamespace The anonymous namespace that was added
+  virtual void AddedAnonymousNamespace(const TranslationUnitDecl *TU,
+   NamespaceDecl *AnonNamespace) {}
+
   // NOTE: If new methods are added they should also be added to
   // MultiplexASTMutationListener.
 };

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 01af50ca694fdd..91449ebcceec37 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -120,7 +120,7 @@ class TranslationUnitDecl : public Decl,
   ASTContext () const { return Ctx; }
 
   NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
-  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
+  void setAnonymousNamespace(NamespaceDecl *D);
 
   static TranslationUnitDecl *Create(ASTContext );
 

diff  --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 443f7703104700..892d7363e06dd7 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -399,6 +399,11 @@ class ASTWriter : public ASTDeserializationListener,
   /// record containing modifications to them.
   DeclUpdateMap DeclUpdates;
 
+  /// DeclUpdates added during parsing the GMF. We split these from
+  /// DeclUpdates since we want to add these updates in GMF on need.
+  /// Only meaningful for reduced BMI.
+  DeclUpdateMap DeclUpdatesFromGMF;
+
   using FirstLatestDeclMap = llvm::DenseMap;
 
   /// Map of first declarations from a chained PCH that point to the
@@ -866,6 +871,11 @@ class ASTWriter : public 

[clang] [clang] fix half && bfloat16 convert node expr codegen (PR #89051)

2024-04-17 Thread via cfe-commits

JinjinLi868 wrote:

> > This appears to just assert today, but interpreting this as bitcast doesn't 
> > make sense. I would expect this to emit a pair of casts, fpext to float, 
> > and fptrunc down to half
> 
> If we don't just reject it as an invalid cast

i understand your means, it like a Hardware behavior to do fp16 convert to 
bf16(firstly, fp16 fpext to float32, second , float32 fptrunc to bfloat16).  
But In some target, it supply a HW instruction to complete the process  
(fp16->float32->bf16) . so it just supply a intrinsic (fp16 -> bf16)

https://github.com/llvm/llvm-project/pull/89051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] HeaderSearch::MarkFileModuleHeader creates extra HeaderFileInfo, breaks PCM reuse (PR #89005)

2024-04-17 Thread Ian Anderson via cfe-commits

https://github.com/ian-twilightcoder edited 
https://github.com/llvm/llvm-project/pull/89005
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] HeaderSearch::MarkFileModuleHeader creates extra HeaderFileInfo, breaks PCM reuse (PR #89005)

2024-04-17 Thread Ian Anderson via cfe-commits

https://github.com/ian-twilightcoder edited 
https://github.com/llvm/llvm-project/pull/89005
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Annotate ampamp after new/delete as BinaryOperator (PR #89033)

2024-04-17 Thread Owen Pan via cfe-commits

https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89033
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b6cc667 - [clang-format] Annotate ampamp after new/delete as BinaryOperator (#89033)

2024-04-17 Thread via cfe-commits

Author: Owen Pan
Date: 2024-04-17T19:53:24-07:00
New Revision: b6cc667190e3bee7485a225d3dadd8a57c0a22b6

URL: 
https://github.com/llvm/llvm-project/commit/b6cc667190e3bee7485a225d3dadd8a57c0a22b6
DIFF: 
https://github.com/llvm/llvm-project/commit/b6cc667190e3bee7485a225d3dadd8a57c0a22b6.diff

LOG: [clang-format] Annotate ampamp after new/delete as BinaryOperator (#89033)

Fixes #78789.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 80e5605fb5778d..a679683077ac94 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2912,6 +2912,8 @@ class AnnotatingParser {
   return TT_UnaryOperator;
 if (PrevToken->is(TT_TypeName))
   return TT_PointerOrReference;
+if (PrevToken->isOneOf(tok::kw_new, tok::kw_delete) && Tok.is(tok::ampamp))
+  return TT_BinaryOperator;
 
 const FormatToken *NextToken = Tok.getNextNonComment();
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index a71b6806476956..4f445c64ab303a 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -309,6 +309,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_OverloadedOperatorLParen);
   EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_FunctionLBrace);
   EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("if (new && num) {\n"
+"  new = 1;\n"
+"}\n"
+"if (!delete && num) {\n"
+"  delete = 1;\n"
+"}");
+  ASSERT_EQ(Tokens.size(), 26u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[16], tok::ampamp, TT_BinaryOperator);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 29ecd6d - [clang-format] Revert breaking stream operators to previous default (#89016)

2024-04-17 Thread via cfe-commits

Author: Owen Pan
Date: 2024-04-17T19:51:46-07:00
New Revision: 29ecd6d50f1400e3101f27567b535eb8af905f58

URL: 
https://github.com/llvm/llvm-project/commit/29ecd6d50f1400e3101f27567b535eb8af905f58
DIFF: 
https://github.com/llvm/llvm-project/commit/29ecd6d50f1400e3101f27567b535eb8af905f58.diff

LOG: [clang-format] Revert breaking stream operators to previous default 
(#89016)

Reverts commit d68826dfbd98, which changes the previous default behavior
of always breaking before a stream insertion operator `<<` if both
operands are string literals.

Also reverts the related commits 27f547968cce and bf05be5b87fc.

See the discussion in #88483.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp
polly/lib/Analysis/DependenceInfo.cpp
polly/lib/Analysis/ScopBuilder.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 628f70417866c3..80e5605fb5778d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5595,12 +5595,8 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  // FIXME: Breaking after newlines seems useful in general. Turn this into an
-  // option and recognize more cases like endl etc, and break independent of
-  // what comes after operator lessless.
-  if (Right.is(tok::lessless) && Right.Next &&
-  Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) &&
-  Left.TokenText.ends_with("\\n\"")) {
+  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
+  Right.Next->is(tok::string_literal)) {
 return true;
   }
   if (Right.is(TT_RequiresClause)) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 4906b3350b5b22..bc61b9c089e922 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -27339,12 +27339,6 @@ TEST_F(FormatTest, 
PPDirectivesAndCommentsInBracedInit) {
getLLVMStyleWithColumns(30));
 }
 
-TEST_F(FormatTest, StreamOutputOperator) {
-  verifyFormat("std::cout << \"foo\" << \"bar\" << baz;");
-  verifyFormat("std::cout << \"foo\\n\"\n"
-   "  << \"bar\";");
-}
-
 TEST_F(FormatTest, BreakAdjacentStringLiterals) {
   constexpr StringRef Code{
   "return \"Code\" \"\\0\\52\\26\\55\\55\\0\" \"x013\" \"\\02\\xBA\";"};
@@ -27359,6 +27353,7 @@ TEST_F(FormatTest, BreakAdjacentStringLiterals) {
   Style.BreakAdjacentStringLiterals = false;
   verifyFormat(Code, Style);
 }
+
 } // namespace
 } // namespace test
 } // namespace format

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index da02ced8c7a949..a71b6806476956 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2841,15 +2841,6 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[16], BK_BracedInit);
 }
 
-TEST_F(TokenAnnotatorTest, StreamOperator) {
-  auto Tokens = annotate("\"foo\\n\" << aux << \"foo\\n\" << \"foo\";");
-  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
-  EXPECT_FALSE(Tokens[1]->MustBreakBefore);
-  EXPECT_FALSE(Tokens[3]->MustBreakBefore);
-  // Only break between string literals if the former ends with \n.
-  EXPECT_TRUE(Tokens[5]->MustBreakBefore);
-}
-
 TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) {
   auto Tokens = annotate("auto foo() -> enum En {}");
   ASSERT_EQ(Tokens.size(), 10u) << Tokens;

diff  --git a/polly/lib/Analysis/DependenceInfo.cpp 
b/polly/lib/Analysis/DependenceInfo.cpp
index 9ee004fbac9e53..a530fa7b58fa6e 100644
--- a/polly/lib/Analysis/DependenceInfo.cpp
+++ b/polly/lib/Analysis/DependenceInfo.cpp
@@ -951,8 +951,8 @@ class DependenceInfoPrinterLegacyPass final : public 
ScopPass {
   bool runOnScop(Scop ) override {
 DependenceInfo  = getAnalysis();
 
-OS << "Printing analysis '" << P.getPassName() << "' for " << "region: '"
-   << S.getRegion().getNameStr() << "' in function '"
+OS << "Printing analysis '" << P.getPassName() << "' for "
+   << "region: '" << S.getRegion().getNameStr() << "' in function '"
<< S.getFunction().getName() << "':\n";
 P.printScop(OS, S);
 

diff  --git a/polly/lib/Analysis/ScopBuilder.cpp 
b/polly/lib/Analysis/ScopBuilder.cpp
index 214e4d360d6bbb..a34f2931527255 100644
--- a/polly/lib/Analysis/ScopBuilder.cpp
+++ b/polly/lib/Analysis/ScopBuilder.cpp
@@ -2715,9 +2715,10 @@ void ScopBuilder::addUserContext() {
 if (NameContext != NameUserContext) {
   std::string SpaceStr = stringFromIslObj(Space, "null");
   errs() << "Error: the name of dimension " << i
- << " provided in -polly-context " << "is '" << 

[clang] [polly] [clang-format] Revert breaking stream operators to previous default (PR #89016)

2024-04-17 Thread Owen Pan via cfe-commits

https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/89016
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] fix half && bfloat16 convert node expr codegen (PR #89051)

2024-04-17 Thread via cfe-commits

JinjinLi868 wrote:

> This appears to just assert today, but interpreting this as bitcast doesn't 
> make sense. I would expect this to emit a pair of casts, fpext to float, and 
> fptrunc down to half



https://github.com/llvm/llvm-project/pull/89051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-17 Thread Joshua Batista via cfe-commits


@@ -482,15 +484,18 @@ static BuiltinTypeDeclBuilder 
setupBufferType(CXXRecordDecl *Decl, Sema ,
   bool IsROV) {
   return BuiltinTypeDeclBuilder(Decl)
   .addHandleMember()
-  .addDefaultHandleConstructor(S, RC)
-  .annotateResourceClass(RC, RK, IsROV);
+  .addDefaultHandleConstructor(S, RC);
 }
 
 void HLSLExternalSemaSource::defineHLSLTypesWithForwardDeclarations() {
   CXXRecordDecl *Decl;
-  Decl = BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
- .addSimpleTemplateParams({"element_type"})
- .Record;
+  Decl =
+  BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
+  .addSimpleTemplateParams({"element_type"})
+  .annotateResourceClass(ResourceClass::UAV, ResourceKind::TypedBuffer,
+ /*IsROV=*/false)
+  .Record;
+

bob80905 wrote:

We do need to move it, since the attribute won't be available when it is time 
to diagnose otherwise. The extra parameters have been removed.

https://github.com/llvm/llvm-project/pull/87578
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] fix UB in aarch64 bfloat16 scalar conversion (PR #89062)

2024-04-17 Thread via cfe-commits

https://github.com/nihui updated https://github.com/llvm/llvm-project/pull/89062

>From 05461899522816d2569fdab73b9eeda525524cc8 Mon Sep 17 00:00:00 2001
From: nihui 
Date: Wed, 17 Apr 2024 20:04:00 +0800
Subject: [PATCH] fix UB in bfloat16 scalar conversion

---
 clang/include/clang/Basic/arm_neon.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/arm_neon.td 
b/clang/include/clang/Basic/arm_neon.td
index 6d655c39360d3b..6390ba3f9fe5e5 100644
--- a/clang/include/clang/Basic/arm_neon.td
+++ b/clang/include/clang/Basic/arm_neon.td
@@ -275,7 +275,7 @@ def OP_VCVT_BF16_F32_HI_A32
(call "vget_low", $p0))>;
 
 def OP_CVT_F32_BF16
-: Op<(bitcast "R", (op "<<", (bitcast "int32_t", $p0),
+: Op<(bitcast "R", (op "<<", (cast "int32_t", (bitcast "int16_t", $p0)),
  (literal "int32_t", "16")))>;
 
 
//===--===//

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Matheus Izvekov via cfe-commits


@@ -3647,15 +3647,19 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = dyn_cast(D))
+IsLambdaDefinition = cast(MD->getDeclContext())->isLambda();

mizvekov wrote:

Thanks, this works, but if we are going this way, why not also check the lambda 
was defined without a return type?

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> I tested this idea, might be like this:

I meant something else. This patch makes it so the delayed function type 
importation happens unconditionally.
I was aware that change would cause breakages.

What I meant is that, we have a special sugar type node that marks deduction, 
this AutoType, and we apply it everywhere else, except this lambda case you 
exposed. I was going to suggest we do the same for these lambdas. That would 
make things more consistent.



https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89076

>From 49b4cd16c7f22bf31239f9474bb68c81ed76f057 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 17 Apr 2024 22:22:18 +0800
Subject: [PATCH 1/3] [clang-tidy] bugprone-lambda-function-name ignore macro
 in captures

Fixes: #89065
---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp| 7 ---
 clang-tools-extra/docs/ReleaseNotes.rst| 4 
 .../clang-tidy/checkers/bugprone/lambda-function-name.cpp  | 1 +
 3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index 5260a8b4ecb0ba..f3dbb8d1e70286 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -56,6 +56,8 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks {
   LambdaFunctionNameCheck::SourceRangeSet* SuppressMacroExpansions;
 };
 
+AST_MATCHER(CXXMethodDecl, isInLambda) { return Node.getParent()->isLambda(); }
+
 } // namespace
 
 LambdaFunctionNameCheck::LambdaFunctionNameCheck(StringRef Name,
@@ -69,9 +71,8 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  // Match on PredefinedExprs inside a lambda.
-  Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
- this);
+  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
+  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
 }
 
 void LambdaFunctionNameCheck::registerPPCallbacks(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7095c56fe6..d5d14cef130e97 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ Changes in existing checks
   ` check to ignore code
   within unevaluated contexts, such as ``decltype``.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by ignoring
+  ``__func__`` macro in lambda captures.
+
 - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion
   ` check by
   eliminating false positives resulting from direct usage of bitwise operators
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
index 936ee87a856cd2..921deecdcc5ed7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
@@ -19,6 +19,7 @@ void Positives() {
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__FUNCTION__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
   [] { EMBED_IN_ANOTHER_MACRO1; }();
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__func__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
+  [func=__func__] { func; }();
 }
 
 #define FUNC_MACRO_WITH_FILE_AND_LINE Foo(__func__, __FILE__, __LINE__)

>From 233ebada2bfb9fea9fad848ab3ef60ad2ca39984 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Apr 2024 06:41:33 +0800
Subject: [PATCH 2/3] update matcher

---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp   | 11 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  2 +-
 .../checkers/bugprone/lambda-function-name.cpp| 11 ++-
 3 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index f3dbb8d1e70286..d78004c45b01e9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -8,7 +8,9 @@
 
 #include "LambdaFunctionNameCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
@@ -71,8 +73,13 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
-  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
+  Finder->addMatcher(
+  functionDecl(cxxMethodDecl(isInLambda()),
+   hasBody(hasDescendant(expr(
+   

[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89076

>From 49b4cd16c7f22bf31239f9474bb68c81ed76f057 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 17 Apr 2024 22:22:18 +0800
Subject: [PATCH 1/3] [clang-tidy] bugprone-lambda-function-name ignore macro
 in captures

Fixes: #89065
---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp| 7 ---
 clang-tools-extra/docs/ReleaseNotes.rst| 4 
 .../clang-tidy/checkers/bugprone/lambda-function-name.cpp  | 1 +
 3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index 5260a8b4ecb0ba..f3dbb8d1e70286 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -56,6 +56,8 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks {
   LambdaFunctionNameCheck::SourceRangeSet* SuppressMacroExpansions;
 };
 
+AST_MATCHER(CXXMethodDecl, isInLambda) { return Node.getParent()->isLambda(); }
+
 } // namespace
 
 LambdaFunctionNameCheck::LambdaFunctionNameCheck(StringRef Name,
@@ -69,9 +71,8 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  // Match on PredefinedExprs inside a lambda.
-  Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
- this);
+  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
+  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
 }
 
 void LambdaFunctionNameCheck::registerPPCallbacks(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7095c56fe6..d5d14cef130e97 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ Changes in existing checks
   ` check to ignore code
   within unevaluated contexts, such as ``decltype``.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by ignoring
+  ``__func__`` macro in lambda captures.
+
 - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion
   ` check by
   eliminating false positives resulting from direct usage of bitwise operators
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
index 936ee87a856cd2..921deecdcc5ed7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
@@ -19,6 +19,7 @@ void Positives() {
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__FUNCTION__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
   [] { EMBED_IN_ANOTHER_MACRO1; }();
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__func__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
+  [func=__func__] { func; }();
 }
 
 #define FUNC_MACRO_WITH_FILE_AND_LINE Foo(__func__, __FILE__, __LINE__)

>From 233ebada2bfb9fea9fad848ab3ef60ad2ca39984 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Apr 2024 06:41:33 +0800
Subject: [PATCH 2/3] update matcher

---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp   | 11 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  2 +-
 .../checkers/bugprone/lambda-function-name.cpp| 11 ++-
 3 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index f3dbb8d1e70286..d78004c45b01e9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -8,7 +8,9 @@
 
 #include "LambdaFunctionNameCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
@@ -71,8 +73,13 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
-  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
+  Finder->addMatcher(
+  functionDecl(cxxMethodDecl(isInLambda()),
+   hasBody(hasDescendant(expr(
+   

[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

danix800 wrote:

> I think it would be a good idea to double check this for performance 
> regressions, since this case will recurse into the function every time with 
> this patch. Though I don't know if there is a better way to test it than to 
> merge it and wait for it to be picked up by google.

For large TU it's worth considering for performance. The previous commit 
relaxed the `TypeVisitor` checking to all `FunctionDecl`. I reverted back to 
the original `auto` impl, plus an extra condition that if it's a `lambda` 
definition, see 
https://github.com/llvm/llvm-project/pull/89096/commits/3f1d714a2aa4b236afe9bb1384be073fb155a2b8

> 
> Another idea to avoid any potential regressions, is to mark the return type 
> as deduced anyway, with the distinction that 'auto' was not written.

I tested this idea, might be like this:
```
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 712958594473..988efcbef3a3 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3680,24 +3680,10 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
-  FromReturnTy = Importer.getFromContext().VoidTy;
-  UsedDifferentProtoType = true;
-}
-FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
-// FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
-// FunctionDecl that we are importing the FunctionProtoType for.
-// To avoid an infinite recursion when importing, create the FunctionDecl
-// with a simplified function type.
-if (FromEPI.ExceptionSpec.SourceDecl ||
-FromEPI.ExceptionSpec.SourceTemplate ||
-FromEPI.ExceptionSpec.NoexceptExpr) {
-  FunctionProtoType::ExtProtoInfo DefaultEPI;
-  FromEPI = DefaultEPI;
-  UsedDifferentProtoType = true;
-}
+FunctionProtoType::ExtProtoInfo DefaultEPI;
+UsedDifferentProtoType = true;
 FromTy = Importer.getFromContext().getFunctionType(
-FromReturnTy, FromFPT->getParamTypes(), FromEPI);
+Importer.getFromContext().VoidTy, FromFPT->getParamTypes(), 
DefaultEPI);
 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
 FromTy, D->getBeginLoc());
   }
```
but this will break two testcases from `check-clang-astmerge-exprs-cpp`:
```
Failed Tests (2):
  Clang :: ASTMerge/class-template/test.cpp
  Clang :: ASTMerge/exprs-cpp/test.cpp
```

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CUDA][HIP] Fix record layout on Windows (PR #87651)

2024-04-17 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu closed 
https://github.com/llvm/llvm-project/pull/87651
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 748ef7e - [CUDA][HIP] Fix record layout on Windows (#87651)

2024-04-17 Thread via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2024-04-17T21:44:12-04:00
New Revision: 748ef7eccc8b997ee5553cc5aadf04d7c7d0556f

URL: 
https://github.com/llvm/llvm-project/commit/748ef7eccc8b997ee5553cc5aadf04d7c7d0556f
DIFF: 
https://github.com/llvm/llvm-project/commit/748ef7eccc8b997ee5553cc5aadf04d7c7d0556f.diff

LOG: [CUDA][HIP] Fix record layout on Windows (#87651)

On windows, record layout should be consistent with host side, otherwise
host code is not able to access fields of the record correctly.

Fixes: https://github.com/llvm/llvm-project/issues/51031

Fixes: SWDEV-446010

Added: 
clang/test/CodeGenCUDA/record-layout.cu

Modified: 
clang/lib/AST/RecordLayoutBuilder.cpp

Removed: 




diff  --git a/clang/lib/AST/RecordLayoutBuilder.cpp 
b/clang/lib/AST/RecordLayoutBuilder.cpp
index a3b7431f7ffd6d..d9bf62c2bbb04a 100644
--- a/clang/lib/AST/RecordLayoutBuilder.cpp
+++ b/clang/lib/AST/RecordLayoutBuilder.cpp
@@ -2458,6 +2458,11 @@ static bool mustSkipTailPadding(TargetCXXABI ABI, const 
CXXRecordDecl *RD) {
 }
 
 static bool isMsLayout(const ASTContext ) {
+  // Check if it's CUDA device compilation; ensure layout consistency with 
host.
+  if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
+  Context.getAuxTargetInfo())
+return Context.getAuxTargetInfo()->getCXXABI().isMicrosoft();
+
   return Context.getTargetInfo().getCXXABI().isMicrosoft();
 }
 

diff  --git a/clang/test/CodeGenCUDA/record-layout.cu 
b/clang/test/CodeGenCUDA/record-layout.cu
new file mode 100644
index 00..dd34121ccb9d36
--- /dev/null
+++ b/clang/test/CodeGenCUDA/record-layout.cu
@@ -0,0 +1,200 @@
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fdump-record-layouts \
+// RUN:   -emit-llvm -o %t -xhip %s 2>&1 | FileCheck %s --check-prefix=AST
+// RUN: cat %t | FileCheck --check-prefixes=CHECK,HOST %s
+// RUN: %clang_cc1 -fcuda-is-device -triple amdgcn-amd-amdhsa -target-cpu 
gfx1100 \
+// RUN:   -emit-llvm -fdump-record-layouts -aux-triple x86_64-pc-windows-msvc \
+// RUN:   -o %t -xhip %s | FileCheck %s --check-prefix=AST
+// RUN: cat %t | FileCheck --check-prefixes=CHECK,DEV %s
+
+#include "Inputs/cuda.h"
+
+// AST: *** Dumping AST Record Layout
+// AST-LABEL: 0 | struct C
+// AST-NEXT:  0 |   struct A (base) (empty)
+// AST-NEXT:  1 |   struct B (base) (empty)
+// AST-NEXT:  4 |   int i
+// AST-NEXT:| [sizeof=8, align=4,
+// AST-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK: %struct.C = type { [4 x i8], i32 }
+
+struct A {};
+struct B {};
+struct C : A, B {
+int i;
+};
+
+// AST: *** Dumping AST Record Layout
+// AST-LABEL:  0 | struct I
+// AST-NEXT:   0 |   (I vftable pointer)
+// AST-NEXT:   8 |   int i
+// AST-NEXT: | [sizeof=16, align=8,
+// AST-NEXT: |  nvsize=16, nvalign=8]
+
+// AST: *** Dumping AST Record Layout
+// AST-LABEL:  0 | struct J
+// AST-NEXT:   0 |   struct I (primary base)
+// AST-NEXT:   0 | (I vftable pointer)
+// AST-NEXT:   8 | int i
+// AST-NEXT:  16 |   int j
+// AST-NEXT: | [sizeof=24, align=8,
+// AST-NEXT: |  nvsize=24, nvalign=8]
+
+// CHECK: %struct.I = type { ptr, i32 }
+// CHECK: %struct.J = type { %struct.I, i32 }
+
+// HOST: @0 = private unnamed_addr constant { [4 x ptr] } { [4 x ptr] [ptr 
@"??_R4J@@6B@", ptr @"?f@J@@UEAAXXZ", ptr null, ptr @"?h@J@@UEAAXXZ"] }, 
comdat($"??_7J@@6B@")
+// HOST: @1 = private unnamed_addr constant { [4 x ptr] } { [4 x ptr] [ptr 
@"??_R4I@@6B@", ptr @_purecall, ptr null, ptr @_purecall] }, 
comdat($"??_7I@@6B@")
+// HOST: @"??_7J@@6B@" = unnamed_addr alias ptr, getelementptr inbounds ({ [4 
x ptr] }, ptr @0, i32 0, i32 0, i32 1)
+// HOST: @"??_7I@@6B@" = unnamed_addr alias ptr, getelementptr inbounds ({ [4 
x ptr] }, ptr @1, i32 0, i32 0, i32 1)
+
+// DEV: @_ZTV1J = linkonce_odr unnamed_addr addrspace(1) constant { [5 x ptr 
addrspace(1)] } { [5 x ptr addrspace(1)] [ptr addrspace(1) null, ptr 
addrspace(1) null, ptr addrspace(1) null, ptr addrspace(1) addrspacecast (ptr 
@_ZN1J1gEv to ptr addrspace(1)), ptr addrspace(1) addrspacecast (ptr @_ZN1J1hEv 
to ptr addrspace(1))] }, comdat, align 8
+// DEV: @_ZTV1I = linkonce_odr unnamed_addr addrspace(1) constant { [5 x ptr 
addrspace(1)] } { [5 x ptr addrspace(1)] [ptr addrspace(1) null, ptr 
addrspace(1) null, ptr addrspace(1) null, ptr addrspace(1) addrspacecast (ptr 
@__cxa_pure_virtual to ptr addrspace(1)), ptr addrspace(1) addrspacecast (ptr 
@__cxa_pure_virtual to ptr addrspace(1))] }, comdat, align 8
+struct I {
+virtual void f() = 0;
+__device__ virtual void g() = 0;
+__device__ __host__ virtual void h() = 0;
+int i;
+};
+
+struct J : I {
+void f() override {}
+__device__ void g() override {}
+__device__ __host__ void h() override {}
+int j;
+};
+
+// DEV: define dso_local amdgpu_kernel 

[clang] [Clang] Handle structs with inner structs and no fields (PR #89126)

2024-04-17 Thread Eli Friedman via cfe-commits


@@ -844,7 +847,18 @@ const FieldDecl 
*CodeGenFunction::FindFlexibleArrayMemberField(
   if (const FieldDecl *Field =

efriedma-quic wrote:

Maybe instead of looking for RecordDecls, this code should be looking for 
fields where the type of the field is an anonymous struct/union.

https://github.com/llvm/llvm-project/pull/89126
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Handle structs with inner structs and no fields (PR #89126)

2024-04-17 Thread Eli Friedman via cfe-commits


@@ -844,7 +847,18 @@ const FieldDecl 
*CodeGenFunction::FindFlexibleArrayMemberField(
   if (const FieldDecl *Field =

efriedma-quic wrote:

FieldNo and Layout are referring to fields of "RD"; the "Field" found in the 
recursive visit is a member of Record (or some subobject of Record).  So the 
code is doing math on completely unrelated offsets.  Checking getFieldCount is 
just masking the issue.

https://github.com/llvm/llvm-project/pull/89126
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [InstallAPI] Add support for aliased exports (PR #88750)

2024-04-17 Thread Zixu Wang via cfe-commits

https://github.com/zixu-w approved this pull request.


https://github.com/llvm/llvm-project/pull/88750
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] fix UB in aarch64 bfloat16 scalar conversion (PR #89062)

2024-04-17 Thread via cfe-commits

https://github.com/nihui updated https://github.com/llvm/llvm-project/pull/89062

>From c9e664be047d980786aa50ac682be529971caedd Mon Sep 17 00:00:00 2001
From: nihui 
Date: Wed, 17 Apr 2024 20:04:00 +0800
Subject: [PATCH] fix UB in bfloat16 scalar conversion

---
 clang/include/clang/Basic/arm_neon.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/arm_neon.td 
b/clang/include/clang/Basic/arm_neon.td
index 6d655c39360d3b..6390ba3f9fe5e5 100644
--- a/clang/include/clang/Basic/arm_neon.td
+++ b/clang/include/clang/Basic/arm_neon.td
@@ -275,7 +275,7 @@ def OP_VCVT_BF16_F32_HI_A32
(call "vget_low", $p0))>;
 
 def OP_CVT_F32_BF16
-: Op<(bitcast "R", (op "<<", (bitcast "int32_t", $p0),
+: Op<(bitcast "R", (op "<<", (cast "int32_t", (bitcast "int16_t", $p0)),
  (literal "int32_t", "16")))>;
 
 
//===--===//

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits


@@ -3649,19 +3649,15 @@ class IsTypeDeclaredInsideVisitor
 
 /// This function checks if the function has 'auto' return type that contains
 /// a reference (in any way) to a declaration inside the same function.

danix800 wrote:

Thanks for reminding, fixed in 
https://github.com/llvm/llvm-project/pull/89096/commits/3f1d714a2aa4b236afe9bb1384be073fb155a2b8

https://github.com/llvm/llvm-project/pull/89096
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ASTImporter] Fix infinite recurse on return type declared inside body (#68775) (PR #89096)

2024-04-17 Thread Ding Fei via cfe-commits

https://github.com/danix800 updated 
https://github.com/llvm/llvm-project/pull/89096

>From 0d6d52365a5d31045c347412c3a0fe8be7119006 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 00:33:29 +0800
Subject: [PATCH 1/2] [ASTImporter] Fix infinite recurse on return type
 declared inside body (#68775)

Lambda without trailing auto could has return type declared
inside the body too.
---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/lib/AST/ASTImporter.cpp   | 16 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 16 
 3 files changed, 24 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..7a623c6be72fd2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -545,6 +545,8 @@ Bug Fixes to AST Handling
 Miscellaneous Bug Fixes
 ^^^
 
+- Fixed an infinite recursion on return type declared inside body (#GH68775).
+
 Miscellaneous Clang Crashes Fixed
 ^
 
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 6aaa34c55ce307..3bbd6ebaf1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -695,7 +695,7 @@ namespace clang {
 // Returns true if the given function has a placeholder return type and
 // that type is declared inside the body of the function.
 // E.g. auto f() { struct X{}; return X(); }
-bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
+bool hasReturnTypeDeclaredInside(FunctionDecl *D);
   };
 
 template 
@@ -3649,19 +3649,15 @@ class IsTypeDeclaredInsideVisitor
 
 /// This function checks if the function has 'auto' return type that contains
 /// a reference (in any way) to a declaration inside the same function.
-bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
+bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
   QualType RetT = FromFPT->getReturnType();
-  if (isa(RetT.getTypePtr())) {
-FunctionDecl *Def = D->getDefinition();
-IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
-return Visitor.CheckType(RetT);
-  }
-
-  return false;
+  FunctionDecl *Def = D->getDefinition();
+  IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
+  return Visitor.CheckType(RetT);
 }
 
 ExplicitSpecifier
@@ -3811,7 +3807,7 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
+if (hasReturnTypeDeclaredInside(D)) {
   FromReturnTy = Importer.getFromContext().VoidTy;
   UsedDifferentProtoType = true;
 }
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index acc596fef87b76..3fac5514319c24 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -6721,6 +6721,22 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
LambdaInFunctionBody) {
   EXPECT_FALSE(FromL->isDependentLambda());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, LambdaReturnTypeDeclaredInside) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  void foo() {
+(void) []() {
+  struct X {};
+  return X();
+};
+  }
+  )",
+  Lang_CXX11, "", Lang_CXX11, "foo");
+  auto *ToLambda = FirstDeclMatcher().match(To, lambdaExpr());
+  EXPECT_TRUE(ToLambda);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
   Decl *FromTU = getTuDecl(
   R"(

>From 3f1d714a2aa4b236afe9bb1384be073fb155a2b8 Mon Sep 17 00:00:00 2001
From: dingfei 
Date: Thu, 18 Apr 2024 08:56:56 +0800
Subject: [PATCH 2/2] Limit TypeVisitor checking to 'auto' and lambda
 definition only

1. Fix potential perf regression;
2. Fix comment.
---
 clang/lib/AST/ASTImporter.cpp | 16 
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3bbd6ebaf1..d98cb80c349db2 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3647,17 +3647,25 @@ class IsTypeDeclaredInsideVisitor
 };
 } // namespace
 
-/// This function checks if the function has 'auto' return type that contains
+/// This function checks if the given function has a return type that contains
 /// a reference (in any way) to a declaration inside the same function.
 bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
   QualType FromTy = D->getType();
   const auto *FromFPT = FromTy->getAs();
   assert(FromFPT && "Must be called on FunctionProtoType");
 
+  bool IsLambdaDefinition = false;
+  if (const auto *MD = 

[clang] [Clang][Sema] set declaration invalid earlier to prevent crash in calculating record layout (PR #87173)

2024-04-17 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky closed https://github.com/llvm/llvm-project/pull/87173
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 156ab4d - [Clang][Sema] set declaration invalid earlier to prevent crash in calculating record layout (#87173)

2024-04-17 Thread via cfe-commits

Author: Qizhi Hu
Date: 2024-04-18T08:52:25+08:00
New Revision: 156ab4d4fb06be93b0cfce675e4cf86d330d879c

URL: 
https://github.com/llvm/llvm-project/commit/156ab4d4fb06be93b0cfce675e4cf86d330d879c
DIFF: 
https://github.com/llvm/llvm-project/commit/156ab4d4fb06be93b0cfce675e4cf86d330d879c.diff

LOG: [Clang][Sema] set declaration invalid earlier to prevent crash in 
calculating record layout (#87173)

Try to fix https://github.com/llvm/llvm-project/issues/75221
This crash caused by calculating record layout which contains a field
declaration with dependent type. Make it invalid before it is a complete
definition to prevent this crash. Define a new scope type to record this
type alias and set the record declaration invalid when it is defined in
a type alias template.

Co-authored-by: huqizhi <836744...@qq.com>

Added: 
clang/test/SemaCXX/PR75221.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Scope.h
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..6c51c2d1f483ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -536,6 +536,8 @@ Bug Fixes to C++ Support
   Fixes (#GH70604), (#GH79754), (#GH84163), (#GH84425), (#GH86054), 
(#GH86398), and (#GH86399).
 - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329).
 - Fix a crash in requires expression with templated base class member 
function. Fixes (#GH84020).
+- Fix a crash caused by defined struct in a type alias template when the 
structure
+  has fields with dependent type. Fixes (#GH75221).
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/include/clang/Sema/Scope.h 
b/clang/include/clang/Sema/Scope.h
index 099c2739e8603a..1752a25111a775 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -156,6 +156,9 @@ class Scope {
 /// This is the scope of an OpenACC Compute Construct, which restricts
 /// jumping into/out of it.
 OpenACCComputeConstructScope = 0x1000,
+
+/// This is a scope of type alias declaration.
+TypeAliasScope = 0x2000,
   };
 
 private:
@@ -580,6 +583,9 @@ class Scope {
   /// if/switch/while/for statement.
   bool isControlScope() const { return getFlags() & Scope::ControlScope; }
 
+  /// Determine whether this scope is a type alias scope.
+  bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes

diff  --git a/clang/lib/Parse/ParseDeclCXX.cpp 
b/clang/lib/Parse/ParseDeclCXX.cpp
index 51fd64b2d01aa7..8e0e8682482933 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -799,6 +799,11 @@ Parser::DeclGroupPtrTy Parser::ParseUsingDeclaration(
 ProhibitAttributes(PrefixAttrs);
 
 Decl *DeclFromDeclSpec = nullptr;
+Scope *CurScope = getCurScope();
+if (CurScope)
+  CurScope->setFlags(Scope::ScopeFlags::TypeAliasScope |
+ CurScope->getFlags());
+
 Decl *AD = ParseAliasDeclarationAfterDeclarator(
 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, );
 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 1bde99d6fce740..356abe09a5ca62 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19529,6 +19529,13 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
   // Okay, we successfully defined 'Record'.
   if (Record) {
 bool Completed = false;
+if (S) {
+  Scope *Parent = S->getParent();
+  if (Parent && Parent->isTypeAliasScope() &&
+  Parent->isTemplateParamScope())
+Record->setInvalidDecl();
+}
+
 if (CXXRecord) {
   if (!CXXRecord->isInvalidDecl()) {
 // Set access bits correctly on the directly-declared conversions.

diff  --git a/clang/test/SemaCXX/PR75221.cpp b/clang/test/SemaCXX/PR75221.cpp
new file mode 100644
index 00..b342e347c5606a
--- /dev/null
+++ b/clang/test/SemaCXX/PR75221.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -verify -std=c++11 -fsyntax-only %s
+
+template  using foo = struct foo { // expected-error {{'foo' cannot 
be defined in a type alias template}}
+  T size = 0;
+};
+foo a;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] set declaration invalid earlier to prevent crash in calculating record layout (PR #87173)

2024-04-17 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/87173

>From 19b2cab0c84a934910f65536a0627045d30b9729 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Sun, 31 Mar 2024 09:38:05 +0800
Subject: [PATCH] [Clang][Sema] set declaration invalid earlier to prevent
 crash in calculating record layout

---
 clang/docs/ReleaseNotes.rst  | 2 ++
 clang/include/clang/Sema/Scope.h | 6 ++
 clang/lib/Parse/ParseDeclCXX.cpp | 5 +
 clang/lib/Sema/SemaDecl.cpp  | 7 +++
 clang/test/SemaCXX/PR75221.cpp   | 6 ++
 5 files changed, 26 insertions(+)
 create mode 100644 clang/test/SemaCXX/PR75221.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c19ad9fba58f37..6c51c2d1f483ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -536,6 +536,8 @@ Bug Fixes to C++ Support
   Fixes (#GH70604), (#GH79754), (#GH84163), (#GH84425), (#GH86054), 
(#GH86398), and (#GH86399).
 - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329).
 - Fix a crash in requires expression with templated base class member 
function. Fixes (#GH84020).
+- Fix a crash caused by defined struct in a type alias template when the 
structure
+  has fields with dependent type. Fixes (#GH75221).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 099c2739e8603a..1752a25111a775 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -156,6 +156,9 @@ class Scope {
 /// This is the scope of an OpenACC Compute Construct, which restricts
 /// jumping into/out of it.
 OpenACCComputeConstructScope = 0x1000,
+
+/// This is a scope of type alias declaration.
+TypeAliasScope = 0x2000,
   };
 
 private:
@@ -580,6 +583,9 @@ class Scope {
   /// if/switch/while/for statement.
   bool isControlScope() const { return getFlags() & Scope::ControlScope; }
 
+  /// Determine whether this scope is a type alias scope.
+  bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 51fd64b2d01aa7..8e0e8682482933 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -799,6 +799,11 @@ Parser::DeclGroupPtrTy Parser::ParseUsingDeclaration(
 ProhibitAttributes(PrefixAttrs);
 
 Decl *DeclFromDeclSpec = nullptr;
+Scope *CurScope = getCurScope();
+if (CurScope)
+  CurScope->setFlags(Scope::ScopeFlags::TypeAliasScope |
+ CurScope->getFlags());
+
 Decl *AD = ParseAliasDeclarationAfterDeclarator(
 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, );
 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 1bde99d6fce740..356abe09a5ca62 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19529,6 +19529,13 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
   // Okay, we successfully defined 'Record'.
   if (Record) {
 bool Completed = false;
+if (S) {
+  Scope *Parent = S->getParent();
+  if (Parent && Parent->isTypeAliasScope() &&
+  Parent->isTemplateParamScope())
+Record->setInvalidDecl();
+}
+
 if (CXXRecord) {
   if (!CXXRecord->isInvalidDecl()) {
 // Set access bits correctly on the directly-declared conversions.
diff --git a/clang/test/SemaCXX/PR75221.cpp b/clang/test/SemaCXX/PR75221.cpp
new file mode 100644
index 00..b342e347c5606a
--- /dev/null
+++ b/clang/test/SemaCXX/PR75221.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -verify -std=c++11 -fsyntax-only %s
+
+template  using foo = struct foo { // expected-error {{'foo' cannot 
be defined in a type alias template}}
+  T size = 0;
+};
+foo a;

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Handle structs with inner structs and no fields (PR #89126)

2024-04-17 Thread Kees Cook via cfe-commits

https://github.com/kees approved this pull request.

Tests and logic adjustment looks good to me.

https://github.com/llvm/llvm-project/pull/89126
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm] Apply modernize-use-starts-ends-with on llvm-project (PR #89140)

2024-04-17 Thread Nicolas van Kempen via cfe-commits

nicovank wrote:

`std::string::starts_with` is only available from C++20, and LLVM is limited to 
C++17 as far as I know. However, the two objects here are `StringRef` so this 
is safe.

https://github.com/llvm/llvm-project/pull/89140
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

What, if anything, about the scenario you're describing is specific to "normal" 
cleanups?

https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [InstallAPI] Add support for aliased exports (PR #88750)

2024-04-17 Thread Cyndy Ishida via cfe-commits


@@ -259,7 +259,10 @@ bool Options::processLinkerOptions(InputArgList ) {
   if (auto *Arg = Args.getLastArg(drv::OPT_umbrella))
 LinkerOpts.ParentUmbrella = Arg->getValue();
 
-  LinkerOpts.IsDylib = Args.hasArg(drv::OPT_dynamiclib);

cyndyishida wrote:

nope, looks like I was missing some test coverage, added one implicitly here 
https://github.com/llvm/llvm-project/pull/88750/files#diff-0b1bbd3584706760de8a4030db1b04120c2c7c1f640681be80114f59278988bfR22

https://github.com/llvm/llvm-project/pull/88750
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [InstallAPI] Add support for aliased exports (PR #88750)

2024-04-17 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/88750

>From b2b54ad8ccf930a19327563a64c52c9f4013103f Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Thu, 11 Apr 2024 13:13:45 -0700
Subject: [PATCH 1/4] [InstallAPI] Add support for aliased exports

Apple's ld supports alias_lists, described as
```
 -alias_list filename
 The specified filename contains a list of aliases. The symbol name 
and its alias are on one
 line, separated by whitespace.  Lines starting with # are ignored.
```
To handle this for installapi-produced TBD files, pass along the same
input and account for it in verification.
---
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |   1 +
 clang/include/clang/Driver/Options.td |   1 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  15 +-
 clang/include/clang/InstallAPI/MachO.h|   1 +
 clang/lib/InstallAPI/DylibVerifier.cpp|  24 +
 clang/test/InstallAPI/alias_list.test | 461 ++
 clang/tools/clang-installapi/Options.cpp  |  24 +-
 clang/tools/clang-installapi/Options.h|   3 +
 llvm/include/llvm/TextAPI/Utils.h |  12 +
 llvm/lib/TextAPI/Utils.cpp|  34 ++
 10 files changed, 569 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/InstallAPI/alias_list.test

diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 396bff0146a373..91a40cd589b385 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -24,6 +24,7 @@ def err_no_matching_target : Error<"no matching target found 
for target variant
 def err_unsupported_vendor : Error<"vendor '%0' is not supported: '%1'">;
 def err_unsupported_environment : Error<"environment '%0' is not supported: 
'%1'">;
 def err_unsupported_os : Error<"os '%0' is not supported: '%1'">;
+def err_cannot_read_alias_list : Error<"could not read alias list '%0': %1">;
 } // end of command line category.
 
 let CategoryName = "Verification" in {
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index e24626913add76..8c38acb72362c7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1505,6 +1505,7 @@ def end_no_unused_arguments : Flag<["--"], 
"end-no-unused-arguments">,
 def interface_stub_version_EQ : JoinedOrSeparate<["-"], 
"interface-stub-version=">,
   Visibility<[ClangOption, CC1Option]>;
 def exported__symbols__list : Separate<["-"], "exported_symbols_list">;
+def alias_list : Separate<["-"], "alias_list">, Flags<[LinkerInput]>;
 def extract_api : Flag<["-"], "extract-api">,
   Visibility<[ClangOption, CC1Option]>, Group,
   HelpText<"Extract API information">;
diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index 31de212fc423a5..f1a949d8f99394 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -78,10 +78,12 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   DylibVerifier() = default;
 
   DylibVerifier(llvm::MachO::Records &, ReexportedInterfaces &,
-DiagnosticsEngine *Diag, VerificationMode Mode, bool Zippered,
-bool Demangle, StringRef DSYMPath)
-  : Dylib(std::move(Dylib)), Reexports(std::move(Reexports)), Mode(Mode),
-Zippered(Zippered), Demangle(Demangle), DSYMPath(DSYMPath),
+AliasMap Aliases, DiagnosticsEngine *Diag,
+VerificationMode Mode, bool Zippered, bool Demangle,
+StringRef DSYMPath)
+  : Dylib(std::move(Dylib)), Reexports(std::move(Reexports)),
+Aliases(std::move(Aliases)), Mode(Mode), Zippered(Zippered),
+Demangle(Demangle), DSYMPath(DSYMPath),
 Exports(std::make_unique()), Ctx(VerifierContext{Diag}) {}
 
   Result verify(GlobalRecord *R, const FrontendAttrs *FA);
@@ -104,7 +106,7 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   void setTarget(const Target );
 
   /// Release ownership over exports.
-  std::unique_ptr getExports() { return std::move(Exports); }
+  std::unique_ptr getExports();
 
   /// Get result of verification.
   Result getState() const { return Ctx.FrontendState; }
@@ -189,6 +191,9 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   // Reexported interfaces apart of the library.
   ReexportedInterfaces Reexports;
 
+  // Symbol aliases.
+  AliasMap Aliases;
+
   // Controls what class of violations to report.
   VerificationMode Mode = VerificationMode::Invalid;
 
diff --git a/clang/include/clang/InstallAPI/MachO.h 
b/clang/include/clang/InstallAPI/MachO.h
index 854399f54ba6c8..9da91a62e23311 100644
--- a/clang/include/clang/InstallAPI/MachO.h
+++ b/clang/include/clang/InstallAPI/MachO.h
@@ -23,6 +23,7 @@
 #include "llvm/TextAPI/TextAPIWriter.h"
 #include 

[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)

2024-04-17 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/88666

>From 8d48a0bd1cf15b9cf00bc294912b674b5f94a11c Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Mon, 15 Apr 2024 00:36:06 +0800
Subject: [PATCH 1/4] [Clang] Allow the value of unroll count to be zero  in
 '#pragma GCC unroll' and '#pragma unroll'

Signed-off-by: yronglin 
---
 clang/docs/ReleaseNotes.rst |  4 
 clang/include/clang/Sema/Sema.h |  3 ++-
 clang/lib/CodeGen/CGLoopInfo.cpp|  2 ++
 clang/lib/Parse/ParsePragma.cpp |  7 ---
 clang/lib/Sema/SemaExpr.cpp | 12 +--
 clang/lib/Sema/SemaStmtAttr.cpp | 19 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp  |  3 ++-
 clang/test/CodeGenCXX/pragma-gcc-unroll.cpp | 22 +
 clang/test/Parser/pragma-unroll.cpp |  8 ++--
 9 files changed, 66 insertions(+), 14 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ade8f4e93d5a0c..5183edcf01b1cc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -423,6 +423,10 @@ Bug Fixes in This Version
 - Fixed a regression in CTAD that a friend declaration that befriends itself 
may cause
   incorrect constraint substitution. (#GH86769).
 
+- Clang now allowed the value of unroll count to be zero in ``#pragma GCC 
unroll`` and ``#pragma unroll``. 
+  The values of 0 and 1 block any unrolling of the loop. This keeps the same 
behavior with GCC.
+  Fixes (`#88624 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index c6e0332c3176b3..3b2f3a6d82675c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -5469,7 +5469,8 @@ class Sema final : public SemaBase {
   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
 
-  bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
+  bool CheckLoopHintExpr(Expr *E, SourceLocation Loc,
+ const IdentifierInfo *PragmaNameInfo);
 
   ExprResult ActOnNumericConstant(const Token , Scope *UDLScope = nullptr);
   ExprResult ActOnCharacterConstant(const Token ,
diff --git a/clang/lib/CodeGen/CGLoopInfo.cpp b/clang/lib/CodeGen/CGLoopInfo.cpp
index 0d4800b90a2f26..72d1471021ac02 100644
--- a/clang/lib/CodeGen/CGLoopInfo.cpp
+++ b/clang/lib/CodeGen/CGLoopInfo.cpp
@@ -673,6 +673,8 @@ void LoopInfoStack::push(BasicBlock *Header, 
clang::ASTContext ,
 setPipelineDisabled(true);
 break;
   case LoopHintAttr::UnrollCount:
+setUnrollState(LoopAttributes::Disable);
+break;
   case LoopHintAttr::UnrollAndJamCount:
   case LoopHintAttr::VectorizeWidth:
   case LoopHintAttr::InterleaveCount:
diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index 3979f75b6020db..8fed9e70f7a56e 100644
--- a/clang/lib/Parse/ParsePragma.cpp
+++ b/clang/lib/Parse/ParsePragma.cpp
@@ -1569,7 +1569,8 @@ bool Parser::HandlePragmaLoopHint(LoopHint ) {
   ConsumeToken(); // Consume the constant expression eof terminator.
 
   if (Arg2Error || R.isInvalid() ||
-  Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
+  Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation(),
+PragmaNameInfo))
 return false;
 
   // Argument is a constant expression with an integer type.
@@ -1593,8 +1594,8 @@ bool Parser::HandlePragmaLoopHint(LoopHint ) {
 
 ConsumeToken(); // Consume the constant expression eof terminator.
 
-if (R.isInvalid() ||
-Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
+if (R.isInvalid() || Actions.CheckLoopHintExpr(
+ R.get(), Toks[0].getLocation(), PragmaNameInfo))
   return false;
 
 // Argument is a constant expression with an integer type.
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 505d068ac42ebe..437b31716ed30c 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -3885,7 +3885,8 @@ static Expr *BuildFloatingLiteral(Sema , 
NumericLiteralParser ,
   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
 }
 
-bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
+bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc,
+ const IdentifierInfo *PragmaNameInfo) {
   assert(E && "Invalid expression");
 
   if (E->isValueDependent())
@@ -3903,7 +3904,14 @@ bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation 
Loc) {
   if (R.isInvalid())
 return true;
 
-  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
+  // GCC allows the value of unroll count to be 0.
+  // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says

[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Attributes] Support Attributes being declared as only supporting late parsing when passing an experimental feature flag (PR #88596)

2024-04-17 Thread Yeoul Na via cfe-commits


@@ -91,11 +91,24 @@ static StringRef normalizeAttrName(StringRef Name) {
 
 /// isAttributeLateParsed - Return true if the attribute has arguments that
 /// require late parsing.
-static bool isAttributeLateParsed(const IdentifierInfo ) {
+bool Parser::isAttributeLateParsed(const IdentifierInfo ) {

rapidsna wrote:

I think the function also needs some update to make it so that attributes 
marked as `LateParseAttrExperimentalExt` will fall back to the behavior 
equivalent to `LateParseAttrStandard`. Currently, it seems that the function 
will always return `false` for attributes with `LateParseAttrExperimentalExt` 
when the experimental flag is disabled.

https://github.com/llvm/llvm-project/pull/88596
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Julian Schmidt via cfe-commits


@@ -69,9 +73,13 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  // Match on PredefinedExprs inside a lambda.
-  Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
- this);
+  Finder->addMatcher(
+  functionDecl(cxxMethodDecl(isInLambda()),
+   hasBody(hasDescendant(expr(
+   predefinedExpr(hasAncestor(functionDecl().bind("fn")))
+   .bind("E",
+   functionDecl(equalsBoundNode("fn"))),
+  this);

5chmidti wrote:

If you make the outer `functionDecl` the `cxxMethodDecl`, then you can remove 
the inner `cxxMethodDecl` that encloses the lambda. Or was there a reason for 
doing it this way?
You can also drop the `expr` matcher that surrounds the `predefinedExpr`, and 
the `functionDecl` surrounding the `equalsBoundNode`.

I.e.:
```c++
cxxMethodDecl(isInLambda(),
hasBody(hasDescendant(
predefinedExpr(hasAncestor(functionDecl().bind("fn")))
.bind("E"))),
equalsBoundNode("fn"))
```

https://github.com/llvm/llvm-project/pull/89076
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Julian Schmidt via cfe-commits


@@ -151,6 +151,10 @@ Changes in existing checks
   ` check to ignore code
   within unevaluated contexts, such as ``decltype``.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by ignoring
+  ``__func__`` macro in lambda captures and nested function declaration.

5chmidti wrote:

I think the default parameter part should be included as well (+nits):
`check by ignoring the ``__func__`` macro in lambda captures, initializers of 
default parameters and nested function declarations.`

https://github.com/llvm/llvm-project/pull/89076
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Utkarsh Saxena (usx95)


Changes

Latest diff: 
https://github.com/llvm/llvm-project/pull/89154/files/f1ab4c2677394bbfc985d9680d5eecd7b2e6a882..26bb3b19c551348de5bf88bd16f90b60c28a8a2b
Consider the following:
```cpp

struct A { };

struct B { B(const A); };

struct S {
  A a;
  B b;
};

int AcceptS(S s);

void Accept2(int x, int y);

void Test() {
  Accept2(AcceptS({.a = A{}, .b = A{}}), ({ return; 0; }));
}
```
We add cleanups as follows:
1. push dtor for field `S::a`
2. push dtor for temp `A{}` (used by ` B(const A)`)
3. push dtor for field `S::b`
4. Deactivate 3 `S::b`- This pops the cleanup.
5. Deactivate 1 `S::a` - Does not pop the cleanup as *2* is top.
6. push dtor for `~S()`.
7. ...

It is important to deactivate **5** using active flags. Without the active 
flags, the `return` will fallthrough it as an active cleanup. It would run both 
`~S()` and dtor `S::a` leading to double free of `~A()`.
In this patch, we unconditionally emit active flags while deactivating normal 
cleanups. These flags are deleted later by the `AllocaTracker` if the cleanup 
is not emitted.
Fixes https://github.com/llvm/llvm-project/issues/63818
Fixes https://github.com/llvm/llvm-project/issues/88478

---

Patch is 62.57 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/89154.diff


11 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (+7-6) 
- (modified) clang/lib/CodeGen/CGCleanup.cpp (+38-38) 
- (modified) clang/lib/CodeGen/CGCleanup.h (+56-1) 
- (modified) clang/lib/CodeGen/CGDecl.cpp (+42-19) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+9-3) 
- (modified) clang/lib/CodeGen/CGExprAgg.cpp (+26-61) 
- (modified) clang/lib/CodeGen/CGExprCXX.cpp (+19-19) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+6) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+96-3) 
- (added) clang/test/CodeGenCXX/control-flow-in-stmt-expr.cpp (+478) 
- (added) clang/test/CodeGenCoroutines/coro-suspend-cleanups.cpp (+93) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 3f5463a9a70e9d..9004e96bc1a0cf 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4693,11 +4693,11 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 AggValueSlot Slot = args.isUsingInAlloca()
 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
 
-bool DestroyedInCallee = true, NeedsEHCleanup = true;
+bool DestroyedInCallee = true, NeedsCleanup = true;
 if (const auto *RD = type->getAsCXXRecordDecl())
   DestroyedInCallee = RD->hasNonTrivialDestructor();
 else
-  NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
+  NeedsCleanup = type.isDestructedType();
 
 if (DestroyedInCallee)
   Slot.setExternallyDestructed();
@@ -4706,14 +4706,15 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 RValue RV = Slot.asRValue();
 args.add(RV, type);
 
-if (DestroyedInCallee && NeedsEHCleanup) {
+if (DestroyedInCallee && NeedsCleanup) {
   // Create a no-op GEP between the placeholder and the cleanup so we can
   // RAUW it successfully.  It also serves as a marker of the first
   // instruction where the cleanup is active.
-  pushFullExprCleanup(EHCleanup, Slot.getAddress(),
-  type);
+  pushFullExprCleanup(NormalAndEHCleanup,
+  Slot.getAddress(), type);
   // This unreachable is a temporary marker which will be removed later.
-  llvm::Instruction *IsActive = Builder.CreateUnreachable();
+  llvm::Instruction *IsActive =
+  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
   args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
 }
 return;
diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index e6f8e6873004f2..469e0363b744ac 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction 
,
 /// Pops a cleanup block.  If the block includes a normal cleanup, the
 /// current insertion point is threaded through the cleanup, as are
 /// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+  bool ForDeactivation) {
   assert(!EHStack.empty() && "cleanup stack is empty!");
   assert(isa(*EHStack.begin()) && "top not a cleanup!");
   EHCleanupScope  = cast(*EHStack.begin());
   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
 
+  // If we are deactivating a normal cleanup, we need to pretend that the
+  // fallthrough is unreachable. We restore this IP before returning.
+  

[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-coroutines

Author: Utkarsh Saxena (usx95)


Changes

Latest diff: 
https://github.com/llvm/llvm-project/pull/89154/files/f1ab4c2677394bbfc985d9680d5eecd7b2e6a882..26bb3b19c551348de5bf88bd16f90b60c28a8a2b
Consider the following:
```cpp

struct A { };

struct B { B(const A); };

struct S {
  A a;
  B b;
};

int AcceptS(S s);

void Accept2(int x, int y);

void Test() {
  Accept2(AcceptS({.a = A{}, .b = A{}}), ({ return; 0; }));
}
```
We add cleanups as follows:
1. push dtor for field `S::a`
2. push dtor for temp `A{}` (used by ` B(const A)`)
3. push dtor for field `S::b`
4. Deactivate 3 `S::b`- This pops the cleanup.
5. Deactivate 1 `S::a` - Does not pop the cleanup as *2* is top.
6. push dtor for `~S()`.
7. ...

It is important to deactivate **5** using active flags. Without the active 
flags, the `return` will fallthrough it as an active cleanup. It would run both 
`~S()` and dtor `S::a` leading to double free of `~A()`.
In this patch, we unconditionally emit active flags while deactivating normal 
cleanups. These flags are deleted later by the `AllocaTracker` if the cleanup 
is not emitted.
Fixes https://github.com/llvm/llvm-project/issues/63818
Fixes https://github.com/llvm/llvm-project/issues/88478

---

Patch is 62.57 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/89154.diff


11 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (+7-6) 
- (modified) clang/lib/CodeGen/CGCleanup.cpp (+38-38) 
- (modified) clang/lib/CodeGen/CGCleanup.h (+56-1) 
- (modified) clang/lib/CodeGen/CGDecl.cpp (+42-19) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+9-3) 
- (modified) clang/lib/CodeGen/CGExprAgg.cpp (+26-61) 
- (modified) clang/lib/CodeGen/CGExprCXX.cpp (+19-19) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+6) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+96-3) 
- (added) clang/test/CodeGenCXX/control-flow-in-stmt-expr.cpp (+478) 
- (added) clang/test/CodeGenCoroutines/coro-suspend-cleanups.cpp (+93) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 3f5463a9a70e9d..9004e96bc1a0cf 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4693,11 +4693,11 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 AggValueSlot Slot = args.isUsingInAlloca()
 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
 
-bool DestroyedInCallee = true, NeedsEHCleanup = true;
+bool DestroyedInCallee = true, NeedsCleanup = true;
 if (const auto *RD = type->getAsCXXRecordDecl())
   DestroyedInCallee = RD->hasNonTrivialDestructor();
 else
-  NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
+  NeedsCleanup = type.isDestructedType();
 
 if (DestroyedInCallee)
   Slot.setExternallyDestructed();
@@ -4706,14 +4706,15 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 RValue RV = Slot.asRValue();
 args.add(RV, type);
 
-if (DestroyedInCallee && NeedsEHCleanup) {
+if (DestroyedInCallee && NeedsCleanup) {
   // Create a no-op GEP between the placeholder and the cleanup so we can
   // RAUW it successfully.  It also serves as a marker of the first
   // instruction where the cleanup is active.
-  pushFullExprCleanup(EHCleanup, Slot.getAddress(),
-  type);
+  pushFullExprCleanup(NormalAndEHCleanup,
+  Slot.getAddress(), type);
   // This unreachable is a temporary marker which will be removed later.
-  llvm::Instruction *IsActive = Builder.CreateUnreachable();
+  llvm::Instruction *IsActive =
+  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
   args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
 }
 return;
diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index e6f8e6873004f2..469e0363b744ac 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction 
,
 /// Pops a cleanup block.  If the block includes a normal cleanup, the
 /// current insertion point is threaded through the cleanup, as are
 /// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+  bool ForDeactivation) {
   assert(!EHStack.empty() && "cleanup stack is empty!");
   assert(isa(*EHStack.begin()) && "top not a cleanup!");
   EHCleanupScope  = cast(*EHStack.begin());
   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
 
+  // If we are deactivating a normal cleanup, we need to pretend that the
+  // fallthrough is unreachable. We restore this IP before returning.
+  CGBuilderTy::InsertPoint NormalDeactivateOrigIP;

[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 ready_for_review 
https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 edited https://github.com/llvm/llvm-project/pull/89154
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/89154

>From f1ab4c2677394bbfc985d9680d5eecd7b2e6a882 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 17 Apr 2024 22:47:36 +
Subject: [PATCH 1/2] Reapply "[codegen] Emit missing cleanups for stmt-expr
 and coro suspensions" and related commits (#4)

This reverts commit 9d8be2408768912dc113a342050049231e4fc8d1.
---
 clang/lib/CodeGen/CGCall.cpp  |  13 +-
 clang/lib/CodeGen/CGCleanup.cpp   |  49 ++-
 clang/lib/CodeGen/CGCleanup.h |  57 ++-
 clang/lib/CodeGen/CGDecl.cpp  |  61 ++-
 clang/lib/CodeGen/CGExpr.cpp  |  12 +-
 clang/lib/CodeGen/CGExprAgg.cpp   |  87 ++--
 clang/lib/CodeGen/CGExprCXX.cpp   |  38 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |   6 +
 clang/lib/CodeGen/CodeGenFunction.h   |  99 -
 .../CodeGenCXX/control-flow-in-stmt-expr.cpp  | 409 ++
 .../coro-suspend-cleanups.cpp |  93 
 11 files changed, 796 insertions(+), 128 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/control-flow-in-stmt-expr.cpp
 create mode 100644 clang/test/CodeGenCoroutines/coro-suspend-cleanups.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 3f5463a9a70e9d..9004e96bc1a0cf 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4693,11 +4693,11 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 AggValueSlot Slot = args.isUsingInAlloca()
 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
 
-bool DestroyedInCallee = true, NeedsEHCleanup = true;
+bool DestroyedInCallee = true, NeedsCleanup = true;
 if (const auto *RD = type->getAsCXXRecordDecl())
   DestroyedInCallee = RD->hasNonTrivialDestructor();
 else
-  NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
+  NeedsCleanup = type.isDestructedType();
 
 if (DestroyedInCallee)
   Slot.setExternallyDestructed();
@@ -4706,14 +4706,15 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 RValue RV = Slot.asRValue();
 args.add(RV, type);
 
-if (DestroyedInCallee && NeedsEHCleanup) {
+if (DestroyedInCallee && NeedsCleanup) {
   // Create a no-op GEP between the placeholder and the cleanup so we can
   // RAUW it successfully.  It also serves as a marker of the first
   // instruction where the cleanup is active.
-  pushFullExprCleanup(EHCleanup, Slot.getAddress(),
-  type);
+  pushFullExprCleanup(NormalAndEHCleanup,
+  Slot.getAddress(), type);
   // This unreachable is a temporary marker which will be removed later.
-  llvm::Instruction *IsActive = Builder.CreateUnreachable();
+  llvm::Instruction *IsActive =
+  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
   args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
 }
 return;
diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index e6f8e6873004f2..8683f19d9da28e 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction 
,
 /// Pops a cleanup block.  If the block includes a normal cleanup, the
 /// current insertion point is threaded through the cleanup, as are
 /// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+  bool ForDeactivation) {
   assert(!EHStack.empty() && "cleanup stack is empty!");
   assert(isa(*EHStack.begin()) && "top not a cleanup!");
   EHCleanupScope  = cast(*EHStack.begin());
   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
 
+  // If we are deactivating a normal cleanup, we need to pretend that the
+  // fallthrough is unreachable. We restore this IP before returning.
+  CGBuilderTy::InsertPoint NormalDeactivateOrigIP;
+  if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) 
{
+NormalDeactivateOrigIP = Builder.saveAndClearIP();
+  }
   // Remember activation information.
   bool IsActive = Scope.isActive();
   Address NormalActiveFlag =
@@ -667,7 +674,8 @@ void CodeGenFunction::PopCleanupBlock(bool 
FallthroughIsBranchThrough) {
 
   // - whether there's a fallthrough
   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
-  bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
+  bool HasFallthrough =
+  FallthroughSource != nullptr && (IsActive || HasExistingBranches);
 
   // Branch-through fall-throughs leave the insertion point set to the
   // end of the last cleanup, which points to the current scope.  The
@@ -692,7 +700,11 @@ void 

[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-17 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 created https://github.com/llvm/llvm-project/pull/89154

None

>From f1ab4c2677394bbfc985d9680d5eecd7b2e6a882 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 17 Apr 2024 22:47:36 +
Subject: [PATCH 1/2] Reapply "[codegen] Emit missing cleanups for stmt-expr
 and coro suspensions" and related commits (#4)

This reverts commit 9d8be2408768912dc113a342050049231e4fc8d1.
---
 clang/lib/CodeGen/CGCall.cpp  |  13 +-
 clang/lib/CodeGen/CGCleanup.cpp   |  49 ++-
 clang/lib/CodeGen/CGCleanup.h |  57 ++-
 clang/lib/CodeGen/CGDecl.cpp  |  61 ++-
 clang/lib/CodeGen/CGExpr.cpp  |  12 +-
 clang/lib/CodeGen/CGExprAgg.cpp   |  87 ++--
 clang/lib/CodeGen/CGExprCXX.cpp   |  38 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |   6 +
 clang/lib/CodeGen/CodeGenFunction.h   |  99 -
 .../CodeGenCXX/control-flow-in-stmt-expr.cpp  | 409 ++
 .../coro-suspend-cleanups.cpp |  93 
 11 files changed, 796 insertions(+), 128 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/control-flow-in-stmt-expr.cpp
 create mode 100644 clang/test/CodeGenCoroutines/coro-suspend-cleanups.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 3f5463a9a70e9d..9004e96bc1a0cf 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4693,11 +4693,11 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 AggValueSlot Slot = args.isUsingInAlloca()
 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
 
-bool DestroyedInCallee = true, NeedsEHCleanup = true;
+bool DestroyedInCallee = true, NeedsCleanup = true;
 if (const auto *RD = type->getAsCXXRecordDecl())
   DestroyedInCallee = RD->hasNonTrivialDestructor();
 else
-  NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
+  NeedsCleanup = type.isDestructedType();
 
 if (DestroyedInCallee)
   Slot.setExternallyDestructed();
@@ -4706,14 +4706,15 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 RValue RV = Slot.asRValue();
 args.add(RV, type);
 
-if (DestroyedInCallee && NeedsEHCleanup) {
+if (DestroyedInCallee && NeedsCleanup) {
   // Create a no-op GEP between the placeholder and the cleanup so we can
   // RAUW it successfully.  It also serves as a marker of the first
   // instruction where the cleanup is active.
-  pushFullExprCleanup(EHCleanup, Slot.getAddress(),
-  type);
+  pushFullExprCleanup(NormalAndEHCleanup,
+  Slot.getAddress(), type);
   // This unreachable is a temporary marker which will be removed later.
-  llvm::Instruction *IsActive = Builder.CreateUnreachable();
+  llvm::Instruction *IsActive =
+  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
   args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
 }
 return;
diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index e6f8e6873004f2..8683f19d9da28e 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction 
,
 /// Pops a cleanup block.  If the block includes a normal cleanup, the
 /// current insertion point is threaded through the cleanup, as are
 /// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+  bool ForDeactivation) {
   assert(!EHStack.empty() && "cleanup stack is empty!");
   assert(isa(*EHStack.begin()) && "top not a cleanup!");
   EHCleanupScope  = cast(*EHStack.begin());
   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
 
+  // If we are deactivating a normal cleanup, we need to pretend that the
+  // fallthrough is unreachable. We restore this IP before returning.
+  CGBuilderTy::InsertPoint NormalDeactivateOrigIP;
+  if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) 
{
+NormalDeactivateOrigIP = Builder.saveAndClearIP();
+  }
   // Remember activation information.
   bool IsActive = Scope.isActive();
   Address NormalActiveFlag =
@@ -667,7 +674,8 @@ void CodeGenFunction::PopCleanupBlock(bool 
FallthroughIsBranchThrough) {
 
   // - whether there's a fallthrough
   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
-  bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
+  bool HasFallthrough =
+  FallthroughSource != nullptr && (IsActive || HasExistingBranches);
 
   // Branch-through fall-throughs leave the insertion point set to the
   // end of the last cleanup, which points to the current scope.  The
@@ -692,7 +700,11 @@ void 

[clang] [llvm] [InstallAPI] Add support for aliased exports (PR #88750)

2024-04-17 Thread Zixu Wang via cfe-commits


@@ -259,7 +259,10 @@ bool Options::processLinkerOptions(InputArgList ) {
   if (auto *Arg = Args.getLastArg(drv::OPT_umbrella))
 LinkerOpts.ParentUmbrella = Arg->getValue();
 
-  LinkerOpts.IsDylib = Args.hasArg(drv::OPT_dynamiclib);

zixu-w wrote:

Is this expected to get removed?

https://github.com/llvm/llvm-project/pull/88750
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Carving out -Wformat warning about scoped enums into a subwarning (PR #88595)

2024-04-17 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/88595

>From 29d2d19c9dea9e3f818a34c97f95bd7c93b9433b Mon Sep 17 00:00:00 2001
From: Zijun 
Date: Sat, 13 Apr 2024 00:53:38 +
Subject: [PATCH 1/5] Carving out -Wformat warning about scoped enums into a
 subwarning

Make it part of -Wformat-pedantic.
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 4 ++--
 clang/test/Sema/format-strings-scanf.c   | 2 +-
 clang/test/Sema/format-strings-signedness.c  | 6 +++---
 3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 774d2b53a38252..4ba27d62208da4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9827,7 +9827,7 @@ def warn_scanf_nonzero_width : Warning<
 def warn_format_conversion_argument_type_mismatch : Warning<
   "format specifies type %0 but the argument has "
   "%select{type|underlying type}2 %1">,
-  InGroup;
+  InGroup;
 def warn_format_conversion_argument_type_mismatch_pedantic : Extension<
   warn_format_conversion_argument_type_mismatch.Summary>,
   InGroup;
@@ -9840,7 +9840,7 @@ def 
warn_format_conversion_argument_type_mismatch_confusion : Warning<
 def warn_format_argument_needs_cast : Warning<
   "%select{values of type|enum values with underlying type}2 '%0' should not "
   "be used as format arguments; add an explicit cast to %1 instead">,
-  InGroup;
+  InGroup;
 def warn_format_argument_needs_cast_pedantic : Warning<
   warn_format_argument_needs_cast.Summary>,
   InGroup, DefaultIgnore;
diff --git a/clang/test/Sema/format-strings-scanf.c 
b/clang/test/Sema/format-strings-scanf.c
index eb5b8ec36bf7a4..9bdc46bfeebc3b 100644
--- a/clang/test/Sema/format-strings-scanf.c
+++ b/clang/test/Sema/format-strings-scanf.c
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wformat-nonliteral %s
 
 // Test that -Wformat=0 works:
-// RUN: %clang_cc1 -std=c11 -fsyntax-only -Werror -Wformat=0 %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -Werror -Wformat=0 
-Wno-format-pedantic %s
 
 #include 
 typedef __SIZE_TYPE__ size_t;
diff --git a/clang/test/Sema/format-strings-signedness.c 
b/clang/test/Sema/format-strings-signedness.c
index d5a8140d9ef8a0..ccd4d72c2d2635 100644
--- a/clang/test/Sema/format-strings-signedness.c
+++ b/clang/test/Sema/format-strings-signedness.c
@@ -12,8 +12,8 @@
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only -Wformat 
-verify=okay %s
 
 // Verify that -Wformat-signedness with -Wno-format are not reported (gcc 
compat).
-// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify=okay %s
-// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify=okay %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify %s
 // okay-no-diagnostics
 
 int printf(const char *restrict format, ...);
@@ -218,5 +218,5 @@ void test_printf_unsigned_priX16(uint16_t x) {
 void test_suppress(int x)
 {
 #pragma GCC diagnostic ignored "-Wformat"
-printf("%u", x);
+printf("%u", x); // expected-warning{{format specifies type 'unsigned int' 
but the argument has type 'int'}}
 }

>From 46e8d902d92b71e9bad2321321eed3de489e837f Mon Sep 17 00:00:00 2001
From: Zijun 
Date: Sat, 13 Apr 2024 00:53:38 +
Subject: [PATCH 2/5] Carving out -Wformat warning about scoped enums into a
 subwarning

Make it part of -Wformat-pedantic.

Fixes #81647
---
 clang/test/Sema/format-strings-signedness.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/test/Sema/format-strings-signedness.c 
b/clang/test/Sema/format-strings-signedness.c
index ccd4d72c2d2635..a06884cb9fe090 100644
--- a/clang/test/Sema/format-strings-signedness.c
+++ b/clang/test/Sema/format-strings-signedness.c
@@ -11,7 +11,7 @@
 // (gcc compat).
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only -Wformat 
-verify=okay %s
 
-// Verify that -Wformat-signedness with -Wno-format are not reported (gcc 
compat).
+// Verify that -Wformat-signedness with -Wno-format are still reported (gcc 
compat).
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify %s
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify %s
 // okay-no-diagnostics
@@ -213,7 +213,7 @@ void test_printf_unsigned_priX16(uint16_t x) {
   printf("PRIX16: %" "X" /*PRIX16*/ "\n", x); // no-warning
 }
 
-// Verify that we can suppress a -Wformat-signedness warning by ignoring
+// Verify that we can not suppress a -Wformat-signedness warning by ignoring
 // -Wformat (gcc compat).
 void 

[clang] Carving out -Wformat warning about scoped enums into a subwarning (PR #88595)

2024-04-17 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/88595

>From 29d2d19c9dea9e3f818a34c97f95bd7c93b9433b Mon Sep 17 00:00:00 2001
From: Zijun 
Date: Sat, 13 Apr 2024 00:53:38 +
Subject: [PATCH 1/4] Carving out -Wformat warning about scoped enums into a
 subwarning

Make it part of -Wformat-pedantic.
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 4 ++--
 clang/test/Sema/format-strings-scanf.c   | 2 +-
 clang/test/Sema/format-strings-signedness.c  | 6 +++---
 3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 774d2b53a38252..4ba27d62208da4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9827,7 +9827,7 @@ def warn_scanf_nonzero_width : Warning<
 def warn_format_conversion_argument_type_mismatch : Warning<
   "format specifies type %0 but the argument has "
   "%select{type|underlying type}2 %1">,
-  InGroup;
+  InGroup;
 def warn_format_conversion_argument_type_mismatch_pedantic : Extension<
   warn_format_conversion_argument_type_mismatch.Summary>,
   InGroup;
@@ -9840,7 +9840,7 @@ def 
warn_format_conversion_argument_type_mismatch_confusion : Warning<
 def warn_format_argument_needs_cast : Warning<
   "%select{values of type|enum values with underlying type}2 '%0' should not "
   "be used as format arguments; add an explicit cast to %1 instead">,
-  InGroup;
+  InGroup;
 def warn_format_argument_needs_cast_pedantic : Warning<
   warn_format_argument_needs_cast.Summary>,
   InGroup, DefaultIgnore;
diff --git a/clang/test/Sema/format-strings-scanf.c 
b/clang/test/Sema/format-strings-scanf.c
index eb5b8ec36bf7a4..9bdc46bfeebc3b 100644
--- a/clang/test/Sema/format-strings-scanf.c
+++ b/clang/test/Sema/format-strings-scanf.c
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wformat-nonliteral %s
 
 // Test that -Wformat=0 works:
-// RUN: %clang_cc1 -std=c11 -fsyntax-only -Werror -Wformat=0 %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -Werror -Wformat=0 
-Wno-format-pedantic %s
 
 #include 
 typedef __SIZE_TYPE__ size_t;
diff --git a/clang/test/Sema/format-strings-signedness.c 
b/clang/test/Sema/format-strings-signedness.c
index d5a8140d9ef8a0..ccd4d72c2d2635 100644
--- a/clang/test/Sema/format-strings-signedness.c
+++ b/clang/test/Sema/format-strings-signedness.c
@@ -12,8 +12,8 @@
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only -Wformat 
-verify=okay %s
 
 // Verify that -Wformat-signedness with -Wno-format are not reported (gcc 
compat).
-// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify=okay %s
-// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify=okay %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify %s
 // okay-no-diagnostics
 
 int printf(const char *restrict format, ...);
@@ -218,5 +218,5 @@ void test_printf_unsigned_priX16(uint16_t x) {
 void test_suppress(int x)
 {
 #pragma GCC diagnostic ignored "-Wformat"
-printf("%u", x);
+printf("%u", x); // expected-warning{{format specifies type 'unsigned int' 
but the argument has type 'int'}}
 }

>From 46e8d902d92b71e9bad2321321eed3de489e837f Mon Sep 17 00:00:00 2001
From: Zijun 
Date: Sat, 13 Apr 2024 00:53:38 +
Subject: [PATCH 2/4] Carving out -Wformat warning about scoped enums into a
 subwarning

Make it part of -Wformat-pedantic.

Fixes #81647
---
 clang/test/Sema/format-strings-signedness.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/test/Sema/format-strings-signedness.c 
b/clang/test/Sema/format-strings-signedness.c
index ccd4d72c2d2635..a06884cb9fe090 100644
--- a/clang/test/Sema/format-strings-signedness.c
+++ b/clang/test/Sema/format-strings-signedness.c
@@ -11,7 +11,7 @@
 // (gcc compat).
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only -Wformat 
-verify=okay %s
 
-// Verify that -Wformat-signedness with -Wno-format are not reported (gcc 
compat).
+// Verify that -Wformat-signedness with -Wno-format are still reported (gcc 
compat).
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wformat-signedness -Wno-format -verify %s
 // RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -std=c11 -fsyntax-only 
-Wno-format -Wformat-signedness -verify %s
 // okay-no-diagnostics
@@ -213,7 +213,7 @@ void test_printf_unsigned_priX16(uint16_t x) {
   printf("PRIX16: %" "X" /*PRIX16*/ "\n", x); // no-warning
 }
 
-// Verify that we can suppress a -Wformat-signedness warning by ignoring
+// Verify that we can not suppress a -Wformat-signedness warning by ignoring
 // -Wformat (gcc compat).
 void 

[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89076

>From 49b4cd16c7f22bf31239f9474bb68c81ed76f057 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 17 Apr 2024 22:22:18 +0800
Subject: [PATCH 1/2] [clang-tidy] bugprone-lambda-function-name ignore macro
 in captures

Fixes: #89065
---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp| 7 ---
 clang-tools-extra/docs/ReleaseNotes.rst| 4 
 .../clang-tidy/checkers/bugprone/lambda-function-name.cpp  | 1 +
 3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index 5260a8b4ecb0ba..f3dbb8d1e70286 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -56,6 +56,8 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks {
   LambdaFunctionNameCheck::SourceRangeSet* SuppressMacroExpansions;
 };
 
+AST_MATCHER(CXXMethodDecl, isInLambda) { return Node.getParent()->isLambda(); }
+
 } // namespace
 
 LambdaFunctionNameCheck::LambdaFunctionNameCheck(StringRef Name,
@@ -69,9 +71,8 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  // Match on PredefinedExprs inside a lambda.
-  Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
- this);
+  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
+  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
 }
 
 void LambdaFunctionNameCheck::registerPPCallbacks(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7095c56fe6..d5d14cef130e97 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ Changes in existing checks
   ` check to ignore code
   within unevaluated contexts, such as ``decltype``.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by ignoring
+  ``__func__`` macro in lambda captures.
+
 - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion
   ` check by
   eliminating false positives resulting from direct usage of bitwise operators
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
index 936ee87a856cd2..921deecdcc5ed7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
@@ -19,6 +19,7 @@ void Positives() {
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__FUNCTION__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
   [] { EMBED_IN_ANOTHER_MACRO1; }();
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__func__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
+  [func=__func__] { func; }();
 }
 
 #define FUNC_MACRO_WITH_FILE_AND_LINE Foo(__func__, __FILE__, __LINE__)

>From 233ebada2bfb9fea9fad848ab3ef60ad2ca39984 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Apr 2024 06:41:33 +0800
Subject: [PATCH 2/2] update matcher

---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp   | 11 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  2 +-
 .../checkers/bugprone/lambda-function-name.cpp| 11 ++-
 3 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index f3dbb8d1e70286..d78004c45b01e9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -8,7 +8,9 @@
 
 #include "LambdaFunctionNameCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
@@ -71,8 +73,13 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
-  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
+  Finder->addMatcher(
+  functionDecl(cxxMethodDecl(isInLambda()),
+   hasBody(hasDescendant(expr(
+   

[clang-tools-extra] [clang-tidy] bugprone-lambda-function-name ignore macro in captures (PR #89076)

2024-04-17 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89076

>From 49b4cd16c7f22bf31239f9474bb68c81ed76f057 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 17 Apr 2024 22:22:18 +0800
Subject: [PATCH 1/2] [clang-tidy] bugprone-lambda-function-name ignore macro
 in captures

Fixes: #89065
---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp| 7 ---
 clang-tools-extra/docs/ReleaseNotes.rst| 4 
 .../clang-tidy/checkers/bugprone/lambda-function-name.cpp  | 1 +
 3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index 5260a8b4ecb0ba..f3dbb8d1e70286 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -56,6 +56,8 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks {
   LambdaFunctionNameCheck::SourceRangeSet* SuppressMacroExpansions;
 };
 
+AST_MATCHER(CXXMethodDecl, isInLambda) { return Node.getParent()->isLambda(); }
+
 } // namespace
 
 LambdaFunctionNameCheck::LambdaFunctionNameCheck(StringRef Name,
@@ -69,9 +71,8 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  // Match on PredefinedExprs inside a lambda.
-  Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
- this);
+  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
+  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
 }
 
 void LambdaFunctionNameCheck::registerPPCallbacks(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7095c56fe6..d5d14cef130e97 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ Changes in existing checks
   ` check to ignore code
   within unevaluated contexts, such as ``decltype``.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by ignoring
+  ``__func__`` macro in lambda captures.
+
 - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion
   ` check by
   eliminating false positives resulting from direct usage of bitwise operators
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
index 936ee87a856cd2..921deecdcc5ed7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
@@ -19,6 +19,7 @@ void Positives() {
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__FUNCTION__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
   [] { EMBED_IN_ANOTHER_MACRO1; }();
   // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, 
'__func__' expands to the name of the function call operator; consider 
capturing the name of the enclosing function explicitly 
[bugprone-lambda-function-name]
+  [func=__func__] { func; }();
 }
 
 #define FUNC_MACRO_WITH_FILE_AND_LINE Foo(__func__, __FILE__, __LINE__)

>From 855110a8a1ce76a6a817cbe29be173164f48093e Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Apr 2024 06:41:33 +0800
Subject: [PATCH 2/2] update matcher

---
 .../clang-tidy/bugprone/LambdaFunctionNameCheck.cpp | 13 +++--
 clang-tools-extra/docs/ReleaseNotes.rst |  2 +-
 .../checkers/bugprone/lambda-function-name.cpp  | 11 ++-
 3 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index f3dbb8d1e70286..5393db1b0b3ae9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -8,7 +8,9 @@
 
 #include "LambdaFunctionNameCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
@@ -71,8 +73,13 @@ void 
LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
-  auto IsInsideALambda = hasAncestor(cxxMethodDecl(isInLambda()));
-  Finder->addMatcher(predefinedExpr(IsInsideALambda).bind("E"), this);
+  Finder->addMatcher(
+  functionDecl(cxxMethodDecl(isInLambda()),
+   hasBody(hasDescendant(expr(
+   

[clang] [llvm] [InstallAPI] Add support for aliased exports (PR #88750)

2024-04-17 Thread Cyndy Ishida via cfe-commits

cyndyishida wrote:

ping, is there anything else needed to land this patch? 

https://github.com/llvm/llvm-project/pull/88750
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] HeaderSearch::MarkFileModuleHeader creates extra HeaderFileInfo, breaks PCM reuse (PR #89005)

2024-04-17 Thread Ian Anderson via cfe-commits


@@ -1313,6 +1313,14 @@ OptionalFileEntryRef 
HeaderSearch::LookupSubframeworkHeader(
 // File Info Management.
 
//===--===//
 
+static bool
+headerFileInfoModuleBitsMatchRole(const HeaderFileInfo *HFI,
+  ModuleMap::ModuleHeaderRole Role) {
+  return (HFI->isModuleHeader == ModuleMap::isModular(Role)) &&
+ (HFI->isTextualModuleHeader ==
+  ((Role & ModuleMap::TextualHeader) != 0));

ian-twilightcoder wrote:

I don't think I quite understand. I think the test looked something like this.
```
module A [no_undeclared_includes] {
  module one { header "one.h" }
  module two { header "two" }
}
module B {
  module one { textual header "one.h" }
  module three { header "three.h" }
}
```
That allows one.h to include three.h even though A doesn't have a `use B`. But 
wouldn't the better setup be to have the `use B`? I might not be quite 
understanding what you're saying.

https://github.com/llvm/llvm-project/pull/89005
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Attributes] Support Attributes being declared as only supporting late parsing when passing an experimental feature flag (PR #88596)

2024-04-17 Thread Yeoul Na via cfe-commits


@@ -592,6 +592,46 @@ class AttrSubjectMatcherAggregateRule 
{
 
 def SubjectMatcherForNamed : AttrSubjectMatcherAggregateRule;
 
+// Late Attribute parsing mode enum
+class LateAttrParseKind  {
+  int Kind = val;
+}
+
+// Never late parsed
+def LateAttrParseNever : LateAttrParseKind<0>;
+
+// Standard late attribute parsing
+//
+// This is language dependent. For example:
+//
+// * For C++ enables late parsing of a declaration attributes
+// * For C does not enable late parsing of attributes
+//
+def LateAttrParseStandard: LateAttrParseKind<1>;
+
+// Experimental extension to standard late attribute parsing
+//
+// This extension behaves like `LateAttrParseStandard` but allows
+// late parsing attributes in more contexts.
+//
+// This extension changes behavior depending on whether the
+// `-fexperimental-late-parse-attributes`
+// (`LangOpts.ExperimentalLateParseAttributes`) flag is enabled.
+//
+// * If the flag is disabled then the attribute is parsed just like
+//   `LateAttrParseStandard`.
+//
+// * If the flag is enabled and if the attribute is being used in a context
+//   supported by this extension it will be late parsed. Otherwise the 
attribute
+//   will be parsed just like `LateAttrParseStandard`.
+//
+// Currently this extension extends `LateAttrParseStandard` by allowing:
+//
+// * For C, late parsing of the `counted_by` as a type or decl attribute.
+//   (TODO: Not implemented yet).

rapidsna wrote:

I don't have a strong opinion here. Having TODO in the comment seems okay to me.

https://github.com/llvm/llvm-project/pull/88596
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [llvm][support] Implement tracing virtual file system (PR #88326)

2024-04-17 Thread Michael Spencer via cfe-commits


@@ -1125,6 +1125,54 @@ class YAMLVFSWriter {
   void write(llvm::raw_ostream );
 };
 
+/// File system that tracks the number of calls to the underlying file system.
+/// This is particularly useful when wrapped around \c RealFileSystem to add
+/// lightweight tracking of expensive syscalls.
+class TracingFileSystem
+: public llvm::RTTIExtends {
+public:
+  static const char ID;
+
+  std::size_t NumStatusCalls = 0;

Bigcheese wrote:

Looking at the existing VFSs there appears to be a reasonable subset that 
currently are thread safe for stat/open/etc., but some definitely aren't. I 
think it's fine to make this one thread safe and document that it is if the 
underlying FS is.

I think they can also all be relaxed memory order, you have to have some other 
synchronization before collecting the numbers at the end anyway.

https://github.com/llvm/llvm-project/pull/88326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [llvm][support] Implement tracing virtual file system (PR #88326)

2024-04-17 Thread Michael Spencer via cfe-commits


@@ -2933,8 +2933,21 @@ recursive_directory_iterator::increment(std::error_code 
) {
   return *this;
 }
 
+void TracingFileSystem::printImpl(raw_ostream , PrintType Type,

Bigcheese wrote:

Should this print the current stat values?

https://github.com/llvm/llvm-project/pull/88326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [llvm][support] Implement tracing virtual file system (PR #88326)

2024-04-17 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese approved this pull request.

lgtm with some comments.

https://github.com/llvm/llvm-project/pull/88326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [llvm][support] Implement tracing virtual file system (PR #88326)

2024-04-17 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese edited 
https://github.com/llvm/llvm-project/pull/88326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Attributes] Support Attributes being declared as only supporting late parsing when passing an experimental feature flag (PR #88596)

2024-04-17 Thread Yeoul Na via cfe-commits


@@ -592,6 +592,46 @@ class AttrSubjectMatcherAggregateRule 
{
 
 def SubjectMatcherForNamed : AttrSubjectMatcherAggregateRule;
 
+// Late Attribute parsing mode enum

rapidsna wrote:

@delcypher Thanks! LGTM.

https://github.com/llvm/llvm-project/pull/88596
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC] Implement 'num_workers' clause for compute constructs (PR #89151)

2024-04-17 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 693a458287d019c5c6a66fe3019d099df2978cdb 
d3894971090921b92c71ba5a18151cb2033c8cfa -- 
clang/test/SemaOpenACC/compute-construct-intexpr-clause-ast.cpp 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.c 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.cpp 
clang/include/clang/AST/OpenACCClause.h clang/include/clang/Parse/Parser.h 
clang/include/clang/Sema/SemaOpenACC.h clang/lib/AST/OpenACCClause.cpp 
clang/lib/AST/StmtProfile.cpp clang/lib/AST/TextNodeDumper.cpp 
clang/lib/Parse/ParseOpenACC.cpp clang/lib/Sema/SemaOpenACC.cpp 
clang/lib/Sema/TreeTransform.h clang/lib/Serialization/ASTReader.cpp 
clang/lib/Serialization/ASTWriter.cpp clang/test/ParserOpenACC/parse-clauses.c 
clang/tools/libclang/CIndex.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/AST/OpenACCClause.h 
b/clang/include/clang/AST/OpenACCClause.h
index 7a60620d58..aeb359ab7e 100644
--- a/clang/include/clang/AST/OpenACCClause.h
+++ b/clang/include/clang/AST/OpenACCClause.h
@@ -162,18 +162,18 @@ public:
 class OpenACCClauseWithIntExprs : public OpenACCClauseWithParams {
   llvm::SmallVector IntExprs;
 
-  protected:
-OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc,
-  SourceLocation LParenLoc,
-  ArrayRef IntExprs, SourceLocation EndLoc)
-: OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc),
-  IntExprs(IntExprs) {}
-
-/// Gets the entire list of integer expressions, but leave it to the
-/// individual clauses to expose this how they'd like.
-llvm::ArrayRef getIntExprs() const { return IntExprs; }
-
-  public:
+protected:
+  OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc,
+SourceLocation LParenLoc, ArrayRef 
IntExprs,
+SourceLocation EndLoc)
+  : OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc),
+IntExprs(IntExprs) {}
+
+  /// Gets the entire list of integer expressions, but leave it to the
+  /// individual clauses to expose this how they'd like.
+  llvm::ArrayRef getIntExprs() const { return IntExprs; }
+
+public:
   child_range children() {
 return child_range(reinterpret_cast(IntExprs.begin()),
reinterpret_cast(IntExprs.end()));
@@ -189,27 +189,29 @@ class OpenACCClauseWithIntExprs : public 
OpenACCClauseWithParams {
 /// A more restrictive version of the IntExprs version that exposes a single
 /// integer expression.
 class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithIntExprs {
-  protected:
-OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation 
BeginLoc,
-   SourceLocation LParenLoc, Expr *IntExpr,
-   SourceLocation EndLoc)
-: OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, IntExpr, EndLoc) {}
-
-  public:
-bool hasIntExpr() const { return !getIntExprs().empty(); }
-const Expr *getIntExpr() const {
-  return hasIntExpr() ? getIntExprs()[0] : nullptr;
-}
-Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }
+protected:
+  OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation BeginLoc,
+ SourceLocation LParenLoc, Expr *IntExpr,
+ SourceLocation EndLoc)
+  : OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, IntExpr, EndLoc) {}
+
+public:
+  bool hasIntExpr() const { return !getIntExprs().empty(); }
+  const Expr *getIntExpr() const {
+return hasIntExpr() ? getIntExprs()[0] : nullptr;
+  }
+  Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }
 };
 
 class OpenACCNumWorkersClause : public OpenACCClauseWithSingleIntExpr {
   OpenACCNumWorkersClause(SourceLocation BeginLoc, SourceLocation LParenLoc,
   Expr *IntExpr, SourceLocation EndLoc);
-  public:
-static OpenACCNumWorkersClause *
-Create(const ASTContext , SourceLocation BeginLoc,
-   SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc);
+
+public:
+  static OpenACCNumWorkersClause *Create(const ASTContext ,
+ SourceLocation BeginLoc,
+ SourceLocation LParenLoc,
+ Expr *IntExpr, SourceLocation EndLoc);
 };
 
 template  class OpenACCClauseVisitor {
diff --git a/clang/include/clang/Sema/SemaOpenACC.h 
b/clang/include/clang/Sema/SemaOpenACC.h
index eb461fa7db..b995edebe8 100644
--- a/clang/include/clang/Sema/SemaOpenACC.h
+++ b/clang/include/clang/Sema/SemaOpenACC.h
@@ -105,7 +105,7 @@ public:
 }
 
 ArrayRef getIntExprs() const {
-  

[clang] [OpenACC] Implement 'num_workers' clause for compute constructs (PR #89151)

2024-04-17 Thread Erich Keane via cfe-commits

https://github.com/erichkeane updated 
https://github.com/llvm/llvm-project/pull/89151

>From d3894971090921b92c71ba5a18151cb2033c8cfa Mon Sep 17 00:00:00 2001
From: erichkeane 
Date: Tue, 16 Apr 2024 09:43:55 -0700
Subject: [PATCH 1/2] [OpenACC] Implement 'num_workers' clause for compute
 constructs

This clause just takes an 'int expr', which is not optional.  This patch
implements the clause on compute constructs.
---
 clang/include/clang/AST/OpenACCClause.h   |  56 
 .../clang/Basic/DiagnosticSemaKinds.td|  12 +
 clang/include/clang/Basic/OpenACCClauses.def  |   1 +
 clang/include/clang/Parse/Parser.h|   9 +-
 clang/include/clang/Sema/SemaOpenACC.h|  36 ++-
 clang/lib/AST/OpenACCClause.cpp   |  26 ++
 clang/lib/AST/StmtProfile.cpp |   7 +
 clang/lib/AST/TextNodeDumper.cpp  |   1 +
 clang/lib/Parse/ParseOpenACC.cpp  |  57 ++--
 clang/lib/Sema/SemaOpenACC.cpp| 122 +
 clang/lib/Sema/TreeTransform.h|  23 ++
 clang/lib/Serialization/ASTReader.cpp |   7 +-
 clang/lib/Serialization/ASTWriter.cpp |   7 +-
 clang/test/ParserOpenACC/parse-clauses.c  |   2 -
 .../compute-construct-intexpr-clause-ast.cpp  | 255 ++
 .../compute-construct-num_workers-clause.c|  33 +++
 .../compute-construct-num_workers-clause.cpp  | 133 +
 clang/tools/libclang/CIndex.cpp   |   4 +
 18 files changed, 764 insertions(+), 27 deletions(-)
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-intexpr-clause-ast.cpp
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.c
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.cpp

diff --git a/clang/include/clang/AST/OpenACCClause.h 
b/clang/include/clang/AST/OpenACCClause.h
index 07587849eb1219..7a60620d5875c5 100644
--- a/clang/include/clang/AST/OpenACCClause.h
+++ b/clang/include/clang/AST/OpenACCClause.h
@@ -156,6 +156,62 @@ class OpenACCSelfClause : public 
OpenACCClauseWithCondition {
Expr *ConditionExpr, SourceLocation EndLoc);
 };
 
+/// Represents one of a handful of classes that have integer expressions.
+/// Semantically, many only permit a single expression, with a few that permit
+/// up to 3.
+class OpenACCClauseWithIntExprs : public OpenACCClauseWithParams {
+  llvm::SmallVector IntExprs;
+
+  protected:
+OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc,
+  SourceLocation LParenLoc,
+  ArrayRef IntExprs, SourceLocation EndLoc)
+: OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc),
+  IntExprs(IntExprs) {}
+
+/// Gets the entire list of integer expressions, but leave it to the
+/// individual clauses to expose this how they'd like.
+llvm::ArrayRef getIntExprs() const { return IntExprs; }
+
+  public:
+  child_range children() {
+return child_range(reinterpret_cast(IntExprs.begin()),
+   reinterpret_cast(IntExprs.end()));
+  }
+
+  const_child_range children() const {
+child_range Children =
+const_cast(this)->children();
+return const_child_range(Children.begin(), Children.end());
+  }
+};
+
+/// A more restrictive version of the IntExprs version that exposes a single
+/// integer expression.
+class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithIntExprs {
+  protected:
+OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation 
BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr,
+   SourceLocation EndLoc)
+: OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, IntExpr, EndLoc) {}
+
+  public:
+bool hasIntExpr() const { return !getIntExprs().empty(); }
+const Expr *getIntExpr() const {
+  return hasIntExpr() ? getIntExprs()[0] : nullptr;
+}
+Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }
+};
+
+class OpenACCNumWorkersClause : public OpenACCClauseWithSingleIntExpr {
+  OpenACCNumWorkersClause(SourceLocation BeginLoc, SourceLocation LParenLoc,
+  Expr *IntExpr, SourceLocation EndLoc);
+  public:
+static OpenACCNumWorkersClause *
+Create(const ASTContext , SourceLocation BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc);
+};
+
 template  class OpenACCClauseVisitor {
   Impl () { return static_cast(*this); }
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 30a8543489f48e..5ac1b3dc6233a3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12268,4 +12268,16 @@ def warn_acc_if_self_conflict
 : Warning<"OpenACC construct 'self' has no effect when an 'if' clause "
   "evaluates to true">,

[clang] [OpenACC] Implement 'num_workers' clause for compute constructs (PR #89151)

2024-04-17 Thread Erich Keane via cfe-commits


@@ -0,0 +1,133 @@
+// RUN: %clang_cc1 %s -fopenacc -verify
+
+struct NotConvertible{} NC;
+struct Incomplete *SomeIncomplete; // #INCOMPLETE
+enum E{} SomeE;
+enum class E2{} SomeE2;
+
+struct CorrectConvert {
+  operator int();
+} Convert;
+
+struct ExplicitConvertOnly {
+  explicit operator int() const; // #EXPL_CONV
+} Explicit;
+
+struct AmbiguousConvert{
+  operator int(); // #AMBIG_INT
+  operator short(); // #AMBIG_SHORT
+  operator float();
+} Ambiguous;
+
+void Test() {
+#pragma acc parallel num_workers(1)
+  while(1);
+#pragma acc kernels num_workers(1)
+  while(1);
+
+  // expected-error@+1{{OpenACC clause 'num_workers' requires expression of 
integer type ('struct NotConvertible' invalid}}
+#pragma acc parallel num_workers(NC)
+  while(1);
+
+  // expected-error@+2{{OpenACC integer expression has incomplete class type 
'struct Incomplete'}}
+  // expected-note@#INCOMPLETE{{forward declaration of 'Incomplete'}}
+#pragma acc kernels num_workers(*SomeIncomplete)
+  while(1);
+
+#pragma acc parallel num_workers(SomeE)
+  while(1);
+
+  // expected-error@+1{{OpenACC clause 'num_workers' requires expression of 
integer type ('enum E2' invalid}}
+#pragma acc kernels num_workers(SomeE2)
+  while(1);
+
+#pragma acc parallel num_workers(Convert)
+  while(1);
+
+  // expected-error@+2{{OpenACC integer expression type 'struct 
ExplicitConvertOnly' requires explicit conversion to 'int'}}
+  // expected-note@#EXPL_CONV{{conversion to integral type 'int'}}
+#pragma acc kernels num_workers(Explicit)
+  while(1);
+
+  // expected-error@+3{{multiple conversions from expression type 'struct 
AmbiguousConvert' to an integral type}}
+  // expected-note@#AMBIG_INT{{conversion to integral type 'int'}}
+  // expected-note@#AMBIG_SHORT{{conversion to integral type 'short'}}
+#pragma acc parallel num_workers(Ambiguous)
+  while(1);
+}
+
+struct HasInt {
+  using IntTy = int;
+  using ShortTy = short;
+  static constexpr int value = 1;
+  static constexpr AmbiguousConvert ACValue;
+  static constexpr ExplicitConvertOnly EXValue;
+
+  operator char();
+};
+
+template
+void TestInst() {
+
+  // expected-error@+1{{no member named 'Invalid' in 'HasInt'}}
+#pragma acc parallel num_workers(HasInt::Invalid)
+  while (1);
+
+  // expected-error@+2{{no member named 'Invalid' in 'HasInt'}}
+  // expected-note@#INST{{in instantiation of function template specialization 
'TestInst' requested here}}
+#pragma acc kernels num_workers(T::Invalid)
+  while (1);
+
+  // expected-error@+3{{multiple conversions from expression type 'const 
AmbiguousConvert' to an integral type}}
+  // expected-note@#AMBIG_INT{{conversion to integral type 'int'}}
+  // expected-note@#AMBIG_SHORT{{conversion to integral type 'short'}}
+#pragma acc parallel num_workers(HasInt::ACValue)
+  while (1);
+
+  // expected-error@+3{{multiple conversions from expression type 'const 
AmbiguousConvert' to an integral type}}
+  // expected-note@#AMBIG_INT{{conversion to integral type 'int'}}
+  // expected-note@#AMBIG_SHORT{{conversion to integral type 'short'}}
+#pragma acc kernels num_workers(T::ACValue)
+  while (1);
+
+  // expected-error@+2{{OpenACC integer expression type 'const 
ExplicitConvertOnly' requires explicit conversion to 'int'}}
+  // expected-note@#EXPL_CONV{{conversion to integral type 'int'}}
+#pragma acc parallel num_workers(HasInt::EXValue)

erichkeane wrote:

Note: this is expected to diagnose the above error/note 2x until this patch is 
committed: https://github.com/llvm/llvm-project/pull/89142

as it uses the same infrastructure.  I'll ensure these are committed in the 
correct order.

https://github.com/llvm/llvm-project/pull/89151
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC] Implement 'num_workers' clause for compute constructs (PR #89151)

2024-04-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Erich Keane (erichkeane)


Changes

This clause just takes an 'int expr', which is not optional.  This patch 
implements the clause on compute constructs.

---

Patch is 44.13 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/89151.diff


18 Files Affected:

- (modified) clang/include/clang/AST/OpenACCClause.h (+56) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+12) 
- (modified) clang/include/clang/Basic/OpenACCClauses.def (+1) 
- (modified) clang/include/clang/Parse/Parser.h (+5-4) 
- (modified) clang/include/clang/Sema/SemaOpenACC.h (+34-2) 
- (modified) clang/lib/AST/OpenACCClause.cpp (+26) 
- (modified) clang/lib/AST/StmtProfile.cpp (+7) 
- (modified) clang/lib/AST/TextNodeDumper.cpp (+1) 
- (modified) clang/lib/Parse/ParseOpenACC.cpp (+40-17) 
- (modified) clang/lib/Sema/SemaOpenACC.cpp (+122) 
- (modified) clang/lib/Sema/TreeTransform.h (+23) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+6-1) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+6-1) 
- (modified) clang/test/ParserOpenACC/parse-clauses.c (-2) 
- (added) clang/test/SemaOpenACC/compute-construct-intexpr-clause-ast.cpp 
(+255) 
- (added) clang/test/SemaOpenACC/compute-construct-num_workers-clause.c (+33) 
- (added) clang/test/SemaOpenACC/compute-construct-num_workers-clause.cpp 
(+133) 
- (modified) clang/tools/libclang/CIndex.cpp (+4) 


``diff
diff --git a/clang/include/clang/AST/OpenACCClause.h 
b/clang/include/clang/AST/OpenACCClause.h
index 07587849eb1219..7a60620d5875c5 100644
--- a/clang/include/clang/AST/OpenACCClause.h
+++ b/clang/include/clang/AST/OpenACCClause.h
@@ -156,6 +156,62 @@ class OpenACCSelfClause : public 
OpenACCClauseWithCondition {
Expr *ConditionExpr, SourceLocation EndLoc);
 };
 
+/// Represents one of a handful of classes that have integer expressions.
+/// Semantically, many only permit a single expression, with a few that permit
+/// up to 3.
+class OpenACCClauseWithIntExprs : public OpenACCClauseWithParams {
+  llvm::SmallVector IntExprs;
+
+  protected:
+OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc,
+  SourceLocation LParenLoc,
+  ArrayRef IntExprs, SourceLocation EndLoc)
+: OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc),
+  IntExprs(IntExprs) {}
+
+/// Gets the entire list of integer expressions, but leave it to the
+/// individual clauses to expose this how they'd like.
+llvm::ArrayRef getIntExprs() const { return IntExprs; }
+
+  public:
+  child_range children() {
+return child_range(reinterpret_cast(IntExprs.begin()),
+   reinterpret_cast(IntExprs.end()));
+  }
+
+  const_child_range children() const {
+child_range Children =
+const_cast(this)->children();
+return const_child_range(Children.begin(), Children.end());
+  }
+};
+
+/// A more restrictive version of the IntExprs version that exposes a single
+/// integer expression.
+class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithIntExprs {
+  protected:
+OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation 
BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr,
+   SourceLocation EndLoc)
+: OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, IntExpr, EndLoc) {}
+
+  public:
+bool hasIntExpr() const { return !getIntExprs().empty(); }
+const Expr *getIntExpr() const {
+  return hasIntExpr() ? getIntExprs()[0] : nullptr;
+}
+Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }
+};
+
+class OpenACCNumWorkersClause : public OpenACCClauseWithSingleIntExpr {
+  OpenACCNumWorkersClause(SourceLocation BeginLoc, SourceLocation LParenLoc,
+  Expr *IntExpr, SourceLocation EndLoc);
+  public:
+static OpenACCNumWorkersClause *
+Create(const ASTContext , SourceLocation BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc);
+};
+
 template  class OpenACCClauseVisitor {
   Impl () { return static_cast(*this); }
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 30a8543489f48e..5ac1b3dc6233a3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12268,4 +12268,16 @@ def warn_acc_if_self_conflict
 : Warning<"OpenACC construct 'self' has no effect when an 'if' clause "
   "evaluates to true">,
   InGroup>;
+def err_acc_int_expr_requires_integer
+: Error<"OpenACC %select{clause|directive}0 '%1' requires expression of "
+"integer type (%2 invalid)">;
+def err_acc_int_expr_incomplete_class_type
+: Error<"OpenACC integer expression has incomplete class type %0">;

[clang] [OpenACC] Implement 'num_workers' clause for compute constructs (PR #89151)

2024-04-17 Thread Erich Keane via cfe-commits

https://github.com/erichkeane created 
https://github.com/llvm/llvm-project/pull/89151

This clause just takes an 'int expr', which is not optional.  This patch 
implements the clause on compute constructs.

>From d3894971090921b92c71ba5a18151cb2033c8cfa Mon Sep 17 00:00:00 2001
From: erichkeane 
Date: Tue, 16 Apr 2024 09:43:55 -0700
Subject: [PATCH] [OpenACC] Implement 'num_workers' clause for compute
 constructs

This clause just takes an 'int expr', which is not optional.  This patch
implements the clause on compute constructs.
---
 clang/include/clang/AST/OpenACCClause.h   |  56 
 .../clang/Basic/DiagnosticSemaKinds.td|  12 +
 clang/include/clang/Basic/OpenACCClauses.def  |   1 +
 clang/include/clang/Parse/Parser.h|   9 +-
 clang/include/clang/Sema/SemaOpenACC.h|  36 ++-
 clang/lib/AST/OpenACCClause.cpp   |  26 ++
 clang/lib/AST/StmtProfile.cpp |   7 +
 clang/lib/AST/TextNodeDumper.cpp  |   1 +
 clang/lib/Parse/ParseOpenACC.cpp  |  57 ++--
 clang/lib/Sema/SemaOpenACC.cpp| 122 +
 clang/lib/Sema/TreeTransform.h|  23 ++
 clang/lib/Serialization/ASTReader.cpp |   7 +-
 clang/lib/Serialization/ASTWriter.cpp |   7 +-
 clang/test/ParserOpenACC/parse-clauses.c  |   2 -
 .../compute-construct-intexpr-clause-ast.cpp  | 255 ++
 .../compute-construct-num_workers-clause.c|  33 +++
 .../compute-construct-num_workers-clause.cpp  | 133 +
 clang/tools/libclang/CIndex.cpp   |   4 +
 18 files changed, 764 insertions(+), 27 deletions(-)
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-intexpr-clause-ast.cpp
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.c
 create mode 100644 
clang/test/SemaOpenACC/compute-construct-num_workers-clause.cpp

diff --git a/clang/include/clang/AST/OpenACCClause.h 
b/clang/include/clang/AST/OpenACCClause.h
index 07587849eb1219..7a60620d5875c5 100644
--- a/clang/include/clang/AST/OpenACCClause.h
+++ b/clang/include/clang/AST/OpenACCClause.h
@@ -156,6 +156,62 @@ class OpenACCSelfClause : public 
OpenACCClauseWithCondition {
Expr *ConditionExpr, SourceLocation EndLoc);
 };
 
+/// Represents one of a handful of classes that have integer expressions.
+/// Semantically, many only permit a single expression, with a few that permit
+/// up to 3.
+class OpenACCClauseWithIntExprs : public OpenACCClauseWithParams {
+  llvm::SmallVector IntExprs;
+
+  protected:
+OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc,
+  SourceLocation LParenLoc,
+  ArrayRef IntExprs, SourceLocation EndLoc)
+: OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc),
+  IntExprs(IntExprs) {}
+
+/// Gets the entire list of integer expressions, but leave it to the
+/// individual clauses to expose this how they'd like.
+llvm::ArrayRef getIntExprs() const { return IntExprs; }
+
+  public:
+  child_range children() {
+return child_range(reinterpret_cast(IntExprs.begin()),
+   reinterpret_cast(IntExprs.end()));
+  }
+
+  const_child_range children() const {
+child_range Children =
+const_cast(this)->children();
+return const_child_range(Children.begin(), Children.end());
+  }
+};
+
+/// A more restrictive version of the IntExprs version that exposes a single
+/// integer expression.
+class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithIntExprs {
+  protected:
+OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation 
BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr,
+   SourceLocation EndLoc)
+: OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, IntExpr, EndLoc) {}
+
+  public:
+bool hasIntExpr() const { return !getIntExprs().empty(); }
+const Expr *getIntExpr() const {
+  return hasIntExpr() ? getIntExprs()[0] : nullptr;
+}
+Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }
+};
+
+class OpenACCNumWorkersClause : public OpenACCClauseWithSingleIntExpr {
+  OpenACCNumWorkersClause(SourceLocation BeginLoc, SourceLocation LParenLoc,
+  Expr *IntExpr, SourceLocation EndLoc);
+  public:
+static OpenACCNumWorkersClause *
+Create(const ASTContext , SourceLocation BeginLoc,
+   SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc);
+};
+
 template  class OpenACCClauseVisitor {
   Impl () { return static_cast(*this); }
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 30a8543489f48e..5ac1b3dc6233a3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12268,4 +12268,16 @@ def warn_acc_if_self_conflict
  

  1   2   3   4   5   >