[PATCH] D122460: [clang] fixed bug #54406

2022-03-25 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/Sema/SemaExprMember.cpp:690
+// int n = a.B::m;
+if (BaseExpr && isa(DC) && isa(RDecl)) {
+  CXXRecordDecl *SRecord = cast(DC)->getCanonicalDecl();

We don't generally cite bug numbers in the source code; we just cite the 
language rule.  You can reference the bug number in your test, though.

The standard says that this is an error even when the member access is 
implicit, so the check for `BaseExpr` is incorrect.

Conversely, the standard says this is not an error when the declaration 
referenced is not a non-static data member or member function, so you cannot do 
this before the lookup; in fact, you cannot do it until we've fully resolved 
the lookup, which may require contextual information.

All of the code paths that build a non-static member eventually funnel into 
`BuildMemberExpr`, so maybe that's the right place for the check?  But note 
that you have to check explicitly for a non-static member, because `MemberExpr` 
is used for all of them.

Technically, this rule wasn't in C++98, but since it does appear in C++03, I 
agree we should just enforce it unconditionally, as we usually treat C++03 as 
an errata release rather than its own language mode.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122460/new/

https://reviews.llvm.org/D122460

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


[clang] 392bb8c - [OpenMP] Fix AMDGPU globals test

2022-03-25 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-03-25T23:05:41-04:00
New Revision: 392bb8cf1f726207fd994b400f6bc38cb4757a05

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

LOG: [OpenMP] Fix AMDGPU globals test

Added: 


Modified: 
clang/test/OpenMP/amdgcn_target_global_constructor.cpp

Removed: 




diff  --git a/clang/test/OpenMP/amdgcn_target_global_constructor.cpp 
b/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
index 9ada77fe8a805..43082913bc4a6 100644
--- a/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ b/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -1,4 +1,4 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --check-globals --include-generated-funcs 
--replace-value-regex "__omp_offloading__[0-9a-z]_[0-9a-z]_"
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex 
"__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" 
"pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _
 // REQUIRES: amdgpu-registered-target
 
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
@@ -20,14 +20,7 @@ S A;
 #pragma omp end declare target
 
 #endif
-//.
-// CHECK: @__omp_rtl_debug_kind = weak_odr hidden addrspace(1) constant i32 0
-// CHECK: @__omp_rtl_assume_teams_oversubscription = weak_odr hidden 
addrspace(1) constant i32 0
-// CHECK: @__omp_rtl_assume_threads_oversubscription = weak_odr hidden 
addrspace(1) constant i32 0
-// CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) 
constant i32 0
-// CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
-//.
-// CHECK-LABEL: define 
{{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading_.*_.*}}_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 
dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to 
%struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +38,7 @@ S A;
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define 
{{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading_.*_.*}}_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 
dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to 
%struct.S*)) #[[ATTR4:[0-9]+]]
@@ -85,20 +78,3 @@ S A;
 // CHECK-NEXT:call void @_Z3foov() #[[ATTR3]]
 // CHECK-NEXT:ret void
 //
-//.
-// CHECK: attributes #0 = { nounwind "kernel" "min-legal-vector-width"="0" }
-// CHECK: attributes #1 = { convergent noinline nounwind optnone 
"frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" }
-// CHECK: attributes #2 = { convergent "frame-pointer"="none" 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" }
-// CHECK: attributes #3 = { convergent }
-// CHECK: attributes #4 = { convergent nounwind }
-//.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1680388141, 
!"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1680388141, 
!"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor", i32 19, i32 2}
-// CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @{{.*}}_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @{{.*}}_A_l19_dtor, !"kernel", i32 1}
-// CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
-// CHECK: !6 = !{i32 7, !"openmp", i32 50}
-// CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
-// CHECK: !8 = !{!"clang version 15.0.0"}
-//.



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


[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9d3550c51733: [OpenMP] Add AMDGPU calling convention to ctor 
/ dtor functions (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122515/new/

https://reviews.llvm.org/D122515

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  openmp/libomptarget/test/offloading/global_constructor.cpp

Index: openmp/libomptarget/test/offloading/global_constructor.cpp
===
--- openmp/libomptarget/test/offloading/global_constructor.cpp
+++ openmp/libomptarget/test/offloading/global_constructor.cpp
@@ -1,23 +1,25 @@
 // RUN: %libomptarget-compilexx-generic && %libomptarget-run-generic | %fcheck-generic
 
-// Fails in DAGToDAG on an address space problem
-// UNSUPPORTED: amdgcn-amd-amdhsa
-// UNSUPPORTED: amdgcn-amd-amdhsa-newDriver
-
-#include 
 #include 
 
-const double Host = log(2.0) / log(2.0);
-#pragma omp declare target
-const double Device = log(2.0) / log(2.0);
-#pragma omp end declare target
+int foo() { return 1; }
+
+class C {
+public:
+  C() : x(foo()) {}
+
+  int x;
+};
+
+C c;
+#pragma omp declare target(c)
 
 int main() {
-  double X;
-#pragma omp target map(from : X)
-  { X = Device; }
+  int x = 0;
+#pragma omp target map(from : x)
+  { x = c.x; }
 
   // CHECK: PASS
-  if (X == Host)
+  if (x == 1)
 printf("PASS\n");
 }
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -1,4 +1,4 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --check-globals --include-generated-funcs
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --check-globals --include-generated-funcs --replace-value-regex "__omp_offloading__[0-9a-z]_[0-9a-z]_"
 // REQUIRES: amdgpu-registered-target
 
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
@@ -27,7 +27,7 @@
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1680388141, !"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1680388141, !"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_dtor, !"kernel", i32 1}
+// CHECK: !3 = !{void ()* @{{.*}}_A_l19_ctor, !"kernel", i32 1}
+// CHECK: !4 = !{void ()* @{{.*}}_A_l19_dtor, !"kernel", i32 1}
 // CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
 // CHECK: !6 = !{i32 7, !"openmp", i32 50}
 // CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+

[PATCH] D122504: [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3c6d32ec6cdb: [OpenMP] Make Ctor / Dtor functions have 
external visibility (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122504/new/

https://reviews.llvm.org/D122504

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  clang/test/OpenMP/declare_target_codegen.cpp
  clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp

Index: clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
===
--- clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
+++ clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
@@ -44,7 +44,7 @@
 static int c = foo() + bar() + baz();
 #pragma omp declare target (c)
 // HOST-DAG: @[[C_CTOR:__omp_offloading__.+_c_l44_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
+// DEVICE-DAG: define weak_odr void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
 // DEVICE-DAG: call noundef i32 [[FOO]]()
 // DEVICE-DAG: call noundef i32 [[BAR]]()
 // DEVICE-DAG: call noundef i32 [[BAZ]]()
@@ -61,14 +61,14 @@
 S cd = doo() + car() + caz() + baz();
 #pragma omp end declare target
 // HOST-DAG: @[[CD_CTOR:__omp_offloading__.+_cd_l61_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
+// DEVICE-DAG: define weak_odr void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
 // DEVICE-DAG: call noundef i32 [[DOO]]()
 // DEVICE-DAG: call noundef i32 [[CAR]]()
 // DEVICE-DAG: call noundef i32 [[CAZ]]()
 // DEVICE-DAG: ret void
 
 // HOST-DAG: @[[CD_DTOR:__omp_offloading__.+_cd_l61_dtor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
+// DEVICE-DAG: define weak_odr void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
 // DEVICE-DAG: call void
 // DEVICE-DAG: ret void
 
Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -46,7 +46,6 @@
 // CHECK-DAG: [[STAT:@.+stat]] = internal global %struct.S zeroinitializer,
 // CHECK-DAG: [[STAT_REF:@.+]] = internal constant %struct.S* [[STAT]]
 // CHECK-DAG: @out_decl_target ={{ protected | }}global i32 0,
-// CHECK-DAG: @llvm.used = appending global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading__{{.+}}_globals_l[[@LINE+84]]_ctor to i8*), i8* bitcast (void ()* @__omp_offloading__{{.+}}_stat_l[[@LINE+85]]_ctor to i8*)],
 // CHECK-DAG: @llvm.compiler.used = appending global [1 x i8*] [i8* bitcast (%struct.S** [[STAT_REF]] to i8*)],
 
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -26,9 +26,8 @@
 // CHECK: @__omp_rtl_assume_threads_oversubscription = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
-// CHECK: @llvm.used = appending addrspace(1) global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading_{{.*}}_ctor to i8*), i8* bitcast (void ()* @__omp_offloading_{{.*}}_dtor to i8*)], section "llvm.metadata"
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading_{{.*}}_ctor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -46,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading_{{.*}}_dtor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -87,19 +86,19 @@
 // CHECK-NEXT:ret void
 //
 //.
-// CHECK: attributes #0 = { convergent
-// CHECK: attributes #1 = { convergent
-// CHECK: attributes #2 = { convergent
-// CHECK: attributes #3 = { convergent
-// CHECK: attributes #4 = { convergent
+// CHECK: attributes #0 = { nounwind "kernel" "min-legal-vector-width"="0" }
+// CHECK: 

[clang] 9d3550c - [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-03-25T22:44:20-04:00
New Revision: 9d3550c5173373305c10a5a471a935be205191a2

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

LOG: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

This patch adds the necessary AMDGPU calling convention to the ctor /
dtor kernels. These are fundamentally device kenels called by the host
on image load. Without this calling convention information the AMDGPU
plugin is unable to identify them.

Depends on D122504

Fixes #54091

Reviewed By: jdoerfert

Differential Revision: https://reviews.llvm.org/D122515

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/test/OpenMP/amdgcn_target_global_constructor.cpp
openmp/libomptarget/test/offloading/global_constructor.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index eeefa608fb7ee..5cc1fdb56aa54 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1972,6 +1974,8 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_dtor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
   DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);

diff  --git a/clang/test/OpenMP/amdgcn_target_global_constructor.cpp 
b/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
index 35bebaafdf544..9ada77fe8a805 100644
--- a/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ b/clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -1,4 +1,4 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --check-globals --include-generated-funcs
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --check-globals --include-generated-funcs 
--replace-value-regex "__omp_offloading__[0-9a-z]_[0-9a-z]_"
 // REQUIRES: amdgpu-registered-target
 
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
@@ -27,7 +27,7 @@ S A;
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) 
constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define 
{{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 
dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to 
%struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@ S A;
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define 
{{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 
dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to 
%struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@ S A;
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, 
!"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, 
!"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1680388141, 
!"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1680388141, 
!"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* 

[clang] 3c6d32e - [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-03-25T22:44:17-04:00
New Revision: 3c6d32ec6cdb426d531e0a3b3aa4449ff6e4d75c

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

LOG: [OpenMP] Make Ctor / Dtor functions have external visibility

The default construction of constructor functions by LLVM tends to make
them have internal linkage. When we call a ctor / dtor function in the
target region we are actually creating a kernel that is called at
registration. Because the ctor is a kernel we need to make sure it's
externally visible so we can actually call it. This prevented AMDGPU
from correctly using constructors while NVPTX could use them simply
because it ignored internal visibility.

Reviewed By: JonChesterfield

Differential Revision: https://reviews.llvm.org/D122504

Added: 


Modified: 
clang/lib/CodeGen/CGDeclCXX.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/OpenMP/amdgcn_target_global_constructor.cpp
clang/test/OpenMP/declare_target_codegen.cpp
clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index 7b880c1354e19..52d5b27eb01cb 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -425,9 +425,8 @@ void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value 
*NeedsInit,
 
 llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
 llvm::FunctionType *FTy, const Twine , const CGFunctionInfo ,
-SourceLocation Loc, bool TLS) {
-  llvm::Function *Fn = llvm::Function::Create(
-  FTy, llvm::GlobalValue::InternalLinkage, Name, ());
+SourceLocation Loc, bool TLS, llvm::GlobalVariable::LinkageTypes Linkage) {
+  llvm::Function *Fn = llvm::Function::Create(FTy, Linkage, Name, 
());
 
   if (!getLangOpts().AppleKext && !TLS) {
 // Set the section if needed.
@@ -435,7 +434,8 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   Fn->setSection(Section);
   }
 
-  SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
+  if (Linkage == llvm::GlobalVariable::InternalLinkage)
+SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
 
   Fn->setCallingConv(getRuntimeCC());
 

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 84527eb884cfd..eeefa608fb7ee 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1926,7 +1926,8 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   const CGFunctionInfo  = CGM.getTypes().arrangeNullaryFunction();
   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
-  FTy, Twine(Buffer, "_ctor"), FI, Loc);
+  FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
+  llvm::GlobalValue::WeakODRLinkage);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1944,7 +1945,6 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   CtorCGF.FinishFunction();
   Ctor = Fn;
   ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
-  CGM.addUsedGlobal(cast(Ctor));
 } else {
   Ctor = new llvm::GlobalVariable(
   CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
@@ -1970,7 +1970,8 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   const CGFunctionInfo  = CGM.getTypes().arrangeNullaryFunction();
   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
-  FTy, Twine(Buffer, "_dtor"), FI, Loc);
+  FTy, Twine(Buffer, "_dtor"), FI, Loc, false,
+  llvm::GlobalValue::WeakODRLinkage);
   auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
   DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1989,7 +1990,6 @@ bool 
CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
   DtorCGF.FinishFunction();
   Dtor = Fn;
   ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
-  CGM.addUsedGlobal(cast(Dtor));
 } else {
   Dtor = new llvm::GlobalVariable(
   CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index 1fcd5d4d808a1..b04393e38cf74 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -826,7 +826,9 @@ class CodeGenModule : public CodeGenTypeCache {
 
   

[PATCH] D122519: [AIX] XFAIL test for lack of visibility support

2022-03-25 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 418369.
Jake-Egan added a comment.

Updated the comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122519/new/

https://reviews.llvm.org/D122519

Files:
  clang/test/OpenMP/target_update_messages.cpp


Index: clang/test/OpenMP/target_update_messages.cpp
===
--- clang/test/OpenMP/target_update_messages.cpp
+++ clang/test/OpenMP/target_update_messages.cpp
@@ -1,3 +1,6 @@
+// Visibility hidden is not currently implemented on AIX.
+// XFAIL: aix
+
 // RUN: %clang_cc1 -verify=expected,lt50,lt51 -fopenmp -fopenmp-version=45 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,lt51 -fopenmp -fopenmp-version=50 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,ge51 -fopenmp -fopenmp-version=51 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized


Index: clang/test/OpenMP/target_update_messages.cpp
===
--- clang/test/OpenMP/target_update_messages.cpp
+++ clang/test/OpenMP/target_update_messages.cpp
@@ -1,3 +1,6 @@
+// Visibility hidden is not currently implemented on AIX.
+// XFAIL: aix
+
 // RUN: %clang_cc1 -verify=expected,lt50,lt51 -fopenmp -fopenmp-version=45 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,lt51 -fopenmp -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,ge51 -fopenmp -fopenmp-version=51 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122519: [AIX] XFAIL test for lack of visibility support

2022-03-25 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan created this revision.
Herald added a project: All.
Jake-Egan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122519

Files:
  clang/test/OpenMP/target_update_messages.cpp


Index: clang/test/OpenMP/target_update_messages.cpp
===
--- clang/test/OpenMP/target_update_messages.cpp
+++ clang/test/OpenMP/target_update_messages.cpp
@@ -1,3 +1,6 @@
+// Visibility is not currently implemented on AIX
+// XFAIL: aix
+
 // RUN: %clang_cc1 -verify=expected,lt50,lt51 -fopenmp -fopenmp-version=45 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,lt51 -fopenmp -fopenmp-version=50 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,ge51 -fopenmp -fopenmp-version=51 
-ferror-limit 100 -o - -std=c++11 %s -Wuninitialized


Index: clang/test/OpenMP/target_update_messages.cpp
===
--- clang/test/OpenMP/target_update_messages.cpp
+++ clang/test/OpenMP/target_update_messages.cpp
@@ -1,3 +1,6 @@
+// Visibility is not currently implemented on AIX
+// XFAIL: aix
+
 // RUN: %clang_cc1 -verify=expected,lt50,lt51 -fopenmp -fopenmp-version=45 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,lt51 -fopenmp -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
 // RUN: %clang_cc1 -verify=expected,ge50,ge51 -fopenmp -fopenmp-version=51 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418365.
jhuber6 added a comment.

Fix test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122515/new/

https://reviews.llvm.org/D122515

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  openmp/libomptarget/test/offloading/global_constructor.cpp

Index: openmp/libomptarget/test/offloading/global_constructor.cpp
===
--- openmp/libomptarget/test/offloading/global_constructor.cpp
+++ openmp/libomptarget/test/offloading/global_constructor.cpp
@@ -1,23 +1,25 @@
 // RUN: %libomptarget-compilexx-generic && %libomptarget-run-generic | %fcheck-generic
 
-// Fails in DAGToDAG on an address space problem
-// UNSUPPORTED: amdgcn-amd-amdhsa
-// UNSUPPORTED: amdgcn-amd-amdhsa-newDriver
-
-#include 
 #include 
 
-const double Host = log(2.0) / log(2.0);
-#pragma omp declare target
-const double Device = log(2.0) / log(2.0);
-#pragma omp end declare target
+int foo() { return 1; }
+
+class C {
+public:
+  C() : x(foo()) {}
+
+  int x;
+};
+
+C c;
+#pragma omp declare target(c)
 
 int main() {
-  double X;
-#pragma omp target map(from : X)
-  { X = Device; }
+  int x = 0;
+#pragma omp target map(from : x)
+  { x = c.x; }
 
   // CHECK: PASS
-  if (X == Host)
+  if (x == 1)
 printf("PASS\n");
 }
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -1,4 +1,4 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --check-globals --include-generated-funcs
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --check-globals --include-generated-funcs --replace-value-regex "__omp_offloading__[0-9a-z]_[0-9a-z]_"
 // REQUIRES: amdgpu-registered-target
 
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
@@ -27,7 +27,7 @@
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1680388141, !"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1680388141, !"{{__omp_offloading__[0-9a-z]+_[0-9a-z]+}}_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_dtor, !"kernel", i32 1}
+// CHECK: !3 = !{void ()* @{{.*}}_A_l19_ctor, !"kernel", i32 1}
+// CHECK: !4 = !{void ()* @{{.*}}_A_l19_dtor, !"kernel", i32 1}
 // CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
 // CHECK: !6 = !{i32 7, !"openmp", i32 50}
 // CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 

[PATCH] D115844: [ubsan] Using metadata instead of prologue data for function sanitizer

2022-03-25 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.
Herald added a subscriber: MaskRay.

ping ...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115844/new/

https://reviews.llvm.org/D115844

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


[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added a comment.

@davidxl,
I added comments in 
https://github.com/llvm/llvm-project/commit/ead8586645f54de16cfc6fa26028d818efc425f2

@MaskRay,
I followed the style guide for nested if statements in 
https://github.com/llvm/llvm-project/commit/ead8586645f54de16cfc6fa26028d818efc425f2


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122336/new/

https://reviews.llvm.org/D122336

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


[PATCH] D122513: [analyzer] Fix "RhsLoc and LhsLoc bitwidth must be same"

2022-03-25 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Why doesn't the AST handle this for us through implicit casts? Do we really 
need to duplicate type promotion logic in the static analyzer?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122513/new/

https://reviews.llvm.org/D122513

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


[PATCH] D121328: Disable -Wmissing-prototypes for internal linkage functions that aren't explicitly marked "static"""

2022-03-25 Thread David Blaikie via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG34b9b1ea4874: Disable -Wmissing-prototypes for internal 
linkage functions that arent… (authored by dblaikie).

Changed prior to commit:
  https://reviews.llvm.org/D121328?vs=417989=418360#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121328/new/

https://reviews.llvm.org/D121328

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/anonymous-struct.cpp
  clang/test/SemaCXX/warn-missing-prototypes.cpp


Index: clang/test/SemaCXX/warn-missing-prototypes.cpp
===
--- clang/test/SemaCXX/warn-missing-prototypes.cpp
+++ clang/test/SemaCXX/warn-missing-prototypes.cpp
@@ -44,3 +44,16 @@
 extern void k() {} // expected-warning {{no previous prototype for function 
'k'}}
 // expected-note@-1{{declare 'static' if the function is not intended to be 
used outside of this translation unit}}
 // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{.*}}-[[@LINE-2]]:{{.*}}}:"{{.*}}"
+
+namespace {
+struct anon { };
+}
+
+// No warning because this has internal linkage despite not being declared
+// explicitly 'static', owing to the internal linkage parameter.
+void l(anon) {
+}
+
+void *operator new(decltype(sizeof(3)) size, const anon &) throw() {
+  return nullptr;
+}
Index: clang/test/SemaCXX/anonymous-struct.cpp
===
--- clang/test/SemaCXX/anonymous-struct.cpp
+++ clang/test/SemaCXX/anonymous-struct.cpp
@@ -183,3 +183,9 @@
 void memcpy(); // expected-note {{due to this member}}
   } A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
 }
+namespace inline_defined_static_member {
+typedef struct { // expected-warning {{anonymous non-C-compatible type}}
+  static void f() { // expected-note {{due to this member}}
+  }
+} A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14233,6 +14233,11 @@
   if (FD->isDeleted())
 return false;
 
+  // Don't warn on implicitly local functions (such as having local-typed
+  // parameters).
+  if (!FD->isExternallyVisible())
+return false;
+
   for (const FunctionDecl *Prev = FD->getPreviousDecl();
Prev; Prev = Prev->getPreviousDecl()) {
 // Ignore any declarations that occur in function or method


Index: clang/test/SemaCXX/warn-missing-prototypes.cpp
===
--- clang/test/SemaCXX/warn-missing-prototypes.cpp
+++ clang/test/SemaCXX/warn-missing-prototypes.cpp
@@ -44,3 +44,16 @@
 extern void k() {} // expected-warning {{no previous prototype for function 'k'}}
 // expected-note@-1{{declare 'static' if the function is not intended to be used outside of this translation unit}}
 // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{.*}}-[[@LINE-2]]:{{.*}}}:"{{.*}}"
+
+namespace {
+struct anon { };
+}
+
+// No warning because this has internal linkage despite not being declared
+// explicitly 'static', owing to the internal linkage parameter.
+void l(anon) {
+}
+
+void *operator new(decltype(sizeof(3)) size, const anon &) throw() {
+  return nullptr;
+}
Index: clang/test/SemaCXX/anonymous-struct.cpp
===
--- clang/test/SemaCXX/anonymous-struct.cpp
+++ clang/test/SemaCXX/anonymous-struct.cpp
@@ -183,3 +183,9 @@
 void memcpy(); // expected-note {{due to this member}}
   } A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
 }
+namespace inline_defined_static_member {
+typedef struct { // expected-warning {{anonymous non-C-compatible type}}
+  static void f() { // expected-note {{due to this member}}
+  }
+} A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14233,6 +14233,11 @@
   if (FD->isDeleted())
 return false;
 
+  // Don't warn on implicitly local functions (such as having local-typed
+  // parameters).
+  if (!FD->isExternallyVisible())
+return false;
+
   for (const FunctionDecl *Prev = FD->getPreviousDecl();
Prev; Prev = Prev->getPreviousDecl()) {
 // Ignore any declarations that occur in function or method
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 34b9b1e - Disable -Wmissing-prototypes for internal linkage functions that aren't explicitly marked "static"

2022-03-25 Thread David Blaikie via cfe-commits

Author: David Blaikie
Date: 2022-03-25T23:53:19Z
New Revision: 34b9b1ea4874b109b998d59a837f81f2f730001c

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

LOG: Disable -Wmissing-prototypes for internal linkage functions that aren't 
explicitly marked "static"

Some functions can end up non-externally visible despite not being
declared "static" or in an unnamed namespace in C++ - such as by having
parameters that are of non-external types.

Such functions aren't mistakenly intended to be defining some function
that needs a declaration. They could be maybe more legible (except for
the operator new example) with an explicit static, but that's a
stylistic thing outside what should be addressed by a warning.

This reapplies 275c56226d7fbd6a4d554807374f78d323aa0c1c - once we figure
out what to do about the change in behavior for -Wnon-c-typedef-for-linkage
(this reverts the revert commit 85ee1d3ca1d06b6bd3477515b8d0c72c8df7c069)

Differential Revision: https://reviews.llvm.org/D121328

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/SemaCXX/anonymous-struct.cpp
clang/test/SemaCXX/warn-missing-prototypes.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5c262063a6aef..4051ab29fb26f 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -14233,6 +14233,11 @@ ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
   if (FD->isDeleted())
 return false;
 
+  // Don't warn on implicitly local functions (such as having local-typed
+  // parameters).
+  if (!FD->isExternallyVisible())
+return false;
+
   for (const FunctionDecl *Prev = FD->getPreviousDecl();
Prev; Prev = Prev->getPreviousDecl()) {
 // Ignore any declarations that occur in function or method

diff  --git a/clang/test/SemaCXX/anonymous-struct.cpp 
b/clang/test/SemaCXX/anonymous-struct.cpp
index 0a5395e15780b..7cf05ee3c49ae 100644
--- a/clang/test/SemaCXX/anonymous-struct.cpp
+++ b/clang/test/SemaCXX/anonymous-struct.cpp
@@ -183,3 +183,9 @@ namespace BuiltinName {
 void memcpy(); // expected-note {{due to this member}}
   } A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
 }
+namespace inline_defined_static_member {
+typedef struct { // expected-warning {{anonymous non-C-compatible type}}
+  static void f() { // expected-note {{due to this member}}
+  }
+} A; // expected-note {{given name 'A' for linkage purposes by this typedef}}
+}

diff  --git a/clang/test/SemaCXX/warn-missing-prototypes.cpp 
b/clang/test/SemaCXX/warn-missing-prototypes.cpp
index e8637e5a90eab..2880514ee02b7 100644
--- a/clang/test/SemaCXX/warn-missing-prototypes.cpp
+++ b/clang/test/SemaCXX/warn-missing-prototypes.cpp
@@ -44,3 +44,16 @@ void j() = delete;
 extern void k() {} // expected-warning {{no previous prototype for function 
'k'}}
 // expected-note@-1{{declare 'static' if the function is not intended to be 
used outside of this translation unit}}
 // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{.*}}-[[@LINE-2]]:{{.*}}}:"{{.*}}"
