[clang] [clang][ASTImporter] fix variable inline of CXX17 (PR #87314)

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

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


[clang] [clang][ASTImporter] fix variable inline of CXX17 (PR #87314)

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

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

>From 1a1071845f2409dd07be454fb68ff42911fb62a2 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 2 Apr 2024 13:18:14 +0800
Subject: [PATCH] [clang][ASTImporter] fix variable inline of CXX17

---
 clang/lib/AST/ASTImporter.cpp   |  7 ++-
 clang/unittests/AST/ASTImporterTest.cpp | 28 +
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 94a47a8f619018..2b2c7c0491dfe5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4579,7 +4579,12 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 if (!RedeclOrErr)
   return RedeclOrErr.takeError();
   }
-
+  if (D->isInlineSpecified()) {
+ToVar->setInlineSpecified();
+  }
+  if (D->isInline()) {
+ToVar->setImplicitlyInline();
+  }
   return ToVar;
 }
 
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 35ab7e3b7fe314..d57736830f0223 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5317,6 +5317,34 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   EXPECT_FALSE(ToX);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateDeclInlineWithCXX17) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX17, "input1.cc");
+  Decl *FromTU2 = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+template  void get() { X; }
+  };
+  template  T qvariant_cast(const S ) { return v.get; }
+  )",
+  Lang_CXX17, "input2.cc");
+  auto *FromX = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToX = Import(FromX, Lang_CXX17);
+  EXPECT_TRUE(ToX);
+  auto *FromX2 = FirstDeclMatcher().match(
+  FromTU2, varTemplateDecl(hasName("X")));
+  auto *ToX2 = Import(FromX2, Lang_CXX17);
+  EXPECT_TRUE(ToX2);
+  EXPECT_TRUE(ToX == ToX2);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) {
   constexpr auto Code =
   R"(

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


[clang] [clang][ASTImporter] fix variable inline of CXX17 (PR #87314)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Fix crash int the testcase from 
https://github.com/llvm/llvm-project/issues/75114#issuecomment-1872595956
Forget to set inline of variable declaration would make 
`isThisDeclarationADefinition` get incorrect result and didn't get imported 
variable. This will lead to a new `VarTemplateDecl` being created and call 
`setDescribedVarTemplate` again which produce the crash.

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


2 Files Affected:

- (modified) clang/lib/AST/ASTImporter.cpp (+7-2) 
- (modified) clang/unittests/AST/ASTImporterTest.cpp (+28) 


``diff
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 94a47a8f619018..cfdb2cb5c778e3 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4579,7 +4579,12 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 if (!RedeclOrErr)
   return RedeclOrErr.takeError();
   }
-
+  if (D->isInlineSpecified()) {
+ToVar->setInlineSpecified();
+  }
+  if (D->isInline()) {
+ToVar->setImplicitlyInline();
+  }
   return ToVar;
 }
 
@@ -6410,7 +6415,7 @@ ExpectedDecl 
ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
 }
 ToVarTD->setPreviousDecl(Recent);
   }
-
+  // Importer.MapImported(D, ToVarTD);
   return ToVarTD;
 }
 
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 35ab7e3b7fe314..d57736830f0223 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5317,6 +5317,34 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   EXPECT_FALSE(ToX);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateDeclInlineWithCXX17) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX17, "input1.cc");
+  Decl *FromTU2 = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+template  void get() { X; }
+  };
+  template  T qvariant_cast(const S ) { return v.get; }
+  )",
+  Lang_CXX17, "input2.cc");
+  auto *FromX = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToX = Import(FromX, Lang_CXX17);
+  EXPECT_TRUE(ToX);
+  auto *FromX2 = FirstDeclMatcher().match(
+  FromTU2, varTemplateDecl(hasName("X")));
+  auto *ToX2 = Import(FromX2, Lang_CXX17);
+  EXPECT_TRUE(ToX2);
+  EXPECT_TRUE(ToX == ToX2);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) {
   constexpr auto Code =
   R"(

``




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


[clang] [clang][ASTImporter] fix variable inline of CXX17 (PR #87314)

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

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/87314

Fix crash int the testcase from 
https://github.com/llvm/llvm-project/issues/75114#issuecomment-1872595956
Forget to set inline of variable declaration would make 
`isThisDeclarationADefinition` get incorrect result and didn't get imported 
variable. This will lead to a new `VarTemplateDecl` being created and call 
`setDescribedVarTemplate` again which produce the crash.

>From 2f579346d6955e06d8e16bb29467ed5da332451d Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 2 Apr 2024 13:18:14 +0800
Subject: [PATCH] [clang][ASTImporter] fix variable inline of CXX17

---
 clang/lib/AST/ASTImporter.cpp   |  9 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 28 +
 2 files changed, 35 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 94a47a8f619018..cfdb2cb5c778e3 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4579,7 +4579,12 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 if (!RedeclOrErr)
   return RedeclOrErr.takeError();
   }
-
+  if (D->isInlineSpecified()) {
+ToVar->setInlineSpecified();
+  }
+  if (D->isInline()) {
+ToVar->setImplicitlyInline();
+  }
   return ToVar;
 }
 
@@ -6410,7 +6415,7 @@ ExpectedDecl 
ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
 }
 ToVarTD->setPreviousDecl(Recent);
   }
