[clang] clang: add unnamed_addr function attribute (PR #92499)

2024-05-17 Thread YAMAMOTO Takashi via cfe-commits

https://github.com/yamt updated https://github.com/llvm/llvm-project/pull/92499

>From 52b744c91bdba1cf8cda9d6164ec8fc130d75fab Mon Sep 17 00:00:00 2001
From: YAMAMOTO Takashi 
Date: Fri, 17 May 2024 14:47:06 +0900
Subject: [PATCH] [clang] add unnamed_addr function attribute

It simply applies the LLVM attribute with the same name to the function.

Sometimes, a programmer knows that function pointer uniqueness doesn't
really matter for some of their functions. In that case, this attribute
opens a possibility of certain optimizations like mergefunc with aliases.
It's especially useful for code generators.
---
 clang/include/clang/Basic/Attr.td  | 7 +++
 clang/lib/CodeGen/CodeGenModule.cpp| 4 
 .../Misc/pragma-attribute-supported-attributes-list.test   | 1 +
 3 files changed, 12 insertions(+)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 52552ba488560..3ee7d43d339f1 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1944,6 +1944,13 @@ def ReturnsTwice : InheritableAttr {
   let SimpleHandler = 1;
 }
 
+def UnnamedAddr : InheritableAttr {
+  let Spellings = [Clang<"unnamed_addr">];
+  let Subjects = SubjectList<[Function]>;
+  let Documentation = [Undocumented];
+  let SimpleHandler = 1;
+}
+
 def DisableTailCalls : InheritableAttr {
   let Spellings = [Clang<"disable_tail_calls">];
   let Subjects = SubjectList<[Function, ObjCMethod]>;
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 489c08a4d4819..ac9f082a1049b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2506,6 +2506,10 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::MinSize);
   }
 
+  if (D->hasAttr()) {
+F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
+  }
+
   F->addFnAttrs(B);
 
   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test 
b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 318bfb2df2a7a..62ab5cee27a71 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -199,6 +199,7 @@
 // CHECK-NEXT: TestTypestate (SubjectMatchRule_function_is_member)
 // CHECK-NEXT: TrivialABI (SubjectMatchRule_record)
 // CHECK-NEXT: Uninitialized (SubjectMatchRule_variable_is_local)
+// CHECK-NEXT: UnnamedAddr (SubjectMatchRule_function)
 // CHECK-NEXT: UnsafeBufferUsage (SubjectMatchRule_function)
 // CHECK-NEXT: UseHandle (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: VecReturn (SubjectMatchRule_record)

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