+
+namespace {
+struct anon { };
+}
+
+// No warning because this has internal linkage despite not being declared
+// explicitly 'static', owing to the internal linkage parameter.
+void l(anon) {
+}
+
+void *operator new(decltype(sizeof(3)) size, const anon &) throw() {
+  return nullptr;
+}



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


[PATCH] D23934: Add a -ffixed-date-time= flag that sets the initial value of __DATE__, __TIME__, __TIMESTAMP__

2022-03-25 Thread Anmol P. Paralkar via Phabricator via cfe-commits
appcs added a comment.

In D23934#3314277 , @appcs wrote:

> Hello, Will this feature be committed? Thanks!



In D23934#3355355 , @emaste wrote:

> The original author appears to have given up on it. Someone will need to 
> rebase and work on pushing it forward

Rebased. Please see: D122517 


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D23934/new/

https://reviews.llvm.org/D23934

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-25 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 418356.
void marked 2 inline comments as done.
void added a comment.

Move casting check into the SemaCast where it belongs.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121556/new/

https://reviews.llvm.org/D121556

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,409 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// 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 contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string ) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandstruct-seed=1234567890abcdef");
+  return tooling::buildASTFromCodeWithArgs(SourceCode, Args, "input.c");
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext , const std::string ) {
+  return FirstDeclMatcher().match(C.getTranslationUnitDecl(),
+  recordDecl(hasName(Name)));
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names , const field_names ) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast_matchers {
+
+#define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest
+
+TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) {
+  const field_names Seq = {"a", "b", "c", "d"};
+
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a"}));
+  ASSERT_FALSE(isSubsequence(Seq, {"a", "d"}));
+}
+
+#define RANDSTRUCT_TEST StructureLayoutRandomization
+
+TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+};
+  )c");
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+  const field_names Expected = {"bacon", "lettuce", "tomato", "mayonnaise"};
+
+  ASSERT_FALSE(RD->getAttr());
+  ASSERT_FALSE(RD->isRandomized());
+  ASSERT_EQ(Expected, getFieldNamesFromRecord(RD));
+}
+
+TEST(RANDSTRUCT_TEST, MarkedNoRandomize) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+} 

[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418355.
jhuber6 added a comment.

Remove leftover code.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122515/new/

https://reviews.llvm.org/D122515

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  openmp/libomptarget/test/offloading/global_constructor.cpp

Index: openmp/libomptarget/test/offloading/global_constructor.cpp
===
--- openmp/libomptarget/test/offloading/global_constructor.cpp
+++ openmp/libomptarget/test/offloading/global_constructor.cpp
@@ -1,23 +1,25 @@
 // RUN: %libomptarget-compilexx-generic && %libomptarget-run-generic | %fcheck-generic
 
-// Fails in DAGToDAG on an address space problem
-// UNSUPPORTED: amdgcn-amd-amdhsa
-// UNSUPPORTED: amdgcn-amd-amdhsa-newDriver
-
-#include 
 #include 
 
-const double Host = log(2.0) / log(2.0);
-#pragma omp declare target
-const double Device = log(2.0) / log(2.0);
-#pragma omp end declare target
+int foo() { return 1; }
+
+class C {
+public:
+  C() : x(foo()) {}
+
+  int x;
+};
+
+C c;
+#pragma omp declare target(c)
 
 int main() {
-  double X;
-#pragma omp target map(from : X)
-  { X = Device; }
+  int x = 0;
+#pragma omp target map(from : x)
+  { x = c.x; }
 
   // CHECK: PASS
-  if (X == Host)
+  if (x == 1)
 printf("PASS\n");
 }
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -27,7 +27,7 @@
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_dtor, !"kernel", i32 1}
+// CHECK: !3 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_ctor, !"kernel", i32 1}
+// CHECK: !4 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_dtor, !"kernel", i32 1}
 // CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
 // CHECK: !6 = !{i32 7, !"openmp", i32 50}
 // CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1972,6 +1974,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_dtor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
   DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);

[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122515/new/

https://reviews.llvm.org/D122515

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


[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418354.
jhuber6 added a comment.

Making test better.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122515/new/

https://reviews.llvm.org/D122515

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  openmp/libomptarget/test/offloading/global_constructor.cpp

Index: openmp/libomptarget/test/offloading/global_constructor.cpp
===
--- openmp/libomptarget/test/offloading/global_constructor.cpp
+++ openmp/libomptarget/test/offloading/global_constructor.cpp
@@ -1,23 +1,25 @@
 // RUN: %libomptarget-compilexx-generic && %libomptarget-run-generic | %fcheck-generic
 
-// Fails in DAGToDAG on an address space problem
-// UNSUPPORTED: amdgcn-amd-amdhsa
-// UNSUPPORTED: amdgcn-amd-amdhsa-newDriver
-
-#include 
 #include 
 
-const double Host = log(2.0) / log(2.0);
-#pragma omp declare target
-const double Device = log(2.0) / log(2.0);
-#pragma omp end declare target
+int foo() { return 1; }
+
+class C {
+public:
+  C() : x(foo()) {}
+
+  int x;
+};
+
+C c;
+#pragma omp declare target(c)
 
 int main() {
-  double X;
-#pragma omp target map(from : X)
-  { X = Device; }
+  int x = 0;
+#pragma omp target map(from : x)
+  { x = c.x; }
 
   // CHECK: PASS
-  if (X == Host)
+  if (x == 1)
 printf("PASS\n");
 }
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -27,7 +27,7 @@
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_dtor, !"kernel", i32 1}
+// CHECK: !3 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_ctor, !"kernel", i32 1}
+// CHECK: !4 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_dtor, !"kernel", i32 1}
 // CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
 // CHECK: !6 = !{i32 7, !"openmp", i32 50}
 // CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1972,6 +1974,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_dtor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
   DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ -1990,6 +1994,8 

[clang-tools-extra] 16eaa52 - [pseudo] Fix the wrong rule ids in ForestTest.

2022-03-25 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-03-26T00:05:37+01:00
New Revision: 16eaa5240e30af36a91db387df3c2e83e742

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

LOG: [pseudo] Fix the wrong rule ids in ForestTest.

Added: 


Modified: 
clang-tools-extra/pseudo/unittests/ForestTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/unittests/ForestTest.cpp 
b/clang-tools-extra/pseudo/unittests/ForestTest.cpp
index a734a8f7f8616..f382e0748afe2 100644
--- a/clang-tools-extra/pseudo/unittests/ForestTest.cpp
+++ b/clang-tools-extra/pseudo/unittests/ForestTest.cpp
@@ -90,8 +90,8 @@ TEST_F(ForestTest, DumpBasic) {
 TEST_F(ForestTest, DumpAmbiguousAndRefs) {
   build(R"cpp(
 _ := type
-type := class-type # rule 1
-type := enum-type # rule 2
+type := class-type # rule 3
+type := enum-type # rule 4
 class-type := shared-type
 enum-type := shared-type
 shared-type := IDENTIFIER)cpp");
@@ -106,21 +106,21 @@ TEST_F(ForestTest, DumpAmbiguousAndRefs) {
   symbol("shared-type"), ruleFor("shared-type"), {Terminals.begin()});
   const auto *ClassType = (
   symbol("class-type"), ruleFor("class-type"), {SharedType});
-  const auto *Enumtype = (
+  const auto *EnumType = (
   symbol("enum-type"), ruleFor("enum-type"), {SharedType});
   const auto *Alternative1 =
-  (symbol("type"), /*RuleID=*/1, {ClassType});
+  (symbol("type"), /*RuleID=*/3, {ClassType});
   const auto *Alternative2 =
-  (symbol("type"), /*RuleID=*/2, {Enumtype});
+  (symbol("type"), /*RuleID=*/4, {EnumType});
   const auto *Type =
   (symbol("type"), {Alternative1, Alternative2});
   EXPECT_EQ(Type->dumpRecursive(*G),
 "[  0, end) type := \n"
-"[  0, end) ├─class-type := shared-type\n"
+"[  0, end) ├─type := class-type\n"
 "[  0, end) │ └─class-type := shared-type\n"
 "[  0, end) │   └─shared-type := IDENTIFIER #1\n"
 "[  0, end) │ └─IDENTIFIER := tok[0]\n"
-"[  0, end) └─enum-type := shared-type\n"
+"[  0, end) └─type := enum-type\n"
 "[  0, end)   └─enum-type := shared-type\n"
 "[  0, end) └─shared-type := IDENTIFIER =#1\n"
 "[  0, end)   └─IDENTIFIER := tok[0]\n");



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


[clang-tools-extra] 41e69fb - [pseudo] Add missing header guard for Forest.h

2022-03-25 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-03-25T23:51:19+01:00
New Revision: 41e69fb2453505bd42f5a6bc15369b50adebeac4

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

LOG: [pseudo] Add missing header guard for Forest.h

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Forest.h

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
index 650f9131bd2ea..2b22fd564f742 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
@@ -17,6 +17,9 @@
 //
 
//===--===//
 
+#ifndef CLANG_PSEUDO_FOREST_H
+#define CLANG_PSEUDO_FOREST_H
+
 #include "clang-pseudo/Grammar.h"
 #include "clang-pseudo/Token.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -176,3 +179,5 @@ class ForestArena {
 
 } // namespace pseudo
 } // namespace clang
+
+#endif // CLANG_PSEUDO_FOREST_H



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


[PATCH] D122515: [OpenMP] Add AMDGPU calling convention to ctor / dtor functions

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, tianshilei1992, JonChesterfield, ronlieb.
Herald added subscribers: guansong, t-tye, tpr, dstuttard, yaxunl, jvesely, 
kzhuravl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: openmp-commits, cfe-commits, sstefan1, wdng.
Herald added projects: clang, OpenMP.

This patch adds the necessary AMDGPU calling convention to the ctor /
dtor kernels. These are fundamentally device kenels called by the host
on image load. Without this calling convention information the AMDGPU
plugin is unable to identify them.

Depends on D122504 

Fixes #54091


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122515

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  openmp/libomptarget/test/offloading/global_constructor.cpp

Index: openmp/libomptarget/test/offloading/global_constructor.cpp
===
--- openmp/libomptarget/test/offloading/global_constructor.cpp
+++ openmp/libomptarget/test/offloading/global_constructor.cpp
@@ -1,23 +1,23 @@
 // RUN: %libomptarget-compilexx-generic && %libomptarget-run-generic | %fcheck-generic
 
-// Fails in DAGToDAG on an address space problem
-// UNSUPPORTED: amdgcn-amd-amdhsa
-// UNSUPPORTED: amdgcn-amd-amdhsa-newDriver
-
-#include 
 #include 
 
-const double Host = log(2.0) / log(2.0);
-#pragma omp declare target
-const double Device = log(2.0) / log(2.0);
-#pragma omp end declare target
+class C {
+public:
+  C() : x(1) {}
+
+  int x;
+};
+
+C c;
+#pragma omp declare target(c)
 
 int main() {
-  double X;
-#pragma omp target map(from : X)
-  { X = Device; }
+  int x = 0;
+#pragma omp target map(from : x)
+  { x = c.x; }
 
   // CHECK: PASS
-  if (X == Host)
+  if (x == 1)
 printf("PASS\n");
 }
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -27,7 +27,7 @@
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -45,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_6139fe30_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -92,11 +92,11 @@
 // CHECK: attributes #3 = { convergent }
 // CHECK: attributes #4 = { convergent nounwind }
 //.
-// CHECK: !0 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_ctor", i32 19, i32 1}
-// CHECK: !1 = !{i32 0, i32 64770, i32 1631194454, !"__omp_offloading__fd02_613a0d56_A_l19_dtor", i32 19, i32 2}
+// CHECK: !0 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_ctor", i32 19, i32 1}
+// CHECK: !1 = !{i32 0, i32 64770, i32 1631190576, !"__omp_offloading__fd02_6139fe30_A_l19_dtor", i32 19, i32 2}
 // CHECK: !2 = !{i32 1, !"A", i32 0, i32 0}
-// CHECK: !3 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_ctor, !"kernel", i32 1}
-// CHECK: !4 = !{void ()* @__omp_offloading__fd02_613a0d56_A_l19_dtor, !"kernel", i32 1}
+// CHECK: !3 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_ctor, !"kernel", i32 1}
+// CHECK: !4 = !{void ()* @__omp_offloading__fd02_6139fe30_A_l19_dtor, !"kernel", i32 1}
 // CHECK: !5 = !{i32 1, !"wchar_size", i32 4}
 // CHECK: !6 = !{i32 7, !"openmp", i32 50}
 // CHECK: !7 = !{i32 7, !"openmp-device", i32 50}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1928,6 +1928,8 @@
   llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
   FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
   llvm::GlobalValue::WeakODRLinkage);
+  if (CGM.getTriple().isAMDGCN())
+Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
   auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
   CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
 FunctionArgList(), Loc, Loc);
@@ 

[PATCH] D122513: [analyzer] Fix "RhsLoc and LhsLoc bitwidth must be same"

2022-03-25 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers created this revision.
vabridgers added reviewers: NoQ, steakhal, martong.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: All.
vabridgers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