-
+  // Importer.MapImported(D, ToVarTD);
   return ToVarTD;
 }
 
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 35ab7e3b7fe314..d57736830f0223 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5317,6 +5317,34 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   EXPECT_FALSE(ToX);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateDeclInlineWithCXX17) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX17, "input1.cc");
+  Decl *FromTU2 = getTuDecl(
+  R"(
+  struct S {
+template  static constexpr bool X = true;
+template  void get() { X; }
+  };
+  template  T qvariant_cast(const S ) { return v.get; }
+  )",
+  Lang_CXX17, "input2.cc");
+  auto *FromX = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToX = Import(FromX, Lang_CXX17);
+  EXPECT_TRUE(ToX);
+  auto *FromX2 = FirstDeclMatcher().match(
+  FromTU2, varTemplateDecl(hasName("X")));
+  auto *ToX2 = Import(FromX2, Lang_CXX17);
+  EXPECT_TRUE(ToX2);
+  EXPECT_TRUE(ToX == ToX2);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) {
   constexpr auto Code =
   R"(

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


[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/86783

>From b886dcf2da25417d9f8cd75ff4aa58686e35139d Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 27 Mar 2024 17:11:04 +0800
Subject: [PATCH 1/4] [PowerPC] Implement 32-bit expansion for rldimi

rldimi is 64-bit instruction, due to backward compatibility, it needs to
be expanded into series of rlwimi in 32-bit environment. In the future,
we may improve bit permutation selector and remove such direct codegen.
---
 clang/lib/Sema/SemaChecking.cpp |   1 -
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 109 --
 llvm/test/CodeGen/PowerPC/rldimi.ll | 366 
 3 files changed, 454 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 11401b6f56c0ea..d2cbe5417d682d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5236,7 +5236,6 @@ static bool isPPC_64Builtin(unsigned BuiltinID) {
   case PPC::BI__builtin_ppc_fetch_and_andlp:
   case PPC::BI__builtin_ppc_fetch_and_orlp:
   case PPC::BI__builtin_ppc_fetch_and_swaplp:
-  case PPC::BI__builtin_ppc_rldimi:
 return true;
   }
   return false;
diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index 7436b202fba0d9..3281a0dfd08729 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -643,6 +643,7 @@ PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine 
,
   // We want to custom lower some of our intrinsics.
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
+  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
@@ -10757,6 +10758,88 @@ static bool getVectorCompareInfo(SDValue Intrin, int 
,
   return true;
 }
 
+static SDValue getRotateInsert32(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME) {
+  assert(SH < 32 && MB < 32 && ME < 32 &&
+ "Invalid argument for rotate insert!");
+  return SDValue(
+  DAG.getMachineNode(PPC::RLWIMI, Loc, MVT::i32,
+ {Dst, Src, DAG.getTargetConstant(SH, Loc, MVT::i32),
+  DAG.getTargetConstant(MB, Loc, MVT::i32),
+  DAG.getTargetConstant(ME, Loc, MVT::i32)}),
+  0);
+}
+
+static SDValue getRotateInsert64(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME, bool IsPPC64) {
+  assert(SH < 64 && MB < 64 && ME < 64 &&
+ "Invalid argument for rotate insert!");
+  if (IsPPC64) {
+// rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
+if (ME < 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH + 1, Loc, MVT::i32));
+} else if (ME > 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH - 63, Loc, MVT::i32));
+}
+return SDValue(DAG.getMachineNode(
+   PPC::RLDIMI, Loc, MVT::i64,
+   {Dst, Src, DAG.getTargetConstant(63 - ME, Loc, 
MVT::i32),
+DAG.getTargetConstant(MB, Loc, MVT::i32)}),
+   0);
+  }
+
+  // To implement rldimi(Dst, Src) on 32-bit target, four parts are needed. SH
+  // is adjusted to simplify cases. Invalid ranges will be skipped.
+  // - SrcHi inserted into DstHi with [0, 32-SH)
+  // - SrcLo inserted into DstHi with [32-SH, 32)
+  // - SrcHi inserted into DstLo with [32, 64-SH)
+  // - SrcLo inserted into DstLo with [64-SH, 64)
+  auto [SrcLo, SrcHi] = DAG.SplitScalar(Src, Loc, MVT::i32, MVT::i32);
+  auto [DstLo, DstHi] = DAG.SplitScalar(Dst, Loc, MVT::i32, MVT::i32);
+  if (SH >= 32) {
+SH -= 32;
+std::swap(SrcLo, SrcHi);
+  }
+  auto GetSubInsert = [, , SH](unsigned Left, unsigned Right,
+   SDValue Src, SDValue Dst, unsigned MB,
+   unsigned ME) {
+if (Left > Right)
+  return Dst;
+
+if (MB <= ME) {
+  if (MB <= Right && ME >= Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH,
+ std::max(MB, Left) % 32,
+ std::min(ME, Right) % 32);
+} else {
+  if (MB < Left || ME > Right)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, Left % 32, Right % 
32);
+
+  if (MB <= Right && ME < Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, MB % 32, 

[clang] [X86_32] Teach X86_32 va_arg to ignore empty structs. (PR #86075)

2024-04-01 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/86075

>From 355f540288d87ca35a8e5790e4eaff383d619201 Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Thu, 21 Mar 2024 11:23:56 +0800
Subject: [PATCH] [X86_32] Teach X86_32 va_arg to ignore empty structs.

Empty structs are ignored for parameter passing purposes, but va_arg was
incrementing the pointer anyway for that the size of empty struct in c++
is 1 byte, which could lead to va_list getting out of sync.
---
 clang/lib/CodeGen/Targets/X86.cpp  |  6 ++
 clang/test/CodeGenCXX/x86_32-vaarg.cpp | 20 
 2 files changed, 26 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/x86_32-vaarg.cpp

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 1146a851a7715d..c831777699f627 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1069,6 +1069,12 @@ Address X86_32ABIInfo::EmitVAArg(CodeGenFunction ,
 
   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
 
+  CCState State(*const_cast(CGF.CurFnInfo));
+  ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
+  // Empty records are ignored for parameter passing purposes.
+  if (AI.isIgnore())
+return CGF.CreateMemTemp(Ty);
+
   // x86-32 changes the alignment of certain arguments on the stack.
   //
   // Just messing with TypeInfo like this works because we never pass
diff --git a/clang/test/CodeGenCXX/x86_32-vaarg.cpp 
b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
new file mode 100644
index 00..23eac1164118c6
--- /dev/null
+++ b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
@@ -0,0 +1,20 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -x c -o - %s | FileCheck 
%s
+
+typedef struct {} empty;
+
+// CHECK-LABEL: @{{.*}}empty_record_test
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RESULT_PTR:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[LIST:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[TMP:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1
+// CHECK-NEXT:store ptr [[AGG_RESULT:%.*]], ptr [[RESULT_PTR]], align 4
+// CHECK-NEXT:store i32 [[Z:%.*]], ptr [[Z_ADDR]], align 4
+// CHECK-NEXT:call void @llvm.va_start(ptr [[LIST]])
+empty empty_record_test(int z, ...) {
+  __builtin_va_list list;
+  __builtin_va_start(list, z);
+  return __builtin_va_arg(list, empty);
+}

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


[clang] cppcheck: use move semantics for 'NodeKinds' and update possible callers to use it (PR #87273)

2024-04-01 Thread Amila Senadheera via cfe-commits

Amila-Rukshan wrote:

@firewave, Thank you for pointing it out! I blindly tried to fix it looking at 
the cppcheck output. 

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-04-01 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

This failure is caused by the patch
https://lab.llvm.org/buildbot/#/builders/239/builds/6363/steps/10/logs/stdio
cc @hctim 

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce bugs. (PR #87310)

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

efriedma-quic wrote:

We can't just skip compiling part of the code because it's infinite recursion.

It's not clear to me there's really a bug here to solve.  Maybe the compiler 
can detect simple cases of infinite recursion and print a warning.

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


[clang] cppcheck: use move semantics for 'NodeKinds' and update possible callers to use it (PR #87273)

2024-04-01 Thread Amila Senadheera via cfe-commits

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


[clang] Add support for builtin_verbose_trap (PR #79230)

2024-04-01 Thread Akira Hatanaka via cfe-commits


@@ -3424,6 +3445,26 @@ llvm::DIMacroFile 
*CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
   return DBuilder.createTempMacroFile(Parent, Line, FName);
 }
 
+llvm::DILocation *CGDebugInfo::CreateTrapFailureMessageFor(

ahatanak wrote:

@dwblaikie any comments?

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


[clang] cppcheck: pass NodeKinds by const reference (PR #87273)

2024-04-01 Thread Amila Senadheera via cfe-commits

https://github.com/Amila-Rukshan updated 
https://github.com/llvm/llvm-project/pull/87273

>From 4f8349936403d29ac14179fb7d9e1429a09914ff Mon Sep 17 00:00:00 2001
From: amila 
Date: Tue, 2 Apr 2024 00:15:59 +0530
Subject: [PATCH] use move semantics for NodeKinds and update possible callers
 to use it

Signed-off-by: amila 
---
 clang/lib/ASTMatchers/Dynamic/Marshallers.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index c76ddf17b719d4..0e640cbada7268 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -937,7 +937,7 @@ class MapAnyOfMatcherDescriptor : public MatcherDescriptor {
 public:
   MapAnyOfMatcherDescriptor(ASTNodeKind CladeNodeKind,
 std::vector NodeKinds)
-  : CladeNodeKind(CladeNodeKind), NodeKinds(NodeKinds) {}
+  : CladeNodeKind(CladeNodeKind), NodeKinds(std::move(NodeKinds)) {}
 
   VariantMatcher create(SourceRange NameRange, ArrayRef Args,
 Diagnostics *Error) const override {
@@ -1026,7 +1026,7 @@ class MapAnyOfBuilderDescriptor : public 
MatcherDescriptor {
 }
 
 return std::make_unique(CladeNodeKind,
-   NodeKinds);
+   std::move(NodeKinds));
   }
 
   bool isVariadic() const override { return true; }

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


[clang] [clang] Fix bitfield access unit for vbase corner case (PR #87238)

2024-04-01 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

This failure is caused by the patch 
https://lab.llvm.org/buildbot/#/builders/239/builds/6363/steps/10/logs/stdio

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


[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/86783

>From b886dcf2da25417d9f8cd75ff4aa58686e35139d Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 27 Mar 2024 17:11:04 +0800
Subject: [PATCH 1/3] [PowerPC] Implement 32-bit expansion for rldimi

rldimi is 64-bit instruction, due to backward compatibility, it needs to
be expanded into series of rlwimi in 32-bit environment. In the future,
we may improve bit permutation selector and remove such direct codegen.
---
 clang/lib/Sema/SemaChecking.cpp |   1 -
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 109 --
 llvm/test/CodeGen/PowerPC/rldimi.ll | 366 
 3 files changed, 454 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 11401b6f56c0ea..d2cbe5417d682d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5236,7 +5236,6 @@ static bool isPPC_64Builtin(unsigned BuiltinID) {
   case PPC::BI__builtin_ppc_fetch_and_andlp:
   case PPC::BI__builtin_ppc_fetch_and_orlp:
   case PPC::BI__builtin_ppc_fetch_and_swaplp:
-  case PPC::BI__builtin_ppc_rldimi:
 return true;
   }
   return false;
diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index 7436b202fba0d9..3281a0dfd08729 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -643,6 +643,7 @@ PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine 
,
   // We want to custom lower some of our intrinsics.
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
+  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
@@ -10757,6 +10758,88 @@ static bool getVectorCompareInfo(SDValue Intrin, int 
,
   return true;
 }
 
+static SDValue getRotateInsert32(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME) {
+  assert(SH < 32 && MB < 32 && ME < 32 &&
+ "Invalid argument for rotate insert!");
+  return SDValue(
+  DAG.getMachineNode(PPC::RLWIMI, Loc, MVT::i32,
+ {Dst, Src, DAG.getTargetConstant(SH, Loc, MVT::i32),
+  DAG.getTargetConstant(MB, Loc, MVT::i32),
+  DAG.getTargetConstant(ME, Loc, MVT::i32)}),
+  0);
+}
+
+static SDValue getRotateInsert64(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME, bool IsPPC64) {
+  assert(SH < 64 && MB < 64 && ME < 64 &&
+ "Invalid argument for rotate insert!");
+  if (IsPPC64) {
+// rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
+if (ME < 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH + 1, Loc, MVT::i32));
+} else if (ME > 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH - 63, Loc, MVT::i32));
+}
+return SDValue(DAG.getMachineNode(
+   PPC::RLDIMI, Loc, MVT::i64,
+   {Dst, Src, DAG.getTargetConstant(63 - ME, Loc, 
MVT::i32),
+DAG.getTargetConstant(MB, Loc, MVT::i32)}),
+   0);
+  }
+
+  // To implement rldimi(Dst, Src) on 32-bit target, four parts are needed. SH
+  // is adjusted to simplify cases. Invalid ranges will be skipped.
+  // - SrcHi inserted into DstHi with [0, 32-SH)
+  // - SrcLo inserted into DstHi with [32-SH, 32)
+  // - SrcHi inserted into DstLo with [32, 64-SH)
+  // - SrcLo inserted into DstLo with [64-SH, 64)
+  auto [SrcLo, SrcHi] = DAG.SplitScalar(Src, Loc, MVT::i32, MVT::i32);
+  auto [DstLo, DstHi] = DAG.SplitScalar(Dst, Loc, MVT::i32, MVT::i32);
+  if (SH >= 32) {
+SH -= 32;
+std::swap(SrcLo, SrcHi);
+  }
+  auto GetSubInsert = [, , SH](unsigned Left, unsigned Right,
+   SDValue Src, SDValue Dst, unsigned MB,
+   unsigned ME) {
+if (Left > Right)
+  return Dst;
+
+if (MB <= ME) {
+  if (MB <= Right && ME >= Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH,
+ std::max(MB, Left) % 32,
+ std::min(ME, Right) % 32);
+} else {
+  if (MB < Left || ME > Right)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, Left % 32, Right % 
32);
+
+  if (MB <= Right && ME < Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, MB % 32, 

[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Qiu Chaofan via cfe-commits

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


[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/86783

>From b886dcf2da25417d9f8cd75ff4aa58686e35139d Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 27 Mar 2024 17:11:04 +0800
Subject: [PATCH 1/2] [PowerPC] Implement 32-bit expansion for rldimi

rldimi is 64-bit instruction, due to backward compatibility, it needs to
be expanded into series of rlwimi in 32-bit environment. In the future,
we may improve bit permutation selector and remove such direct codegen.
---
 clang/lib/Sema/SemaChecking.cpp |   1 -
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 109 --
 llvm/test/CodeGen/PowerPC/rldimi.ll | 366 
 3 files changed, 454 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 11401b6f56c0ea..d2cbe5417d682d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5236,7 +5236,6 @@ static bool isPPC_64Builtin(unsigned BuiltinID) {
   case PPC::BI__builtin_ppc_fetch_and_andlp:
   case PPC::BI__builtin_ppc_fetch_and_orlp:
   case PPC::BI__builtin_ppc_fetch_and_swaplp:
-  case PPC::BI__builtin_ppc_rldimi:
 return true;
   }
   return false;
diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index 7436b202fba0d9..3281a0dfd08729 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -643,6 +643,7 @@ PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine 
,
   // We want to custom lower some of our intrinsics.
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
+  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
@@ -10757,6 +10758,88 @@ static bool getVectorCompareInfo(SDValue Intrin, int 
,
   return true;
 }
 
+static SDValue getRotateInsert32(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME) {
+  assert(SH < 32 && MB < 32 && ME < 32 &&
+ "Invalid argument for rotate insert!");
+  return SDValue(
+  DAG.getMachineNode(PPC::RLWIMI, Loc, MVT::i32,
+ {Dst, Src, DAG.getTargetConstant(SH, Loc, MVT::i32),
+  DAG.getTargetConstant(MB, Loc, MVT::i32),
+  DAG.getTargetConstant(ME, Loc, MVT::i32)}),
+  0);
+}
+
+static SDValue getRotateInsert64(SelectionDAG , SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME, bool IsPPC64) {
+  assert(SH < 64 && MB < 64 && ME < 64 &&
+ "Invalid argument for rotate insert!");
+  if (IsPPC64) {
+// rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
+if (ME < 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH + 1, Loc, MVT::i32));
+} else if (ME > 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH - 63, Loc, MVT::i32));
+}
+return SDValue(DAG.getMachineNode(
+   PPC::RLDIMI, Loc, MVT::i64,
+   {Dst, Src, DAG.getTargetConstant(63 - ME, Loc, 
MVT::i32),
+DAG.getTargetConstant(MB, Loc, MVT::i32)}),
+   0);
+  }
+
+  // To implement rldimi(Dst, Src) on 32-bit target, four parts are needed. SH
+  // is adjusted to simplify cases. Invalid ranges will be skipped.
+  // - SrcHi inserted into DstHi with [0, 32-SH)
+  // - SrcLo inserted into DstHi with [32-SH, 32)
+  // - SrcHi inserted into DstLo with [32, 64-SH)
+  // - SrcLo inserted into DstLo with [64-SH, 64)
+  auto [SrcLo, SrcHi] = DAG.SplitScalar(Src, Loc, MVT::i32, MVT::i32);
+  auto [DstLo, DstHi] = DAG.SplitScalar(Dst, Loc, MVT::i32, MVT::i32);
+  if (SH >= 32) {
+SH -= 32;
+std::swap(SrcLo, SrcHi);
+  }
+  auto GetSubInsert = [, , SH](unsigned Left, unsigned Right,
+   SDValue Src, SDValue Dst, unsigned MB,
+   unsigned ME) {
+if (Left > Right)
+  return Dst;
+
+if (MB <= ME) {
+  if (MB <= Right && ME >= Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH,
+ std::max(MB, Left) % 32,
+ std::min(ME, Right) % 32);
+} else {
+  if (MB < Left || ME > Right)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, Left % 32, Right % 
32);
+
+  if (MB <= Right && ME < Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, MB % 32, 

[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce bugs. (PR #87310)

2024-04-01 Thread via cfe-commits

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


[clang] [UEFI] X86_64 UEFI Clang Driver (PR #76838)

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,92 @@
+//===--- UEFI.h - UEFI ToolChain Implementations --*- C++ -*-===//
+//
+// 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 "UEFI.h"
+#include "CommonArgs.h"
+#include "Darwin.h"
+#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/Options.h"
+#include "clang/Driver/SanitizerArgs.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/TargetParser/Host.h"
+
+using namespace clang::driver;
+using namespace clang::driver::toolchains;
+using namespace clang;
+using namespace llvm::opt;
+
+UEFI::UEFI(const Driver , const llvm::Triple , const ArgList )
+: ToolChain(D, Triple, Args) {
+  getProgramPaths().push_back(getDriver().getInstalledDir());
+  if (getDriver().getInstalledDir() != getDriver().Dir)
+getProgramPaths().push_back(getDriver().Dir);
+}
+
+Tool *UEFI::buildLinker() const { return new tools::uefi::Linker(*this); }
+
+void tools::uefi::Linker::ConstructJob(Compilation , const JobAction ,
+   const InputInfo ,
+   const InputInfoList ,
+   const ArgList ,
+   const char *LinkingOutput) const {
+  ArgStringList CmdArgs;
+  auto  = static_cast(getToolChain());
+
+  assert((Output.isFilename() || Output.isNothing()) && "invalid output");
+  if (Output.isFilename())
+CmdArgs.push_back(
+Args.MakeArgString(std::string("-out:") + Output.getFilename()));
+
+  CmdArgs.push_back("-nologo");
+
+  // TODO: Other UEFI binary subsystems that are currently unsupported:
+  // efi_boot_service_driver, efi_rom, efi_runtime_driver.
+  CmdArgs.push_back("-subsystem:efi_application");
+
+  // Default entry function name according to the TianoCore reference
+  // implementation is EfiMain.
+  // TODO: Provide a flag to override the entry function name.
+  CmdArgs.push_back("-entry:EfiMain");
+
+  // "Terminal Service Aware" flag is not needed for UEFI applications.
+  CmdArgs.push_back("-tsaware:no");
+
+  // EFI_APPLICATION to be linked as DLL by default.
+  CmdArgs.push_back("-dll");
+
+  if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
+CmdArgs.push_back("-debug");
+
+  Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
+
+  AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
+
+  // This should ideally be handled by ToolChain::GetLinkerPath but we need
+  // to special case some linker paths. In the case of lld, we need to
+  // translate 'lld' into 'lld-link'.
+  StringRef Linker =
+  Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER);
+  if (Linker.empty() || Linker.equals("lld"))
+Linker = "lld-link";
+
+  auto LinkerPath = TC.GetProgramPath(Linker.str().c_str());
+  auto LinkCmd = std::make_unique(
+  JA, *this, ResponseFileSupport::AtFileUTF16(),

Prabhuk wrote:

Yes. This maintains compatibility with LINK.exe which only supports UTF-16. 

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce bugs. (PR #87310)

2024-04-01 Thread via cfe-commits

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce bugs. (PR #87310)

2024-04-01 Thread via cfe-commits

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce. (PR #87310)

2024-04-01 Thread via cfe-commits

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce. (PR #87310)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: idle666 (idler66)


Changes

For example, struct base { public : base() {} template typename T 
base(T x) {} }; struct derived : public base { public: derived() {} 
derived(derived that): base(that) {} }; int main() { derived d1; derived 
d2 = d1; return 0;}

The copy constructor of base is not chosen because it is not an exact match for 
the argument type derived. 
The templated constructor base(T x) can accept arguments of any type T. 
In the line derived(const derived that): base(that), the that object 
should be copied twice — once during the initialization of the derived class 
and again when passing it to the base class constructor. 
The assignment d2 = d1 via base(that) would result in an infinite recursion and 
eventually lead to a stack overflow.

Multiple executions of copy semantics lead to stack overflow. 
So, for the templated constructor base(T x), if T is a subclass of base, 
pass-by-reference should be used!

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (+22-2) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+1-1) 
- (modified) clang/unittests/CodeGen/CMakeLists.txt (+1) 
- (added) llvm/TemplateInstantiationTest.cpp (+216) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 4c2577126e48b3..395b25207e1dfd 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4520,7 +4520,7 @@ void CodeGenFunction::EmitCallArgs(
 (isa(AC.getDecl()) &&
  isObjCMethodWithTypeParams(cast(AC.getDecl() 
&&
"Argument and parameter types don't match");
-EmitCallArg(Args, *Arg, ArgTypes[Idx]);
+EmitCallArg(Args, *Arg, ArgTypes[Idx], AC);
 // In particular, we depend on it being the last arg in Args, and the
 // objectsize bits depend on there only being one arg if !LeftToRight.
 assert(InitialArgSize + 1 == Args.size() &&
@@ -4611,7 +4611,7 @@ void CallArg::copyInto(CodeGenFunction , Address 
Addr) const {
 }
 
 void CodeGenFunction::EmitCallArg(CallArgList , const Expr *E,
-  QualType type) {
+  QualType type, const AbstractCallee& AC) {
   DisableDebugLocationUpdates Dis(*this, E);
   if (const ObjCIndirectCopyRestoreExpr *CRE
 = dyn_cast(E)) {
@@ -4627,6 +4627,26 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 return args.add(EmitReferenceBindingToExpr(E), type);
   }
 
+  auto IsSingleParameterCopyConstructor = [&]() {
+if(1 != AC.getNumParams()) return false;
+if (const CXXRecordDecl* SubRecordDecl = type->getAsCXXRecordDecl()) {
+  if (const CXXConstructorDecl* ConstructorDecl = 
dyn_cast(AC.getDecl())) {
+if(const CXXRecordDecl* BaseRecordDecl = 
dyn_cast(ConstructorDecl->getParent())) {
+  if(SubRecordDecl->isDerivedFrom(BaseRecordDecl)) {
+return true;
+  }
+}
+  }
+}
+return false;
+  };
+  if(IsSingleParameterCopyConstructor()) {
+AggValueSlot Slot = args.isUsingInAlloca()
+? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
+RValue RV = Slot.asRValue();
+return args.add(RV, type);
+  }
+
   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
 
   // In the Microsoft C++ ABI, aggregate arguments are destructed by the 
callee.
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 618e78809db408..f2305a9307396f 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4746,7 +4746,7 @@ class CodeGenFunction : public CodeGenTypeCache {
AbstractCallee AC, unsigned ParmNum);
 
   /// EmitCallArg - Emit a single call argument.
-  void EmitCallArg(CallArgList , const Expr *E, QualType ArgType);
+  void EmitCallArg(CallArgList , const Expr *E, QualType ArgType, const 
AbstractCallee& AC);
 
   /// EmitDelegateCallArg - We are performing a delegate call; that
   /// is, the current function is delegating to another one.  Produce
diff --git a/clang/unittests/CodeGen/CMakeLists.txt 
b/clang/unittests/CodeGen/CMakeLists.txt
index a437f441568f27..8870237c85539d 100644
--- a/clang/unittests/CodeGen/CMakeLists.txt
+++ b/clang/unittests/CodeGen/CMakeLists.txt
@@ -9,6 +9,7 @@ add_clang_unittest(ClangCodeGenTests
   CodeGenExternalTest.cpp
   TBAAMetadataTest.cpp
   CheckTargetFeaturesTest.cpp
+  TemplateInstantiationTest.cpp
   )
 
 clang_target_link_libraries(ClangCodeGenTests
diff --git a/llvm/TemplateInstantiationTest.cpp 
b/llvm/TemplateInstantiationTest.cpp
new file mode 100644
index 00..fbb7b94e6f5aa7
--- /dev/null
+++ b/llvm/TemplateInstantiationTest.cpp
@@ -0,0 +1,216 @@
+//===- unittests/CodeGen/TemplateInstantiationTest.cpp - template 
instantiation test -===//
+//
+// Part of the LLVM Project, under the 

[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce. (PR #87310)

2024-04-01 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce. (PR #87310)

2024-04-01 Thread via cfe-commits

https://github.com/idler66 created 
https://github.com/llvm/llvm-project/pull/87310

For example, struct base { public : base() {} template  base(T x) 
{} }; struct derived : public base { public: derived() {} derived(derived& 
that): base(that) {} }; int main() { derived d1; derived d2 = d1; return 0;}

The copy constructor of base is not chosen because it is not an exact match for 
the argument type derived. 
The templated constructor base(T x) can accept arguments of any type T. 
In the line derived(const derived& that): base(that), the that object should be 
copied twice — once during the initialization of the derived class and again 
when passing it to the base class constructor. 
The assignment d2 = d1 via base(that) would result in an infinite recursion and 
eventually lead to a stack overflow.

Multiple executions of copy semantics lead to stack overflow. 
So, for the templated constructor base(T x), if T is a subclass of base, 
pass-by-reference should be used!

>From 34736d931a250f8ca2d65bde6e5136e6736ef76b Mon Sep 17 00:00:00 2001
From: wangjufan 
Date: Sun, 31 Mar 2024 23:49:30 +0800
Subject: [PATCH] [clang][CodeGen] Fix templated constructors in base classes
 introduce bugs.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

For example, struct base { public : base() {} template  base(T x) 
{} };
struct derived : public base { public: derived() {} derived(derived& that): 
base(that) {} };
int main() { derived d1; derived d2 = d1; return 0;}

The copy constructor of base is not chosen because it is not an exact match for 
the argument type derived.
The templated constructor base(T x) can accept arguments of any type T.
In the line derived(const derived& that): base(that), the that object should be 
copied twice — once during the initialization of the derived class and again 
when passing it to the base class constructor.
The assignment d2 = d1 via base(that) would result in an infinite recursion and 
eventually lead to a stack overflow.

Multiple executions of copy semantics lead to stack overflow.
So, for the templated constructor base(T x),
if T is a subclass of base, pass-by-reference should be used!
---
 clang/lib/CodeGen/CGCall.cpp   |  24 ++-
 clang/lib/CodeGen/CodeGenFunction.h|   2 +-
 clang/unittests/CodeGen/CMakeLists.txt |   1 +
 llvm/TemplateInstantiationTest.cpp | 216 +
 4 files changed, 240 insertions(+), 3 deletions(-)
 create mode 100644 llvm/TemplateInstantiationTest.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 4c2577126e48b3..395b25207e1dfd 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4520,7 +4520,7 @@ void CodeGenFunction::EmitCallArgs(
 (isa(AC.getDecl()) &&
  isObjCMethodWithTypeParams(cast(AC.getDecl() 
&&
"Argument and parameter types don't match");
-EmitCallArg(Args, *Arg, ArgTypes[Idx]);
+EmitCallArg(Args, *Arg, ArgTypes[Idx], AC);
 // In particular, we depend on it being the last arg in Args, and the
 // objectsize bits depend on there only being one arg if !LeftToRight.
 assert(InitialArgSize + 1 == Args.size() &&
@@ -4611,7 +4611,7 @@ void CallArg::copyInto(CodeGenFunction , Address 
Addr) const {
 }
 
 void CodeGenFunction::EmitCallArg(CallArgList , const Expr *E,
-  QualType type) {
+  QualType type, const AbstractCallee& AC) {
   DisableDebugLocationUpdates Dis(*this, E);
   if (const ObjCIndirectCopyRestoreExpr *CRE
 = dyn_cast(E)) {
@@ -4627,6 +4627,26 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 return args.add(EmitReferenceBindingToExpr(E), type);
   }
 
+  auto IsSingleParameterCopyConstructor = [&]() {
+if(1 != AC.getNumParams()) return false;
+if (const CXXRecordDecl* SubRecordDecl = type->getAsCXXRecordDecl()) {
+  if (const CXXConstructorDecl* ConstructorDecl = 
dyn_cast(AC.getDecl())) {
+if(const CXXRecordDecl* BaseRecordDecl = 
dyn_cast(ConstructorDecl->getParent())) {
+  if(SubRecordDecl->isDerivedFrom(BaseRecordDecl)) {
+return true;
+  }
+}
+  }
+}
+return false;
+  };
+  if(IsSingleParameterCopyConstructor()) {
+AggValueSlot Slot = args.isUsingInAlloca()
+? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
+RValue RV = Slot.asRValue();
+return args.add(RV, type);
+  }
+
   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
 
   // In the Microsoft C++ ABI, aggregate arguments are destructed by the 
callee.
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 618e78809db408..f2305a9307396f 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4746,7 +4746,7 @@ class CodeGenFunction : public CodeGenTypeCache {

[clang] [M68k] Change gcc register name from a7 to sp. (PR #87095)

2024-04-01 Thread Min-Yih Hsu via cfe-commits

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

Thank you! LGTM

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


[clang] [polly] [clang-format] Correctly annotate block braces of empty ctors/dtors (PR #82097)

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

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


[clang] [clang-format] Fix a regression in annotating TrailingReturnArrow (PR #86624)

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

owenca wrote:

Ping @mydeveloperday @HazardyKnusperkeks @rymiel 

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


[clang] [X86_64] fix arg pass error in struct. (PR #86902)

2024-04-01 Thread Longsheng Mou via cfe-commits

CoTinker wrote:

Thank you very much, I'll try it.

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


[clang] [clang-format] Lambda parameter should be passed by const reference (PR #87306)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Closes #87254.

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


1 Files Affected:

- (modified) clang/lib/Format/Format.cpp (+1-1) 


``diff
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 46ed5baaeacead..1a45d5089e209c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3578,7 +3578,7 @@ cleanupAroundReplacements(StringRef Code, const 
tooling::Replacements ,
   // We need to use lambda function here since there are two versions of
   // `cleanup`.
   auto Cleanup = [](const FormatStyle , StringRef Code,
-std::vector Ranges,
+const std::vector ,
 StringRef FileName) -> tooling::Replacements {
 return cleanup(Style, Code, Ranges, FileName);
   };

``




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


[clang] [clang-format] Lambda parameter should be passed by const reference (PR #87306)

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

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/87306

Closes #87254.

>From 91edc2bff0ea98e39b5614ae91ab562c1135b6e7 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 1 Apr 2024 20:08:21 -0700
Subject: [PATCH] [clang-format] Lambda parameter should be passed by const
 reference

Closes #87254.
---
 clang/lib/Format/Format.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 46ed5baaeacead..1a45d5089e209c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3578,7 +3578,7 @@ cleanupAroundReplacements(StringRef Code, const 
tooling::Replacements ,
   // We need to use lambda function here since there are two versions of
   // `cleanup`.
   auto Cleanup = [](const FormatStyle , StringRef Code,
-std::vector Ranges,
+const std::vector ,
 StringRef FileName) -> tooling::Replacements {
 return cleanup(Style, Code, Ranges, FileName);
   };

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


[clang] [X86_64] fix arg pass error in struct. (PR #86902)

2024-04-01 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/86902

>From 09596bbeeedecb312f8be40d153bb267abc2d659 Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Fri, 15 Mar 2024 20:50:54 +0800
Subject: [PATCH] [X86_64] fix arg pass error in struct.

In some struct like s67, only one i64 register is used when the structure
parameter is transferred, which is obviously incorrect.So we need
to treat the split case specially, using memory like gcc.
---
 clang/lib/CodeGen/Targets/X86.cpp |  6 +-
 clang/test/CodeGen/X86/x86_64-arguments.c | 18 ++
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 1146a851a7715d..8f4df98af117a0 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -2100,8 +2100,12 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class ,
 postMerge(Size, Lo, Hi);
 return;
   }
+
+  bool InMemory = Offset % getContext().getTypeAlign(i->getType()) ||
+  (i->getType()->getAs() &&
+   Offset % getContext().getTypeSize(i->getType()));
   // Note, skip this test for bit-fields, see below.
-  if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
+  if (!BitField && InMemory) {
 Lo = Memory;
 postMerge(Size, Lo, Hi);
 return;
diff --git a/clang/test/CodeGen/X86/x86_64-arguments.c 
b/clang/test/CodeGen/X86/x86_64-arguments.c
index cf5636cfd518b6..82845f0a2b31fd 100644
--- a/clang/test/CodeGen/X86/x86_64-arguments.c
+++ b/clang/test/CodeGen/X86/x86_64-arguments.c
@@ -533,6 +533,24 @@ typedef float t66 __attribute__((__vector_size__(128), 
__aligned__(128)));
 void f66(t66 a0) {
 }
 
+typedef long long t67 __attribute__((aligned (4)));
+struct s67 {
+  int a;
+  t67 b;
+};
+// CHECK-LABEL: define{{.*}} void @f67(ptr noundef byval(%struct.s67) align 8 
%x)
+void f67(struct s67 x) {
+}
+
+typedef double t68 __attribute__((aligned (4)));
+struct s68 {
+  int a;
+  t68 b;
+};
+// CHECK-LABEL: define{{.*}} void @f68(ptr noundef byval(%struct.s68) align 8 
%x)
+void f68(struct s68 x) {
+}
+
 /// The synthesized __va_list_tag does not have file/line fields.
 // CHECK:  = distinct !DICompositeType(tag: DW_TAG_structure_type, name: 
"__va_list_tag",
 // CHECK-NOT:  file:

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


[clang] [X86_32] Teach X86_32 va_arg to ignore empty structs. (PR #86075)

2024-04-01 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/86075

>From a4d9a6fefdbe7c0ee6a891af230438a10ddd7c5a Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Thu, 21 Mar 2024 11:23:56 +0800
Subject: [PATCH] [X86_32] Teach X86_32 va_arg to ignore empty structs.

Empty structs are ignored for parameter passing purposes, but va_arg was
incrementing the pointer anyway for that the size of empty struct in c++
is 1 byte, which could lead to va_list getting out of sync.
---
 clang/lib/CodeGen/Targets/X86.cpp  |  6 ++
 clang/test/CodeGenCXX/x86_32-vaarg.cpp | 20 
 2 files changed, 26 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/x86_32-vaarg.cpp

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 1146a851a7715d..c831777699f627 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1069,6 +1069,12 @@ Address X86_32ABIInfo::EmitVAArg(CodeGenFunction ,
 
   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
 
+  CCState State(*const_cast(CGF.CurFnInfo));
+  ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
+  // Empty records are ignored for parameter passing purposes.
+  if (AI.isIgnore())
+return CGF.CreateMemTemp(Ty);
+
   // x86-32 changes the alignment of certain arguments on the stack.
   //
   // Just messing with TypeInfo like this works because we never pass
diff --git a/clang/test/CodeGenCXX/x86_32-vaarg.cpp 
b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
new file mode 100644
index 00..23eac1164118c6
--- /dev/null
+++ b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
@@ -0,0 +1,20 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -x c -o - %s | FileCheck 
%s
+
+typedef struct {} empty;
+
+// CHECK-LABEL: @{{.*}}empty_record_test
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RESULT_PTR:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[LIST:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[TMP:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1
+// CHECK-NEXT:store ptr [[AGG_RESULT:%.*]], ptr [[RESULT_PTR]], align 4
+// CHECK-NEXT:store i32 [[Z:%.*]], ptr [[Z_ADDR]], align 4
+// CHECK-NEXT:call void @llvm.va_start(ptr [[LIST]])
+empty empty_record_test(int z, ...) {
+  __builtin_va_list list;
+  __builtin_va_start(list, z);
+  return __builtin_va_arg(list, empty);
+}

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


[clang] [X86_32] Teach X86_32 va_arg to ignore empty structs. (PR #86075)

2024-04-01 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/86075

>From 929fba43012209b74b654b8d9a017a43826063fe Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Thu, 21 Mar 2024 11:23:56 +0800
Subject: [PATCH] [X86_32] Teach X86_32 va_arg to ignore empty structs.

Empty structs are ignored for parameter passing purposes, but va_arg was
incrementing the pointer anyway for that the size of empty struct in c++
is 1 byte, which could lead to va_list getting out of sync.
---
 clang/lib/CodeGen/Targets/X86.cpp  |  6 ++
 clang/test/CodeGenCXX/x86_32-vaarg.cpp | 20 
 2 files changed, 26 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/x86_32-vaarg.cpp

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 1ec0f159ebcb8a..38143d1eed21aa 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1069,6 +1069,12 @@ Address X86_32ABIInfo::EmitVAArg(CodeGenFunction ,
 
   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
 
+  CCState State(*const_cast(CGF.CurFnInfo));
+  ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
+  // Empty records are ignored for parameter passing purposes.
+  if (AI.isIgnore())
+return CGF.CreateMemTemp(Ty);
+
   // x86-32 changes the alignment of certain arguments on the stack.
   //
   // Just messing with TypeInfo like this works because we never pass
diff --git a/clang/test/CodeGenCXX/x86_32-vaarg.cpp 
b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
new file mode 100644
index 00..23eac1164118c6
--- /dev/null
+++ b/clang/test/CodeGenCXX/x86_32-vaarg.cpp
@@ -0,0 +1,20 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple i386-linux-gnu -emit-llvm -x c -o - %s | FileCheck 
%s
+
+typedef struct {} empty;
+
+// CHECK-LABEL: @{{.*}}empty_record_test
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RESULT_PTR:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[LIST:%.*]] = alloca ptr, align 4
+// CHECK-NEXT:[[TMP:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1
+// CHECK-NEXT:store ptr [[AGG_RESULT:%.*]], ptr [[RESULT_PTR]], align 4
+// CHECK-NEXT:store i32 [[Z:%.*]], ptr [[Z_ADDR]], align 4
+// CHECK-NEXT:call void @llvm.va_start(ptr [[LIST]])
+empty empty_record_test(int z, ...) {
+  __builtin_va_list list;
+  __builtin_va_start(list, z);
+  return __builtin_va_arg(list, empty);
+}

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


[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-01 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-directx

@llvm/pr-subscribers-hlsl

Author: Farzon Lotfi (farzonl)


Changes

Start of #83882
- `Builtins.td` - add the `hlsl` `all` elementwise builtin.
- `CGBuiltin.cpp` - Show a use case for CGHLSLUtils via an `all` intrinsic 
codegen.
- `CGHLSLRuntime.cpp` - move `thread_id` to use CGHLSLUtils.
- `CGHLSLUtils.h` - Create a macro to help pick the right intrinsic for the 
backend.
- `hlsl_intrinsics.h` - Add the `all` api.
- `SemaChecking.cpp` - Add `all` builtin type checking
- `IntrinsicsDirectX.td` - Add the `all` `dx` intrinsic
- `IntrinsicsSPIRV.td` - Add the `all` `spv` intrinsic
- `SPIRVInstructionSelector.cpp` - Add an implementation of  `OpAll` for 
`spv_all` intrinsic

Decided to implement a new intrinsic instead of edit an existing one to 
formalize the design without editing a bunch of test cases.

---

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


11 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+9) 
- (modified) clang/lib/CodeGen/CGHLSLRuntime.cpp (+4-14) 
- (added) clang/lib/CodeGen/CGHLSLUtils.h (+44) 
- (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (+112) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+1) 
- (added) clang/test/CodeGenHLSL/builtins/all.hlsl (+277) 
- (modified) llvm/include/llvm/IR/IntrinsicsDirectX.td (+2-1) 
- (modified) llvm/include/llvm/IR/IntrinsicsSPIRV.td (+1) 
- (modified) llvm/lib/Target/SPIRV/SPIRVInstructionSelector.cpp (+19) 
- (added) llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll (+95) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bb007231c0b783..eec25d59c6a7dc 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -13,6 +13,7 @@
 #include "ABIInfo.h"
 #include "CGCUDARuntime.h"
 #include "CGCXXABI.h"
+#include "CGHLSLUtils.h"
 #include "CGObjCRuntime.h"
 #include "CGOpenCLRuntime.h"
 #include "CGRecordLayout.h"
@@ -18182,6 +18183,14 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+CGHLSLUtils::get_hlsl_all_intrinsic(
+CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 794d93358b0a4c..c772049dbe3acc 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -14,11 +14,10 @@
 
 #include "CGHLSLRuntime.h"
 #include "CGDebugInfo.h"
+#include "CGHLSLUtils.h"
 #include "CodeGenModule.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/TargetOptions.h"
-#include "llvm/IR/IntrinsicsDirectX.h"
-#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -343,18 +342,9 @@ llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> 
,
 return B.CreateCall(FunctionCallee(DxGroupIndex));
   }
   if (D.hasAttr()) {
-llvm::Function *ThreadIDIntrinsic;
-switch (CGM.getTarget().getTriple().getArch()) {
-case llvm::Triple::dxil:
-  ThreadIDIntrinsic = CGM.getIntrinsic(Intrinsic::dx_thread_id);
-  break;
-case llvm::Triple::spirv:
-  ThreadIDIntrinsic = CGM.getIntrinsic(Intrinsic::spv_thread_id);
-  break;
-default:
-  llvm_unreachable("Input semantic not supported by target");
-  break;
-}
+llvm::Function *ThreadIDIntrinsic =
+CGM.getIntrinsic(CGHLSLUtils::get_hlsl_thread_id_intrinsic(
+CGM.getTarget().getTriple().getArch()));
 return buildVectorInput(B, ThreadIDIntrinsic, Ty);
   }
   assert(false && "Unhandled parameter attribute");
diff --git a/clang/lib/CodeGen/CGHLSLUtils.h b/clang/lib/CodeGen/CGHLSLUtils.h
new file mode 100644
index 00..ca29835105aa87
--- /dev/null
+++ b/clang/lib/CodeGen/CGHLSLUtils.h
@@ -0,0 

[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Farzon Lotfi (farzonl)


Changes

Start of #83882
- `Builtins.td` - add the `hlsl` `all` elementwise builtin.
- `CGBuiltin.cpp` - Show a use case for CGHLSLUtils via an `all` intrinsic 
codegen.
- `CGHLSLRuntime.cpp` - move `thread_id` to use CGHLSLUtils.
- `CGHLSLUtils.h` - Create a macro to help pick the right intrinsic for the 
backend.
- `hlsl_intrinsics.h` - Add the `all` api.
- `SemaChecking.cpp` - Add `all` builtin type checking
- `IntrinsicsDirectX.td` - Add the `all` `dx` intrinsic
- `IntrinsicsSPIRV.td` - Add the `all` `spv` intrinsic
- `SPIRVInstructionSelector.cpp` - Add an implementation of  `OpAll` for 
`spv_all` intrinsic

Decided to implement a new intrinsic instead of edit an existing one to 
formalize the design without editing a bunch of test cases.

---

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


11 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+9) 
- (modified) clang/lib/CodeGen/CGHLSLRuntime.cpp (+4-14) 
- (added) clang/lib/CodeGen/CGHLSLUtils.h (+44) 
- (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (+112) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+1) 
- (added) clang/test/CodeGenHLSL/builtins/all.hlsl (+277) 
- (modified) llvm/include/llvm/IR/IntrinsicsDirectX.td (+2-1) 
- (modified) llvm/include/llvm/IR/IntrinsicsSPIRV.td (+1) 
- (modified) llvm/lib/Target/SPIRV/SPIRVInstructionSelector.cpp (+19) 
- (added) llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll (+95) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bb007231c0b783..eec25d59c6a7dc 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -13,6 +13,7 @@
 #include "ABIInfo.h"
 #include "CGCUDARuntime.h"
 #include "CGCXXABI.h"
+#include "CGHLSLUtils.h"
 #include "CGObjCRuntime.h"
 #include "CGOpenCLRuntime.h"
 #include "CGRecordLayout.h"
@@ -18182,6 +18183,14 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+CGHLSLUtils::get_hlsl_all_intrinsic(
+CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 794d93358b0a4c..c772049dbe3acc 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -14,11 +14,10 @@
 
 #include "CGHLSLRuntime.h"
 #include "CGDebugInfo.h"
+#include "CGHLSLUtils.h"
 #include "CodeGenModule.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/TargetOptions.h"
-#include "llvm/IR/IntrinsicsDirectX.h"
-#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -343,18 +342,9 @@ llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> 
,
 return B.CreateCall(FunctionCallee(DxGroupIndex));
   }
   if (D.hasAttr()) {
-llvm::Function *ThreadIDIntrinsic;
-switch (CGM.getTarget().getTriple().getArch()) {
-case llvm::Triple::dxil:
-  ThreadIDIntrinsic = CGM.getIntrinsic(Intrinsic::dx_thread_id);
-  break;
-case llvm::Triple::spirv:
-  ThreadIDIntrinsic = CGM.getIntrinsic(Intrinsic::spv_thread_id);
-  break;
-default:
-  llvm_unreachable("Input semantic not supported by target");
-  break;
-}
+llvm::Function *ThreadIDIntrinsic =
+CGM.getIntrinsic(CGHLSLUtils::get_hlsl_thread_id_intrinsic(
+CGM.getTarget().getTriple().getArch()));
 return buildVectorInput(B, ThreadIDIntrinsic, Ty);
   }
   assert(false && "Unhandled parameter attribute");
diff --git a/clang/lib/CodeGen/CGHLSLUtils.h b/clang/lib/CodeGen/CGHLSLUtils.h
new file mode 100644
index 00..ca29835105aa87
--- /dev/null
+++ b/clang/lib/CodeGen/CGHLSLUtils.h
@@ -0,0 +1,44 @@
+
+//===- CGHLSLUtils.h - 

[clang] [libclc] [llvm] [openmp] [Clang] `__attribute__((assume))` refactor (PR #84934)

2024-04-01 Thread Johannes Doerfert via cfe-commits

jdoerfert wrote:

FWIW, for OpenMP we only need to support the [[]] spelling in C++. The fact we 
had everything else was a side-effect of the implementation, IIRC. 
Thus, this should be fine for OpenMP.

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


[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread Farzon Lotfi via cfe-commits

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


[clang] [clang]Treat arguments to builtin type traits as template type arguments (PR #87132)

2024-04-01 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

LGTM but I want @fahadnayyar to verify this addresses his concerns.

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


[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/87171

>From 47518b4172cef216f1cc84e54b65e979b4c679c2 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 28 Mar 2024 21:05:36 -0400
Subject: [PATCH 1/2] [HLSL][DXIL][SPIRV] Intrinsic unification PR

---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  19 ++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 112 +++
 clang/lib/Sema/SemaChecking.cpp   |   1 +
 clang/test/CodeGenHLSL/builtins/all.hlsl  | 277 ++
 llvm/include/llvm/IR/Intrinsics.td|  12 +
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   4 +-
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |   3 +-
 .../Target/SPIRV/SPIRVInstructionSelector.cpp |  19 ++
 .../test/CodeGen/SPIRV/hlsl-intrinsics/all.ll |  95 ++
 10 files changed, 545 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/all.hlsl
 create mode 100644 llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bb007231c0b783..add7ec1fa0eb45 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -51,6 +51,7 @@
 #include "llvm/IR/IntrinsicsR600.h"
 #include "llvm/IR/IntrinsicsRISCV.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/IntrinsicsVE.h"
 #include "llvm/IR/IntrinsicsWebAssembly.h"
 #include "llvm/IR/IntrinsicsX86.h"
@@ -18176,12 +18177,30 @@ Intrinsic::ID getDotProductIntrinsic(QualType QT, int 
elementCount) {
   return Intrinsic::dx_udot;
 }
 
+Intrinsic::ID getAllIntrinsic(const llvm::Triple::ArchType Arch) {
+  switch (Arch) {
+  case llvm::Triple::dxil:
+return Intrinsic::dx_all;
+  case llvm::Triple::spirv:
+return Intrinsic::spv_all;
+  default:
+llvm_unreachable("Input semantic not supported by target");
+  }
+}
+
 Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
 const CallExpr *E) {
   if (!getLangOpts().HLSL)
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+getAllIntrinsic(CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 9fb6204f90c9a8..06409c6fc77417 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -100,6 +100,118 @@ double3 abs(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_abs)
 double4 abs(double4);
 
+//===--===//
+// all builtins
+//===--===//
+
+/// \fn bool all(T x)
+/// \brief Returns True if all components of the \a x parameter are non-zero;
+/// otherwise, false. \param x The input value.
+
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t4);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t4);
+#endif
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(half);

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

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


@@ -41,9 +43,10 @@ Base::~Base() {}
 // CHECK: @_ZTSW3Mod4Base = constant
 // CHECK: @_ZTIW3Mod4Base = constant
 
-// CHECK-INLINE: @_ZTVW3Mod4Base = linkonce_odr {{.*}}unnamed_addr constant
-// CHECK-INLINE: @_ZTSW3Mod4Base = linkonce_odr {{.*}}constant
-// CHECK-INLINE: @_ZTIW3Mod4Base = linkonce_odr {{.*}}constant
+// With the new Itanium C++ ABI, the linkage of vtables in modules don't need 
to be linkonce ODR.

ChuanqiXu9 wrote:

While I agree `weak` may work here, I feel it is odd. I feel the default strong 
linkage seems better when it is applicable. What's the advance to use `weak` 
linkage here?

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


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

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


@@ -1483,10 +1483,15 @@ void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl 
*D) {
   if (D->isThisDeclarationADefinition())
 Record.AddCXXDefinitionData(D);
 
-  // Store (what we currently believe to be) the key function to avoid
-  // deserializing every method so we can compute it.
-  if (D->isCompleteDefinition())
-Record.AddDeclRef(Context.getCurrentKeyFunction(D));
+  if (D->isCompleteDefinition()) {
+if (D->getOwningModule() && D->getOwningModule()->isInterfaceOrPartition())
+  Writer.ModularCodegenDecls.push_back(Writer.GetDeclRef(D));
+else {
+  // Store (what we currently believe to be) the key function to avoid

ChuanqiXu9 wrote:

Done as suggested. I'll perform the optimization later.

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


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

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

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/75912

>From 7399d2417a4b758fa0a98da1f99f3b4ec0eb1046 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Tue, 19 Dec 2023 17:00:59 +0800
Subject: [PATCH 1/3] [C++20] [Modules] [Itanium ABI] Generate the vtable in
 the module unit of dynamic classes

Close https://github.com/llvm/llvm-project/issues/70585 and reflect
https://github.com/itanium-cxx-abi/cxx-abi/issues/170.

The significant change of the patch is: for dynamic classes attached to
module units, we generate the vtable to the attached module units
directly and the key functions for such classes is meaningless.
---
 clang/lib/CodeGen/CGVTables.cpp   | 28 ++
 clang/lib/CodeGen/CodeGenModule.cpp   |  9 +
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |  6 +++
 clang/lib/Sema/SemaDecl.cpp   |  9 +
 clang/lib/Sema/SemaDeclCXX.cpp| 13 +--
 clang/lib/Serialization/ASTReaderDecl.cpp | 13 ++-
 clang/lib/Serialization/ASTWriterDecl.cpp | 13 +--
 clang/test/CodeGenCXX/modules-vtable.cppm | 27 -
 clang/test/CodeGenCXX/pr70585.cppm| 47 +++
 9 files changed, 139 insertions(+), 26 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/pr70585.cppm

diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 8dee3f74b44b4e..54a2c725a10ba3 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -1046,6 +1046,11 @@ CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) 
{
   if (!RD->isExternallyVisible())
 return llvm::GlobalVariable::InternalLinkage;
 
+  // V-tables for non-template classes with an owning module are always
+  // uniquely emitted in that module.
+  if (Module *M = RD->getOwningModule(); M && M->isNamedModule())
+return llvm::GlobalVariable::ExternalLinkage;
+
   // We're at the end of the translation unit, so the current key
   // function is fully correct.
   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
@@ -1180,6 +1185,21 @@ bool CodeGenVTables::isVTableExternal(const 
CXXRecordDecl *RD) {
   TSK == TSK_ExplicitInstantiationDefinition)
 return false;
 
+  // Itanium C++ ABI [5.2.3]:
+  // Virtual tables for dynamic classes are emitted as follows:
+  //
+  // - If the class is templated, the tables are emitted in every object that
+  // references any of them.
+  // - Otherwise, if the class is attached to a module, the tables are uniquely
+  // emitted in the object for the module unit in which it is defined.
+  // - Otherwise, if the class has a key function (see below), the tables are
+  // emitted in the object for the translation unit containing the definition 
of
+  // the key function. This is unique if the key function is not inline.
+  // - Otherwise, the tables are emitted in every object that references any of
+  // them.
+  if (Module *M = RD->getOwningModule(); M && M->isNamedModule())
+return M != CGM.getContext().getCurrentNamedModule();
+
   // Otherwise, if the class doesn't have a key function (possibly
   // anymore), the vtable must be defined here.
   const CXXMethodDecl *keyFunction = 
CGM.getContext().getCurrentKeyFunction(RD);
@@ -1189,13 +1209,7 @@ bool CodeGenVTables::isVTableExternal(const 
CXXRecordDecl *RD) {
   const FunctionDecl *Def;
   // Otherwise, if we don't have a definition of the key function, the
   // vtable must be defined somewhere else.
-  if (!keyFunction->hasBody(Def))
-return true;
-
-  assert(Def && "The body of the key function is not assigned to Def?");
-  // If the non-inline key function comes from another module unit, the vtable
-  // must be defined there.
-  return Def->isInAnotherModuleUnit() && !Def->isInlineSpecified();
+  return !keyFunction->hasBody(Def);
 }
 
 /// Given that we're currently at the end of the translation unit, and
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index e3ed5e90f2d36b..61369bedd147eb 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -6777,6 +6777,15 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
   DI->completeUnusedClass(*CRD);
 }
+// If we're emitting a dynamic class from the importable module we're
+// emitting, we always need to emit the virtual table according to the ABI
+// requirement.
+if (CRD->getOwningModule() &&
+CRD->getOwningModule()->isInterfaceOrPartition() &&
+CRD->getDefinition() && CRD->isDynamicClass() &&
+CRD->getOwningModule() == getContext().getCurrentNamedModule())
+  EmitVTable(CRD);
+
 // Emit any static data members, they may be definitions.
 for (auto *I : CRD->decls())
   if (isa(I) || isa(I))
diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index bdd53a192f828a..6473f356d5bb19 

[clang] MIPS/Clang: Set HasUnalignedAccess false if +strict-align (PR #87257)

2024-04-01 Thread YunQiang Su via cfe-commits


@@ -330,6 +331,8 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  else if (Feature == "+strict-align")
+StrictAlign = true;

wzssyqa wrote:

We cannot due to that +strict-align may be listed before +mips32/64.

I have some try. In all my try, +mips32/64 appeared before +strict-align.
But I am not sure that +mips32/64 will always appear before +strict-align.

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


[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)

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


@@ -3017,6 +3017,7 @@ defm prebuilt_implicit_modules : 
BoolFOption<"prebuilt-implicit-modules",
 
 def fmodule_output_EQ : Joined<["-"], "fmodule-output=">,
   Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>,
+  MarshallingInfoString>,

ChuanqiXu9 wrote:

Since the flag was only used in drivers. So we didn't need a variable. But 
after this patch, we need a variable. If we separate this out, we may get a 
unused variable in that patch. I feel it is not so good.

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


[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)

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


@@ -193,6 +193,20 @@ DwarfFissionKind getDebugFissionKind(const Driver ,
  const llvm::opt::ArgList ,
  llvm::opt::Arg *);
 
+// Calculate the output path of the module file when compiling a module unit
+// with the `-fmodule-output` option or `-fmodule-output=` option specified.
+// The behavior is:
+// - If `-fmodule-output=` is specfied, then the module file is
+//   writing to the value.
+// - Otherwise if the output object file of the module unit is specified, the
+// output path
+//   of the module file should be the same with the output object file except
+//   the corresponding suffix. This requires both `-o` and `-c` are specified.
+// - Otherwise, the output path of the module file will be the same with the
+//   input with the corresponding suffix.
+llvm::SmallString<256>
+getCXX20NamedModuleOutputPath(const llvm::opt::ArgList ,

ChuanqiXu9 wrote:

Done in 
https://github.com/llvm/llvm-project/commit/21f85e230056172cffcaec76352e5a2019b54b86

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


[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)

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

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/85050

>From 79706501a7a3f0f2e0e9c9411bdd5e00e34ae175 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Tue, 12 Mar 2024 17:26:49 +0800
Subject: [PATCH 1/3] [C++20] [Modules] Introduce -fgen-reduced-bmi

---
 clang/include/clang/CodeGen/CodeGenAction.h   |  2 +
 clang/include/clang/Driver/Options.td |  6 +++
 .../include/clang/Frontend/FrontendOptions.h  |  9 +++-
 clang/include/clang/Serialization/ASTWriter.h |  7 +--
 clang/lib/CodeGen/CodeGenAction.cpp   | 19 +++
 clang/lib/Driver/Driver.cpp   | 12 -
 clang/lib/Driver/ToolChains/Clang.cpp | 23 ++--
 clang/lib/Frontend/FrontendActions.cpp|  7 +++
 clang/lib/Frontend/PrecompiledPreamble.cpp|  3 +-
 clang/lib/Serialization/GeneratePCH.cpp   | 23 ++--
 .../test/Driver/module-fgen-reduced-bmi.cppm  | 53 +++
 clang/test/Modules/gen-reduced-bmi.cppm   | 36 +
 12 files changed, 186 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/Driver/module-fgen-reduced-bmi.cppm
 create mode 100644 clang/test/Modules/gen-reduced-bmi.cppm

diff --git a/clang/include/clang/CodeGen/CodeGenAction.h 
b/clang/include/clang/CodeGen/CodeGenAction.h
index 7ad2988e589eb2..186dbb43f01ef7 100644
--- a/clang/include/clang/CodeGen/CodeGenAction.h
+++ b/clang/include/clang/CodeGen/CodeGenAction.h
@@ -57,6 +57,8 @@ class CodeGenAction : public ASTFrontendAction {
   bool loadLinkModules(CompilerInstance );
 
 protected:
+  bool BeginSourceFileAction(CompilerInstance ) override;
+
   /// Create a new code generation action.  If the optional \p _VMContext
   /// parameter is supplied, the action uses it without taking ownership,
   /// otherwise it creates a fresh LLVM context and takes ownership.
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f5289fb00c895e..3b920db56586f2 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3017,6 +3017,7 @@ defm prebuilt_implicit_modules : 
BoolFOption<"prebuilt-implicit-modules",
 
 def fmodule_output_EQ : Joined<["-"], "fmodule-output=">,
   Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>,
+  MarshallingInfoString>,
   HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
 def fmodule_output : Flag<["-"], "fmodule-output">, Flags<[NoXarchOption]>,
   Visibility<[ClangOption, CC1Option]>,
@@ -3030,6 +3031,11 @@ defm skip_odr_check_in_gmf : BoolOption<"f", 
"skip-odr-check-in-gmf",
   "Perform ODR checks for decls in the global module fragment.">>,
   Group;
 
+def gen_reduced_bmi : Flag<["-"], "fgen-reduced-bmi">,
+  Group, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Generate the reduced BMI">,
+  MarshallingInfoFlag>;
+
 def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, 
Group,
   Visibility<[ClangOption, CC1Option]>, MetaVarName<"">,
   HelpText<"Specify the interval (in seconds) between attempts to prune the 
module cache">,
diff --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 8085dbcbf671a6..ddfd4f30d1b773 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -387,6 +387,10 @@ class FrontendOptions {
   LLVM_PREFERRED_TYPE(bool)
   unsigned ModulesShareFileManager : 1;
 
+  /// Whether to generate reduced BMI for C++20 named modules.
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned GenReducedBMI : 1;
+
   CodeCompleteOptions CodeCompleteOpts;
 
   /// Specifies the output format of the AST.
@@ -553,6 +557,9 @@ class FrontendOptions {
   /// Path which stores the output files for -ftime-trace
   std::string TimeTracePath;
 
+  /// Output Path for module output file.
+  std::string ModuleOutputPath;
+
 public:
   FrontendOptions()
   : DisableFree(false), RelocatablePCH(false), ShowHelp(false),
@@ -565,7 +572,7 @@ class FrontendOptions {
 BuildingImplicitModuleUsesLock(true), ModulesEmbedAllFiles(false),
 IncludeTimestamps(true), UseTemporary(true),
 AllowPCMWithCompilerErrors(false), ModulesShareFileManager(true),
-TimeTraceGranularity(500) {}
+GenReducedBMI(false), TimeTraceGranularity(500) {}
 
   /// getInputKindForExtension - Return the appropriate input kind for a file
   /// extension. For example, "c" would return Language::C.
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 3ed9803fa3745b..bd310b6c7a5cdd 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -846,7 +846,7 @@ class ASTWriter : public ASTDeserializationListener,
 /// AST and semantic-analysis consumer that generates a
 /// precompiled header from the parsed source code.
 class PCHGenerator : public SemaConsumer {
-  

[clang] 21f85e2 - [NFC] [C++20] [Modules] Pulling out getCXX20NamedModuleOutputPath into a seperate function

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

Author: Chuanqi Xu
Date: 2024-04-02T09:58:59+08:00
New Revision: 21f85e230056172cffcaec76352e5a2019b54b86

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

LOG: [NFC] [C++20] [Modules] Pulling out getCXX20NamedModuleOutputPath into a 
seperate function

Required in the review process of
https://github.com/llvm/llvm-project/pull/85050.

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Clang.h

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 7a53764364ce4d..1a0f5f27eda2fc 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -5814,19 +5814,9 @@ static const char *GetModuleOutputPath(Compilation , 
const JobAction ,
  (C.getArgs().hasArg(options::OPT_fmodule_output) ||
   C.getArgs().hasArg(options::OPT_fmodule_output_EQ)));
 
-  if (Arg *ModuleOutputEQ =
-  C.getArgs().getLastArg(options::OPT_fmodule_output_EQ))
-return C.addResultFile(ModuleOutputEQ->getValue(), );
+  SmallString<256> OutputPath =
+  tools::getCXX20NamedModuleOutputPath(C.getArgs(), BaseInput);
 
-  SmallString<64> OutputPath;
-  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
-  if (FinalOutput && C.getArgs().hasArg(options::OPT_c))
-OutputPath = FinalOutput->getValue();
-  else
-OutputPath = BaseInput;
-
-  const char *Extension = types::getTypeTempSuffix(JA.getType());
-  llvm::sys::path::replace_extension(OutputPath, Extension);
   return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), );
 }
 

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 3bcacff7724c7d..b03ac6018d2b80 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3839,6 +3839,24 @@ bool 
Driver::getDefaultModuleCachePath(SmallVectorImpl ) {
   return false;
 }
 
+llvm::SmallString<256>
+clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList ,
+const char *BaseInput) {
+  if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
+return StringRef(ModuleOutputEQ->getValue());
+
+  SmallString<256> OutputPath;
+  if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
+  FinalOutput && Args.hasArg(options::OPT_c))
+OutputPath = FinalOutput->getValue();
+  else
+OutputPath = BaseInput;
+
+  const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
+  llvm::sys::path::replace_extension(OutputPath, Extension);
+  return OutputPath;
+}
+
 static bool RenderModulesOptions(Compilation , const Driver ,
  const ArgList , const InputInfo ,
  const InputInfo , bool HaveStd20,

diff  --git a/clang/lib/Driver/ToolChains/Clang.h 
b/clang/lib/Driver/ToolChains/Clang.h
index 0f503c4bd1c4fe..18f6c5ed06a59a 100644
--- a/clang/lib/Driver/ToolChains/Clang.h
+++ b/clang/lib/Driver/ToolChains/Clang.h
@@ -193,6 +193,21 @@ DwarfFissionKind getDebugFissionKind(const Driver ,
  const llvm::opt::ArgList ,
  llvm::opt::Arg *);
 
+// Calculate the output path of the module file when compiling a module unit
+// with the `-fmodule-output` option or `-fmodule-output=` option specified.
+// The behavior is:
+// - If `-fmodule-output=` is specfied, then the module file is
+//   writing to the value.
+// - Otherwise if the output object file of the module unit is specified, the
+// output path
+//   of the module file should be the same with the output object file except
+//   the corresponding suffix. This requires both `-o` and `-c` are specified.
+// - Otherwise, the output path of the module file will be the same with the
+//   input with the corresponding suffix.
+llvm::SmallString<256>
+getCXX20NamedModuleOutputPath(const llvm::opt::ArgList ,
+  const char *BaseInput);
+
 } // end namespace tools
 
 } // end namespace driver



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


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

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


@@ -3899,6 +3899,9 @@ static QualType 
GetDeclSpecTypeForDeclarator(TypeProcessingState ,
   SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
   << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   D.setInvalidType(true);
+  OwnedTagDecl->setCompleteDefinition(false);
+  OwnedTagDecl->setInvalidDecl();
+  OwnedTagDecl->setCompleteDefinition();

jcsxky wrote:

@shafik If I understand correctly, you want to set `OwnedTagDecl` invalid 
before it is a complete definition. I will look into the code.

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


[clang] [compiler-rt] [asan][windows] Eliminate the static asan runtime on windows (PR #81677)

2024-04-01 Thread Charlie Barto via cfe-commits

barcharcraz wrote:

@rnk @vitalybuka

This should be ready for a more in-depth review (I'll stop force-pushing)

The remaining commits here all depend on each-other in some way. Splitting off 
any more commits would mean introducing bugs into main until other parts of 
this are merged.



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


[clang] [InstallAPI] Fixup dsym test (PR #87299)

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

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


[clang] 30fd099 - [InstallAPI] Fixup dsym test (#87299)

2024-04-01 Thread via cfe-commits

Author: Cyndy Ishida
Date: 2024-04-01T18:30:23-07:00
New Revision: 30fd099d5062638b5fe6b89135ad6433a888023a

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

LOG: [InstallAPI] Fixup dsym test  (#87299)

Update the test to run when the compiler is built to support
arm64-darwin targets.

Added: 


Modified: 
clang/test/InstallAPI/diagnostics-dsym.test

Removed: 




diff  --git a/clang/test/InstallAPI/diagnostics-dsym.test 
b/clang/test/InstallAPI/diagnostics-dsym.test
index 8a1b394f2f8683..c9cbeffef7bacc 100644
--- a/clang/test/InstallAPI/diagnostics-dsym.test
+++ b/clang/test/InstallAPI/diagnostics-dsym.test
@@ -1,23 +1,24 @@
-; REQUIRES: 86_64-darwin
+; REQUIRES: system-darwin
+; REQUIRES: target-aarch64 
 
 ; RUN: rm -rf %t
 ; RUN: split-file %s %t
 
 // Build a simple dylib with debug info.
-; RUN: %clang --target=x86_64-apple-macos10.15 -g -dynamiclib %t/foo.c \
+; RUN: %clang --target=arm64-apple-macos11 -g -dynamiclib %t/foo.c \
 ; RUN: -current_version 1 -compatibility_version 1 -L%t/usr/lib \
 ; RUN: -save-temps \
 ; RUN: -o %t/foo.dylib -install_name %t/foo.dylib
 ; RUN: dsymutil %t/foo.dylib -o %t/foo.dSYM
 
-; RUN: not clang-installapi -x c++ --target=x86_64-apple-macos10.15 \
+; RUN: not clang-installapi -x c++ --target=arm64-apple-macos11 \
 ; RUN: -install_name %t/foo.dylib  \
 ; RUN: -current_version 1 -compatibility_version 1 \
 ; RUN: -o %t/output.tbd \
 ; RUN: --verify-against=%t/foo.dylib --dsym=%t/foo.dSYM \
 ; RUN: --verify-mode=Pedantic 2>&1 | FileCheck %s
 
-; CHECK: violations found for x86_64 
+; CHECK: violations found for arm64 
 ; CHECK: foo.c:5:0: error: no declaration found for exported symbol 'bar' in 
dynamic library
 ; CHECK: foo.c:1:0: error: no declaration found for exported symbol 'foo' in 
dynamic library
 
@@ -31,9 +32,9 @@ char bar = 'a';
 ;--- usr/lib/libSystem.tbd
 --- !tapi-tbd
 tbd-version: 4
-targets: [ x86_64-macos ]
+targets: [ arm64-macos ]
 install-name:'/usr/lib/libSystem.B.dylib'
 exports: 
-  - targets: [ x86_64-macos ]
+  - targets: [ arm64-macos ]
 symbols: [ dyld_stub_binder ]
 ...



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


[clang] [InstallAPI] Fixup dsym test (PR #87299)

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

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

>From fc2b73a261a0eddb19d49fcbbf301ec40a1d5ed2 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Mon, 1 Apr 2024 18:09:27 -0700
Subject: [PATCH] [InstallAPI] Fixup dsym test to actually run when compiler is
 built for arm64-darwin support

---
 clang/test/InstallAPI/diagnostics-dsym.test | 13 +++--
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/clang/test/InstallAPI/diagnostics-dsym.test 
b/clang/test/InstallAPI/diagnostics-dsym.test
index 8a1b394f2f8683..c9cbeffef7bacc 100644
--- a/clang/test/InstallAPI/diagnostics-dsym.test
+++ b/clang/test/InstallAPI/diagnostics-dsym.test
@@ -1,23 +1,24 @@
-; REQUIRES: 86_64-darwin
+; REQUIRES: system-darwin
+; REQUIRES: target-aarch64 
 
 ; RUN: rm -rf %t
 ; RUN: split-file %s %t
 
 // Build a simple dylib with debug info.
-; RUN: %clang --target=x86_64-apple-macos10.15 -g -dynamiclib %t/foo.c \
+; RUN: %clang --target=arm64-apple-macos11 -g -dynamiclib %t/foo.c \
 ; RUN: -current_version 1 -compatibility_version 1 -L%t/usr/lib \
 ; RUN: -save-temps \
 ; RUN: -o %t/foo.dylib -install_name %t/foo.dylib
 ; RUN: dsymutil %t/foo.dylib -o %t/foo.dSYM
 
-; RUN: not clang-installapi -x c++ --target=x86_64-apple-macos10.15 \
+; RUN: not clang-installapi -x c++ --target=arm64-apple-macos11 \
 ; RUN: -install_name %t/foo.dylib  \
 ; RUN: -current_version 1 -compatibility_version 1 \
 ; RUN: -o %t/output.tbd \
 ; RUN: --verify-against=%t/foo.dylib --dsym=%t/foo.dSYM \
 ; RUN: --verify-mode=Pedantic 2>&1 | FileCheck %s
 
-; CHECK: violations found for x86_64 
+; CHECK: violations found for arm64 
 ; CHECK: foo.c:5:0: error: no declaration found for exported symbol 'bar' in 
dynamic library
 ; CHECK: foo.c:1:0: error: no declaration found for exported symbol 'foo' in 
dynamic library
 
@@ -31,9 +32,9 @@ char bar = 'a';
 ;--- usr/lib/libSystem.tbd
 --- !tapi-tbd
 tbd-version: 4
-targets: [ x86_64-macos ]
+targets: [ arm64-macos ]
 install-name:'/usr/lib/libSystem.B.dylib'
 exports: 
-  - targets: [ x86_64-macos ]
+  - targets: [ arm64-macos ]
 symbols: [ dyld_stub_binder ]
 ...

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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-04-01 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

LGTM after addressing Aaron's comments.

Can you elaborate more on the details of the bug in the summary. This goes into 
the git log and we want folks to be able to understand the problem well from 
the summary w/o having to do additional checks.

Thank you

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


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

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


@@ -3899,6 +3899,9 @@ static QualType 
GetDeclSpecTypeForDeclarator(TypeProcessingState ,
   SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
   << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   D.setInvalidType(true);
+  OwnedTagDecl->setCompleteDefinition(false);
+  OwnedTagDecl->setInvalidDecl();
+  OwnedTagDecl->setCompleteDefinition();

jcsxky wrote:

@erichkeane Condition holds in outer `if`(line 3841) indicates `OwnedTagDecl` 
is a complete definition.

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


[clang] [InstallAPI] Fixup dsym test (PR #87299)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes

Update the test to run when the compiler is built to support arm64-darwin 
targets.

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


1 Files Affected:

- (modified) clang/test/InstallAPI/diagnostics-dsym.test (+7-6) 


``diff
diff --git a/clang/test/InstallAPI/diagnostics-dsym.test 
b/clang/test/InstallAPI/diagnostics-dsym.test
index 8a1b394f2f8683..c9cbeffef7bacc 100644
--- a/clang/test/InstallAPI/diagnostics-dsym.test
+++ b/clang/test/InstallAPI/diagnostics-dsym.test
@@ -1,23 +1,24 @@
-; REQUIRES: 86_64-darwin
+; REQUIRES: system-darwin
+; REQUIRES: target-aarch64 
 
 ; RUN: rm -rf %t
 ; RUN: split-file %s %t
 
 // Build a simple dylib with debug info.
-; RUN: %clang --target=x86_64-apple-macos10.15 -g -dynamiclib %t/foo.c \
+; RUN: %clang --target=arm64-apple-macos11 -g -dynamiclib %t/foo.c \
 ; RUN: -current_version 1 -compatibility_version 1 -L%t/usr/lib \
 ; RUN: -save-temps \
 ; RUN: -o %t/foo.dylib -install_name %t/foo.dylib
 ; RUN: dsymutil %t/foo.dylib -o %t/foo.dSYM
 
-; RUN: not clang-installapi -x c++ --target=x86_64-apple-macos10.15 \
+; RUN: not clang-installapi -x c++ --target=arm64-apple-macos11 \
 ; RUN: -install_name %t/foo.dylib  \
 ; RUN: -current_version 1 -compatibility_version 1 \
 ; RUN: -o %t/output.tbd \
 ; RUN: --verify-against=%t/foo.dylib --dsym=%t/foo.dSYM \
 ; RUN: --verify-mode=Pedantic 2>&1 | FileCheck %s
 
-; CHECK: violations found for x86_64 
+; CHECK: violations found for arm64 
 ; CHECK: foo.c:5:0: error: no declaration found for exported symbol 'bar' in 
dynamic library
 ; CHECK: foo.c:1:0: error: no declaration found for exported symbol 'foo' in 
dynamic library
 
@@ -31,9 +32,9 @@ char bar = 'a';
 ;--- usr/lib/libSystem.tbd
 --- !tapi-tbd
 tbd-version: 4
-targets: [ x86_64-macos ]
+targets: [ arm64-macos ]
 install-name:'/usr/lib/libSystem.B.dylib'
 exports: 
-  - targets: [ x86_64-macos ]
+  - targets: [ arm64-macos ]
 symbols: [ dyld_stub_binder ]
 ...

``




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


[clang] [InstallAPI] Fixup dsym test (PR #87299)

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

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/87299

Update the test to run when the compiler is built to support arm64-darwin 
targets.

>From fc2b73a261a0eddb19d49fcbbf301ec40a1d5ed2 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Mon, 1 Apr 2024 18:09:27 -0700
Subject: [PATCH] [InstallAPI] Fixup dsym test to actually run when compiler is
 built for arm64-darwin support

---
 clang/test/InstallAPI/diagnostics-dsym.test | 13 +++--
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/clang/test/InstallAPI/diagnostics-dsym.test 
b/clang/test/InstallAPI/diagnostics-dsym.test
index 8a1b394f2f8683..c9cbeffef7bacc 100644
--- a/clang/test/InstallAPI/diagnostics-dsym.test
+++ b/clang/test/InstallAPI/diagnostics-dsym.test
@@ -1,23 +1,24 @@
-; REQUIRES: 86_64-darwin
+; REQUIRES: system-darwin
+; REQUIRES: target-aarch64 
 
 ; RUN: rm -rf %t
 ; RUN: split-file %s %t
 
 // Build a simple dylib with debug info.
-; RUN: %clang --target=x86_64-apple-macos10.15 -g -dynamiclib %t/foo.c \
+; RUN: %clang --target=arm64-apple-macos11 -g -dynamiclib %t/foo.c \
 ; RUN: -current_version 1 -compatibility_version 1 -L%t/usr/lib \
 ; RUN: -save-temps \
 ; RUN: -o %t/foo.dylib -install_name %t/foo.dylib
 ; RUN: dsymutil %t/foo.dylib -o %t/foo.dSYM
 
-; RUN: not clang-installapi -x c++ --target=x86_64-apple-macos10.15 \
+; RUN: not clang-installapi -x c++ --target=arm64-apple-macos11 \
 ; RUN: -install_name %t/foo.dylib  \
 ; RUN: -current_version 1 -compatibility_version 1 \
 ; RUN: -o %t/output.tbd \
 ; RUN: --verify-against=%t/foo.dylib --dsym=%t/foo.dSYM \
 ; RUN: --verify-mode=Pedantic 2>&1 | FileCheck %s
 
-; CHECK: violations found for x86_64 
+; CHECK: violations found for arm64 
 ; CHECK: foo.c:5:0: error: no declaration found for exported symbol 'bar' in 
dynamic library
 ; CHECK: foo.c:1:0: error: no declaration found for exported symbol 'foo' in 
dynamic library
 
@@ -31,9 +32,9 @@ char bar = 'a';
 ;--- usr/lib/libSystem.tbd
 --- !tapi-tbd
 tbd-version: 4
-targets: [ x86_64-macos ]
+targets: [ arm64-macos ]
 install-name:'/usr/lib/libSystem.B.dylib'
 exports: 
-  - targets: [ x86_64-macos ]
+  - targets: [ arm64-macos ]
 symbols: [ dyld_stub_binder ]
 ...

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


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

2024-04-01 Thread Shafik Yaghmour via cfe-commits


@@ -3899,6 +3899,9 @@ static QualType 
GetDeclSpecTypeForDeclarator(TypeProcessingState ,
   SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
   << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   D.setInvalidType(true);
+  OwnedTagDecl->setCompleteDefinition(false);
+  OwnedTagDecl->setInvalidDecl();
+  OwnedTagDecl->setCompleteDefinition();

shafik wrote:

`GetDeclSpecTypeForDeclarator` is called from two places 
`GetTypeForDeclaratorCast(...)` and where that is called `D.isInvalidType()` is 
checked. It is also called from `GetTypeForDeclarator(...)` and the checking of 
after that call is a bit more varied. I am wondering if we are being sloppy in 
one of those calls. 

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


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

2024-04-01 Thread Shafik Yaghmour via cfe-commits


@@ -3899,6 +3899,9 @@ static QualType 
GetDeclSpecTypeForDeclarator(TypeProcessingState ,
   SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
   << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   D.setInvalidType(true);
+  OwnedTagDecl->setCompleteDefinition(false);
+  OwnedTagDecl->setInvalidDecl();
+  OwnedTagDecl->setCompleteDefinition();

shafik wrote:

I am little uncomfortable with this change here, I see that you are calling 
`setCompleteDefinition(false)` in order to get around the `assert` that the 
decl is not complete in `Decl::setInvalidDecl(...)`. If this precondition is 
not true we need to understand why it break down or if this implies we should 
be handling this differently.

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


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

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,278 @@
+//===--- 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 "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  //   check if the function has initializer list argument
+  if (Call->getNumArgs() < 3) {
+auto ArgIterator = Call->arguments().begin();
+
+const auto *InitListExpr =
+dyn_cast(*ArgIterator);
+const auto *InitList =
+InitListExpr != nullptr
+? dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())
+: nullptr;
+
+if (InitListExpr && InitList) {
+  Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+ InitList->inits().end());
+  Result.First = *ArgIterator;
+  Result.Last = *ArgIterator;
+
+  // check if there is a comparison argument
+  std::advance(ArgIterator, 1);
+  if (ArgIterator != Call->arguments().end()) {
+Result.Compare = *ArgIterator;
+  }
+
+  return Result;
+}
+// if it has 3 arguments then the last will be the comparison
+  } else {
+Result.Compare = *(std::next(Call->arguments().begin(), 2));
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static SmallVector
+generateReplacement(const MatchFinder::MatchResult ,
+const CallExpr *TopCall, const FindArgsResult ) {
+  SmallVector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const auto  = *Match.SourceManager;
+  const auto LanguageOpts = Match.Context->getLangOpts();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  // add { and } if the top call doesn't have an initializer list arg
+  if (!IsInitializerList) {
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+if (Result.Compare)
+  FixItHints.push_back(FixItHint::CreateInsertion(
+  Lexer::getLocForEndOfToken(Result.Last->getEndLoc(), 0, SourceMngr,
+ LanguageOpts),
+  "}"));
+else
+  FixItHints.push_back(
+  FixItHint::CreateInsertion(TopCall->getEndLoc(), "}"));
+  }
+
+  for (const Expr *Arg : Result.Args) {
+const auto *InnerCall = dyn_cast(Arg->IgnoreParenImpCasts());
+
+// If the argument is not a nested call
+if (!InnerCall) {
+  // check if typecast is required
+  const QualType ArgType = Arg->IgnoreParenImpCasts()
+   ->getType()
+   .getUnqualifiedType()
+   .getCanonicalType();
+
+  if (ArgType == ResultType)
+continue;
+
+  const StringRef ArgText = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Arg->getSourceRange()), SourceMngr,
+  LanguageOpts);
+
+  Twine Replacement = llvm::Twine("static_cast<")
+  .concat(ResultType.getAsString(LanguageOpts))
+  .concat(">(")
+  .concat(ArgText)
+  .concat(")");
+
+  FixItHints.push_back(FixItHint::CreateReplacement(Arg->getSourceRange(),
+Replacement.str()));
+
+  continue;
+}
+
+const auto InnerResult = findArgs(InnerCall);
+const auto InnerReplacements =
+generateReplacement(Match, InnerCall, InnerResult);
+const bool IsInnerInitializerList = InnerResult.First == InnerResult.Last;
+
+// if the nested call doesn't have arguments skip it
+if (!InnerResult.First || !InnerResult.Last)
+  continue;
+
+// if the nested call is not the same 

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

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,278 @@
+//===--- 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 "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  //   check if the function has initializer list argument
+  if (Call->getNumArgs() < 3) {
+auto ArgIterator = Call->arguments().begin();
+
+const auto *InitListExpr =
+dyn_cast(*ArgIterator);
+const auto *InitList =
+InitListExpr != nullptr
+? dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())
+: nullptr;
+
+if (InitListExpr && InitList) {
+  Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+ InitList->inits().end());
+  Result.First = *ArgIterator;
+  Result.Last = *ArgIterator;
+
+  // check if there is a comparison argument
+  std::advance(ArgIterator, 1);
+  if (ArgIterator != Call->arguments().end()) {
+Result.Compare = *ArgIterator;
+  }
+
+  return Result;
+}
+// if it has 3 arguments then the last will be the comparison
+  } else {
+Result.Compare = *(std::next(Call->arguments().begin(), 2));
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static SmallVector
+generateReplacement(const MatchFinder::MatchResult ,
+const CallExpr *TopCall, const FindArgsResult ) {
+  SmallVector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const auto  = *Match.SourceManager;
+  const auto LanguageOpts = Match.Context->getLangOpts();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  // add { and } if the top call doesn't have an initializer list arg
+  if (!IsInitializerList) {
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+if (Result.Compare)
+  FixItHints.push_back(FixItHint::CreateInsertion(
+  Lexer::getLocForEndOfToken(Result.Last->getEndLoc(), 0, SourceMngr,
+ LanguageOpts),

sopyb wrote:

I even went ahead and debugged it to make sure Result.Last is the correct Expr 
and it is. I was unable to figure out why it is happening

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-04-01 Thread via cfe-commits


@@ -0,0 +1,278 @@
+//===--- 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 "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  //   check if the function has initializer list argument
+  if (Call->getNumArgs() < 3) {
+auto ArgIterator = Call->arguments().begin();
+
+const auto *InitListExpr =
+dyn_cast(*ArgIterator);
+const auto *InitList =
+InitListExpr != nullptr
+? dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())
+: nullptr;
+
+if (InitListExpr && InitList) {
+  Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+ InitList->inits().end());
+  Result.First = *ArgIterator;
+  Result.Last = *ArgIterator;
+
+  // check if there is a comparison argument
+  std::advance(ArgIterator, 1);
+  if (ArgIterator != Call->arguments().end()) {
+Result.Compare = *ArgIterator;
+  }
+
+  return Result;
+}
+// if it has 3 arguments then the last will be the comparison
+  } else {
+Result.Compare = *(std::next(Call->arguments().begin(), 2));
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static SmallVector
+generateReplacement(const MatchFinder::MatchResult ,
+const CallExpr *TopCall, const FindArgsResult ) {
+  SmallVector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const auto  = *Match.SourceManager;
+  const auto LanguageOpts = Match.Context->getLangOpts();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  // add { and } if the top call doesn't have an initializer list arg
+  if (!IsInitializerList) {
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+if (Result.Compare)
+  FixItHints.push_back(FixItHint::CreateInsertion(
+  Lexer::getLocForEndOfToken(Result.Last->getEndLoc(), 0, SourceMngr,
+ LanguageOpts),

sopyb wrote:

Weird because on my side I get stuff like `int max2c = std::max({1, 2, 3, }4);` 
happening where the token would just decide to go before the last argument 
despite using getEndLoc()

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-04-01 Thread via cfe-commits


@@ -0,0 +1,278 @@
+//===--- 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 "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  //   check if the function has initializer list argument
+  if (Call->getNumArgs() < 3) {
+auto ArgIterator = Call->arguments().begin();
+
+const auto *InitListExpr =
+dyn_cast(*ArgIterator);
+const auto *InitList =
+InitListExpr != nullptr
+? dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())
+: nullptr;
+
+if (InitListExpr && InitList) {
+  Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+ InitList->inits().end());
+  Result.First = *ArgIterator;
+  Result.Last = *ArgIterator;
+
+  // check if there is a comparison argument
+  std::advance(ArgIterator, 1);
+  if (ArgIterator != Call->arguments().end()) {
+Result.Compare = *ArgIterator;
+  }
+
+  return Result;
+}
+// if it has 3 arguments then the last will be the comparison
+  } else {
+Result.Compare = *(std::next(Call->arguments().begin(), 2));
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static SmallVector
+generateReplacement(const MatchFinder::MatchResult ,
+const CallExpr *TopCall, const FindArgsResult ) {
+  SmallVector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const auto  = *Match.SourceManager;
+  const auto LanguageOpts = Match.Context->getLangOpts();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  // add { and } if the top call doesn't have an initializer list arg
+  if (!IsInitializerList) {
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+if (Result.Compare)
+  FixItHints.push_back(FixItHint::CreateInsertion(
+  Lexer::getLocForEndOfToken(Result.Last->getEndLoc(), 0, SourceMngr,
+ LanguageOpts),
+  "}"));
+else
+  FixItHints.push_back(
+  FixItHint::CreateInsertion(TopCall->getEndLoc(), "}"));
+  }
+
+  for (const Expr *Arg : Result.Args) {
+const auto *InnerCall = dyn_cast(Arg->IgnoreParenImpCasts());
+
+// If the argument is not a nested call
+if (!InnerCall) {
+  // check if typecast is required
+  const QualType ArgType = Arg->IgnoreParenImpCasts()
+   ->getType()
+   .getUnqualifiedType()
+   .getCanonicalType();
+
+  if (ArgType == ResultType)
+continue;
+
+  const StringRef ArgText = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Arg->getSourceRange()), SourceMngr,
+  LanguageOpts);
+
+  Twine Replacement = llvm::Twine("static_cast<")
+  .concat(ResultType.getAsString(LanguageOpts))
+  .concat(">(")
+  .concat(ArgText)
+  .concat(")");
+
+  FixItHints.push_back(FixItHint::CreateReplacement(Arg->getSourceRange(),
+Replacement.str()));
+
+  continue;
+}
+
+const auto InnerResult = findArgs(InnerCall);
+const auto InnerReplacements =
+generateReplacement(Match, InnerCall, InnerResult);
+const bool IsInnerInitializerList = InnerResult.First == InnerResult.Last;
+
+// if the nested call doesn't have arguments skip it
+if (!InnerResult.First || !InnerResult.Last)
+  continue;
+
+// if the nested call is not the same 

[clang] [Clang][CodeGen] Fix `CanSkipVTablePointerInitialization` for dynamic classes with a trivial anonymous union (PR #84651)

2024-04-01 Thread Max Winkler via cfe-commits

https://github.com/MaxEW707 updated 
https://github.com/llvm/llvm-project/pull/84651

>From 28cbaad3c16e985306c7b977cb7d9e8e89c39a07 Mon Sep 17 00:00:00 2001
From: MaxEW707 <82551778+maxew...@users.noreply.github.com>
Date: Sat, 9 Mar 2024 15:40:52 -0500
Subject: [PATCH 1/2] Fix `CanSkipVTablePointerInitialization` for dynamic
 classes with an anonymous union

---
 clang/lib/CodeGen/CGClass.cpp |  2 +-
 .../skip-vtable-pointer-initialization.cpp| 63 +++
 2 files changed, 64 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index d18f186ce5b415..ca3ac7142af9c0 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -1395,7 +1395,7 @@ FieldHasTrivialDestructorBody(ASTContext ,
 
   // The destructor for an implicit anonymous union member is never invoked.
   if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
-return false;
+return true;
 
   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
 }
diff --git a/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp 
b/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
index eb8f21b57aa7b6..d99a45869fdb54 100644
--- a/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
+++ b/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | 
FileCheck %s
+// RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -emit-llvm -o - | FileCheck 
%s
 
 // See Test9 for test description.
 // CHECK: @_ZTTN5Test91BE = linkonce_odr unnamed_addr constant
@@ -198,3 +199,65 @@ struct C : virtual B {
 C::~C() {}
 
 }
+
+namespace Test10 {
+
+// Check that we don't initialize the vtable pointer in A::~A(), since the 
class has an anonymous union which
+// never has its destructor invoked.
+struct A {
+virtual void f();
+~A();
+
+union
+{
+int i;
+unsigned u;
+};
+};
+
+// CHECK-LABEL: define{{.*}} void @_ZN6Test101AD2Ev
+// CHECK-NOT: store ptr getelementptr inbounds ({ [3 x ptr] }, ptr 
@_ZTVN6Test101AE, i32 0, inrange i32 0, i32 2), ptr
+A::~A() {
+}
+
+}
+
+namespace Test11 {
+
+// Check that we don't initialize the vtable pointer in A::~A(), even if the 
base class has a non trivial destructor.
+struct Field {
+~Field();
+};
+
+struct A : public Field {
+virtual void f();
+~A();
+};
+
+// CHECK-LABEL: define{{.*}} void @_ZN6Test111AD2Ev
+// CHECK-NOT: store ptr getelementptr inbounds ({ [3 x ptr] }, ptr 
@_ZTVN6Test111AE, i32 0, inrange i32 0, i32 2), ptr
+A::~A() {
+}
+
+}
+
+namespace Test12 {
+
+// Check that we don't initialize the vtable pointer in A::~A(), since the 
class has an anonymous struct with trivial fields.
+struct A {
+virtual void f();
+~A();
+
+struct
+{
+int i;
+unsigned u;
+};
+};
+
+// CHECK-LABEL: define{{.*}} void @_ZN6Test121AD2Ev
+// CHECK-NOT: store ptr getelementptr inbounds ({ [3 x ptr] }, ptr 
@_ZTVN6Test121AE, i32 0, inrange i32 0, i32 2), ptr
+A::~A() {
+}
+
+}

>From fd190fb64877636c94cbaf73d1977018e592a622 Mon Sep 17 00:00:00 2001
From: MaxEW707 
Date: Mon, 1 Apr 2024 20:36:54 -0400
Subject: [PATCH 2/2] remove RUN line in unit test

---
 clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp 
b/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
index d99a45869fdb54..9c5388fd64a502 100644
--- a/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
+++ b/clang/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | 
FileCheck %s
-// RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -emit-llvm -o - | FileCheck 
%s
 
 // See Test9 for test description.
 // CHECK: @_ZTTN5Test91BE = linkonce_odr unnamed_addr constant

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


[clang] [Clang][CodeGen] Fix `CanSkipVTablePointerInitialization` for dynamic classes with a trivial anonymous union (PR #84651)

2024-04-01 Thread Max Winkler via cfe-commits


@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | 
FileCheck %s
+// RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -emit-llvm -o - | FileCheck 
%s

MaxEW707 wrote:

Fair point since they are both Itanium ABI. I'll remove the line.

https://github.com/llvm/llvm-project/pull/84651
___
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-04-01 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] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-04-01 Thread William Junda Huang via cfe-commits

huangjd wrote:

I am making another diff (not to be submitted) to get statistics on how 
frequently these 2 cases are encountered 

https://github.com/llvm/llvm-project/pull/81545
___
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-04-01 Thread via cfe-commits


@@ -0,0 +1,278 @@
+//===--- 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 "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  //   check if the function has initializer list argument
+  if (Call->getNumArgs() < 3) {
+auto ArgIterator = Call->arguments().begin();
+
+const auto *InitListExpr =
+dyn_cast(*ArgIterator);
+const auto *InitList =
+InitListExpr != nullptr
+? dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())
+: nullptr;
+
+if (InitListExpr && InitList) {
+  Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+ InitList->inits().end());
+  Result.First = *ArgIterator;
+  Result.Last = *ArgIterator;
+
+  // check if there is a comparison argument
+  std::advance(ArgIterator, 1);
+  if (ArgIterator != Call->arguments().end()) {
+Result.Compare = *ArgIterator;
+  }
+
+  return Result;
+}
+// if it has 3 arguments then the last will be the comparison
+  } else {
+Result.Compare = *(std::next(Call->arguments().begin(), 2));
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static SmallVector
+generateReplacement(const MatchFinder::MatchResult ,
+const CallExpr *TopCall, const FindArgsResult ) {
+  SmallVector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const auto  = *Match.SourceManager;
+  const auto LanguageOpts = Match.Context->getLangOpts();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  // add { and } if the top call doesn't have an initializer list arg
+  if (!IsInitializerList) {
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+if (Result.Compare)
+  FixItHints.push_back(FixItHint::CreateInsertion(
+  Lexer::getLocForEndOfToken(Result.Last->getEndLoc(), 0, SourceMngr,
+ LanguageOpts),
+  "}"));
+else
+  FixItHints.push_back(
+  FixItHint::CreateInsertion(TopCall->getEndLoc(), "}"));
+  }
+
+  for (const Expr *Arg : Result.Args) {
+const auto *InnerCall = dyn_cast(Arg->IgnoreParenImpCasts());
+
+// If the argument is not a nested call
+if (!InnerCall) {
+  // check if typecast is required
+  const QualType ArgType = Arg->IgnoreParenImpCasts()
+   ->getType()
+   .getUnqualifiedType()
+   .getCanonicalType();
+
+  if (ArgType == ResultType)
+continue;
+
+  const StringRef ArgText = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Arg->getSourceRange()), SourceMngr,
+  LanguageOpts);
+
+  Twine Replacement = llvm::Twine("static_cast<")
+  .concat(ResultType.getAsString(LanguageOpts))
+  .concat(">(")
+  .concat(ArgText)
+  .concat(")");
+
+  FixItHints.push_back(FixItHint::CreateReplacement(Arg->getSourceRange(),
+Replacement.str()));
+
+  continue;
+}
+
+const auto InnerResult = findArgs(InnerCall);
+const auto InnerReplacements =
+generateReplacement(Match, InnerCall, InnerResult);
+const bool IsInnerInitializerList = InnerResult.First == InnerResult.Last;
+
+// if the nested call doesn't have arguments skip it
+if (!InnerResult.First || !InnerResult.Last)
+  continue;
+
+// if the nested call is not the same 

[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-04-01 Thread William Junda Huang via cfe-commits

huangjd wrote:

> > > Reading LLVM IR lit CHECK lines from clang codegen is a bit difficult - 
> > > could you include some simple examples (perhaps from the new clang tests 
> > > in this patch) showing the DWARF output just as comments in this review 
> > > for something more easily glanceable?
> > 
> > 
> > Attached is the output of the following command
> > `clang ~/llvm-project/clang/test/CodeGenCXX/debug-info-ptr-to-ptr.cpp 
> > -fdebug-info-for-pointer-type -g2 -S -O3 -o /tmp/debug-info-ptr-to-ptr.txt`
> > [debug-info-ptr-to-ptr.txt](https://github.com/llvm/llvm-project/files/14659111/debug-info-ptr-to-ptr.txt)
> 
> Thanks - OK, so this only applies to intermediate structures and arrays (is 
> it useful for arrays? You can't really reorder them - learning that the hot 
> part of an array is the 5th-10th element might be of limited (or at least 
> sufficiently different from the struct layout stuff) value - and it's a more 
> dynamic property/has a runtime parameter component that might be harder to 
> use?)
> 
> Do you have size impact numbers for this? I wouldn't put this under a 
> (possibly cc1) flag for now unless we've got some pretty compelling data that 
> this doesn't substantially change debug info size, which would be a bit 
> surprising to me - I'd assume this would be quite expensive, but it's just a 
> guess.

For clarification,
LLVM previously supported: 
`int foo(A* a) { return a->i; }`  In this case the type of variable `a` is 
emitted, and for the instruction `mov 8(%rdi), %rax` (assume offset is 8), the 
debug info emitted for this instruction associates `%rdi` to `a`, and by 
looking up the data layout in A's type info, we know which field is accessed.

This patch handles two cases that are previously not supported.
1. `int foo(void* a) { return ((A*)a)->i; }` Previously only the debug info of 
void pointer type `a` is emitted, and it is still associated to `%rdi`, so we 
couldn't deduce what is being accessed from that instruction. In this patch, it 
emits a pseudo variable in addition, which is also associated to `%rdi`, and it 
has the correct type info when traversing the member expression. 

2. `int foo(B* b) { return b->a->i; }` Previously only the debug info of `b` is 
emitted, but not the intermediate value, so for the second `mov` instruction 
emitted, it could not associate the memory operand to any variable. In this 
patch it emits a pseudo variable for intermediate values if it is used as the 
pointer operand in a member expr. 

It should apply to array, if the expression actually ends up in an instruction 
like `mov 8(%rdi), %rax`. I have test cases for it, and assembly dump also 
shows the memory operand is correlated to the pseudo variable. Note that in 
most use cases the presence of array is actually irrelevant because we are not 
type casting the array element itself ( `((A&)foo[i]).member`, that's generally 
invalid), instead we type cast the pointer (`((A*) foo[i])->member`) in this 
case whatever being type casted doesn't matter because it's case 1.

As for impact, I believe @namhyung did some measurement for building the Linux 
kernel, and it does not have a significant impact. 


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


[clang] [llvm] [HLSL][DXIL][SPIRV] Intrinsic unification PR (PR #87171)

2024-04-01 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/87171

>From dcf4896ca4d86a34a731f31e7dc42e271a62a02f Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 28 Mar 2024 21:05:36 -0400
Subject: [PATCH 1/2] [HLSL][DXIL][SPIRV] Intrinsic unification PR

---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  19 ++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 112 +++
 clang/lib/Sema/SemaChecking.cpp   |   1 +
 clang/test/CodeGenHLSL/builtins/all.hlsl  | 277 ++
 llvm/include/llvm/IR/Intrinsics.td|  12 +
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   4 +-
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |   3 +-
 .../Target/SPIRV/SPIRVInstructionSelector.cpp |  19 ++
 .../test/CodeGen/SPIRV/hlsl-intrinsics/all.ll |  95 ++
 10 files changed, 545 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/all.hlsl
 create mode 100644 llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bb007231c0b783..add7ec1fa0eb45 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -51,6 +51,7 @@
 #include "llvm/IR/IntrinsicsR600.h"
 #include "llvm/IR/IntrinsicsRISCV.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/IntrinsicsVE.h"
 #include "llvm/IR/IntrinsicsWebAssembly.h"
 #include "llvm/IR/IntrinsicsX86.h"
@@ -18176,12 +18177,30 @@ Intrinsic::ID getDotProductIntrinsic(QualType QT, int 
elementCount) {
   return Intrinsic::dx_udot;
 }
 
+Intrinsic::ID getAllIntrinsic(const llvm::Triple::ArchType Arch) {
+  switch (Arch) {
+  case llvm::Triple::dxil:
+return Intrinsic::dx_all;
+  case llvm::Triple::spirv:
+return Intrinsic::spv_all;
+  default:
+llvm_unreachable("Input semantic not supported by target");
+  }
+}
+
 Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
 const CallExpr *E) {
   if (!getLangOpts().HLSL)
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+getAllIntrinsic(CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 9fb6204f90c9a8..06409c6fc77417 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -100,6 +100,118 @@ double3 abs(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_abs)
 double4 abs(double4);
 
+//===--===//
+// all builtins
+//===--===//
+
+/// \fn bool all(T x)
+/// \brief Returns True if all components of the \a x parameter are non-zero;
+/// otherwise, false. \param x The input value.
+
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t4);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t4);
+#endif
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(half);

[clang] [DebugInfo] Add flag to only emit referenced member functions (PR #87018)

2024-04-01 Thread Adrian Prantl via cfe-commits

adrian-prantl wrote:

Seems to be a reasonable tuning option to have available. I probably wouldn't 
want this to be on by default, but I can see the appeal.

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


[clang] [BitInt] Expose a _BitInt literal suffix in C++ (PR #86586)

2024-04-01 Thread Richard Smith via cfe-commits


@@ -1117,19 +1118,37 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
   if (isImaginary) break;   // Cannot be repeated.
   isImaginary = true;
   continue;  // Success.
+case '_':
+  if (isFPConstant)
+break; // Invalid for floats
+  if (HasSize)
+break;
+  if (possibleBitInt)
+break; // Cannot be repeated.
+  if (LangOpts.CPlusPlus && s[1] == '_') {
+// Scan ahead to find possible rest of BitInt suffix
+for (const char *c = s; c != ThisTokEnd; ++c) {
+  if (*c == 'w' || *c == 'W') {
+possibleBitInt = true;
+++s;

zygoloid wrote:

FYI, per CWG1810 / [over.literal]/1, it's now IFNDR rather than UB:

> Some literal suffix identifiers are reserved for future standardization; see 
> [usrlit.suffix]. A declaration whose literal-operator-id uses such a literal 
> suffix identifier is ill-formed, no diagnostic required.

... but that doesn't make a difference here. (The "NDR" part is just to allow 
implementations to permit the standard library to declare these literal 
operators.)

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


[clang] [clang][Sema] Ignore the parentheses in the guard of DiagnoseUnexpandedParameterPack (PR #86401)

2024-04-01 Thread David Blaikie via cfe-commits

dwblaikie wrote:

Thanks for continuing to look into this!

@cor3ntin - perhaps you've got some more thoughts on this too?

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


[clang] [M68k] Change gcc register name from a7 to sp. (PR #87095)

2024-04-01 Thread Jim Lin via cfe-commits

tclin914 wrote:

> Is it possible use `TargetInfo::getGCCRegAliases` to model the aliasing 
> between a7 and sp? Also, could you add a simple test?

Implement getGCCRegAliases and add testcase.

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


[clang] [OpenMP] Use loaded offloading toolchains to add libraries (PR #87108)

2024-04-01 Thread Joseph Huber via cfe-commits

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


[clang] f2a87b0 - [OpenMP] Use loaded offloading toolchains to add libraries (#87108)

2024-04-01 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-04-01T17:26:20-05:00
New Revision: f2a87b07e7fe1892a11ee9424d22dbaec5de5b5b

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

LOG: [OpenMP] Use loaded offloading toolchains to add libraries (#87108)

Summary:
We want to pass these GPU libraries by default if a certain offloading
toolchain is loaded for OpenMP. Previously I parsed this from the
arguments because it's only available in the compilation. This doesn't
really work for `native` and it's extra effort, so this patch just
passes in the `Compilation` as an extr argument and uses that. Tests
should be unaffected.

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/CommonArgs.h
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/DragonFly.cpp
clang/lib/Driver/ToolChains/FreeBSD.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/Haiku.cpp
clang/lib/Driver/ToolChains/NetBSD.cpp
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/lib/Driver/ToolChains/Solaris.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index ace4fb99581e38..62a53b85ce098b 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1075,14 +1075,14 @@ void tools::addLTOOptions(const ToolChain , 
const ArgList ,
 
 /// Adds the '-lcgpu' and '-lmgpu' libraries to the compilation to include the
 /// LLVM C library for GPUs.
-static void addOpenMPDeviceLibC(const ToolChain , const ArgList ,
+static void addOpenMPDeviceLibC(const Compilation , const ArgList ,
 ArgStringList ) {
   if (Args.hasArg(options::OPT_nogpulib) || Args.hasArg(options::OPT_nolibc))
 return;
 
   // Check the resource directory for the LLVM libc GPU declarations. If it's
   // found we can assume that LLVM was built with support for the GPU libc.
-  SmallString<256> LibCDecls(TC.getDriver().ResourceDir);
+  SmallString<256> LibCDecls(C.getDriver().ResourceDir);
   llvm::sys::path::append(LibCDecls, "include", "llvm_libc_wrappers",
   "llvm-libc-decls");
   bool HasLibC = llvm::sys::fs::exists(LibCDecls) &&
@@ -1090,38 +1090,23 @@ static void addOpenMPDeviceLibC(const ToolChain , 
const ArgList ,
   if (!Args.hasFlag(options::OPT_gpulibc, options::OPT_nogpulibc, HasLibC))
 return;
 
-  // We don't have access to the offloading toolchains here, so determine from
-  // the arguments if we have any active NVPTX or AMDGPU toolchains.
-  llvm::DenseSet Libraries;
-  if (const Arg *Targets = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
-if (llvm::any_of(Targets->getValues(),
- [](auto S) { return llvm::Triple(S).isAMDGPU(); })) {
-  Libraries.insert("-lcgpu-amdgpu");
-  Libraries.insert("-lmgpu-amdgpu");
-}
-if (llvm::any_of(Targets->getValues(),
- [](auto S) { return llvm::Triple(S).isNVPTX(); })) {
-  Libraries.insert("-lcgpu-nvptx");
-  Libraries.insert("-lmgpu-nvptx");
-}
-  }
+  SmallVector ToolChains;
+  auto TCRange = C.getOffloadToolChains(Action::OFK_OpenMP);
+  for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
+ToolChains.push_back(TI->second);
 
-  for (StringRef Arch : Args.getAllArgValues(options::OPT_offload_arch_EQ)) {
-if (llvm::any_of(llvm::split(Arch, ","), [](StringRef Str) {
-  return IsAMDGpuArch(StringToCudaArch(Str));
-})) {
-  Libraries.insert("-lcgpu-amdgpu");
-  Libraries.insert("-lmgpu-amdgpu");
-}
-if (llvm::any_of(llvm::split(Arch, ","), [](StringRef Str) {
-  return IsNVIDIAGpuArch(StringToCudaArch(Str));
-})) {
-  Libraries.insert("-lcgpu-nvptx");
-  Libraries.insert("-lmgpu-nvptx");
-}
+  if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
+return TC->getTriple().isAMDGPU();
+  })) {
+CmdArgs.push_back("-lcgpu-amdgpu");
+CmdArgs.push_back("-lmgpu-amdgpu");
+  }
+  if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
+return TC->getTriple().isNVPTX();
+  })) {
+CmdArgs.push_back("-lcgpu-nvptx");
+CmdArgs.push_back("-lmgpu-nvptx");
   }
-
-  llvm::append_range(CmdArgs, Libraries);
 }
 
 void tools::addOpenMPRuntimeLibraryPath(const ToolChain ,
@@ -1153,9 +1138,10 @@ void tools::addArchSpecificRPath(const ToolChain , 
const ArgList ,
   }
 }
 
-bool tools::addOpenMPRuntime(ArgStringList , const ToolChain ,
- const ArgList , bool ForceStaticHostRuntime,
- bool IsOffloadingHost, bool GompNeedsRT) {
+bool tools::addOpenMPRuntime(const Compilation , ArgStringList ,
+ 

[clang] [M68k] Change gcc register name from a7 to sp. (PR #87095)

2024-04-01 Thread Jim Lin via cfe-commits

https://github.com/tclin914 updated 
https://github.com/llvm/llvm-project/pull/87095

>From dec6021133f67304bfc9942a1a4985cce6a15645 Mon Sep 17 00:00:00 2001
From: Jim Lin 
Date: Sat, 30 Mar 2024 01:37:49 +0800
Subject: [PATCH 1/3] [M68k] Change gcc register name from a7 to sp

In M68kRegisterInfo.td, register SP is defined with name x7 and alternate name 
a7.

Fixes: https://github.com/llvm/llvm-project/issues/78620
---
 clang/lib/Basic/Targets/M68k.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Targets/M68k.cpp b/clang/lib/Basic/Targets/M68k.cpp
index 1b7e0a7f32c9be..9e6b59f1e42a8d 100644
--- a/clang/lib/Basic/Targets/M68k.cpp
+++ b/clang/lib/Basic/Targets/M68k.cpp
@@ -127,7 +127,7 @@ bool M68kTargetInfo::hasFeature(StringRef Feature) const {
 
 const char *const M68kTargetInfo::GCCRegNames[] = {
 "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
-"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
+"a0", "a1", "a2", "a3", "a4", "a5", "a6", "sp",
 "pc"};
 
 ArrayRef M68kTargetInfo::getGCCRegNames() const {

>From ded6535bd84ac612f20ab116ae6690a2b5a70c0b Mon Sep 17 00:00:00 2001
From: Jim Lin 
Date: Tue, 2 Apr 2024 05:06:09 +0800
Subject: [PATCH 2/3] Implement getGCCRegAliases and add testcase

Testcase is copied from
clang/test/CodeGen/LoongArch/inline-asm-gcc-regs.c.
---
 clang/lib/Basic/Targets/M68k.cpp  |   9 +-
 clang/lib/Basic/Targets/M68k.h|   1 +
 clang/test/CodeGen/M68k/inline-asm-gcc-regs.c | 134 ++
 3 files changed, 142 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/M68k/inline-asm-gcc-regs.c

diff --git a/clang/lib/Basic/Targets/M68k.cpp b/clang/lib/Basic/Targets/M68k.cpp
index 9e6b59f1e42a8d..94f2630d953cdc 100644
--- a/clang/lib/Basic/Targets/M68k.cpp
+++ b/clang/lib/Basic/Targets/M68k.cpp
@@ -134,9 +134,14 @@ ArrayRef M68kTargetInfo::getGCCRegNames() 
const {
   return llvm::ArrayRef(GCCRegNames);
 }
 
+const TargetInfo::GCCRegAlias M68kTargetInfo::GCCRegAliases[] = {
+  {{"bp"}, "a5"},
+  {{"fp"}, "a6"},
+  {{"usp", "ssp", "isp", "a7"}, "sp"},
+};
+
 ArrayRef M68kTargetInfo::getGCCRegAliases() const {
-  // No aliases.
-  return std::nullopt;
+  return llvm::ArrayRef(GCCRegAliases);
 }
 
 bool M68kTargetInfo::validateAsmConstraint(
diff --git a/clang/lib/Basic/Targets/M68k.h b/clang/lib/Basic/Targets/M68k.h
index a9c262e62fbad0..7ffa901127e504 100644
--- a/clang/lib/Basic/Targets/M68k.h
+++ b/clang/lib/Basic/Targets/M68k.h
@@ -25,6 +25,7 @@ namespace targets {
 
 class LLVM_LIBRARY_VISIBILITY M68kTargetInfo : public TargetInfo {
   static const char *const GCCRegNames[];
+  static const TargetInfo::GCCRegAlias GCCRegAliases[];
 
   enum CPUKind {
 CK_Unknown,
diff --git a/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c 
b/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c
new file mode 100644
index 00..40d3543d8a6f90
--- /dev/null
+++ b/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c
@@ -0,0 +1,134 @@
+// RUN: %clang_cc1 -triple m68k -emit-llvm -O2 %s -o - | FileCheck %s
+
+/// Check GCC register names and alias can be used in register variable 
definition.
+
+// CHECK-LABEL: @test_d0
+// CHECK: call void asm sideeffect "", "{d0}"(i32 undef)
+void test_d0() {
+register int a asm ("d0");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d1
+// CHECK: call void asm sideeffect "", "{d1}"(i32 undef)
+void test_d1() {
+register int a asm ("d1");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d2
+// CHECK: call void asm sideeffect "", "{d2}"(i32 undef)
+void test_d2() {
+register int a asm ("d2");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d3
+// CHECK: call void asm sideeffect "", "{d3}"(i32 undef)
+void test_d3() {
+register int a asm ("d3");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d4
+// CHECK: call void asm sideeffect "", "{d4}"(i32 undef)
+void test_d4() {
+register int a asm ("d4");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d5
+// CHECK: call void asm sideeffect "", "{d5}"(i32 undef)
+void test_d5() {
+register int a asm ("d5");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d6
+// CHECK: call void asm sideeffect "", "{d6}"(i32 undef)
+void test_d6() {
+register int a asm ("d6");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d7
+// CHECK: call void asm sideeffect "", "{d7}"(i32 undef)
+void test_d7() {
+register int a asm ("d7");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a0
+// CHECK: call void asm sideeffect "", "{a0}"(i32 undef)
+void test_a0() {
+register int a asm ("a0");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a1
+// CHECK: call void asm sideeffect "", "{a1}"(i32 undef)
+void test_a1() {
+register int a asm ("a1");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a2
+// CHECK: call void asm sideeffect "", "{a2}"(i32 undef)
+void test_a2() {
+register int a asm ("a2");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a3

[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

2024-04-01 Thread Jun Wang via cfe-commits

jwanggit86 wrote:

@jayfoad @arsenm Any other comments?

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


[clang] [M68k] Change gcc register name from a7 to sp. (PR #87095)

2024-04-01 Thread Jim Lin via cfe-commits

https://github.com/tclin914 updated 
https://github.com/llvm/llvm-project/pull/87095

>From dec6021133f67304bfc9942a1a4985cce6a15645 Mon Sep 17 00:00:00 2001
From: Jim Lin 
Date: Sat, 30 Mar 2024 01:37:49 +0800
Subject: [PATCH 1/2] [M68k] Change gcc register name from a7 to sp

In M68kRegisterInfo.td, register SP is defined with name x7 and alternate name 
a7.

Fixes: https://github.com/llvm/llvm-project/issues/78620
---
 clang/lib/Basic/Targets/M68k.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Targets/M68k.cpp b/clang/lib/Basic/Targets/M68k.cpp
index 1b7e0a7f32c9be..9e6b59f1e42a8d 100644
--- a/clang/lib/Basic/Targets/M68k.cpp
+++ b/clang/lib/Basic/Targets/M68k.cpp
@@ -127,7 +127,7 @@ bool M68kTargetInfo::hasFeature(StringRef Feature) const {
 
 const char *const M68kTargetInfo::GCCRegNames[] = {
 "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
-"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
+"a0", "a1", "a2", "a3", "a4", "a5", "a6", "sp",
 "pc"};
 
 ArrayRef M68kTargetInfo::getGCCRegNames() const {

>From ded6535bd84ac612f20ab116ae6690a2b5a70c0b Mon Sep 17 00:00:00 2001
From: Jim Lin 
Date: Tue, 2 Apr 2024 05:06:09 +0800
Subject: [PATCH 2/2] Implement getGCCRegAliases and add testcase

Testcase is copied from
clang/test/CodeGen/LoongArch/inline-asm-gcc-regs.c.
---
 clang/lib/Basic/Targets/M68k.cpp  |   9 +-
 clang/lib/Basic/Targets/M68k.h|   1 +
 clang/test/CodeGen/M68k/inline-asm-gcc-regs.c | 134 ++
 3 files changed, 142 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/M68k/inline-asm-gcc-regs.c

diff --git a/clang/lib/Basic/Targets/M68k.cpp b/clang/lib/Basic/Targets/M68k.cpp
index 9e6b59f1e42a8d..94f2630d953cdc 100644
--- a/clang/lib/Basic/Targets/M68k.cpp
+++ b/clang/lib/Basic/Targets/M68k.cpp
@@ -134,9 +134,14 @@ ArrayRef M68kTargetInfo::getGCCRegNames() 
const {
   return llvm::ArrayRef(GCCRegNames);
 }
 
+const TargetInfo::GCCRegAlias M68kTargetInfo::GCCRegAliases[] = {
+  {{"bp"}, "a5"},
+  {{"fp"}, "a6"},
+  {{"usp", "ssp", "isp", "a7"}, "sp"},
+};
+
 ArrayRef M68kTargetInfo::getGCCRegAliases() const {
-  // No aliases.
-  return std::nullopt;
+  return llvm::ArrayRef(GCCRegAliases);
 }
 
 bool M68kTargetInfo::validateAsmConstraint(
diff --git a/clang/lib/Basic/Targets/M68k.h b/clang/lib/Basic/Targets/M68k.h
index a9c262e62fbad0..7ffa901127e504 100644
--- a/clang/lib/Basic/Targets/M68k.h
+++ b/clang/lib/Basic/Targets/M68k.h
@@ -25,6 +25,7 @@ namespace targets {
 
 class LLVM_LIBRARY_VISIBILITY M68kTargetInfo : public TargetInfo {
   static const char *const GCCRegNames[];
+  static const TargetInfo::GCCRegAlias GCCRegAliases[];
 
   enum CPUKind {
 CK_Unknown,
diff --git a/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c 
b/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c
new file mode 100644
index 00..40d3543d8a6f90
--- /dev/null
+++ b/clang/test/CodeGen/M68k/inline-asm-gcc-regs.c
@@ -0,0 +1,134 @@
+// RUN: %clang_cc1 -triple m68k -emit-llvm -O2 %s -o - | FileCheck %s
+
+/// Check GCC register names and alias can be used in register variable 
definition.
+
+// CHECK-LABEL: @test_d0
+// CHECK: call void asm sideeffect "", "{d0}"(i32 undef)
+void test_d0() {
+register int a asm ("d0");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d1
+// CHECK: call void asm sideeffect "", "{d1}"(i32 undef)
+void test_d1() {
+register int a asm ("d1");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d2
+// CHECK: call void asm sideeffect "", "{d2}"(i32 undef)
+void test_d2() {
+register int a asm ("d2");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d3
+// CHECK: call void asm sideeffect "", "{d3}"(i32 undef)
+void test_d3() {
+register int a asm ("d3");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d4
+// CHECK: call void asm sideeffect "", "{d4}"(i32 undef)
+void test_d4() {
+register int a asm ("d4");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d5
+// CHECK: call void asm sideeffect "", "{d5}"(i32 undef)
+void test_d5() {
+register int a asm ("d5");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d6
+// CHECK: call void asm sideeffect "", "{d6}"(i32 undef)
+void test_d6() {
+register int a asm ("d6");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_d7
+// CHECK: call void asm sideeffect "", "{d7}"(i32 undef)
+void test_d7() {
+register int a asm ("d7");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a0
+// CHECK: call void asm sideeffect "", "{a0}"(i32 undef)
+void test_a0() {
+register int a asm ("a0");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a1
+// CHECK: call void asm sideeffect "", "{a1}"(i32 undef)
+void test_a1() {
+register int a asm ("a1");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a2
+// CHECK: call void asm sideeffect "", "{a2}"(i32 undef)
+void test_a2() {
+register int a asm ("a2");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_a3

[clang] [clang] MangledSymbol: Added move to Names param in init list (PR #87287)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Braden Helmer (bradenhelmer)


Changes

Fixes #87255

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


1 Files Affected:

- (modified) clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp (+2-1) 


``diff
diff --git a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp 
b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
index d58f5bb0919906..81a827dba26b90 100644
--- a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
+++ b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
@@ -33,7 +33,8 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer {
 
 MangledSymbol(const std::string , uint8_t Type, uint8_t Binding,
   std::vector Names)
-: ParentName(ParentName), Type(Type), Binding(Binding), Names(Names) {}
+: ParentName(ParentName), Type(Type), Binding(Binding),
+  Names(std::move(Names)) {}
   };
   using MangledSymbols = std::map;
 

``




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


[clang] [clang] MangledSymbol: Added move to Names param in init list (PR #87287)

2024-04-01 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang] MangledSymbol: Added move to Names param in init list (PR #87287)

2024-04-01 Thread Braden Helmer via cfe-commits

https://github.com/bradenhelmer created 
https://github.com/llvm/llvm-project/pull/87287

Fixes #87255

>From 4d0290b2dc10705cf229e4c1c3b40dd5155ea61c Mon Sep 17 00:00:00 2001
From: Braden Helmer 
Date: Mon, 1 Apr 2024 18:09:59 -0400
Subject: [PATCH] Added move for Names parameter in MangledSymbol ctor

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

diff --git a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp 
b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
index d58f5bb0919906..81a827dba26b90 100644
--- a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
+++ b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
@@ -33,7 +33,8 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer {
 
 MangledSymbol(const std::string , uint8_t Type, uint8_t Binding,
   std::vector Names)
-: ParentName(ParentName), Type(Type), Binding(Binding), Names(Names) {}
+: ParentName(ParentName), Type(Type), Binding(Binding),
+  Names(std::move(Names)) {}
   };
   using MangledSymbols = std::map;
 

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


[clang] cppcheck: pass NodeKinds by const reference (PR #87273)

2024-04-01 Thread Oliver Stöneberg via cfe-commits

firewave wrote:

Depending on the calling code the fix might actually be the introduction of 
`std::move()`.

This is a known issue upstream: https://trac.cppcheck.net/ticket/12384.

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


[clang] [clang] Add test for CWG1606 (PR #87274)

2024-04-01 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

It looks like we do have a test and it looks like the restriction was lifted in 
C++20.

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


[clang] [clang] Add test for CWG1606 (PR #87274)

2024-04-01 Thread Shafik Yaghmour via cfe-commits

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

Thank you for the test! LGTM.

Do we also have a test that `sizeof([=]{ return i + j;})` should fail as well? 
Tangentially related to this DR but if we don't we should cover that in our 
tests someplace.

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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

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


[clang] [OpenMP][CodeGen] Improved codegen for combined loop directives (PR #87278)

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


@@ -6135,6 +6137,79 @@ processImplicitMapsWithDefaultMappers(Sema , 
DSAStackTy *Stack,
   }
 }
 
+namespace {
+/// A 'teams loop' with a nested 'loop bind(parallel)' or generic function
+/// call in the associated loop-nest cannot be a 'parallel for'.
+class TeamsLoopChecker final : public ConstStmtVisitor {
+  Sema 
+
+public:
+  bool teamsLoopCanBeParallelFor() const { return TeamsLoopCanBeParallelFor; }
+
+  // Is there a nested OpenMP loop bind(parallel)
+  void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
+if (D->getDirectiveKind() == llvm::omp::Directive::OMPD_loop) {
+  if (const auto *C = D->getSingleClause())
+if (C->getBindKind() == OMPC_BIND_parallel) {
+  TeamsLoopCanBeParallelFor = false;
+  // No need to continue visiting any more
+  return;
+}
+}
+for (const Stmt *Child : D->children())
+  if (Child)
+Visit(Child);
+  }
+
+  void VisitCallExpr(const CallExpr *C) {

efriedma-quic wrote:

I'm concerned detecting CallExprs like this is going to have unexpected effects 
on the generated code: there are a lot of constructs that are written as 
"calls", but don't actually call anything external.  So minor changes to the 
user's code could have an unexpectedly large impact on code generation.

Is there some way we can do this transform in an LLVM IR optimization pass?

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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


@@ -1105,19 +1105,24 @@ void CodeGenFunction::EmitNewArrayInitializer(
 }
 
 // Enter a partial-destruction Cleanup if necessary.
-if (needsEHCleanup(DtorKind)) {
+if (DtorKind) {
+  AllocaTrackerRAII AllocaTracker(*this);

usx95 wrote:

Unfortunately, that is not the case. We do create more allocas in conditional 
branches in `pushFullExprCleanup`, for eg: create `cond-cleanup.save` allocas 
in `DominatingLLVMValue::save` 
([src](https://github.com/llvm/llvm-project/blob/e93b5f5a4776ffea12d03652559dfdf8d421184c/clang/lib/CodeGen/CodeGenFunction.h#L5184)).


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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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


@@ -266,6 +269,54 @@ class alignas(8) EHCleanupScope : public EHScope {
   };
   mutable struct ExtInfo *ExtInfo;
 
+  /// Erases auxillary allocas and their usages for an unused cleanup.
+  /// Cleanups should mark these allocas as 'used' if the cleanup is
+  /// emitted, otherwise these instructions would be erased.
+  struct AuxillaryAllocas {
+SmallVector AuxAllocas;
+bool used = false;
+
+// Records a potentially unused instruction to be erased later.
+void Add(llvm::AllocaInst *Alloca) { AuxAllocas.push_back(Alloca); }
+
+// Mark all recorded instructions as used. These will not be erased later.
+void MarkUsed() {
+  used = true;
+  AuxAllocas.clear();
+}
+
+~AuxillaryAllocas() {
+  if (used)
+return;
+  llvm::SetVector Uses;
+  for (auto *Inst : llvm::reverse(AuxAllocas))
+CollectUses(Inst, Uses);
+  // Delete uses in the reverse order of insertion.
+  for (auto *I : llvm::reverse(Uses))
+I->eraseFromParent();
+}
+
+  private:
+void CollectUses(llvm::Instruction *I,
+ llvm::SetVector ) {
+  if (!I || !Uses.insert(I))
+return;
+  for (auto *User : I->materialized_users()) {

usx95 wrote:

Done.

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


[clang] e93b5f5 - [ubsan][NFC] Remove recently added `cl::init(false)`

2024-04-01 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2024-04-01T13:37:42-07:00
New Revision: e93b5f5a4776ffea12d03652559dfdf8d421184c

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

LOG: [ubsan][NFC] Remove recently added `cl::init(false)`

Extracted from #84858

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/CodeGen/CGExpr.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 82b30b8d815629..1220c575d1df9f 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -101,20 +101,19 @@ namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
 cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
-cl::desc("Insert remove-traps pass."),
-cl::init(false));
+cl::desc("Insert remove-traps pass."));
 
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
-cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
+cl::desc("Insert sanitizers on OptimizerEarlyEP."));
 
 extern cl::opt ProfileCorrelate;
 
 // Re-link builtin bitcodes after optimization
 cl::opt ClRelinkBuiltinBitcodePostop(
 "relink-builtin-bitcode-postop", cl::Optional,
-cl::desc("Re-link builtin bitcodes after optimization."), cl::init(false));
+cl::desc("Re-link builtin bitcodes after optimization."));
 } // namespace llvm
 
 namespace {

diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index e0d5575d57d02d..54432353e7420d 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -56,8 +56,7 @@ using namespace CodeGen;
 // Experiment to make sanitizers easier to debug
 static llvm::cl::opt ClSanitizeDebugDeoptimization(
 "ubsan-unique-traps", llvm::cl::Optional,
-llvm::cl::desc("Deoptimize traps for UBSAN so there is 1 trap per check"),
-llvm::cl::init(false));
+llvm::cl::desc("Deoptimize traps for UBSAN so there is 1 trap per check"));
 
 //======//
 //Miscellaneous Helper Methods



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


[clang] Rework the printing of attributes (PR #87281)

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

https://github.com/vgvassilev updated 
https://github.com/llvm/llvm-project/pull/87281

>From 94f1c8653903cc3db55abd641c68a9dd11f05df3 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Mon, 1 Apr 2024 15:01:33 +
Subject: [PATCH 1/5] Revert "Remove extra switch from  0323938d"

This reverts commit 6c0b9e35761738726aded3b399db89eb0a86f82b.
---
 clang/lib/AST/DeclPrinter.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index edbcdfe4d55bc9..1ab74c71d0fd49 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -277,6 +277,7 @@ static bool canPrintOnLeftSide(const Attr *A) {
 }
 
 static bool mustPrintOnLeftSide(attr::Kind kind) {
+  switch (kind) {
 #ifdef CLANG_ATTR_LIST_PrintOnLeft
   switch (kind) {
   CLANG_ATTR_LIST_PrintOnLeft

>From 871f5b06e0da167c4cf50d336bdc38f0eb684b6b Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Mon, 1 Apr 2024 15:01:44 +
Subject: [PATCH 2/5] Revert "Fix warning in MSVC"

This reverts commit 0323938d3c7a1a48b60a7dea8ec7300e98b4a931.
---
 clang/lib/AST/DeclPrinter.cpp | 20 +++-
 clang/utils/TableGen/ClangAttrEmitter.cpp | 11 +--
 2 files changed, 4 insertions(+), 27 deletions(-)

diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index 1ab74c71d0fd49..c2e0edd5f1f12c 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -250,23 +250,13 @@ raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
   return Out;
 }
 
-// For CLANG_ATTR_LIST_CanPrintOnLeft macro.
-#include "clang/Basic/AttrLeftSideCanPrintList.inc"
-
-// For CLANG_ATTR_LIST_PrintOnLeft macro.
-#include "clang/Basic/AttrLeftSideMustPrintList.inc"
-
 static bool canPrintOnLeftSide(attr::Kind kind) {
-#ifdef CLANG_ATTR_LIST_CanPrintOnLeft
   switch (kind) {
-  CLANG_ATTR_LIST_CanPrintOnLeft
+#include "clang/Basic/AttrLeftSideCanPrintList.inc"
 return true;
   default:
 return false;
   }
-#else
-  return false;
-#endif
 }
 
 static bool canPrintOnLeftSide(const Attr *A) {
@@ -278,16 +268,11 @@ static bool canPrintOnLeftSide(const Attr *A) {
 
 static bool mustPrintOnLeftSide(attr::Kind kind) {
   switch (kind) {
-#ifdef CLANG_ATTR_LIST_PrintOnLeft
-  switch (kind) {
-  CLANG_ATTR_LIST_PrintOnLeft
+#include "clang/Basic/AttrLeftSideMustPrintList.inc"
 return true;
   default:
 return false;
   }
-#else
-  return false;
-#endif
 }
 
 static bool mustPrintOnLeftSide(const Attr *A) {
@@ -329,6 +314,7 @@ void DeclPrinter::prettyPrintAttributes(Decl *D, 
llvm::raw_ostream ,
VD->getInitStyle() == VarDecl::CallInit)
   AttrLoc = AttrPrintLoc::Left;
   }
+
   // Only print the side matches the user requested.
   if ((Loc & AttrLoc) != AttrPrintLoc::None)
 A->printPretty(Out, Policy);
diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index eb5c34d15693d7..985cc1aee579e9 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3327,8 +3327,6 @@ void EmitClangAttrPrintList(const std::string , 
RecordKeeper ,
 
   std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
   std::vector PragmaAttrs;
-  bool first = false;
-
   for (auto *Attr : Attrs) {
 if (!Attr->getValueAsBit("ASTNode"))
   continue;
@@ -3336,15 +3334,8 @@ void EmitClangAttrPrintList(const std::string 
, RecordKeeper ,
 if (!Attr->getValueAsBit(FieldName))
   continue;
 
-if (!first) {
-  first = true;
-  OS << "#define CLANG_ATTR_LIST_" << FieldName;
-}
-
-OS << " \\\n case attr::" << Attr->getName() << ":";
+OS << "case attr::" << Attr->getName() << ":\n";
   }
-
-  OS << '\n';
 }
 
 // Emits the enumeration list for attributes.

>From e7e2e90da2a9644b0ca8a4c5c464c75a35f019a5 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Mon, 1 Apr 2024 15:11:28 +
Subject: [PATCH 3/5] Revert "Fix ast print of variables with attributes"

This reverts commit 46f3ade5083b8bfce55c78a21086a487eaac6f99.
---
 clang/include/clang/Basic/Attr.td|  14 +-
 clang/include/clang/Basic/CMakeLists.txt |  10 --
 clang/lib/AST/DeclPrinter.cpp| 137 +++
 clang/test/AST/ast-print-attr-knr.c  |  17 ---
 clang/test/AST/ast-print-attr.c  |   6 -
 clang/test/AST/ast-print-method-decl.cpp |   2 +-
 clang/test/AST/ast-print-pragmas.cpp |   4 +-
 clang/test/Analysis/blocks.mm|   2 +-
 clang/test/OpenMP/assumes_codegen.cpp|  22 +--
 clang/test/OpenMP/assumes_print.cpp  |   6 +-
 clang/test/OpenMP/assumes_template_print.cpp |  20 +--
 clang/test/OpenMP/declare_simd_ast_print.cpp |   4 +-
 clang/test/Sema/attr-print.c |   3 +-
 clang/test/SemaCXX/attr-print.cpp|   3 +-
 clang/test/SemaCXX/cxx11-attr-print.cpp  |   7 +-
 

[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

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


@@ -0,0 +1,97 @@
+//===--- MathMissingParenthesesCheck.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 "MathMissingParenthesesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+unless(isAssignmentOperator()),
+unless(isComparisonOperator()),
+unless(hasAnyOperatorName("&&", "||")),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+
+static int getPrecedence(const BinaryOperator *BinOp) {
+  if (!BinOp)
+return 0;
+  switch (BinOp->getOpcode()) {
+  case BO_Mul:
+  case BO_Div:
+  case BO_Rem:
+return 5;
+  case BO_Add:
+  case BO_Sub:
+return 4;
+  case BO_And:
+return 3;
+  case BO_Xor:
+return 2;
+  case BO_Or:
+return 1;
+  default:
+return 0;
+  }
+}
+static void addParantheses(const BinaryOperator *BinOp,
+   const BinaryOperator *ParentBinOp,
+   ClangTidyCheck *Check,
+   const clang::SourceManager ,
+   const clang::LangOptions ) {
+  if (!BinOp)
+return;
+
+  int Precedence1 = getPrecedence(BinOp);
+  int Precedence2 = getPrecedence(ParentBinOp);
+
+  if (ParentBinOp != nullptr && Precedence1 != Precedence2) {
+const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
+const clang::SourceLocation EndLoc =
+clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts);
+
+auto Diag =
+Check->diag(StartLoc,
+"'%0' has higher precedence than '%1'; add parentheses to "
+"explicitly specify the order of operations")
+<< (Precedence1 > Precedence2 ? BinOp->getOpcodeStr()
+  : ParentBinOp->getOpcodeStr())
+<< (Precedence1 > Precedence2 ? ParentBinOp->getOpcodeStr()
+  : BinOp->getOpcodeStr());
+
+Diag << FixItHint::CreateInsertion(StartLoc, "(");
+Diag << FixItHint::CreateInsertion(EndLoc, ")");
+Diag << SourceRange(StartLoc, EndLoc);

5chmidti wrote:

Nit: You could stream these directly into the diagnostic, like the operator 
strings, and remove the `Diag` variable`.

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

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

https://github.com/5chmidti approved this pull request.

LGTM from my side, others are still reviewing.

Your test file contains a few trailing whitespaces that you could remove.

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

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

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


[clang] [BitInt] Expose a _BitInt literal suffix in C++ (PR #86586)

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


@@ -974,6 +974,7 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
   bool isFixedPointConstant = isFixedPointLiteral();
   bool isFPConstant = isFloatingLiteral();
   bool HasSize = false;
+  bool PossibleBitInt = false;

erichkeane wrote:

I'd  want this generalized for all 'starts with two `_` cases.

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


[clang] [BitInt] Expose a _BitInt literal suffix in C++ (PR #86586)

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


@@ -1117,6 +1118,26 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
   if (isImaginary) break;   // Cannot be repeated.
   isImaginary = true;
   continue;  // Success.
+case '_':
+  if (isFPConstant)
+break; // Invalid for floats
+  if (HasSize)
+break;
+  if (PossibleBitInt)
+break; // Cannot be repeated.
+  if (LangOpts.CPlusPlus && s + 1 < ThisTokEnd && s[1] == '_') {
+// Scan ahead to find possible rest of BitInt suffix
+for (const char *c = s; c != ThisTokEnd; ++c) {
+  if (*c == 'w' || *c == 'W') {

erichkeane wrote:

I think we're probably better off consuming all of the __wb/__uwb here rather 
than falling through to the code on ~1151.

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


[clang] [BitInt] Expose a _BitInt literal suffix in C++ (PR #86586)

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


@@ -80,7 +80,8 @@ class NumericLiteralParser {
   bool isFloat128 : 1;  // 1.0q
   bool isFract : 1; // 1.0hr/r/lr/uhr/ur/ulr
   bool isAccum : 1; // 1.0hk/k/lk/uhk/uk/ulk
-  bool isBitInt : 1;// 1wb, 1uwb (C23)
+  bool isBitInt : 1; // 1wb, 1uwb (C23) or 1__wb, 1__uwb (Clang extension in 
C++

erichkeane wrote:

please make the comments line up with the above, I know clang-format disagrees 
(and requires manual modification), but this makes a lot of sense with the way 
it is lined up.

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


[clang] Rework the printing of attributes (PR #87281)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vassil Vassilev (vgvassilev)


Changes

Commit https://github.com/llvm/llvm-project/commit/46f3ade introduced a notion 
of printing the attributes on the left to improve the printing of attributes 
attached to variable declarations. The intent was to produce more GCC 
compatible code because clang tends to print the attributes on the right hand 
side which is not accepted by gcc.

This approach has increased the complexity in tablegen and the attrubutes 
themselves as now the are supposed to know where they could appear. That lead 
to mishandling of the `override` keyword which is modelled as an attribute in 
clang.

This patch takes an inspiration from the existing approach and tries to keep 
the position of the attributes as they were written. To do so we use simpler 
heuristic which checks if the source locations of the attribute precedes the 
declaration. If so, it is considered to be printed before the declaration.

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

---

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


16 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+1-13) 
- (modified) clang/include/clang/Basic/CMakeLists.txt (-10) 
- (modified) clang/lib/AST/DeclPrinter.cpp (+45-132) 
- (removed) clang/test/AST/ast-print-attr-knr.c (-17) 
- (modified) clang/test/AST/ast-print-method-decl.cpp (+1-1) 
- (modified) clang/test/AST/ast-print-no-sanitize.cpp (+1-1) 
- (modified) clang/test/Analysis/scopes-cfg-output.cpp (+1-1) 
- (modified) clang/test/OpenMP/assumes_codegen.cpp (+9-9) 
- (modified) clang/test/OpenMP/assumes_print.cpp (+1-1) 
- (modified) clang/test/OpenMP/assumes_template_print.cpp (+7-7) 
- (modified) clang/test/OpenMP/declare_simd_ast_print.cpp (+2-2) 
- (modified) clang/test/SemaCXX/attr-no-sanitize.cpp (+3-3) 
- (modified) clang/test/SemaCXX/cxx11-attr-print.cpp (+4-4) 
- (modified) clang/utils/TableGen/ClangAttrEmitter.cpp (-31) 
- (modified) clang/utils/TableGen/TableGen.cpp (-16) 
- (modified) clang/utils/TableGen/TableGenBackends.h (-2) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e03e55612645b..bb77f62405fbec 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -324,13 +324,10 @@ class Spelling {
 }
 
 class GNU : Spelling;
-class Declspec : Spelling {
-  bit PrintOnLeft = 1;
-}
+class Declspec : Spelling;
 class Microsoft : Spelling;
 class CXX11
 : Spelling {
-  bit CanPrintOnLeft = 0;
   string Namespace = namespace;
 }
 class C23
@@ -596,12 +593,6 @@ class AttrSubjectMatcherAggregateRule 
{
 def SubjectMatcherForNamed : AttrSubjectMatcherAggregateRule;
 
 class Attr {
-  // Specifies that when printed, this attribute is meaningful on the
-  // 'left side' of the declaration.
-  bit CanPrintOnLeft = 1;
-  // Specifies that when printed, this attribute is required to be printed on
-  // the 'left side' of the declaration.
-  bit PrintOnLeft = 0;
   // The various ways in which an attribute can be spelled in source
   list Spellings;
   // The things to which an attribute can appertain
@@ -937,7 +928,6 @@ def AVRSignal : InheritableAttr, 
TargetSpecificAttr {
 }
 
 def AsmLabel : InheritableAttr {
-  let CanPrintOnLeft = 0;
   let Spellings = [CustomKeyword<"asm">, CustomKeyword<"__asm__">];
   let Args = [
 // Label specifies the mangled name for the decl.
@@ -1534,7 +1524,6 @@ def AllocSize : InheritableAttr {
 }
 
 def EnableIf : InheritableAttr {
-  let CanPrintOnLeft = 0;
   // Does not have a [[]] spelling because this attribute requires the ability
   // to parse function arguments but the attribute is not written in the type
   // position.
@@ -3149,7 +3138,6 @@ def Unavailable : InheritableAttr {
 }
 
 def DiagnoseIf : InheritableAttr {
-  let CanPrintOnLeft = 0;
   // Does not have a [[]] spelling because this attribute requires the ability
   // to parse function arguments but the attribute is not written in the type
   // position.
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 7d53c751c13ac4..2ef6ddc68f4bf3 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -31,16 +31,6 @@ clang_tablegen(AttrList.inc -gen-clang-attr-list
   SOURCE Attr.td
   TARGET ClangAttrList)
 
-clang_tablegen(AttrLeftSideCanPrintList.inc -gen-clang-attr-can-print-left-list
-  -I ${CMAKE_CURRENT_SOURCE_DIR}/../../
-  SOURCE Attr.td
-  TARGET ClangAttrCanPrintLeftList)
-
-clang_tablegen(AttrLeftSideMustPrintList.inc 
-gen-clang-attr-must-print-left-list
-  -I ${CMAKE_CURRENT_SOURCE_DIR}/../../
-  SOURCE Attr.td
-  TARGET ClangAttrMustPrintLeftList)
-
 clang_tablegen(AttrSubMatchRulesList.inc 
-gen-clang-attr-subject-match-rule-list
   -I ${CMAKE_CURRENT_SOURCE_DIR}/../../
   SOURCE Attr.td
diff --git 

[clang] Rework the printing of attributes (PR #87281)

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

vgvassilev wrote:

@giulianobelinassi, I could not select you for a reviewer but please take a 
look at the pull request.

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


  1   2   3   4   >