[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-24 Thread via cfe-commits

cor3ntin wrote:

> Thank you working on this. I'm really like this feature! I've a question, do 
> we have any further plans to support GNU extension attributes(e.g. 
> __attribute__((aligned)))? Although it is not included in the paper.

No, sorry!

My goal here is to increase conformance, not to invent new extensions.
If someone wants to do that work, they would have to motivate the change, do 
the design leg work and synchronize with GCC.
More generally, supporting GNU syntax in relatively new, C++ specific 
constructs is probably of limited use.
If there were attributes useful in structured binding that don't yet have a 
`[[]]` spelling, we should probably would want to fix that instead.


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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

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

efriedma-quic wrote:

> No. But I am confused, isn't this just shadowing a global variable with a 
> lesser-scoped one. Are they the same? What behavior do we want here?

This is declaring, then defining, a global variable; sorry if that wasn't clear.

Probably should be an error?  It'll be confusing no matter what we do.

> However, after making the patch and testing it I am not sure what we want. Do 
> we want to cancel implicit promotions for less-than-ints that possess the 
> wraps attribute (doesn't sound spec compliant)? Or, should wrapping things 
> still undergo promotion but now wrap at different bounds than what their 
> original type specified?

I assume for your usage, you want the result of the arithmetic to be the same 
whether or not the compiler supports the "wraps" attribute, which constrains 
your choices.

> More on this, I don't see how changing implementation from attribute-based to 
> type-based resolves any of these design decisions. Neither approach is 
> necessarily easier to implement or to understand for developers, if the right 
> decisions are made in terms of behavior then the attribute approach can be 
> just as useful and predictable.

If you had a distinct canonical type, you would have had to make explicit 
decisions about a bunch of these things... and the rest would be stable 
independent of details of non-canonical type propagation.

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


[clang] Notifying assume directive as 'worked on'. (PR #90022)

2024-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (SunilKuravinakop)


Changes

Notifying assume directive as 'worked on'.  When checked on slack channel, 
nobody was working on assume directive.

 Changes to be committed:
modified:   clang/docs/OpenMPSupport.rst

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


1 Files Affected:

- (modified) clang/docs/OpenMPSupport.rst (+3-1) 


``diff
diff --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index f8146bc365e833..3562872b407bf7 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -310,7 +310,9 @@ implementation.
 
+--+--+--+---+
 | misc | dispatch construct and function variant 
argument adjustment  | :part:`worked on`| D99537, D99679
|
 
+--+--+--+---+
-| misc | assume and assumes directives 
   | :part:`worked on`| 
  |
+| misc | assumes directives
| :part:`worked on`|
   |
++--+--+--+---+
+| misc | assume directive  
  | :part:`worked on`|  
 |
 
+--+--+--+---+
 | misc | nothing directive 
   | :good:`done` | D123286 
  |
 
+--+--+--+---+

``




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


[clang] Notifying assume directive as 'worked on'. (PR #90022)

2024-04-24 Thread via cfe-commits

https://github.com/SunilKuravinakop created 
https://github.com/llvm/llvm-project/pull/90022

Notifying assume directive as 'worked on'.  When checked on slack channel, 
nobody was working on assume directive.

 Changes to be committed:
modified:   clang/docs/OpenMPSupport.rst

>From 031b44a69d2b2d408bf07714be0427bab65f29ca Mon Sep 17 00:00:00 2001
From: Sunil Kuravinakop 
Date: Thu, 25 Apr 2024 01:45:29 -0500
Subject: [PATCH] Notifying assume directive as 'worked on'. When checked on
 slack channel, nobody was working on assume directive.

 Changes to be committed:
modified:   clang/docs/OpenMPSupport.rst
---
 clang/docs/OpenMPSupport.rst | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index f8146bc365e833..3562872b407bf7 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -310,7 +310,9 @@ implementation.
 
+--+--+--+---+
 | misc | dispatch construct and function variant 
argument adjustment  | :part:`worked on`| D99537, D99679
|
 
+--+--+--+---+
-| misc | assume and assumes directives 
   | :part:`worked on`| 
  |
+| misc | assumes directives
| :part:`worked on`|
   |
++--+--+--+---+
+| misc | assume directive  
  | :part:`worked on`|  
 |
 
+--+--+--+---+
 | misc | nothing directive 
   | :good:`done` | D123286 
  |
 
+--+--+--+---+

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-24 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja edited 
https://github.com/llvm/llvm-project/pull/89942
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2024-04-24 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,165 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -disable-O0-optnone 
-emit-llvm \
+// RUN:   %s -o - | opt -S -passes=mem2reg | FileCheck %s
+
+// CHECK-LABEL: define dso_local half @test_convert_from_bf16_to_fp16(
+// CHECK-SAME: bfloat noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext bfloat [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to half
+// CHECK-NEXT:ret half [[FPTRUNC]]
+//
+_Float16 test_convert_from_bf16_to_fp16(__bf16 a) {
+return (_Float16)a;
+}
+
+// CHECK-LABEL: define dso_local bfloat @test_convert_from_fp16_to_bf16(
+// CHECK-SAME: half noundef [[A:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext half [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to bfloat
+// CHECK-NEXT:ret bfloat [[FPTRUNC]]
+//
+__bf16 test_convert_from_fp16_to_bf16(_Float16 a) {
+return (__bf16)a;
+}
+
+typedef _Float16 half2 __attribute__((ext_vector_type(2)));
+typedef _Float16 half4 __attribute__((ext_vector_type(4)));
+
+typedef __bf16 bfloat2 __attribute__((ext_vector_type(2)));
+typedef __bf16 bfloat4 __attribute__((ext_vector_type(4)));
+
+// CHECK-LABEL: define dso_local i32 @test_cast_from_half2_to_bfloat2(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x half>, ptr [[IN]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x half> [[IN1]] to <2 x bfloat>
+// CHECK-NEXT:store <2 x bfloat> [[TMP0]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[RETVAL]], align 4
+// CHECK-NEXT:ret i32 [[TMP1]]
+//
+bfloat2 test_cast_from_half2_to_bfloat2(half2 in) {
+  return (bfloat2)in;
+}
+
+
+// CHECK-LABEL: define dso_local double @test_cast_from_half4_to_bfloat4(
+// CHECK-SAME: double noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <4 x bfloat>, align 8
+// CHECK-NEXT:[[IN:%.*]] = alloca <4 x half>, align 8
+// CHECK-NEXT:store double [[IN_COERCE]], ptr [[IN]], align 8
+// CHECK-NEXT:[[IN1:%.*]] = load <4 x half>, ptr [[IN]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <4 x half> [[IN1]] to <4 x bfloat>
+// CHECK-NEXT:store <4 x bfloat> [[TMP0]], ptr [[RETVAL]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load double, ptr [[RETVAL]], align 8
+// CHECK-NEXT:ret double [[TMP1]]
+//
+bfloat4 test_cast_from_half4_to_bfloat4(half4 in) {
+  return (bfloat4)in;
+}
+
+// CHECK-LABEL: define dso_local i32 @test_cast_from_bfloat2_to_half2(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x bfloat>, ptr [[IN]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x bfloat> [[IN1]] to <2 x half>
+// CHECK-NEXT:store <2 x half> [[TMP0]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[RETVAL]], align 4
+// CHECK-NEXT:ret i32 [[TMP1]]
+//
+half2 test_cast_from_bfloat2_to_half2(bfloat2 in) {
+  return (half2)in;
+}
+
+
+// CHECK-LABEL: define dso_local double @test_cast_from_bfloat4_to_half4(
+// CHECK-SAME: double noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <4 x half>, align 8
+// CHECK-NEXT:[[IN:%.*]] = alloca <4 x bfloat>, align 8
+// CHECK-NEXT:store double [[IN_COERCE]], ptr [[IN]], align 8
+// CHECK-NEXT:[[IN1:%.*]] = load <4 x bfloat>, ptr [[IN]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <4 x bfloat> [[IN1]] to <4 x half>
+// CHECK-NEXT:store <4 x half> [[TMP0]], ptr [[RETVAL]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load double, ptr [[RETVAL]], align 8
+// CHECK-NEXT:ret double [[TMP1]]
+//
+half4 test_cast_from_bfloat4_to_half4(bfloat4 in) {
+  return (half4)in;
+}
+
+
+// CHECK-LABEL: define dso_local i32 @test_convertvector_from_half2_to_bfloat2(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x half>, ptr [[IN]], align 4
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext <2 x half> [[IN1]] to <2 x float>
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc <2 x float> [[FPEXT]] to <2 x 
bfloat>
+// CHECK-NEXT:store <2 x bfloat> [[FPTRUNC]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load i32,

[clang] [clang-repl] Extend the C support. (PR #89804)

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

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

>From 50fa9c91bee980a114ebab2b3301a1e378dd2b81 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Tue, 23 Apr 2024 18:07:06 +
Subject: [PATCH] [clang-repl] Extend the C support.

The IdResolver chain is the main way for C to implement lookup rules. Every new
partial translation unit caused clang to exit the top-most scope which in turn
cleaned up the IdResolver chain. That was not an issue for C++ because its
lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units
maintaining proper C-style lookup infrastructure.
---
 clang/lib/Interpreter/IncrementalParser.cpp | 13 +++--
 clang/lib/Sema/SemaDecl.cpp |  3 ++-
 clang/test/Interpreter/execute.c| 21 +
 3 files changed, 34 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Interpreter/execute.c

diff --git a/clang/lib/Interpreter/IncrementalParser.cpp 
b/clang/lib/Interpreter/IncrementalParser.cpp
index ef90fe9e6f5451..f1cb5fc870eb94 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -387,8 +387,7 @@ std::unique_ptr 
IncrementalParser::GenModule() {
 
 void IncrementalParser::CleanUpPTU(PartialTranslationUnit &PTU) {
   TranslationUnitDecl *MostRecentTU = PTU.TUPart;
-  TranslationUnitDecl *FirstTU = MostRecentTU->getFirstDecl();
-  if (StoredDeclsMap *Map = FirstTU->getPrimaryContext()->getLookupPtr()) {
+  if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) 
{
 for (auto &&[Key, List] : *Map) {
   DeclContextLookupResult R = List.getLookupResult();
   std::vector NamedDeclsToRemove;
@@ -407,6 +406,16 @@ void IncrementalParser::CleanUpPTU(PartialTranslationUnit 
&PTU) {
   }
 }
   }
+
+  // FIXME: We should de-allocate MostRecentTU
+  for (Decl *D : MostRecentTU->decls()) {
+if (!isa(D))
+  continue;
+// Check if we need to clean up the IdResolver chain.
+NamedDecl *ND = cast(D);
+if (ND->getDeclName().getFETokenInfo())
+  getCI()->getSema().IdResolver.RemoveDecl(ND);
+  }
 }
 
 llvm::StringRef IncrementalParser::GetMangledName(GlobalDecl GD) const {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index e0745fe9a45367..4f8c7e2b2e2941 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2282,7 +2282,8 @@ void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
 
 // Remove this name from our lexical scope, and warn on it if we haven't
 // already.
-IdResolver.RemoveDecl(D);
+if (!PP.isIncrementalProcessingEnabled())
+  IdResolver.RemoveDecl(D);
 auto ShadowI = ShadowingDecls.find(D);
 if (ShadowI != ShadowingDecls.end()) {
   if (const auto *FD = dyn_cast(ShadowI->second)) {
diff --git a/clang/test/Interpreter/execute.c b/clang/test/Interpreter/execute.c
new file mode 100644
index 00..44a3a32c930112
--- /dev/null
+++ b/clang/test/Interpreter/execute.c
@@ -0,0 +1,21 @@
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -Xclang -Xcc -verify | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -O2 -Xcc -Xclang -Xcc -verify| 
FileCheck %s
+int printf(const char *, ...);
+int i = 42; err // expected-error{{use of undeclared identifier}}
+int i = 42;
+struct S { float f; struct S *m;} s = {1.0, 0};
+// FIXME: Making foo inline fails to emit the function.
+int foo() { return 42; }
+void run() {\
+  printf("i = %d\n", i);\
+  printf("S[f=%f, m=0x%llx]\n", s.f, (unsigned long long)s.m);  \
+  int r3 = foo();   \
+}
+run();
+// CHECK: i = 42
+// CHECK-NEXT: S[f=1.00, m=0x0]
+
+%quit

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [clang] pointer to member with qualified-id enclosed in parentheses in unevaluated context should be invalid (PR #89713)

2024-04-24 Thread via cfe-commits

cor3ntin wrote:

@t3nsor Do you know the reason for the "not enclosed in parameters" in 
https://eel.is/c++draft/expr.unary.op#4 ?

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-24 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja edited 
https://github.com/llvm/llvm-project/pull/89942
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2024-04-24 Thread via cfe-commits

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

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

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

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1f18e0d5ba409a..8e35c801bc9599 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -1431,7 +1431,10 @@ Value *ScalarExprEmitter::EmitScalarCast(Value *Src, 
QualType SrcType,
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }
 
-  if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
+  if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
+Value *FloatVal = Builder.CreateFPExt(Src, Builder.getFloatTy(), "fpext");
+return Builder.CreateFPTrunc(FloatVal, DstTy, "fptrunc");
+  } else if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
 return Builder.CreateFPTrunc(Src, DstTy, "conv");
   return Builder.CreateFPExt(Src, DstTy, "conv");
 }
@@ -1906,7 +1909,15 @@ Value 
*ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
   } else {
 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
"Unknown real conversion");
-if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
+if ((DstEltTy->is16bitFPTy() && SrcEltTy->is16bitFPTy())) {
+  auto *ScrVecTy = cast(SrcTy);
+  Value *FloatVal = Builder.CreateFPExt(
+  Src,
+  llvm::VectorType::get(Builder.getFloatTy(),
+ScrVecTy->getElementCount()),
+  "fpext");
+  Res = Builder.CreateFPTrunc(FloatVal, DstTy, "fptrunc");
+} else if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
   Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
 else
   Res = Builder.CreateFPExt(Src, DstTy, "conv");
diff --git a/clang/test/CodeGen/X86/bfloat16-convert-half.c 
b/clang/test/CodeGen/X86/bfloat16-convert-half.c
new file mode 100644
index 00..3f60bd13b33d48
--- /dev/null
+++ b/clang/test/CodeGen/X86/bfloat16-convert-half.c
@@ -0,0 +1,165 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -disable-O0-optnone 
-emit-llvm \
+// RUN:   %s -o - | opt -S -passes=mem2reg | FileCheck %s
+
+// CHECK-LABEL: define dso_local half @test_convert_from_bf16_to_fp16(
+// CHECK-SAME: bfloat noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext bfloat [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to half
+// CHECK-NEXT:ret half [[FPTRUNC]]
+//
+_Float16 test_convert_from_bf16_to_fp16(__bf16 a) {
+return (_Float16)a;
+}
+
+// CHECK-LABEL: define dso_local bfloat @test_convert_from_fp16_to_bf16(
+// CHECK-SAME: half noundef [[A:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext half [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to bfloat
+// CHECK-NEXT:ret bfloat [[FPTRUNC]]
+//
+__bf16 test_convert_from_fp16_to_bf16(_Float16 a) {
+return (__bf16)a;
+}
+
+typedef _Float16 half2 __attribute__((ext_vector_type(2)));
+typedef _Float16 half4 __attribute__((ext_vector_type(4)));
+
+typedef __bf16 bfloat2 __attribute__((ext_vector_type(2)));
+typedef __bf16 bfloat4 __attribute__((ext_vector_type(4)));
+
+// CHECK-LABEL: define dso_local i32 @test_cast_from_half2_to_bfloat2(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x half>, ptr [[IN]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x half> [[IN1]] to <2 x bfloat>
+// CHECK-NEXT:store <2 x bfloat> [[TMP0]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[RETVAL]], align 4
+// CHECK-NEXT:ret i32 [[TMP1]]
+//
+bfloat2 test_cast_from_half2_to_bfloat2(half2 in) {
+  return (bfloat2)in;
+}
+
+
+// CHECK-LABEL: define dso_local double @test_cast_from_half4_to_bfloat4(
+// CHECK-SAME: double noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <4 x bfloat>, align 8
+// CHECK-NEXT:[[IN:%.*]] = alloca <4 x half>, align 8
+// CHECK-NEXT:store double [[IN_COERCE]], ptr [[IN]], align 8
+// CHECK-NEXT:[[IN1:%.*]] = load <4 x half>, ptr [[IN]], align 8
+// CHECK-NEXT:[[TMP0:%

[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-24 Thread via cfe-commits


@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -std=c++26 -fsyntax-only -verify %s
+
+auto&& f1() {
+  return 42; // expected-error{{returning reference to local temporary object}}
+}
+const double& f2() {
+  static int x = 42;
+  return x; // expected-error{{returning reference to local temporary object}}
+}
+auto&& id(auto&& r) {
+  return static_cast(r);
+}
+auto&& f3() {
+  return id(42);// OK, but probably a bug
+}
+
+static_assert(__is_convertible(int, const int &));
+static_assert(__is_nothrow_convertible(int, const int &));

cor3ntin wrote:

I would not mind keeping these two lines here (just to signal all the paragraph 
was implemented), and adding more exhaustive testing in type-traits.cpp

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


[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-04-24 Thread Wentao Zhang via cfe-commits


@@ -292,10 +292,36 @@ class CoverageMappingBuilder {
 return SM.getLocForEndOfFile(SM.getFileID(Loc));
   }
 
-  /// Find out where the current file is included or macro is expanded.
-  SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
-return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
-   : SM.getIncludeLoc(SM.getFileID(Loc));
+  /// Find out where a macro is expanded. If the immediate result is a
+  /// , keep looking until the result isn't. Return the source
+  /// range of the found result, or std::nullopt if the while loop didn't get
+  /// executed, which means the location wasn't changed.
+  std::optional getNonScratchExpansion(SourceLocation Loc) {
+std::optional EndLoc = std::nullopt;
+while (Loc.isMacroID() &&
+   SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
+  auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
+  Loc = ExpansionRange.getBegin();
+  EndLoc = ExpansionRange.getEnd();
+}
+if (EndLoc.has_value())
+  return SourceRange(Loc, EndLoc.value());

whentojump wrote:

> Actually returns CharSourceRange.

True. Ideally we can circulate around `CharSourceRange` without converting back 
and forth too much but I found it hard to make both two callers clean and 
straightforward. 

> You may rewind them 

I can do that, meanwhile I'll also seek if there's a better way



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


[clang] [NFC] Move DeclID from serialization/ASTBitCodes.h to AST/DeclID.h (PR #89873)

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

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


[clang] c2a98fd - [NFC] Move DeclID from serialization/ASTBitCodes.h to AST/DeclID.h (#89873)

2024-04-24 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2024-04-25T13:53:22+08:00
New Revision: c2a98fdeb3aede1a8db492a6ea30f4fa85b60edc

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

LOG: [NFC] Move DeclID from serialization/ASTBitCodes.h to AST/DeclID.h (#89873)

Previously, the DeclID is defined in serialization/ASTBitCodes.h under
clang::serialization namespace. However, actually the DeclID is not
purely used in serialization part. The DeclID is already widely used in
AST and all around the clang project via classes like `LazyPtrDecl` or
calling `ExternalASTSource::getExernalDecl()`. All such uses are via the
raw underlying type of `DeclID` as `uint32_t`. This is not pretty good.

This patch moves the DeclID class family to a new header `AST/DeclID.h`
so that the whole project can use the wrapped class `DeclID`,
`GlobalDeclID` and `LocalDeclID` instead of the raw underlying type.
This can improve the readability and the type safety.

Added: 
clang/include/clang/AST/DeclID.h

Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/AST/ExternalASTSource.h
clang/include/clang/Frontend/ASTUnit.h
clang/include/clang/Frontend/MultiplexConsumer.h
clang/include/clang/Sema/MultiplexExternalSemaSource.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/include/clang/Serialization/ASTDeserializationListener.h
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ASTRecordReader.h
clang/include/clang/Serialization/ASTWriter.h
clang/include/clang/Serialization/ModuleFile.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/AST/DeclCXX.cpp
clang/lib/AST/DeclFriend.cpp
clang/lib/AST/DeclObjC.cpp
clang/lib/AST/DeclOpenMP.cpp
clang/lib/AST/DeclTemplate.cpp
clang/lib/AST/ExternalASTSource.cpp
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Frontend/MultiplexConsumer.cpp
clang/lib/Sema/MultiplexExternalSemaSource.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/ASTWriterDecl.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index d5ed20ff50157d..ecec9bfcf30079 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -455,7 +455,7 @@ class ASTContext : public RefCountedBase {
   /// initialization of another module).
   struct PerModuleInitializers {
 llvm::SmallVector Initializers;
-llvm::SmallVector LazyInitializers;
+llvm::SmallVector LazyInitializers;
 
 void resolve(ASTContext &Ctx);
   };
@@ -1059,7 +1059,7 @@ class ASTContext : public RefCountedBase {
   /// or an ImportDecl nominating another module that has initializers.
   void addModuleInitializer(Module *M, Decl *Init);
 
-  void addLazyModuleInitializers(Module *M, ArrayRef IDs);
+  void addLazyModuleInitializers(Module *M, ArrayRef IDs);
 
   /// Get the initializations to perform when importing a module, if any.
   ArrayRef getModuleInitializers(Module *M);

diff  --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index d8cafc3d81526e..474e51c1df6d68 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -15,6 +15,7 @@
 
 #include "clang/AST/ASTDumperUtils.h"
 #include "clang/AST/AttrIterator.h"
+#include "clang/AST/DeclID.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/SelectorLocationsKind.h"
 #include "clang/Basic/IdentifierTable.h"
@@ -239,9 +240,6 @@ class alignas(8) Decl {
 ModulePrivate
   };
 
-  /// An ID number that refers to a declaration in an AST file.
-  using DeclID = uint32_t;
-
 protected:
   /// The next declaration within the same lexical
   /// DeclContext. These pointers form the linked list that is

diff  --git a/clang/include/clang/AST/DeclID.h 
b/clang/include/clang/AST/DeclID.h
new file mode 100644
index 00..e2c6dd65e86bc3
--- /dev/null
+++ b/clang/include/clang/AST/DeclID.h
@@ -0,0 +1,177 @@
+//===--- DeclID.h - ID number for deserialized declarations  *- 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
+//
+//===--===//
+//
+// This file defines DeclID class family to describe the deserialized
+// declarations. The DeclID is widely used in AST via LazyDeclPtr, or calls to
+// `ExternalAST

[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -42,6 +42,54 @@ Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool 
CBuffer,
 void SemaHLSL::ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace) {
   auto *BufDecl = cast(Dcl);
   BufDecl->setRBraceLoc(RBrace);
+
+  // Validate packoffset.
+  llvm::SmallVector> PackOffsetVec;
+  bool HasPackOffset = false;
+  bool HasNonPackOffset = false;
+  for (auto *Field : BufDecl->decls()) {
+VarDecl *Var = dyn_cast(Field);
+if (!Var)
+  continue;
+if (Field->hasAttr()) {
+  PackOffsetVec.emplace_back(Var, Field->getAttr());
+  HasPackOffset = true;
+} else {
+  HasNonPackOffset = true;
+}
+  }
+
+  if (HasPackOffset && HasNonPackOffset) {
+Diag(BufDecl->getLocation(), diag::err_hlsl_packoffset_mix);
+  } else if (HasPackOffset) {
+ASTContext &Context = getASTContext();
+// Make sure no overlap in packoffset.
+llvm::SmallDenseMap>

hekota wrote:

You could also sort the ranges (by `Begin`) and then walk through them to make 
sure they are incrementing. That would avoid the O(n^2) overlap check.

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


[clang] [clang-repl] Extend the C support. (PR #89804)

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

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

>From 8317ce33d07d0986e314de0b39aa977f784e0619 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Tue, 23 Apr 2024 18:07:06 +
Subject: [PATCH] [clang-repl] Extend the C support.

The IdResolver chain is the main way for C to implement lookup rules. Every new
partial translation unit caused clang to exit the top-most scope which in turn
cleaned up the IdResolver chain. That was not an issue for C++ because its
lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units
maintaining proper C-style lookup infrastructure.
---
 clang/lib/Interpreter/IncrementalParser.cpp | 13 +++--
 clang/lib/Sema/SemaDecl.cpp |  3 ++-
 clang/test/Interpreter/execute.c| 21 +
 3 files changed, 34 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Interpreter/execute.c

diff --git a/clang/lib/Interpreter/IncrementalParser.cpp 
b/clang/lib/Interpreter/IncrementalParser.cpp
index ef90fe9e6f5451..f1cb5fc870eb94 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -387,8 +387,7 @@ std::unique_ptr 
IncrementalParser::GenModule() {
 
 void IncrementalParser::CleanUpPTU(PartialTranslationUnit &PTU) {
   TranslationUnitDecl *MostRecentTU = PTU.TUPart;
-  TranslationUnitDecl *FirstTU = MostRecentTU->getFirstDecl();
-  if (StoredDeclsMap *Map = FirstTU->getPrimaryContext()->getLookupPtr()) {
+  if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) 
{
 for (auto &&[Key, List] : *Map) {
   DeclContextLookupResult R = List.getLookupResult();
   std::vector NamedDeclsToRemove;
@@ -407,6 +406,16 @@ void IncrementalParser::CleanUpPTU(PartialTranslationUnit 
&PTU) {
   }
 }
   }
+
+  // FIXME: We should de-allocate MostRecentTU
+  for (Decl *D : MostRecentTU->decls()) {
+if (!isa(D))
+  continue;
+// Check if we need to clean up the IdResolver chain.
+NamedDecl *ND = cast(D);
+if (ND->getDeclName().getFETokenInfo())
+  getCI()->getSema().IdResolver.RemoveDecl(ND);
+  }
 }
 
 llvm::StringRef IncrementalParser::GetMangledName(GlobalDecl GD) const {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 452e00fa32b102..2a0f73b42d3088 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2282,7 +2282,8 @@ void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
 
 // Remove this name from our lexical scope, and warn on it if we haven't
 // already.
-IdResolver.RemoveDecl(D);
+if (!PP.isIncrementalProcessingEnabled())
+  IdResolver.RemoveDecl(D);
 auto ShadowI = ShadowingDecls.find(D);
 if (ShadowI != ShadowingDecls.end()) {
   if (const auto *FD = dyn_cast(ShadowI->second)) {
diff --git a/clang/test/Interpreter/execute.c b/clang/test/Interpreter/execute.c
new file mode 100644
index 00..44a3a32c930112
--- /dev/null
+++ b/clang/test/Interpreter/execute.c
@@ -0,0 +1,21 @@
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -Xclang -Xcc -verify | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -O2 -Xcc -Xclang -Xcc -verify| 
FileCheck %s
+int printf(const char *, ...);
+int i = 42; err // expected-error{{use of undeclared identifier}}
+int i = 42;
+struct S { float f; struct S *m;} s = {1.0, 0};
+// FIXME: Making foo inline fails to emit the function.
+int foo() { return 42; }
+void run() {\
+  printf("i = %d\n", i);\
+  printf("S[f=%f, m=0x%llx]\n", s.f, (unsigned long long)s.m);  \
+  int r3 = foo();   \
+}
+run();
+// CHECK: i = 42
+// CHECK-NEXT: S[f=1.00, m=0x0]
+
+%quit

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


[clang] [clang-repl] Fix the process return code if diagnostics occurred. (PR #89879)

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

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


[clang] fd5f06e - [clang-repl] Fix the process return code if diagnostics occurred. (#89879)

2024-04-24 Thread via cfe-commits

Author: Vassil Vassilev
Date: 2024-04-25T08:46:04+03:00
New Revision: fd5f06eb6d8d8b05846c8d7bd2431079ef707b37

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

LOG: [clang-repl] Fix the process return code if diagnostics occurred. (#89879)

Should fix the failure seen in the pre-merge infrastructure of #89804.

Added: 


Modified: 
clang/test/Interpreter/fail.cpp
clang/tools/clang-repl/ClangRepl.cpp

Removed: 




diff  --git a/clang/test/Interpreter/fail.cpp b/clang/test/Interpreter/fail.cpp
index 4e301f37548f1f..633d92794325c2 100644
--- a/clang/test/Interpreter/fail.cpp
+++ b/clang/test/Interpreter/fail.cpp
@@ -1,12 +1,19 @@
-// FIXME: There're some inconsistencies between interactive and non-interactive
-// modes. For example, when clang-repl runs in the interactive mode, issues an
-// error, and then successfully recovers if we decide it's a success then for
-// the non-interactive mode the exit code should be a failure.
-// RUN: clang-repl "int x = 10;" "int y=7; err;" "int y = 10;"
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
-// RUN: cat %s | not clang-repl | FileCheck %s
-BOOM!
+// clang-repl can be called from the prompt in non-interactive mode as a
+// calculator in shell scripts, for example. In that case if there is an error
+// we should set the exit code as failure.
+// RUN: not clang-repl "int x = 10;" "int y=7; err;" "int y = 10;"
+
+// In interactive (REPL) mode, we can have errors but we should exit with
+// success because errors in the input code are part of the interactive use.
+// RUN: cat %s | clang-repl | FileCheck %s
+
+// However, interactive mode should fail when we specified -verify and there
+// was a diagnostic mismatches. This will make the testsuite fail as intended.
+// RUN: cat %s | not clang-repl -Xcc -Xclang -Xcc -verify | FileCheck %s
+
+BOOM! // expected-error {{intended to fail the -verify test}}
 extern "C" int printf(const char *, ...);
 int i = 42;
 auto r1 = printf("i = %d\n", i);

diff  --git a/clang/tools/clang-repl/ClangRepl.cpp 
b/clang/tools/clang-repl/ClangRepl.cpp
index aecf61b97fc719..9cfc70462893dd 100644
--- a/clang/tools/clang-repl/ClangRepl.cpp
+++ b/clang/tools/clang-repl/ClangRepl.cpp
@@ -215,13 +215,15 @@ int main(int argc, const char **argv) {
   } else
 Interp = ExitOnErr(clang::Interpreter::create(std::move(CI)));
 
+  bool HasError = false;
+
   for (const std::string &input : OptInputs) {
-if (auto Err = Interp->ParseAndExecute(input))
+if (auto Err = Interp->ParseAndExecute(input)) {
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
+  HasError = true;
+}
   }
 
-  bool HasError = false;
-
   if (OptInputs.empty()) {
 llvm::LineEditor LE("clang-repl");
 std::string Input;
@@ -241,18 +243,13 @@ int main(int argc, const char **argv) {
 break;
   }
   if (Input == R"(%undo)") {
-if (auto Err = Interp->Undo()) {
+if (auto Err = Interp->Undo())
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
-  HasError = true;
-}
   } else if (Input.rfind("%lib ", 0) == 0) {
-if (auto Err = Interp->LoadDynamicLibrary(Input.data() + 5)) {
+if (auto Err = Interp->LoadDynamicLibrary(Input.data() + 5))
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
-  HasError = true;
-}
   } else if (auto Err = Interp->ParseAndExecute(Input)) {
 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
-HasError = true;
   }
 
   Input = "";



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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

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

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

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

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


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


[clang] [ASTMatchers] forCallable should not erase binding on success (PR #89657)

2024-04-24 Thread Marco Borgeaud via cfe-commits

https://github.com/marco-antognini-sonarsource updated 
https://github.com/llvm/llvm-project/pull/89657

>From ebc417fe98f1cb0e030ec77c17c0150c3fcca7f9 Mon Sep 17 00:00:00 2001
From: Marco Borgeaud
 <89914223+marco-antognini-sonarsou...@users.noreply.github.com>
Date: Fri, 19 Apr 2024 17:33:22 +0200
Subject: [PATCH] forCallable should not erase binding on success

Do not erase Builder when the first check fails because it could succeed
on the second stack frame.

The problem was that `InnerMatcher.matches` erases the bindings when it
returns false. The appropriate solution is to pass a copy of the
bindings, similar to what `matchesFirstInRange` does.
---
 clang/include/clang/ASTMatchers/ASTMatchers.h |  16 ++-
 .../ASTMatchers/ASTMatchersTraversalTest.cpp  | 130 ++
 2 files changed, 142 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index dc1f49525a004a..54671fe4043378 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -8341,20 +8341,28 @@ AST_MATCHER_P(Stmt, forCallable, 
internal::Matcher, InnerMatcher) {
 const auto &CurNode = Stack.back();
 Stack.pop_back();
 if (const auto *FuncDeclNode = CurNode.get()) {
-  if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
+  BoundNodesTreeBuilder B = *Builder;
+  if (InnerMatcher.matches(*FuncDeclNode, Finder, &B)) {
+*Builder = std::move(B);
 return true;
   }
 } else if (const auto *LambdaExprNode = CurNode.get()) {
+  BoundNodesTreeBuilder B = *Builder;
   if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
-   Builder)) {
+   &B)) {
+*Builder = std::move(B);
 return true;
   }
 } else if (const auto *ObjCMethodDeclNode = CurNode.get()) 
{
-  if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, Builder)) {
+  BoundNodesTreeBuilder B = *Builder;
+  if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, &B)) {
+*Builder = std::move(B);
 return true;
   }
 } else if (const auto *BlockDeclNode = CurNode.get()) {
-  if (InnerMatcher.matches(*BlockDeclNode, Finder, Builder)) {
+  BoundNodesTreeBuilder B = *Builder;
+  if (InnerMatcher.matches(*BlockDeclNode, Finder, &B)) {
+*Builder = std::move(B);
 return true;
   }
 } else {
diff --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 6911d7600a7188..2ecbdf659358fe 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -5916,6 +5916,37 @@ TEST(StatementMatcher, ForCallable) {
   EXPECT_TRUE(notMatches(CppString2,
  returnStmt(forCallable(functionDecl(hasName("F"));
 
+  StringRef CodeWithDeepCallExpr = R"cpp(
+void Other();
+void Function() {
+  {
+(
+  Other()
+);
+  }
+}
+)cpp";
+  auto ForCallableFirst =
+  callExpr(forCallable(functionDecl(hasName("Function"))),
+   callee(functionDecl(hasName("Other")).bind("callee")))
+  .bind("call");
+  auto ForCallableSecond =
+  callExpr(callee(functionDecl(hasName("Other")).bind("callee")),
+   forCallable(functionDecl(hasName("Function"
+  .bind("call");
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  CodeWithDeepCallExpr, ForCallableFirst,
+  std::make_unique>("call")));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  CodeWithDeepCallExpr, ForCallableFirst,
+  std::make_unique>("callee")));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  CodeWithDeepCallExpr, ForCallableSecond,
+  std::make_unique>("call")));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  CodeWithDeepCallExpr, ForCallableSecond,
+  std::make_unique>("callee")));
+
   // These tests are specific to forCallable().
   StringRef ObjCString1 = "@interface I"
   "-(void) foo;"
@@ -5957,6 +5988,105 @@ TEST(StatementMatcher, ForCallable) {
   binaryOperator(forCallable(blockDecl();
 }
 
+namespace {
+class ForCallablePreservesBindingWithMultipleParentsTestCallback
+: public BoundNodesCallback {
+public:
+  bool run(const BoundNodes *BoundNodes) override {
+FunctionDecl const *FunDecl =
+BoundNodes->getNodeAs("funDecl");
+// Validate test assumptions. This would be expressed as ASSERT_* in
+// a TEST().
+if (!FunDecl) {
+  EXPECT_TRUE(false && "Incorrect test setup");
+  return false;
+}
+auto const *FunDef = FunDecl->getDefinition();
+if (!FunDef || !FunDef->getBody() ||
+FunDef->getNameAsString() != "Function") {
+  EXPECT_TRUE(false && "Incorrect test setup");
+  return false;
+}
+
+ExpectCorrectResult(
+"Baseline",
+callExpr(callee(

[clang] [Clang] [CodeGen] Perform derived-to-base conversion on explicit object parameter in lambda (PR #89828)

2024-04-24 Thread via cfe-commits

Sirraide wrote:

> @Sirraide See example of
> 
> https://github.com/llvm/llvm-project/blob/662ef8604268b207910225ecca90daf30a46720b/clang/test/CXX/drs/dr25xx.cpp#L148
> 
> 
> In this case, the date should be 2024-04-19.

Ah, thanks.

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/77456

>From 6c184f9714c94af94c7692e1264061b8dc14e912 Mon Sep 17 00:00:00 2001
From: NorthBlue333 
Date: Tue, 9 Jan 2024 14:01:14 +0100
Subject: [PATCH 1/3] [clang-format] Do not update cursor pos if no includes
 replacement

Signed-off-by: NorthBlue333 
---
 clang/lib/Format/Format.cpp |   3 +
 clang/unittests/Format/SortIncludesTest.cpp | 119 +++-
 2 files changed, 119 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 46ed5baaeacead..e12ad2ced38285 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3114,6 +3114,7 @@ static void sortCppIncludes(const FormatStyle &Style,
 return;
   }
 
+  const auto OldCursor = Cursor ? *Cursor : 0;
   std::string result;
   for (unsigned Index : Indices) {
 if (!result.empty()) {
@@ -3137,6 +3138,8 @@ static void sortCppIncludes(const FormatStyle &Style,
   // the entire range of blocks. Otherwise, no replacement is generated.
   if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
  IncludesBeginOffset, IncludesBlockSize {
+if (Cursor)
+*Cursor = OldCursor;
 return;
   }
 
diff --git a/clang/unittests/Format/SortIncludesTest.cpp 
b/clang/unittests/Format/SortIncludesTest.cpp
index 772eb53806b4b1..791ab7bb185ed9 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -6,19 +6,19 @@
 //
 
//===--===//
 
-#include "FormatTestUtils.h"
+#include "FormatTestBase.h"
 #include "clang/Format/Format.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
 
-#define DEBUG_TYPE "format-test"
+#define DEBUG_TYPE "sort-includes-test"
 
 namespace clang {
 namespace format {
 namespace {
 
-class SortIncludesTest : public ::testing::Test {
+class SortIncludesTest : public test::FormatTestBase {
 protected:
   std::vector GetCodeRange(StringRef Code) {
 return std::vector(1, tooling::Range(0, Code.size()));
@@ -821,6 +821,119 @@ TEST_F(SortIncludesTest, 
CalculatesCorrectCursorPositionWithRegrouping) {
   EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line
 }
 
+TEST_F(SortIncludesTest,
+   CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) 
{
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  FmtStyle.LineEnding = FormatStyle::LE_CRLF;
+  Style.IncludeCategories = {
+  {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}};
+  std::string Code = "#include \"a\"\r\n" // Start of line: 0
+ "\r\n"   // Start of line: 14
+ "#include \"b\"\r\n" // Start of line: 16
+ "\r\n"   // Start of line: 30
+ "#include \"c\"\r\n" // Start of line: 32
+ "\r\n"   // Start of line: 46
+ "int i;";// Start of line: 48
+  verifyNoChange(Code);
+  EXPECT_EQ(0u, newCursor(Code, 0));
+  EXPECT_EQ(14u, newCursor(Code, 14));
+  EXPECT_EQ(16u, newCursor(Code, 16));
+  EXPECT_EQ(30u, newCursor(Code, 30));
+  EXPECT_EQ(32u, newCursor(Code, 32));
+  EXPECT_EQ(46u, newCursor(Code, 46));
+  EXPECT_EQ(48u, newCursor(Code, 48));
+}
+
+TEST_F(
+SortIncludesTest,
+
CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF)
 {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  FmtStyle.LineEnding = FormatStyle::LE_CRLF;
+  Style.IncludeCategories = {{".*", 0, 0, false}};
+  std::string Code = "#include \"a\"\r\n" // Start of line: 0
+ "\r\n"   // Start of line: 14
+ "#include \"b\"\r\n" // Start of line: 16
+ "\r\n"   // Start of line: 30
+ "#include \"c\"\r\n" // Start of line: 32
+ "\r\n"   // Start of line: 46
+ "int i;";// Start of line: 48
+  std::string Expected = "#include \"a\"\r\n" // Start of line: 0
+ "#include \"b\"\r\n" // Start of line: 14
+ "#include \"c\"\r\n" // Start of line: 28
+ "\r\n"   // Start of line: 42
+ "int i;";// Start of line: 44
+  EXPECT_EQ(Expected, sort(Code));
+  EXPECT_EQ(0u, newCursor(Code, 0));
+  EXPECT_EQ(
+  14u,
+  newCursor(Code, 14)); // cursor on empty line in include block is ignored
+  EXPECT_EQ(14u, newCursor(Code, 16));
+  EXPECT_EQ(
+  30u,
+  newCursor(Code, 30)); // cursor on empty line in include block is ignored
+  EXPECT_EQ(28u, newCursor(Code, 32));
+  EXPECT_EQ(42u, newCursor(Code, 46));
+  EXPECT_EQ(44u, newCursor(Code, 48));
+}
+
+TEST_F(
+SortIncludesTest,
+
Calculates

[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [llvm] [RISCV] Add generic CPUs for profiles (PR #84877)

2024-04-24 Thread Pengcheng Wang via cfe-commits

wangpc-pp wrote:

Gentle ping.

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


[clang] [clang][NFC] Reformat suspicious condition (PR #89923)

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

https://github.com/shafik commented:

This makes sense, I added Nico since they added the change that brought in that 
line.

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -7398,6 +7398,26 @@ The full documentation is available here: 
https://docs.microsoft.com/en-us/windo
   }];
 }
 
+def HLSLPackOffsetDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The packoffset attribute is used to change the layout of a cbuffer.
+Attribute spelling in HLSL is: ``packoffset(c[Subcomponent[.component]])``.

hekota wrote:

This is different from the doc linked below that has:
 `packoffset( c[Subcomponent][.component] )`

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -42,6 +42,54 @@ Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool 
CBuffer,
 void SemaHLSL::ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace) {
   auto *BufDecl = cast(Dcl);
   BufDecl->setRBraceLoc(RBrace);
+
+  // Validate packoffset.
+  llvm::SmallVector> PackOffsetVec;
+  bool HasPackOffset = false;
+  bool HasNonPackOffset = false;
+  for (auto *Field : BufDecl->decls()) {
+VarDecl *Var = dyn_cast(Field);
+if (!Var)
+  continue;
+if (Field->hasAttr()) {
+  PackOffsetVec.emplace_back(Var, Field->getAttr());
+  HasPackOffset = true;
+} else {
+  HasNonPackOffset = true;
+}
+  }
+
+  if (HasPackOffset && HasNonPackOffset) {
+Diag(BufDecl->getLocation(), diag::err_hlsl_packoffset_mix);
+  } else if (HasPackOffset) {
+ASTContext &Context = getASTContext();
+// Make sure no overlap in packoffset.
+llvm::SmallDenseMap>
+PackOffsetRanges;
+for (auto &Pair : PackOffsetVec) {
+  VarDecl *Var = Pair.first;
+  HLSLPackOffsetAttr *Attr = Pair.second;
+  unsigned Size = Context.getTypeSize(Var->getType());
+  unsigned Begin = Attr->getOffset() * 32;
+  unsigned End = Begin + Size;
+  for (auto &Range : PackOffsetRanges) {
+VarDecl *OtherVar = Range.first;
+unsigned OtherBegin = Range.second.first;
+unsigned OtherEnd = Range.second.second;
+if (Begin < OtherEnd && OtherBegin < Begin) {
+  Diag(Var->getLocation(), diag::err_hlsl_packoffset_overlap)
+  << Var << OtherVar;
+  break;
+} else if (OtherBegin < End && Begin < OtherBegin) {
+  Diag(Var->getLocation(), diag::err_hlsl_packoffset_overlap)
+  << Var << OtherVar;
+  break;
+}

hekota wrote:

I don't think this covers all cases and it can be simplified. We know `Begin` 
is always less than `End`. The ranges do not overlap when `End <= OtherBegin || 
Begin >= OtherEnd`. So if I negate this condition I get:

```
if (End > OtherBegin && Begin < OtherEnd) {
  Diag(...)
}
```

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -42,6 +42,54 @@ Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool 
CBuffer,
 void SemaHLSL::ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace) {
   auto *BufDecl = cast(Dcl);
   BufDecl->setRBraceLoc(RBrace);
+
+  // Validate packoffset.
+  llvm::SmallVector> PackOffsetVec;
+  bool HasPackOffset = false;
+  bool HasNonPackOffset = false;
+  for (auto *Field : BufDecl->decls()) {
+VarDecl *Var = dyn_cast(Field);
+if (!Var)
+  continue;
+if (Field->hasAttr()) {
+  PackOffsetVec.emplace_back(Var, Field->getAttr());
+  HasPackOffset = true;
+} else {
+  HasNonPackOffset = true;
+}
+  }
+
+  if (HasPackOffset && HasNonPackOffset) {
+Diag(BufDecl->getLocation(), diag::err_hlsl_packoffset_mix);
+  } else if (HasPackOffset) {
+ASTContext &Context = getASTContext();
+// Make sure no overlap in packoffset.
+llvm::SmallDenseMap>

hekota wrote:

Why use a hashtable when no lookup is needed? You can use the SmallVector above 
to store (Var, Begin, End) when you find the attribute and then iterate over 
that. No need for 2 data structures.

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -183,6 +183,86 @@ void Parser::ParseHLSLAnnotations(ParsedAttributes &Attrs,
   return;
 }
   } break;
+  case ParsedAttr::AT_HLSLPackOffset: {
+// Parse 'packoffset( c[Subcomponent][.component] )'.
+// Check '('.
+if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after)) {
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+// Check c[Subcomponent] as an identifier.
+if (!Tok.is(tok::identifier)) {
+  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+StringRef OffsetStr = Tok.getIdentifierInfo()->getName();
+SourceLocation OffsetLoc = Tok.getLocation();
+if (OffsetStr[0] != 'c') {
+  Diag(Tok.getLocation(), diag::err_hlsl_packoffset_invalid_reg)
+  << OffsetStr;
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+OffsetStr = OffsetStr.substr(1);
+unsigned SubComponent = 0;
+if (!OffsetStr.empty()) {
+  // Make sure SubComponent is a number.
+  if (OffsetStr.getAsInteger(10, SubComponent)) {
+Diag(OffsetLoc.getLocWithOffset(1),
+ diag::err_hlsl_unsupported_register_number);
+return;
+  }
+}
+unsigned Component = 0;
+ConsumeToken(); // consume identifier.
+if (Tok.is(tok::period)) {
+  ConsumeToken(); // consume period.
+  if (!Tok.is(tok::identifier)) {
+Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
+SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+return;
+  }
+  StringRef ComponentStr = Tok.getIdentifierInfo()->getName();
+  SourceLocation SpaceLoc = Tok.getLocation();
+  ConsumeToken(); // consume identifier.
+  // Make sure Component is a single character.
+  if (ComponentStr.size() != 1) {
+Diag(SpaceLoc, diag::err_hlsl_unsupported_component) << ComponentStr;
+SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+return;
+  } else {

hekota wrote:

Nit - `else` is not needed here because the `if` branch returns.

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -183,6 +183,86 @@ void Parser::ParseHLSLAnnotations(ParsedAttributes &Attrs,
   return;
 }
   } break;
+  case ParsedAttr::AT_HLSLPackOffset: {
+// Parse 'packoffset( c[Subcomponent][.component] )'.
+// Check '('.
+if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after)) {
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+// Check c[Subcomponent] as an identifier.
+if (!Tok.is(tok::identifier)) {
+  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+StringRef OffsetStr = Tok.getIdentifierInfo()->getName();
+SourceLocation OffsetLoc = Tok.getLocation();
+if (OffsetStr[0] != 'c') {
+  Diag(Tok.getLocation(), diag::err_hlsl_packoffset_invalid_reg)
+  << OffsetStr;
+  SkipUntil(tok::r_paren, StopAtSemi); // skip through )
+  return;
+}
+OffsetStr = OffsetStr.substr(1);
+unsigned SubComponent = 0;
+if (!OffsetStr.empty()) {
+  // Make sure SubComponent is a number.
+  if (OffsetStr.getAsInteger(10, SubComponent)) {
+Diag(OffsetLoc.getLocWithOffset(1),
+ diag::err_hlsl_unsupported_register_number);

hekota wrote:

Add `SkipUntil(tok::r_paren, StopAtSemi); // skip through )`

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits


@@ -7314,6 +7314,47 @@ static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, 
Decl *D,
   D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
 }
 
+static void handleHLSLPackOffsetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  if (!isa(D)) {
+S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
+<< AL << "cbuffer constant";
+return;
+  }
+  auto *BufDecl = dyn_cast(D->getDeclContext());
+  if (!BufDecl) {
+S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
+<< AL << "cbuffer constant";
+return;

hekota wrote:

Both conditions issue the same diagnostic and `BufDecl` does not seem to be 
used after this. Maybe merge them?

`if (!isa(D) || !isa(D->getDeclContext()) {`

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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


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


[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-04-24 Thread Helena Kotas via cfe-commits

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-24 Thread A. Jiang via cfe-commits


@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -std=c++26 -fsyntax-only -verify %s
+
+auto&& f1() {
+  return 42; // expected-error{{returning reference to local temporary object}}
+}
+const double& f2() {
+  static int x = 42;
+  return x; // expected-error{{returning reference to local temporary object}}
+}
+auto&& id(auto&& r) {
+  return static_cast(r);
+}
+auto&& f3() {
+  return id(42);// OK, but probably a bug
+}
+
+static_assert(__is_convertible(int, const int &));
+static_assert(__is_nothrow_convertible(int, const int &));

frederick-vs-ja wrote:

I think these should go to `clang/test/SemaCXX/type-traits.cpp` (and be 
unconditionally tested). Note that test coverage for `__is_convertible` is 
already present.
https://github.com/llvm/llvm-project/blob/4b10ade1a6afa1fcff5752aaebd86a1611d499d7/clang/test/SemaCXX/type-traits.cpp#L2556-L2560

But test coverage for `__is_nothrow_convertible` where destination types are 
references seems missing. Perhaps we should add it in another PR.

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/77456

>From 6c184f9714c94af94c7692e1264061b8dc14e912 Mon Sep 17 00:00:00 2001
From: NorthBlue333 
Date: Tue, 9 Jan 2024 14:01:14 +0100
Subject: [PATCH 1/2] [clang-format] Do not update cursor pos if no includes
 replacement

Signed-off-by: NorthBlue333 
---
 clang/lib/Format/Format.cpp |   3 +
 clang/unittests/Format/SortIncludesTest.cpp | 119 +++-
 2 files changed, 119 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 46ed5baaeacead..e12ad2ced38285 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3114,6 +3114,7 @@ static void sortCppIncludes(const FormatStyle &Style,
 return;
   }
 
+  const auto OldCursor = Cursor ? *Cursor : 0;
   std::string result;
   for (unsigned Index : Indices) {
 if (!result.empty()) {
@@ -3137,6 +3138,8 @@ static void sortCppIncludes(const FormatStyle &Style,
   // the entire range of blocks. Otherwise, no replacement is generated.
   if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
  IncludesBeginOffset, IncludesBlockSize {
+if (Cursor)
+*Cursor = OldCursor;
 return;
   }
 
diff --git a/clang/unittests/Format/SortIncludesTest.cpp 
b/clang/unittests/Format/SortIncludesTest.cpp
index 772eb53806b4b1..791ab7bb185ed9 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -6,19 +6,19 @@
 //
 
//===--===//
 
-#include "FormatTestUtils.h"
+#include "FormatTestBase.h"
 #include "clang/Format/Format.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
 
-#define DEBUG_TYPE "format-test"
+#define DEBUG_TYPE "sort-includes-test"
 
 namespace clang {
 namespace format {
 namespace {
 
-class SortIncludesTest : public ::testing::Test {
+class SortIncludesTest : public test::FormatTestBase {
 protected:
   std::vector GetCodeRange(StringRef Code) {
 return std::vector(1, tooling::Range(0, Code.size()));
@@ -821,6 +821,119 @@ TEST_F(SortIncludesTest, 
CalculatesCorrectCursorPositionWithRegrouping) {
   EXPECT_EQ(27u, newCursor(Code, 28)); // Start of last line
 }
 
+TEST_F(SortIncludesTest,
+   CalculatesCorrectCursorPositionWhenNoReplacementsWithRegroupingAndCRLF) 
{
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  FmtStyle.LineEnding = FormatStyle::LE_CRLF;
+  Style.IncludeCategories = {
+  {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}};
+  std::string Code = "#include \"a\"\r\n" // Start of line: 0
+ "\r\n"   // Start of line: 14
+ "#include \"b\"\r\n" // Start of line: 16
+ "\r\n"   // Start of line: 30
+ "#include \"c\"\r\n" // Start of line: 32
+ "\r\n"   // Start of line: 46
+ "int i;";// Start of line: 48
+  verifyNoChange(Code);
+  EXPECT_EQ(0u, newCursor(Code, 0));
+  EXPECT_EQ(14u, newCursor(Code, 14));
+  EXPECT_EQ(16u, newCursor(Code, 16));
+  EXPECT_EQ(30u, newCursor(Code, 30));
+  EXPECT_EQ(32u, newCursor(Code, 32));
+  EXPECT_EQ(46u, newCursor(Code, 46));
+  EXPECT_EQ(48u, newCursor(Code, 48));
+}
+
+TEST_F(
+SortIncludesTest,
+
CalculatesCorrectCursorPositionWhenRemoveLinesReplacementsWithRegroupingAndCRLF)
 {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  FmtStyle.LineEnding = FormatStyle::LE_CRLF;
+  Style.IncludeCategories = {{".*", 0, 0, false}};
+  std::string Code = "#include \"a\"\r\n" // Start of line: 0
+ "\r\n"   // Start of line: 14
+ "#include \"b\"\r\n" // Start of line: 16
+ "\r\n"   // Start of line: 30
+ "#include \"c\"\r\n" // Start of line: 32
+ "\r\n"   // Start of line: 46
+ "int i;";// Start of line: 48
+  std::string Expected = "#include \"a\"\r\n" // Start of line: 0
+ "#include \"b\"\r\n" // Start of line: 14
+ "#include \"c\"\r\n" // Start of line: 28
+ "\r\n"   // Start of line: 42
+ "int i;";// Start of line: 44
+  EXPECT_EQ(Expected, sort(Code));
+  EXPECT_EQ(0u, newCursor(Code, 0));
+  EXPECT_EQ(
+  14u,
+  newCursor(Code, 14)); // cursor on empty line in include block is ignored
+  EXPECT_EQ(14u, newCursor(Code, 16));
+  EXPECT_EQ(
+  30u,
+  newCursor(Code, 30)); // cursor on empty line in include block is ignored
+  EXPECT_EQ(28u, newCursor(Code, 32));
+  EXPECT_EQ(42u, newCursor(Code, 46));
+  EXPECT_EQ(44u, newCursor(Code, 48));
+}
+
+TEST_F(
+SortIncludesTest,
+
Calculates

[clang] [clang] MangledSymbol: remove pointless copy of vector (PR #90012)

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

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

LGTM

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


[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-04-24 Thread NAKAMURA Takumi via cfe-commits


@@ -292,10 +292,36 @@ class CoverageMappingBuilder {
 return SM.getLocForEndOfFile(SM.getFileID(Loc));
   }
 
-  /// Find out where the current file is included or macro is expanded.
-  SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
-return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
-   : SM.getIncludeLoc(SM.getFileID(Loc));
+  /// Find out where a macro is expanded. If the immediate result is a
+  /// , keep looking until the result isn't. Return the source
+  /// range of the found result, or std::nullopt if the while loop didn't get
+  /// executed, which means the location wasn't changed.
+  std::optional getNonScratchExpansion(SourceLocation Loc) {
+std::optional EndLoc = std::nullopt;
+while (Loc.isMacroID() &&
+   SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
+  auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
+  Loc = ExpansionRange.getBegin();
+  EndLoc = ExpansionRange.getEnd();
+}
+if (EndLoc.has_value())
+  return SourceRange(Loc, EndLoc.value());

chapuni wrote:

I wrongly supposed `isWrittenInScratchSpace()` would return `SourceRange`. 
Actually returns `CharSourceRange`.

You may rewind them with your previous change, if you prefer. The current 
implementation is not clean a bit.

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

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

owenca wrote:

> I have squashed the commits in only one. Note that I have left the failing 
> tests in the commit, I am not sure if I should remove them or not.

Unfortunately, this wiped out my updates that fixed a formatting error and 
added `#if 0` for the failing tests.

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


[clang] [clang-repl] Fix the process return code if diagnostics occurred. (PR #89879)

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

vgvassilev wrote:

The Unix pre-merge seems okay, however the windows pre-merge check is doing 
nothing for more than 12h. I will move forward. 

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


[clang] [Clang] [CodeGen] Perform derived-to-base conversion on explicit object parameter in lambda (PR #89828)

2024-04-24 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

@Sirraide See example of 
https://github.com/llvm/llvm-project/blob/662ef8604268b207910225ecca90daf30a46720b/clang/test/CXX/drs/dr25xx.cpp#L148
In this case, the date should be 2024-04-19.

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


[clang] 4b10ade - [clang-format] Annotate enum braces as BK_Block (#89871)

2024-04-24 Thread via cfe-commits

Author: Owen Pan
Date: 2024-04-24T21:46:45-07:00
New Revision: 4b10ade1a6afa1fcff5752aaebd86a1611d499d7

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

LOG: [clang-format] Annotate enum braces as BK_Block (#89871)

Fixes #89759.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 6e4e6901e473f7..3a263955a6a8fe 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -534,11 +534,11 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 case tok::r_brace:
   if (LBraceStack.empty())
 break;
-  if (LBraceStack.back().Tok->is(BK_Unknown)) {
+  if (auto *LBrace = LBraceStack.back().Tok; LBrace->is(BK_Unknown)) {
 bool ProbablyBracedList = false;
 if (Style.Language == FormatStyle::LK_Proto) {
   ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
-} else {
+} else if (LBrace->isNot(TT_EnumLBrace)) {
   // Using OriginalColumn to distinguish between ObjC methods and
   // binary operators is a bit hacky.
   bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
@@ -552,7 +552,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 
   // If we already marked the opening brace as braced list, the closing
   // must also be part of it.
-  ProbablyBracedList = LBraceStack.back().Tok->is(TT_BracedListLBrace);
+  ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
 
   ProbablyBracedList = ProbablyBracedList ||
(Style.isJavaScript() &&
@@ -608,13 +608,9 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 ProbablyBracedList = true;
   }
 }
-if (ProbablyBracedList) {
-  Tok->setBlockKind(BK_BracedInit);
-  LBraceStack.back().Tok->setBlockKind(BK_BracedInit);
-} else {
-  Tok->setBlockKind(BK_Block);
-  LBraceStack.back().Tok->setBlockKind(BK_Block);
-}
+const auto BlockKind = ProbablyBracedList ? BK_BracedInit : BK_Block;
+Tok->setBlockKind(BlockKind);
+LBrace->setBlockKind(BlockKind);
   }
   LBraceStack.pop_back();
   break;
@@ -2418,6 +2414,7 @@ bool UnwrappedLineParser::tryToParseChildBlock() {
 }
 
 bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) {
+  assert(!IsAngleBracket || !IsEnum);
   bool HasError = false;
 
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
@@ -2440,8 +2437,11 @@ bool UnwrappedLineParser::parseBracedList(bool 
IsAngleBracket, bool IsEnum) {
   }
 }
 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
-  if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
-addUnwrappedLine();
+  if (IsEnum) {
+FormatTok->setBlockKind(BK_Block);
+if (!Style.AllowShortEnumsOnASingleLine)
+  addUnwrappedLine();
+  }
   nextToken();
   return !HasError;
 }

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 6b8ab441cb46f8..dff5251d2e9406 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2915,6 +2915,23 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   ASSERT_EQ(Tokens.size(), 10u) << Tokens;
   EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[7], BK_BracedInit);
+
+  Tokens = annotate("#ifdef DEBUG_ENABLED\n"
+"#else\n"
+"#endif\n"
+"class RenderingServer : Object {\n"
+"#ifndef DISABLE_DEPRECATED\n"
+"  enum Features {\n"
+"FEATURE_SHADERS,\n"
+"FEATURE_MULTITHREADED,\n"
+"  };\n"
+"#endif\n"
+"};");
+  ASSERT_EQ(Tokens.size(), 29u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[11], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[17], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[22], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[26], BK_Block);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) {



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


[clang] [clang-format] Annotate enum braces as BK_Block (PR #89871)

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

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


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

2024-04-24 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp updated 
https://github.com/llvm/llvm-project/pull/83774

>From 2ed73672a548b77a36675343b420ef57266e46ab Mon Sep 17 00:00:00 2001
From: wangpc 
Date: Fri, 14 Jul 2023 10:38:14 +0800
Subject: [PATCH] [clang] Enable sized deallocation by default in C++14 onwards

Since C++14 has been released for about nine years and most standard
libraries have implemented sized deallocation functions, it's time to
make this feature default again.

Differential Revision: https://reviews.llvm.org/D112921
---
 .../clangd/unittests/FindTargetTests.cpp  |   4 +-
 .../checkers/misc/new-delete-overloads.cpp|  10 -
 clang/docs/ReleaseNotes.rst   |   5 +
 clang/include/clang/Driver/Options.td |   8 +-
 clang/lib/Driver/ToolChains/Clang.cpp |  13 +-
 clang/lib/Driver/ToolChains/Darwin.cpp|  58 -
 clang/lib/Driver/ToolChains/Darwin.h  |   4 +
 clang/lib/Driver/ToolChains/ZOS.cpp   |   6 +
 clang/test/AST/ast-dump-expr-json.cpp |   2 +-
 clang/test/AST/ast-dump-expr.cpp  |   2 +-
 clang/test/AST/ast-dump-stmt-json.cpp | 244 +-
 clang/test/Analysis/cxxnewexpr-callback.cpp   |   4 +-
 .../basic.stc.dynamic.deallocation/p2.cpp |   2 +-
 clang/test/CXX/drs/cwg292.cpp |  17 +-
 .../test/CXX/expr/expr.unary/expr.new/p14.cpp |   2 +-
 .../CodeGenCXX/cxx1y-sized-deallocation.cpp   |  10 +-
 .../CodeGenCXX/cxx1z-aligned-allocation.cpp   |   6 +-
 .../CodeGenCXX/cxx2a-destroying-delete.cpp|   4 +-
 clang/test/CodeGenCXX/delete-two-arg.cpp  |   4 +-
 clang/test/CodeGenCXX/delete.cpp  |  12 +-
 clang/test/CodeGenCXX/dllimport.cpp   |   4 +-
 clang/test/CodeGenCXX/new.cpp |   6 +-
 .../coro-aligned-alloc-2.cpp  |   2 -
 .../CodeGenCoroutines/coro-aligned-alloc.cpp  |   6 +-
 clang/test/CodeGenCoroutines/coro-alloc.cpp   |   6 +-
 clang/test/CodeGenCoroutines/coro-cleanup.cpp |   6 +-
 clang/test/CodeGenCoroutines/coro-dealloc.cpp |   2 -
 clang/test/CodeGenCoroutines/coro-gro.cpp |   3 +-
 clang/test/CodeGenCoroutines/pr56919.cpp  |   9 +-
 clang/test/Lexer/cxx-features.cpp |  20 +-
 clang/test/PCH/cxx1z-aligned-alloc.cpp|  10 +-
 clang/test/SemaCXX/MicrosoftExtensions.cpp|   8 +-
 .../SemaCXX/builtin-operator-new-delete.cpp   |   2 +-
 .../test/SemaCXX/cxx1y-sized-deallocation.cpp |   2 +-
 .../unavailable_aligned_allocation.cpp|  15 +-
 clang/tools/clang-repl/CMakeLists.txt |  59 +
 clang/unittests/Interpreter/CMakeLists.txt|  59 +
 .../StaticAnalyzer/CallEventTest.cpp  |   2 +-
 clang/www/cxx_status.html |  11 +-
 .../support.dynamic/libcpp_deallocate.sh.cpp  |   3 +
 .../sized_delete_array14.pass.cpp |   8 +-
 .../new.delete.single/sized_delete14.pass.cpp |   8 +-
 42 files changed, 555 insertions(+), 113 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 799a549ff0816e..88aae2729904f4 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -839,7 +839,9 @@ TEST_F(TargetDeclTest, OverloadExpr) {
   [[delete]] x;
 }
   )cpp";
-  EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
+  // Sized deallocation is enabled by default in C++14 onwards.
+  EXPECT_DECLS("CXXDeleteExpr",
+   "void operator delete(void *, unsigned long) noexcept");
 }
 
 TEST_F(TargetDeclTest, DependentExprs) {
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
index 78f021144b2e19..f86fe8a4c5b14f 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
@@ -12,16 +12,6 @@ struct S {
 // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has 
no matching declaration of 'operator delete' at the same scope
 void *operator new(size_t size) noexcept(false);
 
-struct T {
-  // Sized deallocations are not enabled by default, and so this new/delete 
pair
-  // does not match. However, we expect only one warning, for the new, because
-  // the operator delete is a placement delete and we do not warn on 
mismatching
-  // placement operations.
-  // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' 
has no matching declaration of 'operator delete' at the same scope
-  void *operator new(size_t size) noexcept;
-  void operator delete(void *ptr, size_t) noexcept; // ok only if sized 
deallocation is enabled
-};
-
 struct U {
   void *operator new(size_t size) noexcept;
   void operator delete(void *ptr) noexcept;
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7bea43ec64f062..5

[clang] [clang-format] Remove YAML hack to emit a BasedOnStyle comment (PR #89228)

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

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


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


[clang] [clang] deprecate frelaxed-template-template-args, make it on by default (PR #89807)

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

mizvekov wrote:

So Jason pointed out that GCC's provisional wording for CWG2398 picks a dubious 
candidate for this example:
```C++
template struct match2;

template class t1,typename T>
struct match2, typename t1::type > { typedef int type; }; // #5
 

template class t2,typename T0,typename T1>
struct match2, typename t2::type > { typedef int type; }; // 
#6 

template  struct Q { typedef int type; };
match2, int> m;
```

They pick #6, where with this PR we stay with ambiguous.
According to [this GCC 
bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114841), he suggests changing 
GCC to adopt the wording proposed here.

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-24 Thread A. Jiang via cfe-commits


@@ -8340,8 +8340,17 @@ void Sema::checkInitializerLifetime(const 
InitializedEntity &Entity,
 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 
2
 << DiagRange;
   } else {
-Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
- << Entity.getType()->isReferenceType() << DiagRange;
+// P2748R5: Disallow Binding a Returned Glvalue to a Temporary.
+// [stmt.return]/p6: In a function whose return type is a reference,
+// other than an invented function for std::is_convertible 
([meta.rel]),
+// a return statement that binds the returned reference to a temporary
+// expression ([class.temporary]) is ill-formed.

frederick-vs-ja wrote:

> I wanted to implement LWG4028 as well

I don't know which part of LWG4028 is "not yet implemented". As the submitter, 
my intent was just to reflect what implementations actually did and to avoid 
crux in the core wording.

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


[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-04-24 Thread Wentao Zhang via cfe-commits

https://github.com/whentojump updated 
https://github.com/llvm/llvm-project/pull/89869

>From 968ef430dd09ee4545323426d0c5b550c6a0f690 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Fri, 19 Apr 2024 15:16:05 +0900
Subject: [PATCH 1/6] [MC/DC][Coverage] Workaround for `##` conditions

A synthesized identifier with `##` is emitted to ``.
`llvm-cov` cannot handle ` since it doesn't have actual files.

As a workaround, peel `` to the actual definition if the 
definition is present.

This affects predefined built-in macros, like __LINE__.

Fixes #87000
---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 12 +-
 clang/test/CoverageMapping/builtinmacro.c |  2 +-
 clang/test/CoverageMapping/macros.c   |  8 ++--
 .../test/CoverageMapping/mcdc-scratch-space.c | 39 +++
 4 files changed, 56 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CoverageMapping/mcdc-scratch-space.c

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 733686d4946b3c..f92706f579a7b9 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -339,8 +339,18 @@ class CoverageMappingBuilder {
 
 llvm::SmallSet Visited;
 SmallVector, 8> FileLocs;
-for (const auto &Region : SourceRegions) {
+for (auto &Region : SourceRegions) {
   SourceLocation Loc = Region.getBeginLoc();
+
+  // Replace Region with its definition if it is in .
+  while (Loc.isMacroID() &&
+ SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
+auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
+Loc = ExpansionRange.getBegin();
+Region.setStartLoc(Loc);
+Region.setEndLoc(ExpansionRange.getEnd());
+  }
+
   FileID File = SM.getFileID(Loc);
   if (!Visited.insert(File).second)
 continue;
diff --git a/clang/test/CoverageMapping/builtinmacro.c 
b/clang/test/CoverageMapping/builtinmacro.c
index abcdc191523a5d..5d5a176aa7d87e 100644
--- a/clang/test/CoverageMapping/builtinmacro.c
+++ b/clang/test/CoverageMapping/builtinmacro.c
@@ -4,7 +4,7 @@
 
 // CHECK: filename
 const char *filename (const char *name) { // CHECK-NEXT: File 0, [[@LINE]]:41 
-> [[@LINE+3]]:2 = #0
-  static const char this_file[] = __FILE__;
+  static const char this_file[] = __FILE__; // CHECK-NEXT: File 0, 
[[@LINE]]:35 -> [[@LINE]]:35 = #0
   return this_file;
 }
 
diff --git a/clang/test/CoverageMapping/macros.c 
b/clang/test/CoverageMapping/macros.c
index 6bd3be434139a2..fcf21170ef135c 100644
--- a/clang/test/CoverageMapping/macros.c
+++ b/clang/test/CoverageMapping/macros.c
@@ -80,12 +80,14 @@ void func7(void) { // CHECK-NEXT: File 0, [[@LINE]]:18 -> 
[[@LINE+6]]:2 = #0
   int kk,ll;   // CHECK-NEXT: File 0, [[@LINE+1]]:7 -> [[@LINE+1]]:8 = #0
   if (k)   // CHECK-NEXT: Branch,File 0, [[@LINE]]:7 -> [[@LINE]]:8 = 
#1
 m(k);  // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:9 -> [[@LINE]]:5 = #1
-  else // CHECK-NEXT: Expansion,File 0, [[@LINE-1]]:5 -> 
[[@LINE-1]]:6 = #0
+  else // CHECK-NEXT: Expansion,File 0, [[@LINE-1]]:5 -> 
[[@LINE-1]]:6 = #1
 l = m(l);  // CHECK-NEXT: Gap,File 0, [[@LINE-2]]:7 -> [[@LINE]]:5 = 
(#0 - #1)
 }  // CHECK-NEXT: File 0, [[@LINE-1]]:5 -> [[@LINE-1]]:10 = 
(#0 - #1)
// CHECK-NEXT: Expansion,File 0, [[@LINE-2]]:9 -> 
[[@LINE-2]]:10 = (#0 - #1)
-   // CHECK-NEXT: File 1, [[@LINE-9]]:14 -> [[@LINE-9]]:18 = #0
-   // CHECK-NEXT: File 2, [[@LINE-10]]:14 -> [[@LINE-10]]:15 = 
(#0 - #1)
+   // CHECK-NEXT: File 1, [[@LINE-9]]:14 -> [[@LINE-9]]:17 = #1
+   // CHECK-NEXT: File 1, [[@LINE-10]]:14 -> [[@LINE-10]]:18 = 
#0
+   // CHECK-NEXT: File 2, [[@LINE-11]]:14 -> [[@LINE-11]]:17 = 
(#0 - #1)
+   // CHECK-NEXT: File 2, [[@LINE-12]]:14 -> [[@LINE-12]]:15 = 
(#0 - #1)
 
 int main(int argc, const char *argv[]) {
   func();
diff --git a/clang/test/CoverageMapping/mcdc-scratch-space.c 
b/clang/test/CoverageMapping/mcdc-scratch-space.c
new file mode 100644
index 00..1b8735cd27445a
--- /dev/null
+++ b/clang/test/CoverageMapping/mcdc-scratch-space.c
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c99 -fcoverage-mcdc 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only %s | FileCheck %s
+
+// CHECK: builtin_macro0:
+int builtin_macro0(int a) {
+  // CHECK: Decision,File 0, [[@LINE+1]]:11 -> [[@LINE+2]]:15 = M:0, C:2
+  return (__LINE__ // CHECK: Branch,File 0, [[@LINE]]:11 -> [[@LINE]]:11 = 0, 
0 [1,2,0]
+  && a); //   CHECK: Branch,File 0, [[@LINE]]:14 -> [[@LINE]]:15 = #2, 
(#1 - #2) [2,0,0]
+}
+
+// CHECK: builtin_macro1:
+int builtin_macro1(int a) {
+  // CHECK: Decision,File 0, [[@LINE+1]]:11 -> [[@LINE+2]]:22 = M:0, C:2
+  return (a // CHECK: Branch,File 0, [[@LINE]]:11 -> [[@LINE]]:12 = (#0 - #1), 
#1

[clang] [clang] pointer to member with qualified-id enclosed in parentheses in unevaluated context should be invalid (PR #89713)

2024-04-24 Thread via cfe-commits


@@ -27,3 +26,20 @@ namespace rdar10544564 {
   X (Y::*func_mem_ptr1)() = &Y::memfunc1;
   X (Y::*func_mem_ptr2)() = &Y::memfunc2;
 }
+
+namespace test2 {
+  struct A {
+int val;
+void func() {}
+  };
+
+  void test() {
+decltype(&(A::val)) ptr1; // expected-error {{invalid use of non-static 
data member 'val'}}
+int A::* ptr2 = &(A::val); // expected-error {{invalid use of non-static 
data member 'val'}}
+
+// FIXME: Error messages in these cases are less than clear, we can do
+// better.
+int size = sizeof(&(A::func)); // expected-error {{call to non-static 
member function without an object argument}}
+void (A::* ptr3)() = &(A::func); // expected-error {{call to non-static 
member function without an object argument}}

zwuis wrote:

> I would expect `err_invalid_non_static_member_use` to be used there too (or 
> rather, that case should be consistent with above)

This inconsistency is irrelevant to PR 40906. I am confused about the following 
questions:

1. Do I need to remove these tests?
2. Do I need to fix this inconsistency in this PR, or a new PR?
3. Should I open an issue for it?

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


[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)

2024-04-24 Thread Troy Butler via cfe-commits

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


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

2024-04-24 Thread via cfe-commits

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

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

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

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1f18e0d5ba409a..8e35c801bc9599 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -1431,7 +1431,10 @@ Value *ScalarExprEmitter::EmitScalarCast(Value *Src, 
QualType SrcType,
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }
 
-  if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
+  if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
+Value *FloatVal = Builder.CreateFPExt(Src, Builder.getFloatTy(), "fpext");
+return Builder.CreateFPTrunc(FloatVal, DstTy, "fptrunc");
+  } else if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
 return Builder.CreateFPTrunc(Src, DstTy, "conv");
   return Builder.CreateFPExt(Src, DstTy, "conv");
 }
@@ -1906,7 +1909,15 @@ Value 
*ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
   } else {
 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
"Unknown real conversion");
-if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
+if ((DstEltTy->is16bitFPTy() && SrcEltTy->is16bitFPTy())) {
+  auto *ScrVecTy = cast(SrcTy);
+  Value *FloatVal = Builder.CreateFPExt(
+  Src,
+  llvm::VectorType::get(Builder.getFloatTy(),
+ScrVecTy->getElementCount()),
+  "fpext");
+  Res = Builder.CreateFPTrunc(FloatVal, DstTy, "fptrunc");
+} else if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
   Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
 else
   Res = Builder.CreateFPExt(Src, DstTy, "conv");
diff --git a/clang/test/CodeGen/X86/bfloat16-convert-half.c 
b/clang/test/CodeGen/X86/bfloat16-convert-half.c
new file mode 100644
index 00..85ebe8502bc033
--- /dev/null
+++ b/clang/test/CodeGen/X86/bfloat16-convert-half.c
@@ -0,0 +1,165 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -disable-O0-optnone 
-emit-llvm \
+// RUN: %s -o - | opt -S -passes=mem2reg | FileCheck %s
+
+// CHECK-LABEL: define dso_local half @test_convert_from_bf16_to_fp16(
+// CHECK-SAME: bfloat noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext bfloat [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to half
+// CHECK-NEXT:ret half [[FPTRUNC]]
+//
+_Float16 test_convert_from_bf16_to_fp16(__bf16 a) {
+return (_Float16)a;
+}
+
+// CHECK-LABEL: define dso_local bfloat @test_convert_from_fp16_to_bf16(
+// CHECK-SAME: half noundef [[A:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[FPEXT:%.*]] = fpext half [[A]] to float
+// CHECK-NEXT:[[FPTRUNC:%.*]] = fptrunc float [[FPEXT]] to bfloat
+// CHECK-NEXT:ret bfloat [[FPTRUNC]]
+//
+__bf16 test_convert_from_fp16_to_bf16(_Float16 a) {
+return (__bf16)a;
+}
+
+typedef _Float16 half2 __attribute__((ext_vector_type(2)));
+typedef _Float16 half4 __attribute__((ext_vector_type(4)));
+
+typedef __bf16 bfloat2 __attribute__((ext_vector_type(2)));
+typedef __bf16 bfloat4 __attribute__((ext_vector_type(4)));
+
+// CHECK-LABEL: define dso_local i32 @test_cast_from_half2_to_bfloat2(
+// CHECK-SAME: i32 noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <2 x bfloat>, align 4
+// CHECK-NEXT:[[IN:%.*]] = alloca <2 x half>, align 4
+// CHECK-NEXT:store i32 [[IN_COERCE]], ptr [[IN]], align 4
+// CHECK-NEXT:[[IN1:%.*]] = load <2 x half>, ptr [[IN]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x half> [[IN1]] to <2 x bfloat>
+// CHECK-NEXT:store <2 x bfloat> [[TMP0]], ptr [[RETVAL]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[RETVAL]], align 4
+// CHECK-NEXT:ret i32 [[TMP1]]
+//
+bfloat2 test_cast_from_half2_to_bfloat2(half2 in) {
+  return (bfloat2)in;
+}
+
+
+// CHECK-LABEL: define dso_local double @test_cast_from_half4_to_bfloat4(
+// CHECK-SAME: double noundef [[IN_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca <4 x bfloat>, align 8
+// CHECK-NEXT:[[IN:%.*]] = alloca <4 x half>, align 8
+// CHECK-NEXT:store double [[IN_COERCE]], ptr [[IN]], align 8
+// CHECK-NEXT:[[IN1:%.*]] = load <4 x half>, ptr [[IN]], align 8
+// CHECK-NEXT:[[TMP0:%.*

[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

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

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-24 Thread Kelvin Li via cfe-commits


@@ -24,6 +24,7 @@ add_flang_library(FIRBuilder
   Runtime/Inquiry.cpp
   Runtime/Intrinsics.cpp
   Runtime/Numeric.cpp
+  Runtime/Main.cpp

kkwli wrote:

I think this list is in alphabetical order?

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-24 Thread Kelvin Li via cfe-commits

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

LG

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-24 Thread Kelvin Li via cfe-commits

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


[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

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

MaskRay wrote:

There may be an example that the current -mrelax-all default penalizes 
Thumb/Thumb2 code size as well, but I haven't found an example.

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


[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

2024-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

Some assembly mnemonics may assemble to instructions of different
lengths. The longer form is to support instructions like a long branch.
-mrelax-all enables `MCRelaxAll`, which expands instructions to the long
form regardless of whether a short form suffices, while -mno-relax-all
only expands instructions when needed.

```
// x86 example
void foo(int a) {
  // -mno-relax-all or gas: short jump (2 bytes)
  // -mrelax-all: near jump (6 bytes)
  if (a) bar();
}
```

The -mrelax-all default for non-RISCV -O0 increases code size with
non-perceivable compile time difference for a stage-2 x86-64 build of
lld.
```
-mrelax-all:file size: 58.2MiB   VM size: 49.7MiB
-mno-relax-all: file size: 60.9MiB   VM size: 52.4MiB
```

There is no compile time difference (other than noise) GNU assembler
doesn't expand instructions by default. Let's remove the -mrelax-all default.


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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+10-42) 
- (modified) clang/test/Driver/integrated-as.c (+1-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 5f5d720cf759f4..651a2b5aac368b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -835,46 +835,6 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, 
Compilation &C,
   }
 }
 
-/// Check whether the given input tree contains any compilation actions.
-static bool ContainsCompileAction(const Action *A) {
-  if (isa(A) || isa(A))
-return true;
-
-  return llvm::any_of(A->inputs(), ContainsCompileAction);
-}
-
-/// Check if -relax-all should be passed to the internal assembler.
-/// This is done by default when compiling non-assembler source with -O0.
-static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
-  bool RelaxDefault = true;
-
-  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
-RelaxDefault = A->getOption().matches(options::OPT_O0);
-
-  // RISC-V requires an indirect jump for offsets larger than 1MiB. This cannot
-  // be done by assembler branch relaxation as it needs a free temporary
-  // register. Because of this, branch relaxation is handled by a MachineIR
-  // pass before the assembler. Forcing assembler branch relaxation for -O0
-  // makes the MachineIR branch relaxation inaccurate and it will miss cases
-  // where an indirect branch is necessary. To avoid this issue we are
-  // sacrificing the compile time improvement of using -mrelax-all for -O0.
-  if (C.getDefaultToolChain().getTriple().isRISCV())
-RelaxDefault = false;
-
-  if (RelaxDefault) {
-RelaxDefault = false;
-for (const auto &Act : C.getActions()) {
-  if (ContainsCompileAction(Act)) {
-RelaxDefault = true;
-break;
-  }
-}
-  }
-
-  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
-  RelaxDefault);
-}
-
 static void
 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
@@ -2472,8 +2432,16 @@ static void 
CollectArgsForIntegratedAssembler(Compilation &C,
   const ArgList &Args,
   ArgStringList &CmdArgs,
   const Driver &D) {
-  if (UseRelaxAll(C, Args))
-CmdArgs.push_back("-mrelax-all");
+  // Default to -mno-relax-all.
+  //
+  // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
+  // cannot be done by assembler branch relaxation as it needs a free temporary
+  // register. Because of this, branch relaxation is handled by a MachineIR 
pass
+  // before the assembler. Forcing assembler branch relaxation for -O0 makes 
the
+  // MachineIR branch relaxation inaccurate and it will miss cases where an
+  // indirect branch is necessary.
+  Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
+options::OPT_mno_relax_all);
 
   // Only default to -mincremental-linker-compatible if we think we are
   // targeting the MSVC linker.
diff --git a/clang/test/Driver/integrated-as.c 
b/clang/test/Driver/integrated-as.c
index e78fde873cf47f..b0a26f6011b0c7 100644
--- a/clang/test/Driver/integrated-as.c
+++ b/clang/test/Driver/integrated-as.c
@@ -3,7 +3,7 @@
 // RUN: %clang -### -c -save-temps -integrated-as --target=x86_64 %s 2>&1 | 
FileCheck %s
 
 // CHECK: cc1as
-// CHECK: -mrelax-all
+// CHECK-NOT: -mrelax-all
 
 // RISC-V does not enable -mrelax-all
 // RUN: %clang -### -c -save-temps -integrated-as --target=riscv64 %s 2>&1 | 
FileCheck %s -check-prefix=RISCV-RELAX

``




https://github.com/llvm/llvm-project/pull/90013
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi

[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

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

https://github.com/MaskRay created 
https://github.com/llvm/llvm-project/pull/90013

Some assembly mnemonics may assemble to instructions of different
lengths. The longer form is to support instructions like a long branch.
-mrelax-all enables `MCRelaxAll`, which expands instructions to the long
form regardless of whether a short form suffices, while -mno-relax-all
only expands instructions when needed.

```
// x86 example
void foo(int a) {
  // -mno-relax-all or gas: short jump (2 bytes)
  // -mrelax-all: near jump (6 bytes)
  if (a) bar();
}
```

The -mrelax-all default for non-RISCV -O0 increases code size with
non-perceivable compile time difference for a stage-2 x86-64 build of
lld.
```
-mrelax-all:file size: 58.2MiB   VM size: 49.7MiB
-mno-relax-all: file size: 60.9MiB   VM size: 52.4MiB
```

There is no compile time difference (other than noise) GNU assembler
doesn't expand instructions by default. Let's remove the -mrelax-all default.


>From f1cbcac55c0816882277a1a3ecf1af47e7558bb3 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Wed, 24 Apr 2024 20:14:08 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/lib/Driver/ToolChains/Clang.cpp | 52 ++-
 clang/test/Driver/integrated-as.c |  2 +-
 2 files changed, 11 insertions(+), 43 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 5f5d720cf759f4..651a2b5aac368b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -835,46 +835,6 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, 
Compilation &C,
   }
 }
 
-/// Check whether the given input tree contains any compilation actions.
-static bool ContainsCompileAction(const Action *A) {
-  if (isa(A) || isa(A))
-return true;
-
-  return llvm::any_of(A->inputs(), ContainsCompileAction);
-}
-
-/// Check if -relax-all should be passed to the internal assembler.
-/// This is done by default when compiling non-assembler source with -O0.
-static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
-  bool RelaxDefault = true;
-
-  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
-RelaxDefault = A->getOption().matches(options::OPT_O0);
-
-  // RISC-V requires an indirect jump for offsets larger than 1MiB. This cannot
-  // be done by assembler branch relaxation as it needs a free temporary
-  // register. Because of this, branch relaxation is handled by a MachineIR
-  // pass before the assembler. Forcing assembler branch relaxation for -O0
-  // makes the MachineIR branch relaxation inaccurate and it will miss cases
-  // where an indirect branch is necessary. To avoid this issue we are
-  // sacrificing the compile time improvement of using -mrelax-all for -O0.
-  if (C.getDefaultToolChain().getTriple().isRISCV())
-RelaxDefault = false;
-
-  if (RelaxDefault) {
-RelaxDefault = false;
-for (const auto &Act : C.getActions()) {
-  if (ContainsCompileAction(Act)) {
-RelaxDefault = true;
-break;
-  }
-}
-  }
-
-  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
-  RelaxDefault);
-}
-
 static void
 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
@@ -2472,8 +2432,16 @@ static void 
CollectArgsForIntegratedAssembler(Compilation &C,
   const ArgList &Args,
   ArgStringList &CmdArgs,
   const Driver &D) {
-  if (UseRelaxAll(C, Args))
-CmdArgs.push_back("-mrelax-all");
+  // Default to -mno-relax-all.
+  //
+  // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
+  // cannot be done by assembler branch relaxation as it needs a free temporary
+  // register. Because of this, branch relaxation is handled by a MachineIR 
pass
+  // before the assembler. Forcing assembler branch relaxation for -O0 makes 
the
+  // MachineIR branch relaxation inaccurate and it will miss cases where an
+  // indirect branch is necessary.
+  Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
+options::OPT_mno_relax_all);
 
   // Only default to -mincremental-linker-compatible if we think we are
   // targeting the MSVC linker.
diff --git a/clang/test/Driver/integrated-as.c 
b/clang/test/Driver/integrated-as.c
index e78fde873cf47f..b0a26f6011b0c7 100644
--- a/clang/test/Driver/integrated-as.c
+++ b/clang/test/Driver/integrated-as.c
@@ -3,7 +3,7 @@
 // RUN: %clang -### -c -save-temps -integrated-as --target=x86_64 %s 2>&1 | 
FileCheck %s
 
 // CHECK: cc1as
-// CHECK: -mrelax-all
+// CHECK-NOT: -mrelax-all
 
 // RISC-V does not enable -mrelax-all
 // 

[clang] [clang] deprecate frelaxed-template-template-args, make it on by default (PR #89807)

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


@@ -507,10 +507,62 @@ static TemplateDeductionResult 
DeduceNonTypeTemplateArgument(
   S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
 }
 
+static NamedDecl *DeduceTemplateArguments(Sema &S, NamedDecl *A,
+  TemplateArgument Default) {
+  switch (A->getKind()) {
+  case Decl::TemplateTypeParm: {
+auto *T = cast(A);
+// FIXME: DefaultArgument can't represent a pack.
+if (T->isParameterPack())

mizvekov wrote:

The test `foo` in 
`clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp` exercises 
this, but it doesn't involve any default arguments, so any effects are 
incidental / harmless.

I have actually just come up with a relevant test case that shows something 
interesting that I wasn't aware before, this could possibly be new info for the 
core issue.

https://godbolt.org/z/rnbzhnqG7

This shows a change of behavior introduced by P05522, only instead of 
introducing ambiguity, it causes different candidates to be picked. Also 
affects GCC.

---

Regarding the FIXME:

So the (Type | NonType | Template) template parameter declarations store the 
default argument for themselves. They have a `setDefaultArgument` method for 
setting that. While for template template parameter declarations the 
`setDefaultArgument` takes a `TemplateArgument`, and that means it can use any 
kind of TemplateArgument as a default argument, including packs.

The same is not true for (Type | NonType) template parameter declarations, 
their `setDefaultArgument` only takes a (Type / Expression), which means a pack 
can't be passed.

This is done presumably to save space in those declarations, while a Type and 
an Expression are a single pointer, a `TemplateArgument` is considerably 
larger, and you would need at least a pointer and an integer to represent a 
pack.

To 'fix' this FIXME, we would have to change that, and allow those declarations 
to be larger in at least some circumstances.

https://github.com/llvm/llvm-project/pull/89807
___
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-24 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(

ahatanaka wrote:

I've updated the patch to pass a category string to the builtin. The artificial 
function name has the format `::` where `` 
is always `__builtin_verbose_trap`.

We should probably use something other than `:` for the separator as users 
might want to use it in the category or message string (e.g., 
`boost::some_library_name`).

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] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)

2024-04-24 Thread via cfe-commits

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

Thanks for the update! I'll merge the PR within ~a day if nobody objects.

https://github.com/llvm/llvm-project/pull/89512
___
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-24 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak updated 
https://github.com/llvm/llvm-project/pull/79230

>From 95200f3bb3859738981240a9d8c503a13ede9601 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Tue, 16 Jan 2024 13:18:09 -0800
Subject: [PATCH 01/13] Add support for builtin_verbose_trap

The builtin causes the program to stop its execution abnormally and shows a
human-readable description of the reason for the termination when a debugger is
attached or in a symbolicated crash log.

The motivation for the builtin is explained in the following RFC:

https://discourse.llvm.org/t/rfc-adding-builtin-verbose-trap-string-literal/75845
---
 clang/docs/LanguageExtensions.rst | 49 ++-
 clang/include/clang/AST/Expr.h|  5 ++
 clang/include/clang/Basic/Builtins.td |  6 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +
 clang/lib/AST/ExprConstant.cpp| 18 +--
 clang/lib/CodeGen/CGBuiltin.cpp   | 12 +
 clang/lib/CodeGen/CGDebugInfo.cpp | 42 
 clang/lib/CodeGen/CGDebugInfo.h   | 20 
 clang/lib/Sema/SemaChecking.cpp   | 22 +
 .../CodeGenCXX/debug-info-verbose-trap.cpp| 49 +++
 clang/test/SemaCXX/verbose-trap.cpp   | 28 +++
 11 files changed, 249 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/debug-info-verbose-trap.cpp
 create mode 100644 clang/test/SemaCXX/verbose-trap.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 84fc4dee02fa80..1dd8d3bcec920d 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -3467,6 +3467,54 @@ Query for this feature with 
``__has_builtin(__builtin_trap)``.
 
 ``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and 
then to ``brk #payload``.
 
+``__builtin_verbose_trap``
+--
+
+``__builtin_verbose_trap`` causes the program to stop its execution abnormally
+and shows a human-readable description of the reason for the termination when a
+debugger is attached or in a symbolicated crash log.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_verbose_trap(const char *reason)
+
+**Description**
+
+``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` 
`_ builtin.
+Additionally, clang emits debug metadata that represents an artificial inline
+frame whose name encodes the string passed to the builtin, prefixed by a 
"magic"
+prefix.
+
+For example, consider the following code:
+
+.. code-block:: c++
+
+void foo(int* p) {
+  if (p == nullptr)
+__builtin_verbose_trap("Argument_must_not_be_null");
+}
+
+The debug metadata would look as if it were produced for the following code:
+
+.. code-block:: c++
+
+__attribute__((always_inline))
+inline void "__llvm_verbose_trap: Argument_must_not_be_null"() {
+  __builtin_trap();
+}
+
+void foo(int* p) {
+  if (p == nullptr)
+"__llvm_verbose_trap: Argument_must_not_be_null"();
+}
+
+However, the LLVM IR would not actually contain a call to the artificial
+function — it only exists in the debug metadata.
+
+Query for this feature with ``__has_builtin(__builtin_verbose_trap)``.
+
 ``__builtin_allow_runtime_check``
 -
 
@@ -3514,7 +3562,6 @@ guarded check. It's unused now. It will enable 
kind-specific lowering in future.
 E.g. a higher hotness cutoff can be used for more expensive kind of check.
 
 Query for this feature with ``__has_builtin(__builtin_allow_runtime_check)``.
-
 ``__builtin_nondeterministic_value``
 
 
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 2bfefeabc348be..9606a5fddd47e3 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -787,6 +787,11 @@ class Expr : public ValueStmt {
  const Expr *PtrExpression, ASTContext &Ctx,
  EvalResult &Status) const;
 
+  /// If the current Expr can be evaluated to a pointer to a null-terminated
+  /// constant string, return the constant string (without the terminating 
null)
+  /// in Result. Return true if it succeeds.
+  bool tryEvaluateString(std::string &Result, ASTContext &Ctx) const;
+
   /// Enumeration used to describe the kind of Null pointer constant
   /// returned from \c isNullPointerConstant().
   enum NullPointerConstantKind {
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index de721a87b3341d..5b3b9d04e576ab 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1152,6 +1152,12 @@ def Trap : Builtin {
   let Prototype = "void()";
 }
 
+def VerboseTrap : Builtin {
+  let Spellings = ["__builtin_verbose_trap"];
+  let Attributes = [NoThrow, NoReturn];
+  let Prot

[clang] [clang] MangledSymbol: remove pointless copy of vector (PR #90012)

2024-04-24 Thread Andrew Sukach via cfe-commits

soukatch wrote:

@dcb314 @shafik @EugeneZelenko Please let me know if this change looks good. 
Thanks!

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


[clang] [clang][modules] Allow including module maps to be non-affecting (PR #89992)

2024-04-24 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 updated 
https://github.com/llvm/llvm-project/pull/89992

>From 6e77e37977bbecc8053d12b4db3f790042b8f34d Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Wed, 24 Apr 2024 11:12:28 -0700
Subject: [PATCH] [clang][modules] Allow including module maps to be
 non-affecting

---
 .../include/clang/Serialization/ASTBitCodes.h |  4 +-
 clang/include/clang/Serialization/ASTWriter.h |  9 ++
 .../include/clang/Serialization/ModuleFile.h  |  1 +
 clang/lib/Serialization/ASTReader.cpp |  5 +-
 clang/lib/Serialization/ASTWriter.cpp | 93 ---
 .../DependencyScanning/ModuleDepCollector.cpp |  2 +-
 .../ClangScanDeps/modules-extern-unrelated.m  | 20 ++--
 7 files changed, 86 insertions(+), 48 deletions(-)

diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index dcfa4ac0c19677..9e90db513fde44 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -41,7 +41,7 @@ namespace serialization {
 /// Version 4 of AST files also requires that the version control branch and
 /// revision match exactly, since there is no backward compatibility of
 /// AST files at this time.
-const unsigned VERSION_MAJOR = 30;
+const unsigned VERSION_MAJOR = 31;
 
 /// AST file minor version number supported by this version of
 /// Clang.
@@ -51,7 +51,7 @@ const unsigned VERSION_MAJOR = 30;
 /// for the previous version could still support reading the new
 /// version by ignoring new kinds of subblocks), this number
 /// should be increased.
-const unsigned VERSION_MINOR = 1;
+const unsigned VERSION_MINOR = 0;
 
 /// An ID number that refers to an identifier in an AST file.
 ///
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 13b4ad4ad2953d..76730803e99b92 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -76,6 +76,10 @@ class StoredDeclsList;
 class SwitchCase;
 class Token;
 
+namespace SrcMgr {
+class FileInfo;
+} // namespace SrcMgr
+
 /// Writes an AST file containing the contents of a translation unit.
 ///
 /// The ASTWriter class produces a bitstream containing the serialized
@@ -491,6 +495,11 @@ class ASTWriter : public ASTDeserializationListener,
   /// during \c SourceManager serialization.
   void computeNonAffectingInputFiles();
 
+  /// Some affecting files can be included from files that are not affecting.
+  /// This function erases source locations pointing into such files.
+  SourceLocation getAffectingIncludeLoc(const SourceManager &SourceMgr,
+const SrcMgr::FileInfo &File);
+
   /// Returns an adjusted \c FileID, accounting for any non-affecting input
   /// files.
   FileID getAdjustedFileID(FileID FID) const;
diff --git a/clang/include/clang/Serialization/ModuleFile.h 
b/clang/include/clang/Serialization/ModuleFile.h
index 492c35dceb08d4..84fb2e8b1e4842 100644
--- a/clang/include/clang/Serialization/ModuleFile.h
+++ b/clang/include/clang/Serialization/ModuleFile.h
@@ -69,6 +69,7 @@ struct InputFileInfo {
   bool Overridden;
   bool Transient;
   bool TopLevel;
+  bool TopLevelAmongAffecting;
   bool ModuleMap;
 };
 
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 43b69045bb0543..2a726ee7fb4491 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -2444,9 +2444,10 @@ InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, 
unsigned ID) {
   R.Overridden = static_cast(Record[3]);
   R.Transient = static_cast(Record[4]);
   R.TopLevel = static_cast(Record[5]);
-  R.ModuleMap = static_cast(Record[6]);
+  R.TopLevelAmongAffecting = static_cast(Record[6]);
+  R.ModuleMap = static_cast(Record[7]);
   std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
-uint16_t AsRequestedLength = Record[7];
+uint16_t AsRequestedLength = Record[8];
 
 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
 std::string Name = Blob.substr(AsRequestedLength).str();
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 30195868ca9965..a6f586f0106773 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -173,54 +173,50 @@ GetAffectingModuleMaps(const Preprocessor &PP, Module 
*RootModule) {
 
   const HeaderSearch &HS = PP.getHeaderSearchInfo();
   const ModuleMap &MM = HS.getModuleMap();
-  const SourceManager &SourceMgr = PP.getSourceManager();
 
   std::set ModuleMaps;
-  auto CollectIncludingModuleMaps = [&](FileID FID, FileEntryRef F) {
-if (!ModuleMaps.insert(F).second)
+  std::set ProcessedModules;
+  auto CollectModuleMapsForHierarchy = [&](const Module *M) {
+M = M->getTopLevelModule();
+
+if (!ProcessedModules.insert(M).second)
   return;
-SourceLocation Loc = Sou

[clang] [clang] MangledSymbol: remove pointless copy of vector (PR #90012)

2024-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andrew Sukach (soukatch)


Changes

This pr addresses #87255 adds a std::move call to the names in 
MangledSymbol's constructor.

---
Full diff: https://github.com/llvm/llvm-project/pull/90012.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 &ParentName, 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/90012
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] MangledSymbol: remove pointless copy of vector (PR #90012)

2024-04-24 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/90012
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] MangledSymbol: remove pointless copy of vector (PR #90012)

2024-04-24 Thread Andrew Sukach via cfe-commits

https://github.com/soukatch created 
https://github.com/llvm/llvm-project/pull/90012

This pr addresses #87255 adds a std::move call to the names in MangledSymbol's 
constructor.

>From b8e20a5a3e37ab9a657ac640b848f638387215fa Mon Sep 17 00:00:00 2001
From: Andrew Sukach 
Date: Wed, 24 Apr 2024 22:50:50 -0400
Subject: [PATCH] [clang] MangledSymbol: remove pointless copy of vector

---
 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 &ParentName, 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] [Clang][Sema] Revisit the fix for the lambda within a type alias template decl (PR #89934)

2024-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

In the last patch #82310, we used template depths to tell if such alias 
decls contain lambdas, which is wrong because the lambda can also appear as a 
part of the default argument, and that would make 
`getTemplateInstantiationArgs` provide extra template arguments in undesired 
contexts. This leads to issue #89853.

Moreover, our approach for https://github.com/llvm/llvm-project/issues/82104 
was sadly wrong. We tried to teach `DeduceReturnType` to consider alias 
template arguments; however, giving these arguments in the context where they 
should have been substituted in a `TransformCallExpr` call is never correct.

This patch addresses such problems by using a `RecursiveASTVisitor` to check if 
the lambda is contained by an alias `Decl`, as well as twiddling the lambda 
dependencies - we should also build a dependent lambda expression if the 
surrounding alias template arguments were dependent.

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

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+38-35) 
- (modified) clang/test/SemaTemplate/alias-template-with-lambdas.cpp (+48-3) 


``diff
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 98d5c7cb3a8a80..8b4d841fab46cf 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprConcepts.h"
 #include "clang/AST/PrettyDeclStackTrace.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeVisitor.h"
@@ -87,12 +88,19 @@ struct Response {
 // than lambda classes.
 const FunctionDecl *
 getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
+  if (!isLambdaCallOperator(LambdaCallOperator))
+return LambdaCallOperator;
   while (true) {
 if (auto *FTD = dyn_cast_if_present(
 LambdaCallOperator->getDescribedTemplate());
 FTD && FTD->getInstantiatedFromMemberTemplate()) {
   LambdaCallOperator =
   FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
+} else if (LambdaCallOperator->getPrimaryTemplate()) {
+  // Cases where the lambda operator is instantiated in
+  // TemplateDeclInstantiator::VisitCXXMethodDecl.
+  LambdaCallOperator =
+  LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
 } else if (auto *Prev = cast(LambdaCallOperator)
 ->getInstantiatedFromMemberFunction())
   LambdaCallOperator = Prev;
@@ -138,22 +146,28 @@ getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
 // Check if we are currently inside of a lambda expression that is
 // surrounded by a using alias declaration. e.g.
 //   template  using type = decltype([](auto) { ^ }());
-// By checking if:
-//  1. The lambda expression and the using alias declaration share the
-//  same declaration context.
-//  2. They have the same template depth.
 // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
 // a DeclContext, nor does it have an associated specialization Decl from which
 // we could collect these template arguments.
 bool isLambdaEnclosedByTypeAliasDecl(
-const FunctionDecl *PrimaryLambdaCallOperator,
+const FunctionDecl *LambdaCallOperator,
 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
-  return cast(PrimaryLambdaCallOperator->getDeclContext())
- ->getTemplateDepth() ==
- PrimaryTypeAliasDecl->getTemplateDepth() &&
- getLambdaAwareParentOfDeclContext(
- const_cast(PrimaryLambdaCallOperator)) ==
- PrimaryTypeAliasDecl->getDeclContext();
+  struct Visitor : RecursiveASTVisitor {
+Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
+bool VisitLambdaExpr(const LambdaExpr *LE) {
+  // Return true to bail out of the traversal, implying the Decl contains
+  // the lambda.
+  return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
+ CallOperator;
+}
+const FunctionDecl *CallOperator;
+  };
+
+  QualType Underlying =
+  PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
+
+  return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
+  .TraverseType(Underlying);
 }
 
 // Add template arguments from a variable template instantiation.
@@ -283,23 +297,8 @@ Response HandleFunction(Sema &SemaRef, const FunctionDecl 
*Function,
 
 // If this function is a generic lambda specialization, we are done.
 if (!ForConstraintInstantiation &&
-isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) {
-  // TypeAliasTemplateDecls should be taken into account, e.g.
-  // when

[clang] [Clang][Sema] Revisit the fix for the lambda within a type alias template decl (PR #89934)

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

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


[clang] [Clang][Sema] Revisit the fix for the lambda within a type alias template decl (PR #89934)

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


@@ -91,15 +91,60 @@ void bar() {
 
 namespace GH82104 {
 
-template  int Zero = 0;
+template  int Value = sizeof...(D);
 
-template 
-using T14 = decltype([]() { return Zero; }());
+template 
+using T14 = decltype([](auto Param) {
+  return Value + V + (int)sizeof(Param);
+}("hello"));
 
 template  using T15 = T14;
 
 static_assert(__is_same(T15, int));
 
+// FIXME: This still crashes because we can't extract template arguments T and 
U
+// outside of the instantiation context of T16.
+#if 0
+template 
+using T16 = decltype([](auto Param) requires (sizeof(Param) != 1 && 
sizeof...(U) > 0) {
+  return Value + sizeof(Param);
+});
+static_assert(T16()(42) == 2 + sizeof(42));
+#endif

zyn0217 wrote:

I have to admit we still have lots of edge cases that our current approach 
(i.e. by extracting template arguments from the type alias instantiation 
context) doesn't cover. However, I think we can still land this patch (because 
it addresses the regressions and covers a number of cases) and probably come up 
with another solution later.

Perhaps, I *think* one promising approach is to change the 
`TypeAliasTemplateDecl` to a kind of `DeclContext` and thereby we can invent 
something e.g. `TypeAliasTemplateSpecializationDecl` so that they can be 
handled like what we do for member function templates.

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


[clang] [Clang][Sema] Revisit the fix for the lambda within a type alias template decl (PR #89934)

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

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

>From 92f8cfb255a549769c39327239c69edd6b2e947e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 24 Apr 2024 20:54:58 +0800
Subject: [PATCH 1/3] [Clang][Sema] Revisit the lambda within a type alias
 template decl

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 72 ++-
 .../alias-template-with-lambdas.cpp   | 27 ++-
 2 files changed, 64 insertions(+), 35 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 98d5c7cb3a8a80..572d8e4c820ee9 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprConcepts.h"
 #include "clang/AST/PrettyDeclStackTrace.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeVisitor.h"
@@ -87,12 +88,19 @@ struct Response {
 // than lambda classes.
 const FunctionDecl *
 getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
+  if (!isLambdaCallOperator(LambdaCallOperator))
+return LambdaCallOperator;
   while (true) {
 if (auto *FTD = dyn_cast_if_present(
 LambdaCallOperator->getDescribedTemplate());
 FTD && FTD->getInstantiatedFromMemberTemplate()) {
   LambdaCallOperator =
   FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
+} else if (LambdaCallOperator->getPrimaryTemplate()) {
+  // Cases where the lambda operator is instantiated in
+  // TemplateDeclInstantiator::VisitCXXMethodDecl.
+  LambdaCallOperator =
+  LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
 } else if (auto *Prev = cast(LambdaCallOperator)
 ->getInstantiatedFromMemberFunction())
   LambdaCallOperator = Prev;
@@ -138,22 +146,30 @@ getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
 // Check if we are currently inside of a lambda expression that is
 // surrounded by a using alias declaration. e.g.
 //   template  using type = decltype([](auto) { ^ }());
-// By checking if:
-//  1. The lambda expression and the using alias declaration share the
-//  same declaration context.
-//  2. They have the same template depth.
 // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
 // a DeclContext, nor does it have an associated specialization Decl from which
 // we could collect these template arguments.
 bool isLambdaEnclosedByTypeAliasDecl(
-const FunctionDecl *PrimaryLambdaCallOperator,
+const FunctionDecl *LambdaCallOperator,
 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
-  return cast(PrimaryLambdaCallOperator->getDeclContext())
- ->getTemplateDepth() ==
- PrimaryTypeAliasDecl->getTemplateDepth() &&
- getLambdaAwareParentOfDeclContext(
- const_cast(PrimaryLambdaCallOperator)) ==
- PrimaryTypeAliasDecl->getDeclContext();
+  struct Visitor : RecursiveASTVisitor {
+Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
+bool VisitLambdaExpr(const LambdaExpr *LE) {
+  // Return true to bail out of the traversal, implying the Decl contains
+  // the lambda.
+  return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
+ CallOperator;
+}
+const FunctionDecl *CallOperator;
+  };
+
+  QualType Underlying =
+  PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
+
+  if (auto *DT = dyn_cast(Underlying.getTypePtr()))
+return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
+.TraverseStmt(DT->getUnderlyingExpr());
+  return false;
 }
 
 // Add template arguments from a variable template instantiation.
@@ -283,23 +299,8 @@ Response HandleFunction(Sema &SemaRef, const FunctionDecl 
*Function,
 
 // If this function is a generic lambda specialization, we are done.
 if (!ForConstraintInstantiation &&
-isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) {
-  // TypeAliasTemplateDecls should be taken into account, e.g.
-  // when we're deducing the return type of a lambda.
-  //
-  // template  int Value = 0;
-  // template 
-  // using T = decltype([]() { return Value; }());
-  //
-  if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
-if (isLambdaEnclosedByTypeAliasDecl(
-
/*PrimaryLambdaCallOperator=*/getPrimaryTemplateOfGenericLambda(
-Function),
-/*PrimaryTypeAliasDecl=*/TypeAlias.PrimaryTypeAliasDecl))
-  return Response::UseNextDecl(Function);
-  }
+isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
   return Response::Done();
-}
 
   } else if (Function->getDescribedFunctionTemplate()) {
 as

[clang] [llvm] [CIR][NFC] Add scaffolding for the CIR dialect and CIROps.td (PR #86080)

2024-04-24 Thread Nathan Lanza via cfe-commits

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


[clang] [llvm] [CIR][NFC] Add scaffolding for the CIR dialect and CIROps.td (PR #86080)

2024-04-24 Thread Nathan Lanza via cfe-commits

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


[clang] 10661ba - [CIR][NFC] Add scaffolding for the CIR dialect and CIROps.td

2024-04-24 Thread via cfe-commits

Author: Nathan Lanza
Date: 2024-04-24T22:26:40-04:00
New Revision: 10661ba2403f73cd2c4b76ebd177fdcf9261cbf2

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

LOG: [CIR][NFC] Add scaffolding for the CIR dialect and CIROps.td

This adds no real content, it just incrementally adds some scaffolding
necessary to enable a future patch to just add our first few ops.

Test Plan:
```
$ cmake -Sllvm -Bbuild -DCLANG_ENABLE_CIR=1 \
  -DLLVM_ENABLE_PROJECTS='clang;mlir' \
  -DCMAKE_BUILD_TYPE=Release -GNinja
$ ninja -C build check-clang
$ ninja -C build MLIRCIROpsIncGen
$ ninja -C build MLIRCIR
```

Reviewers: AaronBallman, erichkeane, bcardosolopes

Reviewed By: erichkeane, AaronBallman, bcardosolopes

Pull Request: https://github.com/llvm/llvm-project/pull/86080

Added: 
clang/include/clang/CIR/Dialect/CMakeLists.txt
clang/include/clang/CIR/Dialect/IR/CIRDialect.h
clang/include/clang/CIR/Dialect/IR/CIRDialect.td
clang/include/clang/CIR/Dialect/IR/CIROps.td
clang/include/clang/CIR/Dialect/IR/CMakeLists.txt
clang/lib/CIR/Dialect/CMakeLists.txt
clang/lib/CIR/Dialect/IR/CIRDialect.cpp
clang/lib/CIR/Dialect/IR/CMakeLists.txt

Modified: 
clang/CMakeLists.txt
clang/include/clang/CIR/CMakeLists.txt
clang/lib/CIR/CMakeLists.txt

Removed: 




diff  --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index f092766fa19f07..cf97e3c6e851ae 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -166,6 +166,10 @@ if(CLANG_ENABLE_LIBXML2)
 endif()
 
 if(CLANG_ENABLE_CIR)
+  if (CLANG_BUILT_STANDALONE)
+message(FATAL_ERROR
+  "ClangIR is not yet supported in the standalone build.")
+  endif()
   if (NOT "${LLVM_ENABLE_PROJECTS}" MATCHES "MLIR|mlir")
 message(FATAL_ERROR
   "Cannot build ClangIR without MLIR in LLVM_ENABLE_PROJECTS")

diff  --git a/clang/include/clang/CIR/CMakeLists.txt 
b/clang/include/clang/CIR/CMakeLists.txt
index e69de29bb2d1d6..f8d6f407a03d02 100644
--- a/clang/include/clang/CIR/CMakeLists.txt
+++ b/clang/include/clang/CIR/CMakeLists.txt
@@ -0,0 +1,6 @@
+set(MLIR_INCLUDE_DIR ${LLVM_MAIN_SRC_DIR}/../mlir/include ) # --includedir
+set(MLIR_TABLEGEN_OUTPUT_DIR ${CMAKE_BINARY_DIR}/tools/mlir/include)
+include_directories(${MLIR_INCLUDE_DIR})
+include_directories(${MLIR_TABLEGEN_OUTPUT_DIR})
+
+add_subdirectory(Dialect)

diff  --git a/clang/include/clang/CIR/Dialect/CMakeLists.txt 
b/clang/include/clang/CIR/Dialect/CMakeLists.txt
new file mode 100644
index 00..f33061b2d87cff
--- /dev/null
+++ b/clang/include/clang/CIR/Dialect/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(IR)

diff  --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
new file mode 100644
index 00..d53e5d1663d62a
--- /dev/null
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
@@ -0,0 +1,16 @@
+//===- CIRDialect.h - CIR dialect ---*- 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
+//
+//===--===//
+//
+// This file declares the CIR dialect.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_CIR_DIALECT_IR_CIRDIALECT_H
+#define LLVM_CLANG_CIR_DIALECT_IR_CIRDIALECT_H
+
+#endif // LLVM_CLANG_CIR_DIALECT_IR_CIRDIALECT_H

diff  --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.td 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
new file mode 100644
index 00..69d6e9774942b9
--- /dev/null
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
@@ -0,0 +1,44 @@
+//===- CIRDialect.td - CIR dialect -*- tablegen 
-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file declares the CIR dialect.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_CIR_DIALECT_IR_CIRDIALECT
+#define LLVM_CLANG_CIR_DIALECT_IR_CIRDIALECT
+
+include "mlir/IR/OpBase.td"
+
+def CIR_Dialect : Dialect {
+  let name = "cir";
+
+  // A short one-line summary of our dialect.
+  let summary = "A high-level dialect for analyzing and optimizing Clang "
+"supported languages";
+
+  let cppNamespace = "::mlir::cir";
+
+  let useDefaultAttributePrinterParser = 0;
+  let useDefaultTypePrinterParser = 0;
+
+  let extraClassDeclaration = 

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

2024-04-24 Thread Hubert Tong via cfe-commits


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

hubert-reinterpretcast wrote:

> Do we want to do the same for C++23? If not what's exactly an "unspecified" 
> value?

It means that `INT_MAX` and `INT_MIN` is fine (based on the wording). The 
committee discussion had already decided that the constexpr evaluation need not 
match the target's runtime in terms of implementation-defined behavior with 
respect to:
- what cases are errors, and
- how non-error cases of NaNs and infinities, etc. are handled.

Instead, C's Annex F was to specify the behaviour; however, that C's Annex F 
did not fully specify the result (as in the case in question) was not discussed.


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


[clang] [Clang][Sema] Revisit the fix for the lambda within a type alias template decl (PR #89934)

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

zyn0217 wrote:

> FYI in my issue, even if the lambda didn't appear as part of the default 
> argument, I was [still able to trigger the 
> bug](https://godbolt.org/z/4KrEMTTdd). Noting in case this fix only resolves 
> the case of lambdas in default template arguments, and not passed in 
> explicitly.
> 
> e.g.
> 
> ```c++
> static constexpr auto not_default_now = [] {
> (void) static_cast(c);
> };
> 
> template
> using broken = decltype(Pred.template operator()<'\0'>());
> 
> broken* boom;
> ```

Yeah, this patch *fixes* that as well. To clarify, the issue was caused by 
having extra template arguments in the context where we don't actually expect 
them. For example, the problem arose from the argument for `Pred` when it was 
substituted before we exercise `DeduceReturnType` for the lambda 
`not_default_now`. This patch now avoids that fault and only offers complete 
arguments relative to the primary template while checking constraints - this 
matches what our constraint checking expects.

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


[clang] [llvm] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)

2024-04-24 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/89796

>From 662f160418c704f45e57e751168903d774b74303 Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Tue, 23 Apr 2024 17:41:25 +0100
Subject: [PATCH 1/4] Add initial support for AMDGCN flavoured SPIRV.

---
 clang/lib/Basic/Targets.cpp   |   6 +-
 clang/lib/Basic/Targets/SPIR.cpp  | 288 +
 clang/lib/Basic/Targets/SPIR.h|  51 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |   7 +
 clang/test/CodeGen/target-data.c  |   4 +
 .../test/CodeGenCUDA/builtins-spirv-amdgcn.cu | 294 ++
 ...tins-unsafe-atomics-spirv-amdgcn-gfx90a.cu |  31 ++
 clang/test/CodeGenCUDA/long-double.cu |   4 +
 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu   | 129 
 .../test/CodeGenCXX/spirv-amdgcn-float16.cpp  |  38 +++
 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp |  27 ++
 .../spirv-amdgcn-dpp-const-fold.hip   |  46 +++
 clang/test/CodeGenHIP/spirv-amdgcn-half.hip   |  15 +
 .../predefined-macros-no-warnings.c   |   1 +
 clang/test/Preprocessor/predefined-macros.c   |  10 +
 ...in-spirv-amdgcn-atomic-inc-dec-failure.cpp |  25 ++
 .../Sema/inline-asm-validate-spirv-amdgcn.cl  | 111 +++
 clang/test/SemaCUDA/allow-int128.cu   |   3 +
 clang/test/SemaCUDA/amdgpu-f128.cu|   1 +
 clang/test/SemaCUDA/float16.cu|   1 +
 clang/test/SemaCUDA/fp16-arg-return.cu|   1 +
 .../test/SemaCUDA/spirv-amdgcn-atomic-ops.cu  |  86 +
 22 files changed, 1178 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenCUDA/builtins-spirv-amdgcn.cu
 create mode 100644 
clang/test/CodeGenCUDA/builtins-unsafe-atomics-spirv-amdgcn-gfx90a.cu
 create mode 100644 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu
 create mode 100644 clang/test/CodeGenCXX/spirv-amdgcn-float16.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-dpp-const-fold.hip
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-half.hip
 create mode 100644 
clang/test/Sema/builtin-spirv-amdgcn-atomic-inc-dec-failure.cpp
 create mode 100644 clang/test/Sema/inline-asm-validate-spirv-amdgcn.cl
 create mode 100644 clang/test/SemaCUDA/spirv-amdgcn-atomic-ops.cu

diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index e3283510c6aac7..04a13e3385d1f6 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -673,8 +673,12 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple &Triple,
   }
   case llvm::Triple::spirv64: {
 if (os != llvm::Triple::UnknownOS ||
-Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
+Triple.getEnvironment() != llvm::Triple::UnknownEnvironment) {
+  if (os == llvm::Triple::OSType::AMDHSA)
+return std::make_unique(Triple, Opts);
+
   return nullptr;
+}
 return std::make_unique(Triple, Opts);
   }
   case llvm::Triple::wasm32:
diff --git a/clang/lib/Basic/Targets/SPIR.cpp b/clang/lib/Basic/Targets/SPIR.cpp
index dc920177d3a910..d7d232ac9484f8 100644
--- a/clang/lib/Basic/Targets/SPIR.cpp
+++ b/clang/lib/Basic/Targets/SPIR.cpp
@@ -12,6 +12,8 @@
 
 #include "SPIR.h"
 #include "Targets.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/TargetBuiltins.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -54,3 +56,289 @@ void SPIRV64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
   DefineStd(Builder, "SPIRV64", Opts);
 }
+
+static constexpr Builtin::Info BuiltinInfo[] = {
+#define BUILTIN(ID, TYPE, ATTRS)   
\
+  {#ID, TYPE, ATTRS, nullptr, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)   
\
+  {#ID, TYPE, ATTRS, FEATURE, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#include "clang/Basic/BuiltinsAMDGPU.def"
+};
+
+namespace {
+const char *AMDGPUGCCRegNames[] = {
+  "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
+  "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17",
+  "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26",
+  "v27", "v28", "v29", "v30", "v31", "v32", "v33", "v34", "v35",
+  "v36", "v37", "v38", "v39", "v40", "v41", "v42", "v43", "v44",
+  "v45", "v46", "v47", "v48", "v49", "v50", "v51", "v52", "v53",
+  "v54", "v55", "v56", "v57", "v58", "v59", "v60", "v61", "v62",
+  "v63", "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71",
+  "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79", "v80",
+  "v81", "v82", "v83", "v84", "v85", "v86", "v87", "v88", "v89",
+  "v90", "v91", "v92", "v93", "v94", "v95", "v96", "v97", "v98",
+  "v99", "v100", "v101", "v102", "v103", "v104", "v105", "v106", "v107",
+  "v108", "v109", "v110", "v111", "v112", "v113", "v114", "v115", "v116",
+  "v117", "v118", "v119", "v120", "v121", "v122", "v123", "v124", "v

[clang] [llvm] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)

2024-04-24 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/89796

>From 662f160418c704f45e57e751168903d774b74303 Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Tue, 23 Apr 2024 17:41:25 +0100
Subject: [PATCH 1/3] Add initial support for AMDGCN flavoured SPIRV.

---
 clang/lib/Basic/Targets.cpp   |   6 +-
 clang/lib/Basic/Targets/SPIR.cpp  | 288 +
 clang/lib/Basic/Targets/SPIR.h|  51 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |   7 +
 clang/test/CodeGen/target-data.c  |   4 +
 .../test/CodeGenCUDA/builtins-spirv-amdgcn.cu | 294 ++
 ...tins-unsafe-atomics-spirv-amdgcn-gfx90a.cu |  31 ++
 clang/test/CodeGenCUDA/long-double.cu |   4 +
 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu   | 129 
 .../test/CodeGenCXX/spirv-amdgcn-float16.cpp  |  38 +++
 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp |  27 ++
 .../spirv-amdgcn-dpp-const-fold.hip   |  46 +++
 clang/test/CodeGenHIP/spirv-amdgcn-half.hip   |  15 +
 .../predefined-macros-no-warnings.c   |   1 +
 clang/test/Preprocessor/predefined-macros.c   |  10 +
 ...in-spirv-amdgcn-atomic-inc-dec-failure.cpp |  25 ++
 .../Sema/inline-asm-validate-spirv-amdgcn.cl  | 111 +++
 clang/test/SemaCUDA/allow-int128.cu   |   3 +
 clang/test/SemaCUDA/amdgpu-f128.cu|   1 +
 clang/test/SemaCUDA/float16.cu|   1 +
 clang/test/SemaCUDA/fp16-arg-return.cu|   1 +
 .../test/SemaCUDA/spirv-amdgcn-atomic-ops.cu  |  86 +
 22 files changed, 1178 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenCUDA/builtins-spirv-amdgcn.cu
 create mode 100644 
clang/test/CodeGenCUDA/builtins-unsafe-atomics-spirv-amdgcn-gfx90a.cu
 create mode 100644 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu
 create mode 100644 clang/test/CodeGenCXX/spirv-amdgcn-float16.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-dpp-const-fold.hip
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-half.hip
 create mode 100644 
clang/test/Sema/builtin-spirv-amdgcn-atomic-inc-dec-failure.cpp
 create mode 100644 clang/test/Sema/inline-asm-validate-spirv-amdgcn.cl
 create mode 100644 clang/test/SemaCUDA/spirv-amdgcn-atomic-ops.cu

diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index e3283510c6aac7..04a13e3385d1f6 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -673,8 +673,12 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple &Triple,
   }
   case llvm::Triple::spirv64: {
 if (os != llvm::Triple::UnknownOS ||
-Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
+Triple.getEnvironment() != llvm::Triple::UnknownEnvironment) {
+  if (os == llvm::Triple::OSType::AMDHSA)
+return std::make_unique(Triple, Opts);
+
   return nullptr;
+}
 return std::make_unique(Triple, Opts);
   }
   case llvm::Triple::wasm32:
diff --git a/clang/lib/Basic/Targets/SPIR.cpp b/clang/lib/Basic/Targets/SPIR.cpp
index dc920177d3a910..d7d232ac9484f8 100644
--- a/clang/lib/Basic/Targets/SPIR.cpp
+++ b/clang/lib/Basic/Targets/SPIR.cpp
@@ -12,6 +12,8 @@
 
 #include "SPIR.h"
 #include "Targets.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/TargetBuiltins.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -54,3 +56,289 @@ void SPIRV64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
   DefineStd(Builder, "SPIRV64", Opts);
 }
+
+static constexpr Builtin::Info BuiltinInfo[] = {
+#define BUILTIN(ID, TYPE, ATTRS)   
\
+  {#ID, TYPE, ATTRS, nullptr, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)   
\
+  {#ID, TYPE, ATTRS, FEATURE, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#include "clang/Basic/BuiltinsAMDGPU.def"
+};
+
+namespace {
+const char *AMDGPUGCCRegNames[] = {
+  "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
+  "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17",
+  "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26",
+  "v27", "v28", "v29", "v30", "v31", "v32", "v33", "v34", "v35",
+  "v36", "v37", "v38", "v39", "v40", "v41", "v42", "v43", "v44",
+  "v45", "v46", "v47", "v48", "v49", "v50", "v51", "v52", "v53",
+  "v54", "v55", "v56", "v57", "v58", "v59", "v60", "v61", "v62",
+  "v63", "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71",
+  "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79", "v80",
+  "v81", "v82", "v83", "v84", "v85", "v86", "v87", "v88", "v89",
+  "v90", "v91", "v92", "v93", "v94", "v95", "v96", "v97", "v98",
+  "v99", "v100", "v101", "v102", "v103", "v104", "v105", "v106", "v107",
+  "v108", "v109", "v110", "v111", "v112", "v113", "v114", "v115", "v116",
+  "v117", "v118", "v119", "v120", "v121", "v122", "v123", "v124", "v

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

2024-04-24 Thread Justin Bogner via cfe-commits


@@ -25,6 +25,7 @@ enum class ResourceClass : uint8_t {
   SRV = 0,
   UAV,
   CBuffer,
+  TBuffer,

bogner wrote:

I hadn't noticed this. Xiang's right, this isn't correct. See 
`CGHLSLRuntime::finishCodeGen` - a tbuffer is annotated with a resource class 
of `SRV` as you would expect.

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


[clang] [buildbot] VE builders: disable ctx_profile (PR #89969)

2024-04-24 Thread Mircea Trofin via cfe-commits

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


[clang] d6cc8d4 - [buildbot] VE builders: disable ctx_profile (#89969)

2024-04-24 Thread via cfe-commits

Author: Mircea Trofin
Date: 2024-04-24T18:37:20-07:00
New Revision: d6cc8d45b3da91b8d48c59fa86b6f1dba9c3e87b

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

LOG: [buildbot] VE builders: disable ctx_profile (#89969)

Added: 


Modified: 
clang/cmake/caches/VectorEngine.cmake

Removed: 




diff  --git a/clang/cmake/caches/VectorEngine.cmake 
b/clang/cmake/caches/VectorEngine.cmake
index e3976f3206db53..2f968a21cc407e 100644
--- a/clang/cmake/caches/VectorEngine.cmake
+++ b/clang/cmake/caches/VectorEngine.cmake
@@ -40,6 +40,7 @@ set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_CRT 
OFF CACHE BOOL "")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_SANITIZERS OFF CACHE 
BOOL "")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_XRAY OFF CACHE BOOL "")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_LIBFUZZER OFF CACHE 
BOOL "")
+set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_CTX_PROFILE OFF CACHE 
BOOL "")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_PROFILE OFF CACHE BOOL 
"")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_MEMPROF OFF CACHE BOOL 
"")
 set(RUNTIMES_x86_64-unknown-linux-gnu_COMPILER_RT_BUILD_ORC OFF CACHE BOOL "")
@@ -52,6 +53,7 @@ 
set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_SANITIZERS OFF CACHE BOOL ""
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_XRAY OFF CACHE BOOL "")
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_LIBFUZZER OFF CACHE BOOL 
"")
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_PROFILE ON CACHE BOOL "")
+set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_CTX_PROFILE OFF CACHE BOOL 
"")
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_MEMPROF OFF CACHE BOOL "")
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_ORC OFF CACHE BOOL "")
 set(RUNTIMES_ve-unknown-linux-gnu_COMPILER_RT_BUILD_GWP_ASAN OFF CACHE BOOL "")



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


[clang] [buildbot] VE builders: disable ctx_profile (PR #89969)

2024-04-24 Thread Kazushi Marukawa via cfe-commits

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

This solves a problem in a buildbot for VE. Thank you.

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


[clang] [buildbot] VE builders: disable ctx_profile (PR #89969)

2024-04-24 Thread Kazushi Marukawa via cfe-commits

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

This solves a problem in a buildbot for VE.  Thank you.

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-24 Thread Justin Stitt via cfe-commits

JustinStitt wrote:

> > > If you declare a variable as both wrapping and non-wrapping, is it 
> > > wrapping?
> > 
> > 
> > I am not sure how to do this. I am sure that with the magic of C anything 
> > is possible but I can't conceive a way to have a variable both have the 
> > attribute and not have the attribute (to be clear, there doesn't exist a 
> > `__attribute__((no-wraps))` currently)
> 
> Say you declare a global variable like the following:
> 
> ```
> typedef int wrapint __attribute((wraps));
> extern wrapint x;
> int x = 0;
> ```
> 
> Is "x" wrapping?

No. But I am confused, isn't this just shadowing a global variable with a 
lesser-scoped one. Are they the same? What behavior do we want here?

> 
> > > If you mark a `short` wrapping, is the type after promotion wrapping?
> > 
> > 
> > This concerns the `-fsanitize=implicit-signed-integer-truncation` sanitizer 
> > which the wraps attribute disables. So the type boundaries pre- and 
> > post-promotion are not enforced by this sanitizer for wrapping types.
> 
> There are cases that don't involve truncation:
> 
> ```
> typedef short wrapshort __attribute((wraps));
> wrapshort x = 0x7FFF;
> int y = x*x*x*x;
> ```

Arithmetic cannot be performed on less-than-ints so the implicit promotions are 
put in place which lose the attribute. I just worked on an update to carry the 
wraps attribute through implicit integer promotion. 

However, after making the patch and testing it I am not sure what we want. Do 
we want to cancel implicit promotions for less-than-ints that possess the wraps 
attribute (doesn't sound spec compliant)? Or, should wrapping things still 
undergo promotion but now wrap at different bounds than what their original 
type specified?

If I make a wrapping char [-128, 127] and do some arithmetic on it it will be 
promoted to int (and still have the wraps attribute, with my patch) then 
proceed.

In the example below, `x*x*x*x*x` is `33,038,369,407` which is greater than 
INT_MAX `2,147,483,647` and will thus overflow (a few times). However, this 
overflow is happening at the integer boundaries not at the char boundaries.

```c
wrapchar x = 127;
int y = x*x*x*x*x; // result: -1321368961
```

The options are:
1) don't carry the wraps attribute through implicit promotions
2) carry the wraps attribute but use promoted-to-type's boundaries for wrapping
3) carry attribute and use the pre-promotion type's boundaries

More on this, I don't see how changing implementation from attribute-based to 
type-based resolves any of these design decisions. Neither approach is 
necessarily easier to implement or to understand for developers, if the right 
decisions are made in terms of behavior then the attribute approach can be just 
as useful and predictable.

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


[clang] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)

2024-04-24 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/89796

>From 662f160418c704f45e57e751168903d774b74303 Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Tue, 23 Apr 2024 17:41:25 +0100
Subject: [PATCH 1/2] Add initial support for AMDGCN flavoured SPIRV.

---
 clang/lib/Basic/Targets.cpp   |   6 +-
 clang/lib/Basic/Targets/SPIR.cpp  | 288 +
 clang/lib/Basic/Targets/SPIR.h|  51 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |   7 +
 clang/test/CodeGen/target-data.c  |   4 +
 .../test/CodeGenCUDA/builtins-spirv-amdgcn.cu | 294 ++
 ...tins-unsafe-atomics-spirv-amdgcn-gfx90a.cu |  31 ++
 clang/test/CodeGenCUDA/long-double.cu |   4 +
 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu   | 129 
 .../test/CodeGenCXX/spirv-amdgcn-float16.cpp  |  38 +++
 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp |  27 ++
 .../spirv-amdgcn-dpp-const-fold.hip   |  46 +++
 clang/test/CodeGenHIP/spirv-amdgcn-half.hip   |  15 +
 .../predefined-macros-no-warnings.c   |   1 +
 clang/test/Preprocessor/predefined-macros.c   |  10 +
 ...in-spirv-amdgcn-atomic-inc-dec-failure.cpp |  25 ++
 .../Sema/inline-asm-validate-spirv-amdgcn.cl  | 111 +++
 clang/test/SemaCUDA/allow-int128.cu   |   3 +
 clang/test/SemaCUDA/amdgpu-f128.cu|   1 +
 clang/test/SemaCUDA/float16.cu|   1 +
 clang/test/SemaCUDA/fp16-arg-return.cu|   1 +
 .../test/SemaCUDA/spirv-amdgcn-atomic-ops.cu  |  86 +
 22 files changed, 1178 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenCUDA/builtins-spirv-amdgcn.cu
 create mode 100644 
clang/test/CodeGenCUDA/builtins-unsafe-atomics-spirv-amdgcn-gfx90a.cu
 create mode 100644 clang/test/CodeGenCUDA/spirv-amdgcn-bf16.cu
 create mode 100644 clang/test/CodeGenCXX/spirv-amdgcn-float16.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-ballot.cpp
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-dpp-const-fold.hip
 create mode 100644 clang/test/CodeGenHIP/spirv-amdgcn-half.hip
 create mode 100644 
clang/test/Sema/builtin-spirv-amdgcn-atomic-inc-dec-failure.cpp
 create mode 100644 clang/test/Sema/inline-asm-validate-spirv-amdgcn.cl
 create mode 100644 clang/test/SemaCUDA/spirv-amdgcn-atomic-ops.cu

diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index e3283510c6aac7..04a13e3385d1f6 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -673,8 +673,12 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple &Triple,
   }
   case llvm::Triple::spirv64: {
 if (os != llvm::Triple::UnknownOS ||
-Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
+Triple.getEnvironment() != llvm::Triple::UnknownEnvironment) {
+  if (os == llvm::Triple::OSType::AMDHSA)
+return std::make_unique(Triple, Opts);
+
   return nullptr;
+}
 return std::make_unique(Triple, Opts);
   }
   case llvm::Triple::wasm32:
diff --git a/clang/lib/Basic/Targets/SPIR.cpp b/clang/lib/Basic/Targets/SPIR.cpp
index dc920177d3a910..d7d232ac9484f8 100644
--- a/clang/lib/Basic/Targets/SPIR.cpp
+++ b/clang/lib/Basic/Targets/SPIR.cpp
@@ -12,6 +12,8 @@
 
 #include "SPIR.h"
 #include "Targets.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/TargetBuiltins.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -54,3 +56,289 @@ void SPIRV64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
   DefineStd(Builder, "SPIRV64", Opts);
 }
+
+static constexpr Builtin::Info BuiltinInfo[] = {
+#define BUILTIN(ID, TYPE, ATTRS)   
\
+  {#ID, TYPE, ATTRS, nullptr, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)   
\
+  {#ID, TYPE, ATTRS, FEATURE, HeaderDesc::NO_HEADER, ALL_LANGUAGES},
+#include "clang/Basic/BuiltinsAMDGPU.def"
+};
+
+namespace {
+const char *AMDGPUGCCRegNames[] = {
+  "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
+  "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17",
+  "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26",
+  "v27", "v28", "v29", "v30", "v31", "v32", "v33", "v34", "v35",
+  "v36", "v37", "v38", "v39", "v40", "v41", "v42", "v43", "v44",
+  "v45", "v46", "v47", "v48", "v49", "v50", "v51", "v52", "v53",
+  "v54", "v55", "v56", "v57", "v58", "v59", "v60", "v61", "v62",
+  "v63", "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71",
+  "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79", "v80",
+  "v81", "v82", "v83", "v84", "v85", "v86", "v87", "v88", "v89",
+  "v90", "v91", "v92", "v93", "v94", "v95", "v96", "v97", "v98",
+  "v99", "v100", "v101", "v102", "v103", "v104", "v105", "v106", "v107",
+  "v108", "v109", "v110", "v111", "v112", "v113", "v114", "v115", "v116",
+  "v117", "v118", "v119", "v120", "v121", "v122", "v123", "v124", "v

[clang] [llvm] [ConstantFolding] Canonicalize constexpr GEPs to i8 (PR #89872)

2024-04-24 Thread Nikita Popov via cfe-commits

nikic wrote:

> Hi @nikic I read this RFC 
> https://discourse.llvm.org/t/rfc-replacing-getelementptr-with-ptradd/68699 
> and it seems it reqires multiple patches to implement it. I am wondering if 
> you have a link or page which contains all related PRs (or future PRs) ? I 
> want to track its progess.

The major patches have been https://github.com/llvm/llvm-project/pull/68882, 
https://github.com/llvm/llvm-project/pull/84341 and this one. There have been 
some smaller changes in between to fix related optimization regressions.


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


[clang] [llvm] [ConstantFolding] Canonicalize constexpr GEPs to i8 (PR #89872)

2024-04-24 Thread Nikita Popov via cfe-commits


@@ -944,43 +943,18 @@ Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
 return ConstantExpr::getIntToPtr(C, ResTy);
   }
 
-  // Otherwise form a regular getelementptr. Recompute the indices so that
-  // we eliminate over-indexing of the notional static type array bounds.
-  // This makes it easy to determine if the getelementptr is "inbounds".
-
-  // For GEPs of GlobalValues, use the value type, otherwise use an i8 GEP.
-  if (auto *GV = dyn_cast(Ptr))
-SrcElemTy = GV->getValueType();
-  else
-SrcElemTy = Type::getInt8Ty(Ptr->getContext());
-
-  if (!SrcElemTy->isSized())
-return nullptr;
-
-  Type *ElemTy = SrcElemTy;
-  SmallVector Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
-  if (Offset != 0)
-return nullptr;
-
-  // Try to add additional zero indices to reach the desired result element
-  // type.
-  // TODO: Should we avoid extra zero indices if ResElemTy can't be reached and
-  // we'll have to insert a bitcast anyway?
-  while (ElemTy != ResElemTy) {
-Type *NextTy = GetElementPtrInst::getTypeAtIndex(ElemTy, (uint64_t)0);
-if (!NextTy)
-  break;
-
-Indices.push_back(APInt::getZero(isa(ElemTy) ? 32 : BitWidth));
-ElemTy = NextTy;
+  // Try to infer inbounds for GEPs of globals.
+  if (!InBounds && Offset.isNonNegative()) {
+bool CanBeNull, CanBeFreed;
+uint64_t DerefBytes =
+Ptr->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
+InBounds = DerefBytes != 0 && !CanBeNull && Offset.sle(DerefBytes);

nikic wrote:

I don't think we'd want to remove it at this point as it's still used in some 
key places like initial IR construction in clang -- longer term, I'd like to 
get rid of the two separate constant folding implementations altogether.

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


[clang] [llvm] [mlir] [Clang][CodeGen] Start migrating away from assuming the Default AS is 0 (PR #88182)

2024-04-24 Thread Alex Voicu via cfe-commits


@@ -2216,7 +2216,7 @@ static llvm::Value *EmitTypeidFromVTable(CodeGenFunction 
&CGF, const Expr *E,
 }
 
 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
-  llvm::Type *PtrTy = llvm::PointerType::getUnqual(getLLVMContext());
+  llvm::Type *PtrTy = Int8PtrTy;

AlexVlx wrote:

It could be `GlobalsInt8PtrTy`, but the main roadblock would require something 
that @rjmccall suggested looking into, namely adding the ability to declare a 
default AS for a class type, which stdlib implementations could then re-use. 
Having said that, I've neither had the time to look into it, nor figured out if 
this would work in general, considering we need to compose with stdlib 
implementations other than libc++. Having said that, perhaps the TODO: should 
actually be at the end of the comment, and just say something along the lines 
of "investigate if it is possible to remove this limitation"?

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


[clang] d530894 - [clang][Sema] Preserve the initializer of invalid VarDecls (#88645)

2024-04-24 Thread via cfe-commits

Author: Nathan Ridge
Date: 2024-04-24T20:31:18-04:00
New Revision: d5308949cf884d8e4b971d51a8b4f73584c4adec

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

LOG: [clang][Sema] Preserve the initializer of invalid VarDecls (#88645)

Fixes https://github.com/clangd/clangd/issues/1821

Added: 


Modified: 
clang/lib/Sema/JumpDiagnostics.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/AST/ast-dump-recovery.cpp

Removed: 




diff  --git a/clang/lib/Sema/JumpDiagnostics.cpp 
b/clang/lib/Sema/JumpDiagnostics.cpp
index ce6211c23218bb..8af36d5c24e3d2 100644
--- a/clang/lib/Sema/JumpDiagnostics.cpp
+++ b/clang/lib/Sema/JumpDiagnostics.cpp
@@ -180,7 +180,8 @@ static ScopePair GetDiagForGotoScopeDecl(Sema &S, const 
Decl *D) {
 }
 
 const Expr *Init = VD->getInit();
-if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
+if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init &&
+!Init->containsErrors()) {
   // C++11 [stmt.dcl]p3:
   //   A program that jumps from a point where a variable with automatic
   //   storage duration is not in scope to a point where it is in scope

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 378615497b13cf..e0745fe9a45367 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13502,16 +13502,18 @@ void Sema::checkNonTrivialCUnion(QualType QT, 
SourceLocation Loc,
 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
   // If there is no declaration, there was an error parsing it.  Just ignore
   // the initializer.
-  if (!RealDecl || RealDecl->isInvalidDecl()) {
+  if (!RealDecl) {
 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null(RealDecl));
 return;
   }
 
-  if (CXXMethodDecl *Method = dyn_cast(RealDecl)) {
-// Pure-specifiers are handled in ActOnPureSpecifier.
-Diag(Method->getLocation(), diag::err_member_function_initialization)
-  << Method->getDeclName() << Init->getSourceRange();
-Method->setInvalidDecl();
+  if (auto *Method = dyn_cast(RealDecl)) {
+if (!Method->isInvalidDecl()) {
+  // Pure-specifiers are handled in ActOnPureSpecifier.
+  Diag(Method->getLocation(), diag::err_member_function_initialization)
+  << Method->getDeclName() << Init->getSourceRange();
+  Method->setInvalidDecl();
+}
 return;
   }
 
@@ -13523,6 +13525,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
 return;
   }
 
+  if (VDecl->isInvalidDecl()) {
+CorrectDelayedTyposInExpr(Init, VDecl);
+ExprResult Recovery =
+CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
+if (Expr *E = Recovery.get())
+  VDecl->setInit(E);
+return;
+  }
+
   // WebAssembly tables can't be used to initialise a variable.
   if (Init && !Init->getType().isNull() &&
   Init->getType()->isWebAssemblyTableType()) {

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index cfb013585ad744..77527743fe8577 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -413,6 +413,14 @@ void RecoveryExprForInvalidDecls(Unknown InvalidDecl) {
   // CHECK-NEXT: `-RecoveryExpr {{.*}} ''
 }
 
+void InitializerOfInvalidDecl() {
+  int ValidDecl;
+  Unkown InvalidDecl = ValidDecl;
+  // CHECK:  VarDecl {{.*}} invalid InvalidDecl
+  // CHECK-NEXT: `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'int' lvalue Var {{.*}} 'ValidDecl'
+}
+
 void RecoverToAnInvalidDecl() {
   Unknown* foo; // invalid decl
   goo; // the typo was correct to the invalid foo.



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


[clang] [clang][Sema] Preserve the initializer of invalid VarDecls (PR #88645)

2024-04-24 Thread Nathan Ridge via cfe-commits

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


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

2024-04-24 Thread via cfe-commits

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

>From 9fba6da7cb1ffbc7d46b69c6ac0cfd15a89c4b56 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Mon, 8 Apr 2024 01:38:23 +0800
Subject: [PATCH 1/3] [Clang] Support lifetime extension of temporary created
 by aggregate initialization using a default member initializer

Signed-off-by: yronglin 
---
 .../clang/Basic/DiagnosticSemaKinds.td|  6 ---
 clang/lib/Sema/SemaExpr.cpp   | 16 
 clang/lib/Sema/SemaInit.cpp   | 39 +--
 .../Analysis/lifetime-extended-regions.cpp|  2 +-
 clang/test/CXX/drs/dr16xx.cpp |  2 -
 clang/test/CXX/drs/dr18xx.cpp |  5 +--
 clang/test/CXX/special/class.temporary/p6.cpp | 20 ++
 clang/test/SemaCXX/constexpr-default-arg.cpp  |  4 +-
 clang/test/SemaCXX/eval-crashes.cpp   |  6 +--
 9 files changed, 62 insertions(+), 38 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a1dda2d2461c31..ba779e83d2afd4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10010,12 +10010,6 @@ def warn_new_dangling_initializer_list : Warning<
   "the allocated initializer list}0 "
   "will be destroyed at the end of the full-expression">,
   InGroup;
-def warn_unsupported_lifetime_extension : Warning<
-  "lifetime extension of "
-  "%select{temporary|backing array of initializer list}0 created "
-  "by aggregate initialization using a default member initializer "
-  "is not yet supported; lifetime of %select{temporary|backing array}0 "
-  "will end at the end of the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 8db4fffeecfe35..b2e0f2a2a60113 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6338,10 +6338,9 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation 
CallLoc,
 Res = Immediate.TransformInitializer(Param->getInit(),
  /*NotCopy=*/false);
   });
-  if (Res.isInvalid())
-return ExprError();
-  Res = ConvertParamDefaultArgument(Param, Res.get(),
-Res.get()->getBeginLoc());
+  if (Res.isUsable())
+Res = ConvertParamDefaultArgument(Param, Res.get(),
+  Res.get()->getBeginLoc());
   if (Res.isInvalid())
 return ExprError();
   Init = Res.get();
@@ -6377,7 +6376,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   Expr *Init = nullptr;
 
   bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
-
+  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
   EnterExpressionEvaluationContext EvalContext(
   *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
 
@@ -6412,11 +6411,14 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   ImmediateCallVisitor V(getASTContext());
   if (!NestedDefaultChecking)
 V.TraverseDecl(Field);
-  if (V.HasImmediateCalls) {
+  if (V.HasImmediateCalls || InLifetimeExtendingContext) {
 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
CurContext};
 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
 NestedDefaultChecking;
+// Pass down lifetime extending flag, and collect temporaries in
+// CreateMaterializeTemporaryExpr when we rewrite the call argument.
+keepInLifetimeExtendingContext();
 
 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
 ExprResult Res;
@@ -6424,7 +6426,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation 
Loc, FieldDecl *Field) {
   Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
/*CXXDirectInit=*/false);
 });
-if (!Res.isInvalid())
+if (Res.isUsable())
   Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
 if (Res.isInvalid()) {
   Field->setInvalidDecl();
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index a75e9925a43146..842412cd674d8c 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -710,6 +710,26 @@ void InitListChecker::FillInEmptyInitForField(unsigned 
Init, FieldDecl *Field,
   if (VerifyOnly)
 return;
 
+  // Enter a lifetime extension context, then we can support lifetime
+  // extension of temporary created by aggregate initialization using a
+  // default member initializer (DR1815 https://wg21.link/CWG1815).
+  //
+  

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

2024-04-24 Thread Xiang Li via cfe-commits


@@ -25,6 +25,7 @@ enum class ResourceClass : uint8_t {
   SRV = 0,
   UAV,
   CBuffer,
+  TBuffer,

python3kgae wrote:

TBuffer should be a resource kind, not resource class.

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


[clang] [Clang] [CodeGen] Perform derived-to-base conversion on explicit object parameter in lambda (PR #89828)

2024-04-24 Thread via cfe-commits

Sirraide wrote:

I’m also not sure if the `dr28xx.cpp` file is meant for open issues, but I’ve 
put the tests for this there for now.

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


[clang] [Clang] [CodeGen] Perform derived-to-base conversion on explicit object parameter in lambda (PR #89828)

2024-04-24 Thread via cfe-commits

Sirraide wrote:

Ok, I’ve added a check for CWG 2881 to sema, but there’s at least 2 things I 
still want to take a look at:
- [ ] Consider emitting the upcast once in the function prologue instead of 
every time a variable is accessed.
- [ ] Check for invalid explicit object parameters when the lambda is 
instantiated rather than when it is called.

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


[clang] [Clang] [CodeGen] Perform derived-to-base conversion on explicit object parameter in lambda (PR #89828)

2024-04-24 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/89828

>From b5422012a65165f27bb31be7e9490892f663acfe Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Tue, 23 Apr 2024 22:45:29 +0200
Subject: [PATCH 1/2] [Clang] [CodeGen] Perform derived-to-base conversion on
 explicit object parameter in lambda

---
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/lib/CodeGen/CGExpr.cpp  | 23 +++
 clang/test/CodeGenCXX/cxx2b-deducing-this.cpp | 63 +++
 3 files changed, 89 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d1f7293a842bb6..34aad4abf39619 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -562,6 +562,9 @@ Bug Fixes to C++ Support
 - Fixed a crash when trying to evaluate a user-defined ``static_assert`` 
message whose ``size()``
   function returns a large or negative value. Fixes (#GH89407).
 - Fixed a use-after-free bug in parsing of type constraints with default 
arguments that involve lambdas. (#GH67235)
+- Fixed a crash when trying to emit captures in a lambda call operator with an 
explicit object
+  parameter that is called on a derived type of the lambda.
+  Fixes (#GH87210), (GH89541).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 931cb391342ea2..33795d7d4d1921 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4684,6 +4684,29 @@ LValue CodeGenFunction::EmitLValueForLambdaField(const 
FieldDecl *Field,
 else
   LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
 D->getType().getNonReferenceType());
+
+// Make sure we have an lvalue to the lambda itself and not a derived 
class.
+auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
+auto *LambdaTy = cast(Field->getParent());
+if (ThisTy != LambdaTy) {
+  CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
+ /*DetectVirtual=*/false);
+
+  [[maybe_unused]] bool Derived = ThisTy->isDerivedFrom(LambdaTy, Paths);
+  assert(Derived && "Type not derived from lambda type?");
+
+  const CXXBasePath *Path = &Paths.front();
+  CXXCastPath BasePathArray;
+  for (unsigned I = 0, E = Path->size(); I != E; ++I)
+BasePathArray.push_back(
+const_cast((*Path)[I].Base));
+
+  Address Base = GetAddressOfBaseClass(
+  LambdaLV.getAddress(*this), ThisTy, BasePathArray.begin(),
+  BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
+
+  LambdaLV = MakeAddrLValue(Base, QualType{LambdaTy->getTypeForDecl(), 0});
+}
   } else {
 QualType LambdaTagType = getContext().getTagDeclType(Field->getParent());
 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
diff --git a/clang/test/CodeGenCXX/cxx2b-deducing-this.cpp 
b/clang/test/CodeGenCXX/cxx2b-deducing-this.cpp
index b755e80db35a12..649fe2afbf4e91 100644
--- a/clang/test/CodeGenCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/CodeGenCXX/cxx2b-deducing-this.cpp
@@ -182,3 +182,66 @@ auto dothing(int num)
   fun();
 }
 }
+
+namespace GH87210 {
+template 
+struct Overloaded : Ts... {
+  using Ts::operator()...;
+};
+
+template 
+Overloaded(Ts...) -> Overloaded;
+
+// CHECK-LABEL: define dso_local void @_ZN7GH872101fEv()
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[X:%.*]] = alloca i32
+// CHECK-NEXT:[[Over:%.*]] = alloca %"{{.*}}Overloaded"
+// CHECK: call noundef ptr 
@"_ZZN7GH872101fEvENH3$_0clINS_10OverloadedIJS0_EDaRT_"(ptr {{.*}} [[Over]])
+void f() {
+  int x;
+  Overloaded o {
+// CHECK: define internal noundef ptr 
@"_ZZN7GH872101fEvENH3$_0clINS_10OverloadedIJS0_EDaRT_"(ptr {{.*}} 
[[Self:%.*]])
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[SelfAddr:%.*]] = alloca ptr
+// CHECK-NEXT:store ptr [[Self]], ptr [[SelfAddr]]
+// CHECK-NEXT:[[SelfPtr:%.*]] = load ptr, ptr [[SelfAddr]]
+// CHECK-NEXT:[[XRef:%.*]] = getelementptr inbounds %{{.*}}, ptr 
[[SelfPtr]], i32 0, i32 0
+// CHECK-NEXT:[[X:%.*]] = load ptr, ptr [[XRef]]
+// CHECK-NEXT:ret ptr [[X]]
+[&](this auto& self) {
+  return &x;
+}
+  };
+  o();
+}
+
+void g() {
+  int x;
+  Overloaded o {
+[=](this auto& self) {
+  return x;
+}
+  };
+  o();
+}
+}
+
+namespace GH89541 {
+// Same as above; just check that this doesn't crash.
+int one = 1;
+auto factory(int& x = one) {
+  return [&](this auto self) {
+x;
+  };
+};
+
+using Base = decltype(factory());
+struct Derived : Base {
+  Derived() : Base(factory()) {}
+};
+
+void f() {
+  Derived d;
+  d();
+}
+}

>From 90d73ea88016307532bb38c4b2e8fa8f082bea75 Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Thu, 25 Apr 2024 01:01:18 +0200
Subject: [PATCH 2/2] [Clang] Tentative implementation of CWG 2881

---
 clang/include/clang/AST/ASTContext.h  |  9 +++

[clang] [Driver] Restore compiler-rt arch suffix for PS and Windows (PR #89775)

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

MaskRay wrote:

I understand that there is some distributed build system pain and I feel 
sympathy.
However, I have pointed out that it is *unsupported* to not provide files for 
driver probing, therefore I am not sure it is fair to revert the patches 
improving
`LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=on` users.

Again, clangDriver does file probing in various places. If you want a specific 
driver decision, provide sufficient files to make it make the best guess for 
you.

If `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=off` users are willing to accept less 
test coverage, we can swap the probed paths in `ToolChain::getCompilerRT` if 
`LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=off`.

I am also fine if Windows users decide to prefer UI for 
`LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=off` configurations and add a 
`isOSWindows()` check somewhere.


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


  1   2   3   4   5   >