clang: /clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:727:
void assertEqualBitWidths(clang::ento::ProgramStateRef,

  clang::ento::Loc, clang::ento::Loc): Assertion `RhsBitwidth ==
  LhsBitwidth && "RhsLoc and LhsLoc bitwidth must be same!"'

This change adjusts the bitwidth of the smaller operand for an evalBinOp
as a result of a comparison operation. This can occur in the specific
case represented by the test cases for a target with different pointer
sizes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122513

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/addrspace-null.c


Index: clang/test/Analysis/addrspace-null.c
===
--- /dev/null
+++ clang/test/Analysis/addrspace-null.c
@@ -0,0 +1,47 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DAMDGCN_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+//
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DDEFAULT_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+
+// expected-no-diagnostics
+
+#define DEVICE __attribute__((address_space(3)))
+
+#if defined(AMDGCN)
+// this crashes
+int fn1() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (void *)0;
+}
+
+// does not crash
+int fn2() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+
+// this crashes
+int fn3() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+#endif
+
+// does not crash
+int fn4() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (void *)0;
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -792,8 +792,27 @@
 
 // If both operands are constants, just perform the operation.
 if (Optional rInt = rhs.getAs()) {
-  SVal ResultVal =
-  lhs.castAs().evalBinOp(BasicVals, op, *rInt);
+  // Need a big enough type to compare both values.
+  //
+  // In the case of something like this for targets with different
+  // pointer sizes based on address space, need to find the largest
+  // bitwidth to use for the evalBinOp
+  //
+  // int fn1() {
+  //   int val = 0;
+  //   __attribute__((address_space(3))) int *dptr = val;
+  //   return dptr == (void *)0;
+  // }
+  llvm::APSInt LHSValue = lhs.castAs().getValue();
+  llvm::APSInt RHSValue = rhs.castAs().getValue();
+  APSIntType OpType = std::max(APSIntType(LHSValue), APSIntType(RHSValue));
+
+  OpType.apply(LHSValue);
+  OpType.apply(RHSValue);
+  loc::ConcreteInt ciLHS = loc::ConcreteInt(LHSValue);
+  loc::ConcreteInt ciRHS = loc::ConcreteInt(RHSValue);
+  SVal ResultVal = ciLHS.evalBinOp(BasicVals, op, ciRHS);
+
   if (Optional Result = ResultVal.getAs())
 return evalCast(*Result, resultTy, QualType{});
 


Index: clang/test/Analysis/addrspace-null.c
===
--- /dev/null
+++ clang/test/Analysis/addrspace-null.c
@@ -0,0 +1,47 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DAMDGCN_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+//
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DDEFAULT_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+
+// expected-no-diagnostics
+
+#define DEVICE __attribute__((address_space(3)))
+
+#if defined(AMDGCN)
+// this crashes
+int fn1() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (void *)0;
+}
+
+// does not crash
+int fn2() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+
+// this crashes
+int 

[PATCH] D120956: [clang][AST matchers] new AST matcher argumentsGivenCountIs(n) that checks the actual number of arguments given in a function call

2022-03-25 Thread Alister Johnson via Phabricator via cfe-commits
ajohnson-uoregon updated this revision to Diff 418346.
ajohnson-uoregon added a comment.

Fixing name of matcher and formatting, still need tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120956/new/

https://reviews.llvm.org/D120956

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp

Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -135,6 +135,7 @@
   REGISTER_MATCHER(anyOf);
   REGISTER_MATCHER(anything);
   REGISTER_MATCHER(argumentCountIs);
+  REGISTER_MATCHER(argumentCountAsWrittenIs);
   REGISTER_MATCHER(arraySubscriptExpr);
   REGISTER_MATCHER(arrayType);
   REGISTER_MATCHER(asString);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4420,6 +4420,29 @@
   return NumArgs == N;
 }
 
+/// Checks that a call expression or a constructor call expression has
+/// a specific number of arguments (EXCLUDING absent default arguments).
+///
+/// Example: callExpr(argumentCountAsWrittenIs(2)) matches f(0, 0) but not f(0)
+/// \code
+///   void f(int x, int y = 0);
+///   f(0, 0);
+///   f(0);
+/// \endcode
+AST_POLYMORPHIC_MATCHER_P(argumentCountAsWrittenIs,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(
+  CallExpr, CXXConstructExpr,
+  CXXUnresolvedConstructExpr, ObjCMessageExpr),
+  unsigned, N) {
+  unsigned NumArgs = Node.getNumArgs();
+  while (NumArgs) {
+if (!isa(Node.getArg(NumArgs - 1)))
+  break;
+--NumArgs;
+  }
+  return NumArgs == N;
+}
+
 /// Matches the n'th argument of a call expression or a constructor
 /// call expression.
 ///
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -3053,6 +3053,17 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html;>CXXConstructExprargumentCountAsWrittenIsunsigned N
+Checks that a call expression or a constructor call expression has
+a specific number of arguments (EXCLUDING absent default arguments).
+
+Example: callExpr(argumentCountAsWrittenIs(2)) matches f(0, 0) but not f(0)
+  void f(int x, int y = 0);
+  f(0, 0);
+  f(0);
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html;>CXXConstructExprargumentCountIsunsigned N
 Checks that a call expression or a constructor call expression has
 a specific number of arguments (including absent default arguments).
@@ -3710,6 +3721,17 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXUnresolvedConstructExpr.html;>CXXUnresolvedConstructExprargumentCountAsWrittenIsunsigned N
+Checks that a call expression or a constructor call expression has
+a specific number of arguments (EXCLUDING absent default arguments).
+
+Example: callExpr(argumentCountAsWrittenIs(2)) matches f(0, 0) but not f(0)
+  void f(int x, int y = 0);
+  f(0, 0);
+  f(0);
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXUnresolvedConstructExpr.html;>CXXUnresolvedConstructExprargumentCountIsunsigned N
 Checks that a call expression or a constructor call expression has
 a specific number of arguments (including absent default arguments).
@@ -3720,6 +3742,17 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CallExpr.html;>CallExprargumentCountAsWrittenIsunsigned N
+Checks that a call expression or a constructor call expression has
+a specific number of arguments (EXCLUDING absent default arguments).
+
+Example: callExpr(argumentCountAsWrittenIs(2)) matches f(0, 0) but not f(0)
+  void f(int x, int y = 0);
+  f(0, 0);
+  f(0);
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CallExpr.html;>CallExprargumentCountIsunsigned N
 Checks that a call expression or a constructor call expression has
 a specific number of arguments (including absent default arguments).
@@ -4831,6 +4864,17 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMessageExpr.html;>ObjCMessageExprargumentCountAsWrittenIsunsigned N
+Checks that a call expression or a constructor call expression has
+a specific number of arguments (EXCLUDING absent default arguments).
+
+Example: callExpr(argumentCountAsWrittenIs(2)) matches f(0, 0) but not f(0)
+  void f(int x, int y = 0);
+  f(0, 0);
+  f(0);
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMessageExpr.html;>ObjCMessageExprargumentCountIsunsigned N
 Checks that a call expression or a constructor call expression has
 a specific number of arguments (including absent default 

[PATCH] D122511: [clang][extract-api] Add Objective-C protocol support

2022-03-25 Thread Zixu Wang via Phabricator via cfe-commits
zixuw created this revision.
Herald added a reviewer: dang.
Herald added a project: All.
zixuw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add support for Objective-C protocol declarations in ExtractAPI.

Depends on D122446 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122511

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/objc_interface.m
  clang/test/ExtractAPI/objc_protocol.m

Index: clang/test/ExtractAPI/objc_protocol.m
===
--- /dev/null
+++ clang/test/ExtractAPI/objc_protocol.m
@@ -0,0 +1,146 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/reference.output.json.in >> \
+// RUN: %t/reference.output.json
+// RUN: %clang -extract-api -x objective-c-header -target arm64-apple-macosx \
+// RUN: %t/input.h -o %t/output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- input.h
+@protocol Protocol
+@end
+
+@protocol AnotherProtocol 
+@end
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationhips": [
+{
+  "kind": "conformsTo",
+  "source": "c:objc(pl)AnotherProtocol",
+  "target": "c:objc(pl)Protocol"
+}
+  ],
+  "symbols": [
+{
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "@protocol"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Protocol"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(pl)Protocol"
+  },
+  "kind": {
+"displayName": "Protocol",
+"identifier": "objective-c.protocol"
+  },
+  "location": {
+"character": 11,
+"line": 1,
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "Protocol"
+  }
+],
+"title": "Protocol"
+  }
+},
+{
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "@protocol"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "AnotherProtocol"
+},
+{
+  "kind": "text",
+  "spelling": " <"
+},
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:objc(pl)Protocol",
+  "spelling": "Protocol"
+},
+{
+  "kind": "text",
+  "spelling": ">"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(pl)AnotherProtocol"
+  },
+  "kind": {
+"displayName": "Protocol",
+"identifier": "objective-c.protocol"
+  },
+  "location": {
+"character": 11,
+"line": 4,
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "AnotherProtocol"
+  }
+],
+"title": "AnotherProtocol"
+  }
+}
+  ]
+}
Index: clang/test/ExtractAPI/objc_interface.m
===
--- clang/test/ExtractAPI/objc_interface.m
+++ clang/test/ExtractAPI/objc_interface.m
@@ -14,8 +14,7 @@
 // CHECK-NOT: warning:
 
 //--- input.h
-@protocol Protocol
-@end
+@protocol Protocol;
 
 @interface Super 
 @property(readonly, getter=getProperty) unsigned Property;
@@ -111,7 +110,7 @@
   },
   "location": {
 "character": 12,
-"line": 4,
+"line": 3,
 "uri": "file://INPUT_DIR/input.h"
   },
   "names": {
@@ -174,7 +173,7 @@
   },
   "location": {
 "character": 1,
-"line": 6,
+"line": 

[PATCH] D122446: [clang][extract-api] Add Objective-C interface support

2022-03-25 Thread Zixu Wang via Phabricator via cfe-commits
zixuw updated this revision to Diff 418342.
zixuw added a comment.

No code change, amend commit message.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122446/new/

https://reviews.llvm.org/D122446

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/objc_interface.m

Index: clang/test/ExtractAPI/objc_interface.m
===
--- /dev/null
+++ clang/test/ExtractAPI/objc_interface.m
@@ -0,0 +1,403 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/reference.output.json.in >> \
+// RUN: %t/reference.output.json
+// RUN: %clang -extract-api -x objective-c-header -target arm64-apple-macosx \
+// RUN: %t/input.h -o %t/output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- input.h
+@protocol Protocol
+@end
+
+@interface Super 
+@property(readonly, getter=getProperty) unsigned Property;
++ (id)getWithProperty:(unsigned) Property;
+@end
+
+@interface Derived : Super {
+  char Ivar;
+}
+- (char)getIvar;
+@end
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationhips": [
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Super(cm)getWithProperty:",
+  "target": "c:objc(cs)Super"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Super(py)Property",
+  "target": "c:objc(cs)Super"
+},
+{
+  "kind": "conformsTo",
+  "source": "c:objc(cs)Super",
+  "target": "c:objc(pl)Protocol"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Derived@Ivar",
+  "target": "c:objc(cs)Derived"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Derived(im)getIvar",
+  "target": "c:objc(cs)Derived"
+},
+{
+  "kind": "inheritsFrom",
+  "source": "c:objc(cs)Derived",
+  "target": "c:objc(cs)Super"
+}
+  ],
+  "symbols": [
+{
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "@interface"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Super"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(cs)Super"
+  },
+  "kind": {
+"displayName": "Class",
+"identifier": "objective-c.class"
+  },
+  "location": {
+"character": 12,
+"line": 4,
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "Super"
+  }
+],
+"title": "Super"
+  }
+},
+{
+  "declarationFragments": [
+{
+  "kind": "text",
+  "spelling": "+ ("
+},
+{
+  "kind": "keyword",
+  "spelling": "id"
+},
+{
+  "kind": "text",
+  "spelling": ")"
+},
+{
+  "kind": "identifier",
+  "spelling": "getWithProperty"
+},
+{
+  "kind": "text",
+  "spelling": ":"
+},
+{
+  "kind": "text",
+  "spelling": "("
+},
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:i",
+  "spelling": "unsigned int"
+},
+{
+  "kind": "text",
+  "spelling": ")"
+},
+{
+  "kind": "internalParam",
+  "spelling": "Property"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(cs)Super(cm)getWithProperty:"
+  },
+  "kind": {
+"displayName": "Type Method",
+"identifier": "objective-c.type.method"
+  },
+  "location": {
+"character": 1,
+"line": 6,
+"uri": "file://INPUT_DIR/input.h"
+  },
+  

[PATCH] D120949: [clang][AST matchers] adding attributedStmt AST matcher

2022-03-25 Thread Alister Johnson via Phabricator via cfe-commits
ajohnson-uoregon updated this revision to Diff 418341.
ajohnson-uoregon added a comment.

updating commit message of last commit to be more accurate


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120949/new/

https://reviews.llvm.org/D120949

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/AST/DeclBase.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -184,9 +184,9 @@
 
 TEST(ASTMatchersTestCUDA, HasAttrCUDA) {
   EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
-  hasAttr(clang::attr::CUDADevice)));
+  decl(hasAttr(clang::attr::CUDADevice;
   EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
-  hasAttr(clang::attr::CUDAGlobal)));
+  decl(hasAttr(clang::attr::CUDAGlobal;
 }
 
 TEST_P(ASTMatchersTest, ValueDecl) {
@@ -2509,6 +2509,37 @@
   EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
 }
 
+TEST(ASTMatchersTest, AttributedStmtBasic) {
+  StringRef Code = "int foo() { [[likely]] return 1; }";
+  EXPECT_TRUE(
+  matchesConditionally(Code, attributedStmt(), true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_hasAttr) {
+  StringRef Code = "int foo() { [[unlikely]] return 1; }";
+  EXPECT_TRUE(matchesConditionally(
+  Code, attributedStmt(hasAttr(attr::Unlikely)), true, {"-std=c++20"}));
+  EXPECT_FALSE(matchesConditionally(
+  Code, attributedStmt(hasAttr(attr::Builtin)), true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_hasSubStmt) {
+  StringRef Code = "int foo() { [[likely]] return 1; }";
+  EXPECT_TRUE(matchesConditionally(
+  Code, attributedStmt(hasSubStmt(returnStmt())), true, {"-std=c++20"}));
+  EXPECT_FALSE(matchesConditionally(Code, attributedStmt(hasSubStmt(ifStmt())),
+true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_multipleAttrs) {
+  StringRef Code = "int foo();\n int main() {\n  [[clang::nomerge]] [[likely]] "
+   "return foo();\n }";
+  EXPECT_TRUE(matchesConditionally(Code, attributedStmt(hasAttr(attr::Likely)),
+   true, {"-std=c++20"}));
+  EXPECT_TRUE(matchesConditionally(Code, attributedStmt(hasAttr(attr::NoMerge)),
+   true, {"-std=c++20"}));
+}
+
 TEST(MatchFinderAPI, MatchesDynamic) {
   StringRef SourceCode = "struct A { void f() {} };";
   auto Matcher = functionDecl(isDefinition()).bind("method");
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -142,6 +142,7 @@
   REGISTER_MATCHER(atomicExpr);
   REGISTER_MATCHER(atomicType);
   REGISTER_MATCHER(attr);
+  REGISTER_MATCHER(attributedStmt);
   REGISTER_MATCHER(autoType);
   REGISTER_MATCHER(autoreleasePoolStmt)
   REGISTER_MATCHER(binaryConditionalOperator);
@@ -355,6 +356,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubStmt);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -981,6 +981,8 @@
 predefinedExpr;
 const internal::VariadicDynCastAllOfMatcher
 designatedInitExpr;
+const internal::VariadicDynCastAllOfMatcher
+attributedStmt;
 const internal::VariadicOperatorMatcherFunc<
 2, std::numeric_limits::max()>
 eachOf = {internal::DynTypedMatcher::VO_EachOf};
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -906,7 +906,6 @@
 }
 
 const AttrVec ::getAttrs() const {
-  assert(HasAttrs && "No attrs to get!");
   return getASTContext().getDeclAttrs(this);
 }
 
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2699,6 +2699,40 @@
   return Node.size() == N;
 }
 
+/// Matches the attribute(s) attached to a Stmt
+///
+/// Given:
+/// \code
+///   constexpr double 

[PATCH] D120949: [clang][AST matchers] adding attributedStmt AST matcher

2022-03-25 Thread Alister Johnson via Phabricator via cfe-commits
ajohnson-uoregon updated this revision to Diff 418338.
ajohnson-uoregon added a comment.

I overloaded hasAttr and had to fix a couple CUDA tests to explicitly use the 
decl overload (the other tests 
for hasAttr did this already, so I think it was just a mistake in those tests).

I also had to remove an assert from Decl::getAttrs in DeclBase.cpp that checked 
if there were actually attributes 
on that decl to make the overload work (when I wrote the overload, I made both 
use getAttrs because AttributedStmts 
don't have attrs() like Decls do). After trawling git blame a bit, it looks 
like that assert was added way 
back in like 2010 when ASTContext::getDeclAttrs just did a straight lookup in 
the DeclAttrs map, which 
presumably would have done bad things if the decl had no attrs. In this commit 
though 
https://github.com/llvm/llvm-project/commit/561eceb4c4a20280d5324c873ddad1940960b891
 that got fixed, so 
getDeclAttrs will return a new empty AttrVec if the lookup fails. The assert is 
not necessary since that commit, 
but I guess no one realized they could remove the assert.

tl;dr That assert broke lots of the old hasAttr tests for Decls that were now 
using getAttrs() instead of attrs(), 
and removing it fixes them, and since it's no longer needed I think it's okay 
to get rid of it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120949/new/

https://reviews.llvm.org/D120949

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/AST/DeclBase.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -184,9 +184,9 @@
 
 TEST(ASTMatchersTestCUDA, HasAttrCUDA) {
   EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
-  hasAttr(clang::attr::CUDADevice)));
+  decl(hasAttr(clang::attr::CUDADevice;
   EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
-  hasAttr(clang::attr::CUDAGlobal)));
+  decl(hasAttr(clang::attr::CUDAGlobal;
 }
 
 TEST_P(ASTMatchersTest, ValueDecl) {
@@ -2509,6 +2509,37 @@
   EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
 }
 
+TEST(ASTMatchersTest, AttributedStmtBasic) {
+  StringRef Code = "int foo() { [[likely]] return 1; }";
+  EXPECT_TRUE(
+  matchesConditionally(Code, attributedStmt(), true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_hasAttr) {
+  StringRef Code = "int foo() { [[unlikely]] return 1; }";
+  EXPECT_TRUE(matchesConditionally(
+  Code, attributedStmt(hasAttr(attr::Unlikely)), true, {"-std=c++20"}));
+  EXPECT_FALSE(matchesConditionally(
+  Code, attributedStmt(hasAttr(attr::Builtin)), true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_hasSubStmt) {
+  StringRef Code = "int foo() { [[likely]] return 1; }";
+  EXPECT_TRUE(matchesConditionally(
+  Code, attributedStmt(hasSubStmt(returnStmt())), true, {"-std=c++20"}));
+  EXPECT_FALSE(matchesConditionally(Code, attributedStmt(hasSubStmt(ifStmt())),
+true, {"-std=c++20"}));
+}
+
+TEST(ASTMatchersTest, AttributedStmt_multipleAttrs) {
+  StringRef Code = "int foo();\n int main() {\n  [[clang::nomerge]] [[likely]] "
+   "return foo();\n }";
+  EXPECT_TRUE(matchesConditionally(Code, attributedStmt(hasAttr(attr::Likely)),
+   true, {"-std=c++20"}));
+  EXPECT_TRUE(matchesConditionally(Code, attributedStmt(hasAttr(attr::NoMerge)),
+   true, {"-std=c++20"}));
+}
+
 TEST(MatchFinderAPI, MatchesDynamic) {
   StringRef SourceCode = "struct A { void f() {} };";
   auto Matcher = functionDecl(isDefinition()).bind("method");
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -142,6 +142,7 @@
   REGISTER_MATCHER(atomicExpr);
   REGISTER_MATCHER(atomicType);
   REGISTER_MATCHER(attr);
+  REGISTER_MATCHER(attributedStmt);
   REGISTER_MATCHER(autoType);
   REGISTER_MATCHER(autoreleasePoolStmt)
   REGISTER_MATCHER(binaryConditionalOperator);
@@ -355,6 +356,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubStmt);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp

[PATCH] D122508: [clang][NFC] Remove unused parameter in `Sema::ActOnDuplicateDefinition`.

2022-03-25 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122508

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaDecl.cpp


Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16698,8 +16698,7 @@
   AddPushedVisibilityAttribute(Tag);
 }
 
-bool Sema::ActOnDuplicateDefinition(DeclSpec , Decl *Prev,
-SkipBodyInfo ) {
+bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo ) {
   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
 return false;
 
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -2049,8 +2049,7 @@
   // Parse the definition body.
   ParseStructUnionBody(StartLoc, TagType, cast(D));
   if (SkipBody.CheckSameAsPrevious &&
-  !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
-SkipBody)) {
+  !Actions.ActOnDuplicateDefinition(TagOrTempResult.get(), SkipBody)) {
 DS.SetTypeSpecError();
 return;
   }
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -4870,7 +4870,7 @@
 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
 ParseEnumBody(StartLoc, D);
 if (SkipBody.CheckSameAsPrevious &&
-!Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
+!Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
   DS.SetTypeSpecError();
   return;
 }
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -3254,8 +3254,7 @@
   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
   /// Differently from C++, actually parse the body and reject / error out
   /// in case of a structural mismatch.
-  bool ActOnDuplicateDefinition(DeclSpec , Decl *Prev,
-SkipBodyInfo );
+  bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo );
 
   typedef void *SkippedDefinitionContext;
 


Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16698,8 +16698,7 @@
   AddPushedVisibilityAttribute(Tag);
 }
 
-bool Sema::ActOnDuplicateDefinition(DeclSpec , Decl *Prev,
-SkipBodyInfo ) {
+bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo ) {
   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
 return false;
 
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -2049,8 +2049,7 @@
   // Parse the definition body.
   ParseStructUnionBody(StartLoc, TagType, cast(D));
   if (SkipBody.CheckSameAsPrevious &&
-  !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
-SkipBody)) {
+  !Actions.ActOnDuplicateDefinition(TagOrTempResult.get(), SkipBody)) {
 DS.SetTypeSpecError();
 return;
   }
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -4870,7 +4870,7 @@
 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
 ParseEnumBody(StartLoc, D);
 if (SkipBody.CheckSameAsPrevious &&
-!Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
+!Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
   DS.SetTypeSpecError();
   return;
 }
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -3254,8 +3254,7 @@
   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
   /// Differently from C++, actually parse the body and reject / error out
   /// in case of a structural mismatch.
-  bool ActOnDuplicateDefinition(DeclSpec , Decl *Prev,
-SkipBodyInfo );
+  bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo );
 
   typedef void *SkippedDefinitionContext;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] afaefb6 - [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for LLVM_ENABLE_RUNTIMES builds

2022-03-25 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-03-25T14:56:18-07:00
New Revision: afaefb671fe12e7788d3e8de6b6193b935fbf16c

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

LOG: [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for 
LLVM_ENABLE_RUNTIMES builds

The rule was added in 2014 to support -stdlib=libc++ and -lc++ without
specifying -L, when D.Dir is not a well-known system library directory like
/usr/lib /usr/lib64. This rule turns out to get in the way with (-m32 for
64-bit clang) or (-m64 for 32-bit clang) for Gentoo :
https://github.com/llvm/llvm-project/issues/54515

Nowadays LLVM_ENABLE_RUNTIMES is the only recommended way building libc++ and
LLVM_ENABLE_PROJECTS=libc++ is deprecated. LLVM_ENABLE_RUNTIMES builds libc++
in D.Dir+"/../lib/${triple}/". The rule is unneeded. Also reverts D108286.

Gentoo uses a modified LLVM_ENABLE_RUNTIMES that installs libc++.so in
well-known paths like /usr/lib64 and /usr/lib which are already covered by
nearby search paths.

Implication: if a downstream package needs something like -lLLVM-15git and uses
libLLVM-15git.so not in a well-known path, it needs to supply -L
D.Dir+"/../lib" explicitly (e.g. via LLVMConfig.cmake), instead of relying on
the previous default search path.

Reviewed By: mgorny

Differential Revision: https://reviews.llvm.org/D122444

Added: 


Modified: 
clang/lib/Driver/ToolChains/Linux.cpp
clang/test/Driver/linux-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Linux.cpp 
b/clang/lib/Driver/ToolChains/Linux.cpp
index c5393b6f42d3f..d647246f05349 100644
--- a/clang/lib/Driver/ToolChains/Linux.cpp
+++ b/clang/lib/Driver/ToolChains/Linux.cpp
@@ -309,18 +309,12 @@ Linux::Linux(const Driver , const llvm::Triple , 
const ArgList )
 
   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
 
-  // Similar to the logic for GCC above, if we are currently running Clang
-  // inside of the requested system root, add its parent library path to those
-  // searched.
-  // FIXME: It's not clear whether we should use the driver's installed
-  // directory ('Dir' below) or the ResourceDir.
-  if (StringRef(D.Dir).startswith(SysRoot)) {
-// Even if OSLibDir != "lib", this is needed for Clang in the build
-// directory (not installed) to find libc++.
+  // The deprecated -DLLVM_ENABLE_PROJECTS=libcxx configuration installs
+  // libc++.so in D.Dir+"/../lib/". Detect this path.
+  // TODO Remove once LLVM_ENABLE_PROJECTS=libcxx is unsupported.
+  if (StringRef(D.Dir).startswith(SysRoot) &&
+  D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
 addPathIfExists(D, D.Dir + "/../lib", Paths);
-if (OSLibDir != "lib")
-  addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
-  }
 
   if (!D.OverlayToolChainPath.empty()) {
 addPathIfExists(D, ExtraPath + "/lib", Paths);

diff  --git a/clang/test/Driver/linux-ld.c b/clang/test/Driver/linux-ld.c
index 4c40eb3583a06..ef3751d6649db 100644
--- a/clang/test/Driver/linux-ld.c
+++ b/clang/test/Driver/linux-ld.c
@@ -530,7 +530,6 @@
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" 
"[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-INSTALL: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-INSTALL: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Test that we can use -stdlib=libc++ in a build system even when it
 // occasionally links C code instead of C++ code.
@@ -547,7 +546,6 @@
 // CHECK-BASIC-LIBCXX-C-LINK-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-C-LINK: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-C-LINK: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-C-LINK: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Check multi arch support on Ubuntu 12.04 LTS.
 // RUN: %clang -no-canonical-prefixes %s -no-pie -### -o %t.o 2>&1 \



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


[PATCH] D122444: [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for LLVM_ENABLE_RUNTIMES builds

2022-03-25 Thread Fangrui Song via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
MaskRay marked an inline comment as done.
Closed by commit rGafaefb671fe1: [Driver][Linux] Remove 
D.Dir+/../lib from default search paths for… (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122444/new/

https://reviews.llvm.org/D122444

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/linux-ld.c


Index: clang/test/Driver/linux-ld.c
===
--- clang/test/Driver/linux-ld.c
+++ clang/test/Driver/linux-ld.c
@@ -530,7 +530,6 @@
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" 
"[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-INSTALL: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-INSTALL: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Test that we can use -stdlib=libc++ in a build system even when it
 // occasionally links C code instead of C++ code.
@@ -547,7 +546,6 @@
 // CHECK-BASIC-LIBCXX-C-LINK-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-C-LINK: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-C-LINK: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-C-LINK: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Check multi arch support on Ubuntu 12.04 LTS.
 // RUN: %clang -no-canonical-prefixes %s -no-pie -### -o %t.o 2>&1 \
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -309,18 +309,12 @@
 
   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
 
-  // Similar to the logic for GCC above, if we are currently running Clang
-  // inside of the requested system root, add its parent library path to those
-  // searched.
-  // FIXME: It's not clear whether we should use the driver's installed
-  // directory ('Dir' below) or the ResourceDir.
-  if (StringRef(D.Dir).startswith(SysRoot)) {
-// Even if OSLibDir != "lib", this is needed for Clang in the build
-// directory (not installed) to find libc++.
+  // The deprecated -DLLVM_ENABLE_PROJECTS=libcxx configuration installs
+  // libc++.so in D.Dir+"/../lib/". Detect this path.
+  // TODO Remove once LLVM_ENABLE_PROJECTS=libcxx is unsupported.
+  if (StringRef(D.Dir).startswith(SysRoot) &&
+  D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
 addPathIfExists(D, D.Dir + "/../lib", Paths);
-if (OSLibDir != "lib")
-  addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
-  }
 
   if (!D.OverlayToolChainPath.empty()) {
 addPathIfExists(D, ExtraPath + "/lib", Paths);


Index: clang/test/Driver/linux-ld.c
===
--- clang/test/Driver/linux-ld.c
+++ clang/test/Driver/linux-ld.c
@@ -530,7 +530,6 @@
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-INSTALL: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-INSTALL: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Test that we can use -stdlib=libc++ in a build system even when it
 // occasionally links C code instead of C++ code.
@@ -547,7 +546,6 @@
 // CHECK-BASIC-LIBCXX-C-LINK-NOT: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v1"
 // CHECK-BASIC-LIBCXX-C-LINK: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
 // CHECK-BASIC-LIBCXX-C-LINK: "--sysroot=[[SYSROOT]]"
-// CHECK-BASIC-LIBCXX-C-LINK: "-L[[SYSROOT]]/usr/bin/../lib"
 //
 // Check multi arch support on Ubuntu 12.04 LTS.
 // RUN: %clang -no-canonical-prefixes %s -no-pie -### -o %t.o 2>&1 \
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -309,18 +309,12 @@
 
   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
 
-  // Similar to the logic for GCC above, if we are currently running Clang
-  // inside of the requested system root, add its parent library path to those
-  // searched.
-  // FIXME: It's not clear whether we should use the driver's installed
-  // directory ('Dir' below) or the ResourceDir.
-  if (StringRef(D.Dir).startswith(SysRoot)) {
-// Even if OSLibDir != "lib", this is needed for Clang in the build
-// directory (not installed) to find libc++.
+  // The deprecated -DLLVM_ENABLE_PROJECTS=libcxx configuration installs
+  // libc++.so in D.Dir+"/../lib/". Detect this path.
+  // TODO Remove once LLVM_ENABLE_PROJECTS=libcxx is unsupported.
+  if (StringRef(D.Dir).startswith(SysRoot) &&
+  D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
 addPathIfExists(D, D.Dir + "/../lib", Paths);
-if (OSLibDir != "lib")
-  

[PATCH] D115907: [misexpect] Re-implement MisExpect Diagnostics

2022-03-25 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 418328.
paulkirth added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115907/new/

https://reviews.llvm.org/D115907

Files:
  clang/docs/MisExpect.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Profile/Inputs/misexpect-branch-nonconst-expect-arg.proftext
  clang/test/Profile/Inputs/misexpect-branch.proftext
  clang/test/Profile/Inputs/misexpect-switch-default-only.proftext
  clang/test/Profile/Inputs/misexpect-switch-default.proftext
  clang/test/Profile/Inputs/misexpect-switch-nonconst.proftext
  clang/test/Profile/Inputs/misexpect-switch.proftext
  clang/test/Profile/misexpect-branch-cold.c
  clang/test/Profile/misexpect-branch-nonconst-expected-val.c
  clang/test/Profile/misexpect-branch-unpredictable.c
  clang/test/Profile/misexpect-branch.c
  clang/test/Profile/misexpect-switch-default.c
  clang/test/Profile/misexpect-switch-nonconst.c
  clang/test/Profile/misexpect-switch-only-default-case.c
  clang/test/Profile/misexpect-switch.c
  llvm/docs/MisExpect.rst
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/include/llvm/IR/LLVMContext.h
  llvm/include/llvm/Target/TargetOptions.h
  llvm/include/llvm/Transforms/Utils/MisExpect.h
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/lib/IR/LLVMContext.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/Transforms/IPO/SampleProfile.cpp
  llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp
  llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
  llvm/lib/Transforms/Utils/CMakeLists.txt
  llvm/lib/Transforms/Utils/MisExpect.cpp
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch-correct.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch-threshold.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-switch-correct.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-switch.proftext
  llvm/test/Transforms/PGOProfile/misexpect-branch-correct.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch-stripped.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch-unpredictable.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch.ll
  llvm/test/Transforms/PGOProfile/misexpect-switch-default.ll
  llvm/test/Transforms/PGOProfile/misexpect-switch.ll

Index: llvm/test/Transforms/PGOProfile/misexpect-switch.ll
===
--- /dev/null
+++ llvm/test/Transforms/PGOProfile/misexpect-switch.ll
@@ -0,0 +1,285 @@
+; Test misexpect diagnostics handle swich statements, and report source locations correctly
+
+; RUN: llvm-profdata merge %S/Inputs/misexpect-switch.proftext -o %t.profdata
+; RUN: llvm-profdata merge %S/Inputs/misexpect-switch-correct.proftext -o %t.c.profdata
+
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pgo-warn-misexpect -S 2>&1 | FileCheck %s --check-prefix=WARNING
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=REMARK
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pgo-warn-misexpect -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=BOTH
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -S 2>&1 | FileCheck %s --check-prefix=DISABLED
+
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.c.profdata -pgo-warn-misexpect -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=CORRECT
+
+; WARNING-DAG: warning: misexpect-switch.c:26:30: 0.00%
+; WARNING-NOT: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+
+; REMARK-NOT: warning: misexpect-switch.c:26:30: 0.00%
+; REMARK-DAG: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+
+; BOTH-DAG: warning: misexpect-switch.c:26:30: 0.00%
+; BOTH-DAG: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+
+; DISABLED-NOT: warning: misexpect-switch.c:26:30: 0.00%
+; DISABLED-NOT: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was 

[PATCH] D122504: [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D122504#3408947 , @JonChesterfield 
wrote:

> Nice, thanks. Wonder if we want protected visibility as well.

I'm not actually sure what having protected visibility would do considering 
it's not applied with `-fvisibility=protected` like we pass currently.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122504/new/

https://reviews.llvm.org/D122504

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


[PATCH] D122504: [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield accepted this revision.
JonChesterfield added a comment.
This revision is now accepted and ready to land.

Nice, thanks. Wonder if we want protected visibility as well.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122504/new/

https://reviews.llvm.org/D122504

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


[PATCH] D122504: [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418321.
jhuber6 added a comment.
Herald added a subscriber: jvesely.

Changing approach, we should optionally use internal linkage for the ctor
creation function since it's not correct to add the internal linkage attributes
and then make it external. Also remove it from the used global since it's not
needed anymore.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122504/new/

https://reviews.llvm.org/D122504

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  clang/test/OpenMP/declare_target_codegen.cpp
  clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp

Index: clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
===
--- clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
+++ clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
@@ -44,7 +44,7 @@
 static int c = foo() + bar() + baz();
 #pragma omp declare target (c)
 // HOST-DAG: @[[C_CTOR:__omp_offloading__.+_c_l44_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
+// DEVICE-DAG: define weak_odr void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
 // DEVICE-DAG: call noundef i32 [[FOO]]()
 // DEVICE-DAG: call noundef i32 [[BAR]]()
 // DEVICE-DAG: call noundef i32 [[BAZ]]()
@@ -61,14 +61,14 @@
 S cd = doo() + car() + caz() + baz();
 #pragma omp end declare target
 // HOST-DAG: @[[CD_CTOR:__omp_offloading__.+_cd_l61_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
+// DEVICE-DAG: define weak_odr void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
 // DEVICE-DAG: call noundef i32 [[DOO]]()
 // DEVICE-DAG: call noundef i32 [[CAR]]()
 // DEVICE-DAG: call noundef i32 [[CAZ]]()
 // DEVICE-DAG: ret void
 
 // HOST-DAG: @[[CD_DTOR:__omp_offloading__.+_cd_l61_dtor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
+// DEVICE-DAG: define weak_odr void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
 // DEVICE-DAG: call void
 // DEVICE-DAG: ret void
 
Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -46,7 +46,6 @@
 // CHECK-DAG: [[STAT:@.+stat]] = internal global %struct.S zeroinitializer,
 // CHECK-DAG: [[STAT_REF:@.+]] = internal constant %struct.S* [[STAT]]
 // CHECK-DAG: @out_decl_target ={{ protected | }}global i32 0,
-// CHECK-DAG: @llvm.used = appending global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading__{{.+}}_globals_l[[@LINE+84]]_ctor to i8*), i8* bitcast (void ()* @__omp_offloading__{{.+}}_stat_l[[@LINE+85]]_ctor to i8*)],
 // CHECK-DAG: @llvm.compiler.used = appending global [1 x i8*] [i8* bitcast (%struct.S** [[STAT_REF]] to i8*)],
 
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
Index: clang/test/OpenMP/amdgcn_target_global_constructor.cpp
===
--- clang/test/OpenMP/amdgcn_target_global_constructor.cpp
+++ clang/test/OpenMP/amdgcn_target_global_constructor.cpp
@@ -26,9 +26,8 @@
 // CHECK: @__omp_rtl_assume_threads_oversubscription = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @__omp_rtl_assume_no_thread_state = weak_odr hidden addrspace(1) constant i32 0
 // CHECK: @A = addrspace(1) global %struct.S zeroinitializer, align 4
-// CHECK: @llvm.used = appending addrspace(1) global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading_{{.*}}_ctor to i8*), i8* bitcast (void ()* @__omp_offloading_{{.*}}_dtor to i8*)], section "llvm.metadata"
 //.
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading_{{.*}}_ctor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_ctor
 // CHECK-SAME: () #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SC1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR3:[0-9]+]]
@@ -46,7 +45,7 @@
 // CHECK-NEXT:ret void
 //
 //
-// CHECK-LABEL: define {{[^@]+}}@__omp_offloading_{{.*}}_dtor
+// CHECK-LABEL: define {{[^@]+}}@__omp_offloading__fd02_613a0d56_A_l19_dtor
 // CHECK-SAME: () #[[ATTR0]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:call void @_ZN1SD1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) addrspacecast ([[STRUCT_S:%.*]] addrspace(1)* @A to %struct.S*)) #[[ATTR4:[0-9]+]]
@@ -87,19 +86,19 @@
 // CHECK-NEXT:ret void
 //
 //.
-// CHECK: attributes #0 = { convergent
-// CHECK: attributes #1 = { convergent
-// CHECK: attributes #2 = { convergent
-// CHECK: attributes #3 = { convergent
-// CHECK: attributes 

[clang] bb9bdef - [Clang] Use pattern to match profile metadata in test.

2022-03-25 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2022-03-25T21:05:58Z
New Revision: bb9bdef4df8a9db4f9ff4ed340cf59948f2145c7

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

LOG: [Clang] Use pattern to match profile metadata in test.

Make the test more robust to slightly different metadata numbering by
using a pattern instead of hard coding the ids.

Added: 


Modified: 
clang/test/CodeGenCXX/attr-likelihood-if-vs-builtin-expect.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/attr-likelihood-if-vs-builtin-expect.cpp 
b/clang/test/CodeGenCXX/attr-likelihood-if-vs-builtin-expect.cpp
index b20537bd784a3..eeb6a8b672965 100644
--- a/clang/test/CodeGenCXX/attr-likelihood-if-vs-builtin-expect.cpp
+++ b/clang/test/CodeGenCXX/attr-likelihood-if-vs-builtin-expect.cpp
@@ -9,9 +9,9 @@ extern bool c();
 
 void ab1(int ) {
   // CHECK-LABEL: define{{.*}}ab1
-  // CHECK: br {{.*}} !prof !6
-  // CHECK: br {{.*}} !prof !6
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY:!.+]]
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (__builtin_expect(a() && b() && a(), 1)) {
 ++i;
   } else {
@@ -21,9 +21,9 @@ void ab1(int ) {
 
 void al(int ) {
   // CHECK-LABEL: define{{.*}}al
-  // CHECK: br {{.*}} !prof !6
-  // CHECK: br {{.*}} !prof !6
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (a() && b() && c()) [[likely]] {
 ++i;
   } else {
@@ -36,7 +36,7 @@ void ab0(int ) {
   // CHECK: br {{.*}}end{{$}}
   // CHECK: br {{.*}}end{{$}}
   // CHECK: br {{.*}}end{{$}}
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY:!.+]]
   if (__builtin_expect(a() && b() && c(), 0)) {
 ++i;
   } else {
@@ -48,7 +48,7 @@ void au(int ) {
   // CHECK-LABEL: define{{.*}}au
   // CHECK: br {{.*}}else{{$}}
   // CHECK: br {{.*}}else{{$}}
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
   if (a() && b() && c()) [[unlikely]] {
 ++i;
   } else {
@@ -61,7 +61,7 @@ void ob1(int ) {
   // CHECK: br {{.*}}false{{$}}
   // CHECK: br {{.*}}rhs{{$}}
   // CHECK: br {{.*}}end{{$}}
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (__builtin_expect(a() || b() || a(), 1)) {
 i = 0;
   } else {
@@ -73,7 +73,7 @@ void ol(int ) {
   // CHECK-LABEL: define{{.*}}ol
   // CHECK: br {{.*}}false{{$}}
   // CHECK: br {{.*}}false2{{$}}
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (a() || b() || c()) [[likely]] {
 i = 0;
   } else {
@@ -83,9 +83,9 @@ void ol(int ) {
 
 void ob0(int ) {
   // CHECK-LABEL: define{{.*}}ob0
-  // CHECK: br {{.*}} !prof !9
-  // CHECK: br {{.*}} !prof !9
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
   if (__builtin_expect(a() || b() || c(), 0)) {
 i = 0;
   } else {
@@ -95,9 +95,9 @@ void ob0(int ) {
 
 void ou(int ) {
   // CHECK-LABEL: define{{.*}}ou
-  // CHECK: br {{.*}} !prof !9
-  // CHECK: br {{.*}} !prof !9
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
   if (a() || b() || c()) [[unlikely]] {
 i = 0;
   } else {
@@ -107,7 +107,7 @@ void ou(int ) {
 
 void nb1(int ) {
   // CHECK-LABEL: define{{.*}}nb1
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (__builtin_expect(!a(), 1)) {
 ++i;
   } else {
@@ -117,7 +117,7 @@ void nb1(int ) {
 
 void nl(int ) {
   // CHECK-LABEL: define{{.*}}nl
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (bool d = !a()) [[likely]] {
 ++i;
   } else {
@@ -127,7 +127,7 @@ void nl(int ) {
 
 void nb0(int ) {
   // CHECK-LABEL: define{{.*}}nb0
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
   if (__builtin_expect(!a(), 0)) {
 ++i;
   } else {
@@ -137,7 +137,7 @@ void nb0(int ) {
 
 void nu(int ) {
   // CHECK-LABEL: define{{.*}}nu
-  // CHECK: br {{.*}} !prof !9
+  // CHECK: br {{.*}} !prof [[BW_UNLIKELY]]
   if (bool d = !a()) [[unlikely]] {
 ++i;
   } else {
@@ -150,7 +150,7 @@ void tb1(int ) {
   // CHECK: br {{.*}}false{{$}}
   // CHECK: br {{.*}}end{{$}}
   // CHECK: br {{.*}}end{{$}}
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof [[BW_LIKELY]]
   if (__builtin_expect(a() ? b() : c(), 1)) {
 ++i;
   } else {
@@ -163,7 +163,7 @@ void tl(int ) {
   // CHECK: br {{.*}}false{{$}}
   // CHECK: br {{.*}}end{{$}}
   // CHECK: br {{.*}}end{{$}}
-  // CHECK: br {{.*}} !prof !6
+  // CHECK: br {{.*}} !prof 

[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:279
+ cast_or_null(Env.getValue(*ComparisonExprLoc))) {
+Env.setValue(*ComparisonExprLoc,
+ Env.makeAnd(*CurrentValue, ComparisonValue));

xazax.hun wrote:
> I am still wondering a bit about this case. 
> 
> We generate: `HasValueVal and ContentsNotEqX and CurrentValue`.'
> I wonder if we want: `HasValueVal  and (ContentsNotEqX  <=> CurrentValue)` 
> instead?  Or even `HasValueVal  and CurrentValue`?
I don't think that the iff version is right, but `HasValueVal  and 
CurrentValue` could be. My concern is that we're not guaranteed that 
`CurrentValue` is populated. And, even if we were, it doesn't feel quite right. 
Assuming its a high fidelity model, we get (logically): `HasValue(opt) and 
Ne(ValueOr(opt,X),X)`. Then, when negated (say, on an else branch) we get 
`not(HasValue(opt)) or not(Ne(ValueOr(opt,X),X))` which is equivalent to 
`not(HasValue(opt)) or Eq(ValueOr(opt,X),X)`. While  true, it seems redundant, 
since the first clause should be derivable from the second (assuming an 
interpretatable semantics to the `ValueOr` predicate).

Regardless, it might be better to step back and figure out how this should be 
done systematically. I'll try to come back with a proposal on that.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122497: [clang][tests][NFC] Add filescope array initialization test

2022-03-25 Thread Aaron H Liu via Phabricator via cfe-commits
AaronLiu accepted this revision.
AaronLiu added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122497/new/

https://reviews.llvm.org/D122497

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


[PATCH] D122504: [OpenMP] Make Ctor / Dtor functions have external visibility

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, JonChesterfield, ronlieb, ABataev.
Herald added subscribers: asavonic, guansong, tpr, yaxunl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

The default construction of constructor functions by LLVM tends to make
them have internal linkage. When we call a ctor / dtor function in the
target region we are actually creating a kernel that is called at
registration. Because the ctor is a kernel we need to make sure it's
externally visible so we can actually call it. This prevented AMDGPU
from correctly using constructors while NVPTX could use them simply
because it ignored internal visibility.

Fixes #54091


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122504

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp


Index: clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
===
--- clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
+++ clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
@@ -44,7 +44,7 @@
 static int c = foo() + bar() + baz();
 #pragma omp declare target (c)
 // HOST-DAG: @[[C_CTOR:__omp_offloading__.+_c_l44_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void 
[[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
+// DEVICE-DAG: define weak_odr dso_local void 
[[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
 // DEVICE-DAG: call noundef i32 [[FOO]]()
 // DEVICE-DAG: call noundef i32 [[BAR]]()
 // DEVICE-DAG: call noundef i32 [[BAZ]]()
@@ -61,14 +61,14 @@
 S cd = doo() + car() + caz() + baz();
 #pragma omp end declare target
 // HOST-DAG: @[[CD_CTOR:__omp_offloading__.+_cd_l61_ctor]] = private constant 
i8 0
-// DEVICE-DAG: define internal void 
[[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
+// DEVICE-DAG: define weak_odr dso_local void 
[[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
 // DEVICE-DAG: call noundef i32 [[DOO]]()
 // DEVICE-DAG: call noundef i32 [[CAR]]()
 // DEVICE-DAG: call noundef i32 [[CAZ]]()
 // DEVICE-DAG: ret void
 
 // HOST-DAG: @[[CD_DTOR:__omp_offloading__.+_cd_l61_dtor]] = private constant 
i8 0
-// DEVICE-DAG: define internal void 
[[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
+// DEVICE-DAG: define weak_odr dso_local void 
[[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
 // DEVICE-DAG: call void
 // DEVICE-DAG: ret void
 
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -3022,6 +3022,13 @@
 // This could happen if the device compilation is invoked standalone.
 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum))
   return;
+
+// If we are registering a ctor / dtor we need to make sure it's externally
+// visible so we can call it from the host.
+if (Flags == OMPTargetRegionEntryCtor || Flags == OMPTargetRegionEntryDtor)
+  if (llvm::GlobalValue *GV = dyn_cast(Addr))
+GV->setLinkage(llvm::GlobalValue::WeakODRLinkage);
+
 auto  =
 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
 Entry.setAddress(Addr);


Index: clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
===
--- clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
+++ clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
@@ -44,7 +44,7 @@
 static int c = foo() + bar() + baz();
 #pragma omp declare target (c)
 // HOST-DAG: @[[C_CTOR:__omp_offloading__.+_c_l44_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
+// DEVICE-DAG: define weak_odr dso_local void [[C_CTOR:@__omp_offloading__.+_c_l44_ctor]]()
 // DEVICE-DAG: call noundef i32 [[FOO]]()
 // DEVICE-DAG: call noundef i32 [[BAR]]()
 // DEVICE-DAG: call noundef i32 [[BAZ]]()
@@ -61,14 +61,14 @@
 S cd = doo() + car() + caz() + baz();
 #pragma omp end declare target
 // HOST-DAG: @[[CD_CTOR:__omp_offloading__.+_cd_l61_ctor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
+// DEVICE-DAG: define weak_odr dso_local void [[CD_CTOR:@__omp_offloading__.+_cd_l61_ctor]]()
 // DEVICE-DAG: call noundef i32 [[DOO]]()
 // DEVICE-DAG: call noundef i32 [[CAR]]()
 // DEVICE-DAG: call noundef i32 [[CAZ]]()
 // DEVICE-DAG: ret void
 
 // HOST-DAG: @[[CD_DTOR:__omp_offloading__.+_cd_l61_dtor]] = private constant i8 0
-// DEVICE-DAG: define internal void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
+// DEVICE-DAG: define weak_odr dso_local void [[CD_DTOR:@__omp_offloading__.+_cd_l61_dtor]]()
 // DEVICE-DAG: call void
 // DEVICE-DAG: ret void
 
Index: 

[PATCH] D122499: [libTooling] Support TransformerResult in consumer callbacks

2022-03-25 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua marked 2 inline comments as done.
li.zhe.hua added inline comments.



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:126-128
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith &) {}

ymandel wrote:
> Why won't a simple specialization work?
Yup, totally. Done.

I guess I see SFINAE so much more often these days I just reach for it first.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122499/new/

https://reviews.llvm.org/D122499

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


[PATCH] D122499: [libTooling] Support TransformerResult in consumer callbacks

2022-03-25 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 418316.
li.zhe.hua added a comment.

Fix for comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122499/new/

https://reviews.llvm.org/D122499

Files:
  clang/include/clang/Tooling/Transformer/Transformer.h
  clang/lib/Tooling/Transformer/Transformer.cpp

Index: clang/lib/Tooling/Transformer/Transformer.cpp
===
--- clang/lib/Tooling/Transformer/Transformer.cpp
+++ clang/lib/Tooling/Transformer/Transformer.cpp
@@ -66,26 +66,6 @@
   return Changes;
 }
 
-void NoMetadataImpl::onMatchImpl(const MatchFinder::MatchResult ) {
-  size_t I = transformer::detail::findSelectedCase(Result, Rule);
-  auto Transformations = Rule.Cases[I].Edits(Result);
-  if (!Transformations) {
-Consumer(Transformations.takeError());
-return;
-  }
-
-  if (Transformations->empty())
-return;
-
-  auto Changes = convertToAtomicChanges(*Transformations, Result);
-  if (!Changes) {
-Consumer(Changes.takeError());
-return;
-  }
-
-  Consumer(llvm::MutableArrayRef(*Changes));
-}
-
 } // namespace detail
 
 void Transformer::registerMatchers(MatchFinder *MatchFinder) {
Index: clang/include/clang/Tooling/Transformer/Transformer.h
===
--- clang/include/clang/Tooling/Transformer/Transformer.h
+++ clang/include/clang/Tooling/Transformer/Transformer.h
@@ -21,7 +21,7 @@
 
 namespace detail {
 /// Implementation details of \c Transformer with type erasure around
-/// \c RewriteRule and \c RewriteRule as well as the corresponding consumers.
+/// \c RewriteRule as well as the corresponding consumers.
 class TransformerImpl {
 public:
   virtual ~TransformerImpl() = default;
@@ -43,33 +43,6 @@
   onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) = 0;
 };
 
-/// Implementation for when no metadata is generated as a part of the
-/// \c RewriteRule.
-class NoMetadataImpl final : public TransformerImpl {
-  transformer::RewriteRule Rule;
-  std::function>)> Consumer;
-
-public:
-  explicit NoMetadataImpl(
-  transformer::RewriteRule R,
-  std::function>)>
-  Consumer)
-  : Rule(std::move(R)), Consumer(std::move(Consumer)) {
-assert(llvm::all_of(Rule.Cases,
-[](const transformer::RewriteRule::Case ) {
-  return Case.Edits;
-}) &&
-   "edit generator must be provided for each rule");
-  }
-
-private:
-  void onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) final;
-  std::vector
-  buildMatchers() const final {
-return transformer::detail::buildMatchers(Rule);
-  }
-};
-
 // FIXME: Use std::type_identity or backport when available.
 template  struct type_identity {
   using type = T;
@@ -81,8 +54,6 @@
   T Metadata;
 };
 
-// Specialization provided only to avoid SFINAE on the Transformer
-// constructor; not intended for use.
 template <> struct TransformerResult {
   llvm::MutableArrayRef Changes;
 };
@@ -107,8 +78,14 @@
   /// other.
   explicit Transformer(transformer::RewriteRuleWith Rule,
ChangeSetConsumer Consumer)
-  : Impl(std::make_unique(std::move(Rule),
-  std::move(Consumer))) {}
+  : Transformer(std::move(Rule),
+[Consumer = std::move(Consumer)](
+llvm::Expected> Result) {
+  if (Result)
+Consumer(Result->Changes);
+  else
+Consumer(Result.takeError());
+}) {}
 
   /// \param Consumer receives all rewrites and the associated metadata for a
   /// single match, or an error. Will always be called for each match, even if
@@ -135,6 +112,44 @@
 };
 
 namespace detail {
+/// Asserts that all \c Metadata for the \c Rule is set.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+void assertMetadataSet(const transformer::RewriteRuleWith ) {
+  assert(llvm::all_of(Rule.Metadata,
+  [](const typename transformer::Generator )
+  -> bool { return !!Metadata; }) &&
+ "metadata generator must be provided for each rule");
+}
+template <>
+inline void assertMetadataSet(const transformer::RewriteRuleWith &) {}
+/// @}
+
+/// Runs the metadata generator on \c Rule and stuffs it into \c Result.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+llvm::Error
+populateMetadata(const transformer::RewriteRuleWith ,
+ size_t SelectedCase,
+ const ast_matchers::MatchFinder::MatchResult ,
+ TransformerResult ) {
+  auto Metadata = Rule.Metadata[SelectedCase]->eval(Match);
+  if (!Metadata)
+return Metadata.takeError();
+  Result.Metadata = std::move(*Metadata);
+  return llvm::Error::success();
+}
+template <>
+inline llvm::Error
+populateMetadata(const 

[PATCH] D122502: [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread William Moses via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG89525cbf283f: [Clang] Add helper method to determine if a 
nonvirtual base has an entry in the… (authored by wsmoses).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122502/new/

https://reviews.llvm.org/D122502

Files:
  clang/lib/CodeGen/CGRecordLayout.h


Index: clang/lib/CodeGen/CGRecordLayout.h
===
--- clang/lib/CodeGen/CGRecordLayout.h
+++ clang/lib/CodeGen/CGRecordLayout.h
@@ -200,6 +200,12 @@
 return FieldInfo.lookup(FD);
   }
 
+  // Return whether the following non virtual base has a corresponding
+  // entry in the LLVM struct.
+  bool hasNonVirtualBaseLLVMField(const CXXRecordDecl *RD) const {
+return NonVirtualBases.count(RD);
+  }
+
   unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const {
 assert(NonVirtualBases.count(RD) && "Invalid non-virtual base!");
 return NonVirtualBases.lookup(RD);


Index: clang/lib/CodeGen/CGRecordLayout.h
===
--- clang/lib/CodeGen/CGRecordLayout.h
+++ clang/lib/CodeGen/CGRecordLayout.h
@@ -200,6 +200,12 @@
 return FieldInfo.lookup(FD);
   }
 
+  // Return whether the following non virtual base has a corresponding
+  // entry in the LLVM struct.
+  bool hasNonVirtualBaseLLVMField(const CXXRecordDecl *RD) const {
+return NonVirtualBases.count(RD);
+  }
+
   unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const {
 assert(NonVirtualBases.count(RD) && "Invalid non-virtual base!");
 return NonVirtualBases.lookup(RD);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 89525cb - [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread William S. Moses via cfe-commits

Author: William S. Moses
Date: 2022-03-25T16:32:12-04:00
New Revision: 89525cbf283f1ffeca1e007a06b29917a9eadc53

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

LOG: [Clang] Add helper method to determine if a nonvirtual base has an entry 
in the LLVM struct

This patch adds a helper method to determine if a nonvirtual base has an entry 
in the LLVM struct. Such a base may not have an entry
if the base does not have any fields/bases itself that would change the size of 
the struct. This utility method is useful for other frontends (Polygeist) that 
use Clang as an API to generate code.

Reviewed By: efriedma

Differential Revision: https://reviews.llvm.org/D122502

Added: 


Modified: 
clang/lib/CodeGen/CGRecordLayout.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGRecordLayout.h 
b/clang/lib/CodeGen/CGRecordLayout.h
index 5a3bcdf72f7b6..d5ea74922603b 100644
--- a/clang/lib/CodeGen/CGRecordLayout.h
+++ b/clang/lib/CodeGen/CGRecordLayout.h
@@ -200,6 +200,12 @@ class CGRecordLayout {
 return FieldInfo.lookup(FD);
   }
 
+  // Return whether the following non virtual base has a corresponding
+  // entry in the LLVM struct.
+  bool hasNonVirtualBaseLLVMField(const CXXRecordDecl *RD) const {
+return NonVirtualBases.count(RD);
+  }
+
   unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const {
 assert(NonVirtualBases.count(RD) && "Invalid non-virtual base!");
 return NonVirtualBases.lookup(RD);



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


[PATCH] D122502: [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122502/new/

https://reviews.llvm.org/D122502

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


[PATCH] D122503: Remove dead code in driver parsing -gsimple-template-names= options

2022-03-25 Thread Paul Robinson via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6aa039775891: Remove dead code in driver parsing 
-gsimple-template-names= options (authored by probinson).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122503/new/

https://reviews.llvm.org/D122503

Files:
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4295,8 +4295,8 @@
 ? "-gpubnames"
 : "-ggnu-pubnames");
   const auto *SimpleTemplateNamesArg =
-  Args.getLastArg(options::OPT_gsimple_template_names, 
options::OPT_gno_simple_template_names,
-  options::OPT_gsimple_template_names_EQ);
+  Args.getLastArg(options::OPT_gsimple_template_names,
+  options::OPT_gno_simple_template_names);
   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
   if (SimpleTemplateNamesArg &&
   checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
@@ -4304,17 +4304,6 @@
 if (Opt.matches(options::OPT_gsimple_template_names)) {
   ForwardTemplateParams = true;
   CmdArgs.push_back("-gsimple-template-names=simple");
-} else if (Opt.matches(options::OPT_gsimple_template_names_EQ)) {
-  ForwardTemplateParams = true;
-  StringRef Value = SimpleTemplateNamesArg->getValue();
-  if (Value == "simple") {
-CmdArgs.push_back("-gsimple-template-names=simple");
-  } else if (Value == "mangled") {
-CmdArgs.push_back("-gsimple-template-names=mangled");
-  } else {
-D.Diag(diag::err_drv_unsupported_option_argument)
-<< Opt.getName() << SimpleTemplateNamesArg->getValue();
-  }
 }
   }
 


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4295,8 +4295,8 @@
 ? "-gpubnames"
 : "-ggnu-pubnames");
   const auto *SimpleTemplateNamesArg =
-  Args.getLastArg(options::OPT_gsimple_template_names, options::OPT_gno_simple_template_names,
-  options::OPT_gsimple_template_names_EQ);
+  Args.getLastArg(options::OPT_gsimple_template_names,
+  options::OPT_gno_simple_template_names);
   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
   if (SimpleTemplateNamesArg &&
   checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
@@ -4304,17 +4304,6 @@
 if (Opt.matches(options::OPT_gsimple_template_names)) {
   ForwardTemplateParams = true;
   CmdArgs.push_back("-gsimple-template-names=simple");
-} else if (Opt.matches(options::OPT_gsimple_template_names_EQ)) {
-  ForwardTemplateParams = true;
-  StringRef Value = SimpleTemplateNamesArg->getValue();
-  if (Value == "simple") {
-CmdArgs.push_back("-gsimple-template-names=simple");
-  } else if (Value == "mangled") {
-CmdArgs.push_back("-gsimple-template-names=mangled");
-  } else {
-D.Diag(diag::err_drv_unsupported_option_argument)
-<< Opt.getName() << SimpleTemplateNamesArg->getValue();
-  }
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6aa0397 - Remove dead code in driver parsing -gsimple-template-names= options

2022-03-25 Thread Paul Robinson via cfe-commits

Author: Paul Robinson
Date: 2022-03-25T13:23:24-07:00
New Revision: 6aa039775891b6eae81604bb851e72192f5a7462

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

LOG: Remove dead code in driver parsing -gsimple-template-names= options

While -g[no-]simple-template-names is a driver option, the fancier
-gsimple-template-names={simple,mangled} option is cc1-only, so code
to handle it in the driver is dead.

Differential Revision: https://reviews.llvm.org/D122503

Added: 


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

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index b9d36a753d072..7c7f9254b34da 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4295,8 +4295,8 @@ static void renderDebugOptions(const ToolChain , const 
Driver ,
 ? "-gpubnames"
 : "-ggnu-pubnames");
   const auto *SimpleTemplateNamesArg =
-  Args.getLastArg(options::OPT_gsimple_template_names, 
options::OPT_gno_simple_template_names,
-  options::OPT_gsimple_template_names_EQ);
+  Args.getLastArg(options::OPT_gsimple_template_names,
+  options::OPT_gno_simple_template_names);
   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
   if (SimpleTemplateNamesArg &&
   checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
@@ -4304,17 +4304,6 @@ static void renderDebugOptions(const ToolChain , 
const Driver ,
 if (Opt.matches(options::OPT_gsimple_template_names)) {
   ForwardTemplateParams = true;
   CmdArgs.push_back("-gsimple-template-names=simple");
-} else if (Opt.matches(options::OPT_gsimple_template_names_EQ)) {
-  ForwardTemplateParams = true;
-  StringRef Value = SimpleTemplateNamesArg->getValue();
-  if (Value == "simple") {
-CmdArgs.push_back("-gsimple-template-names=simple");
-  } else if (Value == "mangled") {
-CmdArgs.push_back("-gsimple-template-names=mangled");
-  } else {
-D.Diag(diag::err_drv_unsupported_option_argument)
-<< Opt.getName() << SimpleTemplateNamesArg->getValue();
-  }
 }
   }
 



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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:295
+// atom.
+BoolValue  = Env.makeAtomicBoolValue();
+return Env.makeOr(Env.makeAnd(HasValueVal, OptionalHoldsEmptyString),

Not related to this PR, but I think in the future we will want to associate 
names to the values to make debugging easier (or maybe to generate really nice 
error messages).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122503: Remove dead code in driver parsing -gsimple-template-names= options

2022-03-25 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a subscriber: cfe-commits.
probinson added a comment.

+cfe-commits; that should have happened automatically?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122503/new/

https://reviews.llvm.org/D122503

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-25 Thread Bill Wendling via Phabricator via cfe-commits
void added inline comments.



Comment at: clang/include/clang/AST/Decl.h:2842
   mutable unsigned CachedFieldIndex : 30;
+  mutable unsigned OriginalFieldIndex : 30;
 

aaron.ballman wrote:
> It's unfortunate that every field node in the AST is now going to be 4 bytes 
> larger for this feature; I worry about the extra memory pressure from the 
> additional overhead, so if there's a way for us to save some space here, I 
> think it might be worth it. (I'm worried that our max template instantiation 
> depth will shrink because of this.)
Turns out this field wasn't used. I removed it.



Comment at: clang/include/clang/Basic/AttrDocs.td:6367
+program should be compiled with the same seed, but keep the seed safe
+otherwise.
+

aaron.ballman wrote:
> I think it would help to explain the effects of this attribute in conjunction 
> with structure packing techniques (the `packed` attribute and bit-fields) and 
> whether any attempt is made to keep the structure packed or those fields 
> together or not. I'd expect no such attempt is made, but people may want to 
> know "attempts to pack this structure" and "randomize this structure layout" 
> are not compatible. (We may want to diagnose in the case of seeing the 
> `packed` attribute, in fact.)
> 
> We should also be more clear that the seed specified does not have to be 
> numeric in nature (from the file or when directly on the command line).
Having randomization and the `packed` attribute probably isn't the best option. 
I'll modify things to prevent that from happening.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121556/new/

https://reviews.llvm.org/D121556

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-25 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 418307.
void marked 5 inline comments as done.
void added a comment.

Add "err_" prefix to error message.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121556/new/

https://reviews.llvm.org/D121556

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,409 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// 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 contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string ) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandstruct-seed=1234567890abcdef");
+  return tooling::buildASTFromCodeWithArgs(SourceCode, Args, "input.c");
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext , const std::string ) {
+  return FirstDeclMatcher().match(C.getTranslationUnitDecl(),
+  recordDecl(hasName(Name)));
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names , const field_names ) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast_matchers {
+
+#define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest
+
+TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) {
+  const field_names Seq = {"a", "b", "c", "d"};
+
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a"}));
+  ASSERT_FALSE(isSubsequence(Seq, {"a", "d"}));
+}
+
+#define RANDSTRUCT_TEST StructureLayoutRandomization
+
+TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+};
+  )c");
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+  const field_names Expected = {"bacon", "lettuce", "tomato", "mayonnaise"};
+
+  ASSERT_FALSE(RD->getAttr());
+  ASSERT_FALSE(RD->isRandomized());
+  ASSERT_EQ(Expected, getFieldNamesFromRecord(RD));
+}
+
+TEST(RANDSTRUCT_TEST, MarkedNoRandomize) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+

[PATCH] D122502: [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread William Moses via Phabricator via cfe-commits
wsmoses added a comment.

Polygeist is a (hopefully soon to be LLVM incubator project: 
https://discourse.llvm.org/t/rfc-polygeist-llvm-incubator-proposal/60890), 
that, among other things, is a Clang-based C/C++ frontend for MLIR. As such, we 
kind of expect to be built alongside clang and borrow the header. As the 
project gets closer to upstream, hopefully the include sharing will actually be 
more explicit (and will be made an upstream PR regardless after some other 
technical debt and paper deadlines).

The relevant code that needs this from our side is here, if curious: 
https://github.com/wsmoses/Polygeist/pull/198/files


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122502/new/

https://reviews.llvm.org/D122502

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


[PATCH] D122258: [MC][RFC] Omit DWARF unwind info if compact unwind is present for all archs

2022-03-25 Thread Jez Ng via Phabricator via cfe-commits
int3 added a comment.

I'm currently working on the eh_frame support in LLD itself, but will circle 
back to this diff in a week or so. Thanks for the feedback!




Comment at: 
clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp:48
 
+// FIXME
 TEST(InterpreterTest, CatchException) {

lhames wrote:
> I guess this is just a placeholder? The final commit should include more 
> detail.
yep, just a placeholder



Comment at: llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp:131-132
+   size_t Size) {
+  if (Size == 0)
+return;
   registerEHFramesInProcess(Addr, Size);

lhames wrote:
> Is this needed? With your change, registerEHFramesInProcess should be a no-op 
> if `Size == 0`.
might not be yeah. I wasn't sure whether the extra entry in `EHFrames` would be 
an issue, but I will double check



Comment at: llvm/tools/llc/llc.cpp:697-700
+auto  = MMIWP->getMMI().getContext();
+Ctx.setGenDwarfForAssembly(Target->Options.ForceDwarfFrameSection);
 const_cast(LLVMTM.getObjFileLowering())
+->Initialize(Ctx, *Target);

lhames wrote:
> This option hand-off feels very manual. I wonder if we should add a 
> `propagateTargetOptionsToMC` function, but maybe the set of options that it 
> would apply to is small enough not to bother for now?
> 
> I would add something like this to `LLVMTargetMachine::addPassesToEmitMC` 
> too, for the the case where the caller passes in a null `MCContext*`. 
thanks for the pointers! I'll look into that


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122258/new/

https://reviews.llvm.org/D122258

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:279
+ cast_or_null(Env.getValue(*ComparisonExprLoc))) {
+Env.setValue(*ComparisonExprLoc,
+ Env.makeAnd(*CurrentValue, ComparisonValue));

I am still wondering a bit about this case. 

We generate: `HasValueVal and ContentsNotEqX and CurrentValue`.'
I wonder if we want: `HasValueVal  and (ContentsNotEqX  <=> CurrentValue)` 
instead?  Or even `HasValueVal  and CurrentValue`?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122502: [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'm not against this, I guess... but clang/lib/CodeGen/CGRecordLayout.h isn't 
an installed header; it's not clear to me how you're using this.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122502/new/

https://reviews.llvm.org/D122502

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-25 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 418305.
void added a comment.
Herald added a subscriber: MaskRay.

Fix how the command line flags are handled.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121556/new/

https://reviews.llvm.org/D121556

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,409 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// 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 contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string ) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandstruct-seed=1234567890abcdef");
+  return tooling::buildASTFromCodeWithArgs(SourceCode, Args, "input.c");
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext , const std::string ) {
+  return FirstDeclMatcher().match(C.getTranslationUnitDecl(),
+  recordDecl(hasName(Name)));
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names , const field_names ) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast_matchers {
+
+#define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest
+
+TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) {
+  const field_names Seq = {"a", "b", "c", "d"};
+
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a"}));
+  ASSERT_FALSE(isSubsequence(Seq, {"a", "d"}));
+}
+
+#define RANDSTRUCT_TEST StructureLayoutRandomization
+
+TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+};
+  )c");
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+  const field_names Expected = {"bacon", "lettuce", "tomato", "mayonnaise"};
+
+  ASSERT_FALSE(RD->getAttr());
+  ASSERT_FALSE(RD->isRandomized());
+  ASSERT_EQ(Expected, getFieldNamesFromRecord(RD));
+}
+
+TEST(RANDSTRUCT_TEST, MarkedNoRandomize) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+   

[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

ymandel wrote:
> xazax.hun wrote:
> > xazax.hun wrote:
> > > ymandel wrote:
> > > > xazax.hun wrote:
> > > > > Is this the right way to initialize `ComparisonValue`?
> > > > > 
> > > > > Considering the expression: `opt.value_or(nullptr) != nullptr`
> > > > > * When `has_value == false`, `opt.value_or(nullptr)` will return 
> > > > > `nullptr`, so `!=` evaluates to false. This case seems to check out.
> > > > > * However, when `has_value == true`, `opt` might still hold an 
> > > > > `nullptr` and `!=` could still evaluate to false. 
> > > > Thanks for digging into this. I think it's correct, but helpful to step 
> > > > through:
> > > > 
> > > > Its correctness depends on `MakeValue`, so I'll focus on that in 
> > > > particular. For the `nullptr` case, we'll get:
> > > > ```
> > > > HasValueVal && ContentsNotEqX
> > > > ```
> > > > So, when `has_value == true`, this basically reduces to 
> > > > `ContentsNotEqX`. Since that's an atom, the result is indeterminate, 
> > > > which I believe is the desired outcome.
> > > > 
> > > > WDYT?  Also, even if I've convinced you, please let me know how i can 
> > > > improve the comments. For that matter, would `MakeValue` be better with 
> > > > a more specific name, like "MakePredicate" or somesuch?
> > > I think what confuses me is that we do something different for the 3 
> > > cases. You convinced me that `HasValueVal && ContentsNotEqX` is correct. 
> > > But we only do this for one branch out of the 3.  What is the reason for 
> > > that?
> > Oh, never mind. Yeah, I think changing `MakeValue` to `MakePredicate` would 
> > make this a bit clearer. After a second read now I understand better what 
> > is going on.
> Just to be clear: the three cases you mean are lines 273-283, or something 
> else?
and never mind my question, then (I rpelied before I saw your updated). I'll 
change the name and add comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

xazax.hun wrote:
> xazax.hun wrote:
> > ymandel wrote:
> > > xazax.hun wrote:
> > > > Is this the right way to initialize `ComparisonValue`?
> > > > 
> > > > Considering the expression: `opt.value_or(nullptr) != nullptr`
> > > > * When `has_value == false`, `opt.value_or(nullptr)` will return 
> > > > `nullptr`, so `!=` evaluates to false. This case seems to check out.
> > > > * However, when `has_value == true`, `opt` might still hold an 
> > > > `nullptr` and `!=` could still evaluate to false. 
> > > Thanks for digging into this. I think it's correct, but helpful to step 
> > > through:
> > > 
> > > Its correctness depends on `MakeValue`, so I'll focus on that in 
> > > particular. For the `nullptr` case, we'll get:
> > > ```
> > > HasValueVal && ContentsNotEqX
> > > ```
> > > So, when `has_value == true`, this basically reduces to `ContentsNotEqX`. 
> > > Since that's an atom, the result is indeterminate, which I believe is the 
> > > desired outcome.
> > > 
> > > WDYT?  Also, even if I've convinced you, please let me know how i can 
> > > improve the comments. For that matter, would `MakeValue` be better with a 
> > > more specific name, like "MakePredicate" or somesuch?
> > I think what confuses me is that we do something different for the 3 cases. 
> > You convinced me that `HasValueVal && ContentsNotEqX` is correct. But we 
> > only do this for one branch out of the 3.  What is the reason for that?
> Oh, never mind. Yeah, I think changing `MakeValue` to `MakePredicate` would 
> make this a bit clearer. After a second read now I understand better what is 
> going on.
Just to be clear: the three cases you mean are lines 273-283, or something else?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > Is this the right way to initialize `ComparisonValue`?
> > > 
> > > Considering the expression: `opt.value_or(nullptr) != nullptr`
> > > * When `has_value == false`, `opt.value_or(nullptr)` will return 
> > > `nullptr`, so `!=` evaluates to false. This case seems to check out.
> > > * However, when `has_value == true`, `opt` might still hold an `nullptr` 
> > > and `!=` could still evaluate to false. 
> > Thanks for digging into this. I think it's correct, but helpful to step 
> > through:
> > 
> > Its correctness depends on `MakeValue`, so I'll focus on that in 
> > particular. For the `nullptr` case, we'll get:
> > ```
> > HasValueVal && ContentsNotEqX
> > ```
> > So, when `has_value == true`, this basically reduces to `ContentsNotEqX`. 
> > Since that's an atom, the result is indeterminate, which I believe is the 
> > desired outcome.
> > 
> > WDYT?  Also, even if I've convinced you, please let me know how i can 
> > improve the comments. For that matter, would `MakeValue` be better with a 
> > more specific name, like "MakePredicate" or somesuch?
> I think what confuses me is that we do something different for the 3 cases. 
> You convinced me that `HasValueVal && ContentsNotEqX` is correct. But we only 
> do this for one branch out of the 3.  What is the reason for that?
Oh, never mind. Yeah, I think changing `MakeValue` to `MakePredicate` would 
make this a bit clearer. After a second read now I understand better what is 
going on.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:307
+  [](Environment , BoolValue ) -> BoolValue & {
+// We can't reason about general vlaues, so we encode the constraint on
+// the optional's contents (namely, that it is not equal to X) as an

Typo: values.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D121951: [AMDGPU][OpenCL] Add "amdgpu-no-hostcall-ptr" in Clang codegen pre-COV_5

2022-03-25 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9381
+  M.getTarget().getTargetOpts().CodeObjectVersion != 500) {
+F->addFnAttr("amdgpu-no-hostcall-ptr");
+  }

scott.linder wrote:
> arsenm wrote:
> > sameerds wrote:
> > > The frontend does not need to worry about this attribute. See the comment 
> > > in the MetadataStreamer. A worthwhile check would be to generate an error 
> > > if we are able to detect that some hostcall service is being used in 
> > > OpenCL on code-object-v4 or lower. None exists right now, but we should 
> > > add the check if such services show up. But those checks are likely to be 
> > > in a different place. For example, enabling asan on OpenCL for 
> > > code-object-v4 should result in an error in the place where asan 
> > > commandline options are parsed.
> > Should be all opencl, not just kernels. Also < instead of !=?
> > The frontend does not need to worry about this attribute. See the comment 
> > in the MetadataStreamer. 
> 
> The reason I went this route is that otherwise the MetadataStreamer can only 
> go off of the presence of the OCL printf metadata to infer that hostcall 
> argument metadata is invalid and will be ignored by the runtime. Ideally, the 
> MetadataStreamer or Verifier or something would actually //require// that a 
> module does not have both OCL printf metadata and functions which are not 
> "amdgpu-no-hostcall-ptr", but I didn't go that far as it would break old 
> IR/bitcode that relies on the implicit behavior.
> 
> I'm OK with removing this code, and the rest of the patch remains essentially 
> unchanged. We will still have an implicit rule based on code-object-version 
> and presence of printf metadata, and at least conceptually you will still be 
> able to compile OCL for pre-V5 and end up with hostcall argument metadata. 
> That case is benign if the runtime just ignores it, but it still seems 
> needlessly relaxed when we can just add the correct attribute in Clang 
> codegen.
> 
> > Should be all opencl, not just kernels. Also < instead of !=?
> 
> Yes, my mistake, I'll update this
+1 for using < instead of !=

However,  device library is written in OpenCL language. There are functions 
using hostcall buffer. We cannot mark all OpenCL functions with this attribute.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121951/new/

https://reviews.llvm.org/D121951

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

ymandel wrote:
> xazax.hun wrote:
> > Is this the right way to initialize `ComparisonValue`?
> > 
> > Considering the expression: `opt.value_or(nullptr) != nullptr`
> > * When `has_value == false`, `opt.value_or(nullptr)` will return `nullptr`, 
> > so `!=` evaluates to false. This case seems to check out.
> > * However, when `has_value == true`, `opt` might still hold an `nullptr` 
> > and `!=` could still evaluate to false. 
> Thanks for digging into this. I think it's correct, but helpful to step 
> through:
> 
> Its correctness depends on `MakeValue`, so I'll focus on that in particular. 
> For the `nullptr` case, we'll get:
> ```
> HasValueVal && ContentsNotEqX
> ```
> So, when `has_value == true`, this basically reduces to `ContentsNotEqX`. 
> Since that's an atom, the result is indeterminate, which I believe is the 
> desired outcome.
> 
> WDYT?  Also, even if I've convinced you, please let me know how i can improve 
> the comments. For that matter, would `MakeValue` be better with a more 
> specific name, like "MakePredicate" or somesuch?
I think what confuses me is that we do something different for the 3 cases. You 
convinced me that `HasValueVal && ContentsNotEqX` is correct. But we only do 
this for one branch out of the 3.  What is the reason for that?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122499: [libTooling] Support TransformerResult in consumer callbacks

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:126-128
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith &) {}

Why won't a simple specialization work?



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:191-193
+} else {
+  // If we don't have metadata and we don't have any edits, skip.
+  if (std::is_void::value)

simplify to `else if` ?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122499/new/

https://reviews.llvm.org/D122499

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


[PATCH] D122179: Serialize PragmaAssumeNonNullLoc to support preambles

2022-03-25 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 418301.
dgoldman added a comment.

Revert comment change


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122179/new/

https://reviews.llvm.org/D122179

Files:
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Lex/PreprocessorOptions.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Index/preamble-assume-nonnull.c

Index: clang/test/Index/preamble-assume-nonnull.c
===
--- /dev/null
+++ clang/test/Index/preamble-assume-nonnull.c
@@ -0,0 +1,6 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s 2>&1 \
+// RUN: | FileCheck %s --implicit-check-not "error:"
+
+#pragma clang assume_nonnull begin
+void foo(int *x);
+#pragma clang assume_nonnull end
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -872,6 +872,7 @@
   RECORD(PP_CONDITIONAL_STACK);
   RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
   RECORD(PP_INCLUDED_FILES);
+  RECORD(PP_ASSUME_NONNULL_LOC);
 
   // SourceManager Block.
   BLOCK(SOURCE_MANAGER_BLOCK);
@@ -2299,6 +2300,17 @@
 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
   }
 
+  // If we have a recorded #pragma assume_nonnull, remember it so it can be
+  // replayed when the preamble terminates into the main file.
+  SourceLocation AssumeNonNullLoc =
+  PP.getPreambleRecordedPragmaAssumeNonNullLoc();
+  if (AssumeNonNullLoc.isValid()) {
+assert(PP.isRecordingPreamble());
+AddSourceLocation(AssumeNonNullLoc, Record);
+Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
+Record.clear();
+  }
+
   if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
 assert(!IsModule);
 auto SkipInfo = PP.getPreambleSkipInfo();
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3109,6 +3109,7 @@
   case IDENTIFIER_OFFSET:
   case INTERESTING_IDENTIFIERS:
   case STATISTICS:
+  case PP_ASSUME_NONNULL_LOC:
   case PP_CONDITIONAL_STACK:
   case PP_COUNTER_VALUE:
   case SOURCE_LOCATION_OFFSETS:
@@ -3371,6 +3372,14 @@
   }
   break;
 
+case PP_ASSUME_NONNULL_LOC: {
+  unsigned Idx = 0;
+  if (!Record.empty())
+PP.setPreambleRecordedPragmaAssumeNonNullLoc(
+ReadSourceLocation(F, Record, Idx));
+  break;
+}
+
 case PP_CONDITIONAL_STACK:
   if (!Record.empty()) {
 unsigned Idx = 0, End = Record.size() - 1;
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -432,8 +432,13 @@
   // instantiation or a _Pragma.
   if (PragmaAssumeNonNullLoc.isValid() &&
   !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
-Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
-
+// If we're at the end of generating a preamble, we should record the
+// unterminated \#pragma clang assume_nonnull so we can restore it later
+// when the preamble is loaded into the main file.
+if (isRecordingPreamble() && isInPrimaryFile())
+  PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;
+else
+  Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
 // Recover by leaving immediately.
 PragmaAssumeNonNullLoc = SourceLocation();
   }
@@ -514,10 +519,14 @@
  PPCallbacks::ExitFile, FileType, ExitedFID);
 }
 
-// Restore conditional stack from the preamble right after exiting from the
-// predefines file.
-if (ExitedFromPredefinesFile)
+// Restore conditional stack as well as the recorded
+// \#pragma clang assume_nonnull from the preamble right after exiting
+// from the predefines file.
+if (ExitedFromPredefinesFile) {
   replayPreambleConditionalStack();
+  if (PreambleRecordedPragmaAssumeNonNullLoc.isValid())
+PragmaAssumeNonNullLoc = PreambleRecordedPragmaAssumeNonNullLoc;
+}
 
 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
 (isInPrimaryFile() ||
Index: clang/include/clang/Serialization/ASTBitCodes.h
===
--- clang/include/clang/Serialization/ASTBitCodes.h
+++ clang/include/clang/Serialization/ASTBitCodes.h
@@ -698,6 +698,10 @@
 
   /// Record code for included files.
   PP_INCLUDED_FILES = 66,
+
+  /// Record code for an unterminated \#pragma clang assume_nonnull begin
+  /// recorded in a 

[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 3 inline comments as done.
ymandel added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

xazax.hun wrote:
> Is this the right way to initialize `ComparisonValue`?
> 
> Considering the expression: `opt.value_or(nullptr) != nullptr`
> * When `has_value == false`, `opt.value_or(nullptr)` will return `nullptr`, 
> so `!=` evaluates to false. This case seems to check out.
> * However, when `has_value == true`, `opt` might still hold an `nullptr` and 
> `!=` could still evaluate to false. 
Thanks for digging into this. I think it's correct, but helpful to step through:

Its correctness depends on `MakeValue`, so I'll focus on that in particular. 
For the `nullptr` case, we'll get:
```
HasValueVal && ContentsNotEqX
```
So, when `has_value == true`, this basically reduces to `ContentsNotEqX`. Since 
that's an atom, the result is indeterminate, which I believe is the desired 
outcome.

WDYT?  Also, even if I've convinced you, please let me know how i can improve 
the comments. For that matter, would `MakeValue` be better with a more specific 
name, like "MakePredicate" or somesuch?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122502: [Clang] Add helper method to determine if a nonvirtual base has an entry in the LLVM struct

2022-03-25 Thread William Moses via Phabricator via cfe-commits
wsmoses created this revision.
wsmoses added reviewers: jdoerfert, ftynse, eli.friedman, stuij, ostannard.
Herald added a project: All.
wsmoses requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch adds a helper method to determine if a nonvirtual base has an entry 
in the LLVM struct. Such a base may not have an entry
if the base does not have any fields/bases itself that would change the size of 
the struct. This utility method is useful for other frontends (Polygeist) that 
use Clang as an API to generate code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122502

Files:
  clang/lib/CodeGen/CGRecordLayout.h


Index: clang/lib/CodeGen/CGRecordLayout.h
===
--- clang/lib/CodeGen/CGRecordLayout.h
+++ clang/lib/CodeGen/CGRecordLayout.h
@@ -200,6 +200,12 @@
 return FieldInfo.lookup(FD);
   }
 
+  // Return whether the following non virtual base has a corresponding
+  // entry in the LLVM struct.
+  bool hasNonVirtualBaseLLVMField(const CXXRecordDecl *RD) const {
+return NonVirtualBases.count(RD);
+  }
+
   unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const {
 assert(NonVirtualBases.count(RD) && "Invalid non-virtual base!");
 return NonVirtualBases.lookup(RD);


Index: clang/lib/CodeGen/CGRecordLayout.h
===
--- clang/lib/CodeGen/CGRecordLayout.h
+++ clang/lib/CodeGen/CGRecordLayout.h
@@ -200,6 +200,12 @@
 return FieldInfo.lookup(FD);
   }
 
+  // Return whether the following non virtual base has a corresponding
+  // entry in the LLVM struct.
+  bool hasNonVirtualBaseLLVMField(const CXXRecordDecl *RD) const {
+return NonVirtualBases.count(RD);
+  }
+
   unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const {
 assert(NonVirtualBases.count(RD) && "Invalid non-virtual base!");
 return NonVirtualBases.lookup(RD);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122499: [libTooling] Support TransformerResult in consumer callbacks

2022-03-25 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 418295.
li.zhe.hua added a comment.

Fix comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122499/new/

https://reviews.llvm.org/D122499

Files:
  clang/include/clang/Tooling/Transformer/Transformer.h
  clang/lib/Tooling/Transformer/Transformer.cpp

Index: clang/lib/Tooling/Transformer/Transformer.cpp
===
--- clang/lib/Tooling/Transformer/Transformer.cpp
+++ clang/lib/Tooling/Transformer/Transformer.cpp
@@ -66,26 +66,6 @@
   return Changes;
 }
 
-void NoMetadataImpl::onMatchImpl(const MatchFinder::MatchResult ) {
-  size_t I = transformer::detail::findSelectedCase(Result, Rule);
-  auto Transformations = Rule.Cases[I].Edits(Result);
-  if (!Transformations) {
-Consumer(Transformations.takeError());
-return;
-  }
-
-  if (Transformations->empty())
-return;
-
-  auto Changes = convertToAtomicChanges(*Transformations, Result);
-  if (!Changes) {
-Consumer(Changes.takeError());
-return;
-  }
-
-  Consumer(llvm::MutableArrayRef(*Changes));
-}
-
 } // namespace detail
 
 void Transformer::registerMatchers(MatchFinder *MatchFinder) {
Index: clang/include/clang/Tooling/Transformer/Transformer.h
===
--- clang/include/clang/Tooling/Transformer/Transformer.h
+++ clang/include/clang/Tooling/Transformer/Transformer.h
@@ -21,7 +21,7 @@
 
 namespace detail {
 /// Implementation details of \c Transformer with type erasure around
-/// \c RewriteRule and \c RewriteRule as well as the corresponding consumers.
+/// \c RewriteRule as well as the corresponding consumers.
 class TransformerImpl {
 public:
   virtual ~TransformerImpl() = default;
@@ -43,33 +43,6 @@
   onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) = 0;
 };
 
-/// Implementation for when no metadata is generated as a part of the
-/// \c RewriteRule.
-class NoMetadataImpl final : public TransformerImpl {
-  transformer::RewriteRule Rule;
-  std::function>)> Consumer;
-
-public:
-  explicit NoMetadataImpl(
-  transformer::RewriteRule R,
-  std::function>)>
-  Consumer)
-  : Rule(std::move(R)), Consumer(std::move(Consumer)) {
-assert(llvm::all_of(Rule.Cases,
-[](const transformer::RewriteRule::Case ) {
-  return Case.Edits;
-}) &&
-   "edit generator must be provided for each rule");
-  }
-
-private:
-  void onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) final;
-  std::vector
-  buildMatchers() const final {
-return transformer::detail::buildMatchers(Rule);
-  }
-};
-
 // FIXME: Use std::type_identity or backport when available.
 template  struct type_identity {
   using type = T;
@@ -81,8 +54,6 @@
   T Metadata;
 };
 
-// Specialization provided only to avoid SFINAE on the Transformer
-// constructor; not intended for use.
 template <> struct TransformerResult {
   llvm::MutableArrayRef Changes;
 };
@@ -107,8 +78,14 @@
   /// other.
   explicit Transformer(transformer::RewriteRuleWith Rule,
ChangeSetConsumer Consumer)
-  : Impl(std::make_unique(std::move(Rule),
-  std::move(Consumer))) {}
+  : Transformer(std::move(Rule),
+[Consumer = std::move(Consumer)](
+llvm::Expected> Result) {
+  if (Result)
+Consumer(Result->Changes);
+  else
+Consumer(Result.takeError());
+}) {}
 
   /// \param Consumer receives all rewrites and the associated metadata for a
   /// single match, or an error. Will always be called for each match, even if
@@ -135,6 +112,46 @@
 };
 
 namespace detail {
+/// Asserts that all \c Metadata for the \c Rule is set.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith ) {
+  assert(llvm::all_of(Rule.Metadata,
+  [](const typename transformer::Generator )
+  -> bool { return !!Metadata; }) &&
+ "metadata generator must be provided for each rule");
+}
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith &) {}
+/// @}
+
+/// Runs the metadata generator on \c Rule and stuffs it into \c Result.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+std::enable_if_t::value, llvm::Error>
+populateMetadata(const transformer::RewriteRuleWith ,
+ size_t SelectedCase,
+ const ast_matchers::MatchFinder::MatchResult ,
+ TransformerResult ) {
+  auto Metadata = Rule.Metadata[SelectedCase]->eval(Match);
+  if (!Metadata)
+return Metadata.takeError();
+  Result.Metadata = std::move(*Metadata);
+  return llvm::Error::success();

[clang-tools-extra] 9a3eeae - [clang-tidy] Fix the condition for building CTTestTidyModule

2022-03-25 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-03-25T21:22:46+02:00
New Revision: 9a3eeae3218f0f8a082d8aabdf4f26e30a86170d

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

LOG: [clang-tidy] Fix the condition for building CTTestTidyModule

This is the correct intended condition; the problematic case where
we don't want to try to build the plugin is "WIN32 AND LLVM_LINK_LLVM_DYLIB"
and thus the negation is "NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB".

Differential Revision: https://reviews.llvm.org/D121687

Added: 


Modified: 
clang-tools-extra/test/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/test/CMakeLists.txt 
b/clang-tools-extra/test/CMakeLists.txt
index d64366cba2328..2cdf186081efc 100644
--- a/clang-tools-extra/test/CMakeLists.txt
+++ b/clang-tools-extra/test/CMakeLists.txt
@@ -73,7 +73,7 @@ foreach(dep ${LLVM_UTILS_DEPS})
 endforeach()
 
 if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
-  if (NOT WIN32 AND NOT LLVM_LINK_LLVM_DYLIB)
+  if (NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB)
 llvm_add_library(
 CTTestTidyModule
 MODULE clang-tidy/CTTestTidyModule.cpp



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


[clang] 57ee624 - [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

2022-03-25 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-03-25T20:22:01+01:00
New Revision: 57ee624d7946b4d42890709287eb71d4eb1fa2fa

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

LOG: [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

CLANG_TOOLS_DIR holds the the current bin/ directory, maybe with a %(build_mode)
placeholder. It is used to add the just-built binaries to $PATH for lit tests.
In most cases it equals LLVM_TOOLS_DIR, which is used for the same purpose.
But for a standalone build of clang, CLANG_TOOLS_DIR points at the build tree
and LLVM_TOOLS_DIR points at the provided LLVM binaries.

Currently CLANG_TOOLS_DIR is set in clang/test/, clang-tools-extra/test/, and
other things always built with clang. This is a few cryptic lines of CMake in
each place. Meanwhile LLVM_TOOLS_DIR is provided by configure_site_lit_cfg().

This patch moves CLANG_TOOLS_DIR to configure_site_lit_cfg() and renames it:
 - there's nothing clang-specific about the value
 - it will also replace LLD_TOOLS_DIR, LLDB_TOOLS_DIR etc (not in this patch)

It also defines CURRENT_LIBS_DIR. While I removed the last usage of
CLANG_LIBS_DIR in e4cab4e24d1, there are LLD_LIBS_DIR usages etc that
may be live, and I'd like to mechanically update them in a followup patch.

Differential Revision: https://reviews.llvm.org/D121763

Added: 


Modified: 
clang-tools-extra/clangd/test/CMakeLists.txt
clang-tools-extra/clangd/test/lit.site.cfg.py.in
clang-tools-extra/pseudo/test/CMakeLists.txt
clang-tools-extra/pseudo/test/lit.site.cfg.py.in
clang-tools-extra/test/CMakeLists.txt
clang-tools-extra/test/lit.site.cfg.py.in
clang/test/CMakeLists.txt
clang/test/lit.site.cfg.py.in
clang/utils/perf-training/CMakeLists.txt
clang/utils/perf-training/lit.site.cfg.in
clang/utils/perf-training/order-files.lit.site.cfg.in
lld/test/CMakeLists.txt
lld/test/Unit/lit.site.cfg.py.in
lld/test/lit.site.cfg.py.in
llvm/cmake/modules/AddLLVM.cmake
llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
llvm/utils/gn/secondary/clang/test/BUILD.gn
llvm/utils/gn/secondary/lld/test/BUILD.gn

Removed: 




diff  --git a/clang-tools-extra/clangd/test/CMakeLists.txt 
b/clang-tools-extra/clangd/test/CMakeLists.txt
index f4c4fb61fbbf1..6bb578263ffc8 100644
--- a/clang-tools-extra/clangd/test/CMakeLists.txt
+++ b/clang-tools-extra/clangd/test/CMakeLists.txt
@@ -1,13 +1,3 @@
-# Set CLANG_TOOLS_DIR to buildtree/bin, or buildtree/%(build_mode)s/bin if the
-# location is dynamic. The latter must be interpolated by lit configs.
-# FIXME: this is duplicated in many places.
-if (CMAKE_CFG_INTDIR STREQUAL ".")
-  set(LLVM_BUILD_MODE ".")
-else ()
-  set(LLVM_BUILD_MODE "%(build_mode)s")
-endif ()
-string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} CLANG_TOOLS_DIR 
${LLVM_RUNTIME_OUTPUT_INTDIR})
-
 set(CLANGD_TEST_DEPS
   clangd
   ClangdTests

diff  --git a/clang-tools-extra/clangd/test/lit.site.cfg.py.in 
b/clang-tools-extra/clangd/test/lit.site.cfg.py.in
index 43475e83f987d..20caa72af3da1 100644
--- a/clang-tools-extra/clangd/test/lit.site.cfg.py.in
+++ b/clang-tools-extra/clangd/test/lit.site.cfg.py.in
@@ -7,7 +7,7 @@ config.host_triple = "@LLVM_HOST_TRIPLE@"
 config.python_executable = "@Python3_EXECUTABLE@"
 # Support substitution of the tools and libs dirs with user parameters. This is
 # used when we can't determine the tool dir at configuration time.
-config.clang_tools_dir = lit_config.substitute("@CLANG_TOOLS_DIR@")
+config.clang_tools_dir = lit_config.substitute("@CURRENT_TOOLS_DIR@")
 config.llvm_tools_dir = lit_config.substitute("@LLVM_TOOLS_DIR@")
 config.llvm_libs_dir = lit_config.substitute("@LLVM_LIBS_DIR@")
 

diff  --git a/clang-tools-extra/pseudo/test/CMakeLists.txt 
b/clang-tools-extra/pseudo/test/CMakeLists.txt
index 334acb58d41c2..e541359ee5cf6 100644
--- a/clang-tools-extra/pseudo/test/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/test/CMakeLists.txt
@@ -1,13 +1,3 @@
-# Set CLANG_TOOLS_DIR to buildtree/bin, or buildtree/%(build_mode)s/bin if the
-# location is dynamic. The latter must be interpolated by lit configs.
-# FIXME: this is duplicated in many places.
-if (CMAKE_CFG_INTDIR STREQUAL ".")
-  set(LLVM_BUILD_MODE ".")
-else ()
-  set(LLVM_BUILD_MODE "%(build_mode)s")
-endif ()
-string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} CLANG_TOOLS_DIR 
${LLVM_RUNTIME_OUTPUT_INTDIR})
-
 set(CLANG_PSEUDO_TEST_DEPS
   clang-pseudo
   ClangPseudoTests

diff  --git a/clang-tools-extra/pseudo/test/lit.site.cfg.py.in 
b/clang-tools-extra/pseudo/test/lit.site.cfg.py.in
index 2f7a095736ecb..3a969381ca613 100644
--- 

[PATCH] D121763: [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

2022-03-25 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57ee624d7946: [cmake] Provide CURRENT_TOOLS_DIR centrally, 
replacing CLANG_TOOLS_DIR (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121763/new/

https://reviews.llvm.org/D121763

Files:
  clang-tools-extra/clangd/test/CMakeLists.txt
  clang-tools-extra/clangd/test/lit.site.cfg.py.in
  clang-tools-extra/pseudo/test/CMakeLists.txt
  clang-tools-extra/pseudo/test/lit.site.cfg.py.in
  clang-tools-extra/test/CMakeLists.txt
  clang-tools-extra/test/lit.site.cfg.py.in
  clang/test/CMakeLists.txt
  clang/test/lit.site.cfg.py.in
  clang/utils/perf-training/CMakeLists.txt
  clang/utils/perf-training/lit.site.cfg.in
  clang/utils/perf-training/order-files.lit.site.cfg.in
  lld/test/CMakeLists.txt
  lld/test/Unit/lit.site.cfg.py.in
  lld/test/lit.site.cfg.py.in
  llvm/cmake/modules/AddLLVM.cmake
  llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
  llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
  llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
  llvm/utils/gn/secondary/clang/test/BUILD.gn
  llvm/utils/gn/secondary/lld/test/BUILD.gn

Index: llvm/utils/gn/secondary/lld/test/BUILD.gn
===
--- llvm/utils/gn/secondary/lld/test/BUILD.gn
+++ llvm/utils/gn/secondary/lld/test/BUILD.gn
@@ -15,8 +15,8 @@
   "LIT_SITE_CFG_IN_HEADER=## Autogenerated from $input, do not edit",
   "LLD_BINARY_DIR=" +
   rebase_path(get_label_info("//lld", "target_out_dir")),
-  "LLD_LIBS_DIR=",  # FIXME: for shared builds only (?)
-  "LLD_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
+  "CURRENT_LIBS_DIR=",  # FIXME: for shared builds only (?)
+  "CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
   "LLD_SOURCE_DIR=" + rebase_path("//lld"),
   "LLVM_BINARY_DIR=" +
   rebase_path(get_label_info("//llvm", "target_out_dir")),
Index: llvm/utils/gn/secondary/clang/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang/test/BUILD.gn
@@ -48,7 +48,7 @@
 "CLANG_DEFAULT_CXX_STDLIB=",  # Empty string means "default value" here.
 "CLANG_DEFAULT_PIE_ON_LINUX=0",
 "CLANG_PLUGIN_SUPPORT=0",  # FIXME: Analysis/plugins need global -fPIC
-"CLANG_TOOLS_DIR=" + rebase_path("$root_out_dir/bin", dir),
+"CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin", dir),
 "CLANG_VENDOR_UTI=org.llvm.clang",
 
 # This is only used if LLVM_USE_SANITIZER includes lsan and the host
Index: llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
@@ -32,7 +32,7 @@
   output = clang_tools_extra_lit_site_cfg_file
 
   extra_values = [
-"CLANG_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
+"CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
 "CLANG_PLUGIN_SUPPORT=0",
 "LLVM_HOST_TRIPLE=$llvm_current_triple",
 "LLVM_INSTALL_TOOLCHAIN_ONLY=0",
Index: llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
@@ -26,7 +26,7 @@
 "CMAKE_CURRENT_SOURCE_DIR=" +
 rebase_path("//clang-tools-extra/pseudo/test"),
 
-"CLANG_TOOLS_DIR=",
+"CURRENT_TOOLS_DIR=",
 "LLVM_LIT_TOOLS_DIR=",  # Intentionally empty, matches cmake build.
 "LLVM_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
 "TARGET_TRIPLE=$llvm_target_triple",
Index: llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
@@ -28,7 +28,7 @@
 "CMAKE_CURRENT_SOURCE_DIR=" +
 rebase_path("//clang-tools-extra/clangd/test"),
 
-"CLANG_TOOLS_DIR=",
+"CURRENT_TOOLS_DIR=",
 "CLANGD_ENABLE_REMOTE=0",
 "CLANGD_TIDY_CHECKS=1",
 "LLVM_HOST_TRIPLE=$llvm_current_triple",
Index: llvm/cmake/modules/AddLLVM.cmake
===
--- llvm/cmake/modules/AddLLVM.cmake
+++ llvm/cmake/modules/AddLLVM.cmake
@@ -1630,13 +1630,15 @@
 
   set_llvm_build_mode()
 
-  # The below might not be the build tree but provided binary tree.
+  # For standalone builds of subprojects, these might not be the build tree but
+  # a provided binary tree.
   set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
   set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
   

[clang-tools-extra] 57ee624 - [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

2022-03-25 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-03-25T20:22:01+01:00
New Revision: 57ee624d7946b4d42890709287eb71d4eb1fa2fa

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

LOG: [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

CLANG_TOOLS_DIR holds the the current bin/ directory, maybe with a %(build_mode)
placeholder. It is used to add the just-built binaries to $PATH for lit tests.
In most cases it equals LLVM_TOOLS_DIR, which is used for the same purpose.
But for a standalone build of clang, CLANG_TOOLS_DIR points at the build tree
and LLVM_TOOLS_DIR points at the provided LLVM binaries.

Currently CLANG_TOOLS_DIR is set in clang/test/, clang-tools-extra/test/, and
other things always built with clang. This is a few cryptic lines of CMake in
each place. Meanwhile LLVM_TOOLS_DIR is provided by configure_site_lit_cfg().

This patch moves CLANG_TOOLS_DIR to configure_site_lit_cfg() and renames it:
 - there's nothing clang-specific about the value
 - it will also replace LLD_TOOLS_DIR, LLDB_TOOLS_DIR etc (not in this patch)

It also defines CURRENT_LIBS_DIR. While I removed the last usage of
CLANG_LIBS_DIR in e4cab4e24d1, there are LLD_LIBS_DIR usages etc that
may be live, and I'd like to mechanically update them in a followup patch.

Differential Revision: https://reviews.llvm.org/D121763

Added: 


Modified: 
clang-tools-extra/clangd/test/CMakeLists.txt
clang-tools-extra/clangd/test/lit.site.cfg.py.in
clang-tools-extra/pseudo/test/CMakeLists.txt
clang-tools-extra/pseudo/test/lit.site.cfg.py.in
clang-tools-extra/test/CMakeLists.txt
clang-tools-extra/test/lit.site.cfg.py.in
clang/test/CMakeLists.txt
clang/test/lit.site.cfg.py.in
clang/utils/perf-training/CMakeLists.txt
clang/utils/perf-training/lit.site.cfg.in
clang/utils/perf-training/order-files.lit.site.cfg.in
lld/test/CMakeLists.txt
lld/test/Unit/lit.site.cfg.py.in
lld/test/lit.site.cfg.py.in
llvm/cmake/modules/AddLLVM.cmake
llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
llvm/utils/gn/secondary/clang/test/BUILD.gn
llvm/utils/gn/secondary/lld/test/BUILD.gn

Removed: 




diff  --git a/clang-tools-extra/clangd/test/CMakeLists.txt 
b/clang-tools-extra/clangd/test/CMakeLists.txt
index f4c4fb61fbbf1..6bb578263ffc8 100644
--- a/clang-tools-extra/clangd/test/CMakeLists.txt
+++ b/clang-tools-extra/clangd/test/CMakeLists.txt
@@ -1,13 +1,3 @@
-# Set CLANG_TOOLS_DIR to buildtree/bin, or buildtree/%(build_mode)s/bin if the
-# location is dynamic. The latter must be interpolated by lit configs.
-# FIXME: this is duplicated in many places.
-if (CMAKE_CFG_INTDIR STREQUAL ".")
-  set(LLVM_BUILD_MODE ".")
-else ()
-  set(LLVM_BUILD_MODE "%(build_mode)s")
-endif ()
-string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} CLANG_TOOLS_DIR 
${LLVM_RUNTIME_OUTPUT_INTDIR})
-
 set(CLANGD_TEST_DEPS
   clangd
   ClangdTests

diff  --git a/clang-tools-extra/clangd/test/lit.site.cfg.py.in 
b/clang-tools-extra/clangd/test/lit.site.cfg.py.in
index 43475e83f987d..20caa72af3da1 100644
--- a/clang-tools-extra/clangd/test/lit.site.cfg.py.in
+++ b/clang-tools-extra/clangd/test/lit.site.cfg.py.in
@@ -7,7 +7,7 @@ config.host_triple = "@LLVM_HOST_TRIPLE@"
 config.python_executable = "@Python3_EXECUTABLE@"
 # Support substitution of the tools and libs dirs with user parameters. This is
 # used when we can't determine the tool dir at configuration time.
-config.clang_tools_dir = lit_config.substitute("@CLANG_TOOLS_DIR@")
+config.clang_tools_dir = lit_config.substitute("@CURRENT_TOOLS_DIR@")
 config.llvm_tools_dir = lit_config.substitute("@LLVM_TOOLS_DIR@")
 config.llvm_libs_dir = lit_config.substitute("@LLVM_LIBS_DIR@")
 

diff  --git a/clang-tools-extra/pseudo/test/CMakeLists.txt 
b/clang-tools-extra/pseudo/test/CMakeLists.txt
index 334acb58d41c2..e541359ee5cf6 100644
--- a/clang-tools-extra/pseudo/test/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/test/CMakeLists.txt
@@ -1,13 +1,3 @@
-# Set CLANG_TOOLS_DIR to buildtree/bin, or buildtree/%(build_mode)s/bin if the
-# location is dynamic. The latter must be interpolated by lit configs.
-# FIXME: this is duplicated in many places.
-if (CMAKE_CFG_INTDIR STREQUAL ".")
-  set(LLVM_BUILD_MODE ".")
-else ()
-  set(LLVM_BUILD_MODE "%(build_mode)s")
-endif ()
-string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} CLANG_TOOLS_DIR 
${LLVM_RUNTIME_OUTPUT_INTDIR})
-
 set(CLANG_PSEUDO_TEST_DEPS
   clang-pseudo
   ClangPseudoTests

diff  --git a/clang-tools-extra/pseudo/test/lit.site.cfg.py.in 
b/clang-tools-extra/pseudo/test/lit.site.cfg.py.in
index 2f7a095736ecb..3a969381ca613 100644
--- 

[PATCH] D122499: [libTooling] Support TransformerResult in consumer callbacks

2022-03-25 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
li.zhe.hua added a reviewer: ymandel.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Support `TransformerResult` in the consumer callback, which
allows generic code to more naturally use the `Transformer` interface
(instead of needing to specialize on `void`).

This also delete the specialization that existed within `Transformer`
itself, instead replacing it with an `std::function` adapter.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122499

Files:
  clang/include/clang/Tooling/Transformer/Transformer.h
  clang/lib/Tooling/Transformer/Transformer.cpp

Index: clang/lib/Tooling/Transformer/Transformer.cpp
===
--- clang/lib/Tooling/Transformer/Transformer.cpp
+++ clang/lib/Tooling/Transformer/Transformer.cpp
@@ -66,26 +66,6 @@
   return Changes;
 }
 
-void NoMetadataImpl::onMatchImpl(const MatchFinder::MatchResult ) {
-  size_t I = transformer::detail::findSelectedCase(Result, Rule);
-  auto Transformations = Rule.Cases[I].Edits(Result);
-  if (!Transformations) {
-Consumer(Transformations.takeError());
-return;
-  }
-
-  if (Transformations->empty())
-return;
-
-  auto Changes = convertToAtomicChanges(*Transformations, Result);
-  if (!Changes) {
-Consumer(Changes.takeError());
-return;
-  }
-
-  Consumer(llvm::MutableArrayRef(*Changes));
-}
-
 } // namespace detail
 
 void Transformer::registerMatchers(MatchFinder *MatchFinder) {
Index: clang/include/clang/Tooling/Transformer/Transformer.h
===
--- clang/include/clang/Tooling/Transformer/Transformer.h
+++ clang/include/clang/Tooling/Transformer/Transformer.h
@@ -21,7 +21,7 @@
 
 namespace detail {
 /// Implementation details of \c Transformer with type erasure around
-/// \c RewriteRule and \c RewriteRule as well as the corresponding consumers.
+/// \c RewriteRule as well as the corresponding consumers.
 class TransformerImpl {
 public:
   virtual ~TransformerImpl() = default;
@@ -43,33 +43,6 @@
   onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) = 0;
 };
 
-/// Implementation for when no metadata is generated as a part of the
-/// \c RewriteRule.
-class NoMetadataImpl final : public TransformerImpl {
-  transformer::RewriteRule Rule;
-  std::function>)> Consumer;
-
-public:
-  explicit NoMetadataImpl(
-  transformer::RewriteRule R,
-  std::function>)>
-  Consumer)
-  : Rule(std::move(R)), Consumer(std::move(Consumer)) {
-assert(llvm::all_of(Rule.Cases,
-[](const transformer::RewriteRule::Case ) {
-  return Case.Edits;
-}) &&
-   "edit generator must be provided for each rule");
-  }
-
-private:
-  void onMatchImpl(const ast_matchers::MatchFinder::MatchResult ) final;
-  std::vector
-  buildMatchers() const final {
-return transformer::detail::buildMatchers(Rule);
-  }
-};
-
 // FIXME: Use std::type_identity or backport when available.
 template  struct type_identity {
   using type = T;
@@ -81,8 +54,6 @@
   T Metadata;
 };
 
-// Specialization provided only to avoid SFINAE on the Transformer
-// constructor; not intended for use.
 template <> struct TransformerResult {
   llvm::MutableArrayRef Changes;
 };
@@ -107,8 +78,14 @@
   /// other.
   explicit Transformer(transformer::RewriteRuleWith Rule,
ChangeSetConsumer Consumer)
-  : Impl(std::make_unique(std::move(Rule),
-  std::move(Consumer))) {}
+  : Transformer(std::move(Rule),
+[Consumer = std::move(Consumer)](
+llvm::Expected> Result) {
+  if (Result)
+Consumer(Result->Changes);
+  else
+Consumer(Result.takeError());
+}) {}
 
   /// \param Consumer receives all rewrites and the associated metadata for a
   /// single match, or an error. Will always be called for each match, even if
@@ -135,6 +112,46 @@
 };
 
 namespace detail {
+/// Asserts that all \c Metadata for the \c Rule is set.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith ) {
+  assert(llvm::all_of(Rule.Metadata,
+  [](const typename transformer::Generator )
+  -> bool { return !!Metadata; }) &&
+ "metadata generator must be provided for each rule");
+}
+template 
+std::enable_if_t::value, void>
+assertMetadataSet(const transformer::RewriteRuleWith &) {}
+/// @}
+
+/// Asserts that all \c Metadata for the \c Rule is set.
+/// FIXME: Use constexpr-if in C++17.
+/// @{
+template 
+std::enable_if_t::value, llvm::Error>
+populateMetadata(const 

[PATCH] D122496: [C11] Correct the resulting type for an assignment expression

2022-03-25 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.

Beside maybe a comment that could help understanding, I think this looks good!




Comment at: clang/lib/Sema/SemaExpr.cpp:13647
   // operand.
-  return (getLangOpts().CPlusPlus
-  ? LHSType : LHSType.getUnqualifiedType());
+  return getLangOpts().CPlusPlus ? LHSType : 
LHSType.getAtomicUnqualifiedType();
 }

I wonder if we want another comment here to make it extra clear that atomic 
should be stripped?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122496/new/

https://reviews.llvm.org/D122496

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


[PATCH] D121687: [clang-tidy] Don't try to build CTTestTidyModule for Windows with dylibs

2022-03-25 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang-tools-extra/test/CMakeLists.txt:84
 if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
-  llvm_add_library(
-  CTTestTidyModule
-  MODULE clang-tidy/CTTestTidyModule.cpp
-  PLUGIN_TOOL clang-tidy
-  DEPENDS clang-tidy-headers)
+  if (NOT WIN32 AND NOT LLVM_LINK_LLVM_DYLIB)
+llvm_add_library(

jeremyd2019 wrote:
> I only just noticed this patch, but it feels to me like this was intended to 
> be OR here, because the condition to be avoided seems to be `WIN32 AND 
> LLVM_LINK_LLVM_DYLIB`, which inverted is `NOT WIN32 OR NOT 
> LLVM_LINK_LLVM_DYLIB`
Oh indeed, thanks, good catch! I'll push a patch fixing that.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121687/new/

https://reviews.llvm.org/D121687

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


[PATCH] D122497: [clang][NFC] Add filescope array initialization test

2022-03-25 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm created this revision.
cebowleratibm added a reviewer: AaronLiu.
cebowleratibm added a project: clang.
Herald added a project: All.
cebowleratibm requested review of this revision.
Herald added a subscriber: cfe-commits.

This test is based on a customer-reported failure in an XL compiler, added here 
to improve clang regression testing.  The primary purpose of the test is to 
ensure that the array initializations can be evaluated without the need for 
runtime initialization.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122497

Files:
  clang/test/CodeGen/array-init-2.c


Index: clang/test/CodeGen/array-init-2.c
===
--- /dev/null
+++ clang/test/CodeGen/array-init-2.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+typedef enum {
+   a,
+   b,
+   c,
+   d,
+   e,
+   f,
+   g,
+   h
+} E;
+
+typedef struct {
+   E c;
+   int val;
+} Entry;
+
+static const Entry entries[] = {
+   {a,},
+   {b,},
+   {c,},
+   {d,},
+   {e,},
+   {f,},
+   {g,},
+   {h,}
+};
+
+const Entry *list[] = {
+   entries,
+   entries,
+   entries
+};
+
+// CHECK: %struct.Entry = type { [[E:i[0-9]+]], i32 }
+// CHECK: @entries = internal constant [8 x %struct.Entry] [%struct.Entry 
zeroinitializer, %struct.Entry { [[E]] 1, i32 0 }, %struct.Entry { [[E]] 2, i32 
0 }, %struct.Entry { [[E]] 3, i32 0 }, %struct.Entry { [[E]] 4, i32 0 }, 
%struct.Entry { [[E]] 5, i32 0 }, %struct.Entry { [[E]] 6, i32 0 }, 
%struct.Entry { [[E]] 7, i32 0 }], align 4
+// CHECK: @list = global [3 x %struct.Entry*] [%struct.Entry* getelementptr 
inbounds ([8 x %struct.Entry], [8 x %struct.Entry]* @entries, i32 0, i32 0), 
%struct.Entry* getelementptr inbounds ([8 x %struct.Entry], [8 x 
%struct.Entry]* @entries, i32 0, i32 0), %struct.Entry* getelementptr inbounds 
([8 x %struct.Entry], [8 x %struct.Entry]* @entries, i32 0, i32 0)], align 8


Index: clang/test/CodeGen/array-init-2.c
===
--- /dev/null
+++ clang/test/CodeGen/array-init-2.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+typedef enum {
+   a,
+   b,
+   c,
+   d,
+   e,
+   f,
+   g,
+   h
+} E;
+
+typedef struct {
+   E c;
+   int val;
+} Entry;
+
+static const Entry entries[] = {
+   {a,},
+   {b,},
+   {c,},
+   {d,},
+   {e,},
+   {f,},
+   {g,},
+   {h,}
+};
+
+const Entry *list[] = {
+   entries,
+   entries,
+   entries
+};
+
+// CHECK: %struct.Entry = type { [[E:i[0-9]+]], i32 }
+// CHECK: @entries = internal constant [8 x %struct.Entry] [%struct.Entry zeroinitializer, %struct.Entry { [[E]] 1, i32 0 }, %struct.Entry { [[E]] 2, i32 0 }, %struct.Entry { [[E]] 3, i32 0 }, %struct.Entry { [[E]] 4, i32 0 }, %struct.Entry { [[E]] 5, i32 0 }, %struct.Entry { [[E]] 6, i32 0 }, %struct.Entry { [[E]] 7, i32 0 }], align 4
+// CHECK: @list = global [3 x %struct.Entry*] [%struct.Entry* getelementptr inbounds ([8 x %struct.Entry], [8 x %struct.Entry]* @entries, i32 0, i32 0), %struct.Entry* getelementptr inbounds ([8 x %struct.Entry], [8 x %struct.Entry]* @entries, i32 0, i32 0), %struct.Entry* getelementptr inbounds ([8 x %struct.Entry], [8 x %struct.Entry]* @entries, i32 0, i32 0)], align 8
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122496: [C11] Correct the resulting type for an assignment expression

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: eli.friedman, jyknight, erichkeane, 
clang-language-wg.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a project: clang.

In C, assignment expressions result in an rvalue whose type is the type of the 
lhs of the assignment after it undergoes lvalue to rvalue conversion. lvalue to 
rvalue conversion in C strips all qualifiers including `_Atomic`.

We used `getUnqualifiedType()` which does not strip the `_Atomic` qualifier 
when we should have used `getAtomicUnqualifiedType()`. This corrects the usage 
and adds some comments to `getUnqualifiedType()` to make it more clear that it 
does not strip `_Atomic` and that's on purpose (see C11 6.2.5p27).

This addresses Issue 48742.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122496

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Type.h
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/atomic-expr.c


Index: clang/test/Sema/atomic-expr.c
===
--- clang/test/Sema/atomic-expr.c
+++ clang/test/Sema/atomic-expr.c
@@ -61,3 +61,17 @@
 int func_14 (void) {
   return data1 == 0;
 }
+
+void func_15(void) {
+  // Ensure that the result of an assignment expression properly strips the
+  // _Atomic qualifier; Issue 48742.
+  _Atomic int x;
+  int y = (x = 2);
+  int z = (int)(x = 2);
+  y = (x = 2);
+  z = (int)(x = 2);
+  y = (x += 2);
+
+  _Static_assert(__builtin_types_compatible_p(__typeof__(x = 2), int), 
"incorrect");
+  _Static_assert(__builtin_types_compatible_p(__typeof__(x += 2), int), 
"incorrect");
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -13644,8 +13644,7 @@
   // is converted to the type of the assignment expression (above).
   // C++ 5.17p1: the type of the assignment expression is that of its left
   // operand.
-  return (getLangOpts().CPlusPlus
-  ? LHSType : LHSType.getUnqualifiedType());
+  return getLangOpts().CPlusPlus ? LHSType : 
LHSType.getAtomicUnqualifiedType();
 }
 
 // Only ignore explicit casts to void.
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -931,6 +931,10 @@
   /// The resulting type might still be qualified if it's sugar for an array
   /// type.  To strip qualifiers even from within a sugared array type, use
   /// ASTContext::getUnqualifiedArrayType.
+  ///
+  /// Note: In C, the _Atomic qualifier is special (see C2x 6.2.5p29 for
+  /// details), and it is not stripped by this function. Use
+  /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic.
   inline QualType getUnqualifiedType() const;
 
   /// Retrieve the unqualified variant of the given type, removing as little
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -82,7 +82,9 @@
   alias, target) identifier instead of only processing one such ``#pragma 
weak``
   per identifier.
   Fixes `Issue 28985 `_.
-
+- Assignment expressions in C11 and later mode now properly strip the _Atomic
+  qualifier when determining the type of the assignment expression. Fixes
+  `Issue 48742 `_.
 - Unevaluated lambdas in dependant contexts no longer result in clang crashing.
   This fixes Issues `50376 