[clang] [clang] CTAD alias: Emit a more descriptive diagnostic message when is_deducible constraint is evaluated to false. (PR #92389)

2024-05-17 Thread Haojian Wu via cfe-commits

hokein wrote:

Thanks @mizvekov for the quick fix.

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


[clang] [clang] Implement a bitwise_copyable builtin type trait. (PR #86512)

2024-05-17 Thread Haojian Wu via cfe-commits


@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+// Scalar types are bitwise clonable.
+static_assert(__is_bitwise_cloneable(int));
+static_assert(__is_bitwise_cloneable(int*));
+// array
+static_assert(__is_bitwise_cloneable(int[10]));
+
+// non-scalar types.
+static_assert(!__is_bitwise_cloneable(int&));
+
+
+struct Forward; // expected-note 2{{forward declaration of 'Forward'}}
+static_assert(!__is_bitwise_cloneable(Forward)); // expected-error 
{{incomplete type 'Forward' used in type trait expression}}
+
+struct Foo { int a; };
+static_assert(__is_bitwise_cloneable(Foo));
+
+struct DynamicClass { virtual int Foo(); };
+static_assert(__is_bitwise_cloneable(DynamicClass));
+
+struct Bar { int& b; }; // trivially copyable
+static_assert(__is_trivially_copyable(Bar));
+static_assert(__is_bitwise_cloneable(Bar));

hokein wrote:

Because of the reference member `int & b`.

Reference types are currently excluded in bitwise-cloneable types (references 
are just alias, and they cannot be reset once initialized).

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


[clang] [clang] add unnamed_addr function attribute (PR #92499)

2024-05-17 Thread YAMAMOTO Takashi via cfe-commits

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-17 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

@arsenm Should we use `image` or `private`?
We could allow both in the frontend, and only use `private` as the canonical 
MMRA.

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


[clang] [libclc] libclc: remove __attribute__((assume)) for clspv targets (PR #92126)

2024-05-17 Thread Romaric Jodin via cfe-commits

rjodinchr wrote:

Is there something else needed on my side to get that PR merged?

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


[clang] [Clang] Fix P2564 handling of variable initializers (PR #89565)

2024-05-17 Thread Mariya Podchishchaeva via cfe-commits

Fznamznon wrote:

@katzdm 
Does it make sense to file an issue so we don't forget to bring the warning 
back?

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


[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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

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

>From 7acbb1dd89dbe266c3e53ab30178ac570722c759 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Thu, 16 May 2024 19:06:25 +0800
Subject: [PATCH 1/2] [Clang][Sema] Avoid pack expansion for expanded empty
 PackIndexingExprs

We previously doubled the id-expression expansion, even when the pack
was expanded to empty. The previous condition for determining whether
we should expand couldn't distinguish between cases where 'the expansion
was previously postponed' and 'the expansion occurred but resulted in
emptiness.'

In the latter scenario, we crash because we have not been examining the
current lambda's parent local instantiation scope since D98068: Any
Decls instantiated in the parent scope are not visible to the generic
lambda. And thus any attempt of looking for instantiated Decls in the lambda
is capped to the current Lambda's LIS.

Fixes https://github.com/llvm/llvm-project/issues/92230
---
 clang/include/clang/AST/ExprCXX.h  | 14 ++
 clang/lib/AST/ExprCXX.cpp  | 16 
 clang/lib/Sema/SemaTemplateVariadic.cpp|  2 +-
 clang/lib/Sema/TreeTransform.h |  6 ++
 clang/test/SemaCXX/cxx2c-pack-indexing.cpp |  8 ++--
 5 files changed, 27 insertions(+), 19 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index fac65628ffede..2617cd36d0df9 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -4381,11 +4381,13 @@ class PackIndexingExpr final
 
   PackIndexingExpr(QualType Type, SourceLocation EllipsisLoc,
SourceLocation RSquareLoc, Expr *PackIdExpr, Expr 
*IndexExpr,
-   ArrayRef SubstitutedExprs = {})
+   ArrayRef SubstitutedExprs = {},
+   bool EmptyPack = false)
   : Expr(PackIndexingExprClass, Type, VK_LValue, OK_Ordinary),
 EllipsisLoc(EllipsisLoc), RSquareLoc(RSquareLoc),
 SubExprs{PackIdExpr, IndexExpr},
-TransformedExpressions(SubstitutedExprs.size()) {
+TransformedExpressions(EmptyPack ? size_t(-1)
+ : SubstitutedExprs.size()) {
 
 auto *Exprs = getTrailingObjects();
 std::uninitialized_copy(SubstitutedExprs.begin(), SubstitutedExprs.end(),
@@ -4408,10 +4410,13 @@ class PackIndexingExpr final
   SourceLocation EllipsisLoc,
   SourceLocation RSquareLoc, Expr *PackIdExpr,
   Expr *IndexExpr, std::optional 
Index,
-  ArrayRef SubstitutedExprs = {});
+  ArrayRef SubstitutedExprs = {},
+  bool EmptyPack = false);
   static PackIndexingExpr *CreateDeserialized(ASTContext &Context,
   unsigned NumTransformedExprs);
 
+  bool isEmptyPack() const { return TransformedExpressions == size_t(-1); }
+
   /// Determine the location of the 'sizeof' keyword.
   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
 
@@ -4446,7 +4451,8 @@ class PackIndexingExpr final
   }
 
   ArrayRef getExpressions() const {
-return {getTrailingObjects(), TransformedExpressions};
+return {getTrailingObjects(),
+isEmptyPack() ? 0 : TransformedExpressions};
   }
 
   static bool classof(const Stmt *T) {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 7e9343271ac3c..01cdd2709b472 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -1665,12 +1665,11 @@ NonTypeTemplateParmDecl 
*SubstNonTypeTemplateParmExpr::getParameter() const {
   getReplacedTemplateParameterList(getAssociatedDecl())->asArray()[Index]);
 }
 
-PackIndexingExpr *PackIndexingExpr::Create(ASTContext &Context,
-   SourceLocation EllipsisLoc,
-   SourceLocation RSquareLoc,
-   Expr *PackIdExpr, Expr *IndexExpr,
-   std::optional Index,
-   ArrayRef SubstitutedExprs) {
+PackIndexingExpr *
+PackIndexingExpr::Create(ASTContext &Context, SourceLocation EllipsisLoc,
+ SourceLocation RSquareLoc, Expr *PackIdExpr,
+ Expr *IndexExpr, std::optional Index,
+ ArrayRef SubstitutedExprs, bool EmptyPack) {
   QualType Type;
   if (Index && !SubstitutedExprs.empty())
 Type = SubstitutedExprs[*Index]->getType();
@@ -1679,8 +1678,9 @@ PackIndexingExpr *PackIndexingExpr::Create(ASTContext 
&Context,
 
   void *Storage =
   Context.Allocate(totalSizeToAlloc(SubstitutedExprs.size()));
-  return new (Storage) PackIndexingExpr(
-  Type, EllipsisLoc, RSquareLoc, PackIdExpr, IndexExpr, SubstitutedExprs);
+  return new (Stora

[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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

https://github.com/zyn0217 commented:

@cor3ntin PTAL. Thanks!

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


[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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


@@ -2157,11 +2157,11 @@ void ASTStmtWriter::VisitSizeOfPackExpr(SizeOfPackExpr 
*E) {
 void ASTStmtWriter::VisitPackIndexingExpr(PackIndexingExpr *E) {
   VisitExpr(E);
   Record.push_back(E->TransformedExpressions);
+  Record.push_back(E->EmptyPack);
   Record.AddSourceLocation(E->getEllipsisLoc());
   Record.AddSourceLocation(E->getRSquareLoc());
   Record.AddStmt(E->getPackIdExpression());
   Record.AddStmt(E->getIndexExpr());
-  Record.push_back(E->TransformedExpressions);

zyn0217 wrote:

This appears to be a copy-paste error of line 2160... So I removed it.

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


[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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


@@ -4377,15 +4377,20 @@ class PackIndexingExpr final
   // The pack being indexed, followed by the index
   Stmt *SubExprs[2];
 
-  size_t TransformedExpressions;
+  // The size of the trailing expressions.
+  unsigned TransformedExpressions : 31;

zyn0217 wrote:

I changed it to `unsigned` because `numTrailingObjects` is designed to return 
an `unsigned` number.

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


[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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

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


[clang] [Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (PR #92385)

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


@@ -4377,15 +4377,20 @@ class PackIndexingExpr final
   // The pack being indexed, followed by the index
   Stmt *SubExprs[2];
 
-  size_t TransformedExpressions;
+  // The size of the trailing expressions.
+  unsigned TransformedExpressions : 31;

zyn0217 wrote:

Aside: I'm not spelling it as `: sizeof(unsigned) - 1` because we seem to write 
down the number 31 directly elsewhere. So I think i'd better respect the 
convention.

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


[clang] [Clang][AArch64] Use __clang_arm_builtin_alias for overloaded svreinterpret's (PR #92427)

2024-05-17 Thread via cfe-commits

rsandifo-arm wrote:

> > Thinking about it a bit more, maybe we can just do some magic to make 
> > things work? Say, if you specify `__attribute__((target("sve"))) 
> > __arm_streaming_compatible`, and the caller is in streaming mode, allow the 
> > call even if the caller doesn't have SVE proper.
> 
> Thinking a bit more, this is probably not quite what we want: even if the 
> function body itself is streaming compatible, it might call non-streaming 
> functions that require SVE. Maybe spell this something like 
> `__attribute__((target("sve-or-streaming"))) __arm_streaming_compatible`.

I suppose the idea here is that:
```
   __attribute__((target("sve"))) void f() { … }
   void g() { … f(); … }
```
should be diagnosed, on the basis that, when compiled with default flags, `g` 
doesn't guarantee the availability of SVE, whereas `f` requires it?  If so, I 
don't think we should do that, for two reasons:

First, it's IMO valid to do:
```
   __attribute__((target("sve"))) void sve_routine() { … }
   void main_interface() {
 if (SVE_is_available() && problem_has_certain_characteristics())
   sve_routine();
 else
   …
   }
```
That is, feature gating can be dynamic.  It doesn't need to be a load-time 
thing.

Second, at least in GCC, the `target` attribute is not part of a function's 
type, so it's not an error to do:
```
foo.h: void f();
foo.cc: __attribute__((target("sve"))) void f() { … }
```
And I'd argue that that's a feature rather than a bug.  It allows load-time 
selection of DSOs based on the target.

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


[clang] [webkit.RefCntblBaseVirtualDtor] Ignore a base class which has a specialized deref function for a given derived class. (PR #92501)

2024-05-17 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/92501

>From 87cfc8234e1294dedc103b9bcd2b7d9d31874c4a Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Thu, 16 May 2024 23:24:13 -0700
Subject: [PATCH 1/4] [webkit.RefCntblBaseVirtualDtor] Ignore a base class
 which has a specialized deref function for a given derived class.

When a base class B has a deref function which calls delete operator on a 
derived class D,
don't emit a warning for B even if it did not have a virtual destructor.
---
 .../WebKit/RefCntblBaseVirtualDtorChecker.cpp | 140 -
 .../ref-cntbl-base-virtual-dtor-templates.cpp | 196 +-
 2 files changed, 330 insertions(+), 6 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 7f4c3a7b787e8..36ab581f1edbd 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -11,16 +11,128 @@
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
+#include "llvm/ADT/DenseSet.h"
 #include 
 
 using namespace clang;
 using namespace ento;
 
 namespace {
+
+class DerefAnalysisVisitor
+: public ConstStmtVisitor {
+  // Returns true if any of child statements return true.
+  bool VisitChildren(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && Visit(Child))
+return true;
+}
+return false;
+  }
+
+  bool VisitBody(const Stmt *Body) {
+if (!Body)
+  return false;
+
+auto [It, IsNew] = VisitedBody.insert(Body);
+if (!IsNew) // This body is recursive
+  return false;
+
+return Visit(Body);
+  }
+
+public:
+  DerefAnalysisVisitor(const TemplateArgumentList &ArgList,
+   const CXXRecordDecl *ClassDecl)
+: ArgList(&ArgList)
+, ClassDecl(ClassDecl)
+  { }
+
+  DerefAnalysisVisitor(const CXXRecordDecl *ClassDecl)
+: ClassDecl(ClassDecl)
+  { }
+
+  bool HasSpecializedDelete(CXXMethodDecl *Decl) {
+if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+  return VisitBody(Tmpl->getBody());
+return VisitBody(Decl->getBody());
+  }
+
+  bool VisitCallExpr(const CallExpr *CE) {
+auto *Callee = CE->getCallee();
+while (auto *Expr = dyn_cast(Callee))
+  Callee = Expr->getSubExpr();
+if (auto *DeclRef = dyn_cast(Callee)) {
+  auto *Decl = DeclRef->getDecl();
+  if (auto *VD = dyn_cast(Decl)) {
+if (auto *Init = VD->getInit()) {
+  if (auto *Lambda = dyn_cast(Init))
+return VisitBody(Lambda->getBody());
+}
+  } else if (auto *FD = dyn_cast(Decl))
+return VisitBody(FD->getBody());
+}
+return false;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
+auto *Callee = MCE->getMethodDecl();
+if (!Callee)
+  return false;
+return VisitBody(Callee->getBody());
+  }
+
+  bool VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
+auto *Arg = E->getArgument();
+while (Arg) {
+  if (auto *Paren = dyn_cast(Arg))
+Arg = Paren->getSubExpr();
+  else if (auto *Cast = dyn_cast(Arg)) {
+Arg = Cast->getSubExpr();
+auto CastType = Cast->getType();
+if (auto *PtrType = dyn_cast(CastType)) {
+  auto PointeeType = PtrType->getPointeeType();
+  while (auto *ET = dyn_cast(PointeeType)) {
+if (ET->isSugared())
+  PointeeType = ET->desugar();
+  }
+  if (auto *ParmType = dyn_cast(PointeeType)) {
+if (ArgList) {
+  auto ParmIndex = ParmType->getIndex();
+  auto Type = ArgList->get(ParmIndex).getAsType();
+  if (auto *RD = dyn_cast(Type)) {
+if (RD->getDecl() == ClassDecl)
+  return true;
+  }
+}
+  } else if (auto *RD = dyn_cast(PointeeType)) {
+if (RD->getDecl() == ClassDecl)
+  return true;
+  }
+}
+  } else
+break;
+}
+return false;
+  }
+
+  bool VisitStmt(const Stmt *S) { return VisitChildren(S); }
+
+  // Return false since the contents of lambda isn't necessarily executed.
+  // If it is executed, VisitCallExpr above will visit its body.
+  bool VisitLambdaExpr(const LambdaExpr *) { return false; }
+
+private:
+  const TemplateArgumentList* ArgList { nullptr };
+  const CXXRecordDecl* ClassDecl;
+  llvm::DenseSet VisitedBody;
+};
+
 class RefCntblBaseVirtualDtorChecker
 : public Checker> {
 private:
@@ -91,8 +2

[clang] ee54c86 - [clang][NFC] Improve const-correctness in `SourceManager` (#92436)

2024-05-17 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-05-17T13:01:37+04:00
New Revision: ee54c86ef70d7809e7d67cd44de2d3153b31c46e

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

LOG: [clang][NFC] Improve const-correctness in `SourceManager` (#92436)

This patch adds several const-qualified variants of existing member
functions to `SourceManager`.
I started with removing const qualification from
`setNumCreatedFIDsForFileID`, and removing `const_cast` in the body of
this function, as I think it doesn't make sense to const-qualify
setters.

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 5258bab584f49..ce33423551039 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -497,6 +497,10 @@ class SLocEntry {
   bool isFile() const { return !isExpansion(); }
 
   const FileInfo &getFile() const {
+return const_cast(this)->getFile();
+  }
+
+  FileInfo &getFile() {
 assert(isFile() && "Not a file SLocEntry!");
 return File;
   }
@@ -1120,12 +1124,12 @@ class SourceManager : public 
RefCountedBase {
   /// Set the number of FileIDs (files and macros) that were created
   /// during preprocessing of \p FID, including it.
   void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs,
-  bool Force = false) const {
+  bool Force = false) {
 auto *Entry = getSLocEntryForFile(FID);
 if (!Entry)
   return;
 assert((Force || Entry->getFile().NumCreatedFIDs == 0) && "Already set!");
-const_cast(Entry->getFile()).NumCreatedFIDs = NumFIDs;
+Entry->getFile().NumCreatedFIDs = NumFIDs;
   }
 
   
//======//
@@ -1730,6 +1734,11 @@ class SourceManager : public 
RefCountedBase {
 
   /// Get a local SLocEntry. This is exposed for indexing.
   const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index) const {
+return const_cast(this)->getLocalSLocEntry(Index);
+  }
+
+  /// Get a local SLocEntry. This is exposed for indexing.
+  SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index) {
 assert(Index < LocalSLocEntryTable.size() && "Invalid index");
 return LocalSLocEntryTable[Index];
   }
@@ -1740,6 +1749,13 @@ class SourceManager : public 
RefCountedBase {
   /// Get a loaded SLocEntry. This is exposed for indexing.
   const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
   bool *Invalid = nullptr) const {
+return const_cast(this)->getLoadedSLocEntry(Index,
+ Invalid);
+  }
+
+  /// Get a loaded SLocEntry. This is exposed for indexing.
+  SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
+bool *Invalid = nullptr) {
 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
 if (SLocEntryLoaded[Index])
   return LoadedSLocEntryTable[Index];
@@ -1748,6 +1764,10 @@ class SourceManager : public 
RefCountedBase {
 
   const SrcMgr::SLocEntry &getSLocEntry(FileID FID,
 bool *Invalid = nullptr) const {
+return const_cast(this)->getSLocEntry(FID, Invalid);
+  }
+
+  SrcMgr::SLocEntry &getSLocEntry(FileID FID, bool *Invalid = nullptr) {
 if (FID.ID == 0 || FID.ID == -1) {
   if (Invalid) *Invalid = true;
   return LocalSLocEntryTable[0];
@@ -1821,14 +1841,23 @@ class SourceManager : public 
RefCountedBase {
   SrcMgr::ContentCache &getFakeContentCacheForRecovery() const;
 
   const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
+  SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid);
 
   const SrcMgr::SLocEntry *getSLocEntryOrNull(FileID FID) const {
+return const_cast(this)->getSLocEntryOrNull(FID);
+  }
+
+  SrcMgr::SLocEntry *getSLocEntryOrNull(FileID FID) {
 bool Invalid = false;
-const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
+SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
 return Invalid ? nullptr : &Entry;
   }
 
   const SrcMgr::SLocEntry *getSLocEntryForFile(FileID FID) const {
+return const_cast(this)->getSLocEntryForFile(FID);
+  }
+
+  SrcMgr::SLocEntry *getSLocEntryForFile(FileID FID) {
 if (auto *Entry = getSLocEntryOrNull(FID))
   if (Entry->isFile())
 return Entry;
@@ -1839,6 +1868,10 @@ class SourceManager : public 
RefCountedBase {
   /// Invalid will not be modified for Local IDs.
   const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
 b

[clang] [clang][NFC] Improve const-correctness in `SourceManager` (PR #92436)

2024-05-17 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [OpenCL] Put constant initializer globals into constant addrspace (PR #90048)

2024-05-17 Thread Sven van Haastregt via cfe-commits


@@ -535,20 +535,23 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   elementType.isTriviallyCopyableType(CGF.getContext())) {
 CodeGen::CodeGenModule &CGM = CGF.CGM;
 ConstantEmitter Emitter(CGF);
-LangAS AS = ArrayQTy.getAddressSpace();
+QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
+CGM.getContext().removeAddrSpaceQualType(ArrayQTy),

svenvh wrote:

@changpeng would you be able to provide an input source that demonstrates the 
issue?

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


[clang] [webkit.RefCntblBaseVirtualDtor] Ignore a base class which has a specialized deref function for a given derived class. (PR #92501)

2024-05-17 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/92501

>From 87cfc8234e1294dedc103b9bcd2b7d9d31874c4a Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Thu, 16 May 2024 23:24:13 -0700
Subject: [PATCH 1/5] [webkit.RefCntblBaseVirtualDtor] Ignore a base class
 which has a specialized deref function for a given derived class.

When a base class B has a deref function which calls delete operator on a 
derived class D,
don't emit a warning for B even if it did not have a virtual destructor.
---
 .../WebKit/RefCntblBaseVirtualDtorChecker.cpp | 140 -
 .../ref-cntbl-base-virtual-dtor-templates.cpp | 196 +-
 2 files changed, 330 insertions(+), 6 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 7f4c3a7b787e8..36ab581f1edbd 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -11,16 +11,128 @@
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
+#include "llvm/ADT/DenseSet.h"
 #include 
 
 using namespace clang;
 using namespace ento;
 
 namespace {
+
+class DerefAnalysisVisitor
+: public ConstStmtVisitor {
+  // Returns true if any of child statements return true.
+  bool VisitChildren(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && Visit(Child))
+return true;
+}
+return false;
+  }
+
+  bool VisitBody(const Stmt *Body) {
+if (!Body)
+  return false;
+
+auto [It, IsNew] = VisitedBody.insert(Body);
+if (!IsNew) // This body is recursive
+  return false;
+
+return Visit(Body);
+  }
+
+public:
+  DerefAnalysisVisitor(const TemplateArgumentList &ArgList,
+   const CXXRecordDecl *ClassDecl)
+: ArgList(&ArgList)
+, ClassDecl(ClassDecl)
+  { }
+
+  DerefAnalysisVisitor(const CXXRecordDecl *ClassDecl)
+: ClassDecl(ClassDecl)
+  { }
+
+  bool HasSpecializedDelete(CXXMethodDecl *Decl) {
+if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+  return VisitBody(Tmpl->getBody());
+return VisitBody(Decl->getBody());
+  }
+
+  bool VisitCallExpr(const CallExpr *CE) {
+auto *Callee = CE->getCallee();
+while (auto *Expr = dyn_cast(Callee))
+  Callee = Expr->getSubExpr();
+if (auto *DeclRef = dyn_cast(Callee)) {
+  auto *Decl = DeclRef->getDecl();
+  if (auto *VD = dyn_cast(Decl)) {
+if (auto *Init = VD->getInit()) {
+  if (auto *Lambda = dyn_cast(Init))
+return VisitBody(Lambda->getBody());
+}
+  } else if (auto *FD = dyn_cast(Decl))
+return VisitBody(FD->getBody());
+}
+return false;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
+auto *Callee = MCE->getMethodDecl();
+if (!Callee)
+  return false;
+return VisitBody(Callee->getBody());
+  }
+
+  bool VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
+auto *Arg = E->getArgument();
+while (Arg) {
+  if (auto *Paren = dyn_cast(Arg))
+Arg = Paren->getSubExpr();
+  else if (auto *Cast = dyn_cast(Arg)) {
+Arg = Cast->getSubExpr();
+auto CastType = Cast->getType();
+if (auto *PtrType = dyn_cast(CastType)) {
+  auto PointeeType = PtrType->getPointeeType();
+  while (auto *ET = dyn_cast(PointeeType)) {
+if (ET->isSugared())
+  PointeeType = ET->desugar();
+  }
+  if (auto *ParmType = dyn_cast(PointeeType)) {
+if (ArgList) {
+  auto ParmIndex = ParmType->getIndex();
+  auto Type = ArgList->get(ParmIndex).getAsType();
+  if (auto *RD = dyn_cast(Type)) {
+if (RD->getDecl() == ClassDecl)
+  return true;
+  }
+}
+  } else if (auto *RD = dyn_cast(PointeeType)) {
+if (RD->getDecl() == ClassDecl)
+  return true;
+  }
+}
+  } else
+break;
+}
+return false;
+  }
+
+  bool VisitStmt(const Stmt *S) { return VisitChildren(S); }
+
+  // Return false since the contents of lambda isn't necessarily executed.
+  // If it is executed, VisitCallExpr above will visit its body.
+  bool VisitLambdaExpr(const LambdaExpr *) { return false; }
+
+private:
+  const TemplateArgumentList* ArgList { nullptr };
+  const CXXRecordDecl* ClassDecl;
+  llvm::DenseSet VisitedBody;
+};
+
 class RefCntblBaseVirtualDtorChecker
 : public Checker> {
 private:
@@ -91,8 +2

[clang] [llvm] [AArch64][TargetParser] move CPUInfo into tablegen [NFC] (PR #92145)

2024-05-17 Thread Tomas Matheson via cfe-commits


@@ -812,178 +812,270 @@ def ProcessorFeatures {
   list Generic = [FeatureFPARMv8, FeatureNEON, FeatureETE];
 }
 
+class AArch64Processor<
+  string n,
+  Architecture64 arch,
+  SchedMachineModel m,
+  list f,
+  list tunef,
+  list default_extensions
+> : ProcessorModel {
+  // The base architecture for this processor.
+  Architecture64 Arch = arch;
+
+  // The set of extensions enabled by default for this processor.
+  list DefaultExts = default_extensions;
+}
+
 // FeatureFuseAdrpAdd is enabled under Generic to allow linker merging
 // optimizations.
 def : ProcessorModel<"generic", CortexA510Model, ProcessorFeatures.Generic,
  [FeatureFuseAES, FeatureFuseAdrpAdd, 
FeaturePostRAScheduler,
   FeatureEnableSelectOptimize]>;
-def : ProcessorModel<"cortex-a35", CortexA53Model, ProcessorFeatures.A53,
- [TuneA35]>;
-def : ProcessorModel<"cortex-a34", CortexA53Model, ProcessorFeatures.A53,
- [TuneA35]>;
-def : ProcessorModel<"cortex-a53", CortexA53Model, ProcessorFeatures.A53,
- [TuneA53]>;
-def : ProcessorModel<"cortex-a55", CortexA55Model, ProcessorFeatures.A55,
- [TuneA55]>;
-def : ProcessorModel<"cortex-a510", CortexA510Model, ProcessorFeatures.A510,
- [TuneA510]>;
-def : ProcessorModel<"cortex-a520", CortexA510Model, ProcessorFeatures.A520,
- [TuneA520]>;
-def : ProcessorModel<"cortex-a520ae", CortexA510Model, 
ProcessorFeatures.A520AE,
- [TuneA520AE]>;
-def : ProcessorModel<"cortex-a57", CortexA57Model, ProcessorFeatures.A53,
- [TuneA57]>;
-def : ProcessorModel<"cortex-a65", CortexA53Model, ProcessorFeatures.A65,
- [TuneA65]>;
-def : ProcessorModel<"cortex-a65ae", CortexA53Model, ProcessorFeatures.A65,
- [TuneA65]>;
-def : ProcessorModel<"cortex-a72", CortexA57Model, ProcessorFeatures.A53,
- [TuneA72]>;
-def : ProcessorModel<"cortex-a73", CortexA57Model, ProcessorFeatures.A53,
- [TuneA73]>;
-def : ProcessorModel<"cortex-a75", CortexA57Model, ProcessorFeatures.A55,
- [TuneA75]>;
-def : ProcessorModel<"cortex-a76", CortexA57Model, ProcessorFeatures.A76,
- [TuneA76]>;
-def : ProcessorModel<"cortex-a76ae", CortexA57Model, ProcessorFeatures.A76,
- [TuneA76]>;
-def : ProcessorModel<"cortex-a77", CortexA57Model, ProcessorFeatures.A77,
- [TuneA77]>;
-def : ProcessorModel<"cortex-a78", CortexA57Model, ProcessorFeatures.A78,
- [TuneA78]>;
-def : ProcessorModel<"cortex-a78ae", CortexA57Model, ProcessorFeatures.A78AE,
- [TuneA78AE]>;
-def : ProcessorModel<"cortex-a78c", CortexA57Model, ProcessorFeatures.A78C,
- [TuneA78C]>;
-def : ProcessorModel<"cortex-a710", NeoverseN2Model, ProcessorFeatures.A710,
- [TuneA710]>;
-def : ProcessorModel<"cortex-a715", NeoverseN2Model, ProcessorFeatures.A715,
- [TuneA715]>;
-def : ProcessorModel<"cortex-a720", NeoverseN2Model, ProcessorFeatures.A720,
- [TuneA720]>;
-def : ProcessorModel<"cortex-a720ae", NeoverseN2Model, 
ProcessorFeatures.A720AE,
- [TuneA720AE]>;
-def : ProcessorModel<"cortex-r82", CortexA55Model, ProcessorFeatures.R82,
- [TuneR82]>;
-def : ProcessorModel<"cortex-r82ae", CortexA55Model, ProcessorFeatures.R82AE,
- [TuneR82AE]>;
-def : ProcessorModel<"cortex-x1", CortexA57Model, ProcessorFeatures.X1,
- [TuneX1]>;
-def : ProcessorModel<"cortex-x1c", CortexA57Model, ProcessorFeatures.X1C,
- [TuneX1]>;
-def : ProcessorModel<"cortex-x2", NeoverseN2Model, ProcessorFeatures.X2,
- [TuneX2]>;
-def : ProcessorModel<"cortex-x3", NeoverseN2Model, ProcessorFeatures.X3,
- [TuneX3]>;
-def : ProcessorModel<"cortex-x4", NeoverseN2Model, ProcessorFeatures.X4,
- [TuneX4]>;
-def : ProcessorModel<"neoverse-e1", CortexA53Model,
- ProcessorFeatures.NeoverseE1, [TuneNeoverseE1]>;
-def : ProcessorModel<"neoverse-n1", NeoverseN1Model,
- ProcessorFeatures.NeoverseN1, [TuneNeoverseN1]>;
-def : ProcessorModel<"neoverse-n2", NeoverseN2Model,
- ProcessorFeatures.NeoverseN2, [TuneNeoverseN2]>;
-def : ProcessorModel<"neoverse-n3", NeoverseN2Model,
- ProcessorFeatures.NeoverseN3, [TuneNeoverseN3]>;
-def : ProcessorModel<"neoverse-512tvb", NeoverseV1Model,
- ProcessorFeatures.Neoverse512TVB, [TuneNeoverse512TVB]>;
-def : ProcessorModel<"neoverse-v1", NeoverseV1Model,
- ProcessorFeatures.NeoverseV1, [TuneNeoverseV1]>;
-def : ProcessorModel<"neoverse-v2", NeoverseV2Model,
- ProcessorFeatures.NeoverseV2, [TuneNeoverseV2]>

[clang] 7a67479 - [clang][ExtractAPI] Correctly generate declaration fragments for non-type template parameters (#91958)

2024-05-17 Thread via cfe-commits

Author: Daniel Grumberg
Date: 2024-05-17T10:33:31+01:00
New Revision: 7a6747939218efbe3b1d2cc0f896dfa97c0ff40f

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

LOG: [clang][ExtractAPI] Correctly generate declaration fragments for non-type 
template parameters (#91958)

Previously we only generated declaration fragments for template type
parameters/arguments, this adds supports for most other possible
template parameters/arguments.

rdar://127732598

Added: 
clang/test/ExtractAPI/non_type_template.cpp

Modified: 
clang/lib/ExtractAPI/DeclarationFragments.cpp
clang/test/ExtractAPI/class_template.cpp
clang/test/ExtractAPI/class_template_param_inheritance.cpp
clang/test/ExtractAPI/class_template_partial_spec.cpp
clang/test/ExtractAPI/class_template_spec.cpp
clang/test/ExtractAPI/concept.cpp
clang/test/ExtractAPI/field_template.cpp
clang/test/ExtractAPI/global_func_template.cpp
clang/test/ExtractAPI/global_func_template_spec.cpp
clang/test/ExtractAPI/global_var_template.cpp
clang/test/ExtractAPI/global_var_template_partial_spec.cpp
clang/test/ExtractAPI/global_var_template_spec.cpp
clang/test/ExtractAPI/method_template.cpp
clang/test/ExtractAPI/method_template_spec.cpp

Removed: 




diff  --git a/clang/lib/ExtractAPI/DeclarationFragments.cpp 
b/clang/lib/ExtractAPI/DeclarationFragments.cpp
index 9bf7950888dbb..98b9343924a83 100644
--- a/clang/lib/ExtractAPI/DeclarationFragments.cpp
+++ b/clang/lib/ExtractAPI/DeclarationFragments.cpp
@@ -12,13 +12,19 @@
 
//===--===//
 
 #include "clang/ExtractAPI/DeclarationFragments.h"
+#include "clang/AST/ASTFwd.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/TemplateBase.h"
+#include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/ExtractAPI/TypedefUnderlyingTypeResolver.h"
 #include "clang/Index/USRGeneration.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
 
 using namespace clang::extractapi;
 using namespace llvm;
@@ -386,6 +392,25 @@ DeclarationFragments 
DeclarationFragmentsBuilder::getFragmentsForType(
 getFragmentsForType(AT->getElementType(), Context, After));
   }
 
+  if (const TemplateSpecializationType *TemplSpecTy =
+  dyn_cast(T)) {
+const auto TemplName = TemplSpecTy->getTemplateName();
+std::string Str;
+raw_string_ostream Stream(Str);
+TemplName.print(Stream, Context.getPrintingPolicy(),
+TemplateName::Qualified::AsWritten);
+SmallString<64> USR("");
+if (const auto *TemplDecl = TemplName.getAsTemplateDecl())
+  index::generateUSRForDecl(TemplDecl, USR);
+
+return Fragments
+.append(Str, DeclarationFragments::FragmentKind::TypeIdentifier, USR)
+.append("<", DeclarationFragments::FragmentKind::Text)
+.append(getFragmentsForTemplateArguments(
+TemplSpecTy->template_arguments(), Context, std::nullopt))
+.append(">", DeclarationFragments::FragmentKind::Text);
+  }
+
   // Everything we care about has been handled now, reduce to the canonical
   // unqualified base type.
   QualType Base = T->getCanonicalTypeUnqualified();
@@ -650,7 +675,6 @@ DeclarationFragments 
DeclarationFragmentsBuilder::getFragmentsForBlock(
 DeclarationFragments
 DeclarationFragmentsBuilder::getFragmentsForFunction(const FunctionDecl *Func) 
{
   DeclarationFragments Fragments;
-  // FIXME: Handle template specialization
   switch (Func->getStorageClass()) {
   case SC_None:
   case SC_PrivateExtern:
@@ -952,27 +976,84 @@ 
DeclarationFragmentsBuilder::getFragmentsForTemplateParameters(
   Fragments.append(",", DeclarationFragments::FragmentKind::Text)
   .appendSpace();
 
-const auto *TemplateParam =
-dyn_cast(ParameterArray[i]);
-if (!TemplateParam)
-  continue;
-if (TemplateParam->hasTypeConstraint())
-  Fragments.append(TemplateParam->getTypeConstraint()
-   ->getNamedConcept()
-   ->getName()
-   .str(),
-   DeclarationFragments::FragmentKind::TypeIdentifier);
-else if (TemplateParam->wasDeclaredWithTypename())
-  Fragments.append("typename", 
DeclarationFragments::FragmentKind::Keyword);
-else
-  Fragments.append("class", DeclarationFragments::FragmentKind::Keyword);
-
-if (TemplateParam->isParameterPack())
-  Fragments.append("...", DeclarationFragments::FragmentKind::Text);
-
-Fragments.appendSpace().append(
-TemplateParam->getName(),
-DeclarationFragments::FragmentKind::GenericP

[clang] [clang][ExtractAPI] Correctly generate declaration fragments for non-type template parameters (PR #91958)

2024-05-17 Thread Daniel Grumberg via cfe-commits

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


[clang] [llvm] [AArch64][TargetParser] move CPUInfo into tablegen [NFC] (PR #92145)

2024-05-17 Thread Tomas Matheson via cfe-commits

tmatheson-arm wrote:

Summary of the PR after the recent changes:

- `CPUInfo` in `TargetParser` is now generated from `AArch64Processors.td`
- The printed order of CPUs has changed, due to definition order.
- `+perfmon` now appears in `target-features` for some CPUs. This is because 
`FeaturePerfMon` was in the list of `SubtargetFeature`s for the CPU but not in 
the `TargetParser` `CPUInfo`, which is now generated from the list of features. 
This is reflected in `TargetParserTest.cpp`.
- The same applies to `+sb` and `+ssbs` in the case of `apple-m1`, `+complxnum` 
for `a64fx`, `+wfxt` for `ampere1b`.
- References to `FeatureCrypto` in CPU feature lists were replaced by 
`FeatureSHA2` + `FeatureAES`. This prevents `+crypto` being output by 
`TargetParser`.
- Made "generic" a real CPU in AArch64Processors.td. This removes some special 
treatment in code, and makes "generic" appear in the list of CPUs. It also 
means some `"target-features"="+fp-armv8,+neon"` appear for the generic CPU. 
`NumAArch64CPUArchs` increases.
- Some CPUs specified AEK_NONE as an extension. This looks like a mistake, 
removed.

The `AArch64Processor` class still takes a top-level reference to an 
architecture.

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


[clang] [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (PR #91965)

2024-05-17 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov updated 
https://github.com/llvm/llvm-project/pull/91965

>From 2e081d74e87ad14fdf6d950d3e3da6bed07ee723 Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Mon, 13 May 2024 14:27:51 +0100
Subject: [PATCH] [Clang][AArch64][SVE] Allow write to SVE vector elements
 using the subscript operator

The patch at https://reviews.llvm.org/D122732 introduced using
the array subscript operator for SVE vectors, however it also
causes an ICE when the subscripting expression is used
as an lvalue.

This patches fixes the error. Lvalue subscripting expressions are
emitted as LLVM IR `insertvector`.
---
 clang/lib/CodeGen/CGExpr.cpp  |  6 --
 clang/lib/Sema/SemaExpr.cpp   |  4 +++-
 clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c | 10 ++
 3 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index d96c7bb1e5682..37b8b723937b7 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4180,8 +4180,10 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const 
ArraySubscriptExpr *E,
 
   // If the base is a vector type, then we are forming a vector element lvalue
   // with this subscript.
-  if (E->getBase()->getType()->isVectorType() &&
-  !isa(E->getBase())) {
+  if (QualType BaseTy = E->getBase()->getType();
+  (BaseTy->isVectorType() && !isa(E->getBase())) ||
+  (BaseTy->isBuiltinType() &&
+   BaseTy->getAs()->isSveVLSBuiltinType())) {
 // Emit the vector as an lvalue to get its address.
 LValue LHS = EmitLValue(E->getBase());
 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index bb4b116fd73ca..fd16be30bd848 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5383,7 +5383,9 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
   }
 
   // Perform default conversions.
-  if (!LHSExp->getType()->getAs()) {
+  if (!LHSExp->getType()->getAs() &&
+  !(LHSExp->getType()->isBuiltinType() &&
+LHSExp->getType()->getAs()->isSveVLSBuiltinType())) {
 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
 if (Result.isInvalid())
   return ExprError();
diff --git a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c 
b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
index fb60c6d100ce6..634423765c4c3 100644
--- a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
+++ b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
@@ -88,3 +88,13 @@ float subscript_float32(svfloat32_t a, size_t b) {
 double subscript_float64(svfloat64_t a, size_t b) {
   return a[b];
 }
+
+// CHECK-LABEL: @subscript_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  
[[A:%.*]], float 1.00e+00, i64 [[B:%.*]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_write_float32(svfloat32_t a, size_t b) {
+  a[b] = 1.0f;
+  return a;
+}

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


[clang] [clang][ExtractAPI] Remove symbols defined in categories to external types unless requested (PR #92522)

2024-05-17 Thread Daniel Grumberg via cfe-commits

https://github.com/daniel-grumberg created 
https://github.com/llvm/llvm-project/pull/92522

rdar://128259890

>From 7650c18c883bb14e5a4b17d6b6d61297f2fa3c44 Mon Sep 17 00:00:00 2001
From: Daniel Grumberg 
Date: Fri, 17 May 2024 11:58:18 +0100
Subject: [PATCH] [clang][ExtractAPI] Remove symbols defined in categories to
 external types unless requested

rdar://128259890
---
 .../Serialization/SymbolGraphSerializer.h  |  9 +++--
 .../Serialization/SymbolGraphSerializer.cpp| 11 +--
 clang/test/ExtractAPI/objc_external_category.m | 18 +-
 3 files changed, 29 insertions(+), 9 deletions(-)

diff --git 
a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h 
b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
index 724b087f7aea9..27e9167ca1ad0 100644
--- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
+++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
@@ -102,6 +102,8 @@ class SymbolGraphSerializer : public 
APISetVisitor {
 
   const bool EmitSymbolLabelsForTesting = false;
 
+  const bool SkipSymbolsInCategoriesToExternalTypes = false;
+
   /// The object instantiated by the last call to serializeAPIRecord.
   Object *CurrentSymbol = nullptr;
 
@@ -271,10 +273,13 @@ class SymbolGraphSerializer : public 
APISetVisitor {
 
   SymbolGraphSerializer(const APISet &API, const APIIgnoresList &IgnoresList,
 bool EmitSymbolLabelsForTesting = false,
-bool ForceEmitToMainModule = false)
+bool ForceEmitToMainModule = false,
+bool SkipSymbolsInCategoriesToExternalTypes = false)
   : Base(API), ForceEmitToMainModule(ForceEmitToMainModule),
 IgnoresList(IgnoresList),
-EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting) {}
+EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting),
+SkipSymbolsInCategoriesToExternalTypes(
+SkipSymbolsInCategoriesToExternalTypes) {}
 };
 
 } // namespace extractapi
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index c16d4623f115d..08e711cafae28 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -925,6 +925,10 @@ bool SymbolGraphSerializer::visitObjCInterfaceRecord(
 
 bool SymbolGraphSerializer::traverseObjCCategoryRecord(
 const ObjCCategoryRecord *Record) {
+  if (SkipSymbolsInCategoriesToExternalTypes &&
+  !API.findRecordForUSR(Record->Interface.USR))
+return true;
+
   auto *CurrentModule = ModuleForCurrentSymbol;
   if (Record->isExtendingExternalModule())
 ModuleForCurrentSymbol = &ExtendedModules[Record->Interface.Source];
@@ -1040,8 +1044,11 @@ void SymbolGraphSerializer::serializeGraphToStream(
 void SymbolGraphSerializer::serializeMainSymbolGraph(
 raw_ostream &OS, const APISet &API, const APIIgnoresList &IgnoresList,
 SymbolGraphSerializerOption Options) {
-  SymbolGraphSerializer Serializer(API, IgnoresList,
-   Options.EmitSymbolLabelsForTesting);
+  SymbolGraphSerializer Serializer(
+  API, IgnoresList, Options.EmitSymbolLabelsForTesting,
+  /*ForceEmitToMainModule=*/true,
+  /*SkipSymbolsInCategoriesToExternalTypes=*/true);
+
   Serializer.traverseAPISet();
   Serializer.serializeGraphToStream(OS, Options, API.ProductName,
 std::move(Serializer.MainModule));
diff --git a/clang/test/ExtractAPI/objc_external_category.m 
b/clang/test/ExtractAPI/objc_external_category.m
index 47e699cb91c0e..8afc92489f28b 100644
--- a/clang/test/ExtractAPI/objc_external_category.m
+++ b/clang/test/ExtractAPI/objc_external_category.m
@@ -4,6 +4,9 @@
 // RUN:   --emit-extension-symbol-graphs --symbol-graph-dir=%t/symbols \
 // RUN:   --product-name=Module -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules-cache \
 // RUN:   -triple arm64-apple-macosx -x objective-c-header %t/input.h -verify
+// RUN: %clang_cc1 -extract-api --pretty-sgf 
--emit-sgf-symbol-labels-for-testing \
+// RUN:   --product-name=Module -o %t/ModuleNoExt.symbols.json -triple 
arm64-apple-macosx \
+// RUN:   -x objective-c-header %t/input.h
 
 //--- input.h
 #include "ExternalModule.h"
@@ -28,15 +31,20 @@ @interface ExtInterface
 header "ExternalModule.h"
 }
 
+// Main symbol graph from the build with extension SGFs
 // RUN: FileCheck %s --input-file  %t/symbols/Module.symbols.json 
--check-prefix MOD
+
 // MOD-NOT: "!testRelLabel": "memberOf $ c:objc(cs)ExtInterface(py)Property $ 
c:objc(cs)ExtInterface"
 // MOD-NOT: "!testRelLabel": "memberOf $ 
c:objc(cs)ExtInterface(im)InstanceMethod $ c:objc(cs)ExtInterface"
 // MOD-NOT: "!testRelLabel": "memberOf $ c:objc(cs)ExtInterface(cm)ClassMethod 
$ c:objc(cs)ExtInterface"
-// MOD-NOT: "!testLabel": "c:objc(cs)ExtInterface(py)P

[clang] [clang][ExtractAPI] Remove symbols defined in categories to external types unless requested (PR #92522)

2024-05-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Daniel Grumberg (daniel-grumberg)


Changes

rdar://128259890

---
Full diff: https://github.com/llvm/llvm-project/pull/92522.diff


3 Files Affected:

- (modified) 
clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h (+7-2) 
- (modified) clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
(+9-2) 
- (modified) clang/test/ExtractAPI/objc_external_category.m (+13-5) 


``diff
diff --git 
a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h 
b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
index 724b087f7aea9..27e9167ca1ad0 100644
--- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
+++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
@@ -102,6 +102,8 @@ class SymbolGraphSerializer : public 
APISetVisitor {
 
   const bool EmitSymbolLabelsForTesting = false;
 
+  const bool SkipSymbolsInCategoriesToExternalTypes = false;
+
   /// The object instantiated by the last call to serializeAPIRecord.
   Object *CurrentSymbol = nullptr;
 
@@ -271,10 +273,13 @@ class SymbolGraphSerializer : public 
APISetVisitor {
 
   SymbolGraphSerializer(const APISet &API, const APIIgnoresList &IgnoresList,
 bool EmitSymbolLabelsForTesting = false,
-bool ForceEmitToMainModule = false)
+bool ForceEmitToMainModule = false,
+bool SkipSymbolsInCategoriesToExternalTypes = false)
   : Base(API), ForceEmitToMainModule(ForceEmitToMainModule),
 IgnoresList(IgnoresList),
-EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting) {}
+EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting),
+SkipSymbolsInCategoriesToExternalTypes(
+SkipSymbolsInCategoriesToExternalTypes) {}
 };
 
 } // namespace extractapi
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index c16d4623f115d..08e711cafae28 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -925,6 +925,10 @@ bool SymbolGraphSerializer::visitObjCInterfaceRecord(
 
 bool SymbolGraphSerializer::traverseObjCCategoryRecord(
 const ObjCCategoryRecord *Record) {
+  if (SkipSymbolsInCategoriesToExternalTypes &&
+  !API.findRecordForUSR(Record->Interface.USR))
+return true;
+
   auto *CurrentModule = ModuleForCurrentSymbol;
   if (Record->isExtendingExternalModule())
 ModuleForCurrentSymbol = &ExtendedModules[Record->Interface.Source];
@@ -1040,8 +1044,11 @@ void SymbolGraphSerializer::serializeGraphToStream(
 void SymbolGraphSerializer::serializeMainSymbolGraph(
 raw_ostream &OS, const APISet &API, const APIIgnoresList &IgnoresList,
 SymbolGraphSerializerOption Options) {
-  SymbolGraphSerializer Serializer(API, IgnoresList,
-   Options.EmitSymbolLabelsForTesting);
+  SymbolGraphSerializer Serializer(
+  API, IgnoresList, Options.EmitSymbolLabelsForTesting,
+  /*ForceEmitToMainModule=*/true,
+  /*SkipSymbolsInCategoriesToExternalTypes=*/true);
+
   Serializer.traverseAPISet();
   Serializer.serializeGraphToStream(OS, Options, API.ProductName,
 std::move(Serializer.MainModule));
diff --git a/clang/test/ExtractAPI/objc_external_category.m 
b/clang/test/ExtractAPI/objc_external_category.m
index 47e699cb91c0e..8afc92489f28b 100644
--- a/clang/test/ExtractAPI/objc_external_category.m
+++ b/clang/test/ExtractAPI/objc_external_category.m
@@ -4,6 +4,9 @@
 // RUN:   --emit-extension-symbol-graphs --symbol-graph-dir=%t/symbols \
 // RUN:   --product-name=Module -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules-cache \
 // RUN:   -triple arm64-apple-macosx -x objective-c-header %t/input.h -verify
+// RUN: %clang_cc1 -extract-api --pretty-sgf 
--emit-sgf-symbol-labels-for-testing \
+// RUN:   --product-name=Module -o %t/ModuleNoExt.symbols.json -triple 
arm64-apple-macosx \
+// RUN:   -x objective-c-header %t/input.h
 
 //--- input.h
 #include "ExternalModule.h"
@@ -28,15 +31,20 @@ @interface ExtInterface
 header "ExternalModule.h"
 }
 
+// Main symbol graph from the build with extension SGFs
 // RUN: FileCheck %s --input-file  %t/symbols/Module.symbols.json 
--check-prefix MOD
+
 // MOD-NOT: "!testRelLabel": "memberOf $ c:objc(cs)ExtInterface(py)Property $ 
c:objc(cs)ExtInterface"
 // MOD-NOT: "!testRelLabel": "memberOf $ 
c:objc(cs)ExtInterface(im)InstanceMethod $ c:objc(cs)ExtInterface"
 // MOD-NOT: "!testRelLabel": "memberOf $ c:objc(cs)ExtInterface(cm)ClassMethod 
$ c:objc(cs)ExtInterface"
-// MOD-NOT: "!testLabel": "c:objc(cs)ExtInterface(py)Property"
-// MOD-NOT: "!testLabel": "c:objc(cs)ExtInterface(im)InstanceMethod"
-// MOD-NOT: "!testLabel": "c:objc(cs)ExtInterface(cm)ClassMethod"
-// MOD-NOT: "!

[clang] 58bad28 - [analyzer][NFC] Require explicit matching mode for CallDescriptions (#92454)

2024-05-17 Thread via cfe-commits

Author: Donát Nagy
Date: 2024-05-17T13:08:45+02:00
New Revision: 58bad2862cf136f9483eb005bbfa6915d459b46d

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

LOG: [analyzer][NFC] Require explicit matching mode for CallDescriptions 
(#92454)

This commit deletes the "simple" constructor of `CallDescription` which
did not require a `CallDescription::Mode` argument and always used the
"wildcard" mode `CDM::Unspecified`.

A few months ago, this vague matching mode was used by many checkers,
which caused bugs like https://github.com/llvm/llvm-project/issues/81597
and https://github.com/llvm/llvm-project/issues/88181. Since then, my
commits improved the available matching modes and ensured that all
checkers explicitly specify the right matching mode.

After those commits, the only remaining references to the "simple"
constructor were some unit tests; this commit updates them to use an
explicitly specified matching mode (often `CDM::SimpleFunc`).

The mode `CDM::Unspecified` was not deleted in this commit because it's
still a reasonable choice in `GenericTaintChecker` and a few unit tests.

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp
clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
clang/unittests/StaticAnalyzer/FalsePositiveRefutationBRVisitorTest.cpp
clang/unittests/StaticAnalyzer/MemRegionDescriptiveNameTest.cpp
clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index ccfe8d47c290b..a99c11766f110 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -56,9 +56,10 @@ class CallDescription {
 /// overloaded operator, a constructor or a destructor).
 CXXMethod,
 
-/// Match any CallEvent that is not an ObjCMethodCall.
-/// FIXME: Previously this was the default behavior of CallDescription, but
-/// its use should be replaced by a more specific mode almost everywhere.
+/// Match any CallEvent that is not an ObjCMethodCall. This should not be
+/// used when the checker looks for a concrete function (and knows whether
+/// it is a method); but GenericTaintChecker uses this mode to match
+/// functions whose name was configured by the user.
 Unspecified,
 
 /// FIXME: Add support for ObjCMethodCall events (I'm not adding it because
@@ -100,13 +101,6 @@ class CallDescription {
   MaybeCount RequiredArgs = std::nullopt,
   MaybeCount RequiredParams = std::nullopt);
 
-  /// Construct a CallDescription with default flags.
-  CallDescription(ArrayRef QualifiedName,
-  MaybeCount RequiredArgs = std::nullopt,
-  MaybeCount RequiredParams = std::nullopt);
-
-  CallDescription(std::nullptr_t) = delete;
-
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 0bb0fe66e54ff..cd23b381f879a 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -48,13 +48,6 @@ ento::CallDescription::CallDescription(Mode MatchAs,
   [](StringRef From) { return From.str(); });
 }
 
-/// Construct a CallDescription with default flags.
-ento::CallDescription::CallDescription(ArrayRef QualifiedName,
-   MaybeCount RequiredArgs /*= None*/,
-   MaybeCount RequiredParams /*= None*/)
-: CallDescription(Mode::Unspecified, QualifiedName, RequiredArgs,
-  RequiredParams) {}
-
 bool ento::CallDescription::matches(const CallEvent &Call) const {
   // FIXME: Add ObjC Message support.
   if (Call.getKind() == CE_ObjCMessage)

diff  --git a/clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp 
b/clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
index 5f562b1c98b0e..70a58026da95f 100644
--- a/clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
+++ b/clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
@@ -33,11 +33,13 @@ class InterestingnessTestChecker : public 
Checker {
const CallEvent &, CheckerContext &)>;
 
   CallDe

[clang] [analyzer][NFC] Require explicit matching mode for CallDescriptions (PR #92454)

2024-05-17 Thread Donát Nagy via cfe-commits

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


[clang] [clang] Implement a bitwise_copyable builtin type trait. (PR #86512)

2024-05-17 Thread Ilya Biryukov via cfe-commits


@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+// Scalar types are bitwise clonable.
+static_assert(__is_bitwise_cloneable(int));
+static_assert(__is_bitwise_cloneable(int*));
+// array
+static_assert(__is_bitwise_cloneable(int[10]));
+
+// non-scalar types.
+static_assert(!__is_bitwise_cloneable(int&));
+
+
+struct Forward; // expected-note 2{{forward declaration of 'Forward'}}
+static_assert(!__is_bitwise_cloneable(Forward)); // expected-error 
{{incomplete type 'Forward' used in type trait expression}}
+
+struct Foo { int a; };
+static_assert(__is_bitwise_cloneable(Foo));
+
+struct DynamicClass { virtual int Foo(); };
+static_assert(__is_bitwise_cloneable(DynamicClass));
+
+struct Bar { int& b; }; // trivially copyable
+static_assert(__is_trivially_copyable(Bar));
+static_assert(__is_bitwise_cloneable(Bar));

ilya-biryukov wrote:

But the reference member in `Bar` does not stop it from being bitwise-cloneable.
We should make up our mind about it: do reference members stop the type from 
being bitwise-cloneable or not?

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


[clang] [clang][Sema] Warn consecutive builtin comparisons in an expression (PR #92200)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -215,3 +215,10 @@ namespace PR20735 {
 // fix-it:"{{.*}}":{[[@LINE-9]]:20-[[@LINE-9]]:20}:")"
   }
 }
+
+void consecutive_builtin_compare(int x, int y, int z) {
+  (void)(x < y < z);  // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x < y > z);  // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x < y <= z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x <= y > z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}

AaronBallman wrote:

> I don't have the capacity to further make clang diagnose case 2 but not case 
> 3.
> I added a TODO note at the bottom of the test lines for now.

SGTM!

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


[clang] [clang][Sema] Warn consecutive builtin comparisons in an expression (PR #92200)

2024-05-17 Thread Aaron Ballman via cfe-commits

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


[clang] [clang][Sema] Warn consecutive builtin comparisons in an expression (PR #92200)

2024-05-17 Thread Aaron Ballman via cfe-commits

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

LGTM aside from a small nit with the release notes.

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


[clang] [clang][Sema] Warn consecutive builtin comparisons in an expression (PR #92200)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -487,6 +487,9 @@ Improvements to Clang's diagnostics
}
  };
 
+- Clang emits a ``-Wparentheses`` warning for expressions with consecutive 
comparisons like ``x < y < z``.
+  It was made a ``-Wparentheses`` warning to be consistent with gcc.

AaronBallman wrote:

```suggestion
- Clang emits a ``-Wparentheses`` warning for expressions with consecutive 
comparisons like ``x < y < z``.
  Fixes #GH20456.
```

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


[clang] [clang-tools-extra] [compiler-rt] [lldb] [llvm] [mlir] [openmp] [polly] fix(python): fix comparison to None (PR #91857)

2024-05-17 Thread Oleksandr Alex Zinenko via cfe-commits

ftynse wrote:

> 10 separate commits/PRs for the same exact sed costs more in commit noise 
> (and effort on the part of @e-kwsm) than one solid, patient, review here

Not unless you subscribe only to a subproject. FWIW, I'm not comfortable 
blanket approving changes, however trivial, to subprojects I'm not actively 
working on, and I suspect most folks here are not. Subprojects may have some 
ongoing work that will be disrupted or reasons why they chose the suboptimal 
implementation.

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits

https://github.com/yronglin created 
https://github.com/llvm/llvm-project/pull/92527

This PR reapply https://github.com/llvm/llvm-project/pull/87933

>From 433df06e3a946916264337bafd0af2028ba70e9d Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 17 May 2024 19:28:04 +0800
Subject: [PATCH] [Clang][CWG1815] Support lifetime extension of temporary
 created by aggregate initialization using a default member initializer

Signed-off-by: yronglin 
---
 .../clang/Basic/DiagnosticSemaKinds.td|  6 --
 clang/lib/Sema/SemaExpr.cpp   | 31 ++--
 clang/lib/Sema/SemaExprCXX.cpp|  3 -
 clang/lib/Sema/SemaInit.cpp   | 19 +
 clang/lib/Sema/TreeTransform.h| 12 ++-
 clang/test/AST/ast-dump-default-init-json.cpp |  6 +-
 clang/test/AST/ast-dump-default-init.cpp  |  2 +-
 .../Analysis/lifetime-extended-regions.cpp|  9 ++-
 clang/test/CXX/drs/cwg16xx.cpp|  2 -
 clang/test/CXX/drs/cwg18xx.cpp| 25 +--
 clang/test/CXX/special/class.temporary/p6.cpp | 34 +
 clang/test/SemaCXX/constexpr-default-arg.cpp  |  4 +-
 .../cxx11-default-member-initializers.cpp | 74 +++
 clang/test/SemaCXX/eval-crashes.cpp   |  6 +-
 clang/www/cxx_dr_status.html  |  2 +-
 15 files changed, 171 insertions(+), 64 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9372c862a36cb..9680efc4951aa 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10041,12 +10041,6 @@ def warn_new_dangling_initializer_list : Warning<
   "the allocated initializer list}0 "
   "will be destroyed at the end of the full-expression">,
   InGroup;
-def warn_unsupported_lifetime_extension : Warning<
-  "lifetime extension of "
-  "%select{temporary|backing array of initializer list}0 created "
-  "by aggregate initialization using a default member initializer "
-  "is not yet supported; lifetime of %select{temporary|backing array}0 "
-  "will end at the end of the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e0aae6333e1a1..95ed15b9c2928 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5621,10 +5621,9 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation 
CallLoc,
 Res = Immediate.TransformInitializer(Param->getInit(),
  /*NotCopy=*/false);
   });
-  if (Res.isInvalid())
-return ExprError();
-  Res = ConvertParamDefaultArgument(Param, Res.get(),
-Res.get()->getBeginLoc());
+  if (Res.isUsable())
+Res = ConvertParamDefaultArgument(Param, Res.get(),
+  Res.get()->getBeginLoc());
   if (Res.isInvalid())
 return ExprError();
   Init = Res.get();
@@ -5660,7 +5659,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   Expr *Init = nullptr;
 
   bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
-
+  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
   EnterExpressionEvaluationContext EvalContext(
   *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
 
@@ -5695,19 +5694,35 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+
+  // CWG1815
+  // Support lifetime extension of temporary created by aggregate
+  // initialization using a default member initializer. We should always 
rebuild
+  // the initializer if it contains any temporaries (if the initializer
+  // expression is an ExprWithCleanups). Then make sure the normal lifetime
+  // extension code recurses into the default initializer and does lifetime
+  // extension when warranted.
+  bool ContainsAnyTemporaries =
+  isa_and_present(Field->getInClassInitializer());
+  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
+  ContainsAnyTemporaries) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
-
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
+
+// Rebuild CXXDefaultInitExpr might cause diagnostics

[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (yronglin)


Changes

This PR reapply https://github.com/llvm/llvm-project/pull/87933

---
Full diff: https://github.com/llvm/llvm-project/pull/92527.diff


15 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (-6) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+23-8) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (-3) 
- (modified) clang/lib/Sema/SemaInit.cpp (+1-18) 
- (modified) clang/lib/Sema/TreeTransform.h (+8-4) 
- (modified) clang/test/AST/ast-dump-default-init-json.cpp (+3-3) 
- (modified) clang/test/AST/ast-dump-default-init.cpp (+1-1) 
- (modified) clang/test/Analysis/lifetime-extended-regions.cpp (+5-4) 
- (modified) clang/test/CXX/drs/cwg16xx.cpp (-2) 
- (modified) clang/test/CXX/drs/cwg18xx.cpp (+17-8) 
- (modified) clang/test/CXX/special/class.temporary/p6.cpp (+34) 
- (modified) clang/test/SemaCXX/constexpr-default-arg.cpp (+2-2) 
- (modified) clang/test/SemaCXX/cxx11-default-member-initializers.cpp (+74) 
- (modified) clang/test/SemaCXX/eval-crashes.cpp (+2-4) 
- (modified) clang/www/cxx_dr_status.html (+1-1) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9372c862a36cb..9680efc4951aa 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10041,12 +10041,6 @@ def warn_new_dangling_initializer_list : Warning<
   "the allocated initializer list}0 "
   "will be destroyed at the end of the full-expression">,
   InGroup;
-def warn_unsupported_lifetime_extension : Warning<
-  "lifetime extension of "
-  "%select{temporary|backing array of initializer list}0 created "
-  "by aggregate initialization using a default member initializer "
-  "is not yet supported; lifetime of %select{temporary|backing array}0 "
-  "will end at the end of the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e0aae6333e1a1..95ed15b9c2928 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5621,10 +5621,9 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation 
CallLoc,
 Res = Immediate.TransformInitializer(Param->getInit(),
  /*NotCopy=*/false);
   });
-  if (Res.isInvalid())
-return ExprError();
-  Res = ConvertParamDefaultArgument(Param, Res.get(),
-Res.get()->getBeginLoc());
+  if (Res.isUsable())
+Res = ConvertParamDefaultArgument(Param, Res.get(),
+  Res.get()->getBeginLoc());
   if (Res.isInvalid())
 return ExprError();
   Init = Res.get();
@@ -5660,7 +5659,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   Expr *Init = nullptr;
 
   bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
-
+  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
   EnterExpressionEvaluationContext EvalContext(
   *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
 
@@ -5695,19 +5694,35 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+
+  // CWG1815
+  // Support lifetime extension of temporary created by aggregate
+  // initialization using a default member initializer. We should always 
rebuild
+  // the initializer if it contains any temporaries (if the initializer
+  // expression is an ExprWithCleanups). Then make sure the normal lifetime
+  // extension code recurses into the default initializer and does lifetime
+  // extension when warranted.
+  bool ContainsAnyTemporaries =
+  isa_and_present(Field->getInClassInitializer());
+  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
+  ContainsAnyTemporaries) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
-
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
+
+// Rebuild CXXDefaultInitExpr might cause diagnostics.
+SFINAETrap Trap(*this);
 runWithSufficientStackSpace(Loc, [&] {
   Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
/*CXXDirectInit=*/false);
 })

[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #87933)

2024-05-17 Thread via cfe-commits

yronglin wrote:

Sorry for the late reply, I found the update of comments from the email, and I 
have a new PR that fixes these problems.

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits


@@ -5695,19 +5694,35 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+
+  // CWG1815
+  // Support lifetime extension of temporary created by aggregate
+  // initialization using a default member initializer. We should always 
rebuild
+  // the initializer if it contains any temporaries (if the initializer
+  // expression is an ExprWithCleanups). Then make sure the normal lifetime
+  // extension code recurses into the default initializer and does lifetime
+  // extension when warranted.
+  bool ContainsAnyTemporaries =
+  isa_and_present(Field->getInClassInitializer());
+  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
+  ContainsAnyTemporaries) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
-
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
+
+// Rebuild CXXDefaultInitExpr might cause diagnostics.
+SFINAETrap Trap(*this);

yronglin wrote:

Should we suppress diagnostic messages? Perhaps the initializer with errors 
should not be rebuilt.

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits

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

>From 4b90d249c5b0790d624a4c1c0b80ff6fc80a70b3 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 17 May 2024 19:38:30 +0800
Subject: [PATCH] [Clang][CWG1815] Support lifetime extension of temporary
 created by aggregate initialization using a default member initializer

Signed-off-by: yronglin 
---
 .../clang/Basic/DiagnosticSemaKinds.td|  6 --
 clang/lib/Sema/SemaExpr.cpp   | 31 ++--
 clang/lib/Sema/SemaExprCXX.cpp|  3 -
 clang/lib/Sema/SemaInit.cpp   | 19 +
 clang/lib/Sema/TreeTransform.h| 12 ++-
 clang/test/AST/ast-dump-default-init-json.cpp |  6 +-
 clang/test/AST/ast-dump-default-init.cpp  |  2 +-
 .../Analysis/lifetime-extended-regions.cpp|  9 ++-
 clang/test/CXX/drs/cwg16xx.cpp|  2 -
 clang/test/CXX/drs/cwg18xx.cpp| 19 +++--
 clang/test/CXX/special/class.temporary/p6.cpp | 34 +
 clang/test/SemaCXX/constexpr-default-arg.cpp  |  4 +-
 .../cxx11-default-member-initializers.cpp | 74 +++
 clang/test/SemaCXX/eval-crashes.cpp   |  6 +-
 clang/www/cxx_dr_status.html  |  2 +-
 15 files changed, 168 insertions(+), 61 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9372c862a36cb..9680efc4951aa 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10041,12 +10041,6 @@ def warn_new_dangling_initializer_list : Warning<
   "the allocated initializer list}0 "
   "will be destroyed at the end of the full-expression">,
   InGroup;
-def warn_unsupported_lifetime_extension : Warning<
-  "lifetime extension of "
-  "%select{temporary|backing array of initializer list}0 created "
-  "by aggregate initialization using a default member initializer "
-  "is not yet supported; lifetime of %select{temporary|backing array}0 "
-  "will end at the end of the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e0aae6333e1a1..95ed15b9c2928 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5621,10 +5621,9 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation 
CallLoc,
 Res = Immediate.TransformInitializer(Param->getInit(),
  /*NotCopy=*/false);
   });
-  if (Res.isInvalid())
-return ExprError();
-  Res = ConvertParamDefaultArgument(Param, Res.get(),
-Res.get()->getBeginLoc());
+  if (Res.isUsable())
+Res = ConvertParamDefaultArgument(Param, Res.get(),
+  Res.get()->getBeginLoc());
   if (Res.isInvalid())
 return ExprError();
   Init = Res.get();
@@ -5660,7 +5659,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   Expr *Init = nullptr;
 
   bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
-
+  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
   EnterExpressionEvaluationContext EvalContext(
   *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
 
@@ -5695,19 +5694,35 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+
+  // CWG1815
+  // Support lifetime extension of temporary created by aggregate
+  // initialization using a default member initializer. We should always 
rebuild
+  // the initializer if it contains any temporaries (if the initializer
+  // expression is an ExprWithCleanups). Then make sure the normal lifetime
+  // extension code recurses into the default initializer and does lifetime
+  // extension when warranted.
+  bool ContainsAnyTemporaries =
+  isa_and_present(Field->getInClassInitializer());
+  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
+  ContainsAnyTemporaries) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
-
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
+
+// Rebuild CXXDefaultInitExpr might cause diagnostics.
+SFINAETrap Trap(*this);
 runWithSufficientStackSpace(Loc

[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits


@@ -5695,19 +5694,35 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+
+  // CWG1815
+  // Support lifetime extension of temporary created by aggregate
+  // initialization using a default member initializer. We should always 
rebuild
+  // the initializer if it contains any temporaries (if the initializer
+  // expression is an ExprWithCleanups). Then make sure the normal lifetime
+  // extension code recurses into the default initializer and does lifetime
+  // extension when warranted.
+  bool ContainsAnyTemporaries =
+  isa_and_present(Field->getInClassInitializer());
+  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
+  ContainsAnyTemporaries) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
-
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
+
+// Rebuild CXXDefaultInitExpr might cause diagnostics.
+SFINAETrap Trap(*this);

yronglin wrote:

Is there a way to detect if there is an error in the initializer? For example, 
access errors.

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

> I think the error node needs to be non-fatal.
Good point, I completely agree.

> For these applications it's more important to catch cases where malloc size 
> and index used for access are coming from "different sources", eg. one is 
> tainted and another isn't, doesn't matter which one.
I agree that we should enable the "pessimistic" handling (= report an error if 
we can't prove that the index is in bounds) for cases when the size is tainted, 
and I'm planning to create a commit that does this in `ArrayBoundCheckerV2`. 
(Previously passing a tainted value to `malloc` was an error, so this case 
simply never appeared.)

I would not emphasize "_different_ sources" in this context: a tainted index 
deserves careful handling even if the offset is also tainted. I see that this 
could produce false positives in situations like
```
char *f() {
  size_t n = get_tainted_value();
  if (!n)
return NULL; // Rule out the case when n - 1 overflows.
  char *p = (char*)malloc(n);
  p[n-1] = '\0';
  return p;
}
```
where (AFAIK) the analyzer cannot conclude that `n - 1 < n` always holds under 
the known constraints. However, I think this wouldn't be very common, and if it 
turns out to be common, then we could improve the evaluation of the comparison 
operators by handling the case of `symbol + constant <=> same symbol`.

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits


@@ -27,6 +27,80 @@ class MemInit {
   C m = s;
 };
 
+namespace std {
+typedef decltype(sizeof(int)) size_t;
+
+// libc++'s implementation
+template  class initializer_list {
+  const _E *__begin_;
+  size_t __size_;
+
+  initializer_list(const _E *__b, size_t __s) : __begin_(__b), __size_(__s) {}
+
+public:
+  typedef _E value_type;
+  typedef const _E &reference;
+  typedef const _E &const_reference;
+  typedef size_t size_type;
+
+  typedef const _E *iterator;
+  typedef const _E *const_iterator;
+
+  initializer_list() : __begin_(nullptr), __size_(0) {}
+
+  size_t size() const { return __size_; }
+  const _E *begin() const { return __begin_; }
+  const _E *end() const { return __begin_ + __size_; }
+};
+} // namespace std
+
+#if __cplusplus >= 201703L
+namespace test_rebuild {

yronglin wrote:

Add more test that from https://github.com/llvm/llvm-project/pull/87933 's 
comments.

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits


@@ -14113,12 +14120,9 @@ 
TreeTransform::TransformCXXTemporaryObjectExpr(
 return SemaRef.MaybeBindToTemporary(E);
   }
 
-  // FIXME: We should just pass E->isListInitialization(), but we're not
-  // prepared to handle list-initialization without a child InitListExpr.
   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
   return getDerived().RebuildCXXTemporaryObjectExpr(
-  T, LParenLoc, Args, E->getEndLoc(),
-  /*ListInitialization=*/LParenLoc.isInvalid());
+  T, LParenLoc, Args, E->getEndLoc(), E->isListInitialization());

yronglin wrote:

The issue in https://github.com/llvm/llvm-project/pull/87933 caused by 
`/*ListInitialization=*/LParenLoc.isInvalid()`. 

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


[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #92527)

2024-05-17 Thread via cfe-commits


@@ -14102,6 +14102,13 @@ 
TreeTransform::TransformCXXTemporaryObjectExpr(
 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
&ArgumentChanged))
   return ExprError();
+
+if (E->isListInitialization() && !E->isStdInitListInitialization()) {

yronglin wrote:

If it is list initialization, but the constructor is called, and it is not the 
case of std::initializer_list, we should recreate an InitListExpr. 
https://godbolt.org/z/K4rzxosx3

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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -9203,15 +9203,15 @@ static NamedDecl *DiagnoseInvalidRedeclaration(
 << Idx << FDParam->getType()
 << NewFD->getParamDecl(Idx - 1)->getType();
 } else if (FDisConst != NewFDisConst) {
-  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
-  << NewFDisConst << FD->getSourceRange().getEnd()
-  << (NewFDisConst
-  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
- .getConstQualifierLoc())
-  : 
FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
-   .getRParenLoc()
-   .getLocWithOffset(1),
-   " const"));
+  auto DB = SemaRef.Diag(FD->getLocation(),
+ diag::note_member_def_close_const_match)
+<< NewFDisConst << FD->getSourceRange().getEnd();
+  if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
+DB << 
FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
+ " const");
+  else if (SourceLocation ConstLoc = FTI.getConstQualifierLoc();

AaronBallman wrote:

I think that hides subtle issues; the caller should really know the difference 
between "const qualifier as written" and "semantically const".

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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -1527,20 +1527,20 @@ struct DeclaratorChunk {
 
 /// Retrieve the location of the 'const' qualifier.
 SourceLocation getConstQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getConstSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getConstSpecLoc()

AaronBallman wrote:

`DeclSpec.h` is basically used only to gather information from the parser, and 
so from that perspective, I think the `assert` makes sense. If the caller is 
asking for the location of the `const` qualifier and one wasn't written in 
source, the caller is doing something out of the ordinary.

I think the fix-it code should be guarded by a call to 
`hasMethodTypeQualifiers()` instead.

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


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

2024-05-17 Thread Zahira Ammarguellat via cfe-commits


@@ -14574,9 +14574,17 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
   default:
 return false;
 
+  case Builtin::BI__builtin_frexpl:
+// AIX library function `frexpl` has 'long double' type and not
+// PPCDoubleDouble type. To make sure we generate the right value, don't
+// constant evaluate it and instead defer to a libcall.
+if (Info.Ctx.getTargetInfo().getTriple().isPPC() &&
+(&Info.Ctx.getTargetInfo().getLongDoubleFormat() !=
+ &llvm::APFloat::PPCDoubleDouble()))
+  return false;
+LLVM_FALLTHROUGH;
   case Builtin::BI__builtin_frexp:
-  case Builtin::BI__builtin_frexpf:
-  case Builtin::BI__builtin_frexpl: {
+  case Builtin::BI__builtin_frexpf: {

zahiraam wrote:

> > With this change (special casing frexpl for AIX) the IR produced is: `call 
> > { double, i32 } @llvm.frexp.f64.i32(double 1.234500e+02)`
> > without this change the IR is: `store double 0.00e+00, ptr 
> > %returnValue, align 8`
> > This doesn't seem correct to me.
> 
> Ignoring considerations around storing to `DummyInt`, the original test code 
> was:
> 
> ```
>   returnValue = __builtin_frexpl(0.0L, &DummyInt);
> ```
> 
> I don't know where the `123.45` came from. That the result is zero for an 
> input of zero is correct; however, the constant-folding in the context of 
> that test would undermine its intent (see check that an appropriate target 
> runtime function is called).

Sorry. The output is:   `call { double, i32 } @llvm.frexp.f64.i32(double 
0.00e+00)`. That was a mistake of my part.

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] a68d20e - [clang] Implement CWG2428 "Deprecating a concept" (#92295)

2024-05-17 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-05-17T16:02:44+04:00
New Revision: a68d20e986053ec571223a9f3ead3e146a27dc82

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

LOG: [clang] Implement CWG2428 "Deprecating a concept" (#92295)

This patch allows attributes to be attached to C++20 concepts,
implementing
[CWG2428](https://cplusplus.github.io/CWG/issues/2428.html).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseTemplate.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/drs/cwg24xx.cpp
clang/test/SemaCXX/cxx-deprecated.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65d191b6161a4..40e41c940b6af 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -226,6 +226,9 @@ Resolutions to C++ Defect Reports
 - Clang now diagnoses declarative nested-name-specifiers with 
pack-index-specifiers.
   (`CWG2858: Declarative nested-name-specifiers and pack-index-specifiers 
`_).
 
+- Clang now allows attributes on concepts.
+  (`CWG2428: Deprecating a concept 
`_).
+
 - P0522 implementation is enabled by default in all language versions, and
   provisional wording for CWG2398 is implemented.
 

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 873592a2d430a..226987b975700 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2022,6 +2022,8 @@ class Sema final : public SemaBase {
   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
const NamedDecl *Callee);
 
+  void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
+
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE = nullptr,
@@ -9356,7 +9358,8 @@ class Sema final : public SemaBase {
   Decl *ActOnConceptDefinition(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
const IdentifierInfo *Name,
-   SourceLocation NameLoc, Expr *ConstraintExpr);
+   SourceLocation NameLoc, Expr *ConstraintExpr,
+   const ParsedAttributesView &Attrs);
 
   void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
 bool &AddToScope);

diff  --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index 665253a6674d2..8f841be422dd8 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -167,9 +167,13 @@ Parser::DeclGroupPtrTy 
Parser::ParseTemplateDeclarationOrSpecialization(
   LastParamListWasEmpty);
 
   // Parse the actual template declaration.
-  if (Tok.is(tok::kw_concept))
-return Actions.ConvertDeclToDeclGroup(
-ParseConceptDefinition(TemplateInfo, DeclEnd));
+  if (Tok.is(tok::kw_concept)) {
+Decl *ConceptDecl = ParseConceptDefinition(TemplateInfo, DeclEnd);
+// We need to explicitly pass ConceptDecl to ParsingDeclRAIIObject, so that
+// delayed diagnostics (e.g. warn_deprecated) have a Decl to work with.
+ParsingTemplateParams.complete(ConceptDecl);
+return Actions.ConvertDeclToDeclGroup(ConceptDecl);
+  }
 
   return ParseDeclarationAfterTemplate(
   Context, TemplateInfo, ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
@@ -316,7 +320,8 @@ Parser::ParseConceptDefinition(const ParsedTemplateInfo 
&TemplateInfo,
   const IdentifierInfo *Id = Result.Identifier;
   SourceLocation IdLoc = Result.getBeginLoc();
 
-  DiagnoseAndSkipCXX11Attributes();
+  ParsedAttributes Attrs(AttrFactory);
+  MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs);
 
   if (!TryConsumeToken(tok::equal)) {
 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
@@ -335,8 +340,8 @@ Parser::ParseConceptDefinition(const ParsedTemplateInfo 
&TemplateInfo,
   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
   Expr *ConstraintExpr = ConstraintExprResult.get();
   return Actions.ActOnConceptDefinition(getCurScope(),
-*TemplateInfo.TemplateParams,
-Id, IdLoc, ConstraintExpr);
+*TemplateInfo.TemplateParams, Id, 
IdLoc,
+ConstraintExpr, Attrs);
 }
 
 /// ParseTemplateParameters - Parses a template-parameter-list enclose

[clang] [clang] Implement CWG2428 "Deprecating a concept" (PR #92295)

2024-05-17 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang-tools-extra] [llvm] [clang-query] Remove support for srcloc output (PR #92442)

2024-05-17 Thread Aaron Ballman via cfe-commits

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

The patch makes sense to me.
I'll not repeat the existing comments, they raise relevant concerns.

It would be nice to extend some test case with a tainted malloc to see how 
those note tags play out from the generic taint checker in this context. For 
this, I'd suggest you to have a look at some taint tests where we enable the 
`text` diagnostic output.

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -48,6 +49,45 @@ void myfoo(int *p);
 void myfooint(int p);
 char *fooRetPtr(void);
 
+void t1(void) {
+  size_t size;
+  scanf("%zu", &size);
+  int *p = malloc(size); // expected-warning{{malloc is called with a tainted 
(potentially attacker controlled) value}}
+  free(p);
+}
+
+void t2(void) {
+  size_t size;
+  scanf("%zu", &size);
+  int *p = calloc(size,2); // expected-warning{{calloc is called with a 
tainted (potentially attacker controlled) value}}
+  free(p);
+}
+
+void t3(void) {
+  size_t size;
+  scanf("%zu", &size);
+  if (1024https://github.com/llvm/llvm-project/pull/92420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -1273,6 +1273,41 @@ Check for memory leaks, double free, and use-after-free 
problems. Traces memory
 .. literalinclude:: checkers/unix_malloc_example.c
 :language: c
 
+If the ``alpha.security.taint.TaintPropagation`` checker is enabled, the 
checker
+warns for cases when the ``size`` parameter of the ``malloc`` , ``calloc``,
+``realloc``, ``alloca`` is tainted (potentially attacker controlled). If an
+attacker can inject a large value as the size parameter, memory exhaustion
+denial of service attack can be carried out.
+
+The analyzer emits warning only if it cannot prove that the size parameter is
+within reasonable bounds (``<= SIZE_MAX/4``). This functionality partially
+covers the SEI Cert coding standard rule `INT04-C
+`_.
+
+You can silence this warning either by bound checking the ``size`` parameter, 
or
+by explicitly marking the ``size`` parameter as sanitized. See the
+:ref:`alpha-security-taint-TaintPropagation` checker for more details.
+
+.. code-block:: c
+
+  void t1(void) {
+size_t size;
+scanf("%zu", &size);
+int *p = malloc(size); // warn: malloc is called with a tainted 
(potentially attacker controlled) value
+free(p);
+  }
+
+  void t3(void) {
+size_t size;
+scanf("%zu", &size);
+if (1024https://github.com/llvm/llvm-project/pull/92420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -1779,18 +1790,79 @@ ProgramStateRef 
MallocChecker::MallocMemAux(CheckerContext &C,
 const CallEvent &Call,
 const Expr *SizeEx, SVal Init,
 ProgramStateRef State,
-AllocationFamily Family) {
+AllocationFamily Family) const {
   if (!State)
 return nullptr;
 
   assert(SizeEx);
   return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
 }
 
+void MallocChecker::reportTaintBug(StringRef Msg, ProgramStateRef State,
+   CheckerContext &C,
+   llvm::ArrayRef TaintedSyms,
+   AllocationFamily Family,
+   const Expr *SizeEx) const {
+  if (ExplodedNode *N = C.generateErrorNode(State)) {
+
+std::optional CheckKind =
+getCheckIfTracked(Family);
+if (!CheckKind)
+  return;
+if (!BT_TaintedAlloc[*CheckKind])
+  BT_TaintedAlloc[*CheckKind].reset(new BugType(CheckNames[*CheckKind],
+"Tainted Memory 
Allocation",
+categories::MemoryError));
+auto R = std::make_unique(
+*BT_TaintedAlloc[*CheckKind], Msg, N);
+
+bugreporter::trackExpressionValue(N, SizeEx, *R);
+for (auto Sym : TaintedSyms)
+  R->markInteresting(Sym);
+C.emitReport(std::move(R));
+  }
+}
+
+void MallocChecker::CheckTaintedness(CheckerContext &C, const CallEvent &Call,
+ const SVal SizeSVal, ProgramStateRef 
State,
+ AllocationFamily Family) const {
+  std::vector TaintedSyms =
+  clang::ento::taint::getTaintedSymbols(State, SizeSVal);

steakhal wrote:

```suggestion
  taint::getTaintedSymbols(State, SizeSVal);
```

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -48,6 +49,45 @@ void myfoo(int *p);
 void myfooint(int p);
 char *fooRetPtr(void);
 
+void t1(void) {
+  size_t size;
+  scanf("%zu", &size);
+  int *p = malloc(size); // expected-warning{{malloc is called with a tainted 
(potentially attacker controlled) value}}
+  free(p);
+}
+
+void t2(void) {
+  size_t size;
+  scanf("%zu", &size);
+  int *p = calloc(size,2); // expected-warning{{calloc is called with a 
tainted (potentially attacker controlled) value}}
+  free(p);
+}
+
+void t3(void) {
+  size_t size;
+  scanf("%zu", &size);
+  if (1024https://github.com/llvm/llvm-project/pull/92420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -1779,18 +1790,79 @@ ProgramStateRef 
MallocChecker::MallocMemAux(CheckerContext &C,
 const CallEvent &Call,
 const Expr *SizeEx, SVal Init,
 ProgramStateRef State,
-AllocationFamily Family) {
+AllocationFamily Family) const {
   if (!State)
 return nullptr;
 
   assert(SizeEx);
   return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
 }
 
+void MallocChecker::reportTaintBug(StringRef Msg, ProgramStateRef State,
+   CheckerContext &C,
+   llvm::ArrayRef TaintedSyms,
+   AllocationFamily Family,
+   const Expr *SizeEx) const {
+  if (ExplodedNode *N = C.generateErrorNode(State)) {
+
+std::optional CheckKind =
+getCheckIfTracked(Family);
+if (!CheckKind)
+  return;
+if (!BT_TaintedAlloc[*CheckKind])
+  BT_TaintedAlloc[*CheckKind].reset(new BugType(CheckNames[*CheckKind],
+"Tainted Memory 
Allocation",
+categories::MemoryError));
+auto R = std::make_unique(
+*BT_TaintedAlloc[*CheckKind], Msg, N);
+
+bugreporter::trackExpressionValue(N, SizeEx, *R);
+for (auto Sym : TaintedSyms)
+  R->markInteresting(Sym);
+C.emitReport(std::move(R));
+  }
+}
+
+void MallocChecker::CheckTaintedness(CheckerContext &C, const CallEvent &Call,
+ const SVal SizeSVal, ProgramStateRef 
State,
+ AllocationFamily Family) const {
+  std::vector TaintedSyms =
+  clang::ento::taint::getTaintedSymbols(State, SizeSVal);
+  if (!TaintedSyms.empty()) {

steakhal wrote:

Transform this into an early-return to reduce indentation.

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -1273,6 +1273,41 @@ Check for memory leaks, double free, and use-after-free 
problems. Traces memory
 .. literalinclude:: checkers/unix_malloc_example.c
 :language: c
 
+If the ``alpha.security.taint.TaintPropagation`` checker is enabled, the 
checker
+warns for cases when the ``size`` parameter of the ``malloc`` , ``calloc``,
+``realloc``, ``alloca`` is tainted (potentially attacker controlled). If an
+attacker can inject a large value as the size parameter, memory exhaustion
+denial of service attack can be carried out.
+
+The analyzer emits warning only if it cannot prove that the size parameter is
+within reasonable bounds (``<= SIZE_MAX/4``). This functionality partially
+covers the SEI Cert coding standard rule `INT04-C
+`_.
+
+You can silence this warning either by bound checking the ``size`` parameter, 
or
+by explicitly marking the ``size`` parameter as sanitized. See the
+:ref:`alpha-security-taint-TaintPropagation` checker for more details.
+
+.. code-block:: c
+
+  void t1(void) {
+size_t size;
+scanf("%zu", &size);
+int *p = malloc(size); // warn: malloc is called with a tainted 
(potentially attacker controlled) value
+free(p);
+  }
+
+  void t3(void) {
+size_t size;
+scanf("%zu", &size);
+if (1024https://github.com/llvm/llvm-project/pull/92420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Balazs Benics via cfe-commits

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


[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -4639,6 +4645,303 @@ class FunctionNoProtoType : public FunctionType, public 
llvm::FoldingSetNode {
   }
 };
 
+// 
--
+
+/// Represents an abstract function effect, using just an enumeration 
describing
+/// its kind.
+class FunctionEffect {
+public:
+  /// Identifies the particular effect.
+  enum class Kind : uint8_t {
+None = 0,
+NonBlocking = 1,
+NonAllocating = 2,
+Blocking = 3,
+Allocating = 4
+  };
+
+  /// Flags describing some behaviors of the effect.
+  using Flags = unsigned;
+  enum FlagBit : Flags {
+// Can verification inspect callees' implementations? (e.g. nonblocking:
+// yes, tcb+types: no). This also implies the need for 2nd-pass
+// verification.
+FE_InferrableOnCallees = 0x1,
+
+// Language constructs which effects can diagnose as disallowed.
+FE_ExcludeThrow = 0x2,
+FE_ExcludeCatch = 0x4,
+FE_ExcludeObjCMessageSend = 0x8,
+FE_ExcludeStaticLocalVars = 0x10,
+FE_ExcludeThreadLocalVars = 0x20
+  };
+
+private:
+  LLVM_PREFERRED_TYPE(Kind)
+  unsigned FKind : 3;
+
+  // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
+  // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
+  // be considered for uniqueness.
+
+public:
+  FunctionEffect() : FKind(unsigned(Kind::None)) {}
+
+  explicit FunctionEffect(Kind K) : FKind(unsigned(K)) {}
+
+  /// The kind of the effect.
+  Kind kind() const { return Kind(FKind); }
+
+  /// Return the opposite kind, for effects which have opposites.
+  Kind oppositeKind() const;
+
+  /// For serialization.
+  uint32_t toOpaqueInt32() const { return FKind; }
+  static FunctionEffect fromOpaqueInt32(uint32_t Value) {
+return FunctionEffect(Kind(Value));
+  }
+
+  /// Flags describing some behaviors of the effect.
+  Flags flags() const {
+switch (kind()) {
+case Kind::NonBlocking:
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeStaticLocalVars |
+ FE_ExcludeThreadLocalVars;
+case Kind::NonAllocating:
+  // Same as NonBlocking, except without FE_ExcludeStaticLocalVars
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeThreadLocalVars;
+case Kind::Blocking:
+case Kind::Allocating:
+  return 0;
+case Kind::None:
+  break;
+}
+llvm_unreachable("unknown effect kind");
+  }
+
+  /// The description printed in diagnostics, e.g. 'nonblocking'.
+  StringRef name() const;
+
+  /// Return true if the effect is allowed to be inferred on the callee,
+  /// which is either a FunctionDecl or BlockDecl.
+  /// This is only used if the effect has FE_InferrableOnCallees flag set.
+  /// Example: This allows nonblocking(false) to prevent inference for the
+  /// function.
+  bool canInferOnFunction(const Decl &Callee) const;
+
+  // Return false for success. When true is returned for a direct call, then 
the
+  // FE_InferrableOnCallees flag may trigger inference rather than an immediate
+  // diagnostic. Caller should be assumed to have the effect (it may not have 
it
+  // explicitly when inferring).
+  bool shouldDiagnoseFunctionCall(bool Direct,
+  ArrayRef CalleeFX) const;
+
+  friend bool operator==(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return LHS.FKind == RHS.FKind;
+  }
+  friend bool operator!=(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return !(LHS == RHS);
+  }
+  friend bool operator<(const FunctionEffect &LHS, const FunctionEffect &RHS) {
+return LHS.FKind < RHS.FKind;
+  }
+};
+
+/// Wrap a function effect's condition expression in another struct so
+/// that FunctionProtoType's TrailingObjects can treat it separately.
+class FunctionEffectCondition {
+  Expr *Cond = nullptr; // if null, unconditional
+
+public:
+  FunctionEffectCondition() = default;
+  FunctionEffectCondition(Expr *E) : Cond(E) {} // implicit OK
+
+  Expr *expr() const { return Cond; }
+
+  bool operator==(const FunctionEffectCondition &RHS) const {
+return Cond == RHS.Cond;
+  }
+};
+
+/// A FunctionEffect plus a potential boolean expression determining whether
+/// the effect is declared (e.g. nonblocking(expr)). Generally the condition
+/// expression when present, is dependent.
+struct FunctionEffectWithCondition {
+  FunctionEffect Effect;
+  FunctionEffectCondition Cond;
+
+  FunctionEffectWithCondition() = default;
+  FunctionEffectWithCondition(const FunctionEffect &E,
+  const FunctionEffectCondition &C)
+  : Effect(E), Cond(C) {}
+
+  /// Return a textual description of the effect, and its condition, if any.
+  std::string description() const;
+
+  friend bool operator<(const FunctionEffectWithCondition &LHS,
+const FunctionEffectWithCondition

[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -1435,6 +1435,38 @@ def CXX11NoReturn : InheritableAttr {
   let Documentation = [CXX11NoReturnDocs];
 }
 
+def NonBlocking : TypeAttr {
+  let Spellings = [CXX11<"clang", "nonblocking">,

AaronBallman wrote:

Present Aaron thanks you and Past Aaron apologized for the churn. ;-)

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


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

2024-05-17 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/88978

>From 3acc848f4fcc68445dfc849f9c6f8d384d3692af Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat 
Date: Tue, 16 Apr 2024 13:09:58 -0700
Subject: [PATCH 1/8] Adding C23 constexpr math functions fmin and frexp.

---
 clang/include/clang/Basic/Builtins.td |  4 +--
 clang/lib/AST/ExprConstant.cpp| 16 -
 clang/test/CodeGen/constexpr-math.cpp | 51 +++
 3 files changed, 68 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/constexpr-math.cpp

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 52c0dd52c28b1..a35c77286229f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -3440,7 +3440,7 @@ def Fmod : FPMathTemplate, LibBuiltin<"math.h"> {
 
 def Frexp : FPMathTemplate, LibBuiltin<"math.h"> {
   let Spellings = ["frexp"];
-  let Attributes = [NoThrow];
+  let Attributes = [NoThrow, Constexpr];
   let Prototype = "T(T, int*)";
   let AddBuiltinPrefixedAlias = 1;
 }
@@ -3618,7 +3618,7 @@ def Fmax : FPMathTemplate, LibBuiltin<"math.h"> {
 
 def Fmin : FPMathTemplate, LibBuiltin<"math.h"> {
   let Spellings = ["fmin"];
-  let Attributes = [NoThrow, Const];
+  let Attributes = [NoThrow, Const, Constexpr];
   let Prototype = "T(T, T)";
   let AddBuiltinPrefixedAlias = 1;
   let OnlyBuiltinPrefixedAliasIsConstexpr = 1;
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5a36621dc5cce..506621ac7e9c1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2922,7 +2922,7 @@ static bool handleFloatFloatBinOp(EvalInfo &Info, 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()) {
 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
 return Info.noteUndefinedBehavior();
   }
@@ -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();
+int FrexpExp;
+Result = llvm::frexp(Result, FrexpExp, RM);
+return true;
+  }
   case Builtin::BI__builtin_huge_val:
   case Builtin::BI__builtin_huge_valf:
   case Builtin::BI__builtin_huge_vall:
@@ -14638,6 +14650,8 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
 return true;
   }
 
+  case Builtin::BIfmin:
+  case Builtin::BIfminf:
   case Builtin::BI__builtin_fmin:
   case Builtin::BI__builtin_fminf:
   case Builtin::BI__builtin_fminl:
diff --git a/clang/test/CodeGen/constexpr-math.cpp 
b/clang/test/CodeGen/constexpr-math.cpp
new file mode 100644
index 0..446bf3f4f7a50
--- /dev/null
+++ b/clang/test/CodeGen/constexpr-math.cpp
@@ -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, &i);
+  constexpr double f9 = __builtin_frexp(0.0, &i);
+  constexpr double f10 = __builtin_frexp(-0.0, &i);
+  constexpr double f11 = __builtin_frexpf(NAN, &i);
+  constexpr double f12 = __builtin_frexpf(-NAN, &i);
+  constexpr double f13 = __builtin_frexpf(INFINITY, &i);
+  constexpr double f14 = __builtin_frexpf(INFINITY, &i);
+
+  return 0;
+}
+
+// CHECK: store double 1.30e+00, ptr {{.*}}
+// CHECK: store double -0.00e+00, ptr {{.*}}
+// CHECK: store double -0.00e+00, ptr {{.*}}
+// CHECK: store float 0xFFF8, ptr {{.*}}
+// CHECK: store float -1.00e+00, ptr {{.*}}
+// CHECK: store float 0xFFF0, ptr {{.*}}
+
+// CHECK: store double 0x3FEEDCCD, ptr {{.*}}
+// CHECK: store double 0.00e+00, ptr {{.*}}
+// CHECK: store double -0.00e+00, ptr {{.*}}

[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Balazs Benics via cfe-commits

steakhal wrote:

> The "cert" package looks not useful and the checker has not a meaningful name 
> with the old naming scheme.
> Additionally tests and documentation is updated.
> The checker looks good enough to be moved into non-alpha package.

Personally, I prefer reviewing content changes separately from deciding/moving 
the checker out of alpha. Here are the reasons for doing so:
 - When content is moved around, a different set of mistakes can be made than 
when updating some doc content.
 - These are orthogonal decisions.

---

I'd suggest to split this PR into two:
 - Keep this PR for updating the content.
 - Have a separate PR for moving it out of alpha.



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


[clang] [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (PR #91965)

2024-05-17 Thread Momchil Velikov via cfe-commits


@@ -4180,8 +4180,10 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const 
ArraySubscriptExpr *E,
 
   // If the base is a vector type, then we are forming a vector element lvalue
   // with this subscript.
-  if (E->getBase()->getType()->isVectorType() &&
-  !isa(E->getBase())) {
+  if (QualType BaseTy = E->getBase()->getType();
+  (BaseTy->isVectorType() && !isa(E->getBase())) ||
+  (BaseTy->isBuiltinType() &&
+   BaseTy->getAs()->isSveVLSBuiltinType())) {

momchil-velikov wrote:

AFAICT here 
https://github.com/llvm/llvm-project/blob/371eccd5dfed88c8e76449233d8388c12be3464b/clang/lib/Sema/SemaExpr.cpp#L5307
 we are enabling array subscripts for SVE only. 

Perhaps we can be generalised to any size-less vector type, in a followup 
patch, @jacquesguan , what do you think?


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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Balazs Benics via cfe-commits


@@ -1179,6 +1179,54 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+.. _security-putenv-with-auto:
+
+security.PutenvWithAuto
+"""
+Finds calls to the ``putenv`` function which pass a pointer to an automatic 
variable as the argument.
+Function ``putenv`` does not copy the passed string, only a pointer to the 
data is stored.
+Content of an automatic variable is likely to be overwritten after returning 
from the parent function.

steakhal wrote:

Even though it's formally called `automatic storage duration`, I'd say that 
`stack`-variable is more commonly understood among programmers.
Consequently, I'd suggest `security.PutenvWithStack` or 
`security.PutenvWithStackVar` instead. I think it would be easier to discover 
that way.
But I guess, this should be discussed separately.

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


[clang] [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (PR #91965)

2024-05-17 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov updated 
https://github.com/llvm/llvm-project/pull/91965

>From fd4a31c1eb48db410f5445f45243dfbc1d9d22ab Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Mon, 13 May 2024 14:27:51 +0100
Subject: [PATCH 1/2] [Clang][AArch64][SVE] Allow write to SVE vector elements
 using the subscript operator

The patch at https://reviews.llvm.org/D122732 introduced using
the array subscript operator for SVE vectors, however it also
causes an ICE when the subscripting expression is used
as an lvalue.

This patches fixes the error. Lvalue subscripting expressions are
emitted as LLVM IR `insertvector`.
---
 clang/lib/CodeGen/CGExpr.cpp  |  6 --
 clang/lib/Sema/SemaExpr.cpp   |  4 +++-
 clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c | 10 ++
 3 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index d96c7bb1e5682..37b8b723937b7 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4180,8 +4180,10 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const 
ArraySubscriptExpr *E,
 
   // If the base is a vector type, then we are forming a vector element lvalue
   // with this subscript.
-  if (E->getBase()->getType()->isVectorType() &&
-  !isa(E->getBase())) {
+  if (QualType BaseTy = E->getBase()->getType();
+  (BaseTy->isVectorType() && !isa(E->getBase())) ||
+  (BaseTy->isBuiltinType() &&
+   BaseTy->getAs()->isSveVLSBuiltinType())) {
 // Emit the vector as an lvalue to get its address.
 LValue LHS = EmitLValue(E->getBase());
 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e0aae6333e1a1..f3983a3cbefb1 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5227,7 +5227,9 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
   }
 
   // Perform default conversions.
-  if (!LHSExp->getType()->getAs()) {
+  if (!LHSExp->getType()->getAs() &&
+  !(LHSExp->getType()->isBuiltinType() &&
+LHSExp->getType()->getAs()->isSveVLSBuiltinType())) {
 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
 if (Result.isInvalid())
   return ExprError();
diff --git a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c 
b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
index fb60c6d100ce6..634423765c4c3 100644
--- a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
+++ b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
@@ -88,3 +88,13 @@ float subscript_float32(svfloat32_t a, size_t b) {
 double subscript_float64(svfloat64_t a, size_t b) {
   return a[b];
 }
+
+// CHECK-LABEL: @subscript_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  
[[A:%.*]], float 1.00e+00, i64 [[B:%.*]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_write_float32(svfloat32_t a, size_t b) {
+  a[b] = 1.0f;
+  return a;
+}

>From fec051ff91df9cc8fca4d0571fe77a18cfb58072 Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Fri, 17 May 2024 13:20:18 +0100
Subject: [PATCH 2/2] [fixiup] Add a test using compound assignment operator

Change-Id: I81e1fd4f23eb65a96e71015de7a4562fcbc53c0f
---
 .../test/CodeGen/aarch64-sve-vector-subscript-ops.c  | 12 
 1 file changed, 12 insertions(+)

diff --git a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c 
b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
index 634423765c4c3..52a05d010de9b 100644
--- a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
+++ b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
@@ -98,3 +98,15 @@ svfloat32_t subscript_write_float32(svfloat32_t a, size_t b) 
{
   a[b] = 1.0f;
   return a;
 }
+
+// CHECK-LABEL: @subscript_read_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECEXT:%.*]] = extractelement  
[[A:%.*]], i64 [[B:%.*]]
+// CHECK-NEXT:[[ADD:%.*]] = fadd float [[VECEXT]], 1.00e+00
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  [[A]], 
float [[ADD]], i64 [[B]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_read_write_float32(svfloat32_t a, size_t b) {
+  a[b] += 1.0f;
+  return a;
+}

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


[clang] [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (PR #91965)

2024-05-17 Thread Momchil Velikov via cfe-commits


@@ -88,3 +88,13 @@ float subscript_float32(svfloat32_t a, size_t b) {
 double subscript_float64(svfloat64_t a, size_t b) {
   return a[b];
 }
+
+// CHECK-LABEL: @subscript_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  
[[A:%.*]], float 1.00e+00, i64 [[B:%.*]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_write_float32(svfloat32_t a, size_t b) {
+  a[b] = 1.0f;

momchil-velikov wrote:

Done.

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits


@@ -1032,11 +1037,6 @@ let ParentPackage = ENV in {
 
 let ParentPackage = POSAlpha in {

NagyDonat wrote:

Please delete the packages that will no longer contain any checkers after this 
change. (As it's a bad naming scheme, they shouldn't be repopulated later.)

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits


@@ -1179,6 +1179,54 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+.. _security-putenv-with-auto:
+
+security.PutenvWithAuto
+"""
+Finds calls to the ``putenv`` function which pass a pointer to an automatic 
variable as the argument.
+Function ``putenv`` does not copy the passed string, only a pointer to the 
data is stored.
+Content of an automatic variable is likely to be overwritten after returning 
from the parent function.
+
+The problem can be solved by using a static variable or dynamically allocated
+memory. Even better is to avoid using ``putenv`` (it has other problems
+related to memory leaks) and use ``setenv`` instead.
+
+The check corresponds to CERT rule
+`POS34-C. Do not call putenv() with a pointer to an automatic variable as the 
argument
+`_.
+
+.. code-block:: c
+
+  int f() {
+char[] env = "NAME=value";
+return putenv(env); // putenv function should not be called with auto 
variables
+  }
+
+Limitations:
+
+   - In specific cases one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track if and when the string passed to 
``putenv``
+ gets deallocated or overwritten, it needs to be slightly more aggressive
+ and warn for each case, leading in some cases to false-positive reports 
like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not 
be called...
+  // More code...
+  // FIXME: It looks like that if one string was passed to putenv,
+  // it should not be deallocated at all, because when reading the
+  // environment variable a pointer into this string is returned.
+  // In this case, if another (or the same) thread reads variable 
"NAME"
+  // at this point and does not copy the returned string, the data may
+  // become invalid.

NagyDonat wrote:

I agree with this remark.

I think you should just remove the whole `Limitations:` section and move this 
remark to the test file.

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

Thanks for bringing this checker out of alpha! I like the new name and I agree 
that the old `Limitations` section was incorrect; and I have some minor 
suggestions in inline comments.

I'd also ask for running this checker on some open source projects; but as 
`putenv` is an outdated function, I'd guess that there would be no results.

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits


@@ -1179,6 +1179,54 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+.. _security-putenv-with-auto:
+
+security.PutenvWithAuto
+"""
+Finds calls to the ``putenv`` function which pass a pointer to an automatic 
variable as the argument.

NagyDonat wrote:

```suggestion
Finds calls to the function ``putenv`` which pass a pointer to an automatic 
variable as the argument.
```

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-17 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,66 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=security.PutenvWithAuto \
+// RUN:  -verify %s
+
+#include "Inputs/system-header-simulator.h"
+void free(void *);
+void *malloc(size_t);
+int putenv(char *);
+int snprintf(char *, size_t, const char *, ...);
+
+int test_auto_var(const char *var) {
+  char env[1024];
+  (void)snprintf(env, sizeof(env), "TEST=%s", var);
+  return putenv(env); // expected-warning{{The 'putenv' function should not be 
called with arguments that have automatic storage}}
+}
+
+int test_static_var(const char *var) {
+  static char env[1024];
+  (void)snprintf(env, sizeof(env), "TEST=%s", var);
+  return putenv(env);
+}
+
+void test_heap_memory(const char *var) {
+  const char *env_format = "TEST=%s";
+  const size_t len = strlen(var) + strlen(env_format);
+  char *env = (char *)malloc(len);
+  if (env == NULL)
+return;
+  if (putenv(env) != 0) // no-warning: env was dynamically allocated.
+free(env);
+}
+
+typedef struct {
+  int A;
+  char Env[1024];
+} Mem;
+
+int test_auto_var_struct() {
+  Mem mem;
+  return putenv(mem.Env); // expected-warning{{The 'putenv' function should 
not be called with arguments that have automatic storage}}
+}
+
+int test_auto_var_subarray() {
+  char env[1024];
+  return putenv(env + 100); // expected-warning{{The 'putenv' function should 
not be called with arguments that have automatic storage}}
+}
+
+int test_constant() {
+  char *env = "TEST";
+  return putenv(env);
+}
+
+extern char *ext_env;
+int test_extern() {
+  return putenv(ext_env); // no-warning: extern storage class.
+}
+
+void test_auto_var_reset() {
+  char env[] = "NAME=value";
+  // TODO: False Positive

NagyDonat wrote:

```suggestion
  // If a string was passed to putenv, it should not be deallocated at all,
  // because when reading the environment variable a pointer into this string
  // is returned.  In this case, if another (or the same) thread reads variable
  // "NAME" at this point and does not copy the returned string, the data may
  // become invalid.
```
As you explained in the `FIXME` added in the documentation, this is not a false 
positive. It's a good idea to keep this testcase, but let's replace the old 
`TODO` comment with your reasoning for reporting this.

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


[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-17 Thread Doug Wyatt via cfe-commits


@@ -4639,6 +4645,303 @@ class FunctionNoProtoType : public FunctionType, public 
llvm::FoldingSetNode {
   }
 };
 
+// 
--
+
+/// Represents an abstract function effect, using just an enumeration 
describing
+/// its kind.
+class FunctionEffect {
+public:
+  /// Identifies the particular effect.
+  enum class Kind : uint8_t {
+None = 0,
+NonBlocking = 1,
+NonAllocating = 2,
+Blocking = 3,
+Allocating = 4
+  };
+
+  /// Flags describing some behaviors of the effect.
+  using Flags = unsigned;
+  enum FlagBit : Flags {
+// Can verification inspect callees' implementations? (e.g. nonblocking:
+// yes, tcb+types: no). This also implies the need for 2nd-pass
+// verification.
+FE_InferrableOnCallees = 0x1,
+
+// Language constructs which effects can diagnose as disallowed.
+FE_ExcludeThrow = 0x2,
+FE_ExcludeCatch = 0x4,
+FE_ExcludeObjCMessageSend = 0x8,
+FE_ExcludeStaticLocalVars = 0x10,
+FE_ExcludeThreadLocalVars = 0x20
+  };
+
+private:
+  LLVM_PREFERRED_TYPE(Kind)
+  unsigned FKind : 3;
+
+  // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
+  // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
+  // be considered for uniqueness.
+
+public:
+  FunctionEffect() : FKind(unsigned(Kind::None)) {}
+
+  explicit FunctionEffect(Kind K) : FKind(unsigned(K)) {}
+
+  /// The kind of the effect.
+  Kind kind() const { return Kind(FKind); }
+
+  /// Return the opposite kind, for effects which have opposites.
+  Kind oppositeKind() const;
+
+  /// For serialization.
+  uint32_t toOpaqueInt32() const { return FKind; }
+  static FunctionEffect fromOpaqueInt32(uint32_t Value) {
+return FunctionEffect(Kind(Value));
+  }
+
+  /// Flags describing some behaviors of the effect.
+  Flags flags() const {
+switch (kind()) {
+case Kind::NonBlocking:
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeStaticLocalVars |
+ FE_ExcludeThreadLocalVars;
+case Kind::NonAllocating:
+  // Same as NonBlocking, except without FE_ExcludeStaticLocalVars
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeThreadLocalVars;
+case Kind::Blocking:
+case Kind::Allocating:
+  return 0;
+case Kind::None:
+  break;
+}
+llvm_unreachable("unknown effect kind");
+  }
+
+  /// The description printed in diagnostics, e.g. 'nonblocking'.
+  StringRef name() const;
+
+  /// Return true if the effect is allowed to be inferred on the callee,
+  /// which is either a FunctionDecl or BlockDecl.
+  /// This is only used if the effect has FE_InferrableOnCallees flag set.
+  /// Example: This allows nonblocking(false) to prevent inference for the
+  /// function.
+  bool canInferOnFunction(const Decl &Callee) const;
+
+  // Return false for success. When true is returned for a direct call, then 
the
+  // FE_InferrableOnCallees flag may trigger inference rather than an immediate
+  // diagnostic. Caller should be assumed to have the effect (it may not have 
it
+  // explicitly when inferring).
+  bool shouldDiagnoseFunctionCall(bool Direct,
+  ArrayRef CalleeFX) const;
+
+  friend bool operator==(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return LHS.FKind == RHS.FKind;
+  }
+  friend bool operator!=(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return !(LHS == RHS);
+  }
+  friend bool operator<(const FunctionEffect &LHS, const FunctionEffect &RHS) {
+return LHS.FKind < RHS.FKind;
+  }
+};
+
+/// Wrap a function effect's condition expression in another struct so
+/// that FunctionProtoType's TrailingObjects can treat it separately.
+class FunctionEffectCondition {
+  Expr *Cond = nullptr; // if null, unconditional
+
+public:
+  FunctionEffectCondition() = default;
+  FunctionEffectCondition(Expr *E) : Cond(E) {} // implicit OK
+
+  Expr *expr() const { return Cond; }
+
+  bool operator==(const FunctionEffectCondition &RHS) const {
+return Cond == RHS.Cond;
+  }
+};
+
+/// A FunctionEffect plus a potential boolean expression determining whether
+/// the effect is declared (e.g. nonblocking(expr)). Generally the condition
+/// expression when present, is dependent.
+struct FunctionEffectWithCondition {
+  FunctionEffect Effect;
+  FunctionEffectCondition Cond;
+
+  FunctionEffectWithCondition() = default;
+  FunctionEffectWithCondition(const FunctionEffect &E,
+  const FunctionEffectCondition &C)
+  : Effect(E), Cond(C) {}
+
+  /// Return a textual description of the effect, and its condition, if any.
+  std::string description() const;
+
+  friend bool operator<(const FunctionEffectWithCondition &LHS,
+const FunctionEffectWithCondition

[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/92452

>From 27fab1ec54259941e3ded174de18cd99aa89bf7e Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Thu, 16 May 2024 16:42:27 -0400
Subject: [PATCH 1/2] [Clang][Sema] Fix crash when diagnosing near-match for
 'constexpr' redeclaration in C++11

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Sema/DeclSpec.h| 12 ++--
 clang/lib/Sema/SemaDecl.cpp| 18 +-
 .../CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp  | 11 +++
 4 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d2928e418623..411a5f752899d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -724,6 +724,8 @@ Bug Fixes to C++ Support
   templates during partial ordering when deducing template arguments from a 
function declaration or when
   taking the address of a function template.
 - Fix a bug with checking constrained non-type template parameters for 
equivalence. Fixes (#GH77377).
+- Fix a C++11 crash when a non-const non-static member function is defined 
out-of-line with
+  the ``constexpr`` specifier.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 23bc780e04979..44d96db54b5f0 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -1527,20 +1527,20 @@ struct DeclaratorChunk {
 
 /// Retrieve the location of the 'const' qualifier.
 SourceLocation getConstQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getConstSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getConstSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'volatile' qualifier.
 SourceLocation getVolatileQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getVolatileSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getVolatileSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'restrict' qualifier.
 SourceLocation getRestrictQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getRestrictSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getRestrictSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'mutable' qualifier, if any.
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0dbdf923df95a..22749dc4799bc 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9203,15 +9203,15 @@ static NamedDecl *DiagnoseInvalidRedeclaration(
 << Idx << FDParam->getType()
 << NewFD->getParamDecl(Idx - 1)->getType();
 } else if (FDisConst != NewFDisConst) {
-  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
-  << NewFDisConst << FD->getSourceRange().getEnd()
-  << (NewFDisConst
-  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
- .getConstQualifierLoc())
-  : 
FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
-   .getRParenLoc()
-   .getLocWithOffset(1),
-   " const"));
+  auto DB = SemaRef.Diag(FD->getLocation(),
+ diag::note_member_def_close_const_match)
+<< NewFDisConst << FD->getSourceRange().getEnd();
+  if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
+DB << 
FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
+ " const");
+  else if (SourceLocation ConstLoc = FTI.getConstQualifierLoc();
+   ConstLoc.isValid())
+DB << FixItHint::CreateRemoval(ConstLoc);
 } else
   SemaRef.Diag(FD->getLocation(),
IsMember ? diag::note_member_def_close_match
diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp 
b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
index a28a5f91c4775..788e93b56bb38 100644
--- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
@@ -154,3 +154,14 @@ namespace {
   // FIXME: We should diagnose this prior to C++17.
   const int &r = A::n;
 }
+
+#if __cplusplus < 201402L
+namespace ImplicitConstexprDef {
+  struct A {
+void f(); // expected-note {{member declaration does not match because it 
is not const qualified}}
+  };
+
+  constexpr void A::f() { } // expected-warning {{'constexpr' non-static 
member function will not be 

[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits


@@ -1527,20 +1527,20 @@ struct DeclaratorChunk {
 
 /// Retrieve the location of the 'const' qualifier.
 SourceLocation getConstQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getConstSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getConstSpecLoc()

sdkrystian wrote:

@AaronBallman Updated

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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits


@@ -9203,15 +9203,15 @@ static NamedDecl *DiagnoseInvalidRedeclaration(
 << Idx << FDParam->getType()
 << NewFD->getParamDecl(Idx - 1)->getType();
 } else if (FDisConst != NewFDisConst) {
-  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
-  << NewFDisConst << FD->getSourceRange().getEnd()
-  << (NewFDisConst
-  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
- .getConstQualifierLoc())
-  : 
FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
-   .getRParenLoc()
-   .getLocWithOffset(1),
-   " const"));
+  auto DB = SemaRef.Diag(FD->getLocation(),
+ diag::note_member_def_close_const_match)
+<< NewFDisConst << FD->getSourceRange().getEnd();
+  if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
+DB << 
FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
+ " const");
+  else if (SourceLocation ConstLoc = FTI.getConstQualifierLoc();

sdkrystian wrote:

Fair enough :)

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


[clang] [clang] CTAD alias: Fix missing template arg packs during the transformation (PR #92535)

2024-05-17 Thread Haojian Wu via cfe-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/92535

clang rejects some valid code (see testcases) because of an incorrect 
transformed deduction guides. This patch fixes it.

We miss the template argument packs during the transformation (`auto 
(type-parameter-0-0...) -> Foo<>`). In 
`TreeTransform::TransformTemplateArguments `, we have a logic of handling 
template argument packs which were originally added to support CTAD alias, it 
doesn't seem to be needed, we need to unpack them. 

>From 21ff4048fdee4f76d7d73ae9f2bfaf18614a4a3b Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 17 May 2024 14:12:04 +0200
Subject: [PATCH] [clang] CTAD alias: Fix missing template arg packs during the
 transformation.

---
 clang/lib/Sema/TreeTransform.h   |  8 
 clang/test/AST/ast-dump-ctad-alias.cpp   | 20 
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp |  5 +
 3 files changed, 25 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index b10e5ba65eb1c..f9fec21bf5bb6 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4818,14 +4818,6 @@ bool TreeTransform::TransformTemplateArguments(
 TemplateArgumentLoc In = *First;
 
 if (In.getArgument().getKind() == TemplateArgument::Pack) {
-  // When building the deduction guides, we rewrite the argument packs
-  // instead of unpacking.
-  if (getSema().CodeSynthesisContexts.back().Kind ==
-  Sema::CodeSynthesisContext::BuildingDeductionGuides) {
-if (getDerived().TransformTemplateArgument(In, Out, Uneval))
-  return true;
-continue;
-  }
   // Unpack argument packs, which we translate them into separate
   // arguments.
   // FIXME: We could do much better if we could guarantee that the
diff --git a/clang/test/AST/ast-dump-ctad-alias.cpp 
b/clang/test/AST/ast-dump-ctad-alias.cpp
index 7fe6c05621eee..9382558393e4c 100644
--- a/clang/test/AST/ast-dump-ctad-alias.cpp
+++ b/clang/test/AST/ast-dump-ctad-alias.cpp
@@ -48,3 +48,23 @@ Out2::AInner t(1.0);
 // CHECK-NEXT: |   |-TemplateArgument type 'double'
 // CHECK-NEXT: |   | `-BuiltinType {{.*}} 'double'
 // CHECK-NEXT: |   `-ParmVarDecl {{.*}} 'double'
+
+template 
+struct Foo {
+  Foo(T1...);
+};
+
+template 
+using AFoo = Foo;
+AFoo a(1, 2);
+// CHECK:  |-CXXDeductionGuideDecl {{.*}} implicit  'auto (type-parameter-0-0...) -> Foo'
+// CHECK-NEXT: | | `-ParmVarDecl {{.*}} 'type-parameter-0-0...' pack
+// CHECK-NEXT: | `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (int, int) -> Foo' implicit_instantiation
+
+template 
+using BFoo = Foo;
+BFoo b2(1.0, 2.0);
+// CHECK:  |-CXXDeductionGuideDecl {{.*}} implicit  'auto (type-parameter-0-0, type-parameter-0-0) -> Foo'
+// CHECK-NEXT: | | |-ParmVarDecl {{.*}} 'type-parameter-0-0'
+// CHECK-NEXT: | | `-ParmVarDecl {{.*}} 'type-parameter-0-0'
+// CHECK-NEXT: | `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (double, double) -> Foo' implicit_instantiation
diff --git a/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp 
b/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
index 7c186dc379c7b..479b0e3606721 100644
--- a/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
+++ b/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
@@ -173,6 +173,11 @@ template 
 using AFoo = Foo;
 
 auto b = AFoo{};
+AFoo a(1, 2);
+
+template 
+using BFoo = Foo;
+BFoo b2(1.0, 2.0);
 } // namespace test13
 
 namespace test14 {

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


[clang] [clang] CTAD alias: Fix missing template arg packs during the transformation (PR #92535)

2024-05-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

clang rejects some valid code (see testcases) because of an incorrect 
transformed deduction guides. This patch fixes it.

We miss the template argument packs during the transformation (`auto 
(type-parameter-0-0...) -> Foo<>`). In 
`TreeTransform::TransformTemplateArguments `, we have a logic of handling 
template argument packs which were originally added to support CTAD alias, it 
doesn't seem to be needed, we need to unpack them. 

---
Full diff: https://github.com/llvm/llvm-project/pull/92535.diff


3 Files Affected:

- (modified) clang/lib/Sema/TreeTransform.h (-8) 
- (modified) clang/test/AST/ast-dump-ctad-alias.cpp (+20) 
- (modified) clang/test/SemaCXX/cxx20-ctad-type-alias.cpp (+5) 


``diff
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index b10e5ba65eb1c..f9fec21bf5bb6 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4818,14 +4818,6 @@ bool TreeTransform::TransformTemplateArguments(
 TemplateArgumentLoc In = *First;
 
 if (In.getArgument().getKind() == TemplateArgument::Pack) {
-  // When building the deduction guides, we rewrite the argument packs
-  // instead of unpacking.
-  if (getSema().CodeSynthesisContexts.back().Kind ==
-  Sema::CodeSynthesisContext::BuildingDeductionGuides) {
-if (getDerived().TransformTemplateArgument(In, Out, Uneval))
-  return true;
-continue;
-  }
   // Unpack argument packs, which we translate them into separate
   // arguments.
   // FIXME: We could do much better if we could guarantee that the
diff --git a/clang/test/AST/ast-dump-ctad-alias.cpp 
b/clang/test/AST/ast-dump-ctad-alias.cpp
index 7fe6c05621eee..9382558393e4c 100644
--- a/clang/test/AST/ast-dump-ctad-alias.cpp
+++ b/clang/test/AST/ast-dump-ctad-alias.cpp
@@ -48,3 +48,23 @@ Out2::AInner t(1.0);
 // CHECK-NEXT: |   |-TemplateArgument type 'double'
 // CHECK-NEXT: |   | `-BuiltinType {{.*}} 'double'
 // CHECK-NEXT: |   `-ParmVarDecl {{.*}} 'double'
+
+template 
+struct Foo {
+  Foo(T1...);
+};
+
+template 
+using AFoo = Foo;
+AFoo a(1, 2);
+// CHECK:  |-CXXDeductionGuideDecl {{.*}} implicit  'auto (type-parameter-0-0...) -> Foo'
+// CHECK-NEXT: | | `-ParmVarDecl {{.*}} 'type-parameter-0-0...' pack
+// CHECK-NEXT: | `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (int, int) -> Foo' implicit_instantiation
+
+template 
+using BFoo = Foo;
+BFoo b2(1.0, 2.0);
+// CHECK:  |-CXXDeductionGuideDecl {{.*}} implicit  'auto (type-parameter-0-0, type-parameter-0-0) -> Foo'
+// CHECK-NEXT: | | |-ParmVarDecl {{.*}} 'type-parameter-0-0'
+// CHECK-NEXT: | | `-ParmVarDecl {{.*}} 'type-parameter-0-0'
+// CHECK-NEXT: | `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (double, double) -> Foo' implicit_instantiation
diff --git a/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp 
b/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
index 7c186dc379c7b..479b0e3606721 100644
--- a/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
+++ b/clang/test/SemaCXX/cxx20-ctad-type-alias.cpp
@@ -173,6 +173,11 @@ template 
 using AFoo = Foo;
 
 auto b = AFoo{};
+AFoo a(1, 2);
+
+template 
+using BFoo = Foo;
+BFoo b2(1.0, 2.0);
 } // namespace test13
 
 namespace test14 {

``




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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits


@@ -724,6 +724,8 @@ Bug Fixes to C++ Support
   templates during partial ordering when deducing template arguments from a 
function declaration or when
   taking the address of a function template.
 - Fix a bug with checking constrained non-type template parameters for 
equivalence. Fixes (#GH77377).
+- Fix a C++11 crash when a non-const non-static member function is defined 
out-of-line with

sdkrystian wrote:

I looked, but couldn't find any

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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-17 Thread Nick Zavaritsky via cfe-commits

https://github.com/mejedi updated 
https://github.com/llvm/llvm-project/pull/91310

>From 440f62d438810fbd1166a9eb3dbfbe10957fba58 Mon Sep 17 00:00:00 2001
From: Nick Zavaritsky 
Date: Sun, 5 May 2024 10:20:52 +
Subject: [PATCH] [BPF] Fix linking issues in static map initializers

When BPF object files are linked with bpftool, every symbol must be
accompanied by BTF info. Ensure that extern functions referenced by
global variable initializers are included in BTF.

The primary motivation is "static" initialization of PROG maps:

  extern int elsewhere(struct xdp_md *);

  struct {
__uint(type, BPF_MAP_TYPE_PROG_ARRAY);
__uint(max_entries, 1);
__type(key, int);
__type(value, int);
__array(values, int (struct xdp_md *));
  } prog_map SEC(".maps") = { .values = { elsewhere } };

BPF backend needs debug info to produce BTF. Debug info is not
normally generated for external variables and functions. Previously, it
was solved differently for variables (collecting variable declarations
in ExternalDeclarations vector) and functions (logic invoked during
codegen in CGExpr.cpp).

This patch generalises ExternalDefclarations to include both function
and variable declarations. This change ensures that function references
are not missed no matter the context. Previously external functions
referenced in constant expressions lacked debug info.
---
 clang/include/clang/AST/ASTConsumer.h |  3 +-
 .../clang/Frontend/MultiplexConsumer.h|  2 +-
 clang/include/clang/Sema/Sema.h   |  2 +-
 clang/lib/CodeGen/BackendConsumer.h   |  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 17 +-
 clang/lib/CodeGen/CodeGenAction.cpp   |  2 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 19 ++-
 clang/lib/CodeGen/CodeGenModule.h |  3 +-
 clang/lib/CodeGen/ModuleBuilder.cpp   |  2 +-
 clang/lib/Frontend/MultiplexConsumer.cpp  |  2 +-
 clang/lib/Interpreter/IncrementalParser.cpp   |  2 +-
 clang/lib/Sema/SemaDecl.cpp   |  8 +++
 clang/test/bpf-debug-info-extern-func.c   |  9 
 llvm/lib/Target/BPF/BTFDebug.cpp  | 23 
 llvm/lib/Target/BPF/BTFDebug.h|  4 ++
 llvm/test/CodeGen/BPF/BTF/extern-var-func2.ll | 54 +++
 16 files changed, 128 insertions(+), 26 deletions(-)
 create mode 100644 clang/test/bpf-debug-info-extern-func.c
 create mode 100644 llvm/test/CodeGen/BPF/BTF/extern-var-func2.ll

diff --git a/clang/include/clang/AST/ASTConsumer.h 
b/clang/include/clang/AST/ASTConsumer.h
index ebcd8059284d8..447f2592d2359 100644
--- a/clang/include/clang/AST/ASTConsumer.h
+++ b/clang/include/clang/AST/ASTConsumer.h
@@ -23,6 +23,7 @@ namespace clang {
   class ASTDeserializationListener; // layering violation because void* is ugly
   class SemaConsumer; // layering violation required for safe SemaConsumer
   class TagDecl;
+  class DeclaratorDecl;
   class VarDecl;
   class FunctionDecl;
   class ImportDecl;
@@ -105,7 +106,7 @@ class ASTConsumer {
   /// CompleteExternalDeclaration - Callback invoked at the end of a 
translation
   /// unit to notify the consumer that the given external declaration should be
   /// completed.
-  virtual void CompleteExternalDeclaration(VarDecl *D) {}
+  virtual void CompleteExternalDeclaration(DeclaratorDecl *D) {}
 
   /// Callback invoked when an MSInheritanceAttr has been attached to a
   /// CXXRecordDecl.
diff --git a/clang/include/clang/Frontend/MultiplexConsumer.h 
b/clang/include/clang/Frontend/MultiplexConsumer.h
index 4ed0d86d3cdfb..e49e3392d1f31 100644
--- a/clang/include/clang/Frontend/MultiplexConsumer.h
+++ b/clang/include/clang/Frontend/MultiplexConsumer.h
@@ -67,7 +67,7 @@ class MultiplexConsumer : public SemaConsumer {
   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
   void HandleImplicitImportDecl(ImportDecl *D) override;
   void CompleteTentativeDefinition(VarDecl *D) override;
-  void CompleteExternalDeclaration(VarDecl *D) override;
+  void CompleteExternalDeclaration(DeclaratorDecl *D) override;
   void AssignInheritanceModel(CXXRecordDecl *RD) override;
   void HandleVTable(CXXRecordDecl *RD) override;
   ASTMutationListener *GetASTMutationListener() override;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 873592a2d430a..adc716681bfe6 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2611,7 +2611,7 @@ class Sema final : public SemaBase {
   TentativeDefinitionsType TentativeDefinitions;
 
   /// All the external declarations encoutered and used in the TU.
-  SmallVector ExternalDeclarations;
+  SmallVector ExternalDeclarations;
 
   /// Generally null except when we temporarily switch decl contexts,
   /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
diff --git a/clang/lib/CodeGen/BackendConsumer.h 
b/clang/lib/CodeGen/BackendConsumer.h
index 0fe9929dca2b3..92ff19ab30844 100644
--- a/clang/lib/CodeGen/Backen

[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-17 Thread Aaron Ballman via cfe-commits


@@ -4639,6 +4645,303 @@ class FunctionNoProtoType : public FunctionType, public 
llvm::FoldingSetNode {
   }
 };
 
+// 
--
+
+/// Represents an abstract function effect, using just an enumeration 
describing
+/// its kind.
+class FunctionEffect {
+public:
+  /// Identifies the particular effect.
+  enum class Kind : uint8_t {
+None = 0,
+NonBlocking = 1,
+NonAllocating = 2,
+Blocking = 3,
+Allocating = 4
+  };
+
+  /// Flags describing some behaviors of the effect.
+  using Flags = unsigned;
+  enum FlagBit : Flags {
+// Can verification inspect callees' implementations? (e.g. nonblocking:
+// yes, tcb+types: no). This also implies the need for 2nd-pass
+// verification.
+FE_InferrableOnCallees = 0x1,
+
+// Language constructs which effects can diagnose as disallowed.
+FE_ExcludeThrow = 0x2,
+FE_ExcludeCatch = 0x4,
+FE_ExcludeObjCMessageSend = 0x8,
+FE_ExcludeStaticLocalVars = 0x10,
+FE_ExcludeThreadLocalVars = 0x20
+  };
+
+private:
+  LLVM_PREFERRED_TYPE(Kind)
+  unsigned FKind : 3;
+
+  // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
+  // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
+  // be considered for uniqueness.
+
+public:
+  FunctionEffect() : FKind(unsigned(Kind::None)) {}
+
+  explicit FunctionEffect(Kind K) : FKind(unsigned(K)) {}
+
+  /// The kind of the effect.
+  Kind kind() const { return Kind(FKind); }
+
+  /// Return the opposite kind, for effects which have opposites.
+  Kind oppositeKind() const;
+
+  /// For serialization.
+  uint32_t toOpaqueInt32() const { return FKind; }
+  static FunctionEffect fromOpaqueInt32(uint32_t Value) {
+return FunctionEffect(Kind(Value));
+  }
+
+  /// Flags describing some behaviors of the effect.
+  Flags flags() const {
+switch (kind()) {
+case Kind::NonBlocking:
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeStaticLocalVars |
+ FE_ExcludeThreadLocalVars;
+case Kind::NonAllocating:
+  // Same as NonBlocking, except without FE_ExcludeStaticLocalVars
+  return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
+ FE_ExcludeObjCMessageSend | FE_ExcludeThreadLocalVars;
+case Kind::Blocking:
+case Kind::Allocating:
+  return 0;
+case Kind::None:
+  break;
+}
+llvm_unreachable("unknown effect kind");
+  }
+
+  /// The description printed in diagnostics, e.g. 'nonblocking'.
+  StringRef name() const;
+
+  /// Return true if the effect is allowed to be inferred on the callee,
+  /// which is either a FunctionDecl or BlockDecl.
+  /// This is only used if the effect has FE_InferrableOnCallees flag set.
+  /// Example: This allows nonblocking(false) to prevent inference for the
+  /// function.
+  bool canInferOnFunction(const Decl &Callee) const;
+
+  // Return false for success. When true is returned for a direct call, then 
the
+  // FE_InferrableOnCallees flag may trigger inference rather than an immediate
+  // diagnostic. Caller should be assumed to have the effect (it may not have 
it
+  // explicitly when inferring).
+  bool shouldDiagnoseFunctionCall(bool Direct,
+  ArrayRef CalleeFX) const;
+
+  friend bool operator==(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return LHS.FKind == RHS.FKind;
+  }
+  friend bool operator!=(const FunctionEffect &LHS, const FunctionEffect &RHS) 
{
+return !(LHS == RHS);
+  }
+  friend bool operator<(const FunctionEffect &LHS, const FunctionEffect &RHS) {
+return LHS.FKind < RHS.FKind;
+  }
+};
+
+/// Wrap a function effect's condition expression in another struct so
+/// that FunctionProtoType's TrailingObjects can treat it separately.
+class FunctionEffectCondition {
+  Expr *Cond = nullptr; // if null, unconditional
+
+public:
+  FunctionEffectCondition() = default;
+  FunctionEffectCondition(Expr *E) : Cond(E) {} // implicit OK
+
+  Expr *expr() const { return Cond; }
+
+  bool operator==(const FunctionEffectCondition &RHS) const {
+return Cond == RHS.Cond;
+  }
+};
+
+/// A FunctionEffect plus a potential boolean expression determining whether
+/// the effect is declared (e.g. nonblocking(expr)). Generally the condition
+/// expression when present, is dependent.
+struct FunctionEffectWithCondition {
+  FunctionEffect Effect;
+  FunctionEffectCondition Cond;
+
+  FunctionEffectWithCondition() = default;
+  FunctionEffectWithCondition(const FunctionEffect &E,
+  const FunctionEffectCondition &C)
+  : Effect(E), Cond(C) {}
+
+  /// Return a textual description of the effect, and its condition, if any.
+  std::string description() const;
+
+  friend bool operator<(const FunctionEffectWithCondition &LHS,
+const FunctionEffectWithCondition

[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/92452

>From 27fab1ec54259941e3ded174de18cd99aa89bf7e Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Thu, 16 May 2024 16:42:27 -0400
Subject: [PATCH 1/2] [Clang][Sema] Fix crash when diagnosing near-match for
 'constexpr' redeclaration in C++11

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Sema/DeclSpec.h| 12 ++--
 clang/lib/Sema/SemaDecl.cpp| 18 +-
 .../CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp  | 11 +++
 4 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d2928e418623..411a5f752899d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -724,6 +724,8 @@ Bug Fixes to C++ Support
   templates during partial ordering when deducing template arguments from a 
function declaration or when
   taking the address of a function template.
 - Fix a bug with checking constrained non-type template parameters for 
equivalence. Fixes (#GH77377).
+- Fix a C++11 crash when a non-const non-static member function is defined 
out-of-line with
+  the ``constexpr`` specifier.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 23bc780e04979..44d96db54b5f0 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -1527,20 +1527,20 @@ struct DeclaratorChunk {
 
 /// Retrieve the location of the 'const' qualifier.
 SourceLocation getConstQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getConstSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getConstSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'volatile' qualifier.
 SourceLocation getVolatileQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getVolatileSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getVolatileSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'restrict' qualifier.
 SourceLocation getRestrictQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getRestrictSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getRestrictSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'mutable' qualifier, if any.
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0dbdf923df95a..22749dc4799bc 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9203,15 +9203,15 @@ static NamedDecl *DiagnoseInvalidRedeclaration(
 << Idx << FDParam->getType()
 << NewFD->getParamDecl(Idx - 1)->getType();
 } else if (FDisConst != NewFDisConst) {
-  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
-  << NewFDisConst << FD->getSourceRange().getEnd()
-  << (NewFDisConst
-  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
- .getConstQualifierLoc())
-  : 
FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
-   .getRParenLoc()
-   .getLocWithOffset(1),
-   " const"));
+  auto DB = SemaRef.Diag(FD->getLocation(),
+ diag::note_member_def_close_const_match)
+<< NewFDisConst << FD->getSourceRange().getEnd();
+  if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
+DB << 
FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
+ " const");
+  else if (SourceLocation ConstLoc = FTI.getConstQualifierLoc();
+   ConstLoc.isValid())
+DB << FixItHint::CreateRemoval(ConstLoc);
 } else
   SemaRef.Diag(FD->getLocation(),
IsMember ? diag::note_member_def_close_match
diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp 
b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
index a28a5f91c4775..788e93b56bb38 100644
--- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
@@ -154,3 +154,14 @@ namespace {
   // FIXME: We should diagnose this prior to C++17.
   const int &r = A::n;
 }
+
+#if __cplusplus < 201402L
+namespace ImplicitConstexprDef {
+  struct A {
+void f(); // expected-note {{member declaration does not match because it 
is not const qualified}}
+  };
+
+  constexpr void A::f() { } // expected-warning {{'constexpr' non-static 
member function will not be 

[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-17 Thread Nick Zavaritsky via cfe-commits

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


[clang] [clang][NFC] Remove const-qualification from `FunctionTemplateSpecializationInfo::TemplateArguments` (PR #92500)

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

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


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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-17 Thread Nick Zavaritsky via cfe-commits

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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits


@@ -724,6 +724,8 @@ Bug Fixes to C++ Support
   templates during partial ordering when deducing template arguments from a 
function declaration or when
   taking the address of a function template.
 - Fix a bug with checking constrained non-type template parameters for 
equivalence. Fixes (#GH77377).
+- Fix a C++11 crash when a non-const non-static member function is defined 
out-of-line with

sdkrystian wrote:

Nevermind, I did :) #61004

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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-17 Thread Nick Zavaritsky via cfe-commits

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


[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/92452

>From 27fab1ec54259941e3ded174de18cd99aa89bf7e Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Thu, 16 May 2024 16:42:27 -0400
Subject: [PATCH 1/3] [Clang][Sema] Fix crash when diagnosing near-match for
 'constexpr' redeclaration in C++11

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Sema/DeclSpec.h| 12 ++--
 clang/lib/Sema/SemaDecl.cpp| 18 +-
 .../CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp  | 11 +++
 4 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d2928e418623..411a5f752899d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -724,6 +724,8 @@ Bug Fixes to C++ Support
   templates during partial ordering when deducing template arguments from a 
function declaration or when
   taking the address of a function template.
 - Fix a bug with checking constrained non-type template parameters for 
equivalence. Fixes (#GH77377).
+- Fix a C++11 crash when a non-const non-static member function is defined 
out-of-line with
+  the ``constexpr`` specifier.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 23bc780e04979..44d96db54b5f0 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -1527,20 +1527,20 @@ struct DeclaratorChunk {
 
 /// Retrieve the location of the 'const' qualifier.
 SourceLocation getConstQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getConstSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getConstSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'volatile' qualifier.
 SourceLocation getVolatileQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getVolatileSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getVolatileSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'restrict' qualifier.
 SourceLocation getRestrictQualifierLoc() const {
-  assert(MethodQualifiers);
-  return MethodQualifiers->getRestrictSpecLoc();
+  return MethodQualifiers ? MethodQualifiers->getRestrictSpecLoc()
+  : SourceLocation();
 }
 
 /// Retrieve the location of the 'mutable' qualifier, if any.
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0dbdf923df95a..22749dc4799bc 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9203,15 +9203,15 @@ static NamedDecl *DiagnoseInvalidRedeclaration(
 << Idx << FDParam->getType()
 << NewFD->getParamDecl(Idx - 1)->getType();
 } else if (FDisConst != NewFDisConst) {
-  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
-  << NewFDisConst << FD->getSourceRange().getEnd()
-  << (NewFDisConst
-  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
- .getConstQualifierLoc())
-  : 
FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
-   .getRParenLoc()
-   .getLocWithOffset(1),
-   " const"));
+  auto DB = SemaRef.Diag(FD->getLocation(),
+ diag::note_member_def_close_const_match)
+<< NewFDisConst << FD->getSourceRange().getEnd();
+  if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
+DB << 
FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
+ " const");
+  else if (SourceLocation ConstLoc = FTI.getConstQualifierLoc();
+   ConstLoc.isValid())
+DB << FixItHint::CreateRemoval(ConstLoc);
 } else
   SemaRef.Diag(FD->getLocation(),
IsMember ? diag::note_member_def_close_match
diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp 
b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
index a28a5f91c4775..788e93b56bb38 100644
--- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p1.cpp
@@ -154,3 +154,14 @@ namespace {
   // FIXME: We should diagnose this prior to C++17.
   const int &r = A::n;
 }
+
+#if __cplusplus < 201402L
+namespace ImplicitConstexprDef {
+  struct A {
+void f(); // expected-note {{member declaration does not match because it 
is not const qualified}}
+  };
+
+  constexpr void A::f() { } // expected-warning {{'constexpr' non-static 
member function will not be 

[clang] [Clang][Sema] Fix crash when diagnosing near-match for 'constexpr' redeclaration in C++11 (PR #92452)

2024-05-17 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [Driver][PS5] Set visibility option defaults (PR #92091)

2024-05-17 Thread Paul T Robinson via cfe-commits


@@ -0,0 +1,33 @@
+/// Check PS5 specific interactions between visibility options.
+/// Detailed testing of -fvisibility-from-dllstorageclass is covered elsewhere.
+
+/// Check defaults.
+// RUN: %clang -### -target x86_64-sie-ps5 -x cl -c -emit-llvm %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=VDEFAULT,VGND_DEFAULT,DEFAULT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// VDEFAULT-DAG: "-fvisibility=hidden"
+// VGND_DEFAULT-DAG: "-fvisibility-global-new-delete=source"
+// DEFAULT-DAG:  "-fvisibility-from-dllstorageclass"
+// DEFAULT-DAG:  "-fvisibility-dllexport=protected"
+// DEFAULT-DAG:  "-fvisibility-nodllstorageclass=keep"
+// DEFAULT-DAG:  "-fvisibility-externs-dllimport=default"
+// DEFAULT-DAG:  "-fvisibility-externs-nodllstorageclass=keep"
+
+/// -fvisibility= specified explicitly.
+// RUN: %clang -### -target x86_64-sie-ps5 -x cl -c -emit-llvm 
-fvisibility=protected %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=VPROTECTED,VGND_DEFAULT,DEFAULT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// VPROTECTED-DAG: "-fvisibility=protected"
+
+/// -fvisibility-ms-compat added explicitly.
+// RUN: %clang -### -target x86_64-sie-ps5 -x cl -c -emit-llvm 
-fvisibility-ms-compat %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=MSCOMPT,VGND_DEFAULT,DEFAULT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// MSCOMPT-DAG: "-fvisibility=hidden"
+// MSCOMPT-DAG: "-ftype-visibility=default"
+
+/// -fvisibility-from-dllstorageclass added explicitly.
+// RUN: %clang -### -target x86_64-sie-ps5 -x cl -c -emit-llvm 
-fvisibility-from-dllstorageclass %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=VDEFAULT,VGND_DEFAULT,DEFAULT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+
+/// -fvisibility-from-dllstorageclass disabled explicitly.
+// RUN: %clang -### -target x86_64-sie-ps5 -x cl -c -emit-llvm 
-fno-visibility-from-dllstorageclass %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=VDEFAULT,VGND_DEFAULT,NOVISFROM %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// NOVISFROM-NOT: "-fvisibility-from-dllstorageclass"

pogo59 wrote:

Already excluded by `--implicit-check-not=fvsibility`

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


[clang] [Driver][PS5] Set visibility option defaults (PR #92091)

2024-05-17 Thread Paul T Robinson via cfe-commits

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


[clang] [Driver][PS5] Set visibility option defaults (PR #92091)

2024-05-17 Thread Paul T Robinson via cfe-commits

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

LGTM. I noted a couple of redundant checks, but if you think it's better for 
them to be explicit, I'm okay with keeping them.

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


[clang] [Driver][PS5] Set visibility option defaults (PR #92091)

2024-05-17 Thread Paul T Robinson via cfe-commits


@@ -0,0 +1,32 @@
+/// Check PS4 specific interactions between visibility options.
+/// Detailed testing of -fvisibility-from-dllstorageclass is covered elsewhere.
+
+/// Check defaults.
+// RUN: %clang -### -target x86_64-scei-ps4 -x cl -c -emit-llvm %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=DEFAULT %s --implicit-check-not=fvisibility 
--implicit-check-not=ftype-visibility --implicit-check-not=dllstorageclass
+// DEFAULT-DAG: "-fvisibility-from-dllstorageclass"
+// DEFAULT-DAG: "-fvisibility-dllexport=protected"
+// DEFAULT-DAG: "-fvisibility-nodllstorageclass=hidden"
+// DEFAULT-DAG: "-fvisibility-externs-dllimport=default"
+// DEFAULT-DAG: "-fvisibility-externs-nodllstorageclass=default"
+
+/// Check that -fvisibility-from-dllstorageclass is added in the presence of 
-fvisibility=.
+// RUN: %clang -### -target x86_64-scei-ps4 -x cl -c -emit-llvm 
-fvisibility=default  %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=DEFAULT,VISEQUALS %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// VISEQUALS-DAG: "-fvisibility=default"
+
+/// Check that -fvisibility-from-dllstorageclass is added in the presence of 
-fvisibility-ms-compat.
+// RUN: %clang -### -target x86_64-scei-ps4 -x cl -c -emit-llvm 
-fvisibility-ms-compat %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=DEFAULT,MSCOMPT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// MSCOMPT-DAG: "-fvisibility=hidden"
+// MSCOMPT-DAG: "-ftype-visibility=default"
+
+/// -fvisibility-from-dllstorageclass added explicitly.
+// RUN: %clang -### -target x86_64-scei-ps4 -x cl -c -emit-llvm 
-fvisibility-from-dllstorageclass %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=DEFAULT %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+
+/// -fvisibility-from-dllstorageclass disabled explicitly.
+// RUN: %clang -### -target x86_64-scei-ps4 -x cl -c -emit-llvm 
-fno-visibility-from-dllstorageclass %s 2>&1 | \
+// RUN:   FileCheck -check-prefixes=NOVISFROM %s 
--implicit-check-not=fvisibility --implicit-check-not=ftype-visibility 
--implicit-check-not=dllstorageclass
+// NOVISFROM-NOT: "-fvisibility-from-dllstorageclass"

pogo59 wrote:

This is already implicitly checked by `--implicit-check-not=fvisibility`

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


[clang] 932ca85 - libclc: remove __attribute__((assume)) for clspv targets (#92126)

2024-05-17 Thread via cfe-commits

Author: Romaric Jodin
Date: 2024-05-17T06:13:32-07:00
New Revision: 932ca85680db5e4579306f37e55746097fb8ec7f

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

LOG: libclc: remove __attribute__((assume)) for clspv targets (#92126)

Instead add a proper attribute in clang, and add convert it to function
metadata to keep the information in the IR. The goal is to remove the
dependency on __attribute__((assume)) that should have not be there in
the first place.

Ref https://github.com/llvm/llvm-project/pull/84934

Added: 
clang/test/CodeGen/clspv_libclc_builtin.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/CodeGen/CodeGenFunction.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test
libclc/generic/include/clc/clcfunc.h

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 40e41c940b6af..9799f878d7d72 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -403,6 +403,10 @@ Attribute Changes in Clang
 - Clang now warns that the ``exclude_from_explicit_instantiation`` attribute
   is ignored when applied to a local class or a member thereof.
 
+- The ``clspv_libclc_builtin`` attribute has been added to allow clspv
+  (`OpenCL-C to Vulkan SPIR-V compiler `_) to 
identify functions coming from libclc
+  (`OpenCL-C builtin library `_).
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 52552ba488560..38ee8356583be 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4561,3 +4561,10 @@ def CodeAlign: StmtAttr {
 static constexpr int MaximumAlignment = 4096;
   }];
 }
+
+def ClspvLibclcBuiltin: InheritableAttr {
+  let Spellings = [Clang<"clspv_libclc_builtin">];
+  let Subjects = SubjectList<[Function]>;
+  let Documentation = [ClspvLibclcBuiltinDoc];
+  let SimpleHandler = 1;
+}

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f351822ac74bd..b48aaf65558ac 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8087,3 +8087,17 @@ requirement:
   }
   }];
 }
+
+def ClspvLibclcBuiltinDoc : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+Attribute used by `clspv`_ (OpenCL-C to Vulkan SPIR-V compiler) to identify 
functions coming from `libclc`_ (OpenCL-C builtin library).
+
+.. code-block:: c
+
+  void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
+
+.. _`clspv`: https://github.com/google/clspv
+.. _`libclc`: https://libclc.llvm.org
+}];
+}

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 34dc0bd5c15bc..04abdadd95379 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -985,6 +985,11 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
 EmitKernelMetadata(FD, Fn);
   }
 
+  if (FD && FD->hasAttr()) {
+Fn->setMetadata("clspv_libclc_builtin",
+llvm::MDNode::get(getLLVMContext(), {}));
+  }
+
   // If we are checking function types, emit a function type signature as
   // prologue data.
   if (FD && SanOpts.has(SanitizerKind::Function)) {

diff  --git a/clang/test/CodeGen/clspv_libclc_builtin.c 
b/clang/test/CodeGen/clspv_libclc_builtin.c
new file mode 100644
index 0..ada2555c79e5b
--- /dev/null
+++ b/clang/test/CodeGen/clspv_libclc_builtin.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -triple spir -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: @foo()
+// CHECK-SAME: !clspv_libclc_builtin
+
+void __attribute__((clspv_libclc_builtin)) foo() {}

diff  --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test 
b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 318bfb2df2a7a..fd0e6d71baa80 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -48,6 +48,7 @@
 // CHECK-NEXT: Capability (SubjectMatchRule_record, 
SubjectMatchRule_type_alias)
 // CHECK-NEXT: CarriesDependency (SubjectMatchRule_variable_is_parameter, 
SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: Cleanup (SubjectMatchRule_variable_is_local)
+// CHECK-NEXT: ClspvLibclcBuiltin (SubjectMatchRule_function)
 // CHECK-NEXT: CmseNSEntry (SubjectMatchRule_function)
 // CHECK-NEXT: Cold (SubjectMatchRule_function)
 // CHECK-NEXT: Common (SubjectMatchRule_variable)

diff  --g

[clang] [libclc] libclc: remove __attribute__((assume)) for clspv targets (PR #92126)

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

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


[clang] [libclc] libclc: remove __attribute__((assume)) for clspv targets (PR #92126)

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

erichkeane wrote:

> Is there something else needed on my side to get that PR merged?

My apologies, I thought you'd been around LLVM enough that you had merge 
rights.  I've done it now.

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


[clang] 9917f3c - [Clang][AArch64] Require SVE or SSVE for scalable types. (#91356)

2024-05-17 Thread via cfe-commits

Author: Sander de Smalen
Date: 2024-05-17T14:21:56+01:00
New Revision: 9917f3ce641490ff95a11d22e37754a972c05420

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

LOG: [Clang][AArch64] Require SVE or SSVE for scalable types. (#91356)

Scalable types are only available when:
* The function is compiled with +sve
* The function is compiled with +sme and the function is executed in
Streaming-SVE mode.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaDecl.cpp

clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_reinterpret_svcount_svbool.c
clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfadd.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmax.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmaxnm.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmin.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfminnm.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmla.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmls.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmul.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfsub.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_create2_bool.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_get4_bool.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_undef_bool.c
clang/test/Sema/aarch64-sme2-sve2p1-diagnostics.c
clang/test/Sema/aarch64-sme2p1-diagnostics.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9372c862a36cb..59f44bc26eaf2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3209,6 +3209,8 @@ def warn_attribute_arm_zt0_builtin_no_zt0_state : Warning<
   InGroup>;
 def err_sve_vector_in_non_sve_target : Error<
   "SVE vector type %0 cannot be used in a target without sve">;
+def err_sve_vector_in_non_streaming_function : Error<
+  "SVE vector type %0 cannot be used in a non-streaming function">;
 def err_attribute_riscv_rvv_bits_unsupported : Error<
   "%0 is only supported when '-mrvv-vector-bits=' is specified with a "
   "value of \"zvl\" or a power 2 in the range [64,65536]">;

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 5d6ce233c775d..c9bc46414c7d2 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -2054,9 +2054,15 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
 if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
   llvm::StringMap CallerFeatureMap;
   Context.getFunctionFeatureMap(CallerFeatureMap, FD);
-  if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap) &&
-  !Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap))
-Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
+  if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
+if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap))
+  Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
+else if (!IsArmStreamingFunction(FD,
+ /*IncludeLocallyStreaming=*/true)) {
+  Diag(D->getLocation(), 
diag::err_sve_vector_in_non_streaming_function)
+  << Ty;
+}
+  }
 }
   };
 

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index bb0bee0d234c5..6c545d695fc9f 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8905,11 +8905,20 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) 
{
 const FunctionDecl *FD = cast(CurContext);
 llvm::StringMap CallerFeatureMap;
 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
-if (!Builtin::evaluateRequiredTargetFeatures(
-"sve", CallerFeatureMap)) {
-  Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
-  NewVD->setInvalidDecl();
-  return;
+
+if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
+  if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
+Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << 
T;
+NewVD->setInvalidDecl();
+return;
+  } else if (!IsArmStreamingFunction(FD,
+ /*IncludeLocallyStreaming=*/true)) {
+Diag(NewVD->getLocation(),
+ diag::err_sve_vector_in_non_streaming_function)
+  

[clang] [Clang][AArch64] Require SVE or SSVE for scalable types. (PR #91356)

2024-05-17 Thread Sander de Smalen via cfe-commits

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


[clang] [clang][Sema] Warn consecutive builtin comparisons in an expression (PR #92200)

2024-05-17 Thread Youngsuk Kim via cfe-commits

https://github.com/JOE1994 updated 
https://github.com/llvm/llvm-project/pull/92200

>From 2c7f9a083c129df70a79d019286b6a29643a8973 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Tue, 14 May 2024 17:42:59 -0500
Subject: [PATCH 1/5] [clang][Sema] Warn consecutive builtin comparisons in an
 expression

Made the following decisions for consistency with `gcc 14.1`:
* Add warning under -Wparentheses
* Set the warning to DefaultIgnore, although -Wparentheses is enabled by default
  * This warning is only issued when -Wparentheses is explicitly enabled
(via -Wparentheses or -Wall)

Closes #20456
---
 clang/docs/ReleaseNotes.rst  | 3 +++
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 4 
 clang/lib/Sema/SemaExpr.cpp  | 5 +
 clang/test/Sema/parentheses.cpp  | 7 +++
 4 files changed, 19 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ae699ebfc6038..13d58e69aeeb7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -487,6 +487,9 @@ Improvements to Clang's diagnostics
}
  };
 
+- Clang emits a ``-Wparentheses`` warning for expressions with consecutive 
comparisons like ``x < y < z``.
+  It was made a ``-Wparentheses`` warning to be consistent with gcc.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6100fba510059..612043f410890 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6911,6 +6911,10 @@ def warn_precedence_bitwise_conditional : Warning<
 def note_precedence_conditional_first : Note<
   "place parentheses around the '?:' expression to evaluate it first">;
 
+def warn_consecutive_comparison : Warning<
+  "comparisons like 'X<=Y<=Z' don't have their mathematical meaning">,
+  InGroup, DefaultIgnore;
+
 def warn_enum_constant_in_bool_context : Warning<
   "converting the enum constant to a boolean">,
   InGroup, DefaultIgnore;
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ec84798e4ce60..fab34f4fa3e14 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14878,6 +14878,11 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation 
OpLoc,
   case BO_GT:
 ConvertHalfVec = true;
 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
+
+if (const auto *BI = dyn_cast(LHSExpr))
+  if (BI->isComparisonOp())
+Diag(OpLoc, diag::warn_consecutive_comparison);
+
 break;
   case BO_EQ:
   case BO_NE:
diff --git a/clang/test/Sema/parentheses.cpp b/clang/test/Sema/parentheses.cpp
index 324d9b5f1e414..8e546461fb643 100644
--- a/clang/test/Sema/parentheses.cpp
+++ b/clang/test/Sema/parentheses.cpp
@@ -215,3 +215,10 @@ namespace PR20735 {
 // fix-it:"{{.*}}":{[[@LINE-9]]:20-[[@LINE-9]]:20}:")"
   }
 }
+
+void consecutive_builtin_compare(int x, int y, int z) {
+  (void)(x < y < z);  // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x < y > z);  // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x < y <= z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x <= y > z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+}

>From b3cc457efc40a345d4b67c776edd470e35f73de2 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Wed, 15 May 2024 13:20:06 -0400
Subject: [PATCH 2/5] Update clang/lib/Sema/SemaExpr.cpp

Co-authored-by: Aaron Ballman 
---
 clang/lib/Sema/SemaExpr.cpp | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index fab34f4fa3e14..b4c54a3da42c0 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14879,9 +14879,8 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation 
OpLoc,
 ConvertHalfVec = true;
 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
 
-if (const auto *BI = dyn_cast(LHSExpr))
-  if (BI->isComparisonOp())
-Diag(OpLoc, diag::warn_consecutive_comparison);
+if (const auto *BI = dyn_cast(LHSExpr); BI && 
BI->isComparisonOp())
+  Diag(OpLoc, diag::warn_consecutive_comparison);
 
 break;
   case BO_EQ:

>From 8df35dcf7b802ce8e280930224575077a08e0541 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Wed, 15 May 2024 12:53:38 -0500
Subject: [PATCH 3/5] Remove DefaultIgnore + clang-format

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td  | 2 +-
 clang/lib/Sema/SemaExpr.cpp   | 3 ++-
 clang/test/Sema/bool-compare.c| 4 ++--
 clang/test/SemaCXX/bool-compare.cpp   | 4 ++--
 clang/test/SemaCXX/cxx2a-adl-only-template-id.cpp | 2 +-
 clang/test/SemaTemplate/typo-dependent-name.cpp   |

  1   2   3   4   >