[clang] 499507f - [clang][Interp][NFC] Remove unused function

2024-01-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-01-27T09:06:03+01:00
New Revision: 499507fdec8eb37dc68cee6c2b6c75557b28024e

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

LOG: [clang][Interp][NFC] Remove unused function

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 2fc61ac4b5d170f..1d5ae46e5634685 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -263,15 +263,6 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   template  bool emitConst(T Value, PrimType Ty, const Expr *E);
   template  bool emitConst(T Value, const Expr *E);
 
-  /// Returns the CXXRecordDecl for the type of the given expression,
-  /// or nullptr if no such decl exists.
-  const CXXRecordDecl *getRecordDecl(const Expr *E) const {
-QualType T = E->getType();
-if (const auto *RD = T->getPointeeCXXRecordDecl())
-  return RD;
-return T->getAsCXXRecordDecl();
-  }
-
   llvm::RoundingMode getRoundingMode(const Expr *E) const {
 FPOptions FPO = E->getFPFeaturesInEffect(Ctx.getLangOpts());
 



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


[clang] ce75cbe - [clang][Interp][NFC] Don't unnecessarily use std::optional

2024-01-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-01-27T09:06:04+01:00
New Revision: ce75cbeda21e3e4e5d0c47ecf44954caf98acfe8

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

LOG: [clang][Interp][NFC] Don't unnecessarily use std::optional

classifyComplexElementType() doesn't return a std::optional anymore.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6cce9b9cb0a2ab7..d4501cefb2131da 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -231,10 +231,7 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 
   case CK_IntegralComplexToBoolean:
   case CK_FloatingComplexToBoolean: {
-std::optional ElemT =
-classifyComplexElementType(SubExpr->getType());
-if (!ElemT)
-  return false;
+PrimType ElemT = classifyComplexElementType(SubExpr->getType());
 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
 // for us, that means (bool)E[0] || (bool)E[1]
 if (!this->visit(SubExpr))
@@ -243,13 +240,13 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   return false;
 if (!this->emitArrayElemPtrUint8(CE))
   return false;
-if (!this->emitLoadPop(*ElemT, CE))
+if (!this->emitLoadPop(ElemT, CE))
   return false;
-if (*ElemT == PT_Float) {
+if (ElemT == PT_Float) {
   if (!this->emitCastFloatingIntegral(PT_Bool, CE))
 return false;
 } else {
-  if (!this->emitCast(*ElemT, PT_Bool, CE))
+  if (!this->emitCast(ElemT, PT_Bool, CE))
 return false;
 }
 
@@ -262,13 +259,13 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   return false;
 if (!this->emitArrayElemPtrPopUint8(CE))
   return false;
-if (!this->emitLoadPop(*ElemT, CE))
+if (!this->emitLoadPop(ElemT, CE))
   return false;
-if (*ElemT == PT_Float) {
+if (ElemT == PT_Float) {
   if (!this->emitCastFloatingIntegral(PT_Bool, CE))
 return false;
 } else {
-  if (!this->emitCast(*ElemT, PT_Bool, CE))
+  if (!this->emitCast(ElemT, PT_Bool, CE))
 return false;
 }
 // Leave the boolean value of E[1] on the stack.



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


[clang-tools-extra] [clang] [llvm] [Clang] Fix : More Detailed "No expected directives found" (PR #78338)

2024-01-27 Thread Shourya Goel via cfe-commits


@@ -179,7 +179,7 @@ def err_verify_invalid_no_diags : Error<
 "%select{expected|'expected-no-diagnostics'}0 directive cannot follow "
 "%select{'expected-no-diagnostics' directive|other expected directives}0">;

Sh0g0-1758 wrote:

Can you please elaborate on this. 

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


[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #75841)

2024-01-27 Thread Brad Smith via cfe-commits

brad0 wrote:

Able to look at this further?

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread Gábor Spaits via cfe-commits


@@ -858,6 +859,27 @@ class PackDeductionScope {
   Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
   }
 
+  // Return the size of the saved packs if all of them has the same size.
+  std::optional getSavedPackSizeIfAllEqual() const {
+if (Packs.size() == 0 ||
+Packs[0].Saved.getKind() != clang::TemplateArgument::Pack)

spaits wrote:

Removed this precondition. I have also removed a redundant condition from the 
checking of the equivalence of pack sizes.

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian created 
https://github.com/llvm/llvm-project/pull/79683

Reapplies #78274 with the addition of a default-error warning 
(`strict-primary-template-shadow`) that is issued for instances of shadowing 
which were previously accepted prior to this patch.


>From abc8f062add9e41ce00b9d035c796256a62859ef Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Tue, 16 Jan 2024 08:05:33 -0500
Subject: [PATCH] Reapply "[Clang][Sema] Diagnose function/variable templates
 that shadow their own template parameters (#78274)"

---
 clang/docs/ReleaseNotes.rst   |  1 +
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/include/clang/Sema/Sema.h   |  2 +-
 clang/lib/Sema/SemaDecl.cpp   | 31 +--
 clang/lib/Sema/SemaTemplate.cpp   |  9 --
 .../test/CXX/temp/temp.res/temp.local/p6.cpp  | 22 ++---
 6 files changed, 51 insertions(+), 17 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..24d3ada5bfd9dfc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,6 +97,7 @@ Attribute Changes in Clang
 
 Improvements to Clang's diagnostics
 ---
+- Clang now diagnoses function/variable templates that shadow their own 
template parameters, e.g. ``template void T();``.
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 649de9f47c46195..4e3b20548913ab5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4966,6 +4966,9 @@ def err_template_param_shadow : Error<
   "declaration of %0 shadows template parameter">;
 def ext_template_param_shadow : ExtWarn<
   err_template_param_shadow.Summary>, InGroup;
+def ext_compat_template_param_shadow : ExtWarn<
+  err_template_param_shadow.Summary>, InGroup<
+  DiagGroup<"strict-primary-template-shadow">>, DefaultError;
 def note_template_param_here : Note<"template parameter is declared here">;
 def note_template_param_external : Note<
   "template parameter from hidden source: %0">;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff73581..5c148db48140ed4 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8256,7 +8256,7 @@ class Sema final {
   TemplateSpecializationKind TSK,
   bool Complain = true);
 
-  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
+  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, 
bool IssueWarning = false);
   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
 
   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f9bf1d14bdc4f68..de65b3c09c28cfe 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -6377,12 +6377,6 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
 return nullptr;
 
-  // The scope passed in may not be a decl scope.  Zip up the scope tree until
-  // we find one that is.
-  while ((S->getFlags() & Scope::DeclScope) == 0 ||
- (S->getFlags() & Scope::TemplateParamScope) != 0)
-S = S->getParent();
-
   DeclContext *DC = CurContext;
   if (D.getCXXScopeSpec().isInvalid())
 D.setInvalidType();
@@ -6506,12 +6500,25 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 RemoveUsingDecls(Previous);
   }
 
-  if (Previous.isSingleResult() &&
-  Previous.getFoundDecl()->isTemplateParameter()) {
+  // if (Previous.isSingleResult() &&
+  //Previous.getFoundDecl()->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle(); TPD && 
TPD->isTemplateParameter()) {
+// Older versions of clang allowed the names of function/variable templates
+// to shadow the names of their template parameters. For the compatibility 
purposes
+// we detect such cases and issue a default-to-error warning that can be 
disabled with
+// -fno-strict-primary-template-shadow.
+bool IssueShadowingWarning = false;
+for (Scope *Inner = S; (Inner->getFlags() & Scope::DeclScope) == 0 ||
+ Inner->isTemplateParamScope(); Inner = Inner->getParent()) {
+  if (IssueShadowingWarning = Inner->isDeclScope(TPD))
+break;
+}
+
 // Maybe we will complain about the shadowed template parameter.
 if (!D.isInvalidType())
   DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-  Previous.getFoundDecl());
+  TPD,
+  IssueShadowingWarning);
 
 // Just pretend that w

[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Krystian Stasiowski (sdkrystian)


Changes

Reapplies #78274 with the addition of a default-error warning 
(`strict-primary-template-shadow`) that is issued for instances of shadowing 
which were previously accepted prior to this patch.


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


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/include/clang/Sema/Sema.h (+1-1) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+22-9) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+6-3) 
- (modified) clang/test/CXX/temp/temp.res/temp.local/p6.cpp (+18-4) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad801..24d3ada5bfd9df 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,6 +97,7 @@ Attribute Changes in Clang
 
 Improvements to Clang's diagnostics
 ---
+- Clang now diagnoses function/variable templates that shadow their own 
template parameters, e.g. ``template void T();``.
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 649de9f47c4619..4e3b20548913ab 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4966,6 +4966,9 @@ def err_template_param_shadow : Error<
   "declaration of %0 shadows template parameter">;
 def ext_template_param_shadow : ExtWarn<
   err_template_param_shadow.Summary>, InGroup;
+def ext_compat_template_param_shadow : ExtWarn<
+  err_template_param_shadow.Summary>, InGroup<
+  DiagGroup<"strict-primary-template-shadow">>, DefaultError;
 def note_template_param_here : Note<"template parameter is declared here">;
 def note_template_param_external : Note<
   "template parameter from hidden source: %0">;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff7358..5c148db48140ed 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8256,7 +8256,7 @@ class Sema final {
   TemplateSpecializationKind TSK,
   bool Complain = true);
 
-  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
+  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, 
bool IssueWarning = false);
   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
 
   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f9bf1d14bdc4f6..de65b3c09c28cf 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -6377,12 +6377,6 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
 return nullptr;
 
-  // The scope passed in may not be a decl scope.  Zip up the scope tree until
-  // we find one that is.
-  while ((S->getFlags() & Scope::DeclScope) == 0 ||
- (S->getFlags() & Scope::TemplateParamScope) != 0)
-S = S->getParent();
-
   DeclContext *DC = CurContext;
   if (D.getCXXScopeSpec().isInvalid())
 D.setInvalidType();
@@ -6506,12 +6500,25 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 RemoveUsingDecls(Previous);
   }
 
-  if (Previous.isSingleResult() &&
-  Previous.getFoundDecl()->isTemplateParameter()) {
+  // if (Previous.isSingleResult() &&
+  //Previous.getFoundDecl()->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle(); TPD && 
TPD->isTemplateParameter()) {
+// Older versions of clang allowed the names of function/variable templates
+// to shadow the names of their template parameters. For the compatibility 
purposes
+// we detect such cases and issue a default-to-error warning that can be 
disabled with
+// -fno-strict-primary-template-shadow.
+bool IssueShadowingWarning = false;
+for (Scope *Inner = S; (Inner->getFlags() & Scope::DeclScope) == 0 ||
+ Inner->isTemplateParamScope(); Inner = Inner->getParent()) {
+  if (IssueShadowingWarning = Inner->isDeclScope(TPD))
+break;
+}
+
 // Maybe we will complain about the shadowed template parameter.
 if (!D.isInvalidType())
   DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-  Previous.getFoundDecl());
+  TPD,
+  IssueShadowingWarning);
 
 // Just pretend that we didn't see the previous declaration.
 Previous.clear();
@@ -6535,6 +6542,12 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   if (getLangOpts().CPlusPlus)
 CheckExtraCXXDefaultArguments(D);
 
+  // The scope pas

[clang] [Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (PR #78274)

2024-01-27 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

See #79683

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff faef68bca852d08511ea0311d8a0d221cb202e73 
abc8f062add9e41ce00b9d035c796256a62859ef -- clang/include/clang/Sema/Sema.h 
clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaTemplate.cpp 
clang/test/CXX/temp/temp.res/temp.local/p6.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5c148db481..d0fb4f0991 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8256,7 +8256,8 @@ public:
   TemplateSpecializationKind TSK,
   bool Complain = true);
 
-  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, 
bool IssueWarning = false);
+  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning = false);
   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
 
   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index de65b3c09c..2cb971b052 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -6502,22 +6502,23 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 
   // if (Previous.isSingleResult() &&
   //Previous.getFoundDecl()->isTemplateParameter()) {