`_,
   `51414 `_,


Index: clang/test/Sema/atomic-expr.c
===
--- clang/test/Sema/atomic-expr.c
+++ clang/test/Sema/atomic-expr.c
@@ -61,3 +61,17 @@
 int func_14 (void) {
   return data1 == 0;
 }
+
+void func_15(void) {
+  // Ensure that the result of an assignment expression properly strips the
+  // _Atomic qualifier; Issue 48742.
+  _Atomic int x;
+  int y = (x = 2);
+  int z = (int)(x = 2);
+  y = (x = 2);
+  z = (int)(x = 2);
+  y = (x += 2);
+
+  _Static_assert(__builtin_types_compatible_p(__typeof__(x = 2), int), "incorrect");
+  _Static_assert(__builtin_types_compatible_p(__typeof__(x += 2), int), "incorrect");
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -13644,8 +13644,7 @@
   // is converted to the type of the assignment expression (above).
   // C++ 5.17p1: the type of the assignment expression is that of its left
   // operand.
-  return (getLangOpts().CPlusPlus
-  ? LHSType : LHSType.getUnqualifiedType());
+  return getLangOpts().CPlusPlus ? LHSType : 

[PATCH] D121687: [clang-tidy] Don't try to build CTTestTidyModule for Windows with dylibs

2022-03-25 Thread Jeremy Drake via Phabricator via cfe-commits
jeremyd2019 added inline comments.



Comment at: clang-tools-extra/test/CMakeLists.txt:84
 if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
-  llvm_add_library(
-  CTTestTidyModule
-  MODULE clang-tidy/CTTestTidyModule.cpp
-  PLUGIN_TOOL clang-tidy
-  DEPENDS clang-tidy-headers)
+  if (NOT WIN32 AND NOT LLVM_LINK_LLVM_DYLIB)
+llvm_add_library(

I only just noticed this patch, but it feels to me like this was intended to be 
OR here, because the condition to be avoided seems to be `WIN32 AND 
LLVM_LINK_LLVM_DYLIB`, which inverted is `NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121687/new/

