[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-20 Thread Matt Arsenault via cfe-commits


@@ -700,10 +700,13 @@ class MSBuiltin {
 //===--- Variable Argument Handling Intrinsics 
===//
 //
 
-def int_vastart : DefaultAttrsIntrinsic<[], [llvm_ptr_ty], [], 
"llvm.va_start">;
-def int_vacopy  : DefaultAttrsIntrinsic<[], [llvm_ptr_ty, llvm_ptr_ty], [],
-"llvm.va_copy">;
-def int_vaend   : DefaultAttrsIntrinsic<[], [llvm_ptr_ty], [], "llvm.va_end">;
+def int_vastart : DefaultAttrsIntrinsic<[],
+[llvm_anyptr_ty], [], "llvm.va_start">;
+def int_vacopy  : DefaultAttrsIntrinsic<[],
+[llvm_anyptr_ty, llvm_anyptr_ty], [],
+"llvm.va_copy">;

arsenm wrote:

vacopy probably shouldn't have 2 type parameters. 
```suggestion
def int_vacopy  : DefaultAttrsIntrinsic<[],
[llvm_anyptr_ty, LLVMMatchType<0>], [],
"llvm.va_copy">;
```

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


[clang] [clang-format] Add --fail-on-incomplete-format. (PR #84346)

2024-03-20 Thread Owen Pan via cfe-commits


@@ -0,0 +1,5 @@
+// RUN: cat %s | not clang-format --fail-on-incomplete-format | FileCheck %s
+// RUN: cat %s | clang-format | FileCheck %s
+int a([) {}
+
+// CHECK: int a([) {}

owenca wrote:

It's missing the EOF. Also, use a single hyphen for the option like other tests.
```suggestion
// RUN: clang-format %s
// RUN: not clang-format %s -fail-on-incomplete-format

int a(
```

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


[clang] 756c205 - [clang][Tooling] Add special symbol mappings for C, starting with size_t (#85784)

2024-03-20 Thread via cfe-commits

Author: kadir çetinkaya
Date: 2024-03-20T08:48:06+01:00
New Revision: 756c20561efa1e58bd7d2a6df147b6b52e23

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

LOG: [clang][Tooling] Add special symbol mappings for C, starting with size_t 
(#85784)

Added: 
clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc

Modified: 
clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
clang/unittests/Tooling/StandardLibraryTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
new file mode 100644
index 00..a515f69ea6a8cf
--- /dev/null
+++ b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
@@ -0,0 +1,14 @@
+//===-- StdSpecialSymbolMap.inc ---*- C 
-*-===//
+//
+// This is a hand-curated list for C symbols that cannot be parsed/extracted
+// via the include-mapping tool (gen_std.py).
+//
+//===--===//
+
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )

diff  --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp 
b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
index adf1b230ff0318..0832bcf66145fa 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -55,11 +55,12 @@ static const SymbolHeaderMapping *getMappingPerLang(Lang L) 
{
 }
 
 static int countSymbols(Lang Language) {
-  ArrayRef Symbols;
+  ArrayRef Symbols;
 #define SYMBOL(Name, NS, Header) #NS #Name,
   switch (Language) {
   case Lang::C: {
 static constexpr const char *CSymbols[] = {
+#include "CSpecialSymbolMap.inc"
 #include "CSymbolMap.inc"
 };
 Symbols = CSymbols;
@@ -147,6 +148,7 @@ static int initialize(Lang Language) {
   switch (Language) {
   case Lang::C: {
 static constexpr Symbol CSymbols[] = {
+#include "CSpecialSymbolMap.inc"
 #include "CSymbolMap.inc"
 };
 for (const Symbol &S : CSymbols)

diff  --git a/clang/unittests/Tooling/StandardLibraryTest.cpp 
b/clang/unittests/Tooling/StandardLibraryTest.cpp
index edca31649accfa..e4c109f3d580d1 100644
--- a/clang/unittests/Tooling/StandardLibraryTest.cpp
+++ b/clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -185,6 +185,19 @@ TEST(StdlibTest, RecognizerForC99) {
 stdlib::Symbol::named("", "uint8_t", stdlib::Lang::C));
 }
 
+TEST(StdlibTest, SpecialCMappings) {
+  TestInputs Input("typedef char size_t;");
+  Input.Language = TestLanguage::Lang_C99;
+  TestAST AST(Input);
+
+  auto &SizeT = lookup(AST, "size_t");
+  stdlib::Recognizer Recognizer;
+  auto ActualSym = Recognizer(&SizeT);
+  assert(ActualSym);
+  EXPECT_EQ(ActualSym, stdlib::Symbol::named("", "size_t", stdlib::Lang::C));
+  EXPECT_EQ(ActualSym->header()->name(), "");
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang



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


[clang] [clang][Tooling] Add special symbol mappings for C, starting with size_t (PR #85784)

2024-03-20 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-20 Thread Brandon Wu via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

4vtomat wrote:

@topperc I'm not sure why we also need "-" for features that are not enabled, 
is there any use case?

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


[clang] [clang] CTAD: build aggregate deduction guides for alias templates. (PR #85904)

2024-03-20 Thread Haojian Wu via cfe-commits

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

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



>From ff697e2a159a4959deb1103d9d8442ef544a Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 15 Mar 2024 10:47:09 +0100
Subject: [PATCH 1/2] [clang] Move the aggreate deduction guide cache login to
 SemaTemplate.cpp, NFC.

this is a NFC refactoring change, which is needed for the upcoming fix
for alias templates.
---
 clang/lib/Sema/SemaInit.cpp | 27 +--
 clang/lib/Sema/SemaTemplate.cpp | 24 ++--
 2 files changed, 27 insertions(+), 24 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index aa470adb30b47f..763cc5dd17129c 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10918,32 +10918,15 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
   Context.getLValueReferenceType(ElementTypes[I].withConst());
   }
 
-llvm::FoldingSetNodeID ID;
-ID.AddPointer(Template);
-for (auto &T : ElementTypes)
-  T.getCanonicalType().Profile(ID);
-unsigned Hash = ID.ComputeHash();
-if (AggregateDeductionCandidates.count(Hash) == 0) {
-  if (FunctionTemplateDecl *TD =
-  DeclareImplicitDeductionGuideFromInitList(
-  Template, ElementTypes,
-  TSInfo->getTypeLoc().getEndLoc())) {
-auto *GD = cast(TD->getTemplatedDecl());
-GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
-AggregateDeductionCandidates[Hash] = GD;
-addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
-  OnlyListConstructors,
-  /*AllowAggregateDeductionCandidate=*/true);
-  }
-} else {
-  CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash];
-  FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate();
-  assert(TD && "aggregate deduction candidate is function template");
+if (FunctionTemplateDecl *TD =
+DeclareImplicitDeductionGuideFromInitList(
+Template, ElementTypes, TSInfo->getTypeLoc().getEndLoc())) 
{
+  auto *GD = cast(TD->getTemplatedDecl());
   addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
 OnlyListConstructors,
 /*AllowAggregateDeductionCandidate=*/true);
+  HasAnyDeductionGuide = true;
 }
-HasAnyDeductionGuide = true;
   }
 };
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 51e8db2dfbaac8..0a4c16f2f09f09 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2987,6 +2987,23 @@ void DeclareImplicitDeductionGuidesForTypeAlias(
 FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList(
 TemplateDecl *Template, MutableArrayRef ParamTypes,
 SourceLocation Loc) {
+  llvm::FoldingSetNodeID ID;
+  ID.AddPointer(Template);
+  for (auto &T : ParamTypes)
+T.getCanonicalType().Profile(ID);
+  unsigned Hash = ID.ComputeHash();
+  
+  auto Found = AggregateDeductionCandidates.find(Hash);
+  if (Found != AggregateDeductionCandidates.end()) {
+CXXDeductionGuideDecl *GD = Found->getSecond();
+return GD->getDescribedFunctionTemplate();
+  }
+  
+  // if (auto *AliasTemplate = 
llvm::dyn_cast(Template)) {
+  //   DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
+  //   return;
+  // }
+
   if (CXXRecordDecl *DefRecord =
   cast(Template->getTemplatedDecl())->getDefinition()) {
 if (TemplateDecl *DescribedTemplate =
@@ -3019,10 +3036,13 @@ FunctionTemplateDecl 
*Sema::DeclareImplicitDeductionGuideFromInitList(
   Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
   ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
 
-  auto *DG = cast(
+  auto *FTD = cast(
   Transform.buildSimpleDeductionGuide(ParamTypes));
   SavedContext.pop();
-  return DG;
+  auto *GD = cast(FTD->getTemplatedDecl());
+  GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
+  AggregateDeductionCandidates[Hash] = GD;
+  return FTD;
 }
 
 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,

>From 9355ff3d75221659a33ca5e7571849ff3135353a Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 19 Mar 2024 23:07:09 +0100
Subject: [PATCH 2/2] [clang] CTAD: build aggregate deduction guides for alias
 templates.

Fixes https://github.com/llvm/llvm-project/issues/85767.
---
 clang/lib/Sema/SemaInit.cpp |   2 +-
 clang/lib/Sema/SemaTemplate.cpp | 183 +++-
 clang/test/SemaTemplate/deduction-guide.cpp |  15 ++
 3 files changed, 153 insertions(+), 47 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b

[clang] [clang] CTAD: build aggregate deduction guides for alias templates. (PR #85904)

2024-03-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

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



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


3 Files Affected:

- (modified) clang/lib/Sema/SemaInit.cpp (+5-22) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+154-43) 
- (modified) clang/test/SemaTemplate/deduction-guide.cpp (+15) 


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index aa470adb30b47f..a2d5bad1300d1f 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10918,32 +10918,15 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
   Context.getLValueReferenceType(ElementTypes[I].withConst());
   }
 
-llvm::FoldingSetNodeID ID;
-ID.AddPointer(Template);
-for (auto &T : ElementTypes)
-  T.getCanonicalType().Profile(ID);
-unsigned Hash = ID.ComputeHash();
-if (AggregateDeductionCandidates.count(Hash) == 0) {
-  if (FunctionTemplateDecl *TD =
-  DeclareImplicitDeductionGuideFromInitList(
-  Template, ElementTypes,
-  TSInfo->getTypeLoc().getEndLoc())) {
-auto *GD = cast(TD->getTemplatedDecl());
-GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
-AggregateDeductionCandidates[Hash] = GD;
-addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
-  OnlyListConstructors,
-  /*AllowAggregateDeductionCandidate=*/true);
-  }
-} else {
-  CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash];
-  FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate();
-  assert(TD && "aggregate deduction candidate is function template");
+if (FunctionTemplateDecl *TD =
+DeclareImplicitDeductionGuideFromInitList(
+LookupTemplateDecl, ElementTypes, 
TSInfo->getTypeLoc().getEndLoc())) {
+  auto *GD = cast(TD->getTemplatedDecl());
   addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
 OnlyListConstructors,
 /*AllowAggregateDeductionCandidate=*/true);
+  HasAnyDeductionGuide = true;
 }
-HasAnyDeductionGuide = true;
   }
 };
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 51e8db2dfbaac8..86d07dd3a2187a 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2725,21 +2725,43 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
-// Build deduction guides for a type alias template.
-void DeclareImplicitDeductionGuidesForTypeAlias(
-Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate, SourceLocation Loc) {
-  auto &Context = SemaRef.Context;
-  // FIXME: if there is an explicit deduction guide after the first use of the
-  // type alias usage, we will not cover this explicit deduction guide. fix 
this
-  // case.
-  if (hasDeclaredDeductionGuides(
-  Context.DeclarationNames.getCXXDeductionGuideName(AliasTemplate),
-  AliasTemplate->getDeclContext()))
-return;
+NamedDecl *TransformTemplateParameter(Sema &SemaRef, DeclContext *DC,
+  NamedDecl *TemplateParam,
+  MultiLevelTemplateArgumentList &Args,
+  unsigned NewIndex) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+  NewIndex);
+  if (auto *TTP = dyn_cast(TemplateParam))
+return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
+  TTP->getDepth());
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
+  NTTP->getDepth());
+  return nullptr;
+}
+
+Expr *TransformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
+ llvm::ArrayRef TransformedArgs) 
{
+  Expr *RC =
+  FTD->getTemplateParameters()->getRequiresClause();
+  if (!RC)
+return nullptr;
+  MultiLevelTemplateArgumentList Args;
+  Args.setKind(TemplateSubstitutionKind::Rewrite);
+  Args.addOuterTemplateArguments(TransformedArgs);
+  ExprResult E = SemaRef.SubstExpr(RC, Args);
+  if (E.isInvalid())
+return nullptr;
+  return E.getAs();
+}
+
+std::pair>
+GetRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) 
{
   // Unwrap the sugared ElaboratedType.
   auto RhsType = AliasTemplate->getTemplatedDecl()
  ->getUnderlyingType()
- .getSingleStepDesugaredType(Context);
+ .getSingleS

[clang] [clang] CTAD: build aggregate deduction guides for alias templates. (PR #85904)

2024-03-20 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 5a744776bb6192dae04360609457c9f49dce43a2 
9355ff3d75221659a33ca5e7571849ff3135353a -- clang/lib/Sema/SemaInit.cpp 
clang/lib/Sema/SemaTemplate.cpp clang/test/SemaTemplate/deduction-guide.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index a2d5bad130..4cb5e69cff 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10920,7 +10920,8 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
 
 if (FunctionTemplateDecl *TD =
 DeclareImplicitDeductionGuideFromInitList(
-LookupTemplateDecl, ElementTypes, 
TSInfo->getTypeLoc().getEndLoc())) {
+LookupTemplateDecl, ElementTypes,
+TSInfo->getTypeLoc().getEndLoc())) {
   auto *GD = cast(TD->getTemplatedDecl());
   addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
 OnlyListConstructors,
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 86d07dd3a2..9f0d4c970f 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2743,8 +2743,7 @@ NamedDecl *TransformTemplateParameter(Sema &SemaRef, 
DeclContext *DC,
 
 Expr *TransformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
  llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC =
-  FTD->getTemplateParameters()->getRequiresClause();
+  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
   MultiLevelTemplateArgumentList Args;
@@ -3005,9 +3004,8 @@ FunctionTemplateDecl 
*DeclareAggrecateDeductionGuideForTypeAlias(
   GetRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
   if (!RHSTemplate)
 return nullptr;
-  auto *RHSDeductionGuide =
-  SemaRef.DeclareImplicitDeductionGuideFromInitList(RHSTemplate, 
ParamTypes,
-Loc);
+  auto *RHSDeductionGuide = SemaRef.DeclareImplicitDeductionGuideFromInitList(
+  RHSTemplate, ParamTypes, Loc);
   if (!RHSDeductionGuide)
 return nullptr;
 
@@ -3028,7 +3026,7 @@ FunctionTemplateDecl 
*DeclareAggrecateDeductionGuideForTypeAlias(
 Args.addOuterTemplateArguments(TransformedTemplateArgs);
 NamedDecl *NewParam = TransformTemplateParameter(
 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
-/*NewIndex=*/ TransformedTemplateParams.size());
+/*NewIndex=*/TransformedTemplateParams.size());
 
 TransformedTemplateArgs[TransformedTemplateParams.size()] =
 SemaRef.Context.getCanonicalTemplateArgument(
@@ -3078,7 +3076,7 @@ FunctionTemplateDecl 
*Sema::DeclareImplicitDeductionGuideFromInitList(
   for (auto &T : ParamTypes)
 T.getCanonicalType().Profile(ID);
   unsigned Hash = ID.ComputeHash();
-  
+
   auto Found = AggregateDeductionCandidates.find(Hash);
   if (Found != AggregateDeductionCandidates.end()) {
 CXXDeductionGuideDecl *GD = Found->getSecond();

``




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


[clang] [CMake] Change GCC_INSTALL_PREFIX from warning to fatal error (PR #85891)

2024-03-20 Thread via cfe-commits

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


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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-03-20 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 7adedf54a6c4d509046915777600b6e66b90bb8c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 13 Oct 2023 14:45:15 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   4 +-
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 105 +
 clang/test/Sema/attr-format-missing.c | 223 ++
 clang/test/Sema/attr-format-missing.cpp   | 211 +
 8 files changed, 552 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9cc2a72f4c864d..1ca055f65f2115 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,7 +65,9 @@ Improvements to Clang's diagnostics
 ^^^
 - We now generate a diagnostic for signed integer overflow due to unary minus
   in a non-constant expression context. This fixes
-  `Issue 31643 `_
+  `Issue 31643 `_.
+- We now generate a diagnostic for missing format attributes
+  `Issue 60718 `_.
 
 Non-comprehensive list of changes in this release
 -
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 17fdcffa2d4274..114cbbc2e82b85 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -482,7 +482,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6d6f474f6dcdab..964166b70c2aee 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -936,6 +936,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 741c2503127af7..064506e7096033 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10615,6 +10615,10 @@ class Sema final {
 ChangedStateAtExit
   };
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
  SourceLocation IncludeLoc);
   void DiagnoseUnterminatedPragmaAlignPack();
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 4602284309491c..d3ac6cb519c56e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6014,8 +6014,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 /// CheckConstructorCall - Check a constructor call for correctness and safety
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 1a0bfb3d91bcc8..f2134f2aac70bd 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6849,6 +6849,111 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// This function is called only if function call is not inside template body.
+// TODO: Add call for function calls inside template body.
+// Check if parent function misses for

[clang] [clang] Catch missing format attributes (PR #70024)

2024-03-20 Thread Budimir Aranđelović via cfe-commits


@@ -6849,6 +6849,71 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which is
+// either char or string or pointer to char and parent function format 
attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+  return false;
+
+AttrType = Attr->getType();
+return true;
+  }))
+return;
+
+  const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+  if (!ParentFuncDecl)
+return;
+
+  // Check if parent function has char, string or pointer to char parameter.
+  unsigned int StringIndex = 0;
+  if (!llvm::any_of(
+  ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+StringIndex = Param->getFunctionScopeIndex() + 1;
+QualType Ty = Param->getType();
+if (isNSStringType(Ty, Context, true))
+  return true;
+if (isCFStringType(Ty, Context))
+  return true;
+if (Ty->isPointerType() &&
+Ty->castAs()->getPointeeType()->isCharType())

budimirarandjelovicsyrmia wrote:

Let this case remains for future addressing.

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


[clang] [FMV] Emit the resolver along with the default version definition. (PR #84405)

2024-03-20 Thread Alexandros Lamprineas via cfe-commits

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


[clang] e6b5bd5 - [FMV] Emit the resolver along with the default version definition. (#84405)

2024-03-20 Thread via cfe-commits

Author: Alexandros Lamprineas
Date: 2024-03-20T09:24:29Z
New Revision: e6b5bd5854c80eac05f415ad282ba84b840b8af8

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

LOG: [FMV] Emit the resolver along with the default version definition. (#84405)

We would like the resolver to be generated eagerly, even if the
versioned function is not called from the current translation
unit. Fixes #81494. It further allows Multi Versioning to work
even if the default target version attribute is omitted from
function declarations.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGen/attr-target-version.c
clang/test/CodeGenCXX/attr-target-version.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index bb26bfcddaeb78..cb153066b28dd1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,6 +3449,9 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
+// Defer until all versions have been semantically checked.
+if (FD->hasAttr() && !FD->isMultiVersion())
+  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -3997,10 +4000,13 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
-  } else if (FD->hasAttr()) {
-GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
+
+  // Defer the resolver emission until we can reason whether the TU
+  // contains a default target version implementation.
+  if (FD->isTargetVersionMultiVersion())
+AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4093,10 +4099,11 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
+bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4122,6 +4129,9 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
+  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
+  CurFD->doesThisDeclarationHaveABody()))
+EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4177,22 +4187,27 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
+if (!EmitResolver)
+  continue;
+
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
-const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-// In prior versions of Clang, the mangling for ifuncs incorrectly
-// included an .ifunc suffix. This alias is generated for backward
-// compatibility. It is deprecated, and may be removed in the future.
-auto *Alias = llvm::GlobalAlias::create(
-DeclTy, 0, getMultiversionLinkage(*this, GD),
-MangledName + ".ifunc", IFunc, &getModule());
-SetCommonAttributes(FD, Alias);
+if (!GetGlobalValue(MangledName + ".ifunc")) {
+  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
+  // In prior versions of Clang, the mangling for ifuncs incorrectly
+  // included an

[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread A. Jiang via cfe-commits


@@ -1386,9 +1386,19 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 std::forward<_Tuple>(__t),
 typename 
__make_tuple_indices>>::type{}))
 
+#if _LIBCPP_STD_VER >= 20
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...> {
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
+#else
+template 
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>, 
+enable_if_t(std::forward<_Tuple>(__t)))...>> * = nullptr)
 _LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+#endif // _LIBCPP_STD_VER >= 20
 
 template 

frederick-vs-ja wrote:

Just making `__make_from_tuple_impl` SFINAE-friendly is insufficient and leads 
to worse diagnostic messages.

I guess we can write the following to make `make_from_tuple` SFINAE-friendly. 
`(requires` can be used since C++20 to make the implemenation clearer.)

```C++
template >>::type, class = 
void>
inline constexpr bool __can_make_from_tuple = false;
template 
inline constexpr bool __can_make_from_tuple<
_Tp, _Tuple, index_sequence<_Idx...>,
enable_if_t(std::declval<_Tuple>()))...>>> = true;

template , int> = 0>
inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp make_from_tuple(_Tuple&& __t)
_LIBCPP_NOEXCEPT_RETURN(std::__make_from_tuple_impl<_Tp>(
std::forward<_Tuple>(__t), typename 
__make_tuple_indices>>::type{}))
```

And perhaps we shouldn't touch `__make_from_tuple_impl` if it's OK to constrain 
`make_from_tuple`.

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


[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread via cfe-commits

https://github.com/zmodem updated 
https://github.com/llvm/llvm-project/pull/85271

>From 97c0ff6c3b05829eb4f0b0350b2c2d000483fe06 Mon Sep 17 00:00:00 2001
From: Hans Wennborg 
Date: Thu, 14 Mar 2024 17:09:44 +0100
Subject: [PATCH 1/5] [Coroutines] Drop dead instructions more aggressively in
 addMustTailToCoroResumes()

The old code used isInstructionTriviallyDead() when walking the path
from a resume call to function return to check if the call is in tail
position.

However, since the code was walking forwards it was not able to get past
instructions such as:

  %gep = getelementptr inbounds i64, ptr %alloc.var, i32 0
  %foo = ptrtoint ptr %gep to i64

This patch calls SimplifyInstructionsInBlock() before walking a block to
remove any dead instructions in a more rigorous fashion.
---
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp| 6 ++
 llvm/test/Transforms/Coroutines/coro-split-musttail7.ll | 7 ++-
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp 
b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 0fce596d3e2ca0..5d3106f157edcd 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -1203,10 +1203,6 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   if (isa(I) || I->isDebugOrPseudoInst() ||
   I->isLifetimeStartOrEnd())
 I = I->getNextNode();
-  else if (isInstructionTriviallyDead(I))
-// Duing we are in the middle of the transformation, we need to erase
-// the dead instruction manually.
-I = &*I->eraseFromParent();
   else
 break;
 }
@@ -1245,6 +1241,7 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   }
 
   BasicBlock *Succ = BR->getSuccessor(SuccIndex);
+  SimplifyInstructionsInBlock(Succ);
   scanPHIsAndUpdateValueMap(I, Succ, ResolvedValues);
   I = GetFirstValidInstruction(Succ->getFirstNonPHIOrDbgOrLifetime());
 
@@ -1288,6 +1285,7 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
 return false;
 
   BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
+  SimplifyInstructionsInBlock(BB);
   scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
   I = GetFirstValidInstruction(BB->getFirstNonPHIOrDbgOrLifetime());
   continue;
diff --git a/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll 
b/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
index 2257d5aee473ee..241de5cfb25a7d 100644
--- a/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
+++ b/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
@@ -1,6 +1,6 @@
 ; Tests that sinked lifetime markers wouldn't provent optimization
 ; to convert a resuming call to a musttail call.
-; The difference between this and coro-split-musttail5.ll and 
coro-split-musttail5.ll
+; The difference between this and coro-split-musttail5.ll and 
coro-split-musttail6.ll
 ; is that this contains dead instruction generated during the transformation,
 ; which makes the optimization harder.
 ; RUN: opt < %s -passes='cgscc(coro-split),simplifycfg,early-cse' -S | 
FileCheck %s
@@ -27,6 +27,11 @@ await.suspend:
   %save2 = call token @llvm.coro.save(ptr null)
   call fastcc void @fakeresume1(ptr align 8 null)
   %suspend2 = call i8 @llvm.coro.suspend(token %save2, i1 false)
+
+  ; These (non-trivially) dead instructions are in the way.
+  %gep = getelementptr inbounds i64, ptr %alloc.var, i32 0
+  %foo = ptrtoint ptr %gep to i64
+
   switch i8 %suspend2, label %exit [
 i8 0, label %await.ready
 i8 1, label %exit

>From e268280f2e384619b4c5b948f7ecf23ebe26b359 Mon Sep 17 00:00:00 2001
From: Hans Wennborg 
Date: Fri, 15 Mar 2024 15:23:12 +0100
Subject: [PATCH 2/5] skip any side-effect free instructions when looking for
 the return

---
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp | 77 
 1 file changed, 29 insertions(+), 48 deletions(-)

diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp 
b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 5d3106f157edcd..df57f9028e380f 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -1197,18 +1197,6 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   assert(InitialInst->getModule());
   const DataLayout &DL = InitialInst->getModule()->getDataLayout();
 
-  auto GetFirstValidInstruction = [](Instruction *I) {
-while (I) {
-  // BitCastInst wouldn't generate actual code so that we could skip it.
-  if (isa(I) || I->isDebugOrPseudoInst() ||
-  I->isLifetimeStartOrEnd())
-I = I->getNextNode();
-  else
-break;
-}
-return I;
-  };
-
   auto TryResolveConstant = [&ResolvedValues](Value *V) {
 auto It = ResolvedValues.find(V);
 if (It != ResolvedValues.end())
@@ -1217,8 +1205,9 @@ static bool simplifyTerminatorLeadingToRet

[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread via cfe-commits

zmodem wrote:

> I am wondering if this is a regression from f786881 (this may not be 
> important)

No, it failed before that commit also.

> And could you put the reduced example into the patch in somewhere of 
> `clang/test/CodeGenCoroutines` as a regression test?

Added `coro-symmetric-transfer-04.cpp`.

Please take another look.

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Abhin P Jose via cfe-commits

Abhinkop wrote:

@nickdesaulniers @AaronBallman Can you'll take a look at this pull request?

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


[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-20 Thread Nikita Popov via cfe-commits

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


[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-03-20 Thread Daniel Kiss via cfe-commits

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


[clang] Revert "[FMV] Emit the resolver along with the default version definition." (PR #85914)

2024-03-20 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/85914

Reverts llvm/llvm-project#84405

In between of passing the precommit tests on github and being merged
some change (perhaps in the AArch64 backend?) landed which resulted
in altering the generated resolver. I will regenerate the tests
perhaps using a less sensitive runline to such changes.

>From 06f3d687a8ecbef5d5c21bc73723e4e4c55997bd Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Wed, 20 Mar 2024 10:08:24 +
Subject: [PATCH] =?UTF-8?q?Revert=20"[FMV]=20Emit=20the=20resolver=20along?=
 =?UTF-8?q?=20with=20the=20default=20version=20definition.=20(#=E2=80=A6"?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This reverts commit e6b5bd5854c80eac05f415ad282ba84b840b8af8.
---
 clang/lib/CodeGen/CodeGenModule.cpp   |  55 +-
 clang/lib/CodeGen/CodeGenModule.h |   5 -
 clang/test/CodeGen/attr-target-version.c  | 546 ++
 clang/test/CodeGenCXX/attr-target-version.cpp | 261 ++---
 4 files changed, 238 insertions(+), 629 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index cb153066b28dd1..bb26bfcddaeb78 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,9 +3449,6 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
-// Defer until all versions have been semantically checked.
-if (FD->hasAttr() && !FD->isMultiVersion())
-  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -4000,13 +3997,10 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
+  } else if (FD->hasAttr()) {
+GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
-
-  // Defer the resolver emission until we can reason whether the TU
-  // contains a default target version implementation.
-  if (FD->isTargetVersionMultiVersion())
-AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4099,11 +4093,10 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
-bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4129,9 +4122,6 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
-  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
-  CurFD->doesThisDeclarationHaveABody()))
-EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4187,27 +4177,22 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
-if (!EmitResolver)
-  continue;
-
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
+const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-if (!GetGlobalValue(MangledName + ".ifunc")) {
-  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
-  // In prior versions of Clang, the mangling for ifuncs incorrectly
-  // included an .ifunc suffix. This alias is generated for backward
-  // compatibility. It is deprecated, and may be removed in the future.
-  auto *Alias = llvm::GlobalAlias::create(
-  DeclTy, 0, getMultiversionLinkage(*this, GD),
-  Mangled

[clang] Revert "[FMV] Emit the resolver along with the default version definition." (PR #85914)

2024-03-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

Reverts llvm/llvm-project#84405

In between of passing the precommit tests on github and being merged
some change (perhaps in the AArch64 backend?) landed which resulted
in altering the generated resolver. I will regenerate the tests
perhaps using a less sensitive runline to such changes.

---

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+13-42) 
- (modified) clang/lib/CodeGen/CodeGenModule.h (-5) 
- (modified) clang/test/CodeGen/attr-target-version.c (+180-366) 
- (modified) clang/test/CodeGenCXX/attr-target-version.cpp (+45-216) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index cb153066b28dd1..bb26bfcddaeb78 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,9 +3449,6 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
-// Defer until all versions have been semantically checked.
-if (FD->hasAttr() && !FD->isMultiVersion())
-  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -4000,13 +3997,10 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
+  } else if (FD->hasAttr()) {
+GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
-
-  // Defer the resolver emission until we can reason whether the TU
-  // contains a default target version implementation.
-  if (FD->isTargetVersionMultiVersion())
-AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4099,11 +4093,10 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
-bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4129,9 +4122,6 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
-  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
-  CurFD->doesThisDeclarationHaveABody()))
-EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4187,27 +4177,22 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
-if (!EmitResolver)
-  continue;
-
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
+const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-if (!GetGlobalValue(MangledName + ".ifunc")) {
-  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
-  // In prior versions of Clang, the mangling for ifuncs incorrectly
-  // included an .ifunc suffix. This alias is generated for backward
-  // compatibility. It is deprecated, and may be removed in the future.
-  auto *Alias = llvm::GlobalAlias::create(
-  DeclTy, 0, getMultiversionLinkage(*this, GD),
-  MangledName + ".ifunc", IFunc, &getModule());
-  SetCommonAttributes(FD, Alias);
-}
+// In prior versions of Clang, the mangling for ifuncs incorrectly
+// included an .ifunc suffix. This alias is generated for backward
+// compatibility. It is deprecated, and may be removed in the future.
+   

[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From f016e3ad661455d18536d7bcb086c4d33ef0c291 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/2] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] [clang][analyzer] Bring cplusplus.ArrayDelete out of alpha (PR #83985)

2024-03-20 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/83985

>From 881701d528255e2c49ed64f5f1df98f0f44c1d7b Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Tue, 5 Mar 2024 09:46:26 +
Subject: [PATCH] [clang][analyzer] Bring cplusplus.ArrayDelete out of alpha

---
 clang/docs/analyzer/checkers.rst  | 69 ---
 .../clang/StaticAnalyzer/Checkers/Checkers.td | 10 +--
 .../Checkers/CXXDeleteChecker.cpp |  4 +-
 clang/test/Analysis/ArrayDelete.cpp   |  2 +-
 clang/www/analyzer/alpha_checks.html  | 20 --
 clang/www/analyzer/available_checks.html  | 27 
 6 files changed, 80 insertions(+), 52 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index fe211514914272..c49f7e09f946a1 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -340,6 +340,51 @@ cplusplus
 
 C++ Checkers.
 
+.. _cplusplus-ArrayDelete:
+
+cplusplus.ArrayDelete (C++)
+"""
+
+Reports destructions of arrays of polymorphic objects that are destructed as
+their base class. If the dynamic type of the array is different from its static
+type, calling `delete[]` is undefined.
+
+This checker corresponds to the CERT rule `EXP51-CPP: Do not delete an array 
through a pointer of the incorrect type 
`_.
+
+.. code-block:: cpp
+
+ class Base {
+ public:
+   virtual ~Base() {}
+ };
+ class Derived : public Base {};
+
+ Base *create() {
+   Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
+   return x;
+ }
+
+ void foo() {
+   Base *x = create();
+   delete[] x; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
+ }
+
+**Limitations**
+
+The checker does not emit note tags when casting to and from reference types,
+even though the pointer values are tracked across references.
+
+.. code-block:: cpp
+
+ void foo() {
+   Derived *d = new Derived[10];
+   Derived &dref = *d;
+
+   Base &bref = static_cast(dref); // no note
+   Base *b = &bref;
+   delete[] b; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
+ }
+
 .. _cplusplus-InnerPointer:
 
 cplusplus.InnerPointer (C++)
@@ -2139,30 +2184,6 @@ Either the comparison is useless or there is division by 
zero.
 alpha.cplusplus
 ^^^
 
-.. _alpha-cplusplus-ArrayDelete:
-
-alpha.cplusplus.ArrayDelete (C++)
-"
-Reports destructions of arrays of polymorphic objects that are destructed as 
their base class.
-This checker corresponds to the CERT rule `EXP51-CPP: Do not delete an array 
through a pointer of the incorrect type 
`_.
-
-.. code-block:: cpp
-
- class Base {
-   virtual ~Base() {}
- };
- class Derived : public Base {}
-
- Base *create() {
-   Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
-   return x;
- }
-
- void foo() {
-   Base *x = create();
-   delete[] x; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
- }
-
 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
 
 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index a224b81c33a624..97fa8ac060eafa 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -622,6 +622,11 @@ def BlockInCriticalSectionChecker : 
Checker<"BlockInCriticalSection">,
 
 let ParentPackage = Cplusplus in {
 
+def ArrayDeleteChecker : Checker<"ArrayDelete">,
+  HelpText<"Reports destructions of arrays of polymorphic objects that are "
+   "destructed as their base class.">,
+  Documentation;
+
 def InnerPointerChecker : Checker<"InnerPointer">,
   HelpText<"Check for inner pointers of C++ containers used after "
"re/deallocation">,
@@ -777,11 +782,6 @@ def ContainerModeling : Checker<"ContainerModeling">,
   Documentation,
   Hidden;
 
-def CXXArrayDeleteChecker : Checker<"ArrayDelete">,
-  HelpText<"Reports destructions of arrays of polymorphic objects that are "
-   "destructed as their base class.">,
-  Documentation;
-
 def DeleteWithNonVirtualDtorChecker : Checker<"DeleteWithNonVirtualDtor">,
   HelpText<"Reports destructions of polymorphic objects with a non-virtual "
"destructor in their base class">,
diff --git a/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
index b4dee1e300e886..1b1226a7f1a71d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker

[clang] Revert "[FMV] Emit the resolver along with the default version definition." (PR #85914)

2024-03-20 Thread Paschalis Mpeis via cfe-commits

https://github.com/paschalis-mpeis approved this pull request.

Approving 'revert commit'.

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 7f0e9d1b00ce1aba5ae2bee9563f1b681ff5d9b8 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/2] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] Revert "[FMV] Emit the resolver along with the default version definition." (PR #85914)

2024-03-20 Thread Nico Weber via cfe-commits

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


[clang] b7975ca - Revert "[FMV] Emit the resolver along with the default version definition." (#85914)

2024-03-20 Thread via cfe-commits

Author: Alexandros Lamprineas
Date: 2024-03-20T06:16:26-04:00
New Revision: b7975cae7b18485e704a86ed4690a621e5064e13

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

LOG: Revert "[FMV] Emit the resolver along with the default version 
definition." (#85914)

Reverts llvm/llvm-project#84405

In between of passing the precommit tests on github and being merged
some change (perhaps in the AArch64 backend?) landed which resulted
in altering the generated resolver. I will regenerate the tests
perhaps using a less sensitive runline to such changes.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGen/attr-target-version.c
clang/test/CodeGenCXX/attr-target-version.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index cb153066b28dd1..bb26bfcddaeb78 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,9 +3449,6 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
-// Defer until all versions have been semantically checked.
-if (FD->hasAttr() && !FD->isMultiVersion())
-  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -4000,13 +3997,10 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
+  } else if (FD->hasAttr()) {
+GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
-
-  // Defer the resolver emission until we can reason whether the TU
-  // contains a default target version implementation.
-  if (FD->isTargetVersionMultiVersion())
-AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4099,11 +4093,10 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
-bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4129,9 +4122,6 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
-  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
-  CurFD->doesThisDeclarationHaveABody()))
-EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4187,27 +4177,22 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
-if (!EmitResolver)
-  continue;
-
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
+const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-if (!GetGlobalValue(MangledName + ".ifunc")) {
-  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
-  // In prior versions of Clang, the mangling for ifuncs incorrectly
-  // included an .ifunc suffix. This alias is generated for backward
-  // compatibility. It is deprecated, and may be removed in the future.
-  auto *Alias = llvm::GlobalAlias::create(
-  DeclTy, 0, getMultiversionLinkage(*this, GD),
-  MangledName + ".ifunc", IFunc, &getModule());
-  SetCommonAttributes(FD, Alias);
-}
+// In prior versions of Clang, the ma

[clang] Revert "[FMV] Emit the resolver along with the default version definition." (PR #85914)

2024-03-20 Thread Nico Weber via cfe-commits

nico wrote:

Thanks for the revert!

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


[clang] [llvm] [GOFF][z/OS] Change PrivateGlobalPrefix and PrivateLabelPrefix to be L# (PR #85730)

2024-03-20 Thread Ulrich Weigand via cfe-commits

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

LGTM, thanks!

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


[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread Chuanqi Xu via cfe-commits

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

LGTM. Thanks.

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


[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread Chuanqi Xu via cfe-commits

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


[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,65 @@
+// This tests that the symmetric transfer at the final suspend point could 
happen successfully.

ChuanqiXu9 wrote:

nit: I feel slightly better to add a link to the github page.

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


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-ir

@llvm/pr-subscribers-clang-codegen

Author: Alexander Shaposhnikov (alexander-shaposhnikov)


Changes

This PR introduces the numerical sanitizer originally proposed by Clement 
Courbet on https://reviews.llvm.org/D97854
(https://arxiv.org/abs/2102.12782).

The main additions include:
- Migration to LLVM opaque pointers
- Migration to various updated APIs
- Extended coverage for LLVM instructions/intrinsics, that enabled us to have a 
green run of tests again



---

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


77 Files Affected:

- (modified) clang/include/clang/Basic/Features.def (+1) 
- (modified) clang/include/clang/Basic/Sanitizers.def (+3) 
- (modified) clang/include/clang/Driver/SanitizerArgs.h (+3) 
- (modified) clang/lib/CodeGen/BackendUtil.cpp (+7) 
- (modified) clang/lib/CodeGen/CGDeclCXX.cpp (+4) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+2) 
- (modified) clang/lib/Driver/SanitizerArgs.cpp (+5-2) 
- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+3) 
- (modified) clang/lib/Driver/ToolChains/Linux.cpp (+4) 
- (modified) clang/runtime/CMakeLists.txt (+2-1) 
- (modified) compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake (+1) 
- (modified) compiler-rt/cmake/config-ix.cmake (+12-1) 
- (added) compiler-rt/include/sanitizer/nsan_interface.h (+75) 
- (added) compiler-rt/lib/nsan/CMakeLists.txt (+61) 
- (added) compiler-rt/lib/nsan/nsan.cc (+828) 
- (added) compiler-rt/lib/nsan/nsan.h (+224) 
- (added) compiler-rt/lib/nsan/nsan.syms.extra (+2) 
- (added) compiler-rt/lib/nsan/nsan_flags.cc (+78) 
- (added) compiler-rt/lib/nsan/nsan_flags.h (+35) 
- (added) compiler-rt/lib/nsan/nsan_flags.inc (+49) 
- (added) compiler-rt/lib/nsan/nsan_interceptors.cc (+363) 
- (added) compiler-rt/lib/nsan/nsan_platform.h (+135) 
- (added) compiler-rt/lib/nsan/nsan_stats.cc (+158) 
- (added) compiler-rt/lib/nsan/nsan_stats.h (+92) 
- (added) compiler-rt/lib/nsan/nsan_suppressions.cc (+76) 
- (added) compiler-rt/lib/nsan/nsan_suppressions.h (+31) 
- (added) compiler-rt/lib/nsan/tests/CMakeLists.txt (+54) 
- (added) compiler-rt/lib/nsan/tests/NSanUnitTest.cpp (+67) 
- (added) compiler-rt/lib/nsan/tests/nsan_unit_test_main.cpp (+18) 
- (added) compiler-rt/test/nsan/CMakeLists.txt (+33) 
- (added) compiler-rt/test/nsan/alloca.cc (+24) 
- (added) compiler-rt/test/nsan/cadna_ex1.cc (+21) 
- (added) compiler-rt/test/nsan/cadna_ex2.cc (+52) 
- (added) compiler-rt/test/nsan/cadna_ex3.cc (+48) 
- (added) compiler-rt/test/nsan/cadna_ex4.cc (+37) 
- (added) compiler-rt/test/nsan/cadna_ex5.cc (+97) 
- (added) compiler-rt/test/nsan/cadna_ex6.cc (+67) 
- (added) compiler-rt/test/nsan/cadna_ex7.cc (+110) 
- (added) compiler-rt/test/nsan/cancellation_fn_ptr.cc (+66) 
- (added) compiler-rt/test/nsan/cancellation_libm.cc (+51) 
- (added) compiler-rt/test/nsan/cancellation_ok.cc (+53) 
- (added) compiler-rt/test/nsan/compare.cc (+28) 
- (added) compiler-rt/test/nsan/compute_pi.cc (+45) 
- (added) compiler-rt/test/nsan/helpers.h (+15) 
- (added) compiler-rt/test/nsan/infinity.cc (+24) 
- (added) compiler-rt/test/nsan/intercept_libc_str.cc (+149) 
- (added) compiler-rt/test/nsan/interface_dump_shadow_mem.cc (+62) 
- (added) compiler-rt/test/nsan/jmmuller.cc (+35) 
- (added) compiler-rt/test/nsan/lit.cfg.py (+45) 
- (added) compiler-rt/test/nsan/lit.site.cfg.py.in (+11) 
- (added) compiler-rt/test/nsan/memcpy.cc (+83) 
- (added) compiler-rt/test/nsan/memset_nonzero.cc (+23) 
- (added) compiler-rt/test/nsan/memset_zero.cc (+24) 
- (added) compiler-rt/test/nsan/rump_royal_pain.cc (+37) 
- (added) compiler-rt/test/nsan/simd.cc (+25) 
- (added) compiler-rt/test/nsan/stable_sort.cc (+52) 
- (added) compiler-rt/test/nsan/stack.cc (+20) 
- (added) compiler-rt/test/nsan/sums.cc (+82) 
- (added) compiler-rt/test/nsan/swap.cc (+46) 
- (added) compiler-rt/test/nsan/type_punning.cc (+26) 
- (added) compiler-rt/test/nsan/uninstrumented_write.cc (+22) 
- (added) compiler-rt/test/nsan/vector_push_back.cc (+17) 
- (added) compiler-rt/test/nsan/verificarlo_case4.cc (+29) 
- (modified) llvm/include/llvm/Bitcode/LLVMBitCodes.h (+1) 
- (modified) llvm/include/llvm/IR/Attributes.td (+4) 
- (added) 
llvm/include/llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h 
(+40) 
- (modified) llvm/lib/Bitcode/Reader/BitcodeReader.cpp (+2) 
- (modified) llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (+2) 
- (modified) llvm/lib/Passes/PassBuilder.cpp (+1) 
- (modified) llvm/lib/Passes/PassRegistry.def (+2) 
- (modified) llvm/lib/Transforms/Instrumentation/CMakeLists.txt (+1) 
- (added) llvm/lib/Transforms/Instrumentation/NumericalStabilitySanitizer.cpp 
(+2261) 
- (modified) llvm/lib/Transforms/Utils/CodeExtractor.cpp (+1) 
- (added) llvm/test/Instrumentation/NumericalStabilitySanitizer/basic.ll (+930) 
- (added) llvm/test/Instrumentation/NumericalStabilitySanitizer/cfg.ll (+113) 
- (added) llvm/test/Instrumentation/NumericalSta

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

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


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread via cfe-commits

github-actions[bot] wrote:




:warning: Python code formatter, darker found issues in your code. :warning:



You can test this locally with the following command:


``bash
darker --check --diff -r 
9fd1c4121f7c797ff7222161cb40cd68ecf0fbc8...f932900890ba96ae01f8c4d762aca5023d0b7fce
 compiler-rt/test/nsan/lit.cfg.py
``





View the diff from darker here.


``diff
--- lit.cfg.py  2024-03-20 09:59:30.00 +
+++ lit.cfg.py  2024-03-20 10:39:52.135628 +
@@ -1,45 +1,53 @@
 # -*- Python -*-
 
 import os
 
 # Setup config name.
-config.name = 'NSan' + config.name_suffix
+config.name = "NSan" + config.name_suffix
 
 # Setup source root.
 config.test_source_root = os.path.dirname(__file__)
 
 # Test suffixes.
-config.suffixes = ['.c', '.cc', '.test']
+config.suffixes = [".c", ".cc", ".test"]
 
 # C & CXX flags.
-c_flags = ([config.target_cflags])
+c_flags = [config.target_cflags]
 
 # Android doesn't want -lrt.
 if not config.android:
-  c_flags += ["-lrt"]
+c_flags += ["-lrt"]
 
-cxx_flags = (c_flags + config.cxx_mode_flags + ["-std=c++17"])
+cxx_flags = c_flags + config.cxx_mode_flags + ["-std=c++17"]
 
-nsan_flags = ["-fsanitize=numerical", "-g",
-  "-mno-omit-leaf-frame-pointer",
-  "-fno-omit-frame-pointer"]
+nsan_flags = [
+"-fsanitize=numerical",
+"-g",
+"-mno-omit-leaf-frame-pointer",
+"-fno-omit-frame-pointer",
+]
+
 
 def build_invocation(compile_flags):
-  return " " + " ".join([config.clang] + compile_flags) + " "
+return " " + " ".join([config.clang] + compile_flags) + " "
+
 
 # Add substitutions.
 config.substitutions.append(("%clang ", build_invocation(c_flags)))
 config.substitutions.append(("%clang_nsan ", build_invocation(c_flags + 
nsan_flags)))
-config.substitutions.append(("%clangxx_nsan ", build_invocation(cxx_flags + 
nsan_flags)))
+config.substitutions.append(
+("%clangxx_nsan ", build_invocation(cxx_flags + nsan_flags))
+)
 
 # Platform-specific default NSAN for lit tests.
-default_nsan_options = ''
+default_nsan_options = ""
 
-config.environment['NSAN_OPTIONS'] = default_nsan_options
-default_nsan_options += ':'
-config.substitutions.append(('%env_nsan_options=',
- 'env NSAN_OPTIONS=' + default_nsan_options))
+config.environment["NSAN_OPTIONS"] = default_nsan_options
+default_nsan_options += ":"
+config.substitutions.append(
+("%env_nsan_options=", "env NSAN_OPTIONS=" + default_nsan_options)
+)
 
 # NSan tests are currently supported on Linux only.
-if config.host_os not in ['Linux']:
-   config.unsupported = True
+if config.host_os not in ["Linux"]:
+config.unsupported = True

``




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


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

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


[clang] [clang][frontend] Make DumpModuleInfoAction emit the full macro (PR #85745)

2024-03-20 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 commented:

Dumping things from the source location makes me nervous... And giving this is 
not related to named modules, I'd like to leave this for @Bigcheese 

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


[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread via cfe-commits

https://github.com/zmodem updated 
https://github.com/llvm/llvm-project/pull/85271

>From 97c0ff6c3b05829eb4f0b0350b2c2d000483fe06 Mon Sep 17 00:00:00 2001
From: Hans Wennborg 
Date: Thu, 14 Mar 2024 17:09:44 +0100
Subject: [PATCH 1/6] [Coroutines] Drop dead instructions more aggressively in
 addMustTailToCoroResumes()

The old code used isInstructionTriviallyDead() when walking the path
from a resume call to function return to check if the call is in tail
position.

However, since the code was walking forwards it was not able to get past
instructions such as:

  %gep = getelementptr inbounds i64, ptr %alloc.var, i32 0
  %foo = ptrtoint ptr %gep to i64

This patch calls SimplifyInstructionsInBlock() before walking a block to
remove any dead instructions in a more rigorous fashion.
---
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp| 6 ++
 llvm/test/Transforms/Coroutines/coro-split-musttail7.ll | 7 ++-
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp 
b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 0fce596d3e2ca0..5d3106f157edcd 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -1203,10 +1203,6 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   if (isa(I) || I->isDebugOrPseudoInst() ||
   I->isLifetimeStartOrEnd())
 I = I->getNextNode();
-  else if (isInstructionTriviallyDead(I))
-// Duing we are in the middle of the transformation, we need to erase
-// the dead instruction manually.
-I = &*I->eraseFromParent();
   else
 break;
 }
@@ -1245,6 +1241,7 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   }
 
   BasicBlock *Succ = BR->getSuccessor(SuccIndex);
+  SimplifyInstructionsInBlock(Succ);
   scanPHIsAndUpdateValueMap(I, Succ, ResolvedValues);
   I = GetFirstValidInstruction(Succ->getFirstNonPHIOrDbgOrLifetime());
 
@@ -1288,6 +1285,7 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
 return false;
 
   BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
+  SimplifyInstructionsInBlock(BB);
   scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
   I = GetFirstValidInstruction(BB->getFirstNonPHIOrDbgOrLifetime());
   continue;
diff --git a/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll 
b/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
index 2257d5aee473ee..241de5cfb25a7d 100644
--- a/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
+++ b/llvm/test/Transforms/Coroutines/coro-split-musttail7.ll
@@ -1,6 +1,6 @@
 ; Tests that sinked lifetime markers wouldn't provent optimization
 ; to convert a resuming call to a musttail call.
-; The difference between this and coro-split-musttail5.ll and 
coro-split-musttail5.ll
+; The difference between this and coro-split-musttail5.ll and 
coro-split-musttail6.ll
 ; is that this contains dead instruction generated during the transformation,
 ; which makes the optimization harder.
 ; RUN: opt < %s -passes='cgscc(coro-split),simplifycfg,early-cse' -S | 
FileCheck %s
@@ -27,6 +27,11 @@ await.suspend:
   %save2 = call token @llvm.coro.save(ptr null)
   call fastcc void @fakeresume1(ptr align 8 null)
   %suspend2 = call i8 @llvm.coro.suspend(token %save2, i1 false)
+
+  ; These (non-trivially) dead instructions are in the way.
+  %gep = getelementptr inbounds i64, ptr %alloc.var, i32 0
+  %foo = ptrtoint ptr %gep to i64
+
   switch i8 %suspend2, label %exit [
 i8 0, label %await.ready
 i8 1, label %exit

>From e268280f2e384619b4c5b948f7ecf23ebe26b359 Mon Sep 17 00:00:00 2001
From: Hans Wennborg 
Date: Fri, 15 Mar 2024 15:23:12 +0100
Subject: [PATCH 2/6] skip any side-effect free instructions when looking for
 the return

---
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp | 77 
 1 file changed, 29 insertions(+), 48 deletions(-)

diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp 
b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 5d3106f157edcd..df57f9028e380f 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -1197,18 +1197,6 @@ static bool simplifyTerminatorLeadingToRet(Instruction 
*InitialInst) {
   assert(InitialInst->getModule());
   const DataLayout &DL = InitialInst->getModule()->getDataLayout();
 
-  auto GetFirstValidInstruction = [](Instruction *I) {
-while (I) {
-  // BitCastInst wouldn't generate actual code so that we could skip it.
-  if (isa(I) || I->isDebugOrPseudoInst() ||
-  I->isLifetimeStartOrEnd())
-I = I->getNextNode();
-  else
-break;
-}
-return I;
-  };
-
   auto TryResolveConstant = [&ResolvedValues](Value *V) {
 auto It = ResolvedValues.find(V);
 if (It != ResolvedValues.end())
@@ -1217,8 +1205,9 @@ static bool simplifyTerminatorLeadingToRet

[clang] [llvm] [Coroutines] Drop dead instructions more aggressively in addMustTailToCoroResumes() (PR #85271)

2024-03-20 Thread via cfe-commits


@@ -0,0 +1,65 @@
+// This tests that the symmetric transfer at the final suspend point could 
happen successfully.

zmodem wrote:

Done.

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


[clang] [llvm] [AArch64] Remove Automatic Enablement of FEAT_F32MM (PR #85203)

2024-03-20 Thread Rodolfo Wottrich via cfe-commits


@@ -2487,10 +2480,10 @@ AArch64ExtensionDependenciesBaseCPUTestParams
  {}},
 {"cortex-a520",
  {},
- {"v9.2a","bf16", "crc", "dotprod", "f32mm",
"flagm",
-  "fp-armv8", "fullfp16", "fp16fml", "i8mm","lse",  "mte",
-  "pauth","perfmon",  "predres", "ras", "rcpc", "rdm",
-  "sb",   "neon", "ssbs","sve", "sve2-bitperm", 
"sve2"},
+ {"v9.2a","bf16","crc",  "dotprod",  "flagm", "fp-armv8",

rgwott wrote:

Are these entries not better off one per line? The patch is modifying all lines 
anyway, might as well make it so that any future modifications would be more 
modular.

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


[clang] [llvm] [AArch64] Remove Automatic Enablement of FEAT_F32MM (PR #85203)

2024-03-20 Thread Jack Styles via cfe-commits


@@ -2487,10 +2480,10 @@ AArch64ExtensionDependenciesBaseCPUTestParams
  {}},
 {"cortex-a520",
  {},
- {"v9.2a","bf16", "crc", "dotprod", "f32mm",
"flagm",
-  "fp-armv8", "fullfp16", "fp16fml", "i8mm","lse",  "mte",
-  "pauth","perfmon",  "predres", "ras", "rcpc", "rdm",
-  "sb",   "neon", "ssbs","sve", "sve2-bitperm", 
"sve2"},
+ {"v9.2a","bf16","crc",  "dotprod",  "flagm", "fp-armv8",

Stylie777 wrote:

I would probably agree with you but the formatting here was assigned by 
`clang-format`. I also thing this is outside of the scope of this PR and should 
be done separately as this is a formatting change rather than a functionality 
change which this PR is focused on.

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


[clang] [llvm] [AArch64] Remove Automatic Enablement of FEAT_F32MM (PR #85203)

2024-03-20 Thread Jack Styles via cfe-commits

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 7f0e9d1b00ce1aba5ae2bee9563f1b681ff5d9b8 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/3] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-20 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/83027

From a061464b75ac02c21e5d74fc4dff8d8afdbba66b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Wed, 20 Mar 2024 10:49:08 +0100
Subject: [PATCH 01/18] [NFC] UnixAPIMisuseChecker inherits from
 Checker

---
 .../Checkers/UnixAPIChecker.cpp   | 60 +--
 1 file changed, 30 insertions(+), 30 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index 19f1ca2dc824c9..599e5e6cedc606 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "llvm/ADT/STLExtras.h"
@@ -41,8 +42,7 @@ enum class OpenVariant {
 namespace {
 
 class UnixAPIMisuseChecker
-: public Checker,
- check::ASTDecl> {
+: public Checker> {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
@@ -52,14 +52,14 @@ class UnixAPIMisuseChecker
   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
 BugReporter &BR) const;
 
-  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
 
-  void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
-  void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
-  void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
+  void CheckOpen(CheckerContext &C, const CallEvent &Call) const;
+  void CheckOpenAt(CheckerContext &C, const CallEvent &Call) const;
+  void CheckPthreadOnce(CheckerContext &C, const CallEvent &Call) const;
 
-  void CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE, OpenVariant Variant) const;
+  void CheckOpenVariant(CheckerContext &C, const CallEvent &Call,
+OpenVariant Variant) const;
 
   void ReportOpenBug(CheckerContext &C, ProgramStateRef State, const char *Msg,
  SourceRange SR) const;
@@ -113,9 +113,9 @@ void UnixAPIMisuseChecker::checkASTDecl(const 
TranslationUnitDecl *TU,
 // "open" (man 2 open)
 //===--===/
 
-void UnixAPIMisuseChecker::checkPreStmt(const CallExpr *CE,
+void UnixAPIMisuseChecker::checkPreCall(const CallEvent &Call,
 CheckerContext &C) const {
-  const FunctionDecl *FD = C.getCalleeDecl(CE);
+  const FunctionDecl *FD = dyn_cast_if_present(Call.getDecl());
   if (!FD || FD->getKind() != Decl::Function)
 return;
 
@@ -130,13 +130,13 @@ void UnixAPIMisuseChecker::checkPreStmt(const CallExpr 
*CE,
 return;
 
   if (FName == "open")
-CheckOpen(C, CE);
+CheckOpen(C, Call);
 
   else if (FName == "openat")
-CheckOpenAt(C, CE);
+CheckOpenAt(C, Call);
 
   else if (FName == "pthread_once")
-CheckPthreadOnce(C, CE);
+CheckPthreadOnce(C, Call);
 }
 void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext &C,
  ProgramStateRef State,
@@ -152,17 +152,17 @@ void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext 
&C,
 }
 
 void UnixAPIMisuseChecker::CheckOpen(CheckerContext &C,
- const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::Open);
+ const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::Open);
 }
 
 void UnixAPIMisuseChecker::CheckOpenAt(CheckerContext &C,
-   const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::OpenAt);
+   const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::OpenAt);
 }
 
 void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE,
+const CallEvent &Call,
 OpenVariant Variant) const {
   // The index of the argument taking the flags open flags (O_RDONLY,
   // O_WRONLY, O_CREAT, etc.),
@@ -191,11 +191,11 @@ void 
UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
 
   ProgramStateRef state = C.getState();
 
-  if (CE->getNumArgs() < MinArgCount) {
+  if (Call.getNumArgs() < MinArgCount) {
 // The frontend

[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-20 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1179,6 +1195,113 @@ void StreamChecker::evalUngetc(const FnDescription 
*Desc, const CallEvent &Call,
   C.addTransition(StateFailed);
 }
 
+ProgramStateRef StreamChecker::ensureGetdelimBufferAndSizeCorrect(
+SVal LinePtrPtrSVal, SVal SizePtrSVal, const Expr *LinePtrPtrExpr,
+const Expr *SizePtrExpr, CheckerContext &C, ProgramStateRef State) const {
+  static constexpr char SizeGreaterThanBufferSize[] =
+  "The buffer from the first argument is smaller than the size "
+  "specified by the second parameter";
+  static constexpr char SizeUndef[] =
+  "The buffer from the first argument is not NULL, but the size specified "
+  "by the second parameter is undefined.";

alejandro-alvarez-sonarsource wrote:

Fixed.

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


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-20 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1179,6 +1195,113 @@ void StreamChecker::evalUngetc(const FnDescription 
*Desc, const CallEvent &Call,
   C.addTransition(StateFailed);
 }
 
+ProgramStateRef StreamChecker::ensureGetdelimBufferAndSizeCorrect(
+SVal LinePtrPtrSVal, SVal SizePtrSVal, const Expr *LinePtrPtrExpr,
+const Expr *SizePtrExpr, CheckerContext &C, ProgramStateRef State) const {
+  static constexpr char SizeGreaterThanBufferSize[] =
+  "The buffer from the first argument is smaller than the size "
+  "specified by the second parameter";
+  static constexpr char SizeUndef[] =
+  "The buffer from the first argument is not NULL, but the size specified "
+  "by the second parameter is undefined.";
+
+  auto EmitBugReport = [this, &C, SizePtrExpr,
+LinePtrPtrExpr](const ProgramStateRef &BugState,

alejandro-alvarez-sonarsource wrote:

Changed.

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits


@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+  }
+  ReplacementText = ReplacementText.substr(0, ReplacementText.size() - 2) + 
"}";
+
+  diag(TopCall->getBeginLoc(),
+   "do not use nested std::%0 calls, use %1 instead")
+  << TopCall->getDirectCallee()->getName() << ReplacementText
+  << FixItHint::CreateReplacement(
+ CharSourceRange::getTokenRange(
+ FirstArg->getBeginLoc(),
+ Lexer::getLocForEndOfToken(TopCall->getEndLoc(), 0,
+Result.Context->getSourceManager(),
+Result.Context->getLangOpts())
+ .getLocWithOffset(-2)),
+ ReplacementText)
+  << Inserter.createMainFileIncludeInsertion("");

sopyb wrote:

Marking this as resolved please check my other reply 
[here](https://github.com/llvm/llvm-project/pull/85572#discussion_r1527662792)

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 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 0f46e31cfbf415fcd3d3ce121bef94e92c6ccfc8 
bf7543ed9e52eba668b1d56e375e71288d800d99 -- 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h 
clang-tools-extra/test/clang-tidy/checkers/modernize/min-max-use-initializer-list.cpp
 clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
index 2fc6b517ad..6e86c39843 100644
--- a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -162,8 +162,7 @@ std::string 
MinMaxUseInitializerListCheck::generateReplacement(
 (InnerCallNameStr == "std::min" ||
  InnerCallNameStr == "std::max")) {
   FindArgsResult innerResult = findArgs(Match, InnerCall);
-  ReplacementText +=
-  generateReplacement(Match, InnerCall, innerResult);
+  ReplacementText += generateReplacement(Match, InnerCall, 
innerResult);
   continue;
 }
   }

``




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


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-20 Thread Alejandro Álvarez Ayllón via cfe-commits

alejandro-alvarez-sonarsource wrote:

Sorry for the force-push, but I have moved now the precondition checks to 
`UnixAPIChecker` after uplifting its API (now it uses `PreCall` instead of 
`PreStmt`). From my understanding, the previous implementation used a legacy 
way of handling them.

The idea would be to rebase, keep the `[NFC]` separate, and squash everything 
that comes after.
Since I had a merge from main in the middle, I found it easier to rebase.

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


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-20 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/83027

From a061464b75ac02c21e5d74fc4dff8d8afdbba66b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Wed, 20 Mar 2024 10:49:08 +0100
Subject: [PATCH 01/19] [NFC] UnixAPIMisuseChecker inherits from
 Checker

---
 .../Checkers/UnixAPIChecker.cpp   | 60 +--
 1 file changed, 30 insertions(+), 30 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index 19f1ca2dc824c9..599e5e6cedc606 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "llvm/ADT/STLExtras.h"
@@ -41,8 +42,7 @@ enum class OpenVariant {
 namespace {
 
 class UnixAPIMisuseChecker
-: public Checker,
- check::ASTDecl> {
+: public Checker> {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
@@ -52,14 +52,14 @@ class UnixAPIMisuseChecker
   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
 BugReporter &BR) const;
 
-  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
 
-  void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
-  void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
-  void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
+  void CheckOpen(CheckerContext &C, const CallEvent &Call) const;
+  void CheckOpenAt(CheckerContext &C, const CallEvent &Call) const;
+  void CheckPthreadOnce(CheckerContext &C, const CallEvent &Call) const;
 
-  void CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE, OpenVariant Variant) const;
+  void CheckOpenVariant(CheckerContext &C, const CallEvent &Call,
+OpenVariant Variant) const;
 
   void ReportOpenBug(CheckerContext &C, ProgramStateRef State, const char *Msg,
  SourceRange SR) const;
@@ -113,9 +113,9 @@ void UnixAPIMisuseChecker::checkASTDecl(const 
TranslationUnitDecl *TU,
 // "open" (man 2 open)
 //===--===/
 
-void UnixAPIMisuseChecker::checkPreStmt(const CallExpr *CE,
+void UnixAPIMisuseChecker::checkPreCall(const CallEvent &Call,
 CheckerContext &C) const {
-  const FunctionDecl *FD = C.getCalleeDecl(CE);
+  const FunctionDecl *FD = dyn_cast_if_present(Call.getDecl());
   if (!FD || FD->getKind() != Decl::Function)
 return;
 
@@ -130,13 +130,13 @@ void UnixAPIMisuseChecker::checkPreStmt(const CallExpr 
*CE,
 return;
 
   if (FName == "open")
-CheckOpen(C, CE);
+CheckOpen(C, Call);
 
   else if (FName == "openat")
-CheckOpenAt(C, CE);
+CheckOpenAt(C, Call);
 
   else if (FName == "pthread_once")
-CheckPthreadOnce(C, CE);
+CheckPthreadOnce(C, Call);
 }
 void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext &C,
  ProgramStateRef State,
@@ -152,17 +152,17 @@ void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext 
&C,
 }
 
 void UnixAPIMisuseChecker::CheckOpen(CheckerContext &C,
- const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::Open);
+ const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::Open);
 }
 
 void UnixAPIMisuseChecker::CheckOpenAt(CheckerContext &C,
-   const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::OpenAt);
+   const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::OpenAt);
 }
 
 void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE,
+const CallEvent &Call,
 OpenVariant Variant) const {
   // The index of the argument taking the flags open flags (O_RDONLY,
   // O_WRONLY, O_CREAT, etc.),
@@ -191,11 +191,11 @@ void 
UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
 
   ProgramStateRef state = C.getState();
 
-  if (CE->getNumArgs() < MinArgCount) {
+  if (Call.getNumArgs() < MinArgCount) {
 // The frontend

[clang] [clang] Add `__has_extension(swiftcc)` support (PR #85347)

2024-03-20 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

Do you need someone to commit this on your behalf?

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 7f0e9d1b00ce1aba5ae2bee9563f1b681ff5d9b8 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/4] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits


@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";

sopyb wrote:

I am unsure if a type cast may even be needed over here since the method 
declaration for std::{max, min} would require the first 2 parameters being 
compared would be type casted to the correct type already or it wouldn't 
compile.

```cpp
template< class T >
const T& max( const T& a, const T& b );

template< class T, class Compare >
const T& max( const T& a, const T& b, Compare comp );

template< class T >
const T& min( const T& a, const T& b );

template< class T, class Compare >
const T& min( const T& a, const T& b, Compare comp );
```

Source: 
 - https://en.cppreference.com/w/cpp/algorithm/min
 - https://en.cppreference.com/w/cpp/algorithm/max

Let me know if I am misunderstanding the intended purpose of the typecast in 
this case.

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 7f0e9d1b00ce1aba5ae2bee9563f1b681ff5d9b8 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/4] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 4e466541a5ccf22d6fef08c71077e1f95ed10616 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/4] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] 4b369ff - [analyzer][NFC] Fix unused variable warning

2024-03-20 Thread Fraser Cormack via cfe-commits

Author: Fraser Cormack
Date: 2024-03-20T11:43:38Z
New Revision: 4b369ff076d9205ddbcfcdef89276a737a83ce0e

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

LOG: [analyzer][NFC] Fix unused variable warning

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 1a9d6d3127fb7f..b36fa95bc73f3e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -43,8 +43,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 if (auto *call = dyn_cast(E)) {
   if (auto *memberCall = dyn_cast(call)) {
 if (auto *decl = memberCall->getMethodDecl()) {
-  std::optional IsGetterOfRefCt =
-  isGetterOfRefCounted(memberCall->getMethodDecl());
+  std::optional IsGetterOfRefCt = isGetterOfRefCounted(decl);
   if (IsGetterOfRefCt && *IsGetterOfRefCt) {
 E = memberCall->getImplicitObjectArgument();
 if (StopAtFirstRefCountedObj) {



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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 4e466541a5ccf22d6fef08c71077e1f95ed10616 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/5] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-20 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/85921

None

>From 144119d57d181fb16e27a5c7d869422a39185978 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 20 Mar 2024 19:36:50 +0800
Subject: [PATCH] [clang][AST][NFC] Add '[[fallthrough]];' to cases fall
 through

---
 clang/lib/CodeGen/CGStmt.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8898e3f22a7df6..7d7744bafb110e 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -160,7 +160,7 @@ void CodeGenFunction::EmitStmt(const Stmt *S, 
ArrayRef Attrs) {
   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast(*S));  
break;
 
   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast(*S));  
break;
-  case Stmt::GCCAsmStmtClass:  // Intentional fall-through.
+  case Stmt::GCCAsmStmtClass:  [[fallthrough]];
   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast(*S));
break;
   case Stmt::CoroutineBodyStmtClass:
 EmitCoroutineBody(cast(*S));

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


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Ben Shi (benshi001)


Changes



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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGStmt.cpp (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8898e3f22a7df6..7d7744bafb110e 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -160,7 +160,7 @@ void CodeGenFunction::EmitStmt(const Stmt *S, 
ArrayRef Attrs) {
   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast(*S));  
break;
 
   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast(*S));  
break;
-  case Stmt::GCCAsmStmtClass:  // Intentional fall-through.
+  case Stmt::GCCAsmStmtClass:  [[fallthrough]];
   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast(*S));
break;
   case Stmt::CoroutineBodyStmtClass:
 EmitCoroutineBody(cast(*S));

``




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


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-20 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 e2fa90fa0a4b7950dd0d7fae6933e89c075d0af0 
144119d57d181fb16e27a5c7d869422a39185978 -- clang/lib/CodeGen/CGStmt.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 7d7744bafb..7bec3d227f 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -160,7 +160,8 @@ void CodeGenFunction::EmitStmt(const Stmt *S, 
ArrayRef Attrs) {
   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast(*S));  
break;
 
   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast(*S));  
break;
-  case Stmt::GCCAsmStmtClass:  [[fallthrough]];
+  case Stmt::GCCAsmStmtClass:
+[[fallthrough]];
   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast(*S));
break;
   case Stmt::CoroutineBodyStmtClass:
 EmitCoroutineBody(cast(*S));

``




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


[clang] Reland [FMV] Emit the resolver along with the default version definit… (PR #85923)

2024-03-20 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/85923

…ion.

This was reverted because the resolver didn't look as expected in one of the 
tests. I believe it had some interaction with #84146. I have now regenerated it 
using -target-feature -fp-armv8.

>From 20a44fd71d408ed5f5c8c8062dff2747f31dd27e Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Wed, 20 Mar 2024 10:32:58 +
Subject: [PATCH] Reland [FMV] Emit the resolver along with the default version
 definition.

This was reverted because the resolver didn't look as expected in one of
the tests. I believe it had some interaction with #84146. I have now
regenerated it using -target-feature -fp-armv8.
---
 clang/lib/CodeGen/CodeGenModule.cpp   |  55 +-
 clang/lib/CodeGen/CodeGenModule.h |   5 +
 clang/test/CodeGen/attr-target-version.c  | 546 --
 clang/test/CodeGenCXX/attr-target-version.cpp | 261 +++--
 4 files changed, 629 insertions(+), 238 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index bb26bfcddaeb78..cb153066b28dd1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,6 +3449,9 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
+// Defer until all versions have been semantically checked.
+if (FD->hasAttr() && !FD->isMultiVersion())
+  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -3997,10 +4000,13 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
-  } else if (FD->hasAttr()) {
-GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
+
+  // Defer the resolver emission until we can reason whether the TU
+  // contains a default target version implementation.
+  if (FD->isTargetVersionMultiVersion())
+AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4093,10 +4099,11 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
+bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4122,6 +4129,9 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
+  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
+  CurFD->doesThisDeclarationHaveABody()))
+EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4177,22 +4187,27 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
+if (!EmitResolver)
+  continue;
+
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
-const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-// In prior versions of Clang, the mangling for ifuncs incorrectly
-// included an .ifunc suffix. This alias is generated for backward
-// compatibility. It is deprecated, and may be removed in the future.
-auto *Alias = llvm::GlobalAlias::create(
-DeclTy, 0, getMultiversionLinkage(*this, GD),
-MangledName + ".ifunc", IFunc, &getModule());
-SetCommonAttributes(FD, Alias);
+if (!GetGlobalValue(MangledName + ".ifunc")) {
+  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
+  // In prior versions of Clang, the 

[clang] Reland [FMV] Emit the resolver along with the default version definit… (PR #85923)

2024-03-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Alexandros Lamprineas (labrinea)


Changes

…ion.

This was reverted because the resolver didn't look as expected in one of the 
tests. I believe it had some interaction with #84146. I have now 
regenerated it using -target-feature -fp-armv8.

---

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+42-13) 
- (modified) clang/lib/CodeGen/CodeGenModule.h (+5) 
- (modified) clang/test/CodeGen/attr-target-version.c (+366-180) 
- (modified) clang/test/CodeGenCXX/attr-target-version.cpp (+216-45) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index bb26bfcddaeb78..cb153066b28dd1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,6 +3449,9 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
+// Defer until all versions have been semantically checked.
+if (FD->hasAttr() && !FD->isMultiVersion())
+  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -3997,10 +4000,13 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
-  } else if (FD->hasAttr()) {
-GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
+
+  // Defer the resolver emission until we can reason whether the TU
+  // contains a default target version implementation.
+  if (FD->isTargetVersionMultiVersion())
+AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4093,10 +4099,11 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
+bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4122,6 +4129,9 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
+  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
+  CurFD->doesThisDeclarationHaveABody()))
+EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4177,22 +4187,27 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
+if (!EmitResolver)
+  continue;
+
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
-const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-// In prior versions of Clang, the mangling for ifuncs incorrectly
-// included an .ifunc suffix. This alias is generated for backward
-// compatibility. It is deprecated, and may be removed in the future.
-auto *Alias = llvm::GlobalAlias::create(
-DeclTy, 0, getMultiversionLinkage(*this, GD),
-MangledName + ".ifunc", IFunc, &getModule());
-SetCommonAttributes(FD, Alias);
+if (!GetGlobalValue(MangledName + ".ifunc")) {
+  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
+  // In prior versions of Clang, the mangling for ifuncs incorrectly
+  // included an .ifunc suffix. This alias is generated for backward
+  // compatibility. It is deprecated, and may be removed in the future.
+  auto *Alias = llvm::GlobalAlias::create(
+  DeclTy, 0, getMultiversionLinkage(*this

[clang] Reland [FMV] Emit the resolver along with the default version definit… (PR #85923)

2024-03-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

…ion.

This was reverted because the resolver didn't look as expected in one of the 
tests. I believe it had some interaction with #84146. I have now 
regenerated it using -target-feature -fp-armv8.

---

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+42-13) 
- (modified) clang/lib/CodeGen/CodeGenModule.h (+5) 
- (modified) clang/test/CodeGen/attr-target-version.c (+366-180) 
- (modified) clang/test/CodeGenCXX/attr-target-version.cpp (+216-45) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index bb26bfcddaeb78..cb153066b28dd1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3449,6 +3449,9 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl 
*Global) {
   // Implicit template instantiations may change linkage if they are later
   // explicitly instantiated, so they should not be emitted eagerly.
   return false;
+// Defer until all versions have been semantically checked.
+if (FD->hasAttr() && !FD->isMultiVersion())
+  return false;
   }
   if (const auto *VD = dyn_cast(Global)) {
 if (Context.getInlineVariableDefinitionKind(VD) ==
@@ -3997,10 +4000,13 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
 // Ensure that the resolver function is also emitted.
 GetOrCreateMultiVersionResolver(GD);
-  } else if (FD->hasAttr()) {
-GetOrCreateMultiVersionResolver(GD);
   } else
 EmitGlobalFunctionDefinition(GD, GV);
+
+  // Defer the resolver emission until we can reason whether the TU
+  // contains a default target version implementation.
+  if (FD->isTargetVersionMultiVersion())
+AddDeferredMultiVersionResolverToEmit(GD);
 }
 
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) 
{
@@ -4093,10 +4099,11 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
+bool EmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
+  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
 GlobalDecl CurGD{
 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
 StringRef MangledName = getMangledName(CurGD);
@@ -4122,6 +4129,9 @@ void CodeGenModule::emitMultiVersionFunctions() {
TA->getArchitecture(), Feats);
 } else {
   const auto *TVA = CurFD->getAttr();
+  if (CurFD->isUsed() || (TVA->isDefaultVersion() &&
+  CurFD->doesThisDeclarationHaveABody()))
+EmitResolver = true;
   llvm::SmallVector Feats;
   TVA->getFeatures(Feats);
   Options.emplace_back(cast(Func),
@@ -4177,22 +4187,27 @@ void CodeGenModule::emitMultiVersionFunctions() {
   continue;
 }
 
+if (!EmitResolver)
+  continue;
+
 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
 if (auto *IFunc = dyn_cast(ResolverConstant)) {
   ResolverConstant = IFunc->getResolver();
   if (FD->isTargetClonesMultiVersion() ||
   FD->isTargetVersionMultiVersion()) {
-const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
-llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
 std::string MangledName = getMangledNameImpl(
 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
-// In prior versions of Clang, the mangling for ifuncs incorrectly
-// included an .ifunc suffix. This alias is generated for backward
-// compatibility. It is deprecated, and may be removed in the future.
-auto *Alias = llvm::GlobalAlias::create(
-DeclTy, 0, getMultiversionLinkage(*this, GD),
-MangledName + ".ifunc", IFunc, &getModule());
-SetCommonAttributes(FD, Alias);
+if (!GetGlobalValue(MangledName + ".ifunc")) {
+  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
+  llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
+  // In prior versions of Clang, the mangling for ifuncs incorrectly
+  // included an .ifunc suffix. This alias is generated for backward
+  // compatibility. It is deprecated, and may be removed in the future.
+  auto *Alias = llvm::GlobalAlias::create(
+  DeclTy, 0, getMultiversionLinkage(*this, GD),
+

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

2024-03-20 Thread via cfe-commits

https://github.com/wheatman updated 
https://github.com/llvm/llvm-project/pull/78742

>From 06c87364d11d50284994a14a6dc9b3f510ca8330 Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Fri, 19 Jan 2024 11:13:33 -0500
Subject: [PATCH] [clang][Sema] Fix for overflow in enumerators(#24667)

Enums which do not have a specified type can only grow to bigger types
which contain more bits than the prior types.  This means that the
largest signed integer type cannot grow to the largest unsigned integer types.

In the Process also implements N3029 Improved Normal Enumerations and N3030
Enhancements to Enumerations which brings C enums more inline with C++
enums.

Fixes #24667
---
 clang/docs/ReleaseNotes.rst |   8 +++
 clang/lib/Sema/SemaDecl.cpp |  88 ++--
 clang/test/C/C2x/n3029.c|  81 ++
 clang/test/C/C2x/n3030.c| 129 
 clang/test/Sema/enum.c  |  43 ++--
 clang/test/SemaCXX/enum.cpp |   2 +
 6 files changed, 327 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/C/C2x/n3029.c
 create mode 100644 clang/test/C/C2x/n3030.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a74c070ff9ffe..9ae53d3a400ad5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -159,6 +159,12 @@ C23 Feature Support
   ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
   macros typically exposed from , such as ``PRIb8``.
   (`#81896: `_).
+- Enumerations should allow values greater than ``INT_MAX`` and smaller than
+  ``INT_MIN``, in order to provide a value-preserved set of integer constants. 
`N3029 Improved Normal Enumerations 
`_
+
+- Enumerations should have the ability to specify the underlying type to aid
+  in portability and usability across platforms, across ABIs, and across
+  languages (for serialization and similar purposes). `N3030 Enhancements to 
Enumerations `_
 
 - Clang now supports `N3018 The constexpr specifier for object definitions`
   `_.
@@ -300,6 +306,8 @@ Bug Fixes in This Version
 
 - Fixes an assertion failure on invalid code when trying to define member
   functions in lambdas.
+- Fixes a miscompilation when an enum has a specified value such that the 
automatic
+  increment overflows a ``signed long``. Fixes #GH24667.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..e6246605e1f0f4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19881,6 +19881,18 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // - If an initializer is specified for an enumerator, the
   //   initializing value has the same type as the expression.
   EltTy = Val->getType();
+} else if (getLangOpts().C23) {
+  // C23 6.7.2.2p11 b4
+  // int, if given explicitly with = and the value of the
+  // integer constant expression is representable by an int
+  //
+  // C23 6.7.2.2p11 b5
+  // the type of the integer constant expression, if given
+  // explicitly with = and if the value of the integer
+  // constant expression is not representable by int;
+  if (isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
+Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
+  EltTy = Val->getType();
 } else {
   // C99 6.7.2.2p2:
   //   The expression that defines the value of an enumeration constant
@@ -19890,8 +19902,8 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // Complain if the value is not representable in an int.
   if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
 Diag(IdLoc, diag::ext_enum_value_not_int)
-  << toString(EnumVal, 10) << Val->getSourceRange()
-  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
+<< toString(EnumVal, 10) << Val->getSourceRange()
+<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());
   else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
 // Force the type of the expression to 'int'.
 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
@@ -19939,20 +19951,28 @@ 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()) {

[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-20 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/85921

>From 707adafab92900392ed5aabffa678afe9b4903d7 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 20 Mar 2024 19:36:50 +0800
Subject: [PATCH] [clang][AST][NFC] Add '[[fallthrough]];' to cases fall
 through

---
 clang/lib/CodeGen/CGStmt.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8898e3f22a7df6..7bec3d227f4cac 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -160,7 +160,8 @@ void CodeGenFunction::EmitStmt(const Stmt *S, 
ArrayRef Attrs) {
   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast(*S));  
break;
 
   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast(*S));  
break;
-  case Stmt::GCCAsmStmtClass:  // Intentional fall-through.
+  case Stmt::GCCAsmStmtClass:
+[[fallthrough]];
   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast(*S));
break;
   case Stmt::CoroutineBodyStmtClass:
 EmitCoroutineBody(cast(*S));

___
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-03-20 Thread via cfe-commits

https://github.com/wheatman updated 
https://github.com/llvm/llvm-project/pull/78742

>From 23b742e4ee96412dca667da94ad166d4d36b73f9 Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Fri, 19 Jan 2024 11:13:33 -0500
Subject: [PATCH] [clang][Sema] Fix for overflow in enumerators(#24667)

Enums which do not have a specified type can only grow to bigger types
which contain more bits than the prior types.  This means that the
largest signed integer type cannot grow to the largest unsigned integer types.

In the Process also implements N3029 Improved Normal Enumerations and N3030
Enhancements to Enumerations which brings C enums more inline with C++
enums.

Fixes #24667
---
 clang/docs/ReleaseNotes.rst |   8 +++
 clang/lib/Sema/SemaDecl.cpp |  90 +++--
 clang/test/C/C2x/n3029.c|  81 ++
 clang/test/C/C2x/n3030.c| 129 
 clang/test/Sema/enum.c  |  43 ++--
 clang/test/SemaCXX/enum.cpp |   2 +
 6 files changed, 328 insertions(+), 25 deletions(-)
 create mode 100644 clang/test/C/C2x/n3029.c
 create mode 100644 clang/test/C/C2x/n3030.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a74c070ff9ffe..9ae53d3a400ad5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -159,6 +159,12 @@ C23 Feature Support
   ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
   macros typically exposed from , such as ``PRIb8``.
   (`#81896: `_).
+- Enumerations should allow values greater than ``INT_MAX`` and smaller than
+  ``INT_MIN``, in order to provide a value-preserved set of integer constants. 
`N3029 Improved Normal Enumerations 
`_
+
+- Enumerations should have the ability to specify the underlying type to aid
+  in portability and usability across platforms, across ABIs, and across
+  languages (for serialization and similar purposes). `N3030 Enhancements to 
Enumerations `_
 
 - Clang now supports `N3018 The constexpr specifier for object definitions`
   `_.
@@ -300,6 +306,8 @@ Bug Fixes in This Version
 
 - Fixes an assertion failure on invalid code when trying to define member
   functions in lambdas.
+- Fixes a miscompilation when an enum has a specified value such that the 
automatic
+  increment overflows a ``signed long``. Fixes #GH24667.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..de672237e676e0 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19881,6 +19881,18 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // - If an initializer is specified for an enumerator, the
   //   initializing value has the same type as the expression.
   EltTy = Val->getType();
+} else if (getLangOpts().C23) {
+  // C23 6.7.2.2p11 b4
+  // int, if given explicitly with = and the value of the
+  // integer constant expression is representable by an int
+  //
+  // C23 6.7.2.2p11 b5
+  // the type of the integer constant expression, if given
+  // explicitly with = and if the value of the integer
+  // constant expression is not representable by int;
+  if (isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
+Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
+  EltTy = Val->getType();
 } else {
   // C99 6.7.2.2p2:
   //   The expression that defines the value of an enumeration constant
@@ -19890,8 +19902,8 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // Complain if the value is not representable in an int.
   if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
 Diag(IdLoc, diag::ext_enum_value_not_int)
-  << toString(EnumVal, 10) << Val->getSourceRange()
-  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
+<< toString(EnumVal, 10) << Val->getSourceRange()
+<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());
   else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
 // Force the type of the expression to 'int'.
 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
@@ -19939,20 +19951,28 @@ 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()) {
   

[clang] 357f00d - [HIP] Correctly omit bundling with the new driver (#85842)

2024-03-20 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-03-20T07:15:49-05:00
New Revision: 357f00dddbe069f75e126188e35cb20edef32a5f

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

LOG: [HIP] Correctly omit bundling with the new driver (#85842)

Summary:
The HIP phases do not emit the offload bundler output when we do not
invoke the final linker phase in device only mode. Check this propery.

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/hip-phases.hip

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1daf588142b3b4..767c1cd47e8cd9 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4645,13 +4645,17 @@ Action *Driver::BuildOffloadingActions(Compilation &C,
 }
   }
 
+  // HIP code in non-RDC mode will bundle the output if it invoked the linker.
+  bool ShouldBundleHIP =
+  C.isOffloadingHostKind(Action::OFK_HIP) &&
+  Args.hasFlag(options::OPT_gpu_bundle_output,
+   options::OPT_no_gpu_bundle_output, true) &&
+  !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) &&
+  !llvm::any_of(OffloadActions,
+[](Action *A) { return A->getType() != types::TY_Image; });
+
   // All kinds exit now in device-only mode except for non-RDC mode HIP.
-  if (offloadDeviceOnly() &&
-  (getFinalPhase(Args) == phases::Preprocess ||
-   !C.isOffloadingHostKind(Action::OFK_HIP) ||
-   !Args.hasFlag(options::OPT_gpu_bundle_output,
- options::OPT_no_gpu_bundle_output, true) ||
-   Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)))
+  if (offloadDeviceOnly() && !ShouldBundleHIP)
 return C.MakeAction(DDeps, types::TY_Nothing);
 
   if (OffloadActions.empty())

diff  --git a/clang/test/Driver/hip-phases.hip 
b/clang/test/Driver/hip-phases.hip
index ca63d4304d3959..180ef43022f818 100644
--- a/clang/test/Driver/hip-phases.hip
+++ b/clang/test/Driver/hip-phases.hip
@@ -648,3 +648,15 @@
 // LTO-NEXT: 14: offload, "host-hip (x86_64-unknown-linux-gnu)" {2}, 
"device-hip (x86_64-unknown-linux-gnu)" {13}, ir
 // LTO-NEXT: 15: backend, {14}, assembler, (host-hip)
 // LTO-NEXT: 16: assembler, {15}, object, (host-hip)
+
+//
+// Test the new driver when not bundling
+//
+// RUN: %clang -### --target=x86_64-linux-gnu --offload-new-driver 
-ccc-print-phases \
+// RUN:--offload-device-only --offload-arch=gfx90a -emit-llvm -c %s 
2>&1 \
+// RUN: | FileCheck -check-prefix=DEVICE-ONLY %s
+//  DEVICE-ONLY: 0: input, "[[INPUT:.+]]", hip, (device-hip, gfx90a)
+// DEVICE-ONLY-NEXT: 1: preprocessor, {0}, hip-cpp-output, (device-hip, gfx90a)
+// DEVICE-ONLY-NEXT: 2: compiler, {1}, ir, (device-hip, gfx90a)
+// DEVICE-ONLY-NEXT: 3: backend, {2}, ir, (device-hip, gfx90a)
+// DEVICE-ONLY-NEXT: 4: offload, "device-hip (amdgcn-amd-amdhsa:gfx90a)" {3}, 
none



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


[clang] [HIP] Correctly omit bundling with the new driver (PR #85842)

2024-03-20 Thread Joseph Huber via cfe-commits

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-20 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

That didn't seem to help (I applied only the CMake changes from the linked PR 
however). Here's the output I get when calling `dump()` on the 
`ExecutionSession` which is failing:

```
JIT session error: Symbols not found: [ ??3@YAXPEAX_K@Z ]
JITDylib "" (ES: 0x02ae9a538360, State = Open)
Link order: [ ("", MatchAllSymbols) ]
Symbol table:
"??2@YAPEAX_K@Z":   [Data] Never-Searched (Materializer 
0x2ae9a6f6600, )
"??2@YAPEAX_KPEAXU__clang_Interpreter_NewTag@@@Z":   [Data] 
Never-Searched (Materializer 0x2ae9a6f6600, )
"?__clang_Interpreter_SetValueNoAlloc@@YAXPEAX00N@Z": 0x7ff6adef44a3 [Data] 
Ready
"?__clang_Interpreter_SetValueNoAlloc@@YAXPEAX00_K@Z": 0x7ff6ade5188e 
[Data] Ready
"?__clang_Interpreter_SetValueWithAlloc@@YAPEAXPEAX00@Z":   
[Data] Never-Searched (Materializer 0x2ae9a6f6600, )
JITDylib "" (ES: 0x02ae9a538360, State = Open)
Link order: [ ("", MatchAllSymbols), ("", 
MatchExportedSymbolsOnly) ]
Symbol table:
"__cxa_atexit":   [Callable] Never-Searched (Materializer 
0x2ae99ed48b0, __standard_lib)
"__dso_handle":   [Data] Never-Searched (Materializer 
0x2ae99ed43e0, __standard_lib)
"__lljit.atexit_helper":   [Data][Hidden] Never-Searched 
(Materializer 0x2ae9a52c740, )
"__lljit.cxa_atexit_helper":   [Data][Hidden] Never-Searched 
(Materializer 0x2ae9a52d4c0, )
"__lljit.platform_support_instance":   [Data] Never-Searched 
(Materializer 0x2ae9a52d4c0, )
"__lljit.run_atexits_helper":   [Data][Hidden] Never-Searched 
(Materializer 0x2ae9a52c740, )
"__lljit_run_atexits":   [Callable][Hidden] Never-Searched 
(Materializer 0x2ae99ed43e0, __standard_lib)
"atexit":   [Callable][Hidden] Never-Searched (Materializer 
0x2ae99ed43e0, __standard_lib)
JITDylib "main" (ES: 0x02ae9a538360, State = Open)
Link order: [ ("main", MatchAllSymbols), ("", 
MatchExportedSymbolsOnly), ("", MatchExportedSymbolsOnly) ]
Symbol table:
"$.incr_module_29.__inits.0":   [Data][Hidden] Ready
"$.incr_module_31.__inits.0":   [Data][Hidden] Ready
"$.incr_module_33.__inits.0":   [*ERROR*][Data][Hidden] 
Materializing
"??0S@@QEAA@XZ": 0x2ae99e00040 [*ERROR*][Callable][Weak] Resolved
"??1S@@QEAA@XZ": 0x2ae99e0 [*ERROR*][Callable][Weak] Resolved
"?x@@3HA": 0x2ae99db [Data] Ready
"?y@@3NA": 0x2ae99de [Data] Ready
"__dso_handle":   [Data] Never-Searched (Materializer 
0x2ae99ed4ac0, __standard_lib)
"__lljit.atexit_helper":   [Data][Hidden] Never-Searched 
(Materializer 0x2ae9a52d9d0, )
"__lljit.run_atexits_helper":   [Data][Hidden] Never-Searched 
(Materializer 0x2ae9a52d9d0, )
"__lljit_run_atexits":   [Callable][Hidden] Never-Searched 
(Materializer 0x2ae99ed4ac0, __standard_lib)
"__orc_init_func.incr_module_29": 0x2ae99d90060 [Callable][Hidden] Ready
"__orc_init_func.incr_module_31": 0x2ae99dc0060 [Callable][Hidden] Ready
"__orc_init_func.incr_module_33": 0x2ae99e00100 [*ERROR*][Callable][Hidden] 
Resolved
"atexit":   [Callable][Hidden] Never-Searched (Materializer 
0x2ae99ed4ac0, __standard_lib)
```

`$.incr_module_33.__inits.0` is the `MaterializationResponsibility` 
`InitSymbol` that failed.

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


[clang] 679e594 - [clang] Add `__has_extension(swiftcc)` support (#85347)

2024-03-20 Thread via cfe-commits

Author: Yuta Saito
Date: 2024-03-20T21:18:57+09:00
New Revision: 679e594d9d400ab688f6cc47b3ca26fe69265cae

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

LOG: [clang] Add `__has_extension(swiftcc)` support (#85347)

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/Features.def
clang/test/Sema/swift-call-conv.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0ce3cbe3266efd..91048daf8f5b75 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -210,6 +210,13 @@ Attribute Changes in Clang
   and each must be a positive integer when provided. The parameter ``x`` is 
required, while ``y`` and
   ``z`` are optional with default value of 1.
 
+- The ``swiftasynccc`` attribute is now considered to be a Clang extension
+  rather than a language standard feature. Please use
+  ``__has_extension(swiftasynccc)`` to check the availability of this attribute
+  for the target platform instead of ``__has_feature(swiftasynccc)``. Also,
+  added a new extension query ``__has_extension(swiftcc)`` corresponding to the
+  ``__attribute__((swiftcc))`` attribute.
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index d61f96ade557d5..9de14f608fd114 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5137,10 +5137,11 @@ that does not. A single parameter may not have multiple 
ABI treatment
 attributes.
 
 Support for this feature is target-dependent, although it should be
-supported on every target that Swift supports. Query for this support
-with ``__has_attribute(swiftcall)``. This implies support for the
-``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
-attributes.
+supported on every target that Swift supports. Query for this attribute
+with ``__has_attribute(swiftcall)``. Query if the target supports the
+calling convention with ``__has_extension(swiftcc)``. This implies
+support for the ``swift_context``, ``swift_error_result``, and
+``swift_indirect_result`` attributes.
   }];
 }
 
@@ -5187,6 +5188,10 @@ the following:
   semantically be performed after a guaranteed tail call, such as the
   non-trivial destruction of a local variable or temporary,
   then the program is ill-formed.
+
+Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
+the target supports the calling convention with
+``__has_extension(swiftasynccc)``.
   }];
 }
 

diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index eeed5f4751f2f4..726ead4b5ab5ab 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -102,7 +102,10 @@ FEATURE(thread_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
 FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
-FEATURE(swiftasynccc,
+EXTENSION(swiftcc,
+  PP.getTargetInfo().checkCallingConvention(CC_Swift) ==
+  clang::TargetInfo::CCCR_OK)
+EXTENSION(swiftasynccc,
   PP.getTargetInfo().checkCallingConvention(CC_SwiftAsync) ==
   clang::TargetInfo::CCCR_OK)
 FEATURE(pragma_stdc_cx_limited_range, true)

diff  --git a/clang/test/Sema/swift-call-conv.c 
b/clang/test/Sema/swift-call-conv.c
index 755c18f5183f85..2c9be840558481 100644
--- a/clang/test/Sema/swift-call-conv.c
+++ b/clang/test/Sema/swift-call-conv.c
@@ -1,7 +1,19 @@
 // RUN: %clang_cc1 -triple aarch64-unknown-windows-msvc -fsyntax-only %s 
-verify
 // RUN: %clang_cc1 -triple thumbv7-unknown-windows-msvc -fsyntax-only %s 
-verify
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -fsyntax-only %s -verify
+// RISC-V does not support swiftcall
+// RUN: %clang_cc1 -triple riscv32-unknown-elf -fsyntax-only %s -verify
 
+#if __has_extension(swiftcc)
 // expected-no-diagnostics
-
+#else
+// expected-warning@+2 {{'__swiftcall__' calling convention is not supported 
for this target}}
+#endif
 void __attribute__((__swiftcall__)) f(void) {}
+
+#if __has_extension(swiftasynccc)
+// expected-no-diagnostics
+#else
+// expected-warning@+2 {{'__swiftasynccall__' calling convention is not 
supported for this target}}
+#endif
+void __attribute__((__swiftasynccall__)) g(void) {}



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


[clang] [clang] Add `__has_extension(swiftcc)` support (PR #85347)

2024-03-20 Thread Yuta Saito via cfe-commits

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 4e466541a5ccf22d6fef08c71077e1f95ed10616 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/6] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 4e466541a5ccf22d6fef08c71077e1f95ed10616 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/7] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-20 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

Did you explicitly list ??3@YAXPEAX_K@Z as it was not part of that code?

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

https://github.com/sopyb updated https://github.com/llvm/llvm-project/pull/85572

>From 17d6ad65216237f9a325d9b608c1372cbbf83ff0 Mon Sep 17 00:00:00 2001
From: sopy 
Date: Sun, 17 Mar 2024 17:30:27 +0200
Subject: [PATCH 1/3] [clang-tidy] add check to suggest replacement of nested
 std::min or std::max with initializer lists

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../MinMaxUseInitializerListCheck.cpp | 138 ++
 .../modernize/MinMaxUseInitializerListCheck.h |  58 
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 6 files changed, 207 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.h

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6852db6c2ee311..8005d6e91c060c 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MinMaxUseInitializerListCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
new file mode 100644
index 00..b7dc3ff436f6e3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MinMaxUseInitializerListCheck.cpp
@@ -0,0 +1,138 @@
+//===--- MinMaxUseInitializerListCheck.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 "MinMaxUseInitializerListCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfContained()) {}
+
+void MinMaxUseInitializerListCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::max"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::max")))
+  .bind("maxCall"),
+  this);
+
+  Finder->addMatcher(
+  callExpr(
+  callee(functionDecl(hasName("::std::min"))),
+  
hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"),
+  unless(
+  
hasParent(callExpr(callee(functionDecl(hasName("::std::min")))
+  .bind("minCall"),
+  this);
+}
+
+void MinMaxUseInitializerListCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  Inserter.registerPreprocessor(PP);
+}
+
+void MinMaxUseInitializerListCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *MaxCall = Result.Nodes.getNodeAs("maxCall");
+  const auto *MinCall = Result.Nodes.getNodeAs("minCall");
+
+  const CallExpr *TopCall = MaxCall ? MaxCall : MinCall;
+  if (!TopCall) {
+return;
+  }
+  const QualType ResultType =
+  TopCall->getDirectCallee()->getReturnType().getNonReferenceType();
+
+  const Expr *FirstArg = nullptr;
+  const Expr *LastArg = nullptr;
+  std::vector Args;
+  findArgs(TopCall, &FirstArg, &LastArg, Args);
+
+  if (!FirstArg || !LastArg || Args.size() <= 2) {
+return;
+  }
+
+  std::string ReplacementText = "{";
+  for (const Expr *Arg : Args) {
+QualType ArgType = Arg->getType();
+bool CastNeeded =
+ArgType.getCanonicalType() != ResultType.getCanonicalType();
+
+if (CastNeeded)
+  ReplacementText += "static_cast<" + ResultType.getAsString() + ">(";
+
+ReplacementText += Lexer::getSourceText(
+CharSourceRange::getTokenRange(Arg->getSourceRange()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+if (CastNeeded)
+  ReplacementText += ")";
+ReplacementText += ", ";
+ 

[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits

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

LGTM! I'll fix up the nit and land on your behalf; thank you for the 
improvement!

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits


@@ -164,6 +164,8 @@ Deprecated Compiler Flags
 Modified Compiler Flags
 ---
 
+* ``-Wextra`` group flag now contains an additional flag i.e, 
``-Wcast-function-type``.

AaronBallman wrote:

```suggestion
- Added ``-Wcast-function-type`` as a warning enabled by ``-Wextra``. #GH76872
```

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman updated 
https://github.com/llvm/llvm-project/pull/77178

>From d147292312ea05eb6b4a28940faffe54093c900e Mon Sep 17 00:00:00 2001
From: Abhin Parekadan Jose 
Date: Sat, 6 Jan 2024 05:09:36 +0100
Subject: [PATCH 1/9] [clang] move -Wcast-function-type under -Wextra

---
 clang/include/clang/Basic/DiagnosticGroups.td |  1 +
 .../Sema/warn-cast-function-type-strict.c |  2 +-
 clang/test/Sema/warn-cast-function-type.c |  1 +
 .../warn-extra-cast-function-type-strict.c| 42 +++
 .../warn-cast-function-type-strict.cpp|  1 +
 .../test/SemaCXX/warn-cast-function-type.cpp  |  1 +
 6 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/warn-extra-cast-function-type-strict.c

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 6765721ae7002c..d3e57de8ac7a58 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1026,6 +1026,7 @@ def Extra : DiagGroup<"extra", [
 EmptyInitStatement,
 StringConcatation,
 FUseLdPath,
+CastFunctionType,
   ]>;
 
 def Most : DiagGroup<"most", [
diff --git a/clang/test/Sema/warn-cast-function-type-strict.c 
b/clang/test/Sema/warn-cast-function-type-strict.c
index 5233680796e972..68b49bb0d05d06 100644
--- a/clang/test/Sema/warn-cast-function-type-strict.c
+++ b/clang/test/Sema/warn-cast-function-type-strict.c
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type -verify
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type-strict -verify
-
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -Wno-ignored-qualifiers -verify
 
 int t(int array[static 12]);
 int u(int i);
diff --git a/clang/test/Sema/warn-cast-function-type.c 
b/clang/test/Sema/warn-cast-function-type.c
index d7ddcdb73725c0..09d169026b1c86 100644
--- a/clang/test/Sema/warn-cast-function-type.c
+++ b/clang/test/Sema/warn-cast-function-type.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type 
-Wno-cast-function-type-strict -verify
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -Wno-cast-function-type-strict 
-verify
 
 int x(long);
 
diff --git a/clang/test/Sema/warn-extra-cast-function-type-strict.c 
b/clang/test/Sema/warn-extra-cast-function-type-strict.c
new file mode 100644
index 00..ef8853616ba832
--- /dev/null
+++ b/clang/test/Sema/warn-extra-cast-function-type-strict.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -verify
+
+
+int t(int array[static 12]);
+int u(int i);
+const int v(int i); /* expected-warning {{'const' type qualifier on return 
type has no effec}} */
+int x(long);
+
+typedef int (f1)(long);
+typedef int (f2)(void*);
+typedef int (f3)();
+typedef void (f4)();
+typedef void (f5)(void);
+typedef int (f6)(long, int);
+typedef int (f7)(long,...);
+typedef int (f8)(int *);
+typedef int (f9)(const int);
+typedef int (f10)(int);
+
+f1 *a;
+f2 *b;
+f3 *c;
+f4 *d;
+f5 *e;
+f6 *f;
+f7 *g;
+f8 *h;
+f9 *i;
+f10 *j;
+
+void foo(void) {
+  a = (f1 *)x;
+  b = (f2 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f2 *' (aka 
'int (*)(void *)') converts to incompatible function type}} */
+  c = (f3 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f3 *' (aka 
'int (*)()') converts to incompatible function type}} */
+  d = (f4 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f4 *' (aka 
'void (*)()') converts to incompatible function type}} */
+  e = (f5 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f5 *' (aka 
'void (*)(void)') converts to incompatible function type}} */
+  f = (f6 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f6 *' (aka 
'int (*)(long, int)') converts to incompatible function type}} */
+  g = (f7 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f7 *' (aka 
'int (*)(long, ...)') converts to incompatible function type}} */
+  h = (f8 *)t;
+  i = (f9 *)u;
+  j = (f10 *)v; /* expected-warning {{cast from 'const int (*)(int)' to 'f10 
*' (aka 'int (*)(int)') converts to incompatible function type}} */
+}
diff --git a/clang/test/SemaCXX/warn-cast-function-type-strict.cpp 
b/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
index f7ee55f84ac280..b3164afde5a0ca 100644
--- a/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
+++ b/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-function-type -verify
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-function-type-strict 
-verify
+// RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wextra -verify
 
 int x(long);
 
diff --git a/clang/test/SemaCXX/warn-cast-function-type.cpp 
b/clang/test/SemaCXX/warn-cast-function-type.cpp
index c613aaea1e33f2..db2ee030fcbfc9 100644
--- a/clang/test/SemaCXX/warn-cast-function-type.cpp
+++ b/clang/test/SemaCXX/warn-cast-function-type.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-fun

[clang] 1de7e6c - [clang] move -Wcast-function-type under -Wextra (#77178)

2024-03-20 Thread via cfe-commits

Author: Abhin P Jose
Date: 2024-03-20T08:34:46-04:00
New Revision: 1de7e6c8cba27296f3fc16d107822ea0ee856759

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

LOG: [clang] move -Wcast-function-type under -Wextra (#77178)

The -Wcast-fuction-type-strict has been moved under dignstic group
-Wextra.
Edited the test cases for -Wcast-fuction-type-strict and
-Wcast-fuction-type in Sema an SemaCXX.

Added a new test case which include a functionality that was already in
the -Wextra group, i.e -Wignored-qualifiers with
-Wcast-fuction-type-strict.

Fixes: #76872

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/test/Sema/warn-cast-function-type-strict.c
clang/test/Sema/warn-cast-function-type.c
clang/test/SemaCXX/warn-cast-function-type-strict.cpp
clang/test/SemaCXX/warn-cast-function-type.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 91048daf8f5b75..a10e942615ffd2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -193,6 +193,8 @@ Modified Compiler Flags
   ``-Wreturn-type``, and moved some of the diagnostics previously controlled by
   ``-Wreturn-type`` under this new flag. Fixes #GH72116.
 
+- Added ``-Wcast-function-type`` as a warning enabled by ``-Wextra``. #GH76872
+
 Removed Compiler Flags
 -
 

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index dee555f783cc45..bf03d4e8f67ee1 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1038,6 +1038,7 @@ def Extra : DiagGroup<"extra", [
 EmptyInitStatement,
 StringConcatation,
 FUseLdPath,
+CastFunctionType,
   ]>;
 
 def Most : DiagGroup<"most", [

diff  --git a/clang/test/Sema/warn-cast-function-type-strict.c 
b/clang/test/Sema/warn-cast-function-type-strict.c
index 5233680796e972..8c88f275d2b336 100644
--- a/clang/test/Sema/warn-cast-function-type-strict.c
+++ b/clang/test/Sema/warn-cast-function-type-strict.c
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type -verify
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type-strict -verify
-
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -Wno-ignored-qualifiers -verify
 
 int t(int array[static 12]);
 int u(int i);
@@ -39,5 +39,6 @@ void foo(void) {
   g = (f7 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f7 *' (aka 
'int (*)(long, ...)') converts to incompatible function type}} */
   h = (f8 *)t;
   i = (f9 *)u;
+  // FIXME: return type qualifier should not be included in the function type 
. Warning should be absent after this issue is fixed. 
https://github.com/llvm/llvm-project/issues/39494 .
   j = (f10 *)v; /* expected-warning {{cast from 'const int (*)(int)' to 'f10 
*' (aka 'int (*)(int)') converts to incompatible function type}} */
 }

diff  --git a/clang/test/Sema/warn-cast-function-type.c 
b/clang/test/Sema/warn-cast-function-type.c
index d7ddcdb73725c0..09d169026b1c86 100644
--- a/clang/test/Sema/warn-cast-function-type.c
+++ b/clang/test/Sema/warn-cast-function-type.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type 
-Wno-cast-function-type-strict -verify
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -Wno-cast-function-type-strict 
-verify
 
 int x(long);
 

diff  --git a/clang/test/SemaCXX/warn-cast-function-type-strict.cpp 
b/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
index f7ee55f84ac280..b3164afde5a0ca 100644
--- a/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
+++ b/clang/test/SemaCXX/warn-cast-function-type-strict.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-function-type -verify
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-function-type-strict 
-verify
+// RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wextra -verify
 
 int x(long);
 

diff  --git a/clang/test/SemaCXX/warn-cast-function-type.cpp 
b/clang/test/SemaCXX/warn-cast-function-type.cpp
index c613aaea1e33f2..db2ee030fcbfc9 100644
--- a/clang/test/SemaCXX/warn-cast-function-type.cpp
+++ b/clang/test/SemaCXX/warn-cast-function-type.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wcast-function-type 
-Wno-cast-function-type-strict -verify
+// RUN: %clang_cc1 %s -fblocks -fsyntax-only -Wextra 
-Wno-cast-function-type-strict -verify
 
 int x(long);
 



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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-20 Thread Aaron Ballman via cfe-commits

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-03-20 Thread via cfe-commits

sopyb wrote:

It should be ready for review now. Sorry for requesting while my code was 
broken. I modified a line and committed it without checking if the code still 
works.

So there aren't a bunch of "Apply Clang format fixes" I also squished those 
into a single commit.

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-20 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> Did you explicitly list ??3@YAXPEAX_K@Z as it was not part of that code?

It is part of that code: 
https://github.com/llvm/llvm-project/pull/84769/files#diff-d7f5dca2bd540f1b18ba90a66497b6b12e40fd07058b70f0fdec638c8e97406eR35


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


[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-20 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> bin/opt: ../../llvm-opt-benchmark/bench/icu/original/servlkf.ll:776:98: 
> error: expected ')' in constantexpr
  store ptr getelementptr inbounds ({ [11 x ptr] }, ptr 
@_ZTVN6icu_7516LocaleKeyFactoryE, i32 0, inrange i32 0, i32 2), ptr %this1, 
align 8

@nikic Do we need an auto-upgrader?

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


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits

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

>From fc8c1a24f09c8860269fbdcfb0b285ffd19f427c Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 15 Mar 2024 00:48:08 +0800
Subject: [PATCH 1/8] [libc++] Implement LWG3528 (`make_from_tuple` can perform
 (the equivalent of) a C-style cast)

Signed-off-by: yronglin 
---
 libcxx/docs/Status/Cxx23Issues.csv|  2 +-
 libcxx/include/tuple  | 12 ++-
 .../tuple.apply/make_from_tuple.verify.cpp| 74 +++
 3 files changed, 85 insertions(+), 3 deletions(-)
 create mode 100644 
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp

diff --git a/libcxx/docs/Status/Cxx23Issues.csv 
b/libcxx/docs/Status/Cxx23Issues.csv
index e00345533b865d..0fd58649b0cf64 100644
--- a/libcxx/docs/Status/Cxx23Issues.csv
+++ b/libcxx/docs/Status/Cxx23Issues.csv
@@ -77,7 +77,7 @@
 `3523 `__,"``iota_view::sentinel`` is not always 
``iota_view``'s sentinel","June 2021","","","|ranges|"
 `3526 `__,"Return types of 
``uses_allocator_construction_args`` unspecified","June 2021","",""
 `3527 `__,"``uses_allocator_construction_args`` 
handles rvalue pairs of rvalue references incorrectly","June 2021","",""
-`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","",""
+`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","|Complete|","19.0"
 `3529 `__,"``priority_queue(first, last)`` should 
construct ``c`` with ``(first, last)``","June 2021","|Complete|","14.0"
 `3530 `__,"``BUILTIN-PTR-MEOW`` should not opt the 
type out of syntactic checks","June 2021","",""
 `3532 `__,"``split_view::inner-iterator::operator++(int)`` should depend on ``Base``","June 
2021","","","|ranges|"
diff --git a/libcxx/include/tuple b/libcxx/include/tuple
index 8808db6739fb9b..1ef546c5b2153d 100644
--- a/libcxx/include/tuple
+++ b/libcxx/include/tuple
@@ -1423,8 +1423,16 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 typename 
__make_tuple_indices>>::type{}))
 
 template 
-inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
-_LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>) 
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+#if _LIBCPP_STD_VER >= 20
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>
+#endif
+{
+  static_assert(is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>, 
+"Cannot constructible target type from the fields of the 
argument tuple.");
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
 
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp make_from_tuple(_Tuple&& __t)
diff --git 
a/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
new file mode 100644
index 00..9bdca4dc7813cb
--- /dev/null
+++ 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
@@ -0,0 +1,74 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14
+
+// 
+
+// template  constexpr T make_from_tuple(Tuple&&);
+
+#include 
+
+int main() {
+  // clang-format off
+#if _LIBCPP_STD_VER <= 20
+  // reinterpret_cast
+  {
+struct B { int b; } b;
+std::tuple t{&b};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* {{static 
assertion failed {{.*}}Cannot constructible target type from the fields of the 
argument tuple.}}
+(void)a;
+  }
+
+  // const_cast
+  {
+const char *str = "Hello";
+std::tuple t{str};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+
+  // static_cast
+  {
+struct B {};
+struct C : public B {} c;
+B &br = c;
+std::tuple t{br};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+#else
+  // reinterpret_cast
+  {
+s

[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-20 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> This is a very niche feature, and I don't think trying to upgrade it is 
> worthwhile.

It exists in many real-world applications. If you are not willing to implement 
the upgrader, I will do this for the original IR files in my benchmark :)


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


[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-20 Thread Nikita Popov via cfe-commits

nikic wrote:

@dtcxzyw Auto-upgrade is only for bitcode files, we usually do not upgrade IR 
files. Can you regenerate the inputs with the new clang version?

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


[clang] [clang] CTAD: Track template template type parameters that referenced in (PR #85405)

2024-03-20 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

The change seems to be correct in the way code is written.

However, I wonder what's the connection between the crash and the function 
being changed? Is there a way to fail gracefully if there are more mistakes in 
this function for incorrect code (e.g. fail deduction instead of crashing)?

Is this also a correctness issue? Is it possible to come with an example where 
the correct code causes a crash? (I suspect there is, we should probably add it 
in as well as this is more severe than crashes on incorrect code).

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-20 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > Did you explicitly list ??3@YAXPEAX_K@Z as it was not part of that code?
> 
> It is part of that code: 
> https://github.com/llvm/llvm-project/pull/84769/files#diff-d7f5dca2bd540f1b18ba90a66497b6b12e40fd07058b70f0fdec638c8e97406eR35

@vgvassilev and I chatted off-list about this and we eventually got to the 
bottom of it. You need to add the CMake changes linked above into the 
CMakeLists.txt that's picked up for unit and lit tests. I think that means 
adding the changes to libclangInterpreter, but I got the unit tests working by 
adding the changes to `clang/unitests/Interpreter/CMakeLists.txt`. One thing to 
pay attention to is the target you're setting the properties for (e.g., you 
don't want to use `clang-repl` as the target because unit tests won't pick that 
up, I had to use `ClangReplInterpreterTests` to get the unit tests to pass).

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-20 Thread Michael Maitland via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

michaelmaitland wrote:

@4vtomat if the MCPU has a feature but the function explicitly disables it then 
I think we want the `-`

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-20 Thread Michael Maitland via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

michaelmaitland wrote:

> But we don't have the FunctionDecl info in the 
> RISCVTargetInfo::initFeatureMap call.

What about keeping this map in ASTContext instead?

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


[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)

2024-03-20 Thread Aaron Ballman via cfe-commits

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

I think the changes here make sense (keeping in mind what @efriedma-quic says 
about long-term goals vs 18.x practicality). Eli, @serge-sans-paille, are you 
okay with the changes as well? (Please don't land on my approval without 
waiting a bit for Eli and Serge.)

If so, I'd like to get this backported into 18.x as well because of the issues 
we're seeing in the wild. Any disagreement?

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


[clang] 3eb8063 - [CodeGen] Fix test on 32-bit targets (NFC)

2024-03-20 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2024-03-20T14:20:44+01:00
New Revision: 3eb806373e3164b242db65f8c900e4adb5a2eddf

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

LOG: [CodeGen] Fix test on 32-bit targets (NFC)

The range here will be different for 32-bit targets. Use a wildcard,
just like all te other target-sensitive parts in this test.

Added: 


Modified: 
clang/test/CodeGenCXX/copy-constructor-synthesis-2.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/copy-constructor-synthesis-2.cpp 
b/clang/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
index 4f96a3ae670774..ae0c3a26c597ea 100644
--- a/clang/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
+++ b/clang/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
@@ -24,4 +24,4 @@ struct A { virtual void a(); };
 A x(A& y) { return y; }
 
 // CHECK: define linkonce_odr {{.*}} @_ZN1AC1ERKS_(ptr {{.*}}%this, ptr 
noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) %0) unnamed_addr
-// CHECK: store ptr getelementptr inbounds inrange(-16, 8) ({ [3 x ptr] }, ptr 
@_ZTV1A, i32 0, i32 0, i32 2)
+// CHECK: store ptr getelementptr inbounds inrange(-{{[0-9]+}}, {{[0-9]+}}) ({ 
[3 x ptr] }, ptr @_ZTV1A, i32 0, i32 0, i32 2)



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


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits

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

>From fc8c1a24f09c8860269fbdcfb0b285ffd19f427c Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 15 Mar 2024 00:48:08 +0800
Subject: [PATCH 1/9] [libc++] Implement LWG3528 (`make_from_tuple` can perform
 (the equivalent of) a C-style cast)

Signed-off-by: yronglin 
---
 libcxx/docs/Status/Cxx23Issues.csv|  2 +-
 libcxx/include/tuple  | 12 ++-
 .../tuple.apply/make_from_tuple.verify.cpp| 74 +++
 3 files changed, 85 insertions(+), 3 deletions(-)
 create mode 100644 
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp

diff --git a/libcxx/docs/Status/Cxx23Issues.csv 
b/libcxx/docs/Status/Cxx23Issues.csv
index e00345533b865d..0fd58649b0cf64 100644
--- a/libcxx/docs/Status/Cxx23Issues.csv
+++ b/libcxx/docs/Status/Cxx23Issues.csv
@@ -77,7 +77,7 @@
 `3523 `__,"``iota_view::sentinel`` is not always 
``iota_view``'s sentinel","June 2021","","","|ranges|"
 `3526 `__,"Return types of 
``uses_allocator_construction_args`` unspecified","June 2021","",""
 `3527 `__,"``uses_allocator_construction_args`` 
handles rvalue pairs of rvalue references incorrectly","June 2021","",""
-`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","",""
+`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","|Complete|","19.0"
 `3529 `__,"``priority_queue(first, last)`` should 
construct ``c`` with ``(first, last)``","June 2021","|Complete|","14.0"
 `3530 `__,"``BUILTIN-PTR-MEOW`` should not opt the 
type out of syntactic checks","June 2021","",""
 `3532 `__,"``split_view::inner-iterator::operator++(int)`` should depend on ``Base``","June 
2021","","","|ranges|"
diff --git a/libcxx/include/tuple b/libcxx/include/tuple
index 8808db6739fb9b..1ef546c5b2153d 100644
--- a/libcxx/include/tuple
+++ b/libcxx/include/tuple
@@ -1423,8 +1423,16 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 typename 
__make_tuple_indices>>::type{}))
 
 template 
-inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
-_LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>) 
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+#if _LIBCPP_STD_VER >= 20
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>
+#endif
+{
+  static_assert(is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>, 
+"Cannot constructible target type from the fields of the 
argument tuple.");
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
 
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp make_from_tuple(_Tuple&& __t)
diff --git 
a/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
new file mode 100644
index 00..9bdca4dc7813cb
--- /dev/null
+++ 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
@@ -0,0 +1,74 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14
+
+// 
+
+// template  constexpr T make_from_tuple(Tuple&&);
+
+#include 
+
+int main() {
+  // clang-format off
+#if _LIBCPP_STD_VER <= 20
+  // reinterpret_cast
+  {
+struct B { int b; } b;
+std::tuple t{&b};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* {{static 
assertion failed {{.*}}Cannot constructible target type from the fields of the 
argument tuple.}}
+(void)a;
+  }
+
+  // const_cast
+  {
+const char *str = "Hello";
+std::tuple t{str};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+
+  // static_cast
+  {
+struct B {};
+struct C : public B {} c;
+B &br = c;
+std::tuple t{br};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+#else
+  // reinterpret_cast
+  {
+s

[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits


@@ -195,6 +195,34 @@ void test_noexcept() {
 }
 }
 
+namespace LWG3528 {
+template >

yronglin wrote:

done

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


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits


@@ -195,6 +195,34 @@ void test_noexcept() {
 }
 }
 
+namespace LWG3528 {
+template >
+struct can_make_from_tuple : std::false_type {};
+template 
+struct can_make_from_tuple<
+_Tp,
+_Tuple,
+std::void_t(
+std::declval<_Tuple>(),
+std::declval<
+typename std::__make_tuple_indices< 
std::tuple_size_v>>::type>()))>>
+: std::true_type {};
+
+struct A {
+  int a;
+};
+struct B : public A {};
+
+// reinterpret_cast
+static_assert(!can_make_from_tuple>::value);
+
+// const_cast
+static_assert(!can_make_from_tuple>::value);

yronglin wrote:

Sorry, I misunderstood before. Added more test now.

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


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits


@@ -195,6 +195,34 @@ void test_noexcept() {
 }
 }
 
+namespace LWG3528 {
+template >
+struct can_make_from_tuple : std::false_type {};
+template 
+struct can_make_from_tuple<
+_Tp,
+_Tuple,
+std::void_t(

yronglin wrote:

done

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


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-20 Thread via cfe-commits

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


  1   2   3   4   >