-  if (auto *TPD = Previous.getAsSingle(); TPD && 
TPD->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle();
+  TPD && TPD->isTemplateParameter()) {
 // Older versions of clang allowed the names of function/variable templates
-// to shadow the names of their template parameters. For the compatibility 
purposes
-// we detect such cases and issue a default-to-error warning that can be 
disabled with
-// -fno-strict-primary-template-shadow.
+// to shadow the names of their template parameters. For the compatibility
+// purposes we detect such cases and issue a default-to-error warning that
+// can be disabled with -fno-strict-primary-template-shadow.
 bool IssueShadowingWarning = false;
 for (Scope *Inner = S; (Inner->getFlags() & Scope::DeclScope) == 0 ||
- Inner->isTemplateParamScope(); Inner = Inner->getParent()) {
+   Inner->isTemplateParamScope();
+ Inner = Inner->getParent()) {
   if (IssueShadowingWarning = Inner->isDeclScope(TPD))
 break;
 }
 
 // Maybe we will complain about the shadowed template parameter.
 if (!D.isInvalidType())
-  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-  TPD,
+  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
   IssueShadowingWarning);
 
 // Just pretend that we didn't see the previous declaration.
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 4ba8dfc19d..2993da99ff 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -885,7 +885,8 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, 
bool IssueWarning) {
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {
   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
 
   // C++ [temp.local]p4:
@@ -894,10 +895,9 @@ void Sema::DiagnoseTemplateParameterShadow(SourceLocation 
Loc, Decl *PrevDecl, b
   //
   // Make this a warning when MSVC compatibility is requested.
   unsigned DiagId = getLangOpts().MSVCCompat
-  ? diag::ext_template_param_shadow
-  : (IssueWarning
-  ? diag::ext_compat_template_param_shadow
-  : diag::err_template_param_shadow);
+? diag::ext_template_param_shadow
+: (IssueWarning ? 
diag::ext_compat_template_param_shadow
+: diag::err_template_param_shadow);
   const auto *ND = cast(PrevDecl);
   Diag(Loc, DiagId) << ND->getDeclName();
   NoteTemplateParameterLocation(*ND);

``




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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

Need to run clang-format on this and mention the flag in the release notes, but 
should be otherwise GTG

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread via cfe-commits
=?utf-8?q?G=C3=A1bor?= Spaits,Gabor Spaits ,Gabor
 Spaits 
Message-ID:
In-Reply-To: 


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

Thanks for working on this!
The changes looks good to me.
Will you need me to merge them on your behalf?

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits


@@ -6506,12 +6500,25 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 RemoveUsingDecls(Previous);
   }
 
-  if (Previous.isSingleResult() &&
-  Previous.getFoundDecl()->isTemplateParameter()) {
+  // if (Previous.isSingleResult() &&
+  //Previous.getFoundDecl()->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle(); TPD && 
TPD->isTemplateParameter()) {
+// Older versions of clang allowed the names of function/variable templates
+// to shadow the names of their template parameters. For the compatibility 
purposes
+// we detect such cases and issue a default-to-error warning that can be 
disabled with
+// -fno-strict-primary-template-shadow.

cor3ntin wrote:

Do you mean `-Wno-strict-primary-template-shadow` here?

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits


@@ -6506,12 +6500,25 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 RemoveUsingDecls(Previous);
   }
 
-  if (Previous.isSingleResult() &&
-  Previous.getFoundDecl()->isTemplateParameter()) {
+  // if (Previous.isSingleResult() &&
+  //Previous.getFoundDecl()->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle(); TPD && 
TPD->isTemplateParameter()) {
+// Older versions of clang allowed the names of function/variable templates
+// to shadow the names of their template parameters. For the compatibility 
purposes
+// we detect such cases and issue a default-to-error warning that can be 
disabled with
+// -fno-strict-primary-template-shadow.

sdkrystian wrote:

Yes :)

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread Gábor Spaits via cfe-commits

spaits wrote:

Thank you for reviewing.

Before merge we should take a look at the CI.

It still fails for libc++ 26 suite, with the same reason as before.

I wanted to reproduce the issue. I built libc++ with the clang++ I compiled:
```
cmake -S "../runtimes" -GNinja \
  -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" \
  -DLIBCXX_CXX_ABI=libcxxabi \
  -DCMAKE_BUILD_TYPE=Debug \
  -DLIBCXX_TEST_PARAMS="std=c++26" \
  -DLIBCXXABI_TEST_PARAMS="std=c++26" \
  -DCMAKE_CXX_COMPILER=/home/spaits/repo/llvm-project/build/bin/clang++ 
\
  -DLLVM_DIR=/home/spaits/repo/llvm-project/build/lib/cmake/llvm
```
Then I run the test:
```
 /home/spaits/repo/llvm-project/build/bin/llvm-lit -a 
/home/spaits/repo/llvm-project/libcxx/test/libcxx/gdb/gdb_pretty_printer_test.sh.cpp
```

Everything worked fine for me.
I don't know why the CI always fails for my PR with the same reason. It looks 
like an env issue in the CI, but it can not be that since other PRs are getting 
green runs.

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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

The libcxx test failure are unrelated.

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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread Gábor Spaits via cfe-commits

spaits wrote:

@cor3ntin I see that you have CI runs that fail with exactly the same reason as 
my runs: 
https://buildkite.com/llvm-project/clang-ci/builds/10874#018d49c2-1224-4939-9430-0e5a2be796a9
 .

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread via cfe-commits
=?utf-8?q?G=C3=A1bor?= Spaits,Gabor Spaits ,Gabor
 Spaits 
Message-ID:
In-Reply-To: 


cor3ntin wrote:

It's unrelated to your changes. Configuration issue on the CI, probably 

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


[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread Gábor Spaits via cfe-commits

spaits wrote:

> It's unrelated to your changes. Configuration issue on the CI, probably

Okay. Then I will merge this.

Thank you very much for reviewing my PR and helping me.

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


[clang] 7fcba00 - [Sema] Substitute parameter packs when deduced from function arguments (#79371)

2024-01-27 Thread via cfe-commits

Author: Gábor Spaits
Date: 2024-01-27T10:43:38+01:00
New Revision: 7fcba000e90b85ce1236a1d43bebb8128332580e

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

LOG: [Sema] Substitute parameter packs when deduced from function arguments 
(#79371)

This pull request would solve
https://github.com/llvm/llvm-project/issues/78449 .
There is also a discussion about this on stackoverflow:
https://stackoverflow.com/questions/77832658/stdtype-identity-to-support-several-variadic-argument-lists
.

The following program is well formed:
```cpp
#include 

template 
struct args_tag
{
using type = std::common_type_t;
};

template 
void bar(args_tag, std::type_identity_t..., int, 
std::type_identity_t...) {}

// example
int main() {
bar(args_tag{}, 4, 8, 15, 16, 23);
}
```

but Clang rejects it, while GCC and MSVC doesn't. The reason for this is
that, in `Sema::DeduceTemplateArguments` we are not prepared for this
case.

# Substitution/deduction of parameter packs
The logic that handles substitution when we have explicit template
arguments (`SubstituteExplicitTemplateArguments`) does not work here,
since the types of the pack are not pushed to `ParamTypes` before the
loop starts that does the deduction.
The other "candidate" that may could have handle this case would be the
loop that does the deduction for trailing packs, but we are not dealing
with trailing packs here.

# Solution proposed in this PR
The solution proposed in this PR works similar to the trailing pack
deduction. The main difference here is the end of the deduction cycle.
When a non-trailing template pack argument is found, whose type is not
explicitly specified and the next type is not a pack type, the length of
the previously deduced pack is retrieved (let that length be `s`). After
that the next `s` arguments are processed in the same way as in the case
of non trailing packs.

# Another possible solution
There is another possible approach that would be less efficient. In the
loop when we get to an element of `ParamTypes` that is a pack and could
be substituted because the type is deduced from a previous argument,
then `s` number of arg types would be inserted before the current
element of `ParamTypes` type. Then we would "cancel" the processing of
the current element, first process the previously inserted elements and
the after that re-process the current element.
Basically we would do what `SubstituteExplicitTemplateArguments` does
but during deduction.

# Adjusted test cases
In
`clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.call/p1-0x.cpp`
there is a test case named `test_pack_not_at_end` that should work, but
still does not. This test case is relevant because the note for the
error message has changed.
This is what the test case looks like currently:
```cpp
template
void pack_not_at_end(tuple, Types... values, int); // expected-note 
{{ vs. }}

void test_pack_not_at_end(tuple t2) {
  pack_not_at_end(t2, 0, 0, 0); // expected-error {{no match}}
  // FIXME: Should the "original argument type must match deduced parameter
  // type" rule apply here?
  pack_not_at_end(t2, 0, 0, 0); // ok
}

```

The previous note said (before my changes):
```
deduced conflicting types for parameter 'Types' ( vs. <>)

The current note says (after my changesand also clang 14 would say this
if the pack was not trailing):
```
deduced conflicting types for parameter 'Types' ( vs. )
```
GCC says: 
```
error: no matching function for call to ‘pack_not_at_end(std::tuple&, int, int, int)’
   70 | pack_not_at_end(t2, 0, 0, 9); // expected-error {{no match}}


-

Co-authored-by: cor3ntin 
Co-authored-by: Erich Keane 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.call/p1-0x.cpp
clang/test/SemaTemplate/deduction.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 905a1f3aa3067b..aa06e2b60ce915 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -73,6 +73,9 @@ C++2c Feature Support
 
 Resolutions to C++ Defect Reports
 ^
+- Substitute template parameter pack, when it is not explicitly specified
+  in the template parameters, but is deduced from a previous argument.
+  (`#78449: `_).
 
 C Language Changes
 --

diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index c9234bf30a5286..25e58f7bdd953d 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -731,6 +731,7 @@ class PackDeductionScope {
   void addPack(unsigned Index) {
 // Save the de

[clang] [Sema] Substitute parameter packs when deduced from function arguments (PR #79371)

2024-01-27 Thread Gábor Spaits via cfe-commits

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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

I have confirmed that the libcxx issues are unrelated. Feel free to merge :)

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits

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

>From 391254191932c8ca325346978de5c57b233cbab8 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Tue, 16 Jan 2024 08:05:33 -0500
Subject: [PATCH] Reapply "[Clang][Sema] Diagnose function/variable templates
 that shadow their own template parameters (#78274)"

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/include/clang/Sema/Sema.h   |  3 +-
 clang/lib/Sema/SemaDecl.cpp   | 34 +--
 clang/lib/Sema/SemaTemplate.cpp   |  9 +++--
 .../test/CXX/temp/temp.res/temp.local/p6.cpp  | 22 +---
 6 files changed, 55 insertions(+), 18 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..0fd8f69930ddfcf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -42,6 +42,8 @@ C/C++ Language Potentially Breaking Changes
 
 C++ Specific Potentially Breaking Changes
 -
+- Clang now diagnoses function/variable templates that shadow their own 
template parameters, e.g. ``template void T();``.
+  This error can be disabled via `-Wno-strict-primary-template-shadow` for 
compatibility with previous versions of clang.
 
 ABI Changes in This Version
 ---
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 649de9f47c46195..4e3b20548913ab5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4966,6 +4966,9 @@ def err_template_param_shadow : Error<
   "declaration of %0 shadows template parameter">;
 def ext_template_param_shadow : ExtWarn<
   err_template_param_shadow.Summary>, InGroup;
+def ext_compat_template_param_shadow : ExtWarn<
+  err_template_param_shadow.Summary>, InGroup<
+  DiagGroup<"strict-primary-template-shadow">>, DefaultError;
 def note_template_param_here : Note<"template parameter is declared here">;
 def note_template_param_external : Note<
   "template parameter from hidden source: %0">;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff73581..d0fb4f09916eda4 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8256,7 +8256,8 @@ class Sema final {
   TemplateSpecializationKind TSK,
   bool Complain = true);
 
-  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
+  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning = false);
   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
 
   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f9bf1d14bdc4f68..2e10a3057cfbee6 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -6377,12 +6377,6 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
 return nullptr;
 
-  // The scope passed in may not be a decl scope.  Zip up the scope tree until
-  // we find one that is.
-  while ((S->getFlags() & Scope::DeclScope) == 0 ||
- (S->getFlags() & Scope::TemplateParamScope) != 0)
-S = S->getParent();
-
   DeclContext *DC = CurContext;
   if (D.getCXXScopeSpec().isInvalid())
 D.setInvalidType();
@@ -6506,12 +6500,26 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
 RemoveUsingDecls(Previous);
   }
 
-  if (Previous.isSingleResult() &&
-  Previous.getFoundDecl()->isTemplateParameter()) {
+  // if (Previous.isSingleResult() &&
+  //Previous.getFoundDecl()->isTemplateParameter()) {
+  if (auto *TPD = Previous.getAsSingle();
+  TPD && TPD->isTemplateParameter()) {
+// Older versions of clang allowed the names of function/variable templates
+// to shadow the names of their template parameters. For the compatibility
+// purposes we detect such cases and issue a default-to-error warning that
+// can be disabled with -Wno-strict-primary-template-shadow.
+bool IssueShadowingWarning = false;
+for (Scope *Inner = S; (Inner->getFlags() & Scope::DeclScope) == 0 ||
+   Inner->isTemplateParamScope();
+ Inner = Inner->getParent()) {
+  if (IssueShadowingWarning = Inner->isDeclScope(TPD))
+break;
+}
+
 // Maybe we will complain about the shadowed template parameter.
 if (!D.isInvalidType())
-  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-  Previous.getFoundDecl());
+  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
+  IssueShadowingWar

[clang] [Serialization] Load Specializations Lazily (PR #76774)

2024-01-27 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

How about taking a step at a time with this patch. Perhaps we should introduce 
the on-disk hash table infrastructure and always deserialize everything. Then 
we can verify that part works on our build infrastructure and then move on with 
the deferring the template loading. I believe that should be relatively easy to 
achieve with the current version of the patch.

Essentially I am proposing making `-fno-load-external-specializations-lazily` 
default so that we can test it without having to modify build infrastructure...

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


[clang] [clang-format] Add AllowShortType option for AlwaysBreakAfterReturnType. (PR #78011)

2024-01-27 Thread Owen Pan via cfe-commits

owenca wrote:

OTOH, if we change `LLVMStyle.AlwaysBreakAfterReturnType` to 
`RTBS_AllowShortType`, we get the following:
```
$ ninja polly-check-format
[24/105] Checking format of /Users/Owe...olly/include/polly/DependenceInfo.h...
FAILED: tools/polly/polly-check-format16 
/Users/Owen/llvm-project/build/tools/polly/polly-check-format16 
cd /Users/Owen/llvm-project/build/tools/polly && 
/Users/Owen/llvm-project/build/bin/clang-format -sort-includes -style=llvm 
/Users/Owen/llvm-project/polly/include/polly/DependenceInfo.h | diff -u 
/Users/Owen/llvm-project/polly/include/polly/DependenceInfo.h -
--- /Users/Owen/llvm-project/polly/include/polly/DependenceInfo.h   
2024-01-05 20:24:43
+++ -   2024-01-27 02:13:13
@@ -332,8 +332,8 @@
 void initializeDependenceInfoPass(llvm::PassRegistry &);
 void initializeDependenceInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeDependenceInfoWrapperPassPass(llvm::PassRegistry &);
-void initializeDependenceInfoPrinterLegacyFunctionPassPass(
-llvm::PassRegistry &);
+void
+initializeDependenceInfoPrinterLegacyFunctionPassPass(llvm::PassRegistry &);
 } // namespace llvm
 
 #endif
[26/105] Checking format of /Users/Owe...polly/include/polly/LinkAllPasses.h...
FAILED: tools/polly/polly-check-format21 
/Users/Owen/llvm-project/build/tools/polly/polly-check-format21 
cd /Users/Owen/llvm-project/build/tools/polly && 
/Users/Owen/llvm-project/build/bin/clang-format -sort-includes -style=llvm 
/Users/Owen/llvm-project/polly/include/polly/LinkAllPasses.h | diff -u 
/Users/Owen/llvm-project/polly/include/polly/LinkAllPasses.h -
--- /Users/Owen/llvm-project/polly/include/polly/LinkAllPasses.h
2024-01-05 20:58:16
+++ -   2024-01-27 02:13:13
@@ -138,8 +138,8 @@
 void initializeDependenceInfoPass(llvm::PassRegistry &);
 void initializeDependenceInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeDependenceInfoWrapperPassPass(llvm::PassRegistry &);
-void initializeDependenceInfoPrinterLegacyFunctionPassPass(
-llvm::PassRegistry &);
+void
+initializeDependenceInfoPrinterLegacyFunctionPassPass(llvm::PassRegistry &);
 void initializeIslAstInfoWrapperPassPass(llvm::PassRegistry &);
 void initializeIslAstInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeCodeGenerationPass(llvm::PassRegistry &);
[33/105] Checking format of /Users/Owe...ect/polly/unittests/Isl/IslTest.cpp...
ninja: build stopped: subcommand failed.
```
which is an improvement IMO.

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {

cor3ntin wrote:

Can this be called `ShadowsFunctionOrVariableName` or something like that ? It 
might be clearer

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits


@@ -6535,6 +6543,12 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   if (getLangOpts().CPlusPlus)
 CheckExtraCXXDefaultArguments(D);
 
+  // The scope passed in may not be a decl scope.  Zip up the scope tree until
+  // we find one that is.
+  while ((S->getFlags() & Scope::DeclScope) == 0 ||
+ (S->getFlags() & Scope::TemplateParamScope) != 0)
+S = S->getParent();

cor3ntin wrote:

We do that in at least 3 places (search for `(S->getFlags() & 
Scope::DeclScope)` )
Can we add a `Scope::getInnermostEnclosingDeclarativeScope()` or something like 
that ?

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {
   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
 
   // C++ [temp.local]p4:
   //   A template-parameter shall not be redeclared within its
   //   scope (including nested scopes).
   //
   // Make this a warning when MSVC compatibility is requested.
-  unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
- : diag::err_template_param_shadow;
+  unsigned DiagId = getLangOpts().MSVCCompat
+? diag::ext_template_param_shadow
+: (IssueWarning ? 
diag::ext_compat_template_param_shadow

cor3ntin wrote:

A comment there too would not hurt

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


[clang] [clang-repl] fix segfault in CleanUpPTU() (PR #75629)

2024-01-27 Thread Pavel Kalugin via cfe-commits

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


[clang] [clang-repl] fix segfault in CleanUpPTU() (PR #75629)

2024-01-27 Thread Pavel Kalugin via cfe-commits

p4vook wrote:

I converted the PR to draft, as this seems to be a part of a bigger problem 
with inserting statements into wrong nodes of the syntax tree (this seems to 
only show up when namespaces are present). I believe it shouldn't be fixed just 
by a simple check for `nullptr`.

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


[compiler-rt] [mlir] [llvm] [flang] [clang] [clang-tools-extra] [libunwind] [libc] [lld] [libcxx] [lldb] Reland: [libc++][format] P2637R3: Member visit (std::basic_format_arg) #76449 (PR #79032)

2024-01-27 Thread Hristo Hristov via cfe-commits

H-G-Hristov wrote:

> I tried this branch on our Windows builders although I'm not sure if it's 
> related or not to this patch:
> 
> ```
> # COMPILED WITH
> C:/b/s/w/ir/x/w/llvm_build/./bin/clang-cl.exe 
> C:\b\s\w\ir\x\w\github-H-G-Hristov-llvm-project\libcxx\test\libcxx\fuzzing\random.pass.cpp
>  --driver-mode=g++ --target=x86_64-pc-windows-msvc -fms-runtime-lib=static 
> -nostdinc++ -I C:/b/s/w/ir/x/w/llvm_build/include/c++/v1 -I 
> C:/b/s/w/ir/x/w/llvm_build/include/x86_64-pc-windows-msvc/c++/v1 -I 
> C:/b/s/w/ir/x/w/github-H-G-Hristov-llvm-project/libcxx/test/support 
> -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_WARNINGS 
> -D_CRT_STDIO_ISO_WIDE_SPECIFIERS -DNOMINMAX -std=c++26 -Werror -Wall 
> -Wctad-maybe-unsupported -Wextra -Wshadow -Wundef -Wunused-template 
> -Wno-unused-command-line-argument -Wno-attributes -Wno-pessimizing-move 
> -Wno-noexcept-type -Wno-atomic-alignment -Wno-reserved-module-identifier 
> -Wdeprecated-copy -Wdeprecated-copy-dtor -Wno-user-defined-literals 
> -Wno-tautological-compare -Wsign-compare -Wunused-variable -Wunused-parameter 
> -Wunreachable-code -Wno-unused-local-typedef -Wno-local-type-template-args 
> -Wno-c++11-extensions -Wno-unknown-pragmas -Wno-pass-failed 
> -Wno-mismatched-new-delete -Wno-redundant-move -Wno-self-move 
> -D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D_LIBCPP_ENABLE_EXPERIMENTAL 
> -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_NONE -Werror=thread-safety 
> -Wuser-defined-warnings  -llibc++experimental -nostdlib -L 
> C:/b/s/w/ir/x/w/llvm_build/./lib/x86_64-pc-windows-msvc -llibc++ -llibcpmt -o 
> C:\b\s\w\ir\x\w\llvm_build\runtimes\runtimes-x86_64-pc-windows-msvc-bins\test\libcxx\fuzzing\Output\random.pass.cpp.dir\t.tmp.exe
> # executed command: C:/b/s/w/ir/x/w/llvm_build/./bin/clang-cl.exe 
> 'C:\b\s\w\ir\x\w\github-H-G-Hristov-llvm-project\libcxx\test\libcxx\fuzzing\random.pass.cpp'
>  --driver-mode=g++ --target=x86_64-pc-windows-msvc -fms-runtime-lib=static 
> -nostdinc++ -I C:/b/s/w/ir/x/w/llvm_build/include/c++/v1 -I 
> C:/b/s/w/ir/x/w/llvm_build/include/x86_64-pc-windows-msvc/c++/v1 -I 
> C:/b/s/w/ir/x/w/github-H-G-Hristov-llvm-project/libcxx/test/support 
> -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_WARNINGS 
> -D_CRT_STDIO_ISO_WIDE_SPECIFIERS -DNOMINMAX -std=c++26 -Werror -Wall 
> -Wctad-maybe-unsupported -Wextra -Wshadow -Wundef -Wunused-template 
> -Wno-unused-command-line-argument -Wno-attributes -Wno-pessimizing-move 
> -Wno-noexcept-type -Wno-atomic-alignment -Wno-reserved-module-identifier 
> -Wdeprecated-copy -Wdeprecated-copy-dtor -Wno-user-defined-literals 
> -Wno-tautological-compare -Wsign-compare -Wunused-variable -Wunused-parameter 
> -Wunreachable-code -Wno-unused-local-typedef -Wno-local-type-template-args 
> -Wno-c++11-extensions -Wno-unknown-pragmas -Wno-pass-failed 
> -Wno-mismatched-new-delete -Wno-redundant-move -Wno-self-move 
> -D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D_LIBCPP_ENABLE_EXPERIMENTAL 
> -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_NONE -Werror=thread-safety 
> -Wuser-defined-warnings -llibc++experimental -nostdlib -L 
> C:/b/s/w/ir/x/w/llvm_build/./lib/x86_64-pc-windows-msvc -llibc++ -llibcpmt -o 
> 'C:\b\s\w\ir\x\w\llvm_build\runtimes\runtimes-x86_64-pc-windows-msvc-bins\test\libcxx\fuzzing\Output\random.pass.cpp.dir\t.tmp.exe'
> # .---command stderr
> # | In file included from 
> C:\b\s\w\ir\x\w\github-H-G-Hristov-llvm-project\libcxx\test\libcxx\fuzzing\random.pass.cpp:16:
> # | In file included from C:/b/s/w/ir/x/w/llvm_build/include/c++/v1\cmath:319:
> # | In file included from 
> C:/b/s/w/ir/x/w/llvm_build/include/c++/v1\math.h:301:
> # | In file included from C:\b\s\w\ir\cache\windows_sdk\Windows 
> Kits\10\Include\10.0.19041.0\ucrt\math.h:11:
> # | C:\b\s\w\ir\cache\windows_sdk\Windows 
> Kits\10\Include\10.0.19041.0\ucrt\corecrt_math.h:413:16: error: call to 
> 'fpclassify' is ambiguous
> # |   413 | return fpclassify(_X) == FP_NAN;
> # |   |^~
> # | 
> C:\b\s\w\ir\x\w\github-H-G-Hristov-llvm-project\libcxx\test\libcxx\fuzzing\random.pass.cpp:166:12:
>  note: in instantiation of function template specialization 'isnan' 
> requested here
> # |   166 |   if (std::isnan(res)) {
> # |   |^
> # | 
> C:\b\s\w\ir\x\w\github-H-G-Hristov-llvm-project\libcxx\test\libcxx\fuzzing\random.pass.cpp:178:10:
>  note: in instantiation of function template specialization 
> 'helper>' requested here
> # |   178 |   return 
> helper>(data, size)   ||
> # |   |  ^
> # | C:\b\s\w\ir\cache\windows_sdk\Windows 
> Kits\10\Include\10.0.19041.0\ucrt\corecrt_math.h:288:31: note: candidate 
> function
> # |   288 | _Check_return_ inline int fpclassify(_In_ float _X) throw()
> # |   |   ^
> # | C:\b\s\w\ir\cache\windows_sdk\Windows 
> Kits\10\Include\10.0.19041.0\ucrt\corecrt_math.h:293:31: note: candidate 
> function
> # |   293 | _Check_return_ inline int fpclassify(_In_ double _X) throw()
> # |   | 

[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

This triggers asan on bots, fix coming in the next couple hours.

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits


@@ -6535,6 +6543,12 @@ NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator 
&D,
   if (getLangOpts().CPlusPlus)
 CheckExtraCXXDefaultArguments(D);
 
+  // The scope passed in may not be a decl scope.  Zip up the scope tree until
+  // we find one that is.
+  while ((S->getFlags() & Scope::DeclScope) == 0 ||
+ (S->getFlags() & Scope::TemplateParamScope) != 0)
+S = S->getParent();

sdkrystian wrote:

I was planning to do that in a separate PR... but I could just throw in here I 
suppose 

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


[lld] [clang-tools-extra] [libcxx] [flang] [clang] [libc] [lldb] [compiler-rt] [llvm] [VPlan] Implement cloning of VPlans. (PR #73158)

2024-01-27 Thread Florian Hahn via cfe-commits

https://github.com/fhahn updated https://github.com/llvm/llvm-project/pull/73158

>From 13a26e8e7440c3b501730b22588af393a3e543cd Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Thu, 6 Jul 2023 08:07:45 +0100
Subject: [PATCH 1/4] [VPlan] Implement cloning of VPlans.

This patch implements cloning for VPlans and recipes. Cloning is used in
the epilogue vectorization path, to clone the VPlan for the main vector
loop. This means we won't re-use a VPlan when executing the VPlan for
the epilogue vector loop, which in turn will enable us to perform
optimizations based on UF & VF.
---
 .../Transforms/Vectorize/LoopVectorize.cpp|   2 +-
 llvm/lib/Transforms/Vectorize/VPlan.cpp   | 124 
 llvm/lib/Transforms/Vectorize/VPlan.h | 182 ++
 .../Transforms/Vectorize/VPlanTest.cpp|   2 +
 4 files changed, 309 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp 
b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 10c068e3b5895c2..9ffd44d59ffc6de 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -10078,7 +10078,7 @@ bool LoopVectorizePass::processLoop(Loop *L) {
 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
EPI, &LVL, &CM, BFI, PSI, Checks);
 
-VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
+VPlan &BestMainPlan = *LVP.getBestPlanFor(EPI.MainLoopVF).clone();
 const auto &[ExpandedSCEVs, ReductionResumeValues] = LVP.executePlan(
 EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV, DT, true);
 ++LoopsVectorized;
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.cpp 
b/llvm/lib/Transforms/Vectorize/VPlan.cpp
index b6e56c47c227f77..99b2a3bd59a64df 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlan.cpp
@@ -615,6 +615,18 @@ void VPBasicBlock::print(raw_ostream &O, const Twine 
&Indent,
 }
 #endif
 
+VPBlockBase *VPRegionBlock::clone() {
+  DenseMap Old2New;
+  DenseMap Old2NewVPValues;
+  VPBlockBase *NewEntry =
+  VPBlockUtils::cloneCFG(Entry, Old2New, Old2NewVPValues);
+  auto *NewR =
+  new VPRegionBlock(NewEntry, Old2New[Exiting], getName(), isReplicator());
+  for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
+Block->setParent(NewR);
+  return NewR;
+}
+
 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
 // Drop all references in VPBasicBlocks and replace all uses with
@@ -982,6 +994,65 @@ void VPlan::updateDominatorTree(DominatorTree *DT, 
BasicBlock *LoopHeaderBB,
   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
 }
 
+static void remapVPValues(VPBasicBlock *OldBB, VPBasicBlock *NewBB,
+  DenseMap &Old2NewVPValues,
+  bool Full = false) {
+  for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
+for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
+  VPValue *NewOp = Old2NewVPValues.lookup(OldR.getOperand(I));
+  if (!Full)
+continue;
+  NewR.setOperand(I, NewOp);
+}
+for (const auto &[OldV, NewV] :
+ zip(OldR.definedValues(), NewR.definedValues()))
+  Old2NewVPValues[OldV] = NewV;
+  }
+}
+
+VPlan *VPlan::clone() {
+  DenseMap Old2New;
+  DenseMap Old2NewVPValues;
+
+  auto *NewPlan = new VPlan();
+  SmallVector NewLiveIns;
+  for (VPValue *LI : VPLiveInsToFree) {
+VPValue *NewLI = new VPValue(LI->getLiveInIRValue());
+NewPlan->VPLiveInsToFree.push_back(NewLI);
+Old2NewVPValues[LI] = NewLI;
+  }
+
+  Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
+  Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
+  if (BackedgeTakenCount) {
+Old2NewVPValues[BackedgeTakenCount] = new VPValue();
+NewPlan->BackedgeTakenCount = Old2NewVPValues[BackedgeTakenCount];
+  }
+
+  auto NewPH = cast(Preheader->clone());
+  remapVPValues(cast(Preheader), cast(NewPH),
+Old2NewVPValues, /*Full*/ true);
+  VPValue *NewTC = Old2NewVPValues.lookup(TripCount);
+  if (!NewTC)
+Old2NewVPValues[TripCount] = new VPValue(TripCount->getLiveInIRValue());
+  NewPlan->TripCount = Old2NewVPValues[TripCount];
+
+  auto *NewEntry = cast(VPBlockUtils::cloneCFG(
+  getEntry(), Old2New, Old2NewVPValues, /*FullRemapping*/ true));
+
+  NewPlan->Entry = NewEntry;
+  NewPlan->Preheader = NewPH;
+  NewEntry->setPlan(NewPlan);
+  NewPH->setPlan(NewPlan);
+  NewPlan->VFs = VFs;
+  NewPlan->UFs = UFs;
+  NewPlan->Name = Name;
+
+  for (const auto &[_, LO] : LiveOuts)
+NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
+  return NewPlan;
+}
+
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 
 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
@@ -1200,6 +1271,59 @@ void VPUser::printOperands(raw_ostream &O, VPSlotTracker 
&SlotTracker) const {
 }
 #end

[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {

sdkrystian wrote:

I think the more generic `IssueWarning` is less ambiguous. We only issue the 
warning for variable/function templates the shadow _their own_ template 
parameters. For example:
```cpp
template
struct A
{
template void U(); // warning
template void T(); // error
void T(); // error
};
```
`ShadowsFunctionOrVariableName` establishes the expectation that its value will 
be `true` for all the above function declarations (its only `true` for the 
first one).

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


[polly] [clang] [clang-format] Add AllowShortType option for AlwaysBreakAfterReturnType. (PR #78011)

2024-01-27 Thread via cfe-commits

https://github.com/rmarker updated 
https://github.com/llvm/llvm-project/pull/78011

>From a1312a0a463bb946f336977b5b01ef7afbede678 Mon Sep 17 00:00:00 2001
From: rmarker 
Date: Thu, 11 Jan 2024 15:01:18 +1030
Subject: [PATCH 1/7] [clang-format] Add ShortReturnTypeColumn option.

---
 clang/docs/ClangFormatStyleOptions.rst | 13 +++
 clang/docs/ReleaseNotes.rst|  1 +
 clang/include/clang/Format/Format.h| 12 ++
 clang/lib/Format/ContinuationIndenter.cpp  |  3 +-
 clang/lib/Format/Format.cpp|  2 +
 clang/unittests/Format/ConfigParseTest.cpp |  1 +
 clang/unittests/Format/FormatTest.cpp  | 44 ++
 7 files changed, 75 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4dc0de3a90f2650..7836cc8f1c9bb5b 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -4999,6 +4999,19 @@ the configuration (without a prefix: ``Auto``).
int bar;   int bar;
  } // namespace b   } // namespace b
 
+.. _ShortReturnTypeColumn:
+
+**ShortReturnTypeColumn** (``Unsigned``) :versionbadge:`clang-format 19` 
:ref:`¶ `
+  When ``AlwaysBreakAfterReturnType`` is ``None``, line breaks are prevented
+  after short return types. This configures the column limit for a type
+  to be regarded as short.
+
+
+  .. note::
+
+   This isn't the length of the type itself, but the column where it
+   finishes. I.e. it includes indentation, etc.
+
 .. _SkipMacroDefinitionBody:
 
 **SkipMacroDefinitionBody** (``Boolean``) :versionbadge:`clang-format 18` 
:ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..669b420fe21ec15 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -184,6 +184,7 @@ AST Matchers
 
 clang-format
 
+- Add ``ShortReturnTypeColumn`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index bc9eecd42f9ebfd..7fd574c98a3944f 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3932,6 +3932,17 @@ struct FormatStyle {
   /// \version 13
   unsigned ShortNamespaceLines;
 
+  /// When ``AlwaysBreakAfterReturnType`` is ``None``, line breaks are 
prevented
+  /// after short return types. This configures the column limit for a type
+  /// to be regarded as short.
+  ///
+  /// \note
+  ///  This isn't the length of the type itself, but the column where it
+  ///  finishes. I.e. it includes indentation, etc.
+  /// \endnote
+  /// \version 19
+  unsigned ShortReturnTypeColumn;
+
   /// Do not format macro definition body.
   /// \version 18
   bool SkipMacroDefinitionBody;
@@ -4899,6 +4910,7 @@ struct FormatStyle {
RequiresExpressionIndentation == R.RequiresExpressionIndentation &&
SeparateDefinitionBlocks == R.SeparateDefinitionBlocks &&
ShortNamespaceLines == R.ShortNamespaceLines &&
+   ShortReturnTypeColumn == R.ShortReturnTypeColumn &&
SkipMacroDefinitionBody == R.SkipMacroDefinitionBody &&
SortIncludes == R.SortIncludes &&
SortJavaStaticImport == R.SortJavaStaticImport &&
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index a3eb9138b218335..3f9c0cc815745c3 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -328,7 +328,8 @@ bool ContinuationIndenter::canBreak(const LineState &State) 
{
 
   // Don't break after very short return types (e.g. "void") as that is often
   // unexpected.
-  if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
+  if (Current.is(TT_FunctionDeclarationName) &&
+  State.Column <= Style.ShortReturnTypeColumn) {
 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
   return false;
   }
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ff326dc784783b2..35478fac7b49629 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1085,6 +1085,7 @@ template <> struct MappingTraits {
Style.RequiresExpressionIndentation);
 IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
+IO.mapOptional("ShortReturnTypeColumn", Style.ShortReturnTypeColumn);
 IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
 IO.mapOptional("SortIncludes", Style.SortIncludes);
 IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
@@ -1557,6 +1558,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
   LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
   LLVMStyle.ShortNamespaceLi

[polly] [clang] [clang-format] Add AllowShortType option for AlwaysBreakAfterReturnType. (PR #78011)

2024-01-27 Thread via cfe-commits

rmarker wrote:

Sounds good.

Updated formatting in polly.

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


[polly] [clang] [clang-format] Add AllowShortType option for AlwaysBreakAfterReturnType. (PR #78011)

2024-01-27 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff c23608b8d58bdeb0134d99168e6d0335da2c8366 
01fd15c864b01218d36f1acd86da8476cddf97c8 -- clang/include/clang/Format/Format.h 
clang/lib/Format/ContinuationIndenter.cpp clang/lib/Format/Format.cpp 
clang/lib/Format/TokenAnnotator.cpp clang/unittests/Format/ConfigParseTest.cpp 
clang/unittests/Format/FormatTest.cpp 
clang/unittests/Format/FormatTestSelective.cpp 
polly/include/polly/DependenceInfo.h polly/include/polly/LinkAllPasses.h 
polly/lib/Analysis/DependenceInfo.cpp polly/lib/Analysis/ScopBuilder.cpp 
polly/lib/Analysis/ScopDetection.cpp polly/lib/CodeGen/IslNodeBuilder.cpp 
polly/lib/Transform/MaximalStaticExpansion.cpp 
polly/lib/Transform/ScheduleOptimizer.cpp
``





View the diff from clang-format here.


``diff
diff --git a/polly/include/polly/DependenceInfo.h 
b/polly/include/polly/DependenceInfo.h
index fb7b1740ea..7526a294c6 100644
--- a/polly/include/polly/DependenceInfo.h
+++ b/polly/include/polly/DependenceInfo.h
@@ -332,8 +332,8 @@ namespace llvm {
 void initializeDependenceInfoPass(llvm::PassRegistry &);
 void initializeDependenceInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeDependenceInfoWrapperPassPass(llvm::PassRegistry &);
-void
-initializeDependenceInfoPrinterLegacyFunctionPassPass(llvm::PassRegistry &);
+void initializeDependenceInfoPrinterLegacyFunctionPassPass(
+llvm::PassRegistry &);
 } // namespace llvm
 
 #endif
diff --git a/polly/include/polly/LinkAllPasses.h 
b/polly/include/polly/LinkAllPasses.h
index a293b7074f..a2f8f33299 100644
--- a/polly/include/polly/LinkAllPasses.h
+++ b/polly/include/polly/LinkAllPasses.h
@@ -138,8 +138,8 @@ void 
initializeJSONImporterPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeDependenceInfoPass(llvm::PassRegistry &);
 void initializeDependenceInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeDependenceInfoWrapperPassPass(llvm::PassRegistry &);
-void
-initializeDependenceInfoPrinterLegacyFunctionPassPass(llvm::PassRegistry &);
+void initializeDependenceInfoPrinterLegacyFunctionPassPass(
+llvm::PassRegistry &);
 void initializeIslAstInfoWrapperPassPass(llvm::PassRegistry &);
 void initializeIslAstInfoPrinterLegacyPassPass(llvm::PassRegistry &);
 void initializeCodeGenerationPass(llvm::PassRegistry &);
diff --git a/polly/lib/Analysis/DependenceInfo.cpp 
b/polly/lib/Analysis/DependenceInfo.cpp
index 3da6738b64..69257c6038 100644
--- a/polly/lib/Analysis/DependenceInfo.cpp
+++ b/polly/lib/Analysis/DependenceInfo.cpp
@@ -647,9 +647,8 @@ bool Dependences::isValidSchedule(Scop &S, isl::schedule 
NewSched) const {
   return isValidSchedule(S, NewSchedules);
 }
 
-bool
-Dependences::isValidSchedule(Scop &S,
- const StatementToIslMapTy &NewSchedule) const {
+bool Dependences::isValidSchedule(
+Scop &S, const StatementToIslMapTy &NewSchedule) const {
   if (LegalityCheckDisabled)
 return true;
 
diff --git a/polly/lib/Analysis/ScopBuilder.cpp 
b/polly/lib/Analysis/ScopBuilder.cpp
index c14b01116e..c62cb2a85c 100644
--- a/polly/lib/Analysis/ScopBuilder.cpp
+++ b/polly/lib/Analysis/ScopBuilder.cpp
@@ -827,9 +827,8 @@ void ScopBuilder::buildInvariantEquivalenceClasses() {
   }
 }
 
-bool
-ScopBuilder::buildDomains(Region *R,
-  DenseMap &InvalidDomainMap) {
+bool ScopBuilder::buildDomains(
+Region *R, DenseMap &InvalidDomainMap) {
   bool IsOnlyNonAffineRegion = scop->isNonAffineSubRegion(R);
   auto *EntryBB = R->getEntry();
   auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
@@ -3298,9 +3297,8 @@ bool ScopBuilder::buildAliasGroups() {
   return true;
 }
 
-bool
-ScopBuilder::buildAliasGroup(AliasGroupTy &AliasGroup,
- DenseSet HasWriteAccess) {
+bool ScopBuilder::buildAliasGroup(
+AliasGroupTy &AliasGroup, DenseSet HasWriteAccess) {
   AliasGroupTy ReadOnlyAccesses;
   AliasGroupTy ReadWriteAccesses;
   SmallPtrSet ReadWriteArrays;
diff --git a/polly/lib/Analysis/ScopDetection.cpp 
b/polly/lib/Analysis/ScopDetection.cpp
index 8af4986dc1..938d3f1496 100644
--- a/polly/lib/Analysis/ScopDetection.cpp
+++ b/polly/lib/Analysis/ScopDetection.cpp
@@ -978,10 +978,9 @@ bool ScopDetection::hasValidArraySizes(DetectionContext 
&Context,
 // non-affine accesses are allowed, we drop the information. In case the
 // information is dropped the memory accesses need to be overapproximated
 // when translated to a polyhedral representation.
-bool
-ScopDetection::computeAccessFunctions(DetectionContext &Context,
-  const SCEVUnknown *BasePointer,
-  std::shared_ptr Shape) const 
{
+bool ScopDetection::computeAccessFunctions(
+DetectionContext &Context, const SCEVUnknown *BasePointer,
+std::shared_ptr Shape)

[lld] [clang-tools-extra] [libcxx] [flang] [clang] [libc] [lldb] [compiler-rt] [llvm] [VPlan] Implement cloning of VPlans. (PR #73158)

2024-01-27 Thread Florian Hahn via cfe-commits

https://github.com/fhahn updated https://github.com/llvm/llvm-project/pull/73158

>From 13a26e8e7440c3b501730b22588af393a3e543cd Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Thu, 6 Jul 2023 08:07:45 +0100
Subject: [PATCH 1/5] [VPlan] Implement cloning of VPlans.

This patch implements cloning for VPlans and recipes. Cloning is used in
the epilogue vectorization path, to clone the VPlan for the main vector
loop. This means we won't re-use a VPlan when executing the VPlan for
the epilogue vector loop, which in turn will enable us to perform
optimizations based on UF & VF.
---
 .../Transforms/Vectorize/LoopVectorize.cpp|   2 +-
 llvm/lib/Transforms/Vectorize/VPlan.cpp   | 124 
 llvm/lib/Transforms/Vectorize/VPlan.h | 182 ++
 .../Transforms/Vectorize/VPlanTest.cpp|   2 +
 4 files changed, 309 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp 
b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 10c068e3b5895c2..9ffd44d59ffc6de 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -10078,7 +10078,7 @@ bool LoopVectorizePass::processLoop(Loop *L) {
 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
EPI, &LVL, &CM, BFI, PSI, Checks);
 
-VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
+VPlan &BestMainPlan = *LVP.getBestPlanFor(EPI.MainLoopVF).clone();
 const auto &[ExpandedSCEVs, ReductionResumeValues] = LVP.executePlan(
 EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV, DT, true);
 ++LoopsVectorized;
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.cpp 
b/llvm/lib/Transforms/Vectorize/VPlan.cpp
index b6e56c47c227f77..99b2a3bd59a64df 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlan.cpp
@@ -615,6 +615,18 @@ void VPBasicBlock::print(raw_ostream &O, const Twine 
&Indent,
 }
 #endif
 
+VPBlockBase *VPRegionBlock::clone() {
+  DenseMap Old2New;
+  DenseMap Old2NewVPValues;
+  VPBlockBase *NewEntry =
+  VPBlockUtils::cloneCFG(Entry, Old2New, Old2NewVPValues);
+  auto *NewR =
+  new VPRegionBlock(NewEntry, Old2New[Exiting], getName(), isReplicator());
+  for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
+Block->setParent(NewR);
+  return NewR;
+}
+
 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
 // Drop all references in VPBasicBlocks and replace all uses with
@@ -982,6 +994,65 @@ void VPlan::updateDominatorTree(DominatorTree *DT, 
BasicBlock *LoopHeaderBB,
   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
 }
 
+static void remapVPValues(VPBasicBlock *OldBB, VPBasicBlock *NewBB,
+  DenseMap &Old2NewVPValues,
+  bool Full = false) {
+  for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
+for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
+  VPValue *NewOp = Old2NewVPValues.lookup(OldR.getOperand(I));
+  if (!Full)
+continue;
+  NewR.setOperand(I, NewOp);
+}
+for (const auto &[OldV, NewV] :
+ zip(OldR.definedValues(), NewR.definedValues()))
+  Old2NewVPValues[OldV] = NewV;
+  }
+}
+
+VPlan *VPlan::clone() {
+  DenseMap Old2New;
+  DenseMap Old2NewVPValues;
+
+  auto *NewPlan = new VPlan();
+  SmallVector NewLiveIns;
+  for (VPValue *LI : VPLiveInsToFree) {
+VPValue *NewLI = new VPValue(LI->getLiveInIRValue());
+NewPlan->VPLiveInsToFree.push_back(NewLI);
+Old2NewVPValues[LI] = NewLI;
+  }
+
+  Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
+  Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
+  if (BackedgeTakenCount) {
+Old2NewVPValues[BackedgeTakenCount] = new VPValue();
+NewPlan->BackedgeTakenCount = Old2NewVPValues[BackedgeTakenCount];
+  }
+
+  auto NewPH = cast(Preheader->clone());
+  remapVPValues(cast(Preheader), cast(NewPH),
+Old2NewVPValues, /*Full*/ true);
+  VPValue *NewTC = Old2NewVPValues.lookup(TripCount);
+  if (!NewTC)
+Old2NewVPValues[TripCount] = new VPValue(TripCount->getLiveInIRValue());
+  NewPlan->TripCount = Old2NewVPValues[TripCount];
+
+  auto *NewEntry = cast(VPBlockUtils::cloneCFG(
+  getEntry(), Old2New, Old2NewVPValues, /*FullRemapping*/ true));
+
+  NewPlan->Entry = NewEntry;
+  NewPlan->Preheader = NewPH;
+  NewEntry->setPlan(NewPlan);
+  NewPH->setPlan(NewPlan);
+  NewPlan->VFs = VFs;
+  NewPlan->UFs = UFs;
+  NewPlan->Name = Name;
+
+  for (const auto &[_, LO] : LiveOuts)
+NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
+  return NewPlan;
+}
+
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 
 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
@@ -1200,6 +1271,59 @@ void VPUser::printOperands(raw_ostream &O, VPSlotTracker 
&SlotTracker) const {
 }
 #end

[clang-tools-extra] [clangd] Fix is spelled in source bug (PR #76668)

2024-01-27 Thread Andrew Schenk via cfe-commits

https://github.com/schenka0 updated 
https://github.com/llvm/llvm-project/pull/76668

>From fd5e586d807fa4532f26188822ac5790202673bc Mon Sep 17 00:00:00 2001
From: schenka0 <154034018+schen...@users.noreply.github.com>
Date: Mon, 1 Jan 2024 01:31:05 -0500
Subject: [PATCH 1/4] Check for invalid SLocEntry before getting spelling

---
 clang-tools-extra/clangd/SourceCode.cpp   |  7 ++-
 .../clangd/unittests/SourceCodeTests.cpp  | 15 +++
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 835038423fdf372..8c573cc6fc064ae 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -232,7 +232,12 @@ bool isSpelledInSource(SourceLocation Loc, const 
SourceManager &SM) {
   if (Loc.isFileID())
 return true;
   auto Spelling = SM.getDecomposedSpellingLoc(Loc);
-  StringRef SpellingFile = SM.getSLocEntry(Spelling.first).getFile().getName();
+  bool InvalidSLocEntry = false;
+  const auto SLocEntry = SM.getSLocEntry(Spelling.first, &InvalidSLocEntry);
+  if (InvalidSLocEntry) {
+return false;
+  }
+  const StringRef SpellingFile = SLocEntry.getFile().getName();
   if (SpellingFile == "")
 return false;
   if (SpellingFile == "")
diff --git a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp 
b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
index 08abde87df6d4d0..5dced4d317c6059 100644
--- a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -813,6 +813,21 @@ TEST(SourceCodeTests, isKeywords) {
   EXPECT_FALSE(isKeyword("override", LangOpts));
 }
 
+TEST(SourceCodeTests, isSpelledInSource) {
+  Annotations Test(R"cpp(
+int abc = 1;
+)cpp");
+
+  ParsedAST AST = TestTU::withCode(Test.code()).build();
+  llvm::errs() << Test.code();
+  const SourceManager &SM = AST.getSourceManager();
+
+  EXPECT_TRUE(
+  isSpelledInSource(SM.getLocForStartOfFile(SM.getMainFileID()), SM));
+  EXPECT_TRUE(isSpelledInSource(SourceLocation(), SM));
+  EXPECT_FALSE(isSpelledInSource(SourceLocation::getFromRawEncoding(-1), SM));
+}
+
 struct IncrementalTestStep {
   llvm::StringRef Src;
   llvm::StringRef Contents;

>From 612c1fea8de7dfea67d5b4fdd23d6f13b9851607 Mon Sep 17 00:00:00 2001
From: schenka0 <154034018+schen...@users.noreply.github.com>
Date: Mon, 1 Jan 2024 11:49:24 -0500
Subject: [PATCH 2/4] Update clang-tools-extra/clangd/SourceCode.cpp

Co-authored-by: Younan Zhang 
---
 clang-tools-extra/clangd/SourceCode.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 8c573cc6fc064ae..58a0d142777d000 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -234,9 +234,8 @@ bool isSpelledInSource(SourceLocation Loc, const 
SourceManager &SM) {
   auto Spelling = SM.getDecomposedSpellingLoc(Loc);
   bool InvalidSLocEntry = false;
   const auto SLocEntry = SM.getSLocEntry(Spelling.first, &InvalidSLocEntry);
-  if (InvalidSLocEntry) {
+  if (InvalidSLocEntry)
 return false;
-  }
   const StringRef SpellingFile = SLocEntry.getFile().getName();
   if (SpellingFile == "")
 return false;

>From d05e29bb46e2d19317fc667ba37e4549e551496a Mon Sep 17 00:00:00 2001
From: schenka0 <154034018+schen...@users.noreply.github.com>
Date: Mon, 1 Jan 2024 21:49:59 -0500
Subject: [PATCH 3/4] Update invalid SourceLocation in testpoint. Use a value
 with the MSB set to 1 (so it is not a FileID) and the remaining bits 0

Address review feedback on formatting and const
---
 clang-tools-extra/clangd/SourceCode.cpp| 2 +-
 clang-tools-extra/clangd/unittests/SourceCodeTests.cpp | 9 +++--
 2 files changed, 4 insertions(+), 7 deletions(-)

diff --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 58a0d142777d000..3e741f6e0b536ba 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -236,7 +236,7 @@ bool isSpelledInSource(SourceLocation Loc, const 
SourceManager &SM) {
   const auto SLocEntry = SM.getSLocEntry(Spelling.first, &InvalidSLocEntry);
   if (InvalidSLocEntry)
 return false;
-  const StringRef SpellingFile = SLocEntry.getFile().getName();
+  StringRef SpellingFile = SLocEntry.getFile().getName();
   if (SpellingFile == "")
 return false;
   if (SpellingFile == "")
diff --git a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp 
b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
index 5dced4d317c6059..a85935125789972 100644
--- a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -814,18 +814,15 @@ TEST(SourceCodeTests, isKeywords) {
 }
 
 TEST(SourceCodeTests, isSpelledInSource) {
-  Annotations Test(R"cpp(
-int abc = 1;

[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {

cor3ntin wrote:

I don't care much about the exact name, although i agree with you my suggestion 
may not be great.  It can be `ShadowsNameOfFunctionOrVariableItIsAttachedTo` or 
whatever name you think is best describing of what it does. `IssueWarning` is a 
bit _too_ generic, or rather it forces us to think about warning in multiple 
places and especially someone calling `DiagnoseTemplateParameterShadow` should 
understand what the bool parameter does.

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


[libc] [compiler-rt] [llvm] [lldb] [flang] [clang-tools-extra] [lld] [libcxx] [clang] [VPlan] Implement cloning of VPlans. (PR #73158)

2024-01-27 Thread Florian Hahn via cfe-commits

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


[clang-tools-extra] [clangd] update list of fast tidy checks (PR #69723)

2024-01-27 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

Given that the release branch for 18 was created, could the list be updated and 
backported, so that clangd-18 will contain the up-to-date fast-checks?

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


[clang] 143b510 - [Clang] Fix asan error after ad1a65fca

2024-01-27 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2024-01-27T14:35:18+01:00
New Revision: 143b510a8fefb0d203c9ac7e036aa9967dd8a2ef

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

LOG: [Clang] Fix asan error after ad1a65fca

Annotating tokens can invalid the stack of Peaked tokens.

Added: 


Modified: 
clang/lib/Parse/ParseExpr.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 6e83b7aa3441b5c..68dc1bc4a40a074 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1065,7 +1065,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 if (getLangOpts().CPlusPlus) {
   // Avoid the unnecessary parse-time lookup in the common case
   // where the syntax forbids a type.
-  const Token &Next = NextToken();
+  Token Next = NextToken();
 
   if (Next.is(tok::ellipsis) && Tok.is(tok::identifier) &&
   GetLookAheadToken(2).is(tok::l_square)) {
@@ -1081,9 +1081,8 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   // If this identifier was reverted from a token ID, and the next token
   // is a parenthesis, this is likely to be a use of a type trait. Check
   // those tokens.
-  if (Next.is(tok::l_paren) &&
-  Tok.is(tok::identifier) &&
-  Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
+  else if (Next.is(tok::l_paren) && Tok.is(tok::identifier) &&
+   Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
 IdentifierInfo *II = Tok.getIdentifierInfo();
 // Build up the mapping of revertible type traits, for future use.
 if (RevertibleTypeTraits.empty()) {
@@ -1170,9 +1169,9 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 }
   }
 
-  if ((!ColonIsSacred && Next.is(tok::colon)) ||
-  Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
-   tok::l_brace)) {
+  else if ((!ColonIsSacred && Next.is(tok::colon)) ||
+   Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
+tok::l_brace)) {
 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
 if (TryAnnotateTypeOrScopeToken())
   return ExprError();



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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

Fixed in 143b510a8fefb0d203c9ac7e036aa9967dd8a2ef

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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread Jie Fu 傅杰 via cfe-commits

DamonFool wrote:

lldb may also need to be fixed?
```
llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4074:11: 
error: enumeration value 'PackIndexing' not handled in switch [-Werror,-Wswitch]
  switch (qual_type->getTypeClass()) {
  ^
llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4751:11: 
error: enumeration value 'PackIndexing' not handled in switch [-Werror,-Wswitch]
  switch (qual_type->getTypeClass()) {
  ^
llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:5080:11: 
error: enumeration value 'PackIndexing' not handled in switch [-Werror,-Wswitch]
  switch (qual_type->getTypeClass()) {
  ^
3 errors generated.
```

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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

> lldb may also need to be fixed?
> 
> ```
> llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4074:11:
>  error: enumeration value 'PackIndexing' not handled in switch 
> [-Werror,-Wswitch]
>   switch (qual_type->getTypeClass()) {
>   ^
> llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4751:11:
>  error: enumeration value 'PackIndexing' not handled in switch 
> [-Werror,-Wswitch]
>   switch (qual_type->getTypeClass()) {
>   ^
> llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:5080:11:
>  error: enumeration value 'PackIndexing' not handled in switch 
> [-Werror,-Wswitch]
>   switch (qual_type->getTypeClass()) {
>   ^
> 3 errors generated.
> ```

Yes. (I missed that, thanks). I'm not familiar with lldb codebase but the fix 
looks trivial.

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-01-27 Thread Krystian Stasiowski via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {

sdkrystian wrote:

I can add javadocs for the parameters that explain the semantics of 
`IssueWarning` and the motivating use-case for it. Is that a good compromise?

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


[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)

2024-01-27 Thread via cfe-commits

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

>From f3f2807dbbdcb81ca4bc575e0572ab49483ecdb7 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 27 Jan 2024 22:54:26 +0800
Subject: [PATCH] [Clang] Implement P2718R0 "Lifetime extension in range-based
 for loops"

 Implement P2718R0 "Lifetime extension in range-based for loops" 
(https://wg21.link/P2718R0)

Differential Revision: https://reviews.llvm.org/D153701
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Parse/Parser.h|   2 +-
 clang/include/clang/Sema/Sema.h   | 104 -
 clang/lib/Frontend/InitPreprocessor.cpp   |   4 +-
 clang/lib/Parse/ParseDecl.cpp |  26 ++
 clang/lib/Parse/ParseStmt.cpp |   8 +-
 clang/lib/Sema/SemaExpr.cpp   |  35 +-
 clang/lib/Sema/SemaExprCXX.cpp|  47 ++-
 clang/lib/Sema/SemaInit.cpp   |   4 +
 clang/lib/Sema/SemaStmt.cpp   |  35 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |   2 +
 clang/lib/Sema/TreeTransform.h|  62 +--
 .../test/AST/ast-dump-for-range-lifetime.cpp  | 355 ++
 clang/test/CXX/special/class.temporary/p6.cpp | 311 ++-
 clang/test/Lexer/cxx-features.cpp |   2 +-
 15 files changed, 914 insertions(+), 86 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-for-range-lifetime.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..2bbbf2b76f87e08 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,6 +65,9 @@ C++20 Feature Support
 C++23 Feature Support
 ^
 
+- Implemented `P2718R0: Lifetime extension in range-based for loops 
`_. Also
+  materialize temporary object which is a prvalue in discarded-value 
expression.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index bde1ac2242cd6c2..d00fc0535e7eb09 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2398,7 +2398,7 @@ class Parser : public CodeCompletionHandler {
   struct ForRangeInit {
 SourceLocation ColonLoc;
 ExprResult RangeExpr;
-
+SmallVector LifetimeExtendTemps;
 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   };
   struct ForRangeInfo : ForRangeInit {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff73581..00bf78f46c11d85 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1342,6 +1342,12 @@ class Sema final {
 /// context not already known to be immediately invoked.
 llvm::SmallPtrSet ReferenceToConsteval;
 
+/// P2718R0 - Lifetime extension in range-based for loops.
+/// MaterializeTemporaryExprs in for-range-init expressions which need to
+/// extend lifetime. Add MaterializeTemporaryExpr* if the value of
+/// InLifetimeExtendingContext is true.
+SmallVector ForRangeLifetimeExtendTemps;
+
 /// \brief Describes whether we are in an expression constext which we have
 /// to handle differently.
 enum ExpressionKind {
@@ -1361,6 +1367,39 @@ class Sema final {
 // VLAs).
 bool InConditionallyConstantEvaluateContext = false;
 
+/// Whether we are currently in a context in which all temporaries must be
+/// lifetime-extended, even if they're not bound to a reference (for
+/// example, in a for-range initializer).
+bool InLifetimeExtendingContext = false;
+
+/// Whether we are currently in a context in which all temporaries must be
+/// materialized.
+///
+/// [class.temporary]/p2:
+/// The materialization of a temporary object is generally delayed as long
+/// as possible in order to avoid creating unnecessary temporary objects.
+///
+/// Temporary objects are materialized:
+///   (2.1) when binding a reference to a prvalue ([dcl.init.ref],
+///   [expr.type.conv], [expr.dynamic.cast], [expr.static.cast],
+///   [expr.const.cast], [expr.cast]),
+///
+///   (2.2) when performing member access on a class prvalue ([expr.ref],
+///   [expr.mptr.oper]),
+///
+///   (2.3) when performing an array-to-pointer conversion or subscripting
+///   on an array prvalue ([conv.array], [expr.sub]),
+///
+///   (2.4) when initializing an object of type
+///   std​::​initializer_list from a braced-init-list
+///   ([dcl.init.list]),
+///
+///   (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof])
+///
+///   (2.6) when a prvalue that has type other than cv void appears as a
+///   discarded-value expression ([expr.context]).
+bool InMaterializeTemporaryObjectContext = false;
+
 // When evaluating immediate functions in the initializer of a default
 // argument or default m

[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2024-01-27 Thread via cfe-commits

cor3ntin wrote:

https://github.com/llvm/llvm-project/pull/79695 

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


[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)

2024-01-27 Thread via cfe-commits

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

>From 077d90133dac70d9ea83718063715aa95c2405b0 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 27 Jan 2024 23:05:37 +0800
Subject: [PATCH] [Clang] Implement P2718R0 "Lifetime extension in range-based
 for loops"

 Implement P2718R0 "Lifetime extension in range-based for loops" 
(https://wg21.link/P2718R0)

Differential Revision: https://reviews.llvm.org/D153701
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Parse/Parser.h|   2 +-
 clang/include/clang/Sema/Sema.h   | 104 -
 clang/lib/Frontend/InitPreprocessor.cpp   |   4 +-
 clang/lib/Parse/ParseDecl.cpp |  26 ++
 clang/lib/Parse/ParseStmt.cpp |   8 +-
 clang/lib/Sema/SemaExpr.cpp   |  34 +-
 clang/lib/Sema/SemaExprCXX.cpp|  47 ++-
 clang/lib/Sema/SemaInit.cpp   |   4 +
 clang/lib/Sema/SemaStmt.cpp   |  35 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |   2 +
 clang/lib/Sema/TreeTransform.h|  62 +--
 .../test/AST/ast-dump-for-range-lifetime.cpp  | 355 ++
 clang/test/CXX/special/class.temporary/p6.cpp | 311 ++-
 clang/test/Lexer/cxx-features.cpp |   2 +-
 15 files changed, 913 insertions(+), 86 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-for-range-lifetime.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..2bbbf2b76f87e08 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,6 +65,9 @@ C++20 Feature Support
 C++23 Feature Support
 ^
 
+- Implemented `P2718R0: Lifetime extension in range-based for loops 
`_. Also
+  materialize temporary object which is a prvalue in discarded-value 
expression.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index bde1ac2242cd6c2..d00fc0535e7eb09 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2398,7 +2398,7 @@ class Parser : public CodeCompletionHandler {
   struct ForRangeInit {
 SourceLocation ColonLoc;
 ExprResult RangeExpr;
-
+SmallVector LifetimeExtendTemps;
 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   };
   struct ForRangeInfo : ForRangeInit {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff73581..00bf78f46c11d85 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1342,6 +1342,12 @@ class Sema final {
 /// context not already known to be immediately invoked.
 llvm::SmallPtrSet ReferenceToConsteval;
 
+/// P2718R0 - Lifetime extension in range-based for loops.
+/// MaterializeTemporaryExprs in for-range-init expressions which need to
+/// extend lifetime. Add MaterializeTemporaryExpr* if the value of
+/// InLifetimeExtendingContext is true.
+SmallVector ForRangeLifetimeExtendTemps;
+
 /// \brief Describes whether we are in an expression constext which we have
 /// to handle differently.
 enum ExpressionKind {
@@ -1361,6 +1367,39 @@ class Sema final {
 // VLAs).
 bool InConditionallyConstantEvaluateContext = false;
 
+/// Whether we are currently in a context in which all temporaries must be
+/// lifetime-extended, even if they're not bound to a reference (for
+/// example, in a for-range initializer).
+bool InLifetimeExtendingContext = false;
+
+/// Whether we are currently in a context in which all temporaries must be
+/// materialized.
+///
+/// [class.temporary]/p2:
+/// The materialization of a temporary object is generally delayed as long
+/// as possible in order to avoid creating unnecessary temporary objects.
+///
+/// Temporary objects are materialized:
+///   (2.1) when binding a reference to a prvalue ([dcl.init.ref],
+///   [expr.type.conv], [expr.dynamic.cast], [expr.static.cast],
+///   [expr.const.cast], [expr.cast]),
+///
+///   (2.2) when performing member access on a class prvalue ([expr.ref],
+///   [expr.mptr.oper]),
+///
+///   (2.3) when performing an array-to-pointer conversion or subscripting
+///   on an array prvalue ([conv.array], [expr.sub]),
+///
+///   (2.4) when initializing an object of type
+///   std​::​initializer_list from a braced-init-list
+///   ([dcl.init.list]),
+///
+///   (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof])
+///
+///   (2.6) when a prvalue that has type other than cv void appears as a
+///   discarded-value expression ([expr.context]).
+bool InMaterializeTemporaryObjectContext = false;
+
 // When evaluating immediate functions in the initializer of a default
 // argument or default m

[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)

2024-01-27 Thread via cfe-commits

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

>From 7bb3c8f8f1e7ffebcf0abfdcbf4a70a9fe73b3ae Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 27 Jan 2024 23:09:15 +0800
Subject: [PATCH] [Clang] Implement P2718R0 "Lifetime extension in range-based
 for loops"

 Implement P2718R0 "Lifetime extension in range-based for loops" 
(https://wg21.link/P2718R0)

Differential Revision: https://reviews.llvm.org/D153701
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Parse/Parser.h|   2 +-
 clang/include/clang/Sema/Sema.h   | 104 -
 clang/lib/Frontend/InitPreprocessor.cpp   |   4 +-
 clang/lib/Parse/ParseDecl.cpp |  26 ++
 clang/lib/Parse/ParseStmt.cpp |   8 +-
 clang/lib/Sema/SemaExpr.cpp   |  34 +-
 clang/lib/Sema/SemaExprCXX.cpp|  46 ++-
 clang/lib/Sema/SemaInit.cpp   |   4 +
 clang/lib/Sema/SemaStmt.cpp   |  35 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |   2 +
 clang/lib/Sema/TreeTransform.h|  62 +--
 .../test/AST/ast-dump-for-range-lifetime.cpp  | 355 ++
 clang/test/CXX/special/class.temporary/p6.cpp | 311 ++-
 clang/test/Lexer/cxx-features.cpp |   2 +-
 15 files changed, 912 insertions(+), 86 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-for-range-lifetime.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad801..2bbbf2b76f87e0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,6 +65,9 @@ C++20 Feature Support
 C++23 Feature Support
 ^
 
+- Implemented `P2718R0: Lifetime extension in range-based for loops 
`_. Also
+  materialize temporary object which is a prvalue in discarded-value 
expression.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index bde1ac2242cd6c..d00fc0535e7eb0 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2398,7 +2398,7 @@ class Parser : public CodeCompletionHandler {
   struct ForRangeInit {
 SourceLocation ColonLoc;
 ExprResult RangeExpr;
-
+SmallVector LifetimeExtendTemps;
 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   };
   struct ForRangeInfo : ForRangeInit {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff7358..00bf78f46c11d8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1342,6 +1342,12 @@ class Sema final {
 /// context not already known to be immediately invoked.
 llvm::SmallPtrSet ReferenceToConsteval;
 
+/// P2718R0 - Lifetime extension in range-based for loops.
+/// MaterializeTemporaryExprs in for-range-init expressions which need to
+/// extend lifetime. Add MaterializeTemporaryExpr* if the value of
+/// InLifetimeExtendingContext is true.
+SmallVector ForRangeLifetimeExtendTemps;
+
 /// \brief Describes whether we are in an expression constext which we have
 /// to handle differently.
 enum ExpressionKind {
@@ -1361,6 +1367,39 @@ class Sema final {
 // VLAs).
 bool InConditionallyConstantEvaluateContext = false;
 
+/// Whether we are currently in a context in which all temporaries must be
+/// lifetime-extended, even if they're not bound to a reference (for
+/// example, in a for-range initializer).
+bool InLifetimeExtendingContext = false;
+
+/// Whether we are currently in a context in which all temporaries must be
+/// materialized.
+///
+/// [class.temporary]/p2:
+/// The materialization of a temporary object is generally delayed as long
+/// as possible in order to avoid creating unnecessary temporary objects.
+///
+/// Temporary objects are materialized:
+///   (2.1) when binding a reference to a prvalue ([dcl.init.ref],
+///   [expr.type.conv], [expr.dynamic.cast], [expr.static.cast],
+///   [expr.const.cast], [expr.cast]),
+///
+///   (2.2) when performing member access on a class prvalue ([expr.ref],
+///   [expr.mptr.oper]),
+///
+///   (2.3) when performing an array-to-pointer conversion or subscripting
+///   on an array prvalue ([conv.array], [expr.sub]),
+///
+///   (2.4) when initializing an object of type
+///   std​::​initializer_list from a braced-init-list
+///   ([dcl.init.list]),
+///
+///   (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof])
+///
+///   (2.6) when a prvalue that has type other than cv void appears as a
+///   discarded-value expression ([expr.context]).
+bool InMaterializeTemporaryObjectContext = false;
+
 // When evaluating immediate functions in the initializer of a default
 // argument or default member 

[clang] [llvm] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits

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


[llvm] [clang-tools-extra] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits


@@ -0,0 +1,195 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+using namespace std;
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {

felix642 wrote:

You are missing `CK_UserDefinedConversion`

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


[llvm] [clang] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits


@@ -0,0 +1,238 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isImplicitCastType(const clang::CastKind castKind) {
+  switch (castKind) {
+  case clang::CK_CPointerToObjCPointerCast:
+  case clang::CK_BlockPointerToObjCPointerCast:
+  case clang::CK_BitCast:
+  case clang::CK_AnyPointerToBlockPointerCast:
+  case clang::CK_NullToMemberPointer:
+  case clang::CK_NullToPointer:
+  case clang::CK_IntegralToPointer:
+  case clang::CK_PointerToIntegral:
+  case clang::CK_IntegralCast:
+  case clang::CK_BooleanToSignedIntegral:
+  case clang::CK_IntegralToFloating:
+  case clang::CK_FloatingToIntegral:
+  case clang::CK_FloatingCast:
+  case clang::CK_ObjCObjectLValueCast:
+  case clang::CK_FloatingRealToComplex:
+  case clang::CK_FloatingComplexToReal:
+  case clang::CK_FloatingComplexCast:
+  case clang::CK_FloatingComplexToIntegralComplex:
+  case clang::CK_IntegralRealToComplex:
+  case clang::CK_IntegralComplexToReal:
+  case clang::CK_IntegralComplexCast:
+  case clang::CK_IntegralComplexToFloatingComplex:
+  case clang::CK_FloatingToFixedPoint:
+  case clang::CK_FixedPointToFloating:
+  case clang::CK_FixedPointCast:
+  case clang::CK_FixedPointToIntegral:
+  case clang::CK_IntegralToFixedPoint:
+  case clang::CK_MatrixCast:
+  case clang::CK_PointerToBoolean:
+  case clang::CK_IntegralToBoolean:
+  case clang::CK_FloatingToBoolean:
+  case clang::CK_MemberPointerToBoolean:
+  case clang::CK_FloatingComplexToBoolean:
+  case clang::CK_IntegralComplexToBoolean:
+return true;
+  default:
+return false;
+  }
+}
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  const auto CastKind = cast(S)->getCastKind();
+  if (isImplicitCastType(CastKind)) {
+found = true;
+const clang::ImplicitCastExpr *ImplicitCast =
+cast(S);
+GlobalImplicitCastType = ImplicitCast->getType();
+// Stop visiting children.
+return false;
+  }
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;
+};
+
+static const llvm::StringRef AlgorithmHeader("");
+
+static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  return false;
+}
+
+static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  return false;
+}
+
+static std::string
+createReplacement(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+  const Expr *CondRhs, const Expr *AssignLhs,
+  const ASTContext &Context, const SourceManager &Source,
+  const LangOptions &LO, StringRef FunctionName,
+  QualType GlobalImplicitCastType) {
+  const llvm::StringRef CondLhsStr = Lexer::getSourceText(
+  Source.getExpansionRange(CondLhs->getSourceRange()), S

[llvm] [clang-tools-extra] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 requested changes to this pull request.


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


[clang] [clang-tools-extra] [llvm] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits


@@ -0,0 +1,238 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isImplicitCastType(const clang::CastKind castKind) {
+  switch (castKind) {
+  case clang::CK_CPointerToObjCPointerCast:
+  case clang::CK_BlockPointerToObjCPointerCast:
+  case clang::CK_BitCast:
+  case clang::CK_AnyPointerToBlockPointerCast:
+  case clang::CK_NullToMemberPointer:
+  case clang::CK_NullToPointer:
+  case clang::CK_IntegralToPointer:
+  case clang::CK_PointerToIntegral:
+  case clang::CK_IntegralCast:
+  case clang::CK_BooleanToSignedIntegral:
+  case clang::CK_IntegralToFloating:
+  case clang::CK_FloatingToIntegral:
+  case clang::CK_FloatingCast:
+  case clang::CK_ObjCObjectLValueCast:
+  case clang::CK_FloatingRealToComplex:
+  case clang::CK_FloatingComplexToReal:
+  case clang::CK_FloatingComplexCast:
+  case clang::CK_FloatingComplexToIntegralComplex:
+  case clang::CK_IntegralRealToComplex:
+  case clang::CK_IntegralComplexToReal:
+  case clang::CK_IntegralComplexCast:
+  case clang::CK_IntegralComplexToFloatingComplex:
+  case clang::CK_FloatingToFixedPoint:
+  case clang::CK_FixedPointToFloating:
+  case clang::CK_FixedPointCast:
+  case clang::CK_FixedPointToIntegral:
+  case clang::CK_IntegralToFixedPoint:
+  case clang::CK_MatrixCast:
+  case clang::CK_PointerToBoolean:
+  case clang::CK_IntegralToBoolean:
+  case clang::CK_FloatingToBoolean:
+  case clang::CK_MemberPointerToBoolean:
+  case clang::CK_FloatingComplexToBoolean:
+  case clang::CK_IntegralComplexToBoolean:
+return true;
+  default:
+return false;
+  }
+}
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  const auto CastKind = cast(S)->getCastKind();
+  if (isImplicitCastType(CastKind)) {
+found = true;
+const clang::ImplicitCastExpr *ImplicitCast =
+cast(S);
+GlobalImplicitCastType = ImplicitCast->getType();
+// Stop visiting children.
+return false;
+  }
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;
+};
+
+static const llvm::StringRef AlgorithmHeader("");
+
+static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  return false;
+}
+
+static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  return false;
+}
+
+static std::string
+createReplacement(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+  const Expr *CondRhs, const Expr *AssignLhs,
+  const ASTContext &Context, const SourceManager &Source,
+  const LangOptions &LO, StringRef FunctionName,
+  QualType GlobalImplicitCastType) {
+  const llvm::StringRef CondLhsStr = Lexer::getSourceText(
+  Source.getExpansionRange(CondLhs->getSourceRange()), S

[llvm] [clang] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits


@@ -0,0 +1,189 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+using namespace std;
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  found = true;
+  const clang::ImplicitCastExpr *ImplicitCast =
+  cast(S);
+  GlobalImplicitCastType = ImplicitCast->getType();
+  // Stop visiting children.
+  return false;
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;

felix642 wrote:

Would you be able to tell me where are you using this ASTContext variable? I'm 
not seeing any usage and I feel like I'm missing something

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


[clang] [clang] Resolve FIXME in altivec.h (PR #78905)

2024-01-27 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/78905

>From f20a18d41c87443483df35314c14ecb560ad4fde Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sun, 21 Jan 2024 11:52:11 -0500
Subject: [PATCH] [clang] Resolve FIXME in altivec.h

treat parameter as a 5-bit signed literal.
---
 clang/lib/Headers/altivec.h | 64 -
 1 file changed, 34 insertions(+), 30 deletions(-)

diff --git a/clang/lib/Headers/altivec.h b/clang/lib/Headers/altivec.h
index 4971631c50f412..84fb98712ccef1 100644
--- a/clang/lib/Headers/altivec.h
+++ b/clang/lib/Headers/altivec.h
@@ -10311,78 +10311,82 @@ static __inline__ vector float __ATTRS_o_ai 
vec_vspltw(vector float __a,
  b1, b2, b3, __b, b1, b2, b3));
 }
 
+typedef union {
+  struct {
+signed int value : 5; // 5-bit signed integer
+  } field;
+  signed char byte;
+} FiveBitSigned;
+
 /* vec_splat_s8 */
 
 #define __builtin_altivec_vspltisb vec_splat_s8
 
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector signed char __ATTRS_o_ai
 vec_splat_s8(signed char __a) {
-  return (vector signed char)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector signed char)(fbs.field.value);
 }
 
 /* vec_vspltisb */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector signed char __ATTRS_o_ai
 vec_vspltisb(signed char __a) {
-  return (vector signed char)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector signed char)(fbs.field.value);
 }
 
 /* vec_splat_s16 */
-
-#define __builtin_altivec_vspltish vec_splat_s16
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector short __ATTRS_o_ai vec_splat_s16(signed char __a) {
-  return (vector short)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector short)(fbs.field.value);
 }
 
 /* vec_vspltish */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector short __ATTRS_o_ai vec_vspltish(signed char __a) {
-  return (vector short)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector short)(fbs.field.value);
 }
 
 /* vec_splat_s32 */
-
-#define __builtin_altivec_vspltisw vec_splat_s32
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector int __ATTRS_o_ai vec_splat_s32(signed char __a) {
-  return (vector int)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector int)(fbs.field.value);
 }
 
 /* vec_vspltisw */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector int __ATTRS_o_ai vec_vspltisw(signed char __a) {
-  return (vector int)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector int)(fbs.field.value);
 }
 
 /* vec_splat_u8 */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector unsigned char __ATTRS_o_ai
 vec_splat_u8(unsigned char __a) {
-  return (vector unsigned char)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector unsigned char)(fbs.field.value);
 }
 
 /* vec_splat_u16 */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector unsigned short __ATTRS_o_ai
 vec_splat_u16(signed char __a) {
-  return (vector unsigned short)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector unsigned short)(fbs.field.value);
 }
 
 /* vec_splat_u32 */
-
-// FIXME: parameter should be treated as 5-bit signed literal
 static __inline__ vector unsigned int __ATTRS_o_ai
 vec_splat_u32(signed char __a) {
-  return (vector unsigned int)(__a);
+  FiveBitSigned fbs;
+  fbs.byte = __a;
+  return (vector unsigned int)(fbs.field.value);
 }
 
 /* vec_sr */

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


[clang] Update test intrinsic to support immediates (PR #79174)

2024-01-27 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/79174

>From c9c9c1373ac8e0d900fb4bc53f3d47c9ba6c9c39 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 23 Jan 2024 12:31:49 -0500
Subject: [PATCH] Update test intrinsic to support immediates

---
 clang/lib/CodeGen/CGBuiltin.cpp | 20 +---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f3ab5ad7b08ec81..10d0ce2ae5b7efd 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -1203,10 +1203,24 @@ static llvm::Value 
*EmitX86BitTestIntrinsic(CodeGenFunction &CGF,
   AsmOS << "bt";
   if (Action)
 AsmOS << Action;
-  AsmOS << SizeSuffix << " $2, ($1)";
 
-  // Build the constraints. FIXME: We should support immediates when possible.
-  std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
+  // Check if BitPos is a ConstantInt (immediate value)
+  if (llvm::ConstantInt *CI = llvm::dyn_cast(BitPos)) {
+// If it is, use the immediate value in the assembly string
+AsmOS << SizeSuffix << " $" << CI->getZExtValue() << ", ($1)";
+  } else {
+// Otherwise, fall back to the existing behavior
+AsmOS << SizeSuffix << " $2, ($1)";
+  }
+
+  // Build the constraints.
+  std::string Constraints;
+  if (llvm::isa(BitPos)) {
+Constraints = "={@ccc},r,~{cc},~{memory}";
+  } else {
+Constraints = "={@ccc},r,r,~{cc},~{memory}";
+  }
+
   std::string_view MachineClobbers = CGF.getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
 Constraints += ',';

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


[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)

2024-01-27 Thread via cfe-commits

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

>From 20b860d86e1db5981b6e362a11ac3ac437a4f007 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 27 Jan 2024 23:25:57 +0800
Subject: [PATCH] [Clang] Implement P2718R0 "Lifetime extension in range-based
 for loops"

 Implement P2718R0 "Lifetime extension in range-based for loops" 
(https://wg21.link/P2718R0)

Differential Revision: https://reviews.llvm.org/D153701
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Parse/Parser.h|   2 +-
 clang/include/clang/Sema/Sema.h   | 104 -
 clang/lib/Frontend/InitPreprocessor.cpp   |   4 +-
 clang/lib/Parse/ParseDecl.cpp |  26 ++
 clang/lib/Parse/ParseStmt.cpp |   8 +-
 clang/lib/Sema/SemaExpr.cpp   |  34 +-
 clang/lib/Sema/SemaExprCXX.cpp|  46 ++-
 clang/lib/Sema/SemaInit.cpp   |   4 +
 clang/lib/Sema/SemaStmt.cpp   |  35 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |   2 +
 clang/lib/Sema/TreeTransform.h|  62 +--
 .../test/AST/ast-dump-for-range-lifetime.cpp  | 355 ++
 clang/test/CXX/special/class.temporary/p6.cpp | 311 ++-
 clang/test/Lexer/cxx-features.cpp |   2 +-
 clang/www/cxx_status.html |   2 +-
 16 files changed, 913 insertions(+), 87 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-for-range-lifetime.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5330cd9caad8011..2bbbf2b76f87e08 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,6 +65,9 @@ C++20 Feature Support
 C++23 Feature Support
 ^
 
+- Implemented `P2718R0: Lifetime extension in range-based for loops 
`_. Also
+  materialize temporary object which is a prvalue in discarded-value 
expression.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index bde1ac2242cd6c2..d00fc0535e7eb09 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2398,7 +2398,7 @@ class Parser : public CodeCompletionHandler {
   struct ForRangeInit {
 SourceLocation ColonLoc;
 ExprResult RangeExpr;
-
+SmallVector LifetimeExtendTemps;
 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   };
   struct ForRangeInfo : ForRangeInit {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff73581..00bf78f46c11d85 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1342,6 +1342,12 @@ class Sema final {
 /// context not already known to be immediately invoked.
 llvm::SmallPtrSet ReferenceToConsteval;
 
+/// P2718R0 - Lifetime extension in range-based for loops.
+/// MaterializeTemporaryExprs in for-range-init expressions which need to
+/// extend lifetime. Add MaterializeTemporaryExpr* if the value of
+/// InLifetimeExtendingContext is true.
+SmallVector ForRangeLifetimeExtendTemps;
+
 /// \brief Describes whether we are in an expression constext which we have
 /// to handle differently.
 enum ExpressionKind {
@@ -1361,6 +1367,39 @@ class Sema final {
 // VLAs).
 bool InConditionallyConstantEvaluateContext = false;
 
+/// Whether we are currently in a context in which all temporaries must be
+/// lifetime-extended, even if they're not bound to a reference (for
+/// example, in a for-range initializer).
+bool InLifetimeExtendingContext = false;
+
+/// Whether we are currently in a context in which all temporaries must be
+/// materialized.
+///
+/// [class.temporary]/p2:
+/// The materialization of a temporary object is generally delayed as long
+/// as possible in order to avoid creating unnecessary temporary objects.
+///
+/// Temporary objects are materialized:
+///   (2.1) when binding a reference to a prvalue ([dcl.init.ref],
+///   [expr.type.conv], [expr.dynamic.cast], [expr.static.cast],
+///   [expr.const.cast], [expr.cast]),
+///
+///   (2.2) when performing member access on a class prvalue ([expr.ref],
+///   [expr.mptr.oper]),
+///
+///   (2.3) when performing an array-to-pointer conversion or subscripting
+///   on an array prvalue ([conv.array], [expr.sub]),
+///
+///   (2.4) when initializing an object of type
+///   std​::​initializer_list from a braced-init-list
+///   ([dcl.init.list]),
+///
+///   (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof])
+///
+///   (2.6) when a prvalue that has type other than cv void appears as a
+///   discarded-value expression ([expr.context]).
+bool InMaterializeTemporaryObjectContext = false;
+
 // When evaluating immediate functions in th

[clang] [libcxx] [SemaCXX] Implement CWG2137 (list-initialization from objects of the same type) (PR #77768)

2024-01-27 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > > As I understood the author, more time was needed to prepare the tests and 
> > > the fix. I just tried to bring the tip of the tree to a good state soon 
> > > (our internal release process was blocked on this) without putting any 
> > > pressure on the author.
> > 
> > 
> > Typically when the author is engaging fairly quickly and only needs a short 
> > time (he had already identified the problem and only had process-related 
> > concerns), it is preferred to be understanding/polite and give them time to 
> > work on it.
> 
> First of all, let me quote the developer policy: ["Remember, it is normal and 
> healthy to have patches reverted. Having a patch reverted does not 
> necessarily mean you did anything 
> wrong."](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). 
> Now, I totally understand the desire to "capture the progress" as well as 
> frustration one might have seeing their work reverted. However, a revert 
> shouldn't be perceived as an impolite or unfriendly action. All contributions 
> are welcome and appreciated. Reverting a commit is merely a way to deal with 
> problems one at a time without blocking others or racing against the clock.

The developer policy also says: "Reverts should be reasonably timely. A change 
submitted two hours ago can be reverted without prior discussion. A change 
submitted two years ago should not be. Where exactly the transition point is is 
hard to say, but it’s probably in the handful of days in tree territory. If you 
are unsure, we encourage you to reply to the commit thread, give the author a 
bit to respond, and then proceed with the revert if the author doesn’t seem to 
be actively responding."

"Reasonably timely" also means that authors who are engaged on a fix are 
expected to have the opportunity to land that fix. Reverts can be disruptive 
and they can clutter the revision history, so *if* we can avoid them, it's 
better to avoid them. However, we don't want to avoid reverts when they help 
keep the tree stable; not reverting can be plenty disruptive, too! There's a 
happy medium somewhere between "revert as quickly as possible at the first sign 
of trouble" and "let authors have infinite time to fix issues".

I think it's better that we err on the side of reverting quickly, and I don't 
think anyone has done anything wrong here. But I think we have some downstream 
projects which are quicker to revert than is comfortable and so some code 
owners are pushing back (gently) on reverts that we think may have jumped the 
gun a bit. For example, I know I've personally had several instances where I've 
had things reverted out from under me as I'm trying to land the fix and that's 
caused significantly more work for me. This review seems to have had a similar 
outcome: the community was told about the issue, the patch author immediately 
responded, and the patch revert happened regardless and more effort is required 
from everyone as a result. Again, I still think the revert is defensible. But I 
also think the push back on the speed at which the revert happened is 
defensible as well. This is mostly just a call to coordinate a bit better. I 
would suggest that if the patch author is engaged on the thread, it would make 
sense to tell them the schedule on which you plan to revert so they have an 
opportunity to tell you if that's going to be disruptive.

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


[clang] [clang] Resolve FIXME in altivec.h (PR #78905)

2024-01-27 Thread Anton Korobeynikov via cfe-commits

asl wrote:

I do not thing this is a proper fix and that it actually improves anything. 
"Treat as signed 5-bit literal" means that:
 - Only allow literal parameters
 - Only allow integers that would fit into 5-bit signed immediate

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-01-27 Thread via cfe-commits

wheatman wrote:

@cor3ntin I tried to ask for your review since it was just what github 
recommended, if you can't do it, could you please suggest somebody else.
Thanks. 

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-01-27 Thread via cfe-commits


@@ -19807,20 +19807,46 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
 //   sufficient to contain the incremented value. If no such type
 //   exists, the program is ill-formed.
 QualType T = getNextLargerIntegralType(Context, EltTy);
-if (T.isNull() || Enum->isFixed()) {
+if (Enum->isFixed()) {
   // There is no integral type larger enough to represent this
   // value. Complain, then allow the value to wrap around.
   EnumVal = LastEnumConst->getInitVal();
   EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
   ++EnumVal;
-  if (Enum->isFixed())
-// When the underlying type is fixed, this is ill-formed.
-Diag(IdLoc, diag::err_enumerator_wrapped)
-  << toString(EnumVal, 10)
-  << EltTy;
-  else
+  // When the underlying type is fixed, this is ill-formed.
+  Diag(IdLoc, diag::err_enumerator_wrapped)
+  << toString(EnumVal, 10) << EltTy;
+
+} else if (T.isNull()) {
+  if (EltTy->isSignedIntegerType() &&
+  (getLangOpts().CPlusPlus ||
+   LangStandard::getLangStandardForKind(getLangOpts().LangStd)
+   .isC23())) {

cor3ntin wrote:

```suggestion
} else if (T.isNull()) {
  if (EltTy->isSignedIntegerType() &&
  (getLangOpts().CPlusPlus ||  getLangOpts().C23)) {
```

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-01-27 Thread via cfe-commits


@@ -19807,20 +19807,46 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
 //   sufficient to contain the incremented value. If no such type
 //   exists, the program is ill-formed.
 QualType T = getNextLargerIntegralType(Context, EltTy);
-if (T.isNull() || Enum->isFixed()) {
+if (Enum->isFixed()) {
   // There is no integral type larger enough to represent this
   // value. Complain, then allow the value to wrap around.
   EnumVal = LastEnumConst->getInitVal();
   EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
   ++EnumVal;
-  if (Enum->isFixed())
-// When the underlying type is fixed, this is ill-formed.
-Diag(IdLoc, diag::err_enumerator_wrapped)
-  << toString(EnumVal, 10)
-  << EltTy;
-  else
+  // When the underlying type is fixed, this is ill-formed.
+  Diag(IdLoc, diag::err_enumerator_wrapped)
+  << toString(EnumVal, 10) << EltTy;
+
+} else if (T.isNull()) {
+  if (EltTy->isSignedIntegerType() &&
+  (getLangOpts().CPlusPlus ||
+   LangStandard::getLangStandardForKind(getLangOpts().LangStd)
+   .isC23())) {
+// FIXME: Int128/UInt128 support, which also needs to be introduced
+// into
+// enum checking below.
+// This case can only happen if we are the largest signed type, so
+// try and become an unsigned type to get more possible values
+if (EltTy == Context.ShortTy) {
+  EltTy = Context.UnsignedShortTy;
+} else if (EltTy == Context.IntTy) {
+  EltTy = Context.UnsignedIntTy;
+} else if (EltTy == Context.LongTy) {
+  EltTy = Context.UnsignedLongTy;
+} else if (EltTy == Context.LongLongTy) {
+  EltTy = Context.UnsignedLongLongTy;
+} else {
+  assert(false && "Enum Type is not basic integral type");
+}
+  } else {

cor3ntin wrote:

Can you use `getCorrespondingUnsignedType` here?

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-01-27 Thread via cfe-commits

https://github.com/cor3ntin commented:

For the C changes, we should make sure we implement the relevant changes of 
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3029.htm and 
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3030.htm


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


[clang] [llvm] [clang-tools-extra] [mlir] fix vulnerabilities (PR #79697)

2024-01-27 Thread via cfe-commits

https://github.com/NxPKG created https://github.com/llvm/llvm-project/pull/79697

[feat: upgrade vscode-languageclient from 8.0.2-next.5 to 
9.0.1](https://github.com/llvm/llvm-project/commit/f7b4f61db6016a1a02d775efc1e921fac785e823)
[fix: upgrade chokidar from 3.5.2 to 
3.5.3](https://github.com/llvm/llvm-project/commit/a93fe7036c42346b2250afb757ebee5e3afcab31)
[fix: upgrade nan from 2.17.0 to 
2.18.0](https://github.com/llvm/llvm-project/commit/c16496fa21ca79f5e98f286bed2265ae11189efb)
[fix: clang/utils/analyzer/requirements.txt to reduce 
vulnerabilities](https://github.com/llvm/llvm-project/commit/778b996957696d770daf92fd4c205e13f78c0850)
[fix: llvm/utils/git/requirements_formatting.txt to reduce 
vulnerabili](https://github.com/llvm/llvm-project/commit/040dceee80835841c21eceea1816f26b1ae744f4)
[fix: llvm/utils/git/requirements.txt to reduce 
vulnerabilities](https://github.com/llvm/llvm-project/commit/1f80440f313dc148813943dcd6c07b1d50d8cb5e)

>From f7b4f61db6016a1a02d775efc1e921fac785e823 Mon Sep 17 00:00:00 2001
From: snyk-bot 
Date: Fri, 19 Jan 2024 07:12:22 +
Subject: [PATCH 1/6] feat: upgrade vscode-languageclient from 8.0.2-next.5 to
 9.0.1

Snyk has created this PR to upgrade vscode-languageclient from 8.0.2-next.5 to 
9.0.1.

See this package in npm:
https://www.npmjs.com/package/vscode-languageclient

See this project in Snyk:
https://app.snyk.io/org/gitaction-log4j/project/a71a1b94-9555-4c53-b459-4ef6c4d3545e?utm_source=github&utm_medium=referral&page=upgrade-pr
---
 mlir/utils/vscode/package-lock.json | 117 +++-
 mlir/utils/vscode/package.json  |   2 +-
 2 files changed, 80 insertions(+), 39 deletions(-)

diff --git a/mlir/utils/vscode/package-lock.json 
b/mlir/utils/vscode/package-lock.json
index c93f6167c80a1e7..7d573b63fcca1f8 100644
--- a/mlir/utils/vscode/package-lock.json
+++ b/mlir/utils/vscode/package-lock.json
@@ -10,7 +10,7 @@
   "dependencies": {
 "base64-js": "^1.5.1",
 "chokidar": "3.5.2",
-"vscode-languageclient": "^8.0.2-next.5"
+"vscode-languageclient": "^9.0.1"
   },
   "devDependencies": {
 "@types/mocha": "^7.0.2",
@@ -279,6 +279,7 @@
   "version": "1.1.11",
   "resolved": 
"https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz";,
   "integrity": 
"sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
+  "dev": true,
   "dependencies": {
 "balanced-match": "^1.0.0",
 "concat-map": "0.0.1"
@@ -509,7 +510,8 @@
 "node_modules/concat-map": {
   "version": "0.0.1",
   "resolved": 
"https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz";,
-  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
+  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
+  "dev": true
 },
 "node_modules/console-control-strings": {
   "version": "1.1.0",
@@ -1198,6 +1200,7 @@
   "version": "3.0.4",
   "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz";,
   "integrity": 
"sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+  "dev": true,
   "dependencies": {
 "brace-expansion": "^1.1.7"
   },
@@ -1881,24 +1884,43 @@
   "dev": true
 },
 "node_modules/vscode-jsonrpc": {
-  "version": "8.0.2-next.1",
-  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2-next.1.tgz";,
-  "integrity": 
"sha512-sbbvGSWja7NVBLHPGawtgezc8DHYJaP4qfr/AaJiyDapWcSFtHyPtm18+LnYMLTmB7bhOUW/lf5PeeuLpP6bKA==",
+  "version": "8.2.0",
+  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz";,
+  "integrity": 
"sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
   "engines": {
 "node": ">=14.0.0"
   }
 },
 "node_modules/vscode-languageclient": {
-  "version": "8.0.2-next.5",
-  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-8.0.2-next.5.tgz";,
-  "integrity": 
"sha512-g87RJLHz0XlRyk6DOTbAk4JHcj8CKggXy4JiFL7OlhETkcYzTOR8d+Qdb4GqZr37PDs1Cl21omtTNK5LyR/RQg==",
+  "version": "9.0.1",
+  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz";,
+  "integrity": 
"sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==",
   "dependencies": {
-"minimatch": "^3.0.4",
-"semver": "^7.3.5",
-"vscode-languageserver-protocol": "3.17.2-next.6"
+"minimatch": "^5.1.0",
+"semver": "^7.3.7",
+"vscode-languageserver-protocol": "3.17.5"
   },
   "engines": {
-"vscode": "^1.67.0"
+"vscode": "^1.82.0"
+  }
+},
+"node_modules/vscode-languageclient/node_modules/brace-expansion": {
+  "version": "2.0.1",
+  "resolved": 
"https://registry.npmjs.org/b

[clang] [llvm] [clang-tools-extra] [mlir] fix vulnerabilities (PR #79697)

2024-01-27 Thread via cfe-commits

github-actions[bot] wrote:

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] 718aac9 - [clang][Diagnostics] Highlight code snippets (#66514)

2024-01-27 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-01-27T17:52:20+01:00
New Revision: 718aac9f7a19227b5c5ec85819a3a5ae24ce32e1

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

LOG: [clang][Diagnostics] Highlight code snippets (#66514)

Add some primitive syntax highlighting to our code snippet output.

This adds "checkpoints" to the Preprocessor, which we can use to start lexing 
from. When printing a code snippet, we lex from the nearest checkpoint and 
highlight the tokens based on their token type.

Added: 
clang/test/Frontend/diagnostic-pipe.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Frontend/TextDiagnostic.h
clang/include/clang/Lex/Preprocessor.h
clang/lib/Frontend/TextDiagnostic.cpp
clang/lib/Frontend/TextDiagnosticPrinter.cpp
clang/lib/Lex/Preprocessor.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa06e2b60ce915..254e0a9cb72979 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -103,6 +103,8 @@ Attribute Changes in Clang
 
 Improvements to Clang's diagnostics
 ---
+- Clang now applies syntax highlighting to the code snippets it
+  prints.
 
 Improvements to Clang's time-trace
 --

diff  --git a/clang/include/clang/Frontend/TextDiagnostic.h 
b/clang/include/clang/Frontend/TextDiagnostic.h
index 7eb0ab0cdc9bca..a2fe8ae995423b 100644
--- a/clang/include/clang/Frontend/TextDiagnostic.h
+++ b/clang/include/clang/Frontend/TextDiagnostic.h
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
 
 #include "clang/Frontend/DiagnosticRenderer.h"
+#include "llvm/Support/raw_ostream.h"
 
 namespace clang {
 
@@ -33,14 +34,22 @@ namespace clang {
 /// printing coming out of libclang.
 class TextDiagnostic : public DiagnosticRenderer {
   raw_ostream &OS;
+  const Preprocessor *PP;
 
 public:
-  TextDiagnostic(raw_ostream &OS,
- const LangOptions &LangOpts,
- DiagnosticOptions *DiagOpts);
+  TextDiagnostic(raw_ostream &OS, const LangOptions &LangOpts,
+ DiagnosticOptions *DiagOpts, const Preprocessor *PP = 
nullptr);
 
   ~TextDiagnostic() override;
 
+  struct StyleRange {
+unsigned Start;
+unsigned End;
+enum llvm::raw_ostream::Colors Color;
+StyleRange(unsigned S, unsigned E, enum llvm::raw_ostream::Colors C)
+: Start(S), End(E), Color(C){};
+  };
+
   /// Print the diagonstic level to a raw_ostream.
   ///
   /// This is a static helper that handles colorizing the level and formatting
@@ -104,7 +113,8 @@ class TextDiagnostic : public DiagnosticRenderer {
ArrayRef Hints);
 
   void emitSnippet(StringRef SourceLine, unsigned MaxLineNoDisplayWidth,
-   unsigned LineNo);
+   unsigned LineNo, unsigned DisplayLineNo,
+   ArrayRef Styles);
 
   void emitParseableFixits(ArrayRef Hints, const SourceManager &SM);
 };

diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 2d9c53cdf5bde8..9d0d53129a12dd 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -284,6 +284,13 @@ class Preprocessor {
   /// The kind of translation unit we are processing.
   const TranslationUnitKind TUKind;
 
+  /// Returns a pointer into the given file's buffer that's guaranteed
+  /// to be between tokens. The returned pointer is always before \p Start.
+  /// The maximum distance betweenthe returned pointer and \p Start is
+  /// limited by a constant value, but also an implementation detail.
+  /// If no such check point exists, \c nullptr is returned.
+  const char *getCheckPoint(FileID FID, const char *Start) const;
+
 private:
   /// The code-completion handler.
   CodeCompletionHandler *CodeComplete = nullptr;
@@ -311,6 +318,9 @@ class Preprocessor {
   /// The import path for named module that we're currently processing.
   SmallVector, 2> 
NamedModuleImportPath;
 
+  llvm::DenseMap> CheckPoints;
+  unsigned CheckPointCounter = 0;
+
   /// Whether the import is an `@import` or a standard c++ modules import.
   bool IsAtImport = false;
 

diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 779dead5d058d1..291d71f6db61f1 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -12,6 +12,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ConvertUTF.h"
@@ -41,6 +42,14 @@ static const enum raw_ostream::Colors fatalColor = 
raw_ost

[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2024-01-27 Thread Timm Baeder via cfe-commits

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


[clang] [llvm] [clang-tools-extra] [mlir] fix vulnerabilities (PR #79697)

2024-01-27 Thread via cfe-commits

https://github.com/NxPKG updated https://github.com/llvm/llvm-project/pull/79697

>From f7b4f61db6016a1a02d775efc1e921fac785e823 Mon Sep 17 00:00:00 2001
From: snyk-bot 
Date: Fri, 19 Jan 2024 07:12:22 +
Subject: [PATCH 1/6] feat: upgrade vscode-languageclient from 8.0.2-next.5 to
 9.0.1

Snyk has created this PR to upgrade vscode-languageclient from 8.0.2-next.5 to 
9.0.1.

See this package in npm:
https://www.npmjs.com/package/vscode-languageclient

See this project in Snyk:
https://app.snyk.io/org/gitaction-log4j/project/a71a1b94-9555-4c53-b459-4ef6c4d3545e?utm_source=github&utm_medium=referral&page=upgrade-pr
---
 mlir/utils/vscode/package-lock.json | 117 +++-
 mlir/utils/vscode/package.json  |   2 +-
 2 files changed, 80 insertions(+), 39 deletions(-)

diff --git a/mlir/utils/vscode/package-lock.json 
b/mlir/utils/vscode/package-lock.json
index c93f6167c80a1e..7d573b63fcca1f 100644
--- a/mlir/utils/vscode/package-lock.json
+++ b/mlir/utils/vscode/package-lock.json
@@ -10,7 +10,7 @@
   "dependencies": {
 "base64-js": "^1.5.1",
 "chokidar": "3.5.2",
-"vscode-languageclient": "^8.0.2-next.5"
+"vscode-languageclient": "^9.0.1"
   },
   "devDependencies": {
 "@types/mocha": "^7.0.2",
@@ -279,6 +279,7 @@
   "version": "1.1.11",
   "resolved": 
"https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz";,
   "integrity": 
"sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
+  "dev": true,
   "dependencies": {
 "balanced-match": "^1.0.0",
 "concat-map": "0.0.1"
@@ -509,7 +510,8 @@
 "node_modules/concat-map": {
   "version": "0.0.1",
   "resolved": 
"https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz";,
-  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
+  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
+  "dev": true
 },
 "node_modules/console-control-strings": {
   "version": "1.1.0",
@@ -1198,6 +1200,7 @@
   "version": "3.0.4",
   "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz";,
   "integrity": 
"sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+  "dev": true,
   "dependencies": {
 "brace-expansion": "^1.1.7"
   },
@@ -1881,24 +1884,43 @@
   "dev": true
 },
 "node_modules/vscode-jsonrpc": {
-  "version": "8.0.2-next.1",
-  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2-next.1.tgz";,
-  "integrity": 
"sha512-sbbvGSWja7NVBLHPGawtgezc8DHYJaP4qfr/AaJiyDapWcSFtHyPtm18+LnYMLTmB7bhOUW/lf5PeeuLpP6bKA==",
+  "version": "8.2.0",
+  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz";,
+  "integrity": 
"sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
   "engines": {
 "node": ">=14.0.0"
   }
 },
 "node_modules/vscode-languageclient": {
-  "version": "8.0.2-next.5",
-  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-8.0.2-next.5.tgz";,
-  "integrity": 
"sha512-g87RJLHz0XlRyk6DOTbAk4JHcj8CKggXy4JiFL7OlhETkcYzTOR8d+Qdb4GqZr37PDs1Cl21omtTNK5LyR/RQg==",
+  "version": "9.0.1",
+  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz";,
+  "integrity": 
"sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==",
   "dependencies": {
-"minimatch": "^3.0.4",
-"semver": "^7.3.5",
-"vscode-languageserver-protocol": "3.17.2-next.6"
+"minimatch": "^5.1.0",
+"semver": "^7.3.7",
+"vscode-languageserver-protocol": "3.17.5"
   },
   "engines": {
-"vscode": "^1.67.0"
+"vscode": "^1.82.0"
+  }
+},
+"node_modules/vscode-languageclient/node_modules/brace-expansion": {
+  "version": "2.0.1",
+  "resolved": 
"https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz";,
+  "integrity": 
"sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
+  "dependencies": {
+"balanced-match": "^1.0.0"
+  }
+},
+"node_modules/vscode-languageclient/node_modules/minimatch": {
+  "version": "5.1.6",
+  "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz";,
+  "integrity": 
"sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
+  "dependencies": {
+"brace-expansion": "^2.0.1"
+  },
+  "engines": {
+"node": ">=10"
   }
 },
 "node_modules/vscode-languageclient/node_modules/semver": {
@@ -1916,18 +1938,18 @@
   }
 },
 "node_modules/vscode-languageserver-protocol": {
-  "version": "3.17.2-next.6",
-  "resolv

[lldb] [mlir] [flang] [compiler-rt] [libc] [libcxx] [clang-tools-extra] [lld] [llvm] [clang] [mlir][transform] Add elementwise criteria to `match.structured.body` (PR #79626)

2024-01-27 Thread via cfe-commits

https://github.com/srcarroll updated 
https://github.com/llvm/llvm-project/pull/79626

>From ab475c9ffb7c3562bad4772389e97b82e9f110c0 Mon Sep 17 00:00:00 2001
From: Sam 
Date: Fri, 26 Jan 2024 11:55:06 -0600
Subject: [PATCH 1/3] Add elementwise criteria to match.structured.body

---
 .../Linalg/TransformOps/LinalgMatchOps.td |  4 +++
 .../Linalg/TransformOps/LinalgMatchOps.cpp|  9 -
 .../Dialect/Linalg/match-ops-interpreter.mlir | 34 +++
 .../Dialect/Linalg/match-ops-invalid.mlir |  2 +-
 4 files changed, 47 insertions(+), 2 deletions(-)

diff --git a/mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td 
b/mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td
index 162dd05f93030f2..dfeb8ae5d5ddbcb 100644
--- a/mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td
+++ b/mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td
@@ -106,6 +106,9 @@ def MatchStructuredBodyOp : Op((bbarg0, bbarg1), bbarg2)` where `` and
 `` are binary operations whose names are specified in the 
attribute
@@ -123,6 +126,7 @@ def MatchStructuredBodyOp : Op:$reduction_position,
UnitAttr:$passthrough,
+   UnitAttr:$elementwise,
OptionalAttr:$contraction);
   let assemblyFormat = "$operand_handle attr-dict `:` type($operand_handle)";
   let extraClassDeclaration = SingleOpMatcher.extraDeclaration;
diff --git a/mlir/lib/Dialect/Linalg/TransformOps/LinalgMatchOps.cpp 
b/mlir/lib/Dialect/Linalg/TransformOps/LinalgMatchOps.cpp
index 115da4b90e063ac..fb18886c16b16d5 100644
--- a/mlir/lib/Dialect/Linalg/TransformOps/LinalgMatchOps.cpp
+++ b/mlir/lib/Dialect/Linalg/TransformOps/LinalgMatchOps.cpp
@@ -11,6 +11,7 @@
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
 #include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
 #include "mlir/Dialect/Linalg/TransformOps/Syntax.h"
+#include "mlir/Dialect/Linalg/Utils/Utils.h"
 #include "mlir/Dialect/Transform/IR/MatchInterfaces.h"
 #include "mlir/IR/BuiltinAttributes.h"
 #include "mlir/Interfaces/FunctionImplementation.h"
@@ -187,6 +188,11 @@ DiagnosedSilenceableFailure 
transform::MatchStructuredBodyOp::matchOperation(
 }
 return DiagnosedSilenceableFailure::success();
   }
+  if (getElementwise()) {
+if (!isElementwise(linalgOp))
+  return emitSilenceableError() << "not elementwise";
+return DiagnosedSilenceableFailure::success();
+  }
   if (std::optional contractionOps = getContraction()) {
 Block &body = linalgOp->getRegion(0).front();
 std::string message;
@@ -209,13 +215,14 @@ DiagnosedSilenceableFailure 
transform::MatchStructuredBodyOp::matchOperation(
 
 LogicalResult transform::MatchStructuredBodyOp::verify() {
   int64_t numOptions = getReductionPosition().has_value() + getPassthrough() +
-   getContraction().has_value();
+   getElementwise() + getContraction().has_value();
 
   if (numOptions > 1) {
 std::string attributeNames;
 llvm::raw_string_ostream os(attributeNames);
 llvm::interleaveComma(ArrayRef{getReductionPositionAttrName(),
getPassthroughAttrName(),
+   getElementwiseAttrName(),
getContractionAttrName()},
   os);
 return emitOpError() << "only one of {" << os.str() << "} is allowed";
diff --git a/mlir/test/Dialect/Linalg/match-ops-interpreter.mlir 
b/mlir/test/Dialect/Linalg/match-ops-interpreter.mlir
index a7353a4c38881e4..0efe70a7b9ae1eb 100644
--- a/mlir/test/Dialect/Linalg/match-ops-interpreter.mlir
+++ b/mlir/test/Dialect/Linalg/match-ops-interpreter.mlir
@@ -180,6 +180,40 @@ module attributes { transform.with_named_sequence } {
 
 // -
 
+module attributes { transform.with_named_sequence } {
+  transform.named_sequence @print_elementwise(%arg0: !transform.any_op 
{transform.readonly}) {
+transform.test_print_remark_at_operand %arg0, "elementwise" : 
!transform.any_op
+transform.yield
+  }
+
+  transform.named_sequence @match_structured_body_elementwise(%arg0: 
!transform.any_op {transform.readonly}) -> !transform.any_op {
+%0 = transform.match.structured failures(propagate) %arg0 : 
(!transform.any_op) -> !transform.any_op {
+^bb0(%arg1: !transform.any_op):
+  transform.match.structured.body %arg1 { elementwise } : !transform.any_op
+  transform.match.structured.yield %arg1 : !transform.any_op
+}
+transform.yield %0 : !transform.any_op
+  }
+
+  transform.named_sequence @__transform_main(%arg0: !transform.any_op 
{transform.consumed}) {
+transform.foreach_match in %arg0
+@match_structured_body_elementwise -> @print_elementwise
+: (!transform.any_op) -> !transform.any_op
+transform.yield
+  }
+
+  func.func @payload(%in1: tensor<2xf32>, %in2: tensor<2xf32>, %out: 
tensor<2xf32>) -> tensor<2xf32> attributes { transform.target_tag = 

[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-27 Thread Jonas Paulsson via cfe-commits

JonPsson1 wrote:

Thanks for review!

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


[clang] 34dd8ec - [clang, SystemZ] Support -munaligned-symbols (#73511)

2024-01-27 Thread via cfe-commits

Author: Jonas Paulsson
Date: 2024-01-27T18:29:37+01:00
New Revision: 34dd8ec8aec17965313b17308faaa6272c235c53

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

LOG: [clang, SystemZ] Support -munaligned-symbols (#73511)

When this option is passed to clang, external (and/or weak) symbols
are not assumed to have the minimum ABI alignment normally required.
Symbols defined locally that are not weak are however still given the
minimum alignment.

This is implemented by passing a new parameter to getMinGlobalAlign()
named HasNonWeakDef that is used to return the right alignment value.

This is needed when external symbols created from a linker script may
not get the ABI minimum alignment and must therefore be treated as
unaligned by the compiler.

Added: 
clang/test/CodeGen/SystemZ/unaligned-symbols.c

Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/Basic/TargetInfo.h
clang/include/clang/Driver/Options.td
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/lib/Basic/Targets/CSKY.cpp
clang/lib/Basic/Targets/CSKY.h
clang/lib/Basic/Targets/NVPTX.cpp
clang/lib/Basic/Targets/SPIR.h
clang/lib/Basic/Targets/SystemZ.cpp
clang/lib/Basic/Targets/SystemZ.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
clang/lib/Sema/SemaOpenMP.cpp
llvm/lib/Target/SystemZ/SystemZFeatures.td

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 668462ef5460646..12ce9af1e53f63d 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2413,12 +2413,18 @@ class ASTContext : public RefCountedBase {
   unsigned getTargetDefaultAlignForAttributeAligned() const;
 
   /// Return the alignment in bits that should be given to a
-  /// global variable with type \p T.
-  unsigned getAlignOfGlobalVar(QualType T) const;
+  /// global variable with type \p T. If \p VD is non-null it will be
+  /// considered specifically for the query.
+  unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
 
   /// Return the alignment in characters that should be given to a
-  /// global variable with type \p T.
-  CharUnits getAlignOfGlobalVarInChars(QualType T) const;
+  /// global variable with type \p T. If \p VD is non-null it will be
+  /// considered specifically for the query.
+  CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
+
+  /// Return the minimum alignement as specified by the target. If \p VD is
+  /// non-null it may be used to identify external or weak variables.
+  unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const;
 
   /// Return a conservative estimate of the alignment of the specified
   /// decl \p D.

diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 9432154d5063ce2..48e9cec482755c3 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -704,8 +704,10 @@ class TargetInfo : public TransferrableTargetInfo,
   }
 
   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
-  /// unless its alignment is explicitly reduced via attributes.
-  virtual unsigned getMinGlobalAlign (uint64_t) const {
+  /// unless its alignment is explicitly reduced via attributes. If \param
+  /// HasNonWeakDef is true, this concerns a VarDecl which has a definition
+  /// in current translation unit and that is not weak.
+  virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const {
 return MinGlobalAlign;
   }
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 773bc1dcda01d5c..d940665969339eb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4619,6 +4619,10 @@ def munaligned_access : Flag<["-"], 
"munaligned-access">, Group,
   HelpText<"Allow memory accesses to be unaligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
 def mno_unaligned_access : Flag<["-"], "mno-unaligned-access">, Group,
   HelpText<"Force all memory accesses to be aligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
+def munaligned_symbols : Flag<["-"], "munaligned-symbols">, Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
+def mno_unaligned_symbols : Flag<["-"], "mno-unaligned-symbols">, 
Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
 } // let Flags = [TargetSpecific]
 def mstrict_align : Flag<["-"], "mstrict-align">, Alias,
   Flags<[HelpHidden]>, Visibility<[ClangOption, CC1Option]>,

diff  --git a/clang

[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-27 Thread Jonas Paulsson via cfe-commits

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


[clang] [concepts] Set up an instantiation scope for constraint expression comparison (PR #79698)

2024-01-27 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/79698

This is a follow-up for the comparison of constraints on out-of-line function 
template definitions. We require the instantiation of a ParmVarDecl while 
transforming the expression if that Decl gets referenced by a DeclRefExpr. 
However, we're not actually performing the class or function template 
instantiation at the time of such comparison. Therefore, let's map these 
parameters to themselves so that they get preserved after the substitution.

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

>From 39f64e6fa02392415f0e2776166d4451346e7e81 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 28 Jan 2024 01:17:32 +0800
Subject: [PATCH] [concepts] Set up an instantiation scope for constraint
 expression comparison

This is a follow-up for the comparison of constraints on out-of-line
function template definitions. We require the instantiation of a
ParmVarDecl while transforming the expression if that Decl gets
referenced by a DeclRefExpr. However, we're not actually performing
the class or function template instantiation at the time of such
comparison. Therefore, let's map these parameters to themselves so
that they get preserved after the substitution.

Fixes https://github.com/llvm/llvm-project/issues/74447.
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaConcept.cpp|  9 
 .../SemaTemplate/concepts-out-of-line-def.cpp | 22 +++
 3 files changed, 34 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa06e2b60ce9155..3c5856788e717e3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -128,6 +128,9 @@ Bug Fixes to C++ Support
 - Fixed a bug where variables referenced by requires-clauses inside
   nested generic lambdas were not properly injected into the constraint scope.
   (`#73418 `_)
+- Fixed a crash where substituting into a requires-expression that refers to 
function
+  parameters during the equivalence determination of two constraint 
expressions.
+  (`#74447 `)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 88fc846c89e42c8..19a460f41175797 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -797,6 +797,15 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   if (Inst.isInvalid())
 return nullptr;
 
+  // Set up a dummy 'instantiation' scope in the case of reference to function
+  // parameters that the surrounding function hasn't been instantiated yet. 
Note
+  // this may happen while we're comparing two templates' constraint
+  // equivalence.
+  LocalInstantiationScope ScopeForParameters(S);
+  if (auto *FD = llvm::dyn_cast(DeclInfo.getDecl()))
+for (auto *PVD : FD->parameters())
+  ScopeForParameters.InstantiatedLocal(PVD, PVD);
+
   std::optional ThisScope;
   if (auto *RD = dyn_cast(DeclInfo.getDeclContext()))
 ThisScope.emplace(S, const_cast(RD), Qualifiers());
diff --git a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp 
b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
index c4e8e6f720c4929..7323ad8d9ef2cb8 100644
--- a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
+++ b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
@@ -536,3 +536,25 @@ void X::bar(decltype(requires { requires 
something_interesting; })) {}
 template 
 void X::bar(decltype(requires { requires is_not_same_v; })) {}
 } // namespace GH74314
+
+namespace GH74447 {
+template  struct S {
+  template 
+  void test(T target, U... value)
+requires requires {
+  target;
+  sizeof...(value) == 1;
+  V == 2;
+};
+};
+
+template 
+template 
+void S::test(T target, U... value)
+  requires requires {
+target;
+sizeof...(value) == 1;
+V == 2;
+  }
+{}
+} // namespace GH74447

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


[clang] [concepts] Set up an instantiation scope for constraint expression comparison (PR #79698)

2024-01-27 Thread Younan Zhang via cfe-commits

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


[clang] [concepts] Set up an instantiation scope for constraint expression comparison (PR #79698)

2024-01-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

This is a follow-up for the comparison of constraints on out-of-line function 
template definitions. We require the instantiation of a ParmVarDecl while 
transforming the expression if that Decl gets referenced by a DeclRefExpr. 
However, we're not actually performing the class or function template 
instantiation at the time of such comparison. Therefore, let's map these 
parameters to themselves so that they get preserved after the substitution.

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

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+9) 
- (modified) clang/test/SemaTemplate/concepts-out-of-line-def.cpp (+22) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa06e2b60ce915..3c5856788e717e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -128,6 +128,9 @@ Bug Fixes to C++ Support
 - Fixed a bug where variables referenced by requires-clauses inside
   nested generic lambdas were not properly injected into the constraint scope.
   (`#73418 `_)
+- Fixed a crash where substituting into a requires-expression that refers to 
function
+  parameters during the equivalence determination of two constraint 
expressions.
+  (`#74447 `)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 88fc846c89e42c..19a460f4117579 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -797,6 +797,15 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   if (Inst.isInvalid())
 return nullptr;
 
+  // Set up a dummy 'instantiation' scope in the case of reference to function
+  // parameters that the surrounding function hasn't been instantiated yet. 
Note
+  // this may happen while we're comparing two templates' constraint
+  // equivalence.
+  LocalInstantiationScope ScopeForParameters(S);
+  if (auto *FD = llvm::dyn_cast(DeclInfo.getDecl()))
+for (auto *PVD : FD->parameters())
+  ScopeForParameters.InstantiatedLocal(PVD, PVD);
+
   std::optional ThisScope;
   if (auto *RD = dyn_cast(DeclInfo.getDeclContext()))
 ThisScope.emplace(S, const_cast(RD), Qualifiers());
diff --git a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp 
b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
index c4e8e6f720c492..7323ad8d9ef2cb 100644
--- a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
+++ b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
@@ -536,3 +536,25 @@ void X::bar(decltype(requires { requires 
something_interesting; })) {}
 template 
 void X::bar(decltype(requires { requires is_not_same_v; })) {}
 } // namespace GH74314
+
+namespace GH74447 {
+template  struct S {
+  template 
+  void test(T target, U... value)
+requires requires {
+  target;
+  sizeof...(value) == 1;
+  V == 2;
+};
+};
+
+template 
+template 
+void S::test(T target, U... value)
+  requires requires {
+target;
+sizeof...(value) == 1;
+V == 2;
+  }
+{}
+} // namespace GH74447

``




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


[clang] e976053 - [clang, SystemZ] Fix test case for buildbot.

2024-01-27 Thread Jonas Paulsson via cfe-commits

Author: Jonas Paulsson
Date: 2024-01-27T19:02:36+01:00
New Revision: e976053a63c251e9b65733ed3574e5c3de62084c

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

LOG: [clang, SystemZ] Fix test case for buildbot.

It seems the automatic Value naming starts on %1 instead of %0 sometimes.

Added: 


Modified: 
clang/test/CodeGen/SystemZ/unaligned-symbols.c

Removed: 




diff  --git a/clang/test/CodeGen/SystemZ/unaligned-symbols.c 
b/clang/test/CodeGen/SystemZ/unaligned-symbols.c
index 193e092b99c2b58..31fc211393dd719 100644
--- a/clang/test/CodeGen/SystemZ/unaligned-symbols.c
+++ b/clang/test/CodeGen/SystemZ/unaligned-symbols.c
@@ -105,8 +105,8 @@ unsigned char foo6 () {
 
 // A weak symbol could be replaced with an unaligned one at link time.
 // CHECK-LABEL: foo7
-// ALIGNED: %0 = load i8, ptr @Weaksym, align 2
-// UNALIGN: %0 = load i8, ptr @Weaksym, align 1
+// ALIGNED: load i8, ptr @Weaksym, align 2
+// UNALIGN: load i8, ptr @Weaksym, align 1
 unsigned char __attribute__((weak)) Weaksym = 0;
 unsigned char foo7 () {
   return Weaksym;



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


[clang] Resolve redundant predicates (PR #79701)

2024-01-27 Thread via cfe-commits

https://github.com/Rageking8 created 
https://github.com/llvm/llvm-project/pull/79701

Fixes #79686

>From 6d0591f238444674f327ca502a93ad72bdd46110 Mon Sep 17 00:00:00 2001
From: Rageking8 <106309953+rageki...@users.noreply.github.com>
Date: Sun, 28 Jan 2024 02:06:39 +0800
Subject: [PATCH] Resolve redundant predicates

---
 clang/lib/Sema/SemaChecking.cpp | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 502b24bcdf8b42b..532c1073b48b747 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17185,7 +17185,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 //  evaluates to true.
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
-bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
+bool ShouldVisitRHS = !EvalOK || !EvalResult;
 if (ShouldVisitRHS) {
   Region = RHSRegion;
   Visit(BO->getRHS());
@@ -17217,7 +17217,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 //  [...] the second operand is not evaluated if the first operand is 
false.
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
-bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
+bool ShouldVisitRHS = !EvalOK || EvalResult;
 if (ShouldVisitRHS) {
   Region = RHSRegion;
   Visit(BO->getRHS());
@@ -17268,8 +17268,8 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 // evaluated. [...]
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
-bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
-bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
+bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
+bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
 if (ShouldVisitTrueExpr) {
   Region = TrueRegion;
   Visit(CO->getTrueExpr());

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


[clang] Resolve redundant predicates (PR #79701)

2024-01-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (Rageking8)


Changes

Fixes #79686

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaChecking.cpp (+4-4) 


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 502b24bcdf8b42b..532c1073b48b747 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17185,7 +17185,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 //  evaluates to true.
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
-bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
+bool ShouldVisitRHS = !EvalOK || !EvalResult;
 if (ShouldVisitRHS) {
   Region = RHSRegion;
   Visit(BO->getRHS());
@@ -17217,7 +17217,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 //  [...] the second operand is not evaluated if the first operand is 
false.
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
-bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
+bool ShouldVisitRHS = !EvalOK || EvalResult;
 if (ShouldVisitRHS) {
   Region = RHSRegion;
   Visit(BO->getRHS());
@@ -17268,8 +17268,8 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 // evaluated. [...]
 bool EvalResult = false;
 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
-bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
-bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
+bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
+bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
 if (ShouldVisitTrueExpr) {
   Region = TrueRegion;
   Visit(CO->getTrueExpr());

``




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


[mlir] [clang] [llvm] Fix unsigned typos (PR #76670)

2024-01-27 Thread via cfe-commits

Rageking8 wrote:

Is this PR ready to merge?

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


[llvm] [clang-tools-extra] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,189 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+using namespace std;
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  found = true;
+  const clang::ImplicitCastExpr *ImplicitCast =
+  cast(S);
+  GlobalImplicitCastType = ImplicitCast->getType();
+  // Stop visiting children.
+  return false;
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;

11happy wrote:

![Screenshot from 2024-01-27 
23-13-22](https://github.com/llvm/llvm-project/assets/76656712/09978a9d-e45b-4a24-b296-a3c71ec47640)
In the definition, Context is used in the constructor as if it were a member of 
the class, so if it's removed it will not declared anywhere in the class.


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


[clang] [llvm] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,195 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+using namespace std;
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {

11happy wrote:

added it

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


[clang] [llvm] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,238 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isImplicitCastType(const clang::CastKind castKind) {
+  switch (castKind) {
+  case clang::CK_CPointerToObjCPointerCast:
+  case clang::CK_BlockPointerToObjCPointerCast:
+  case clang::CK_BitCast:
+  case clang::CK_AnyPointerToBlockPointerCast:
+  case clang::CK_NullToMemberPointer:
+  case clang::CK_NullToPointer:
+  case clang::CK_IntegralToPointer:
+  case clang::CK_PointerToIntegral:
+  case clang::CK_IntegralCast:
+  case clang::CK_BooleanToSignedIntegral:
+  case clang::CK_IntegralToFloating:
+  case clang::CK_FloatingToIntegral:
+  case clang::CK_FloatingCast:
+  case clang::CK_ObjCObjectLValueCast:
+  case clang::CK_FloatingRealToComplex:
+  case clang::CK_FloatingComplexToReal:
+  case clang::CK_FloatingComplexCast:
+  case clang::CK_FloatingComplexToIntegralComplex:
+  case clang::CK_IntegralRealToComplex:
+  case clang::CK_IntegralComplexToReal:
+  case clang::CK_IntegralComplexCast:
+  case clang::CK_IntegralComplexToFloatingComplex:
+  case clang::CK_FloatingToFixedPoint:
+  case clang::CK_FixedPointToFloating:
+  case clang::CK_FixedPointCast:
+  case clang::CK_FixedPointToIntegral:
+  case clang::CK_IntegralToFixedPoint:
+  case clang::CK_MatrixCast:
+  case clang::CK_PointerToBoolean:
+  case clang::CK_IntegralToBoolean:
+  case clang::CK_FloatingToBoolean:
+  case clang::CK_MemberPointerToBoolean:
+  case clang::CK_FloatingComplexToBoolean:
+  case clang::CK_IntegralComplexToBoolean:
+return true;
+  default:
+return false;
+  }
+}
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  const auto CastKind = cast(S)->getCastKind();
+  if (isImplicitCastType(CastKind)) {
+found = true;
+const clang::ImplicitCastExpr *ImplicitCast =
+cast(S);
+GlobalImplicitCastType = ImplicitCast->getType();
+// Stop visiting children.
+return false;
+  }
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;
+};
+
+static const llvm::StringRef AlgorithmHeader("");
+
+static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  return false;
+}
+
+static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  return false;
+}
+
+static std::string
+createReplacement(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+  const Expr *CondRhs, const Expr *AssignLhs,
+  const ASTContext &Context, const SourceManager &Source,
+  const LangOptions &LO, StringRef FunctionName,
+  QualType GlobalImplicitCastType) {
+  const llvm::StringRef CondLhsStr = Lexer::getSourceText(
+  Source.getExpansionRange(CondLhs->getSourceRange()), S

[llvm] [clang-tools-extra] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,238 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isImplicitCastType(const clang::CastKind castKind) {
+  switch (castKind) {
+  case clang::CK_CPointerToObjCPointerCast:
+  case clang::CK_BlockPointerToObjCPointerCast:
+  case clang::CK_BitCast:
+  case clang::CK_AnyPointerToBlockPointerCast:
+  case clang::CK_NullToMemberPointer:
+  case clang::CK_NullToPointer:
+  case clang::CK_IntegralToPointer:
+  case clang::CK_PointerToIntegral:
+  case clang::CK_IntegralCast:
+  case clang::CK_BooleanToSignedIntegral:
+  case clang::CK_IntegralToFloating:
+  case clang::CK_FloatingToIntegral:
+  case clang::CK_FloatingCast:
+  case clang::CK_ObjCObjectLValueCast:
+  case clang::CK_FloatingRealToComplex:
+  case clang::CK_FloatingComplexToReal:
+  case clang::CK_FloatingComplexCast:
+  case clang::CK_FloatingComplexToIntegralComplex:
+  case clang::CK_IntegralRealToComplex:
+  case clang::CK_IntegralComplexToReal:
+  case clang::CK_IntegralComplexCast:
+  case clang::CK_IntegralComplexToFloatingComplex:
+  case clang::CK_FloatingToFixedPoint:
+  case clang::CK_FixedPointToFloating:
+  case clang::CK_FixedPointCast:
+  case clang::CK_FixedPointToIntegral:
+  case clang::CK_IntegralToFixedPoint:
+  case clang::CK_MatrixCast:
+  case clang::CK_PointerToBoolean:
+  case clang::CK_IntegralToBoolean:
+  case clang::CK_FloatingToBoolean:
+  case clang::CK_MemberPointerToBoolean:
+  case clang::CK_FloatingComplexToBoolean:
+  case clang::CK_IntegralComplexToBoolean:
+return true;
+  default:
+return false;
+  }
+}
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  const auto CastKind = cast(S)->getCastKind();
+  if (isImplicitCastType(CastKind)) {
+found = true;
+const clang::ImplicitCastExpr *ImplicitCast =
+cast(S);
+GlobalImplicitCastType = ImplicitCast->getType();
+// Stop visiting children.
+return false;
+  }
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;
+};
+
+static const llvm::StringRef AlgorithmHeader("");
+
+static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  return false;
+}
+
+static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+ const Expr *CondRhs, const Expr *AssignLhs,
+ const Expr *AssignRhs, const ASTContext &Context) {
+  if ((Op == BO_LT || Op == BO_LE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
+return true;
+
+  if ((Op == BO_GT || Op == BO_GE) &&
+  (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+   tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
+return true;
+
+  return false;
+}
+
+static std::string
+createReplacement(const BinaryOperator::Opcode Op, const Expr *CondLhs,
+  const Expr *CondRhs, const Expr *AssignLhs,
+  const ASTContext &Context, const SourceManager &Source,
+  const LangOptions &LO, StringRef FunctionName,
+  QualType GlobalImplicitCastType) {
+  const llvm::StringRef CondLhsStr = Lexer::getSourceText(
+  Source.getExpansionRange(CondLhs->getSourceRange()), S

[clang-tools-extra] [llvm] [clang] [libc] [compiler-rt] [flang] [lld] [libcxx] [libcxxabi] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -2205,93 +2230,141 @@ void 
SampleProfileMatcher::countMismatchedSamples(const FunctionSamples &FS) {
   countMismatchedSamples(CS.second);
 }
 
-void SampleProfileMatcher::countProfileMismatches(
-const Function &F, const FunctionSamples &FS,
-const std::map &IRAnchors,
+void ProfileMatchStats::countMismatchedCallsites(
+const Function &F, const std::map &IRAnchors,
+const std::map>
+&ProfileAnchors,
+const LocToLocMap &IRToProfileLocationMap) {
+  auto &MismatchedCallsites =
+  
FuncMismatchedCallsites[FunctionSamples::getCanonicalFnName(F.getName())];
+
+  auto MapIRLocToProfileLoc = [&](const LineLocation &IRLoc) {
+const auto &ProfileLoc = IRToProfileLocationMap.find(IRLoc);
+if (ProfileLoc != IRToProfileLocationMap.end())
+  return ProfileLoc->second;
+else
+  return IRLoc;
+  };
+
+  std::set MatchedCallsites;
+  for (const auto &I : IRAnchors) {
+// In post-match, use the matching result to remap the current IR callsite.
+const auto &Loc = MapIRLocToProfileLoc(I.first);
+const auto &IRCalleeName = I.second;
+const auto &It = ProfileAnchors.find(Loc);
+if (It == ProfileAnchors.end())
+  continue;
+const auto &Callees = It->second;
+
+// Since indirect call does not have CalleeName, check conservatively if
+// callsite in the profile is a callsite location. This is to reduce num of
+// false positive since otherwise all the indirect call samples will be
+// reported as mismatching.
+if (IRCalleeName == SampleProfileMatcher::UnknownIndirectCallee)
+  MatchedCallsites.insert(Loc);
+else if (Callees.count(getRepInFormat(IRCalleeName)))

WenleiHe wrote:

Add comment explain why we don't expect exactly one callee in profile when 
there is only one callee in IR.  

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


[llvm] [clang] [compiler-rt] [libcxx] [clang-tools-extra] [libcxxabi] [lld] [libc] [flang] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -433,6 +433,44 @@ using CandidateQueue =
 PriorityQueue,
   CandidateComparer>;
 
+// Profile matching statstics.
+class ProfileMatchStats {
+  const Module &M;
+  SampleProfileReader &Reader;
+  const PseudoProbeManager *ProbeManager;
+
+public:
+  ProfileMatchStats(const Module &M, SampleProfileReader &Reader,
+const PseudoProbeManager *ProbeManager)
+  : M(M), Reader(Reader), ProbeManager(ProbeManager) {}
+
+  uint64_t NumMismatchedCallsites = 0;
+  uint64_t TotalProfiledCallsites = 0;
+  uint64_t MismatchedCallsiteSamples = 0;
+  uint64_t NumMismatchedFuncHash = 0;
+  uint64_t TotalProfiledFunc = 0;
+  uint64_t MismatchedFuncHashSamples = 0;
+  uint64_t TotalFunctionSamples = 0;
+
+  // A map from function name to a set of mismatched callsite locations.
+  StringMap> FuncMismatchedCallsites;
+
+  void countMismatchedSamples(const FunctionSamples &FS);
+  void countProfileMismatches(
+  const Function &F, const std::map &IRAnchors,
+  const std::map>
+  &ProfileAnchors);
+  void countMismatchedCallsites(
+  const Function &F, const std::map &IRAnchors,
+  const std::map>
+  &ProfileAnchors,
+  const LocToLocMap &IRToProfileLocationMap);
+  void countMismatchedCallsiteSamples(const FunctionSamples &FS);
+  void countMismatchedCallsiteSamples();
+  void copyUnchangedCallsiteMismatches(
+  const StringMap> &InputMismatchedCallsites);
+};

WenleiHe wrote:

These functions needs some comments as they are somewhat similar but with 
subtle differences. 

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


[libcxx] [clang-tools-extra] [flang] [compiler-rt] [libc] [llvm] [libcxxabi] [lld] [clang] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -2205,93 +2230,141 @@ void 
SampleProfileMatcher::countMismatchedSamples(const FunctionSamples &FS) {
   countMismatchedSamples(CS.second);
 }
 
-void SampleProfileMatcher::countProfileMismatches(
-const Function &F, const FunctionSamples &FS,
-const std::map &IRAnchors,
+void ProfileMatchStats::countMismatchedCallsites(

WenleiHe wrote:

naming: `count` is a stateless and immutable action, but it's not the case here 
as you are tracking and recording `FuncMismatchedCallsites` that later stats 
depends on. 

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


[llvm] [libcxxabi] [clang] [lld] [compiler-rt] [libcxx] [flang] [libc] [clang-tools-extra] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -2460,63 +2528,108 @@ void SampleProfileMatcher::runOnFunction(const 
Function &F) {
   !ProbeManager->profileIsValid(F, *FSFlattened)) {
 // The matching result will be saved to IRToProfileLocationMap, create a 
new
 // map for each function.
+auto &IRToProfileLocationMap = getIRToProfileLocationMap(F);
 runStaleProfileMatching(F, IRAnchors, ProfileAnchors,
-getIRToProfileLocationMap(F));
+IRToProfileLocationMap);
+PostMatchStats.countMismatchedCallsites(F, IRAnchors, ProfileAnchors,
+IRToProfileLocationMap);
   }
 }
 
-void SampleProfileMatcher::runOnModule() {
-  ProfileConverter::flattenProfile(Reader.getProfiles(), FlattenedProfiles,
-   FunctionSamples::ProfileIsCS);
-  for (auto &F : M) {
-if (F.isDeclaration() || !F.hasFnAttribute("use-sample-profile"))
-  continue;
-runOnFunction(F);
-  }
-  if (SalvageStaleProfile)
-distributeIRToProfileLocationMap();
-
+void SampleProfileMatcher::reportOrPersistProfileStats() {
   if (ReportProfileStaleness) {
 if (FunctionSamples::ProfileIsProbeBased) {
-  errs() << "(" << NumMismatchedFuncHash << "/" << TotalProfiledFunc << ")"
+  errs() << "(" << PreMatchStats.NumMismatchedFuncHash << "/"
+ << PreMatchStats.TotalProfiledFunc << ")"
  << " of functions' profile are invalid and "
- << " (" << MismatchedFuncHashSamples << "/" << 
TotalFuncHashSamples
- << ")"
+ << " (" << PreMatchStats.MismatchedFuncHashSamples << "/"
+ << PreMatchStats.TotalFunctionSamples << ")"
  << " of samples are discarded due to function hash mismatch.\n";
 }
-errs() << "(" << NumMismatchedCallsites << "/" << TotalProfiledCallsites
-   << ")"
+errs() << "(" << PreMatchStats.NumMismatchedCallsites << "/"
+   << PreMatchStats.TotalProfiledCallsites << ")"
<< " of callsites' profile are invalid and "
-   << "(" << MismatchedCallsiteSamples << "/" << TotalCallsiteSamples
-   << ")"
+   << "(" << PreMatchStats.MismatchedCallsiteSamples << "/"
+   << PreMatchStats.TotalFunctionSamples << ")"
<< " of samples are discarded due to callsite location mismatch.\n";
+if (SalvageStaleProfile) {
+  uint64_t NumRecoveredCallsites = PostMatchStats.TotalProfiledCallsites -
+   PostMatchStats.NumMismatchedCallsites;
+  uint64_t NumMismatchedCallsites =
+  PreMatchStats.NumMismatchedCallsites - NumRecoveredCallsites;
+  errs() << "Out of " << PostMatchStats.TotalProfiledCallsites
+ << " callsites used for profile matching, "
+ << NumRecoveredCallsites
+ << " callsites have been recovered. After the matching, ("
+ << NumMismatchedCallsites << "/"
+ << PreMatchStats.TotalProfiledCallsites
+ << ") of callsites are still invalid ("
+ << PostMatchStats.MismatchedCallsiteSamples << "/"
+ << PreMatchStats.TotalFunctionSamples << ")"
+ << " of samples are still discarded.\n";
+}
   }
 
   if (PersistProfileStaleness) {
 LLVMContext &Ctx = M.getContext();
 MDBuilder MDB(Ctx);
 
 SmallVector> ProfStatsVec;
+ProfStatsVec.emplace_back("NumMismatchedCallsites",
+  PreMatchStats.NumMismatchedCallsites);
+ProfStatsVec.emplace_back("TotalProfiledCallsites",
+  PreMatchStats.TotalProfiledCallsites);
+ProfStatsVec.emplace_back("MismatchedCallsiteSamples",
+  PreMatchStats.MismatchedCallsiteSamples);
+ProfStatsVec.emplace_back("TotalProfiledFunc",
+  PreMatchStats.TotalProfiledFunc);
+ProfStatsVec.emplace_back("TotalFunctionSamples",
+  PreMatchStats.TotalFunctionSamples);
 if (FunctionSamples::ProfileIsProbeBased) {
-  ProfStatsVec.emplace_back("NumMismatchedFuncHash", 
NumMismatchedFuncHash);
-  ProfStatsVec.emplace_back("TotalProfiledFunc", TotalProfiledFunc);
+  ProfStatsVec.emplace_back("NumMismatchedFuncHash",
+PreMatchStats.NumMismatchedFuncHash);
   ProfStatsVec.emplace_back("MismatchedFuncHashSamples",
-MismatchedFuncHashSamples);
-  ProfStatsVec.emplace_back("TotalFuncHashSamples", TotalFuncHashSamples);
+PreMatchStats.MismatchedFuncHashSamples);
+}
+if (SalvageStaleProfile) {
+  ProfStatsVec.emplace_back("PostMatchNumMismatchedCallsites",
+PostMatchStats.NumMismatchedCallsites);
+  ProfStatsVec.emplace_back("NumCallsitesForMatching",
+PostMatchStats.TotalProfiledCallsites);
+  ProfStatsVec.emplace_back("PostMatch

[clang-tools-extra] [clang] [libc] [flang] [libcxxabi] [libcxx] [lld] [llvm] [compiler-rt] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -433,6 +433,44 @@ using CandidateQueue =
 PriorityQueue,
   CandidateComparer>;
 
+// Profile matching statstics.
+class ProfileMatchStats {

WenleiHe wrote:

I was mostly thinking about a simple struct to encapsulate different stats, 
while keeping most of the logic in the Matcher. But don't have strong opinion. 

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


[libcxx] [llvm] [lld] [libc] [flang] [clang-tools-extra] [clang] [compiler-rt] [libcxxabi] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -433,6 +433,44 @@ using CandidateQueue =
 PriorityQueue,
   CandidateComparer>;
 
+// Profile matching statstics.
+class ProfileMatchStats {
+  const Module &M;
+  SampleProfileReader &Reader;
+  const PseudoProbeManager *ProbeManager;
+
+public:
+  ProfileMatchStats(const Module &M, SampleProfileReader &Reader,
+const PseudoProbeManager *ProbeManager)
+  : M(M), Reader(Reader), ProbeManager(ProbeManager) {}
+
+  uint64_t NumMismatchedCallsites = 0;
+  uint64_t TotalProfiledCallsites = 0;
+  uint64_t MismatchedCallsiteSamples = 0;
+  uint64_t NumMismatchedFuncHash = 0;
+  uint64_t TotalProfiledFunc = 0;
+  uint64_t MismatchedFuncHashSamples = 0;

WenleiHe wrote:

This is really just `MismatchedFunctionSamples`, in contrast to 
`TotalFunctionSamples`.
I know this isn't changed in this patch, but why did we use the term 
`FuncHashSamples`? 

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


[flang] [lld] [clang] [libcxxabi] [compiler-rt] [libc] [llvm] [clang-tools-extra] [libcxx] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -433,6 +433,44 @@ using CandidateQueue =
 PriorityQueue,
   CandidateComparer>;
 
+// Profile matching statstics.
+class ProfileMatchStats {
+  const Module &M;
+  SampleProfileReader &Reader;
+  const PseudoProbeManager *ProbeManager;
+
+public:
+  ProfileMatchStats(const Module &M, SampleProfileReader &Reader,
+const PseudoProbeManager *ProbeManager)
+  : M(M), Reader(Reader), ProbeManager(ProbeManager) {}
+
+  uint64_t NumMismatchedCallsites = 0;
+  uint64_t TotalProfiledCallsites = 0;
+  uint64_t MismatchedCallsiteSamples = 0;
+  uint64_t NumMismatchedFuncHash = 0;
+  uint64_t TotalProfiledFunc = 0;
+  uint64_t MismatchedFuncHashSamples = 0;

WenleiHe wrote:

Add some comment for those stats, particularly what is different between 
`MismatchedCallsiteSamples` and `MismatchedFuncHashSamples`.

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


[libc] [lld] [llvm] [compiler-rt] [libcxx] [flang] [clang-tools-extra] [libcxxabi] [clang] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -2205,93 +2230,141 @@ void 
SampleProfileMatcher::countMismatchedSamples(const FunctionSamples &FS) {
   countMismatchedSamples(CS.second);
 }
 
-void SampleProfileMatcher::countProfileMismatches(
-const Function &F, const FunctionSamples &FS,
-const std::map &IRAnchors,
+void ProfileMatchStats::countMismatchedCallsites(
+const Function &F, const std::map &IRAnchors,
+const std::map>
+&ProfileAnchors,
+const LocToLocMap &IRToProfileLocationMap) {
+  auto &MismatchedCallsites =
+  
FuncMismatchedCallsites[FunctionSamples::getCanonicalFnName(F.getName())];
+
+  auto MapIRLocToProfileLoc = [&](const LineLocation &IRLoc) {

WenleiHe wrote:

This is the place where pre-match and post-match is automatically handled in 
unified way, right? 

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


[libc] [libcxx] [lld] [compiler-rt] [flang] [clang] [libcxxabi] [llvm] [clang-tools-extra] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -433,6 +433,44 @@ using CandidateQueue =
 PriorityQueue,
   CandidateComparer>;
 
+// Profile matching statstics.
+class ProfileMatchStats {
+  const Module &M;
+  SampleProfileReader &Reader;
+  const PseudoProbeManager *ProbeManager;
+
+public:
+  ProfileMatchStats(const Module &M, SampleProfileReader &Reader,
+const PseudoProbeManager *ProbeManager)
+  : M(M), Reader(Reader), ProbeManager(ProbeManager) {}
+
+  uint64_t NumMismatchedCallsites = 0;
+  uint64_t TotalProfiledCallsites = 0;
+  uint64_t MismatchedCallsiteSamples = 0;
+  uint64_t NumMismatchedFuncHash = 0;
+  uint64_t TotalProfiledFunc = 0;
+  uint64_t MismatchedFuncHashSamples = 0;
+  uint64_t TotalFunctionSamples = 0;
+
+  // A map from function name to a set of mismatched callsite locations.
+  StringMap> FuncMismatchedCallsites;

WenleiHe wrote:

I don't see this container being order sensitive, unordered_set would perform 
better for lookups. 

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


[flang] [lld] [clang] [libcxxabi] [compiler-rt] [libc] [llvm] [clang-tools-extra] [libcxx] [CSSPGO] Compute and report post-match profile staleness (PR #79090)

2024-01-27 Thread via cfe-commits


@@ -2205,93 +2230,141 @@ void 
SampleProfileMatcher::countMismatchedSamples(const FunctionSamples &FS) {
   countMismatchedSamples(CS.second);
 }
 
-void SampleProfileMatcher::countProfileMismatches(
-const Function &F, const FunctionSamples &FS,
-const std::map &IRAnchors,
+void ProfileMatchStats::countMismatchedCallsites(
+const Function &F, const std::map &IRAnchors,
+const std::map>
+&ProfileAnchors,
+const LocToLocMap &IRToProfileLocationMap) {
+  auto &MismatchedCallsites =
+  
FuncMismatchedCallsites[FunctionSamples::getCanonicalFnName(F.getName())];
+
+  auto MapIRLocToProfileLoc = [&](const LineLocation &IRLoc) {
+const auto &ProfileLoc = IRToProfileLocationMap.find(IRLoc);
+if (ProfileLoc != IRToProfileLocationMap.end())
+  return ProfileLoc->second;
+else
+  return IRLoc;
+  };
+
+  std::set MatchedCallsites;
+  for (const auto &I : IRAnchors) {
+// In post-match, use the matching result to remap the current IR callsite.
+const auto &Loc = MapIRLocToProfileLoc(I.first);
+const auto &IRCalleeName = I.second;
+const auto &It = ProfileAnchors.find(Loc);
+if (It == ProfileAnchors.end())
+  continue;
+const auto &Callees = It->second;
+
+// Since indirect call does not have CalleeName, check conservatively if
+// callsite in the profile is a callsite location. This is to reduce num of
+// false positive since otherwise all the indirect call samples will be
+// reported as mismatching.
+if (IRCalleeName == SampleProfileMatcher::UnknownIndirectCallee)
+  MatchedCallsites.insert(Loc);
+else if (Callees.count(getRepInFormat(IRCalleeName)))

WenleiHe wrote:

If there is potentially a bug and this is workaround, at least leave a TODO 
comment. Preferably we should not need a workaround.  

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


[clang-tools-extra] [llvm] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-27 Thread Félix-Antoine Constantin via cfe-commits


@@ -0,0 +1,189 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+using namespace std;
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+class ExprVisitor : public clang::RecursiveASTVisitor {
+public:
+  explicit ExprVisitor(clang::ASTContext *Context) : Context(Context) {}
+  bool visitStmt(const clang::Stmt *S, bool &found,
+ clang::QualType &GlobalImplicitCastType) {
+
+if (isa(S) && !found) {
+  found = true;
+  const clang::ImplicitCastExpr *ImplicitCast =
+  cast(S);
+  GlobalImplicitCastType = ImplicitCast->getType();
+  // Stop visiting children.
+  return false;
+}
+// Continue visiting children.
+for (const clang::Stmt *Child : S->children()) {
+  if (Child) {
+this->visitStmt(Child, found, GlobalImplicitCastType);
+  }
+}
+
+return true; // Continue visiting other nodes.
+  }
+
+private:
+  clang::ASTContext *Context;

felix642 wrote:

I can see that, but you're not using that variable anywhere. What's the point 
of declaring it if you're only initializing it and not using it?

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


[llvm] [clang-tools-extra] [mlir] [clang] fix vulnerabilities (PR #79697)

2024-01-27 Thread via cfe-commits

https://github.com/NxPKG updated https://github.com/llvm/llvm-project/pull/79697

>From f7b4f61db6016a1a02d775efc1e921fac785e823 Mon Sep 17 00:00:00 2001
From: snyk-bot 
Date: Fri, 19 Jan 2024 07:12:22 +
Subject: [PATCH 1/6] feat: upgrade vscode-languageclient from 8.0.2-next.5 to
 9.0.1

Snyk has created this PR to upgrade vscode-languageclient from 8.0.2-next.5 to 
9.0.1.

See this package in npm:
https://www.npmjs.com/package/vscode-languageclient

See this project in Snyk:
https://app.snyk.io/org/gitaction-log4j/project/a71a1b94-9555-4c53-b459-4ef6c4d3545e?utm_source=github&utm_medium=referral&page=upgrade-pr
---
 mlir/utils/vscode/package-lock.json | 117 +++-
 mlir/utils/vscode/package.json  |   2 +-
 2 files changed, 80 insertions(+), 39 deletions(-)

diff --git a/mlir/utils/vscode/package-lock.json 
b/mlir/utils/vscode/package-lock.json
index c93f6167c80a1e7..7d573b63fcca1f8 100644
--- a/mlir/utils/vscode/package-lock.json
+++ b/mlir/utils/vscode/package-lock.json
@@ -10,7 +10,7 @@
   "dependencies": {
 "base64-js": "^1.5.1",
 "chokidar": "3.5.2",
-"vscode-languageclient": "^8.0.2-next.5"
+"vscode-languageclient": "^9.0.1"
   },
   "devDependencies": {
 "@types/mocha": "^7.0.2",
@@ -279,6 +279,7 @@
   "version": "1.1.11",
   "resolved": 
"https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz";,
   "integrity": 
"sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
+  "dev": true,
   "dependencies": {
 "balanced-match": "^1.0.0",
 "concat-map": "0.0.1"
@@ -509,7 +510,8 @@
 "node_modules/concat-map": {
   "version": "0.0.1",
   "resolved": 
"https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz";,
-  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
+  "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
+  "dev": true
 },
 "node_modules/console-control-strings": {
   "version": "1.1.0",
@@ -1198,6 +1200,7 @@
   "version": "3.0.4",
   "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz";,
   "integrity": 
"sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+  "dev": true,
   "dependencies": {
 "brace-expansion": "^1.1.7"
   },
@@ -1881,24 +1884,43 @@
   "dev": true
 },
 "node_modules/vscode-jsonrpc": {
-  "version": "8.0.2-next.1",
-  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2-next.1.tgz";,
-  "integrity": 
"sha512-sbbvGSWja7NVBLHPGawtgezc8DHYJaP4qfr/AaJiyDapWcSFtHyPtm18+LnYMLTmB7bhOUW/lf5PeeuLpP6bKA==",
+  "version": "8.2.0",
+  "resolved": 
"https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz";,
+  "integrity": 
"sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
   "engines": {
 "node": ">=14.0.0"
   }
 },
 "node_modules/vscode-languageclient": {
-  "version": "8.0.2-next.5",
-  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-8.0.2-next.5.tgz";,
-  "integrity": 
"sha512-g87RJLHz0XlRyk6DOTbAk4JHcj8CKggXy4JiFL7OlhETkcYzTOR8d+Qdb4GqZr37PDs1Cl21omtTNK5LyR/RQg==",
+  "version": "9.0.1",
+  "resolved": 
"https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz";,
+  "integrity": 
"sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==",
   "dependencies": {
-"minimatch": "^3.0.4",
-"semver": "^7.3.5",
-"vscode-languageserver-protocol": "3.17.2-next.6"
+"minimatch": "^5.1.0",
+"semver": "^7.3.7",
+"vscode-languageserver-protocol": "3.17.5"
   },
   "engines": {
-"vscode": "^1.67.0"
+"vscode": "^1.82.0"
+  }
+},
+"node_modules/vscode-languageclient/node_modules/brace-expansion": {
+  "version": "2.0.1",
+  "resolved": 
"https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz";,
+  "integrity": 
"sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
+  "dependencies": {
+"balanced-match": "^1.0.0"
+  }
+},
+"node_modules/vscode-languageclient/node_modules/minimatch": {
+  "version": "5.1.6",
+  "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz";,
+  "integrity": 
"sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
+  "dependencies": {
+"brace-expansion": "^2.0.1"
+  },
+  "engines": {
+"node": ">=10"
   }
 },
 "node_modules/vscode-languageclient/node_modules/semver": {
@@ -1916,18 +1938,18 @@
   }
 },
 "node_modules/vscode-languageserver-protocol": {
-  "version": "3.17.2-next.6",
-  "reso

  1   2   >