https://reviews.llvm.org/D121687

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


[PATCH] D117522: [clang-tidy] Add modernize-macro-to-enum check

2022-03-25 Thread Douglas Yung via Phabricator via cfe-commits
dyung added a comment.

I've reverted this change in order to get the build bots green again.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D117522/new/

https://reviews.llvm.org/D117522

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


[clang-tools-extra] cef5210 - Revert "[clang-tidy] Add modernize-macro-to-enum check"

2022-03-25 Thread Douglas Yung via cfe-commits

Author: Douglas Yung
Date: 2022-03-25T11:53:42-07:00
New Revision: cef52105bd4b639a76de71cc84ed8d56bdaede1d

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

LOG: Revert "[clang-tidy] Add modernize-macro-to-enum check"

This reverts commit 39b80c8380c86539de391600efaa17184b5a52b4.

This change was causing build failures on several build bots:
- https://lab.llvm.org/buildbot/#/builders/139/builds/19210
- https://lab.llvm.org/buildbot/#/builders/93/builds/7956

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-macro-to-enum.rst
clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum2.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum3.h
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp



diff  --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6bf20552e0182..147c2741d59e4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -11,7 +11,6 @@ add_clang_library(clangTidyModernizeModule
   DeprecatedIosBaseAliasesCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
-  MacroToEnumCheck.cpp
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp

diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
deleted file mode 100644
index 834943483cffb..0
--- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ /dev/null
@@ -1,482 +0,0 @@
-//===--- MacroToEnumCheck.cpp - clang-tidy 
===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "MacroToEnumCheck.h"
-#include "clang/AST/ASTContext.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/Lex/Preprocessor.h"
-#include "llvm/ADT/STLExtras.h"
-#include 
-#include 
-#include 
-#include 
-
-namespace clang {
-namespace tidy {
-namespace modernize {
-
-static bool hasOnlyComments(SourceLocation Loc, const LangOptions ,
-StringRef Text) {
-  // Use a lexer to look for tokens; if we find something other than a single
-  // hash, then there were intervening tokens between macro definitions.
-  std::string Buffer{Text};
-  Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
-Buffer.c_str() + Buffer.size());
-  Token Tok;
-  bool SeenHash = false;
-  while (!Lex.LexFromRawLexer(Tok)) {
-if (Tok.getKind() == tok::hash && !SeenHash) {
-  SeenHash = true;
-  continue;
-}
-return false;
-  }
-
-  // Everything in between was whitespace, so now just look for two blank 
lines,
-  // consisting of two consecutive EOL sequences, either '\n', '\r' or '\r\n'.
-  enum class WhiteSpace {
-Nothing,
-CR,
-LF,
-CRLF,
-CRLFCR,
-  };
-
-  WhiteSpace State = WhiteSpace::Nothing;
-  for (char C : Text) {
-switch (C) {
-case '\r':
-  if (State == WhiteSpace::CR)
-return false;
-
-  State = State == WhiteSpace::CRLF ? WhiteSpace::CRLFCR : WhiteSpace::CR;
-  break;
-
-case '\n':
-  if (State == WhiteSpace::LF || State == WhiteSpace::CRLFCR)
-return false;
-
-  State = State == WhiteSpace::CR ? WhiteSpace::CRLF : WhiteSpace::LF;
-  break;
-
-default:
-  State = WhiteSpace::Nothing;
-  break;
-}
-  }
-
-  return true;
-}
-
-// Validate that this literal token is a valid integer literal.  A literal 
token
-// could be a floating-point token, which isn't acceptable as a value for an
-// enumeration.  A floating-point token must either have a decimal point or an
-// exponent ('E' or 'P').
-static bool isIntegralConstant(const Token ) {
-  const char *Begin = Token.getLiteralData();
-  const char *End = Begin + Token.getLength();
-
-  // not a hexadecimal floating-point literal
-  

[PATCH] D122446: [clang][extract-api] Add Objective-C interface support

2022-03-25 Thread Zixu Wang via Phabricator via cfe-commits
zixuw updated this revision to Diff 418286.
zixuw added a comment.

Move the `Language` fix out into a separate patch: D122495 



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122446/new/

https://reviews.llvm.org/D122446

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/objc_interface.m

Index: clang/test/ExtractAPI/objc_interface.m
===
--- /dev/null
+++ clang/test/ExtractAPI/objc_interface.m
@@ -0,0 +1,403 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/reference.output.json.in >> \
+// RUN: %t/reference.output.json
+// RUN: %clang -extract-api -x objective-c-header -target arm64-apple-macosx \
+// RUN: %t/input.h -o %t/output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- input.h
+@protocol Protocol
+@end
+
+@interface Super 
+@property(readonly, getter=getProperty) unsigned Property;
++ (id)getWithProperty:(unsigned) Property;
+@end
+
+@interface Derived : Super {
+  char Ivar;
+}
+- (char)getIvar;
+@end
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationhips": [
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Super(cm)getWithProperty:",
+  "target": "c:objc(cs)Super"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Super(py)Property",
+  "target": "c:objc(cs)Super"
+},
+{
+  "kind": "conformsTo",
+  "source": "c:objc(cs)Super",
+  "target": "c:objc(pl)Protocol"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Derived@Ivar",
+  "target": "c:objc(cs)Derived"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)Derived(im)getIvar",
+  "target": "c:objc(cs)Derived"
+},
+{
+  "kind": "inheritsFrom",
+  "source": "c:objc(cs)Derived",
+  "target": "c:objc(cs)Super"
+}
+  ],
+  "symbols": [
+{
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "@interface"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Super"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(cs)Super"
+  },
+  "kind": {
+"displayName": "Class",
+"identifier": "objective-c.class"
+  },
+  "location": {
+"character": 12,
+"line": 4,
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "Super"
+  }
+],
+"title": "Super"
+  }
+},
+{
+  "declarationFragments": [
+{
+  "kind": "text",
+  "spelling": "+ ("
+},
+{
+  "kind": "keyword",
+  "spelling": "id"
+},
+{
+  "kind": "text",
+  "spelling": ")"
+},
+{
+  "kind": "identifier",
+  "spelling": "getWithProperty"
+},
+{
+  "kind": "text",
+  "spelling": ":"
+},
+{
+  "kind": "text",
+  "spelling": "("
+},
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:i",
+  "spelling": "unsigned int"
+},
+{
+  "kind": "text",
+  "spelling": ")"
+},
+{
+  "kind": "internalParam",
+  "spelling": "Property"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(cs)Super(cm)getWithProperty:"
+  },
+  "kind": {
+"displayName": "Type Method",
+"identifier": "objective-c.type.method"
+  },
+  "location": {
+"character": 1,
+"line": 6,
+   

[PATCH] D121763: [cmake] Provide CURRENT_TOOLS_DIR centrally, replacing CLANG_TOOLS_DIR

2022-03-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 418285.
sammccall added a comment.

Rebase. Also update LLD since it's simple and similar to clang.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121763/new/

https://reviews.llvm.org/D121763

Files:
  clang-tools-extra/clangd/test/CMakeLists.txt
  clang-tools-extra/clangd/test/lit.site.cfg.py.in
  clang-tools-extra/pseudo/test/CMakeLists.txt
  clang-tools-extra/pseudo/test/lit.site.cfg.py.in
  clang-tools-extra/test/CMakeLists.txt
  clang-tools-extra/test/lit.site.cfg.py.in
  clang/test/CMakeLists.txt
  clang/test/lit.site.cfg.py.in
  clang/utils/perf-training/CMakeLists.txt
  clang/utils/perf-training/lit.site.cfg.in
  clang/utils/perf-training/order-files.lit.site.cfg.in
  lld/test/CMakeLists.txt
  lld/test/Unit/lit.site.cfg.py.in
  lld/test/lit.site.cfg.py.in
  llvm/cmake/modules/AddLLVM.cmake
  llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
  llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
  llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
  llvm/utils/gn/secondary/clang/test/BUILD.gn
  llvm/utils/gn/secondary/lld/test/BUILD.gn

Index: llvm/utils/gn/secondary/lld/test/BUILD.gn
===
--- llvm/utils/gn/secondary/lld/test/BUILD.gn
+++ llvm/utils/gn/secondary/lld/test/BUILD.gn
@@ -15,8 +15,8 @@
   "LIT_SITE_CFG_IN_HEADER=## Autogenerated from $input, do not edit",
   "LLD_BINARY_DIR=" +
   rebase_path(get_label_info("//lld", "target_out_dir")),
-  "LLD_LIBS_DIR=",  # FIXME: for shared builds only (?)
-  "LLD_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
+  "CURRENT_LIBS_DIR=",  # FIXME: for shared builds only (?)
+  "CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
   "LLD_SOURCE_DIR=" + rebase_path("//lld"),
   "LLVM_BINARY_DIR=" +
   rebase_path(get_label_info("//llvm", "target_out_dir")),
Index: llvm/utils/gn/secondary/clang/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang/test/BUILD.gn
@@ -48,7 +48,7 @@
 "CLANG_DEFAULT_CXX_STDLIB=",  # Empty string means "default value" here.
 "CLANG_DEFAULT_PIE_ON_LINUX=0",
 "CLANG_PLUGIN_SUPPORT=0",  # FIXME: Analysis/plugins need global -fPIC
-"CLANG_TOOLS_DIR=" + rebase_path("$root_out_dir/bin", dir),
+"CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin", dir),
 "CLANG_VENDOR_UTI=org.llvm.clang",
 
 # This is only used if LLVM_USE_SANITIZER includes lsan and the host
Index: llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/test/BUILD.gn
@@ -32,7 +32,7 @@
   output = clang_tools_extra_lit_site_cfg_file
 
   extra_values = [
-"CLANG_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
+"CURRENT_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
 "CLANG_PLUGIN_SUPPORT=0",
 "LLVM_HOST_TRIPLE=$llvm_current_triple",
 "LLVM_INSTALL_TOOLCHAIN_ONLY=0",
Index: llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/pseudo/test/BUILD.gn
@@ -26,7 +26,7 @@
 "CMAKE_CURRENT_SOURCE_DIR=" +
 rebase_path("//clang-tools-extra/pseudo/test"),
 
-"CLANG_TOOLS_DIR=",
+"CURRENT_TOOLS_DIR=",
 "LLVM_LIT_TOOLS_DIR=",  # Intentionally empty, matches cmake build.
 "LLVM_TOOLS_DIR=" + rebase_path("$root_out_dir/bin"),
 "TARGET_TRIPLE=$llvm_target_triple",
Index: llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clangd/test/BUILD.gn
@@ -28,7 +28,7 @@
 "CMAKE_CURRENT_SOURCE_DIR=" +
 rebase_path("//clang-tools-extra/clangd/test"),
 
-"CLANG_TOOLS_DIR=",
+"CURRENT_TOOLS_DIR=",
 "CLANGD_ENABLE_REMOTE=0",
 "CLANGD_TIDY_CHECKS=1",
 "LLVM_HOST_TRIPLE=$llvm_current_triple",
Index: llvm/cmake/modules/AddLLVM.cmake
===
--- llvm/cmake/modules/AddLLVM.cmake
+++ llvm/cmake/modules/AddLLVM.cmake
@@ -1630,13 +1630,15 @@
 
   set_llvm_build_mode()
 
-  # The below might not be the build tree but provided binary tree.
+  # For standalone builds of subprojects, these might not be the build tree but
+  # a provided binary tree.
   set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
   set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
   string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
   string(REPLACE 

[PATCH] D122495: [clang][extract-api] Use correct language info from inputs

2022-03-25 Thread Zixu Wang via Phabricator via cfe-commits
zixuw created this revision.
Herald added a reviewer: dang.
Herald added a project: All.
zixuw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The current way of getting the `clang::Language` from `LangOptions` does
not handle Objective-C correctly because `clang::Language::ObjC` does
not correspond to any `LangStandard`. This patch passes the correct
`Language` from the frontend input information.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122495

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/language.c

Index: clang/test/ExtractAPI/language.c
===
--- /dev/null
+++ clang/test/ExtractAPI/language.c
@@ -0,0 +1,166 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/c.reference.output.json.in >> \
+// RUN: %t/c.reference.output.json
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/objc.reference.output.json.in >> \
+// RUN: %t/objc.reference.output.json
+
+// RUN: %clang -extract-api -x c-header -target arm64-apple-macosx \
+// RUN: %t/c.h -o %t/c.output.json | FileCheck -allow-empty %s
+// RUN: %clang -extract-api -x objective-c-header -target arm64-apple-macosx \
+// RUN: %t/objc.h -o %t/objc.output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/c.output.json >> %t/c.output-normalized.json
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/objc.output.json >> %t/objc.output-normalized.json
+
+// RUN: diff %t/c.reference.output.json %t/c.output-normalized.json
+// RUN: diff %t/objc.reference.output.json %t/objc.output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- c.h
+char c;
+
+//--- objc.h
+char objc;
+
+//--- c.reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationhips": [],
+  "symbols": [
+{
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:C",
+  "spelling": "char"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "c"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@c"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "c.var"
+  },
+  "location": {
+"character": 6,
+"line": 1,
+"uri": "file://INPUT_DIR/c.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "c"
+  }
+],
+"title": "c"
+  }
+}
+  ]
+}
+//--- objc.reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationhips": [],
+  "symbols": [
+{
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:C",
+  "spelling": "char"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "objc"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@objc"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"character": 6,
+"line": 1,
+"uri": "file://INPUT_DIR/objc.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "objc"
+  }
+],
+"title": "objc"
+  }
+}
+  ]
+}
Index: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
===
--- clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ 

[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread David Li via Phabricator via cfe-commits
davidxl added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp:569
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;

gulfem wrote:
> MaskRay wrote:
> > https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements
> > 
> > That said, nested if is usually written as a single if with `&&`
> Thanks for the tip @MaskRay, and I'm going to fix that in a following patch. 
It would be helpful to add a comment in the code reflecting the review 
discussions.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122336/new/

https://reviews.llvm.org/D122336

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


[clang] 26e201b - [Clang] Fix error in Documentation introduced by 3784e8cc [nfc].

2022-03-25 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2022-03-25T19:38:36+01:00
New Revision: 26e201b7968cf12e603ef648d1be660bb23f3a08

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

LOG: [Clang] Fix error in Documentation introduced by 3784e8cc [nfc].

The documentation contained extra space.
Also remove https://github.com/llvm/llvm-project/issues/54296
from the list of issues by 3784e8cc as this commit did not
fix it (nor was it supposed to).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 39499b79e34d4..9e7958918b2dc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -84,11 +84,10 @@ Bug Fixes
   Fixes `Issue 28985 `_.
 
 - Unevaluated lambdas in dependant contexts no longer result in clang crashing.
-  This fixes Issues `50376 < 
https://github.com/llvm/llvm-project/issues/50376>`_,
-  `54296 < https://github.com/llvm/llvm-project/issues/54296>`_,
-  `51414 < https://github.com/llvm/llvm-project/issues/51414>`_,
-  `51416 < https://github.com/llvm/llvm-project/issues/51416>`_,
-  and `51641 < https://github.com/llvm/llvm-project/issues/51641>`_.
+  This fixes Issues `50376 
`_,
+  `51414 `_,
+  `51416 `_,
+  and `51641 `_.
 
 
 Improvements to Clang's diagnostics



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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:142
+  // `opt.value_or(nullptr) != nullptr` and `opt.value_or(0) != 0`. Ideally,
+  // we'd support this pattern for any expression, but the AST does not have a
+  // generic expression comparison facility, so we specialize to common cases

Yeah, I think Clang is in a very sad state in this regard. We have a lot of 
half done facilities littered all over the codebase, including:
https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Analysis/CloneDetection.h
https://github.com/llvm/llvm-project/blob/main/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp#L306
https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp#L60





Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:147
+ anyOf(ComparesToSame(cxxNullPtrLiteralExpr()),
+   ComparesToSame(integerLiteral(equals(0);
+}

I wonder if we want to add `""` to support `opt.value_or("") != ""`. Not sure 
how frequent would this be over the empty call.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:270
+  // needed.
+  BoolValue  = MakeValue(Env, *HasValueVal);
+  auto *ComparisonExprLoc =

Is this the right way to initialize `ComparisonValue`?

Considering the expression: `opt.value_or(nullptr) != nullptr`
* When `has_value == false`, `opt.value_or(nullptr)` will return `nullptr`, so 
`!=` evaluates to false. This case seems to check out.
* However, when `has_value == true`, `opt` might still hold an `nullptr` and 
`!=` could still evaluate to false. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122231/new/

https://reviews.llvm.org/D122231

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


[PATCH] D122494: Do not treat use of variable from attribute arguments as ODR use

2022-03-25 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Attribute arguments are always compile-time expressions that need to be
evaluated. So, it is not necessary to treat attribute use as ODR use.

Treatment of use from attribute aruments as ODR use had a side
effect in incorrect processing of attributes applied to nested lambdas.
That happened because ODR use from attribute applied to a lambda forced
Sema to check if used variable is correctly captured.
For the following example:

  const int I = 10;
  auto OL = [=] () {
auto IL = [&](int K) __attribute__((enable_if(I > K, "..."))) {};
  };

when capture-checking function was validating use of either variable `I` or
parameter `K` the error "variable cannot be implicitly captured in a lambda with
no capture-default specified" was emitted. That happened due to the
following order of actions during lambda parsing: first, an empty lambda scope
is pushed to `FunctionScopes` collection in `Sema`, then the attributes on
lambdas are handled, and only after that the info about inner lambda capturing
style is saved to a corresponding lambda scope. So, at the point when
attributes on inner lambda are handled, capture-checking function thinks
that it is already inside the inner lambda and it doesn't have capturing
style, so the error was emitted.

This patch makes this error go away.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122494

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/attr-on-lambda.cpp

Index: clang/test/SemaCXX/attr-on-lambda.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/attr-on-lambda.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// expected-no-diagnostics
+
+constexpr int get(const int A) { return A; }
+
+struct MyStruct {
+  const int Member = get(1);
+};
+
+void foo() {
+
+  const int I = 10;
+  constexpr MyStruct S = {1};
+  auto Outer = [=]() {
+auto Inner1 = [&](int k) __attribute__((enable_if(I > k, "nope"))){};
+
+auto Inner2 = [=]() __attribute__((enable_if(S.Member, "nope"))){};
+
+auto Inner3 = [&](int k) __attribute__((enable_if(k > get(I), "nope"))){};
+  };
+}
+
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -2031,6 +2031,8 @@
 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
 VD->isUsableInConstantExpressions(Context))
   return NOUR_Constant;
+if (ExprEvalContexts.back().InAttributeArgsContext)
+  return NOUR_Constant;
   }
 
   // All remaining non-variable cases constitute an odr-use. For variables, we
@@ -16932,12 +16934,13 @@
   return TransformToPE(*this).TransformType(TInfo);
 }
 
-void
-Sema::PushExpressionEvaluationContext(
+void Sema::PushExpressionEvaluationContext(
 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
-ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
+ExpressionEvaluationContextRecord::ExpressionKind ExprContext,
+bool InAttributeArgs) {
   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
-LambdaContextDecl, ExprContext);
+LambdaContextDecl, ExprContext,
+InAttributeArgs);
 
   // Discarded statements and immediate contexts nested in other
   // discarded statements or immediate context are themselves
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -444,9 +444,11 @@
   // General case. Parse all available expressions.
   bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
   EnterExpressionEvaluationContext Unevaluated(
-  Actions, Uneval
-   ? Sema::ExpressionEvaluationContext::Unevaluated
-   : Sema::ExpressionEvaluationContext::ConstantEvaluated);
+  Actions,
+  Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
+ : Sema::ExpressionEvaluationContext::ConstantEvaluated,
+  nullptr, Sema::ExpressionEvaluationContextRecord::EK_Other, true,
+  /* InAttributeArgs = */ true);
 
   CommaLocsTy CommaLocs;
   ExprVector ParsedExprs;
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -1311,15 +1311,19 @@
 bool InDiscardedStatement;
 bool InImmediateFunctionContext;
 
+bool InAttributeArgsContext;
+
 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
 

[PATCH] D115907: [misexpect] Re-implement MisExpect Diagnostics

2022-03-25 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 418280.
paulkirth added a comment.

Fix check for tolerance diagnostic since we now use GenerateArgs the same way 
as hotness threshold.

Since it has a default value, we need to also ensure that it uses a pattern 
similar to other options.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115907/new/

https://reviews.llvm.org/D115907

Files:
  clang/docs/MisExpect.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Profile/Inputs/misexpect-branch-nonconst-expect-arg.proftext
  clang/test/Profile/Inputs/misexpect-branch.proftext
  clang/test/Profile/Inputs/misexpect-switch-default-only.proftext
  clang/test/Profile/Inputs/misexpect-switch-default.proftext
  clang/test/Profile/Inputs/misexpect-switch-nonconst.proftext
  clang/test/Profile/Inputs/misexpect-switch.proftext
  clang/test/Profile/misexpect-branch-cold.c
  clang/test/Profile/misexpect-branch-nonconst-expected-val.c
  clang/test/Profile/misexpect-branch-unpredictable.c
  clang/test/Profile/misexpect-branch.c
  clang/test/Profile/misexpect-switch-default.c
  clang/test/Profile/misexpect-switch-nonconst.c
  clang/test/Profile/misexpect-switch-only-default-case.c
  clang/test/Profile/misexpect-switch.c
  llvm/docs/MisExpect.rst
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/include/llvm/IR/LLVMContext.h
  llvm/include/llvm/Target/TargetOptions.h
  llvm/include/llvm/Transforms/Utils/MisExpect.h
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/lib/IR/LLVMContext.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/Transforms/IPO/SampleProfile.cpp
  llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp
  llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
  llvm/lib/Transforms/Utils/CMakeLists.txt
  llvm/lib/Transforms/Utils/MisExpect.cpp
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch-correct.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch-threshold.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-branch.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-switch-correct.proftext
  llvm/test/Transforms/PGOProfile/Inputs/misexpect-switch.proftext
  llvm/test/Transforms/PGOProfile/misexpect-branch-correct.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch-stripped.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch-unpredictable.ll
  llvm/test/Transforms/PGOProfile/misexpect-branch.ll
  llvm/test/Transforms/PGOProfile/misexpect-switch-default.ll
  llvm/test/Transforms/PGOProfile/misexpect-switch.ll

Index: llvm/test/Transforms/PGOProfile/misexpect-switch.ll
===
--- /dev/null
+++ llvm/test/Transforms/PGOProfile/misexpect-switch.ll
@@ -0,0 +1,285 @@
+; Test misexpect diagnostics handle swich statements, and report source locations correctly
+
+; RUN: llvm-profdata merge %S/Inputs/misexpect-switch.proftext -o %t.profdata
+; RUN: llvm-profdata merge %S/Inputs/misexpect-switch-correct.proftext -o %t.c.profdata
+
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pgo-warn-misexpect -S 2>&1 | FileCheck %s --check-prefix=WARNING
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=REMARK
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -pgo-warn-misexpect -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=BOTH
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.profdata -S 2>&1 | FileCheck %s --check-prefix=DISABLED
+
+; RUN: opt < %s -passes="function(lower-expect),pgo-instr-use" -pgo-test-profile-file=%t.c.profdata -pgo-warn-misexpect -pass-remarks=misexpect -S 2>&1 | FileCheck %s --check-prefix=CORRECT
+
+; WARNING-DAG: warning: misexpect-switch.c:26:30: 0.00%
+; WARNING-NOT: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+
+; REMARK-NOT: warning: misexpect-switch.c:26:30: 0.00%
+; REMARK-DAG: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+
+; BOTH-DAG: warning: misexpect-switch.c:26:30: 0.00%
+; BOTH-DAG: remark: misexpect-switch.c:26:30: Potential performance regression from use of the llvm.expect intrinsic: Annotation was correct on 0.00% (0 / 8112) of profiled executions.
+

[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

2022-03-25 Thread Corentin Jabot via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3784e8ccfbda: [Clang] Fix Unevaluated Lambdas (authored by 
cor3ntin).

Changed prior to commit:
  https://reviews.llvm.org/D121532?vs=418269=418277#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121532/new/

https://reviews.llvm.org/D121532

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/SemaCXX/lambda-unevaluated.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1024,7 +1024,11 @@
 
   Lambdas in unevaluated contexts
   https://wg21.link/p0315r4;>P0315R4
-  Partial
+  
+Partial
+  temp.deduct/9 is not implemented yet.
+
+  
 
 
 
Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5824,6 +5824,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_FALSE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
@@ -5843,6 +5844,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_TRUE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInGlobalScope) {
Index: clang/test/SemaCXX/lambda-unevaluated.cpp
===
--- clang/test/SemaCXX/lambda-unevaluated.cpp
+++ clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -30,6 +30,27 @@
 auto e = g(0); // expected-error{{no matching function for call}}
 // expected-note@-2 {{substitution failure}}
 
+template 
+auto foo(decltype([] {
+  return [] { return T(); }();
+})) {}
+
+void test() {
+  foo({});
+}
+
+template 
+struct C {
+  template 
+  auto foo(decltype([] {
+return [] { return T(); }();
+  })) {}
+};
+
+void test2() {
+  C{}.foo({});
+}
+
 namespace PR52073 {
 // OK, these are distinct functions not redefinitions.
 template void f(decltype([]{})) {} // expected-note {{candidate}}
@@ -40,6 +61,62 @@
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 // FIXME: We instantiate the lambdas into the context of the function template,
-// so we think they're dependent and can't evaluate a call to them.
+//  so we think they're dependent and can't evaluate a call to them.
 void use_g() { g<6>(&"hello"); } // expected-error {{no matching function}}
 }
+
+namespace GH51416 {
+
+template 
+struct A {
+  void spam(decltype([] {}));
+};
+
+template 
+void A::spam(decltype([] {})) // expected-error{{out-of-line definition of 'spam' does not match}}
+{}
+
+struct B {
+  template 
+  void spam(decltype([] {}));
+};
+
+template 
+void B::spam(decltype([] {})) {} // expected-error{{out-of-line definition of 'spam' does not match}}
+
+} // namespace GH51416
+
+namespace GH50376 {
+
+template 
+struct foo_t {// expected-note 2{{candidate constructor}}
+  foo_t(T ptr) {} // expected-note{{candidate constructor}}
+};
+
+template 
+using alias = foo_t;
+
+template 
+auto fun(T const ) -> alias {
+  return alias{t}; // expected-error{{no viable conversion from returned value of type 'alias<...>'}}
+}
+
+void f() {
+  int i;
+  auto const error = fun(i); // expected-note{{in instantiation}}
+}
+
+} // namespace GH50376
+
+namespace GH51414 {
+template  void spam(decltype([] {}) (*s)[sizeof(T)] = nullptr) {}
+void foo() {
+  spam();
+}
+} // namespace GH51414
+
+namespace GH51641 {
+template 
+void foo(decltype(+[](T) {}) lambda, T param);
+static_assert(!__is_same(decltype(foo), void));
+} // namespace GH51641
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -5733,7 +5733,7 @@
   // Add lambda-specific data.
   if (Data.IsLambda) {
 auto  = D->getLambdaData();
-Record->push_back(Lambda.Dependent);
+Record->push_back(Lambda.DependencyKind);
 Record->push_back(Lambda.IsGenericLambda);
 Record->push_back(Lambda.CaptureDefault);
 

[clang] 3784e8c - [Clang] Fix Unevaluated Lambdas

2022-03-25 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2022-03-25T19:16:45+01:00
New Revision: 3784e8ccfbdaaab31f9e9c221daa59a21827

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

LOG: [Clang] Fix Unevaluated Lambdas

Unlike other types, when lambdas are instanciated,
they are recreated from scratch.
When an unevaluated lambdas appear in the type of a function,
parameter it is instanciated in the wrong declaration context,
as parameters are transformed before the function.

To support lambda in function parameters, we try to
compute whether they are dependant without looking at the
declaration context.

This is a short term stopgap solution to avoid clang
iceing. A better fix might be to inject some kind of
transparent declaration with correctly computed dependency
for function parameters, variable templates, etc.

Fixes https://github.com/llvm/llvm-project/issues/50376
Fixes https://github.com/llvm/llvm-project/issues/51414
Fixes https://github.com/llvm/llvm-project/issues/51416
Fixes https://github.com/llvm/llvm-project/issues/51641
Fixes https://github.com/llvm/llvm-project/issues/54296

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D121532

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/DeclCXX.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/AST/DeclCXX.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/test/SemaCXX/lambda-unevaluated.cpp
clang/unittests/AST/ASTImporterTest.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 58523c2569283..39499b79e34d4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -83,6 +83,14 @@ Bug Fixes
   per identifier.
   Fixes `Issue 28985 `_.
 
+- Unevaluated lambdas in dependant contexts no longer result in clang crashing.
+  This fixes Issues `50376 < 
https://github.com/llvm/llvm-project/issues/50376>`_,
+  `54296 < https://github.com/llvm/llvm-project/issues/54296>`_,
+  `51414 < https://github.com/llvm/llvm-project/issues/51414>`_,
+  `51416 < https://github.com/llvm/llvm-project/issues/51416>`_,
+  and `51641 < https://github.com/llvm/llvm-project/issues/51641>`_.
+
+
 Improvements to Clang's diagnostics
 ^^^
 - ``-Wliteral-range`` will warn on floating-point equality comparisons with

diff  --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 2833df0505dac..545f29975fd89 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -275,6 +275,14 @@ class CXXRecordDecl : public RecordDecl {
 SMF_All = 0x3f
   };
 
+public:
+  enum LambdaDependencyKind {
+LDK_Unknown = 0,
+LDK_AlwaysDependent,
+LDK_NeverDependent,
+  };
+
+private:
   struct DefinitionData {
 #define FIELD(Name, Width, Merge) \
 unsigned Name : Width;
@@ -374,7 +382,7 @@ class CXXRecordDecl : public RecordDecl {
 /// lambda will have been created with the enclosing context as its
 /// declaration context, rather than function. This is an unfortunate
 /// artifact of having to parse the default arguments before.
-unsigned Dependent : 1;
+unsigned DependencyKind : 2;
 
 /// Whether this lambda is a generic lambda.
 unsigned IsGenericLambda : 1;
@@ -408,9 +416,9 @@ class CXXRecordDecl : public RecordDecl {
 /// The type of the call method.
 TypeSourceInfo *MethodTyInfo;
 
-LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool 
Dependent,
+LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, unsigned DK,
  bool IsGeneric, LambdaCaptureDefault CaptureDefault)
-: DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
+: DefinitionData(D), DependencyKind(DK), IsGenericLambda(IsGeneric),
   CaptureDefault(CaptureDefault), NumCaptures(0),
   NumExplicitCaptures(0), HasKnownInternalLinkage(0), 
ManglingNumber(0),
   MethodTyInfo(Info) {
@@ -547,7 +555,7 @@ class CXXRecordDecl : public RecordDecl {
bool DelayTypeCreation = false);
   static CXXRecordDecl *CreateLambda(const ASTContext , DeclContext *DC,
  TypeSourceInfo *Info, SourceLocation Loc,
- bool DependentLambda, bool IsGeneric,
+ unsigned DependencyKind, bool IsGeneric,
   

[PATCH] D120185: [ASTMatchers] Output currently processing match and nodes on crash

2022-03-25 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I've landed it and your build bot is happy, there was another failing buildbot 
so I'll keep an eye on it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120185/new/

https://reviews.llvm.org/D120185

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


[clang] 171cdba - [Clang, TBAA] Use pattern for metadata reference in test.

2022-03-25 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2022-03-25T18:12:39Z
New Revision: 171cdba8674f05bc9b97b6d194911292d4a73731

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

LOG: [Clang,TBAA] Use pattern for metadata reference in test.

Update the single check line that still had a hard-coded metadata
reference. This makes it more robust to slight changes in the metadata
numbering.

Added: 


Modified: 
clang/test/CodeGen/tbaa.cpp

Removed: 




diff  --git a/clang/test/CodeGen/tbaa.cpp b/clang/test/CodeGen/tbaa.cpp
index 554daf875b5b5..02dbd87452b93 100644
--- a/clang/test/CodeGen/tbaa.cpp
+++ b/clang/test/CodeGen/tbaa.cpp
@@ -281,7 +281,7 @@ uint32_t g15(StructS *S, StructS3 *S3, uint64_t count) {
 // NEW-PATH-DAG: [[TYPE_short:!.*]] = !{[[TYPE_char]], i64 2, !"short"}
 // NEW-PATH-DAG: [[TYPE_int:!.*]] = !{[[TYPE_char]], i64 4, !"int"}
 // NEW-PATH-DAG: [[TAG_i32:!.*]] = !{[[TYPE_int]], [[TYPE_int]], i64 0, i64 4}
-// NEW-PATH-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 16, !"_ZTS7StructA", 
[[TYPE_short]], i64 0, i64 2, [[TYPE_int]], i64 4, i64 4, !12, i64 8, i64 2, 
[[TYPE_int]], i64 12, i64 4}
+// NEW-PATH-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 16, !"_ZTS7StructA", 
[[TYPE_short]], i64 0, i64 2, [[TYPE_int]], i64 4, i64 4, [[TYPE_short]], i64 
8, i64 2, [[TYPE_int]], i64 12, i64 4}
 // NEW-PATH-DAG: [[TAG_A_f16]] = !{[[TYPE_A]], [[TYPE_short]], i64 0, i64 2}
 // NEW-PATH-DAG: [[TAG_A_f32]] = !{[[TYPE_A]], [[TYPE_int]], i64 4, i64 4}
 // NEW-PATH-DAG: [[TYPE_B:!.*]] = !{[[TYPE_char]], i64 24, !"_ZTS7StructB", 
[[TYPE_short]], i64 0, i64 2, [[TYPE_A]], i64 4, i64 16, [[TYPE_int]], i64 20, 
i64 4}



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


[PATCH] D122344: [clang][driver] Disable non-functional --version option for clang -cc1

2022-03-25 Thread Emil Kieri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG35b89bc24ca5: [clang][driver] Disable non-functional 
--version option for clang -cc1 (authored by ekieri).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122344/new/

https://reviews.llvm.org/D122344

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Frontend/unknown-arg.c


Index: clang/test/Frontend/unknown-arg.c
===
--- clang/test/Frontend/unknown-arg.c
+++ clang/test/Frontend/unknown-arg.c
@@ -4,6 +4,9 @@
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
 // RUN: not %clang %s -E -Xclang --hel[ 2>&1 | \
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
+// RUN: not %clang_cc1 --version 2>&1 | \
+// RUN: FileCheck %s --check-prefix=DID-YOU-MEAN-VER
 
 // CHECK: error: unknown argument: '--helium'
 // DID-YOU-MEAN: error: unknown argument '--hel['; did you mean '--help'?
+// DID-YOU-MEAN-VER: error: unknown argument '--version'; did you mean 
'-version'?
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4203,7 +4203,7 @@
   HelpText<"Serialize compiler diagnostics to a file">;
 // We give --version different semantics from -version.
 def _version : Flag<["--"], "version">,
-  Flags<[CoreOption, CC1Option, FC1Option, FlangOption]>,
+  Flags<[CoreOption, FC1Option, FlangOption]>,
   HelpText<"Print version information">;
 def _signed_char : Flag<["--"], "signed-char">, Alias;
 def _std : Separate<["--"], "std">, Alias;


Index: clang/test/Frontend/unknown-arg.c
===
--- clang/test/Frontend/unknown-arg.c
+++ clang/test/Frontend/unknown-arg.c
@@ -4,6 +4,9 @@
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
 // RUN: not %clang %s -E -Xclang --hel[ 2>&1 | \
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
+// RUN: not %clang_cc1 --version 2>&1 | \
+// RUN: FileCheck %s --check-prefix=DID-YOU-MEAN-VER
 
 // CHECK: error: unknown argument: '--helium'
 // DID-YOU-MEAN: error: unknown argument '--hel['; did you mean '--help'?
+// DID-YOU-MEAN-VER: error: unknown argument '--version'; did you mean '-version'?
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4203,7 +4203,7 @@
   HelpText<"Serialize compiler diagnostics to a file">;
 // We give --version different semantics from -version.
 def _version : Flag<["--"], "version">,
-  Flags<[CoreOption, CC1Option, FC1Option, FlangOption]>,
+  Flags<[CoreOption, FC1Option, FlangOption]>,
   HelpText<"Print version information">;
 def _signed_char : Flag<["--"], "signed-char">, Alias;
 def _std : Separate<["--"], "std">, Alias;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 35b89bc - [clang][driver] Disable non-functional --version option for clang -cc1

2022-03-25 Thread Emil Kieri via cfe-commits

Author: Emil Kieri
Date: 2022-03-25T19:04:27+01:00
New Revision: 35b89bc24ca58d5b3a87578f69936afb26ef3b69

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

LOG: [clang][driver] Disable non-functional --version option for clang -cc1

This patch removes --version as a clang -cc1 option.
  clang --version
and
  clang --cc1 -version
remain valid. This behaviour is consistent with clang -cc1as.

Previously, clang -cc1 accepted both --version and -version, but
only -version was acted upon. The call
  clang -cc1 --version
stalled without any message: --version was an accepted option but
triggered no action, and the driver waited for standard input.

Reviewed By: thakis

Differential Revision: https://reviews.llvm.org/D122344

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/test/Frontend/unknown-arg.c

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 784751a1a6863..488692e16145f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4203,7 +4203,7 @@ def _serialize_diags : Separate<["-", "--"], 
"serialize-diagnostics">, Flags<[No
   HelpText<"Serialize compiler diagnostics to a file">;
 // We give --version 
diff erent semantics from -version.
 def _version : Flag<["--"], "version">,
-  Flags<[CoreOption, CC1Option, FC1Option, FlangOption]>,
+  Flags<[CoreOption, FC1Option, FlangOption]>,
   HelpText<"Print version information">;
 def _signed_char : Flag<["--"], "signed-char">, Alias;
 def _std : Separate<["--"], "std">, Alias;

diff  --git a/clang/test/Frontend/unknown-arg.c 
b/clang/test/Frontend/unknown-arg.c
index eb2fb1aee2dd5..74a6c842da908 100644
--- a/clang/test/Frontend/unknown-arg.c
+++ b/clang/test/Frontend/unknown-arg.c
@@ -4,6 +4,9 @@
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
 // RUN: not %clang %s -E -Xclang --hel[ 2>&1 | \
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
+// RUN: not %clang_cc1 --version 2>&1 | \
+// RUN: FileCheck %s --check-prefix=DID-YOU-MEAN-VER
 
 // CHECK: error: unknown argument: '--helium'
 // DID-YOU-MEAN: error: unknown argument '--hel['; did you mean '--help'?
+// DID-YOU-MEAN-VER: error: unknown argument '--version'; did you mean 
'-version'?



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


[PATCH] D121951: [AMDGPU][OpenCL] Add "amdgpu-no-hostcall-ptr" in Clang codegen pre-COV_5

2022-03-25 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9381
+  M.getTarget().getTargetOpts().CodeObjectVersion != 500) {
+F->addFnAttr("amdgpu-no-hostcall-ptr");
+  }

arsenm wrote:
> sameerds wrote:
> > The frontend does not need to worry about this attribute. See the comment 
> > in the MetadataStreamer. A worthwhile check would be to generate an error 
> > if we are able to detect that some hostcall service is being used in OpenCL 
> > on code-object-v4 or lower. None exists right now, but we should add the 
> > check if such services show up. But those checks are likely to be in a 
> > different place. For example, enabling asan on OpenCL for code-object-v4 
> > should result in an error in the place where asan commandline options are 
> > parsed.
> Should be all opencl, not just kernels. Also < instead of !=?
> The frontend does not need to worry about this attribute. See the comment in 
> the MetadataStreamer. 

The reason I went this route is that otherwise the MetadataStreamer can only go 
off of the presence of the OCL printf metadata to infer that hostcall argument 
metadata is invalid and will be ignored by the runtime. Ideally, the 
MetadataStreamer or Verifier or something would actually //require// that a 
module does not have both OCL printf metadata and functions which are not 
"amdgpu-no-hostcall-ptr", but I didn't go that far as it would break old 
IR/bitcode that relies on the implicit behavior.

I'm OK with removing this code, and the rest of the patch remains essentially 
unchanged. We will still have an implicit rule based on code-object-version and 
presence of printf metadata, and at least conceptually you will still be able 
to compile OCL for pre-V5 and end up with hostcall argument metadata. That case 
is benign if the runtime just ignores it, but it still seems needlessly relaxed 
when we can just add the correct attribute in Clang codegen.

> Should be all opencl, not just kernels. Also < instead of !=?

Yes, my mistake, I'll update this



Comment at: llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp:406-408
 if (Func.getParent()->getNamedMetadata("llvm.printf.fmts"))
   emitKernelArg(DL, Int8PtrTy, Align(8), ValueKind::HiddenPrintfBuffer);
+else if (!Func.hasFnAttribute("amdgpu-no-hostcall-ptr"))

sameerds wrote:
> I would structure this differently: If this is code-object-v4 or lower, then 
> if  "llvm.printf.fmts" is present, then this kernel clearly contains OpenCL 
> bits, and cannot use hostcall. So it's okay to just assume that the 
> no-hostcall-ptr attribute is always present in this situation, which means 
> the only metadata generated is for ValueKind::HiddenPrintfBuffer. Else if 
> this is code-object-v5, then proceed to emit both metadata.
> 
> 
I'm not sure I follow; doesn't the code as-is implement what you're describing?

If the printf metadata is present, this will only ever emit the 
`HiddenPrintfBuffer`, irrespective of the hostcall attribute. Otherwise, this 
respects `amdgpu-no-hostcall-ptr` (i.e. for HIP and other languages).

The "if this is code-object-v4 or lower" portion is implicit, as this is just 
the `MetadataStreamerV2` impl. The `MetadataStreamerV3` (below) and 
`MetadataStreamerV4` (inherits from V3) impls below are similar. The 
`MetadataStreamerV5` impl is already correct for V5 (i.e. supports both 
argument kinds for the same kernel).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121951/new/

https://reviews.llvm.org/D121951

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


[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Tom Stellard via Phabricator via cfe-commits
tstellar accepted this revision.
tstellar added a comment.
This revision is now accepted and ready to land.

In D122487#3408425 , @rs wrote:

> @tstellar thanks for the review. I can't really think of any other way to 
> test this. I'll wait till Monday if no one else has suggested anything else 
> then I'll commit it. Thanks again.

OK, sounds good.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122487/new/

https://reviews.llvm.org/D122487

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


[clang] b97f260 - Reland "[ASTMatchers] Output currently processing match and nodes on crash"

2022-03-25 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-25T17:53:58Z
New Revision: b97f26083bd04ccbdd63b0c726e047496e5b847a

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

LOG: Reland "[ASTMatchers] Output currently processing match and nodes on crash"

This reverts commit cff34ccb605aa78030cd51cfe44362ed1c1fb80b.

This relands commit d89f9e963e4979466193dc6a15fe091bf7ca5c47

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b54fca707eda8..282cf1d0a4cc1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,6 +96,9 @@ The improvements are...
 Improvements to clang-tidy
 --
 
+- Added trace code to help narrow down any checks and the relevant source code
+  that result in crashes.
+
 New checks
 ^^
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index b19a7fe3be04c..70598460151ae 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Timer.h"
 #include 
 #include 
@@ -760,11 +761,67 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+  class TraceReporter : llvm::PrettyStackTraceEntry {
+  public:
+TraceReporter(const MatchASTVisitor ) : MV(MV) {}
+void print(raw_ostream ) const override {
+  if (!MV.CurMatched) {
+OS << "ASTMatcher: Not currently matching\n";
+return;
+  }
+  assert(MV.ActiveASTContext &&
+ "ActiveASTContext should be set if there is a matched callback");
+
+  OS << "ASTMatcher: Processing '" << MV.CurMatched->getID() << "'\n";
+  const BoundNodes::IDToNodeMap  = MV.CurBoundNodes->getMap();
+  if (Map.empty()) {
+OS << "No bound nodes\n";
+return;
+  }
+  OS << "--- Bound Nodes Begin ---\n";
+  for (const auto  : Map) {
+OS << "" << Item.first << " - { ";
+if (const auto *D = Item.second.get()) {
+  OS << D->getDeclKindName() << "Decl ";
+  if (const auto *ND = dyn_cast(D)) {
+ND->printQualifiedName(OS);
+OS << " : ";
+  } else
+OS << ": ";
+  D->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *S = Item.second.get()) {
+  OS << S->getStmtClassName() << " : ";
+  S->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *T = Item.second.get()) {
+  OS << T->getTypeClassName() << "Type : ";
+  QualType(T, 0).print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else if (const auto *QT = Item.second.get()) {
+  OS << "QualType : ";
+  QT->print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else {
+  OS << Item.second.getNodeKind().asStringRef() << " : ";
+  Item.second.getSourceRange().print(
+  OS, MV.ActiveASTContext->getSourceManager());
+}
+OS << " }\n";
+  }
+  OS << "--- Bound Nodes End ---\n";
+}
+
+  private:
+const MatchASTVisitor 
+  };
+
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
+  const MatchCallback *CurMatched = nullptr;
+  const BoundNodes *CurBoundNodes = nullptr;
+
   struct ASTNodeNotSpelledInSourceScope {
 ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
 : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
@@ -831,7 +888,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Timer.setBucket([MP.second->getID()]);
   BoundNodesTreeBuilder Builder;
   if (MP.first.matches(Node, this, )) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches();
   }
 }
@@ -863,7 +920,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   }
 
   if (MP.first.matches(DynNode, this, )) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches();
   }
 }
@@ -1049,18 +1106,36 @@ class MatchASTVisitor : 

[PATCH] D121591: [C++20][Modules][Driver][HU 4/N] Add fdirectives-only mode for preprocessing output.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418274.
iains added a comment.
Herald added a subscriber: MaskRay.

rebased, adjusted testcases to avoid using clang++.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121591/new/

https://reviews.llvm.org/D121591

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cxx20-fdirectives-only.cpp


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4618,6 +4618,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_back("-P");
+  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
+CmdArgs.push_back("-fdirectives-only");
 }
   } else if (isa(JA)) {
 CmdArgs.push_back("-emit-obj");
@@ -6769,6 +6771,10 @@
   if (RewriteImports)
 CmdArgs.push_back("-frewrite-imports");
 
+  if (Args.hasFlag(options::OPT_fdirectives_only,
+   options::OPT_fno_directives_only, false))
+CmdArgs.push_back("-fdirectives-only");
+
   // Enable rewrite includes if the user's asked for it or if we're generating
   // diagnostics.
   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4279,10 +4279,14 @@
   OutputTy = types::TY_Dependencies;
 } else {
   OutputTy = Input->getType();
+  // For these cases, the preprocessor is only translating forms, the 
Output
+  // still needs preprocessing.
   if (!Args.hasFlag(options::OPT_frewrite_includes,
 options::OPT_fno_rewrite_includes, false) &&
   !Args.hasFlag(options::OPT_frewrite_imports,
 options::OPT_fno_rewrite_imports, false) &&
+  !Args.hasFlag(options::OPT_fdirectives_only,
+options::OPT_fno_directives_only, false) &&
   !CCGenDiagnostics)
 OutputTy = types::getPreprocessedType(OutputTy);
   assert(OutputTy != types::TY_INVALID &&


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4618,6 +4618,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_back("-P");
+  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
+CmdArgs.push_back("-fdirectives-only");
 }
   } else if (isa(JA)) {
 CmdArgs.push_back("-emit-obj");
@@ -6769,6 +6771,10 @@
   if (RewriteImports)
 CmdArgs.push_back("-frewrite-imports");
 
+  if (Args.hasFlag(options::OPT_fdirectives_only,
+   options::OPT_fno_directives_only, false))
+CmdArgs.push_back("-fdirectives-only");
+
   // Enable rewrite includes if the 

[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision as: aaron.ballman.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121532/new/

https://reviews.llvm.org/D121532

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


[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp:569
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;

MaskRay wrote:
> https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements
> 
> That said, nested if is usually written as a single if with `&&`
Thanks for the tip @MaskRay, and I'm going to fix that in a following patch. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122336/new/

https://reviews.llvm.org/D122336

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


[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Ranjeet Singh via Phabricator via cfe-commits
rs added a comment.

@tstellar thanks for the review. I can't really think of any other way to test 
this. I'll wait till Monday if no one else has suggested anything else then 
I'll commit it. Thanks again.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122487/new/

https://reviews.llvm.org/D122487

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


[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp:569
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;

https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements

That said, nested if is usually written as a single if with `&&`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122336/new/

https://reviews.llvm.org/D122336

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


  1   2   >