[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-08-08 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

In D152495#4566634 , @aaron.ballman 
wrote:

> In D152495#4563520 , @hazohelet 
> wrote:
>
>> I reverted this change because it broke sanitizer buildbots.
>> https://lab.llvm.org/buildbot/#/builders/19/builds/18369
>> The cause of the errors here are relatively clear and I can speculatively 
>> replace `if (std::error_code EC = makeCanonical(Path))` with `if 
>> (makeCanonical(Path))`
>
> That changes makes sense to me.
>
>> https://lab.llvm.org/buildbot/#/builders/94/builds/15865
>> https://lab.llvm.org/buildbot/#/builders/240/builds/12947
>> These 2 are not clear for me, so I'll take time to find the cause.
>
> Neither of these are problems with your patch -- they're flaky tests in this 
> case.

Thanks! I'll reland this patch with the unused `std::error_code` fix. I'll 
revert again if the same CI keeps failing for a few hours.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152495

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


[PATCH] D152054: [OpenMP] Codegen support for thread_limit on target directive

2023-08-08 Thread Sandeep via Phabricator via cfe-commits
sandeepkosuri updated this revision to Diff 548082.
sandeepkosuri added a comment.

- Updated `SemaOpenMP.cpp` to support `thread_limit` clause on the newly 
allowed directives.

- This update is to fix the newly added LIT tests' failures (which were 
occurring only on debug build)


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

https://reviews.llvm.org/D152054

Files:
  clang/include/clang/Basic/OpenMPKinds.h
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_for_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_generic_loop_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_tl_codegen.cpp
  clang/test/OpenMP/target_simd_tl_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  openmp/runtime/src/kmp.h
  openmp/runtime/src/kmp_csupport.cpp
  openmp/runtime/src/kmp_ftn_entry.h
  openmp/runtime/src/kmp_global.cpp
  openmp/runtime/src/kmp_runtime.cpp
  openmp/runtime/test/target/target_thread_limit.cpp

Index: openmp/runtime/test/target/target_thread_limit.cpp
===
--- /dev/null
+++ openmp/runtime/test/target/target_thread_limit.cpp
@@ -0,0 +1,168 @@
+// RUN: %libomp-cxx-compile -fopenmp-version=51
+// RUN: %libomp-run | FileCheck %s --check-prefix OMP51
+
+#include 
+#include 
+
+void foo() {
+#pragma omp parallel num_threads(10)
+  { printf("\ntarget: foo(): parallel num_threads(10)"); }
+}
+
+int main(void) {
+
+  int tl = 4;
+  printf("\nmain: thread_limit = %d", omp_get_thread_limit());
+  // OMP51: main: thread_limit = {{[0-9]+}}
+
+#pragma omp target thread_limit(tl)
+  {
+printf("\ntarget: thread_limit = %d", omp_get_thread_limit());
+// OMP51: target: thread_limit = 4
+// check whether thread_limit is honoured
+#pragma omp parallel
+{ printf("\ntarget: parallel"); }
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51-NOT: target: parallel
+
+// check whether num_threads is honoured
+#pragma omp parallel num_threads(2)
+{ printf("\ntarget: parallel num_threads(2)"); }
+// OMP51: target: parallel num_threads(2)
+// OMP51: target: parallel num_threads(2)
+// OMP51-NOT: target: parallel num_threads(2)
+
+// check whether thread_limit is honoured when there is a conflicting
+// num_threads
+#pragma omp parallel num_threads(10)
+{ printf("\ntarget: parallel num_threads(10)"); }
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51-NOT: target: parallel num_threads(10)
+
+// check whether threads are limited across functions
+foo();
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51-NOT: target: foo(): parallel num_threads(10)
+
+// check if user can set num_threads at runtime
+omp_set_num_threads(2);
+#pragma omp parallel
+{ printf("\ntarget: parallel with omp_set_num_thread(2)"); }
+// OMP51: target: parallel with omp_set_num_thread(2)
+// OMP51: target: parallel with omp_set_num_thread(2)
+// OMP51-NOT: target: parallel with omp_set_num_thread(2)
+
+// make sure thread_limit is unaffected by omp_set_num_threads
+printf("\ntarget: thread_limit = %d", omp_get_thread_limit());
+// OMP51: target: thread_limit = 4
+  }
+
+// checking consecutive target regions with different thread_limits
+#pragma omp target thread_limit(3)
+  {
+printf("\nsecond target: thread_limit = %d", omp_get_thread_limit());
+// OMP51: second target: thread_limit = 3
+#pragma omp parallel
+{ printf("\nsecond target: parallel"); }
+// OMP51: second target: parallel
+// OMP51: second target: parallel
+// OMP51: second target: parallel
+// OMP51-NOT: second target: parallel
+  }
+
+  // confirm that thread_limit's effects are limited to target region
+  printf("\nmain: thread_limit = %d", omp_get_thread_limit());
+  // OMP51: main: thread_limit = {{[0-9]+}}
+#pragma omp parallel num_threads(10)
+  { printf("\nmain: parallel num_threads(10)"); }
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_

[PATCH] D157367: [clang-tidy] Ignore delegate constructors in cppcoreguidelines-pro-type-member-init

2023-08-08 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
PiotrZSL added reviewers: carlosgalvezp, njames93, ccotter.
Herald added subscribers: shchenz, kbarton, xazax.hun, nemanjai.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Ignore dependend delegate constructors.

Fixes: #37250


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157367

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -372,8 +372,7 @@
 class PositiveSelfInitialization : NegativeAggregateType
 {
   PositiveSelfInitialization() : PositiveSelfInitialization() {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these bases: NegativeAggregateType
-  // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), 
PositiveSelfInitialization() {}
+  // This will be detected by -Wdelegating-ctor-cycles and there is no proper 
way to fix this
 };
 
 class PositiveIndirectMember {
@@ -579,3 +578,42 @@
 int C = 0;
   };
 };
+
+// Ignore issues from delegate constructors
+namespace PR37250 {
+  template 
+  struct A {
+A() : A(42) {}
+explicit A(int value) : value_(value) {}
+int value_;
+  };
+
+  struct B {
+B() : B(42) {}
+explicit B(int value) : value_(value) {}
+int value_;
+  };
+
+  template 
+  struct C {
+C() : C(T()) {}
+explicit C(T value) : value_(value) {}
+T value_;
+  };
+
+  struct V {
+unsigned size() const;
+  };
+
+  struct S {
+unsigned size_;
+
+S(unsigned size) : size_{size} {}
+
+template
+S(const U& u) : S(u.size()) {}
+  };
+
+  const V v;
+  const S s{v};
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-member-init
+  ` check to ignore
+  dependent delegate constructors.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -281,8 +281,14 @@
 
 void ProTypeMemberInitCheck::registerMatchers(MatchFinder *Finder) {
   auto IsUserProvidedNonDelegatingConstructor =
-  allOf(isUserProvided(),
-unless(anyOf(isInstantiated(), isDelegatingConstructor(;
+  allOf(isUserProvided(), unless(isInstantiated()),
+unless(isDelegatingConstructor()),
+ofClass(cxxRecordDecl().bind("parent")),
+unless(hasAnyConstructorInitializer(cxxCtorInitializer(
+isWritten(), unless(isMemberInitializer()),
+hasTypeLoc(loc(
+qualType(hasDeclaration(equalsBoundNode("parent");
+
   auto IsNonTrivialDefaultConstructor = allOf(
   isDefaultConstructor(), unless(isUserProvided()),
   hasParent(cxxRecordDecl(unless(isTriviallyDefaultConstructible();


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -372,8 +372,7 @@
 class PositiveSelfInitialization : NegativeAggregateType
 {
   PositiveSelfInitialization() : PositiveSelfInitialization() {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these bases: NegativeAggregateType
-  // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), PositiveSelfInitialization() {}
+  // This will be detected by -Wdelegating-ctor-cycles and there is no proper way to fix this
 };
 
 class PositiveIndirectMember {
@@ -579,3 +578,42 @@
 int C = 0;
   };
 };
+
+// Ignore issues from delegate constructors
+namespace PR37250 {
+  template 
+  struct A {
+A() : A(42) {}
+explicit A(int value) : value_(value) {}
+int value_;
+  };
+
+  struct B {
+B() : B(42) {}
+explicit B(int value) : value_

[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-08 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/AST/DeclCXX.cpp:841
   const auto *ParamTy =
-  Method->getParamDecl(0)->getType()->getAs();
+  Method->getNonObjectParameter(0)->getType()->getAs();
   if (!ParamTy || ParamTy->getPointeeType().isConstQualified())

cor3ntin wrote:
> aaron.ballman wrote:
> > Under what circumstances should existing calls to `getParamDecl()` be 
> > converted to using `getNonObjectParameter()` instead? Similar for 
> > `getNumParams()`.
> everytime you want to ignore (or handle differently) the explicit object 
> parameter. I'll do another survey at some point, to be sure i didn't miss a 
> spot
I found a bug https://github.com/cplusplus/CWG/issues/390 ! 
(`AreSpecialMemberFunctionsSameKind`) - So far nothing else but I'll do several 
passes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D154093: [clang-format] Break long string literals in C#, etc.

2023-08-08 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

I'm ok with this if @owenpan is


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154093

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


[clang] 28b5f30 - [Clang][AArch64] Add/implement ACLE keywords for SME.

2023-08-08 Thread Sander de Smalen via cfe-commits

Author: Sander de Smalen
Date: 2023-08-08T07:00:59Z
New Revision: 28b5f3087a3fcd39c80e2b1470a950da17e4cd08

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

LOG: [Clang][AArch64] Add/implement ACLE keywords for SME.

This patch adds all the language-level function keywords defined in:

  https://github.com/ARM-software/acle/pull/188 (merged)
  https://github.com/ARM-software/acle/pull/261 (update after D148700 landed)

The keywords are used to control PSTATE.ZA and PSTATE.SM, which are
respectively used for enabling the use of the ZA matrix array and Streaming
mode. This information needs to be available on call sites, since the use
of ZA or streaming mode may have to be enabled or disabled around the
call-site (depending on the IR attributes set on the caller and the
callee). For calls to functions from a function pointer, there is no IR
declaration available, so the IR attributes must be added explicitly to the
call-site.

With the exception of '__arm_locally_streaming' and '__arm_new_za' the
information is part of the function's interface, not just the function
definition, and thus needs to be propagated through the
FunctionProtoType::ExtProtoInfo.

This patch adds the defintions of these keywords, as well as codegen and
semantic analysis to ensure conversions between function pointers are valid
and that no conflicting keywords are set. For example, '__arm_streaming'
and '__arm_streaming_compatible' are mutually exclusive.

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

Added: 
clang/test/AST/ast-dump-sme-attributes.cpp
clang/test/CodeGen/aarch64-sme-intrinsics/aarch64-sme-attrs.cpp
clang/test/Modules/aarch64-sme-keywords.cppm
clang/test/Sema/aarch64-sme-func-attrs.c

Modified: 
clang/include/clang/AST/Type.h
clang/include/clang/AST/TypeProperties.td
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/Type.cpp
clang/lib/AST/TypePrinter.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 7526ec8906a32c..79badb47d181e5 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -3968,6 +3968,19 @@ class FunctionType : public Type {
   /// because TrailingObjects cannot handle repeated types.
   struct ExceptionType { QualType Type; };
 
+  /// The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number
+  /// of function type attributes that can be set on function types, including
+  /// function pointers.
+  enum AArch64SMETypeAttributes : unsigned {
+SME_NormalFunction = 0,
+SME_PStateSMEnabledMask = 1 << 0,
+SME_PStateSMCompatibleMask = 1 << 1,
+SME_PStateZASharedMask = 1 << 2,
+SME_PStateZAPreservedMask = 1 << 3,
+SME_AttributeMask = 0b111'111 // We only support maximum 6 bits because of 
the
+  // bitmask in FunctionTypeExtraBitfields.
+  };
+
   /// A simple holder for various uncommon bits which do not fit in
   /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
   /// alignment of subsequent objects in TrailingObjects.
@@ -3975,7 +3988,13 @@ class FunctionType : public Type {
 /// The number of types in the exception specification.
 /// A whole unsigned is not needed here and according to
 /// [implimits] 8 bits would be enough here.
-uint16_t NumExceptionType = 0;
+unsigned NumExceptionType : 10;
+
+/// Any AArch64 SME ACLE type attributes that need to be propagated
+/// on declarations and function pointers.
+unsigned AArch64SMEAttributes : 6;
+FunctionTypeExtraBitfields()
+: NumExceptionType(0), AArch64SMEAttributes(SME_NormalFunction) {}
   };
 
 protected:
@@ -4154,18 +4173,22 @@ class FunctionProtoType final
   /// the various bits of extra information about a function prototype.
   struct ExtProtoInfo {
 FunctionType::ExtInfo ExtInfo;
-bool Variadic : 1;
-bool HasTrailingReturn : 1;
+unsigned Variadic : 1;
+unsigned HasTrailingReturn : 1;
+unsigned AArch64SMEAttributes : 6;
 Qualifiers TypeQuals;
 RefQualifierKind RefQualifier = RQ_None;
 ExceptionSpecInfo ExceptionSpec;
 const ExtParameterInfo *ExtParameterInfos = nullptr;
 SourceLocation EllipsisLoc;
 
-ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
+ExtProtoInfo()
+: Variadic(false), HasTrailingReturn(fa

[PATCH] D127762: [Clang][AArch64] Add/implement ACLE keywords for SME.

2023-08-08 Thread Sander de Smalen 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 rG28b5f3087a3f: [Clang][AArch64] Add/implement ACLE keywords 
for SME. (authored by sdesmalen).

Changed prior to commit:
  https://reviews.llvm.org/D127762?vs=547696&id=548086#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127762

Files:
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-dump-sme-attributes.cpp
  clang/test/CodeGen/aarch64-sme-intrinsics/aarch64-sme-attrs.cpp
  clang/test/Modules/aarch64-sme-keywords.cppm
  clang/test/Sema/aarch64-sme-func-attrs.c

Index: clang/test/Sema/aarch64-sme-func-attrs.c
===
--- /dev/null
+++ clang/test/Sema/aarch64-sme-func-attrs.c
@@ -0,0 +1,308 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme -fsyntax-only -verify=expected-cpp -x c++ %s
+
+// Valid attributes
+
+void sme_arm_streaming(void) __arm_streaming;
+void sme_arm_streaming_compatible(void) __arm_streaming_compatible;
+
+__arm_new_za void sme_arm_new_za(void) {}
+void sme_arm_shared_za(void) __arm_shared_za;
+void sme_arm_preserves_za(void) __arm_preserves_za;
+
+__arm_new_za void sme_arm_streaming_new_za(void) __arm_streaming {}
+void sme_arm_streaming_shared_za(void) __arm_streaming __arm_shared_za;
+void sme_arm_streaming_preserves_za(void) __arm_streaming __arm_preserves_za;
+
+__arm_new_za void sme_arm_sc_new_za(void) __arm_streaming_compatible {}
+void sme_arm_sc_shared_za(void) __arm_streaming_compatible __arm_shared_za;
+void sme_arm_sc_preserves_za(void) __arm_streaming_compatible __arm_preserves_za;
+
+void sme_arm_shared_preserves_za(void) __arm_shared_za __arm_preserves_za;
+
+__arm_locally_streaming void sme_arm_locally_streaming(void) { }
+__arm_locally_streaming void sme_arm_streaming_and_locally_streaming(void) __arm_streaming { }
+__arm_locally_streaming void sme_arm_streaming_and_streaming_compatible(void) __arm_streaming_compatible { }
+
+__arm_locally_streaming __arm_new_za void sme_arm_ls_new_za(void) { }
+__arm_locally_streaming void sme_arm_ls_shared_za(void) __arm_shared_za { }
+__arm_locally_streaming void sme_arm_ls_preserves_za(void) __arm_preserves_za { }
+
+// Valid attributes on function pointers
+
+void streaming_ptr(void) __arm_streaming;
+typedef  void (*fptrty1) (void) __arm_streaming;
+fptrty1 call_streaming_func() { return streaming_ptr; }
+
+void streaming_compatible_ptr(void) __arm_streaming_compatible;
+typedef void (*fptrty2) (void) __arm_streaming_compatible;
+fptrty2 call_sc_func() { return streaming_compatible_ptr; }
+
+void shared_za_ptr(void) __arm_shared_za;
+typedef void (*fptrty3) (void) __arm_shared_za;
+fptrty3 call_shared_za_func() { return shared_za_ptr; }
+
+void preserves_za_ptr(void) __arm_preserves_za;
+typedef void (*fptrty4) (void) __arm_preserves_za;
+fptrty4 call_preserve_za_func() { return preserves_za_ptr; }
+
+void shared_preserves_za_ptr(void) __arm_shared_za __arm_preserves_za;
+typedef void (*fptrty5) (void) __arm_shared_za __arm_preserves_za;
+fptrty5 call_shared_preserve_za_func() { return shared_preserves_za_ptr; }
+
+typedef void (*fptrty6) (void);
+fptrty6 cast_nza_func_to_normal() { return sme_arm_new_za; }
+fptrty6 cast_ls_func_to_normal() { return sme_arm_locally_streaming; }
+
+// Invalid attributes
+
+// expected-cpp-error@+4 {{'__arm_streaming_compatible' and '__arm_streaming' are not compatible}}
+// expected-cpp-note@+3 {{conflicting attribute is here}}
+// expected-error@+2 {{'__arm_streaming_compatible' and '__arm_streaming' are not compatible}}
+// expected-note@+1 {{conflicting attribute is here}}
+void streaming_mode(void) __arm_streaming __arm_streaming_compatible;
+
+// expected-cpp-error@+4 {{'__arm_streaming' and '__arm_streaming_compatible' are not compatible}}
+// expected-cpp-note@+3 {{conflicting attribute is here}}
+// expected-error@+2 {{'__arm_streaming' and '__arm_streaming_compatible' are not compatible}}
+// expected-note@+1 {{conflicting attribute is here}}
+void streaming_compatible(void) __arm_streaming_compatible __arm_streaming;
+
+// expected-cpp-error@+2 {{'__arm_new_za' and '__arm_shared_za' are not compatible}}
+// expected-error@+1 {{'__arm_new_za' and '__arm_shared_z

[PATCH] D157362: [RISCV] Add Zicfilp extension.

2023-08-08 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 updated this revision to Diff 548088.
fakepaper56 added a comment.

Also support pseudo instruction lpad.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157362

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/zicfilp-invalid.s
  llvm/test/MC/RISCV/zicfilp-valid.s

Index: llvm/test/MC/RISCV/zicfilp-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfilp-valid.s
@@ -0,0 +1,20 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zicfilp -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zicfilp -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zicfilp < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfilp -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zicfilp < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfilp -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+#
+# RUN: not llvm-mc -triple riscv32 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-ASM-AND-OBJ: auipc zero, 22
+# CHECK-ASM: encoding: [0x17,0x60,0x01,0x00]
+# CHECK-NO-EXT: instruction requires the following: 'Zicfilp' (Landing pad)
+lpad 22
Index: llvm/test/MC/RISCV/zicfilp-invalid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfilp-invalid.s
@@ -0,0 +1,7 @@
+# RUN: not llvm-mc -triple riscv32 -mattr=+experimental-zicfilp -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -mattr=+experimental-zicfilp -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-NO-EXT: immediate must be an integer in the range [0, 1048575]
+lpad 1048576
Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -299,3 +299,6 @@
 
 .attribute arch, "rv32i_xcvbi"
 # CHECK: attribute  5, "rv32i2p1_xcvbi1p0"
+
+.attribute arch, "rv32i_zicfilp0p2"
+# CHECK: attribute  5, "rv32i2p1_zicfilp0p2"
Index: llvm/test/CodeGen/RISCV/attributes.ll
===
--- llvm/test/CodeGen/RISCV/attributes.ll
+++ llvm/test/CodeGen/RISCV/attributes.ll
@@ -86,6 +86,7 @@
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zvfbfmin %s -o - | FileCheck --check-prefixes=CHECK,RV32ZVFBFMIN %s
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zvfbfwma %s -o - | FileCheck --check-prefixes=CHECK,RV32ZVFBFWMA %s
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zacas %s -o - | FileCheck --check-prefix=RV32ZACAS %s
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zicfilp %s -o - | FileCheck --check-prefix=RV32ZICFILP %s
 
 ; RUN: llc -mtriple=riscv64 %s -o - | FileCheck %s
 ; RUN: llc -mtriple=riscv64 -mattr=+m %s -o - | FileCheck --check-prefixes=CHECK,RV64M %s
@@ -174,6 +175,7 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zvfbfmin %s -o - | FileCheck --check-prefixes=CHECK,RV64ZVFBFMIN %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zvfbfwma %s -o - | FileCheck --check-prefixes=CHECK,RV64ZVFBFWMA %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zacas %s -o - | FileCheck --check-prefix=RV64ZACAS %s
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-zicfilp %s -o - | FileCheck --check-prefix=RV64ZICFILP %s
 
 ; CHECK: .attribute 4, 16
 
@@ -262,6 +264,7 @@
 ; RV32ZVFBFMIN: .attribute 5, "rv32i2p1_f2p2_zicsr2p0_zfbfmin0p8_zve32f1p0_zve32x1p0_zvfbfmin0p8_zvl32b1p0"
 ; RV32ZVFBFWMA: .attribute 5, "rv32i2p1_f2p2_zicsr2p0_zfbfmin0p8_zve32f1p0_zve32x1p0_zvfbfmin0p8_zvfbfwma0p8_zvl32b1p0"
 ; RV32ZACAS: .attribute 5, "rv32i2p1_a2p1_zacas1p0"
+; RV32ZICFILP: .attribute 5, "rv32i2p1_zicfilp0p2"
 
 ; RV64M: .attribute 5, "rv64i2p1_m2p0"
 ; RV64ZMMUL: .attribute 5, "rv64i2p1_zmmul1p0"
@@ -349,6 +352,7 @@
 ; RV64ZVFBFMIN: .attribute 5, "rv64i2p1_f2p2_zicsr2p0_zfbfmin0p8_zve32f1p0_zve32x1p0_zvfbfmin0p8_zvl32b1p0"
 ; RV64ZVFBFWMA: .attribute 5, "rv64i2p1_f2p2_zicsr2p0_zfbfmin0p8_zve32f1p0

[clang] 658490a - [OpenMP][OMPD][Doc] Update OMPD implementations details.

2023-08-08 Thread Vignesh Balasubramanian via cfe-commits

Author: Vignesh Balasubramanian
Date: 2023-08-08T13:11:35+05:30
New Revision: 658490abc97a291fc01e463599404f28e2126335

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

LOG: [OpenMP][OMPD][Doc] Update OMPD implementations details.

OMPD is already pushed to LLVM repo through https://reviews.llvm.org/D100181 .
Currently, it supports Openmp 5.0 standard for the host in Linux machines.

Reviewed By: @jdoerfert
Differential Revision: https://reviews.llvm.org/D156878

Added: 


Modified: 
clang/docs/OpenMPSupport.rst

Removed: 




diff  --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index a0ddfb605e658a..adb2391c4af6cb 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -138,7 +138,7 @@ implementation.
 
+--+--+--+---+
 | memory management| allocate directive and allocate clause
   | :good:`done` | r355614,r335952 
  |
 
+--+--+--+---+
-| OMPD | OMPD interfaces   
   | :part:`not upstream` | 
https://github.com/OpenMPToolsInterface/LLVM-openmp/tree/ompd-tests   |
+| OMPD | OMPD interfaces   
   | :part:`done` | https://reviews.llvm.org/D99914   
(Supports only HOST(CPU) and Linux  |
 
+--+--+--+---+
 | OMPT | OMPT interfaces (callback support)
   | :good:`done` | 
  |
 
+--+--+--+---+



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


[PATCH] D156878: [OpenMP][OMPD][Doc] Update the implementation details of OMPD

2023-08-08 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG658490abc97a: [OpenMP][OMPD][Doc] Update OMPD 
implementations details. (authored by Vignesh Balasubramanian 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156878

Files:
  clang/docs/OpenMPSupport.rst


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -138,7 +138,7 @@
 
+--+--+--+---+
 | memory management| allocate directive and allocate clause
   | :good:`done` | r355614,r335952 
  |
 
+--+--+--+---+
-| OMPD | OMPD interfaces   
   | :part:`not upstream` | 
https://github.com/OpenMPToolsInterface/LLVM-openmp/tree/ompd-tests   |
+| OMPD | OMPD interfaces   
   | :part:`done` | https://reviews.llvm.org/D99914   
(Supports only HOST(CPU) and Linux  |
 
+--+--+--+---+
 | OMPT | OMPT interfaces (callback support)
   | :good:`done` | 
  |
 
+--+--+--+---+


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -138,7 +138,7 @@
 +--+--+--+---+
 | memory management| allocate directive and allocate clause   | :good:`done` | r355614,r335952   |
 +--+--+--+---+
-| OMPD | OMPD interfaces  | :part:`not upstream` | https://github.com/OpenMPToolsInterface/LLVM-openmp/tree/ompd-tests   |
+| OMPD | OMPD interfaces  | :part:`done` | https://reviews.llvm.org/D99914   (Supports only HOST(CPU) and Linux  |
 +--+--+--+---+
 | OMPT | OMPT interfaces (callback support)   | :good:`done` |   |
 +--+--+--+---+
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152436: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha.

2023-08-08 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

Why is this checker placed in the "unix" group (instead of e.g. "core")? As far 
as I understand it can check some POSIX-specific functions with a flag (that's 
off by default) but the core functionality checks platform-independent standard 
library functions.

Moreover, if you can, please provide links to some test result examples on open 
source projects (either run some fresh tests or provide links to an earlier 
test run that was running with the same functionality).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152436

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


[PATCH] D157296: [AST][Coroutine] Fix CoyieldExpr missing end loc

2023-08-08 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks for exploring all the options.

For case 1)

> Note that CXXMemberCallExpr 0x55d106716260 > relies on 
> RParenLoc directly. Coroutine is implemented as member call so I think RParen 
> is intended and should exist and be correct.

Yeah, I think this is because we don't have argument, so the getEndLoc 
heuristic 
 
failed, and it returned the RParenLoc which is invalid. This could be fixed by 
adjusting the heuristic there (we fallback to getBeginLoc if the endLoc is 
invalid), but no sure whether it will has any side effect.

for case 2) and 3)

> Note that CXXMemberCallExpr 0x55dcfa09f260  cannot get end loc because 
> no arg exists (but covered by its base).



> This is better, but CXXMemberCallExpr 0x565000382160  'void' still 
> cannot get proper end loc, its base spans , arg also exists 
> but this arg is irrevelant.

Looks like the source range of the `MemberExpr` is not correct in both case 2) 
and 3), I guess this is the culprit, but I think it is a different bug in 
`MemberExpr::getEndLoc` .

  `-MemberExpr 0x55dcfa09f230  '' 
.await_resume 0x55dcfa091bf8
   `-OpaqueValueExpr 0x55dcfa09ef70  
'std::suspend_always':'std::suspend_always' lvalue




Comment at: clang/lib/Sema/SemaCoroutine.cpp:322
+  auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
+  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);
 }

aaron.ballman wrote:
> hokein wrote:
> > Thanks for the fast fix.
> > 
> > Reading the source code here, I'm not sure this is a correct fix (and put 
> > the heuristic here). I assume the `Loc` points the the `co_yield` token 
> > here, passing the `Loc` to the `LParenLoc` and `RParenLoc` parameters seems 
> > wrong to me, there is no `(` and `)` written in the source code here 
> > (because the member call expression is an implicit generated node in the 
> > clang AST), we should pass an invalid source location (`SourceLocation()`).
> > 
> > The `CallExpr::getEndLoc()` has implemented similar 
> > [heuristic](https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Expr.cpp#L1662-L1664)
> >  to handle the case where the RParenLoc is invalid.
> >  passing the Loc to the LParenLoc and RParenLoc parameters seems wrong to me
> 
> FWIW, I thought so as well, but I thought we have the same behavior for 
> `CoreturnExpr` and `CoawaitExpr`. These statements are not really call 
> expressions as far as the AST is concerned, so it's a bit hard to say whether 
> there is a right or wrong answer for where the l- and r-paren locations are 
> for the call.
Agree, the coroutine is a hard case. I was concerned about the 
`MemberCallExpr::getRParenLoc()` API, it returns a valid source location but 
the token it points to is not a `)`, this could lead to subtle bugs in tooling.

since this change is an improvement, I'm fine with the current change.



Comment at: clang/test/AST/coroutine-co_yield-source-range.cpp:4
+
+namespace std {
+template 

nit: use the `test/AST/Inputs/std-coroutine.h` header to avoid repeating the 
boilerplate code. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157296

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


[clang] 38cf47f - [clang] Error on substitution failure within lambda body inside a requires-expression

2023-08-08 Thread via cfe-commits

Author: Podchishchaeva, Mariya
Date: 2023-08-08T01:08:38-07:00
New Revision: 38cf47f037b2504a57ba5673f507241af1d6e19d

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

LOG: [clang] Error on substitution failure within lambda body inside a 
requires-expression

Per CWG 2672 substitution failure within the body of a lambda inside a
requires-expression should be a hard error.

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

Reviewed By: cor3ntin

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/test/CXX/drs/dr26xx.cpp
clang/test/SemaCXX/lambda-unevaluated.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index babade1c70b067..d3757c833ef83a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -157,6 +157,10 @@ Bug Fixes to C++ Support
   (`#35574 _`) and
   (`#27224 _`).
 
+- Clang emits an error on substitution failure within lambda body inside a
+  requires-expression. This fixes:
+  (`#64138 _`).
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 8702e2ca3a1b3b..e7318880af8d3b 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1074,7 +1074,6 @@ std::optional 
Sema::isSFINAEContext() const {
   if (InNonInstantiationSFINAEContext)
 return std::optional(nullptr);
 
-  bool SawLambdaSubstitution = false;
   for (SmallVectorImpl::const_reverse_iterator
  Active = CodeSynthesisContexts.rbegin(),
  ActiveEnd = CodeSynthesisContexts.rend();
@@ -1101,10 +1100,8 @@ std::optional 
Sema::isSFINAEContext() const {
   // A lambda-expression appearing in a function type or a template
   // parameter is not considered part of the immediate context for the
   // purposes of template argument deduction.
-
-  // We need to check parents.
-  SawLambdaSubstitution = true;
-  break;
+  // CWG2672: A lambda-expression body is never in the immediate context.
+  return std::nullopt;
 
 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
@@ -1120,8 +1117,6 @@ std::optional 
Sema::isSFINAEContext() const {
   // We're either substituting explicitly-specified template arguments,
   // deduced template arguments. SFINAE applies unless we are in a lambda
   // expression, see [temp.deduct]p9.
-  if (SawLambdaSubstitution)
-return std::nullopt;
   [[fallthrough]];
 case CodeSynthesisContext::ConstraintSubstitution:
 case CodeSynthesisContext::RequirementInstantiation:

diff  --git a/clang/test/CXX/drs/dr26xx.cpp b/clang/test/CXX/drs/dr26xx.cpp
index e4b6156235ecc0..8dd07b63deb436 100644
--- a/clang/test/CXX/drs/dr26xx.cpp
+++ b/clang/test/CXX/drs/dr26xx.cpp
@@ -150,3 +150,24 @@ static_assert(__is_same(decltype(i), I));
 
 J j = { "ghi" };  // expected-error {{no viable constructor or deduction 
guide}}
 }
+
+namespace dr2672 { // dr2672: 18 open
+template 
+void f(T) requires requires { []() { T::invalid; } (); }; // 
expected-error{{type 'int' cannot be used prior to '::'}}
+  // 
expected-note@-1{{while substituting into a lambda expression here}}
+  // 
expected-note@-2{{in instantiation of requirement here}}
+  // 
expected-note@-3{{while substituting template arguments into constraint 
expression here}}
+void f(...);
+
+template 
+void bar(T) requires requires {
+   decltype([]() -> T {})::foo();
+};
+void bar(...);
+
+void m() {
+  f(0); // expected-note {{while checking constraint satisfaction for template 
'f' required here}}
+// expected-note@-1 {{in instantiation of function template 
specialization}}
+  bar(0);
+}
+}

diff  --git a/clang/test/SemaCXX/lambda-unevaluated.cpp 
b/clang/test/SemaCXX/lambda-unevaluated.cpp
index 179c7327ebdff4..10d4c2228ec9be 100644
--- a/clang/test/SemaCXX/lambda-unevaluated.cpp
+++ b/clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -155,17 +155,24 @@ struct WithFoo { static void foo(); };
 
 template 
 concept lambda_works = requires {
-[]() { T::foo(); };
+[]() { T::foo(); }; // expected-error{{type 'int' cannot be us

[PATCH] D156993: [clang] Error on substitution failure within lambda body inside a requires-expression

2023-08-08 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG38cf47f037b2: [clang] Error on substitution failure within 
lambda body inside a requires… (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156993

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CXX/drs/dr26xx.cpp
  clang/test/SemaCXX/lambda-unevaluated.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -15839,7 +15839,7 @@
 https://cplusplus.github.io/CWG/issues/2672.html";>2672
 open
 Lambda body SFINAE is still required, contrary to intent and note
-Not resolved
+Clang 18
   
   
 https://cplusplus.github.io/CWG/issues/2673.html";>2673
Index: clang/test/SemaCXX/lambda-unevaluated.cpp
===
--- clang/test/SemaCXX/lambda-unevaluated.cpp
+++ clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -155,17 +155,24 @@
 
 template 
 concept lambda_works = requires {
-[]() { T::foo(); };
+[]() { T::foo(); }; // expected-error{{type 'int' cannot be used prior to '::'}}
+// expected-note@-1{{while substituting into a lambda expression here}}
+// expected-note@-2{{in instantiation of requirement here}}
+// expected-note@-4{{while substituting template arguments into constraint expression here}}
 };
 
-static_assert(!lambda_works);
+static_assert(!lambda_works); // expected-note {{while checking the satisfaction of concept 'lambda_works' requested here}}
 static_assert(lambda_works);
 
 template 
-int* func(T) requires requires { []() { T::foo(); }; };
+int* func(T) requires requires { []() { T::foo(); }; }; // expected-error{{type 'int' cannot be used prior to '::'}}
+// expected-note@-1{{while substituting into a lambda expression here}}
+// expected-note@-2{{in instantiation of requirement here}}
+// expected-note@-3{{while substituting template arguments into constraint expression here}}
 double* func(...);
 
-static_assert(__is_same(decltype(func(0)), double*));
+static_assert(__is_same(decltype(func(0)), double*)); // expected-note {{while checking constraint satisfaction for template 'func' required here}}
+  // expected-note@-1 {{in instantiation of function template specialization 'lambda_in_constraints::func'}}
 static_assert(__is_same(decltype(func(WithFoo())), int*));
 
 template 
Index: clang/test/CXX/drs/dr26xx.cpp
===
--- clang/test/CXX/drs/dr26xx.cpp
+++ clang/test/CXX/drs/dr26xx.cpp
@@ -150,3 +150,24 @@
 
 J j = { "ghi" };  // expected-error {{no viable constructor or deduction guide}}
 }
+
+namespace dr2672 { // dr2672: 18 open
+template 
+void f(T) requires requires { []() { T::invalid; } (); }; // expected-error{{type 'int' cannot be used prior to '::'}}
+  // expected-note@-1{{while substituting into a lambda expression here}}
+  // expected-note@-2{{in instantiation of requirement here}}
+  // expected-note@-3{{while substituting template arguments into constraint expression here}}
+void f(...);
+
+template 
+void bar(T) requires requires {
+   decltype([]() -> T {})::foo();
+};
+void bar(...);
+
+void m() {
+  f(0); // expected-note {{while checking constraint satisfaction for template 'f' required here}}
+// expected-note@-1 {{in instantiation of function template specialization}}
+  bar(0);
+}
+}
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1074,7 +1074,6 @@
   if (InNonInstantiationSFINAEContext)
 return std::optional(nullptr);
 
-  bool SawLambdaSubstitution = false;
   for (SmallVectorImpl::const_reverse_iterator
  Active = CodeSynthesisContexts.rbegin(),
  ActiveEnd = CodeSynthesisContexts.rend();
@@ -1101,10 +1100,8 @@
   // A lambda-expression appearing in a function type or a template
   // parameter is not considered part of the immediate context for the
   // purposes of template argument deduction.
-
-  // We need to check parents.
-  SawLambdaSubstitution = true;
-  break;
+  // CWG2672: A lambda-expression body is never in the immediate context.
+  return s

[PATCH] D152436: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha.

2023-08-08 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

This checker was originally in the "unix" package. I agree that this is not 
exact and `core` can be better, the checked functions should be available in 
any default C library on UNIX, OSX, Windows or other platforms too, even the 
POSIX ones at least in some cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152436

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


[clang] cb3136b - [clang] Pass --cuda-path to fix test/Driver/openmp-offload-jit.c

2023-08-08 Thread Jonas Hahnfeld via cfe-commits

Author: Jonas Hahnfeld
Date: 2023-08-08T10:21:55+02:00
New Revision: cb3136b0d3596f5c3984e4fb49359e2a1a28a547

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

LOG: [clang] Pass --cuda-path to fix test/Driver/openmp-offload-jit.c

This test was trying to detect a system installation of CUDA and was
marked as returning exit code 1 as part of D156363. Pass an explicit
CUDA installation to make the test return exit code 0 regardless of
a CUDA being found on the system or not. Also add an explicit -march
to get a stable test.

Added: 


Modified: 
clang/test/Driver/openmp-offload-jit.c

Removed: 




diff  --git a/clang/test/Driver/openmp-offload-jit.c 
b/clang/test/Driver/openmp-offload-jit.c
index d293c72b2ba1d0..6f5ae7ed7365d1 100644
--- a/clang/test/Driver/openmp-offload-jit.c
+++ b/clang/test/Driver/openmp-offload-jit.c
@@ -36,9 +36,10 @@
 // PHASES-JIT-NEXT: 13: clang-linker-wrapper, {12}, image, (host-openmp)
 
 // Check that we add the `--embed-bitcode` flag to the linker wrapper.
-// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp \
-// RUN:   -fopenmp-targets=nvptx64-nvidia-cuda -fopenmp-target-jit %s 2>&1 \
-// RUN: | FileCheck -check-prefix=LINKER %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp \
+// RUN:   --cuda-path=%S/Inputs/CUDA_111/usr/local/cuda \
+// RUN:   -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_52 \
+// RUN:   -fopenmp-target-jit %s 2>&1 | FileCheck -check-prefix=LINKER %s
 // LINKER: clang-linker-wrapper"{{.*}}"--embed-bitcode"
 
 // Check for incompatible combinations



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


[PATCH] D156363: [Driver] -###: exit with code 1 if hasErrorOccurred

2023-08-08 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

`test/Driver/openmp-offload-jit.c` was still failing for me with CUDA 
installed, so I pushed rGcb3136b0d3596f5c3984e4fb49359e2a1a28a547 
 to add an 
explicit `--cuda-path` and make it return exit code 0 on (hopefully) all 
systems.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156363

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


[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2023-08-08 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 548103.
Herald added a subscriber: jplehr.
Herald added a reviewer: kiranchandramohan.

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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -209,6 +209,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -635,7 +636,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -2025,6 +2025,7 @@
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
 CHECK_SIMPLE_CLAUSE(Doacross, OMPC_doacross)
 CHECK_SIMPLE_CLAUSE(OmpxAttribute, OMPC_ompx_attribute)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2389,6 +2389,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(release)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(relaxed)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(seq_cst)
+  { if (a < c

[PATCH] D157374: [clang-tidy] Ignore decltype in misc-redundant-expression

2023-08-08 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
PiotrZSL added reviewers: njames93, carlosgalvezp.
Herald added a subscriber: xazax.hun.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Modify check to ignore any parent typeLoc and
other unevaluated context.

Fixes: #35857


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157374

Files:
  clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp
@@ -855,3 +855,11 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: both sides of operator are equivalent
 
 }
+
+namespace PR35857 {
+  void test() {
+int x = 0;
+int y = 0;
+decltype(x + y - (x + y)) z = 10;
+  }
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -180,6 +180,10 @@
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
 
+- Improved :doc:`misc-redundant-expression
+  ` check to ignore
+  false-positives in unevaluated context (e.g., ``decltype``).
+
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``.
Index: clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -441,8 +441,6 @@
   return Node.isIntegerConstantExpr(Finder->getASTContext());
 }
 
-AST_MATCHER(Expr, isRequiresExpr) { return isa(Node); }
-
 AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
   return areEquivalentExpr(Node.getLHS(), Node.getRHS());
 }
@@ -862,7 +860,8 @@
 
   const auto BannedIntegerLiteral =
   integerLiteral(expandedByMacro(KnownBannedMacroNames));
-  const auto BannedAncestor = expr(isRequiresExpr());
+  const auto IsInUnevaluatedContext = expr(anyOf(
+  hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc(;
 
   // Binary with equivalent operands, like (X != 2 && X != 2).
   Finder->addMatcher(
@@ -879,7 +878,7 @@
unless(hasEitherOperand(hasType(realFloatingPointType(,
unless(hasLHS(AnyLiteralExpr)),
unless(hasDescendant(BannedIntegerLiteral)),
-   unless(hasAncestor(BannedAncestor)))
+   unless(IsInUnevaluatedContext))
.bind("binary")),
   this);
 
@@ -893,7 +892,7 @@
  unless(binaryOperatorIsInMacro()),
  // TODO: if the banned macros are themselves duplicated
  unless(hasDescendant(BannedIntegerLiteral)),
- unless(hasAncestor(BannedAncestor)))
+ unless(IsInUnevaluatedContext))
   .bind("nested-duplicates"),
   this);
 
@@ -904,7 +903,7 @@
// Filter noisy false positives.
unless(conditionalOperatorIsInMacro()),
unless(isInTemplateInstantiation()),
-   unless(hasAncestor(BannedAncestor)))
+   unless(IsInUnevaluatedContext))
.bind("cond")),
   this);
 
@@ -918,7 +917,7 @@
parametersAreEquivalent(),
// Filter noisy false positives.
unless(isMacro()), unless(isInTemplateInstantiation()),
-   unless(hasAncestor(BannedAncestor)))
+   unless(IsInUnevaluatedContext))
.bind("call")),
   this);
 
@@ -929,7 +928,7 @@
   nestedParametersAreEquivalent(), argumentCountIs(2),
   // Filter noisy false positives.
   unless(isMacro()), unless(isInTemplateInstantiation()),
-  unless(hasAncestor(BannedAncestor)))
+  unless(IsInUnevaluatedContext))
   .bind("nested-duplicates"),
   this);
 
@@ -947,7 +946,7 @@
integerLiteral())),
hasRHS(integerLiteral())
.bind("logical-bitwise-confusion")),
-   unless(hasAncestor(BannedAncestor,
+   unless(IsInUnevaluatedContext))),
   this);
 
   // Match expressions like: (X << 8) & 0xFF
@@ -961,7 +960,7 @

[PATCH] D156320: [FLang] Add support for Rpass flag

2023-08-08 Thread victorkingi via Phabricator via cfe-commits
victorkingi added a comment.

In D156320#4560839 , @awarzynski 
wrote:

> Hey @victorkingi , thank you for working on this :)
>
> There's quite a lot going on here and I am thinking that it might be good to 
> split this into a few patches? Also, please note that Flang's driver, unlike 
> Clang, uses MLIR's coding style (use `camelCase` instead of `CamelCase`).
>
>> A StandaloneBackendConsumer was implemented but the DiagnosticsEngine still 
>> doesn't print to console the remarks produced.
>
> This could mean that it's not being deconstructed correctly. Or that it 
> requires explicit flushing. Can you verify that it contains the expected 
> remarks?

Hi @awarzynski thanks for the comments. Splitting it up makes sense, I will do 
that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[clang-tools-extra] 7899d2a - [clang-tidy][NFC] Remove trailing whitespaces from ProTypeVarargCheck

2023-08-08 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-08-08T08:56:41Z
New Revision: 7899d2aa666359adc6b1d3a66e36f07c2130eb6c

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

LOG: [clang-tidy][NFC] Remove trailing whitespaces from ProTypeVarargCheck

Just a whitespace cleanup.

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
index 54c89921a4cbaa..ac1f40cfe18ae6 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -23,36 +23,36 @@ const internal::VariadicDynCastAllOfMatcher VAArgExpr;
 
 static constexpr StringRef AllowedVariadics[] = {
 // clang-format off
-"__builtin_isgreater", 
-"__builtin_isgreaterequal", 
+"__builtin_isgreater",
+"__builtin_isgreaterequal",
 "__builtin_isless",
-"__builtin_islessequal", 
-"__builtin_islessgreater", 
+"__builtin_islessequal",
+"__builtin_islessgreater",
 "__builtin_isunordered",
-"__builtin_fpclassify", 
-"__builtin_isfinite", 
+"__builtin_fpclassify",
+"__builtin_isfinite",
 "__builtin_isinf",
-"__builtin_isinf_sign", 
-"__builtin_isnan", 
+"__builtin_isinf_sign",
+"__builtin_isnan",
 "__builtin_isnormal",
-"__builtin_signbit", 
-"__builtin_constant_p", 
+"__builtin_signbit",
+"__builtin_constant_p",
 "__builtin_classify_type",
 "__builtin_va_start",
-"__builtin_assume_aligned", // Documented as variadic to support default 
+"__builtin_assume_aligned", // Documented as variadic to support default
 // parameters.
 "__builtin_prefetch",   // Documented as variadic to support default
 // parameters.
 "__builtin_shufflevector",  // Documented as variadic but with a defined
 // number of args based on vector size.
-"__builtin_convertvector", 
+"__builtin_convertvector",
 "__builtin_call_with_static_chain",
-"__builtin_annotation", 
-"__builtin_add_overflow", 
+"__builtin_annotation",
+"__builtin_add_overflow",
 "__builtin_sub_overflow",
-"__builtin_mul_overflow", 
+"__builtin_mul_overflow",
 "__builtin_preserve_access_index",
-"__builtin_nontemporal_store", 
+"__builtin_nontemporal_store",
 "__builtin_nontemporal_load",
 "__builtin_ms_va_start",
 // clang-format on



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


[PATCH] D157376: [clang-tidy] Ignore unevaluated context in cppcoreguidelines-pro-type-vararg

2023-08-08 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
PiotrZSL added reviewers: carlosgalvezp, njames93, ccotter.
Herald added subscribers: shchenz, kbarton, xazax.hun, nemanjai.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Ignore decltype, sizeof, alignof in this check.

Fixes: #30542


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157376

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
@@ -66,3 +66,16 @@
   char *tmp1 = in;
   void *tmp2 = in;
 }
+
+namespace PR30542 {
+  struct X;
+  template 
+  char IsNullConstant(X*);
+  template 
+  char (&IsNullConstant(...))[2];
+
+  static_assert(sizeof(IsNullConstant(0)) == 1, "");
+  static_assert(sizeof(IsNullConstant(17)) == 2, "");
+
+  using Type = decltype(IsNullConstant(17));
+}
Index: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
===
--- 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
+++ 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
@@ -7,7 +7,8 @@
 ``va_arg``.
 
 To allow for SFINAE use of vararg functions, a call is not flagged if a literal
-0 is passed as the only vararg argument.
+0 is passed as the only vararg argument or function is used in unevaluated
+context.
 
 Passing to varargs assumes the correct type will be read. This is fragile
 because it cannot generally be enforced to be safe in the language and so 
relies
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-vararg
+  ` check to ignore
+  false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "ProTypeVarargCheck.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -133,7 +134,9 @@
 
   Finder->addMatcher(
   callExpr(callee(functionDecl(isVariadic(),
-   unless(hasAnyName(AllowedVariadics)
+   unless(hasAnyName(AllowedVariadics,
+   unless(hasAncestor(expr(matchers::hasUnevaluatedContext(,
+   unless(hasAncestor(typeLoc(
   .bind("callvararg"),
   this);
 


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
@@ -66,3 +66,16 @@
   char *tmp1 = in;
   void *tmp2 = in;
 }
+
+namespace PR30542 {
+  struct X;
+  template 
+  char IsNullConstant(X*);
+  template 
+  char (&IsNullConstant(...))[2];
+
+  static_assert(sizeof(IsNullConstant(0)) == 1, "");
+  static_assert(sizeof(IsNullConstant(17)) == 2, "");
+
+  using Type = decltype(IsNullConstant(17));
+}
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
@@ -7,7 +7,8 @@
 ``va_arg``.
 
 To allow for SFINAE use of vararg functions, a call is not flagged if a literal
-0 is passed as the only vararg argument.
+0 is passed as the only vararg argument or function is used in unevaluated
+context.
 
 Passing to varargs assumes the correct

[PATCH] D156787: [analyzer][attr] Add docs to ownership_* attributes

2023-08-08 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 548116.
Szelethus marked 4 inline comments as done.
Szelethus added a comment.

Fixes according to reviewer comments.


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

https://reviews.llvm.org/D156787

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/test/Analysis/malloc-annotations.c

Index: clang/test/Analysis/malloc-annotations.c
===
--- clang/test/Analysis/malloc-annotations.c
+++ clang/test/Analysis/malloc-annotations.c
@@ -148,6 +148,14 @@
   return p; // no-warning
 }
 
+// Test ownership_holds -- we expect the ownership to be taken over, and a
+// result assume that the memory will not leak, but also not released yet.
+void af6(void) {
+  int *p = my_malloc(12);
+  my_hold(p);
+  *p = 4; // no-warn: memory is not released yet
+} // no-warn: assume my_hold takes care of releasing the memory
+
 
 
 // This case tests that storing malloc'ed memory to a static variable which is
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1776,6 +1776,8 @@
   if (!State)
 return nullptr;
 
+  // TODO: Check the attribute docs in AttrDocs.td, it states that only malloc
+  // is accepted. Please adjust if we start supporting "new".
   if (Att->getModule()->getName() != "malloc")
 return nullptr;
 
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -1164,6 +1164,61 @@
   }];
 }
 
+def OwnershipDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "ownership_holds, ownership_returns, ownership_takes";
+  let Content = [{
+These attributes help the static analyzer understand custom ownership management
+functions. None of these affect the generated binary in any way, they are only
+meant to assist the Clang Static Analyzer. You can use these annotations if your
+code uses wrapper functions around ``malloc`` or ``free``, or uses functions
+that take over ownership altogether.
+
+Each annotation has two parameters: the first is the type of allocator used to
+allocate the memory (the only accepted value currently is ``malloc``, but
+we intend to recognize ``new`` in the future). We use this to check whether the
+correct deallocator is used. The second is an integer value, described below.
+
+.. code-block:: c
+
+  void __attribute((ownership_takes(malloc, 1))) my_free(void *);
+  void *__attribute((ownership_returns(malloc, 1))) my_malloc(size_t);
+  void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
+
+``onwership_returns``: Functions with this annotation return dynamic memory.
+The second annotation parameter is the size of the returned memory in bytes.
+
+``ownership_takes``: Functions with this annotation deallocate one of the
+function parameters. The second annotation parameter is the index of the
+function parameter to deallocate.
+
+``ownership_holds``: Functions with this annotation take over the ownership of
+one of the parameters. The static analyzer doesn't assume it to be deallocated
+immediately, but assumes that it will be before the end of the program. The
+second annotation parameter is the index of the function parameter to take hold
+of. Indexing starts at 1, so the first parameter's index is 1. The implicit this
+parameter is not supported at this time.
+
+.. code-block:: c
+
+  void foobar() {
+int *p = my_malloc(sizeof(int));
+  } // warn: Memory leak
+
+  void foo() {
+int *p = my_malloc(sizeof(int));
+my_free(p);
+free(p); // warn: Attempt to free released memory
+  }
+
+  void bar() {
+int *p = my_malloc(sizeof(int));
+my_hold(p);
+*p = 4; // no warn: Pointer is not released
+  } // no warn: Ownership is transferred and assumed to have not escaped
+  }];
+}
+
 def ObjCMethodFamilyDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -2355,7 +2355,7 @@
   let Args = [IdentifierArgument<"Module">,
   VariadicParamIdxArgument<"Args">];
   let Subjects = SubjectList<[HasFunctionProto]>;
-  let Documentation = [Undocumented];
+  let Documentation = [OwnershipDocs];
 }
 
 def Packed : InheritableAttr {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156787: [analyzer][attr] Add docs to ownership_* attributes

2023-08-08 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:1189
+``onwership_returns``: Functions with this annotation return dynamic memory.
+The second annotation parameter is the size of the returned memory in bytes.
+

aaron.ballman wrote:
> I'm a bit confused on this last bit; how is the user supposed to statically 
> know that value? I read this as claiming `my_malloc` returns 1 byte of 
> dynamic storage; can the user tie the allocation to a parameter value instead?
I share your confusion, I guess. What I've written here is my best 
understanding of how this works, unfortunately, these annotations were made in 
~2010 (when I was still in elementary school) and abandoned since.

> I read this as claiming my_malloc returns 1 byte of dynamic storage;

Thats what the corresponding code in the Static Analyzer leads me to believe as 
well.

> can the user tie the allocation to a parameter value instead?

No. 


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

https://reviews.llvm.org/D156787

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


[PATCH] D157379: [CodeGen] Restrict addEmittedDeferredDecl to incremental extensions

2023-08-08 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: rjmccall, v.g.vassilev, junaire.
Herald added a project: All.
Hahnfeld requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Reemission is only needed in incremental mode. With this early return,
we avoid overhead from `addEmittedDeferredDecl` in non-incremental mode.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157379

Files:
  clang/lib/CodeGen/CodeGenModule.h


Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -361,6 +361,10 @@
   llvm::DenseMap EmittedDeferredDecls;
 
   void addEmittedDeferredDecl(GlobalDecl GD) {
+// Reemission is only needed in incremental mode.
+if (!Context.getLangOpts().IncrementalExtensions)
+  return;
+
 // Assume a linkage by default that does not need reemission.
 auto L = llvm::GlobalValue::ExternalLinkage;
 if (llvm::isa(GD.getDecl()))


Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -361,6 +361,10 @@
   llvm::DenseMap EmittedDeferredDecls;
 
   void addEmittedDeferredDecl(GlobalDecl GD) {
+// Reemission is only needed in incremental mode.
+if (!Context.getLangOpts().IncrementalExtensions)
+  return;
+
 // Assume a linkage by default that does not need reemission.
 auto L = llvm::GlobalValue::ExternalLinkage;
 if (llvm::isa(GD.getDecl()))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156537: [CodeGen] Keep track of eagerly emitted globals

2023-08-08 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

In D156537#4554413 , @v.g.vassilev 
wrote:

> In D156537#4554052 , @Hahnfeld 
> wrote:
>
>> @v.g.vassilev do we have a means to detect this case? In D156897 
>> , I'm refactoring all accesses to 
>> `EmittedDeferredDecl` to go via `addEmittedDeferredDecl`, so we should just 
>> add an early return when not emitting for a REPL.
>
> We have `getLangOpts().IncrementalExtensions`. Does that work?

Perfect! After D157379 , calling 
`addEmittedDeferredDecl` should immediately return in case we are not in 
incremental mode.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156537

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


[PATCH] D157270: [Clang][AArch64] Add diagnostic for calls from non-ZA to shared-ZA functions.

2023-08-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/test/Sema/aarch64-sme-func-attrs.c:181
 
+void non_za_definition(void) {
+  sme_arm_new_za(); // OK

rsandifo-arm wrote:
> sdesmalen wrote:
> > rsandifo-arm wrote:
> > > sdesmalen wrote:
> > > > rsandifo-arm wrote:
> > > > > Would be good to have some tests for indirect function calls too (via 
> > > > > function pointers), to make sure that the diagnostic still works when 
> > > > > no decl is available.
> > > > > 
> > > > > I suppose this applies to D157269 too.
> > > > I'm not sure that's necessary because D127762 already added tests to 
> > > > ensure the attributes propagate on pointer types, which then sets the 
> > > > ExtProtoInfo for those values. This patch merely checks the SME 
> > > > attribute fields from ExtProtoInfo. i.e. there is already nothing 
> > > > depending on a declaration being available.
> > > But `Sema::checkCall` does have some tests that depend on the decl rather 
> > > than the type.  So the purpose of the test wouldn't be “does the 
> > > attribute stick when applied to indirect function types?” (which I agree 
> > > is already covered), but “does the new code correctly process the 
> > > attribute on the target of a function pointer type?”
> > The declaration is only relevant for the call-site, not the callee.
> > 
> >   if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask) {
> > 
> > The above line checks __arm_shared_za attribute of the callee (could be a 
> > decl, or a function pointer, but in either case is a prototyped function 
> > with the propagated attributes)
> > 
> >   if (auto *CallerFD = dyn_cast(CurContext)) {
> > 
> > The above line checks if the call-site context is a FunctionDecl (or 
> > definition for that matter). If the call is not part of a declaration (e.g. 
> > it's part of some global initialiser), we know it cannot have any live ZA 
> > state (which I now realise is missing a test-case).
> > 
> > So I think that a test like this:
> > 
> >   __arm_new_za void foo(void (*f)() __arm_shared_za) { f(); }
> > 
> > is not testing anything that isn't already tested. But perhaps I'm still 
> > misunderstanding your point. If so, could you give an example of a test you 
> > have in mind?
> That's the kind of test I had in mind.
> 
> checkCall does have some conditions that are based on the callee decl rather 
> than the callee type.  That is, it does distinguish between direct calls and 
> indirect calls.  It would have been easy for the code to be in a block that 
> was guarded with FDecl.  Or it could be accidentally rearranged like that in 
> future, especially if the function grows to have several more tests.
> 
> And yeah, I agree that the code as-written works, and so it doesn't fall into 
> the trap that is being tested for.  But that's true of most tests that get 
> written for new features. :)
> 
> So a test for both the direct and indirect cases seemed worthwhile.  If we 
> were just going to have one, then I think testing the indirect case is more 
> valuable than testing the direct case, since it's the type rather than the 
> decl that matters.
> 
> I won't press the point further though.  Feel free to skip the comment if 
> you'd rather keep the tests as they are.
Thanks for elaborating, I was mostly trying to understand your reasoning for 
adding this test.

> If we were just going to have one, then I think testing the indirect case is 
> more valuable than testing the direct case, since it's the type rather than 
> the decl that matters.
You're right that the tests should probably have used the indirect case from 
the start. I see your argument about the code possibly changing in the future. 
It seems unlikely that someone would add an extra FDecl guard above the block 
where I've added the code, but I see how that's not really the point. I guess 
there is little argument not to add another positive test-case to the patch, so 
I'll just do that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157270

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


[PATCH] D157269: [Clang][AArch64] Diagnostics for SME attributes when target doesn't have 'sme'

2023-08-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen updated this revision to Diff 548130.
sdesmalen added a comment.

- (Clang) Added test-cases for indirect calls.
- (LLVM) Moved the pseudo definition out of the 'let Predicates = [HasSME] {}' 
block as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157269

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp
  llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  
llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll

Index: llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll
@@ -0,0 +1,41 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 2
+; RUN: llc < %s | FileCheck %s
+
+; This that the following code can be compiled without +sme, because if the
+; call is not entered in streaming-SVE mode at runtime, the codepath leading
+; to the smstop/smstart pair will not be executed either.
+
+target triple = "aarch64"
+
+define void @streaming_compatible() #0 {
+; CHECK-LABEL: streaming_compatible:
+; CHECK:   // %bb.0:
+; CHECK-NEXT:stp d15, d14, [sp, #-80]! // 16-byte Folded Spill
+; CHECK-NEXT:stp d13, d12, [sp, #16] // 16-byte Folded Spill
+; CHECK-NEXT:stp d11, d10, [sp, #32] // 16-byte Folded Spill
+; CHECK-NEXT:stp d9, d8, [sp, #48] // 16-byte Folded Spill
+; CHECK-NEXT:stp x30, x19, [sp, #64] // 16-byte Folded Spill
+; CHECK-NEXT:bl __arm_sme_state
+; CHECK-NEXT:and x19, x0, #0x1
+; CHECK-NEXT:tbz x19, #0, .LBB0_2
+; CHECK-NEXT:  // %bb.1:
+; CHECK-NEXT:msr SVCRSM, #0
+; CHECK-NEXT:  .LBB0_2:
+; CHECK-NEXT:bl non_streaming
+; CHECK-NEXT:tbz x19, #0, .LBB0_4
+; CHECK-NEXT:  // %bb.3:
+; CHECK-NEXT:msr SVCRSM, #1
+; CHECK-NEXT:  .LBB0_4:
+; CHECK-NEXT:ldp x30, x19, [sp, #64] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d9, d8, [sp, #48] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d11, d10, [sp, #32] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d13, d12, [sp, #16] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d15, d14, [sp], #80 // 16-byte Folded Reload
+; CHECK-NEXT:ret
+  call void @non_streaming()
+  ret void
+}
+
+declare void @non_streaming()
+
+attributes #0 = { nounwind "aarch64_pstate_sm_compatible" }
Index: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
===
--- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
+++ llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
@@ -442,8 +442,6 @@
 
   assert((!StreamingSVEMode || I->hasSME()) &&
  "Expected SME to be available");
-  assert((!StreamingCompatibleSVEMode || I->hasSVEorSME()) &&
- "Expected SVE or SME to be available");
 
   return I.get();
 }
Index: llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td
===
--- llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td
+++ llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td
@@ -154,6 +154,12 @@
   let Inst{11-9} = pstatefield;
   let Inst{8} = imm;
   let Inst{7-5} = 0b011; // op2
+
+  // We shouldn't require 'sme' to compile streaming-compatible functions which
+  // call non-streaming functions as the SME smstart/smstop will only be
+  // executed at runtime if streaming-mode is enabled, which also means SME must
+  // be enabled.
+  let Predicates = [];
 }
 
 def : InstAlias<"smstart",(MSRpstatesvcrImm1 0b011, 0b1)>;
@@ -165,21 +171,6 @@
 def : InstAlias<"smstop za",  (MSRpstatesvcrImm1 0b010, 0b0)>;
 
 
-// Pseudo to match to smstart/smstop. This expands:
-//
-//  pseudonode (pstate_za|pstate_sm), before_call, expected_value
-//
-// Into:
-//
-//   if (before_call != expected_value)
-// node (pstate_za|pstate_sm)
-//
-// where node can be either 'smstart' or 'smstop'.
-def MSRpstatePseudo :
-  Pseudo<(outs),
-   (ins svcr_op:$pstatefield, timm0_1:$imm, GPR64:$rtpstate, timm0_1:$expected_pstate, variable_ops), []>,
-Sched<[WriteSys]>;
-
 // Pseudo to conditionally restore ZA state. This expands:
 //
 //   pseudonode tpidr2_el0, tpidr2obj, restore_routine
@@ -226,12 +217,6 @@
 def : Pat<(AArch64_smstop (i32 svcr_op:$pstate), (i64 0), (i64 1)),   // after call
   (MSRpstatesvcrImm1 svcr_op:$pstate, 0b0)>;
 
-// The generic case which gets expanded to a pseudo node.
-def : Pat<(AArch64_smstart (i32 svcr_op:$pstate), (i64 GPR64:$rtpstate), (i64 timm0_1:$expected_pstate)),
-  (MSRpstatePseudo svcr_op:$pstate, 0b1, GPR64:$rtpstate, timm0_1:$expected_pstate)>;
-def : Pat<(AArch64_smstop (i32 svcr_op:$pstate), (i6

[PATCH] D157270: [Clang][AArch64] Add diagnostic for calls from non-ZA to shared-ZA functions.

2023-08-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen updated this revision to Diff 548131.
sdesmalen added a comment.

Added test-cases for indirect calls


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157270

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/aarch64-sme-func-attrs.c


Index: clang/test/Sema/aarch64-sme-func-attrs.c
===
--- clang/test/Sema/aarch64-sme-func-attrs.c
+++ clang/test/Sema/aarch64-sme-func-attrs.c
@@ -178,7 +178,31 @@
 void redecl_nopreserve_za(void) __arm_shared_za;
 void redecl_nopreserve_za(void) __arm_shared_za __arm_preserves_za {}
 
+void non_za_definition(void (*shared_za_fn_ptr)(void) __arm_shared_za) {
+  sme_arm_new_za(); // OK
+  // expected-error@+2 {{call to a shared ZA function requires the caller to 
have ZA state}}
+  // expected-cpp-error@+1 {{call to a shared ZA function requires the caller 
to have ZA state}}
+  sme_arm_shared_za();
+  // expected-error@+2 {{call to a shared ZA function requires the caller to 
have ZA state}}
+  // expected-cpp-error@+1 {{call to a shared ZA function requires the caller 
to have ZA state}}
+  shared_za_fn_ptr();
+}
+
+void shared_za_definition(void (*shared_za_fn_ptr)(void) __arm_shared_za) 
__arm_shared_za {
+  sme_arm_shared_za(); // OK
+  shared_za_fn_ptr(); // OK
+}
+
+__arm_new_za void new_za_definition(void (*shared_za_fn_ptr)(void) 
__arm_shared_za) {
+  sme_arm_shared_za(); // OK
+  shared_za_fn_ptr(); // OK
+}
+
 #ifdef __cplusplus
+int shared_za_initializer(void) __arm_shared_za;
+// expected-cpp-error@+1 {{call to a shared ZA function requires the caller to 
have ZA state}}
+int global = shared_za_initializer();
+
 struct S {
   virtual void shared_za_memberfn(void) __arm_shared_za;
 };
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -6765,6 +6765,22 @@
 Diag(Loc, diag::err_sme_call_in_non_sme_target);
   }
 }
+
+// If the callee uses AArch64 SME ZA state but the caller doesn't define
+// any, then this is an error.
+if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask) {
+  bool CallerHasZAState = false;
+  if (auto *CallerFD = dyn_cast(CurContext)) {
+if (CallerFD->hasAttr())
+  CallerHasZAState = true;
+else if (const auto *FPT = 
CallerFD->getType()->getAs())
+  CallerHasZAState = FPT->getExtProtoInfo().AArch64SMEAttributes &
+ FunctionType::SME_PStateZASharedMask;
+  }
+
+  if (!CallerHasZAState)
+Diag(Loc, diag::err_sme_za_call_no_za_state);
+}
   }
 
   if (FDecl && FDecl->hasAttr()) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3629,6 +3629,8 @@
   "function declared %0 was previously declared %1, which has different SME 
function attributes">;
 def err_sme_call_in_non_sme_target : Error<
   "call to a streaming function requires 'sme'">;
+def err_sme_za_call_no_za_state : Error<
+  "call to a shared ZA function requires the caller to have ZA state">;
 def err_sme_definition_using_sm_in_non_sme_target : Error<
   "function executed in streaming-SVE mode requires 'sme'">;
 def err_sme_definition_using_za_in_non_sme_target : Error<


Index: clang/test/Sema/aarch64-sme-func-attrs.c
===
--- clang/test/Sema/aarch64-sme-func-attrs.c
+++ clang/test/Sema/aarch64-sme-func-attrs.c
@@ -178,7 +178,31 @@
 void redecl_nopreserve_za(void) __arm_shared_za;
 void redecl_nopreserve_za(void) __arm_shared_za __arm_preserves_za {}
 
+void non_za_definition(void (*shared_za_fn_ptr)(void) __arm_shared_za) {
+  sme_arm_new_za(); // OK
+  // expected-error@+2 {{call to a shared ZA function requires the caller to have ZA state}}
+  // expected-cpp-error@+1 {{call to a shared ZA function requires the caller to have ZA state}}
+  sme_arm_shared_za();
+  // expected-error@+2 {{call to a shared ZA function requires the caller to have ZA state}}
+  // expected-cpp-error@+1 {{call to a shared ZA function requires the caller to have ZA state}}
+  shared_za_fn_ptr();
+}
+
+void shared_za_definition(void (*shared_za_fn_ptr)(void) __arm_shared_za) __arm_shared_za {
+  sme_arm_shared_za(); // OK
+  shared_za_fn_ptr(); // OK
+}
+
+__arm_new_za void new_za_definition(void (*shared_za_fn_ptr)(void) __arm_shared_za) {
+  sme_arm_shared_za(); // OK
+  shared_za_fn_ptr(); // OK
+}
+
 #ifdef __cplusplus
+int shared_za_initializer(void) __arm_shared_za;
+// expected-cpp-error@+1 {{call to a shared ZA function requires the caller to have ZA state}}
+int global = shared_za_ini

[PATCH] D157332: [clang] Make init for empty no_unique_address fields a no-op write

2023-08-08 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D157332#4568341 , @efriedma wrote:

> I see what you're getting at here... but I don't think this works quite 
> right.  If the empty class has a non-trivial constructor, we have to pass the 
> correct "this" address to that constructor.  Usually a constructor for an 
> empty class won't do anything with that address, but it could theoretically 
> do something with it.

Hmm, I think I see. In this specific case, there's no constructor for the empty 
class invoked at all, we call the function `f()` which returns an `struct S` 
(which is empty). But if we'd remove the initialization of `y(f())` and add a 
constructor to `S()`, I see that we generate code that is indeed wrong in that 
aspect.

> In order to preserve the address in the cases we need it, we need a different 
> invariant: the handling for each aggregate expression in EmitAggExpr needs to 
> ensure it doesn't store anything to an empty class.  Which is unfortunately 
> more fragile than I'd like, but I can't think of a better approach.  This 
> check needs to happen further down the call stack.  Maybe put it in 
> CodeGenFunction::EmitCall.

Ok, I'll see if I can look further into that... (I don't have a huge amount of 
time for it at the moment, so if someone else with an interest in the area, 
e.g. @crtrott or @amyk want to dig into it, feel free!)




Comment at: clang/test/CodeGenCXX/ctor-empty-nounique.cpp:1
+// RUN: %clang_cc1 -triple x86_64-windows-gnu -emit-llvm -o - %s | FileCheck %s
+

cor3ntin wrote:
> This should probably get another run line for powerpc64le
Sure, I could do that. (Initially I had both, but thought people would consider 
it unnecessary duplication.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157332

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


[PATCH] D155824: [LoongArch] Support -march=native and -mtune=

2023-08-08 Thread WÁNG Xuěruì via Phabricator via cfe-commits
xen0n accepted this revision.
xen0n added a comment.
This revision is now accepted and ready to land.

This still LGTM, @steven_wu would you please take another look so this can get 
re-landed if confirmed working?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155824

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


[PATCH] D156320: [FLang] Add support for Rpass flag

2023-08-08 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 548142.
victorkingi added a comment.

fixing failing tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,48 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Reverything implies -Rpass=.*.
+! RUN: %flang_fc1 %s -O1 -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Rpass implies -Rpass=.*
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass=loop-delete 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+
+! CHECK: remark: Loop deleted because it is invariant
+! CHECK-REMARKS-MISSED: remark: loop not vectorized
+! CHECK-REMARKS-ANALYSIS: remark: loop not vectorized: call instruction cannot be vectorized
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -22,6 +22,13 @@
 ! RUN: -fppc-native-vector-element-order \
 ! RUN: -mllvm -print-before-all \
 ! RUN: -save-temps=obj \
+! RUN: -Rpass \
+! RUN: -Rpass-missed \
+! RUN: -Rpass-analysis \
+! RUN: -Rno-pass \
+! RUN: -Reverything \
+! RUN: -Rno-everything \
+! RUN: -Rpass=inline \
 ! RUN: -P \
 ! RUN:   | FileCheck %s
 
@@ -44,5 +51,12 @@
 ! CHECK: "-flang-experimental-hlfir"
 ! CHECK: "-fno-ppc-native-vector-element-order"
 ! CHECK: "-fppc-native-vector-element-order"
+! CHECK: "-Rpass"
+! CHECK: "-Rpass-missed"
+! CHECK: "-Rpass-analysis"
+! CHECK: "-Rno-pass"
+! CHECK: "-Reverything"
+! CHECK: "-Rno-everything"
+! CHECK: "-Rpass=inline"
 ! CHECK: "-mllvm" "-print-before-all"
 ! CHECK: "-save-temps=obj"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -91,6 +91,10 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -R  Enable the specified remark
 ! HELP-NEXT: -save-temps=Save intermediate compilation results.
 ! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
@@ -214,6 +218,10 @@
 ! HELP-FC1-NEXT: -pic-level   Value for __PIC__

[PATCH] D156693: [clang][ASTImporter]Skip check friend template depth

2023-08-08 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

This fix can cause problems because the depth comparison is omitted all times. 
It would be better to omit depth check if the imported template is a friend, 
and has a `ClassTemplateSpecializationDecl` as context. Probably even then it 
is possible to construct cases where the checked template has references to 
other templates with different "depth" which should not omitted in the check. 
But I have no idea of a better solution, only to pass a `ClassTemplateDecl` or 
`ClassTemplateSpecializationDecl` to `StructuralEquivalenceContext` and omit 
the depth check only at this object.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156693

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


[PATCH] D157275: [Driver] Select newest GCC installation on Solaris

2023-08-08 Thread Rainer Orth via Phabricator via cfe-commits
ro added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:2193
 // Skip other prefixes once a GCC installation is found.
-if (Version > VersionZero)
+// Solaris GCC installations live in separate Prefixes per Version
+// (/usr/gcc/) that arrive in directory order, so check all

MaskRay wrote:
> Adding a Solaris special case here seems strange.
> 
> Do you know what the typical `Prefixes` values are on Solaris? Is it possible 
> to remove some elements as a special case for Solaris instead?
Agreed.  This patch in its current form is just meant as a stop-gap measure to 
unbreak basic Solaris functionality while avoiding to affect other targets.

I've described the value of `Prefixes` on Solaris in the Issue: its an array of 
`/usr/gcc/` for each installed version of GCC, however in directory order 
and thus random.  The exact set is variable since every version can be 
installed or uninstalled at any time, old versions get deprecated and removed, 
and new ones added over time.

My fundamental problem here is that I haven't yet been able to reproduce the 
failure your original patch is meant to fix, so I don't really know what to 
guard against.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157275

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


[PATCH] D156787: [analyzer][attr] Add docs to ownership_* attributes

2023-08-08 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:1189
+``onwership_returns``: Functions with this annotation return dynamic memory.
+The second annotation parameter is the size of the returned memory in bytes.
+

Szelethus wrote:
> aaron.ballman wrote:
> > I'm a bit confused on this last bit; how is the user supposed to statically 
> > know that value? I read this as claiming `my_malloc` returns 1 byte of 
> > dynamic storage; can the user tie the allocation to a parameter value 
> > instead?
> I share your confusion, I guess. What I've written here is my best 
> understanding of how this works, unfortunately, these annotations were made 
> in ~2010 (when I was still in elementary school) and abandoned since.
> 
> > I read this as claiming my_malloc returns 1 byte of dynamic storage;
> 
> Thats what the corresponding code in the Static Analyzer leads me to believe 
> as well.
> 
> > can the user tie the allocation to a parameter value instead?
> 
> No. 
I'd guess that this annotation was designed for factory functions that 
construct an instance of a concrete struct type on the heap. Allowing "generic" 
malloc variants (where the allocation size is specified by a parameter) would 
be a good additional feature, but I think that the current annotation also has 
its own uses.

Perhaps it would be good to provide examples like
```
  void __attribute((ownership_takes(malloc, 1))) free_widget(struct widget *);
  struct widget *__attribute((ownership_returns(malloc, sizeof(struct 
widget create_widget(void);
  void __attribute((ownership_holds(malloc, 1))) hold_widget(struct widget *);
```
that correspond to this use case. (By the way, does the checker handle 
non-`void*` pointers?)


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

https://reviews.llvm.org/D156787

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


[PATCH] D156320: [FLang] Add support for Rpass flag

2023-08-08 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 548148.
victorkingi added a comment.

from CamelCase to camelCase variables


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,48 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Reverything implies -Rpass=.*.
+! RUN: %flang_fc1 %s -O1 -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Rpass implies -Rpass=.*
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass=loop-delete 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+
+! CHECK: remark: Loop deleted because it is invariant
+! CHECK-REMARKS-MISSED: remark: loop not vectorized
+! CHECK-REMARKS-ANALYSIS: remark: loop not vectorized: call instruction cannot be vectorized
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -22,6 +22,13 @@
 ! RUN: -fppc-native-vector-element-order \
 ! RUN: -mllvm -print-before-all \
 ! RUN: -save-temps=obj \
+! RUN: -Rpass \
+! RUN: -Rpass-missed \
+! RUN: -Rpass-analysis \
+! RUN: -Rno-pass \
+! RUN: -Reverything \
+! RUN: -Rno-everything \
+! RUN: -Rpass=inline \
 ! RUN: -P \
 ! RUN:   | FileCheck %s
 
@@ -44,5 +51,12 @@
 ! CHECK: "-flang-experimental-hlfir"
 ! CHECK: "-fno-ppc-native-vector-element-order"
 ! CHECK: "-fppc-native-vector-element-order"
+! CHECK: "-Rpass"
+! CHECK: "-Rpass-missed"
+! CHECK: "-Rpass-analysis"
+! CHECK: "-Rno-pass"
+! CHECK: "-Reverything"
+! CHECK: "-Rno-everything"
+! CHECK: "-Rpass=inline"
 ! CHECK: "-mllvm" "-print-before-all"
 ! CHECK: "-save-temps=obj"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -91,6 +91,10 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -R  Enable the specified remark
 ! HELP-NEXT: -save-temps=Save intermediate compilation results.
 ! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
@@ -214,6 +218,10 @@
 ! HELP-FC1-NEXT: -pic-level   

[clang] a2132d7 - [Clang] Fix the do while statement disappearing in AST when an error occurs in the conditional expression of the do while statement

2023-08-08 Thread via cfe-commits

Author: yrong
Date: 2023-08-08T19:34:43+08:00
New Revision: a2132d72bed153a3347763dfaa7e699de7128647

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

LOG: [Clang] Fix the do while statement disappearing in AST when an error 
occurs in the conditional expression of the do while statement

```
constexpr int test() {
do {} while (a + 1 < 10);
return 0;
}
```
Before:
```
`-FunctionDecl 0x56512a172650 <./recovery.cpp:1:1, line:4:1> line:1:15 
constexpr test 'int ()' implicit-inline
  `-CompoundStmt 0x56512a172860 
`-ReturnStmt 0x56512a172850 
  `-IntegerLiteral 0x56512a172830  'int' 0
```
Now:
```
`-FunctionDecl 0x5642c4804650 <./recovery.cpp:1:1, line:4:1> line:1:15 
constexpr test 'int ()' implicit-inline
  `-CompoundStmt 0x5642c48048e0 
|-DoStmt 0x5642c4804890 
| |-CompoundStmt 0x5642c4804740 
| `-BinaryOperator 0x5642c4804870  '' 
contains-errors '<'
|   |-BinaryOperator 0x5642c4804850  '' 
contains-errors '+'
|   | |-RecoveryExpr 0x5642c4804830  '' 
contains-errors lvalue
|   | `-IntegerLiteral 0x5642c48047b0  'int' 1
|   `-IntegerLiteral 0x5642c48047f0  'int' 10
`-ReturnStmt 0x5642c48048d0 
  `-IntegerLiteral 0x5642c48048b0  'int' 0
```

Reviewed By: hokein

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

Added: 


Modified: 
clang/lib/Parse/ParseStmt.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp
index 2346470dbdb73d..bf295b8a0cb8a2 100644
--- a/clang/lib/Parse/ParseStmt.cpp
+++ b/clang/lib/Parse/ParseStmt.cpp
@@ -1894,7 +1894,8 @@ StmtResult Parser::ParseDoStatement() {
   ExprResult Cond = ParseExpression();
   // Correct the typos in condition before closing the scope.
   if (Cond.isUsable())
-Cond = Actions.CorrectDelayedTyposInExpr(Cond);
+Cond = Actions.CorrectDelayedTyposInExpr(Cond, /*InitDecl=*/nullptr,
+ /*RecoverUncorrectedTypos=*/true);
   else {
 if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
   SkipUntil(tok::semi);

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index cc4f8afbfc4441..c882b4659a7310 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -420,3 +420,15 @@ void RecoverToAnInvalidDecl() {
   // CHECK:  RecoveryExpr {{.*}} '' contains-errors lvalue
   // CHECK-NEXT: `-DeclRefExpr {{.*}} 'foo' 'int *'
 }
+
+void RecoveryToDoWhileStmtCond() {
+  // CHECK:   FunctionDecl {{.*}} RecoveryToDoWhileStmtCond
+  // CHECK:   `-DoStmt {{.*}}
+  // CHECK-NEXT:|-CompoundStmt {{.*}}
+  // CHECK-NEXT:`-BinaryOperator {{.*}} '' contains-errors 
'<'
+  // CHECK-NEXT:  |-BinaryOperator {{.*}} '' 
contains-errors '+'
+  // CHECK-NEXT:  | |-RecoveryExpr {{.*}} '' 
contains-errors lvalue
+  // CHECK-NEXT:  | `-IntegerLiteral {{.*}} 'int' 1
+  // CHECK-NEXT:  `-IntegerLiteral {{.*}} 'int' 10
+  do {} while (some_invalid_val + 1 < 10);
+}

diff  --git a/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp 
b/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
index 8bada7c0b6df3e..16654104a9177e 100644
--- a/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ b/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -95,6 +95,8 @@ TEST_EVALUATE(For, for (!!){}); // expected-error + {{}}
 TEST_EVALUATE(ForRange, for (auto x : !!){}); // expected-error + {{}}
 TEST_EVALUATE(While, while (!!){});   // expected-error + {{}}
 TEST_EVALUATE(DoWhile, do {} while (!!););// expected-error + {{}}
+TEST_EVALUATE(DoWhileCond, do {} while (some_cond < 10););// 
expected-error {{use of undeclared identifier}}  \
+  // 
expected-error {{constexpr variable 'forceEvaluateDoWhileCond' must be 
initialized by a constant expression}}
 TEST_EVALUATE(If, if (!!){};);// expected-error + {{}}
 TEST_EVALUATE(IfInit, if (auto x = !!; 1){};);// expected-error + {{}}
 TEST_EVALUATE(ForInit, if (!!;;){};); // expected-error + {{}}



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


[PATCH] D157195: [Clang] Fix the do while statement disappearing in AST when an error occurs in the conditional expression of the do while statement

2023-08-08 Thread Yurong via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yronglin marked 2 inline comments as done.
Closed by commit rGa2132d72bed1: [Clang] Fix the do while statement 
disappearing in AST when an error occurs in… (authored by yronglin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157195

Files:
  clang/lib/Parse/ParseStmt.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/SemaCXX/constexpr-function-recovery-crash.cpp


Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -95,6 +95,8 @@
 TEST_EVALUATE(ForRange, for (auto x : !!){}); // expected-error + {{}}
 TEST_EVALUATE(While, while (!!){});   // expected-error + {{}}
 TEST_EVALUATE(DoWhile, do {} while (!!););// expected-error + {{}}
+TEST_EVALUATE(DoWhileCond, do {} while (some_cond < 10););// 
expected-error {{use of undeclared identifier}}  \
+  // 
expected-error {{constexpr variable 'forceEvaluateDoWhileCond' must be 
initialized by a constant expression}}
 TEST_EVALUATE(If, if (!!){};);// expected-error + {{}}
 TEST_EVALUATE(IfInit, if (auto x = !!; 1){};);// expected-error + {{}}
 TEST_EVALUATE(ForInit, if (!!;;){};); // expected-error + {{}}
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -420,3 +420,15 @@
   // CHECK:  RecoveryExpr {{.*}} '' contains-errors lvalue
   // CHECK-NEXT: `-DeclRefExpr {{.*}} 'foo' 'int *'
 }
+
+void RecoveryToDoWhileStmtCond() {
+  // CHECK:   FunctionDecl {{.*}} RecoveryToDoWhileStmtCond
+  // CHECK:   `-DoStmt {{.*}}
+  // CHECK-NEXT:|-CompoundStmt {{.*}}
+  // CHECK-NEXT:`-BinaryOperator {{.*}} '' contains-errors 
'<'
+  // CHECK-NEXT:  |-BinaryOperator {{.*}} '' 
contains-errors '+'
+  // CHECK-NEXT:  | |-RecoveryExpr {{.*}} '' 
contains-errors lvalue
+  // CHECK-NEXT:  | `-IntegerLiteral {{.*}} 'int' 1
+  // CHECK-NEXT:  `-IntegerLiteral {{.*}} 'int' 10
+  do {} while (some_invalid_val + 1 < 10);
+}
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -1894,7 +1894,8 @@
   ExprResult Cond = ParseExpression();
   // Correct the typos in condition before closing the scope.
   if (Cond.isUsable())
-Cond = Actions.CorrectDelayedTyposInExpr(Cond);
+Cond = Actions.CorrectDelayedTyposInExpr(Cond, /*InitDecl=*/nullptr,
+ /*RecoverUncorrectedTypos=*/true);
   else {
 if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
   SkipUntil(tok::semi);


Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -95,6 +95,8 @@
 TEST_EVALUATE(ForRange, for (auto x : !!){}); // expected-error + {{}}
 TEST_EVALUATE(While, while (!!){});   // expected-error + {{}}
 TEST_EVALUATE(DoWhile, do {} while (!!););// expected-error + {{}}
+TEST_EVALUATE(DoWhileCond, do {} while (some_cond < 10););// expected-error {{use of undeclared identifier}}  \
+  // expected-error {{constexpr variable 'forceEvaluateDoWhileCond' must be initialized by a constant expression}}
 TEST_EVALUATE(If, if (!!){};);// expected-error + {{}}
 TEST_EVALUATE(IfInit, if (auto x = !!; 1){};);// expected-error + {{}}
 TEST_EVALUATE(ForInit, if (!!;;){};); // expected-error + {{}}
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -420,3 +420,15 @@
   // CHECK:  RecoveryExpr {{.*}} '' contains-errors lvalue
   // CHECK-NEXT: `-DeclRefExpr {{.*}} 'foo' 'int *'
 }
+
+void RecoveryToDoWhileStmtCond() {
+  // CHECK:   FunctionDecl {{.*}} RecoveryToDoWhileStmtCond
+  // CHECK:   `-DoStmt {{.*}}
+  // CHECK-NEXT:|-CompoundStmt {{.*}}
+  // CHECK-NEXT:`-BinaryOperator {{.*}} '' contains-errors '<'
+  // CHECK-NEXT:  |-BinaryOperator {{.*}} '' contains-errors '+'
+  // CHECK-NEXT:  | |-RecoveryExpr {{.*}} '' contains-errors lvalue
+  // CHECK-NEXT:  | `-IntegerLiteral {{.*}} 'int' 1
+  // CHECK-NEXT:  `-IntegerLiteral {{.*}} 'int' 10
+  do {} while (some_invalid_val + 1 < 10);
+}
Index: clang/lib/Parse/ParseStmt.cpp

[PATCH] D157383: [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-08 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet created this revision.
hazohelet added reviewers: aaron.ballman, tbaeder, cjdb.
Herald added a project: All.
hazohelet requested review of this revision.
Herald added a project: clang.

BEFORE:

  overflow.cpp:1:21: warning: overflow in expression; result is -2147483648 
with type 'int' [-Winteger-overflow]
  1 | int x = __INT_MAX__ + 1 + 3;
| ^
  overflow.cpp:2:9: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
  2 | int a = -(1 << 31) + 1;
| ^

AFTER:

  overflow.cpp:1:21: warning: overflow in expression; result is -2147483648 
with type 'int' [-Winteger-overflow]
  1 | int x = __INT_MAX__ + 1 + 3;
| ^~~
  overflow.cpp:2:9: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
  2 | int a = -(1 << 31) + 1;
| ^~


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157383

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/Interp.h
  clang/test/Misc/constexpr-source-ranges.cpp


Index: clang/test/Misc/constexpr-source-ranges.cpp
===
--- clang/test/Misc/constexpr-source-ranges.cpp
+++ clang/test/Misc/constexpr-source-ranges.cpp
@@ -13,3 +13,10 @@
 constexpr const int *P = &I;
 constexpr long L = (long)P;
 // CHECK: constexpr-source-ranges.cpp:14:20:{14:20-14:27}
+
+namespace overflow {
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:29}: warning: overflow
+int x = -1 + __INT_MAX__ + 2 + 3;
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:19}: warning: overflow
+int a = -(1 << 31) + 1;
+}
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -269,7 +269,8 @@
 SmallString<32> Trunc;
 Value.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   } else {
 S.CCEDiag(E, diag::note_constexpr_overflow) << Value << Type;
@@ -476,7 +477,8 @@
 SmallString<32> Trunc;
 NegatedValue.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   }
 
@@ -529,7 +531,8 @@
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   }
 
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2798,7 +2798,7 @@
 if (Info.checkingForUndefinedBehavior())
   Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
diag::warn_integer_constant_overflow)
-  << toString(Result, 10) << E->getType();
+  << toString(Result, 10) << E->getType() << E->getSourceRange();
 return HandleOverflow(Info, E, Value, E->getType());
   }
   return true;
@@ -13625,7 +13625,7 @@
   if (Info.checkingForUndefinedBehavior())
 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  diag::warn_integer_constant_overflow)
-<< toString(Value, 10) << E->getType();
+<< toString(Value, 10) << E->getType() << E->getSourceRange();
 
   if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
   E->getType()))


Index: clang/test/Misc/constexpr-source-ranges.cpp
===
--- clang/test/Misc/constexpr-source-ranges.cpp
+++ clang/test/Misc/constexpr-source-ranges.cpp
@@ -13,3 +13,10 @@
 constexpr const int *P = &I;
 constexpr long L = (long)P;
 // CHECK: constexpr-source-ranges.cpp:14:20:{14:20-14:27}
+
+namespace overflow {
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:29}: warning: overflow
+int x = -1 + __INT_MAX__ + 2 + 3;
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:19}: warning: overflow
+int a = -(1 << 31) + 1;
+}
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -269,7 +269,8 @@
 SmallString<32> Trunc;
 Value.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S

[PATCH] D157383: [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-08 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added inline comments.



Comment at: clang/lib/AST/Interp/Interp.h:530-535
   if (S.checkingForUndefinedBehavior()) {
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();

I'm not sure whether this branch takes effect.
I could not find codes that takes this block, so I haven't added tests for this.

FWIW, the old interpreter does not have the corresponding 
`warn_integer_constant_overflow` generated against overflowing increments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157383

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


[PATCH] D142609: [Clang] Fix -Wconstant-logical-operand when LHS is a constant

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D142609#4568095 , @xgupta wrote:

> In D142609#4566418 , @aaron.ballman 
> wrote:
>
>> Concerns have been raised in 
>> https://github.com/llvm/llvm-project/issues/64356 that this is an 
>> undesirable change in diagnostic behavior. The diagnostic is supposed to 
>> fire when misusing a logical operand that most likely should have been a 
>> bitwise operand. There's a feeling that `true && expr` is plausibly done 
>> intentionally more often than `true & expr`.
>>
>> I think we should revert the changes from this patch and in the Clang 17.x 
>> branch so that we can reevaluate the approach taken in this patch. CC 
>> @porglezomp @cjdb
>
> This got reverted and cherry-pick request is made - 
> https://github.com/llvm/llvm-project/issues/64515.

Thank you! There's been some more discussion about the design on the github 
issue, in case you're interested in continuing to pursue this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142609

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


[clang] 241cceb - [Clang][Tooling] Accept preprocessed input files

2023-08-08 Thread J. Ryan Stinnett via cfe-commits

Author: J. Ryan Stinnett
Date: 2023-08-08T12:44:48+01:00
New Revision: 241cceb9af844ef7d7a87124407a04b0a64991fe

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

LOG: [Clang][Tooling] Accept preprocessed input files

This restores the tooling library's ability to accept invocations that take a
preprocessed file as the primary input.

Regressed by https://reviews.llvm.org/D105695
Fixes https://github.com/llvm/llvm-project/issues/63941

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

Added: 


Modified: 
clang/lib/Tooling/Tooling.cpp
clang/unittests/Tooling/ToolingTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp
index 46a784e44b931a..dc82a1f3772dd2 100644
--- a/clang/lib/Tooling/Tooling.cpp
+++ b/clang/lib/Tooling/Tooling.cpp
@@ -147,6 +147,13 @@ getCC1Arguments(DiagnosticsEngine *Diagnostics,
 if (IsCC1Command(Job) && llvm::all_of(Job.getInputInfos(), IsSrcFile))
   CC1Jobs.push_back(&Job);
 
+  // If there are no jobs for source files, try checking again for a single job
+  // with any file type. This accepts a preprocessed file as input.
+  if (CC1Jobs.empty())
+for (const driver::Command &Job : Jobs)
+  if (IsCC1Command(Job))
+CC1Jobs.push_back(&Job);
+
   if (CC1Jobs.empty() ||
   (CC1Jobs.size() > 1 && !ignoreExtraCC1Commands(Compilation))) {
 SmallString<256> error_msg;

diff  --git a/clang/unittests/Tooling/ToolingTest.cpp 
b/clang/unittests/Tooling/ToolingTest.cpp
index ebe03fda78f1ef..354af292a54108 100644
--- a/clang/unittests/Tooling/ToolingTest.cpp
+++ b/clang/unittests/Tooling/ToolingTest.cpp
@@ -449,6 +449,13 @@ TEST_F(CommandLineExtractorTest, AcceptSaveTemps) {
   EXPECT_NE(extractCC1Arguments(Args), nullptr);
 }
 
+TEST_F(CommandLineExtractorTest, AcceptPreprocessedInputFile) {
+  addFile("test.i", "int main() {}\n");
+  const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", "-c",
+"test.i"};
+  EXPECT_NE(extractCC1Arguments(Args), nullptr);
+}
+
 TEST_F(CommandLineExtractorTest, RejectMultipleArchitectures) {
   addFile("test.c", "int main() {}\n");
   const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",



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


[PATCH] D157011: [Clang][Tooling] Accept preprocessed input files

2023-08-08 Thread J. Ryan Stinnett via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG241cceb9af84: [Clang][Tooling] Accept preprocessed input 
files (authored by jryans).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157011

Files:
  clang/lib/Tooling/Tooling.cpp
  clang/unittests/Tooling/ToolingTest.cpp


Index: clang/unittests/Tooling/ToolingTest.cpp
===
--- clang/unittests/Tooling/ToolingTest.cpp
+++ clang/unittests/Tooling/ToolingTest.cpp
@@ -449,6 +449,13 @@
   EXPECT_NE(extractCC1Arguments(Args), nullptr);
 }
 
+TEST_F(CommandLineExtractorTest, AcceptPreprocessedInputFile) {
+  addFile("test.i", "int main() {}\n");
+  const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", "-c",
+"test.i"};
+  EXPECT_NE(extractCC1Arguments(Args), nullptr);
+}
+
 TEST_F(CommandLineExtractorTest, RejectMultipleArchitectures) {
   addFile("test.c", "int main() {}\n");
   const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -147,6 +147,13 @@
 if (IsCC1Command(Job) && llvm::all_of(Job.getInputInfos(), IsSrcFile))
   CC1Jobs.push_back(&Job);
 
+  // If there are no jobs for source files, try checking again for a single job
+  // with any file type. This accepts a preprocessed file as input.
+  if (CC1Jobs.empty())
+for (const driver::Command &Job : Jobs)
+  if (IsCC1Command(Job))
+CC1Jobs.push_back(&Job);
+
   if (CC1Jobs.empty() ||
   (CC1Jobs.size() > 1 && !ignoreExtraCC1Commands(Compilation))) {
 SmallString<256> error_msg;


Index: clang/unittests/Tooling/ToolingTest.cpp
===
--- clang/unittests/Tooling/ToolingTest.cpp
+++ clang/unittests/Tooling/ToolingTest.cpp
@@ -449,6 +449,13 @@
   EXPECT_NE(extractCC1Arguments(Args), nullptr);
 }
 
+TEST_F(CommandLineExtractorTest, AcceptPreprocessedInputFile) {
+  addFile("test.i", "int main() {}\n");
+  const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", "-c",
+"test.i"};
+  EXPECT_NE(extractCC1Arguments(Args), nullptr);
+}
+
 TEST_F(CommandLineExtractorTest, RejectMultipleArchitectures) {
   addFile("test.c", "int main() {}\n");
   const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -147,6 +147,13 @@
 if (IsCC1Command(Job) && llvm::all_of(Job.getInputInfos(), IsSrcFile))
   CC1Jobs.push_back(&Job);
 
+  // If there are no jobs for source files, try checking again for a single job
+  // with any file type. This accepts a preprocessed file as input.
+  if (CC1Jobs.empty())
+for (const driver::Command &Job : Jobs)
+  if (IsCC1Command(Job))
+CC1Jobs.push_back(&Job);
+
   if (CC1Jobs.empty() ||
   (CC1Jobs.size() > 1 && !ignoreExtraCC1Commands(Compilation))) {
 SmallString<256> error_msg;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157324: [clang] Move the Clang CI jobs off of the libc++ builders

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I'm not qualified to give a review of the functional changes, but the intent 
for the changes SGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157324

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


[PATCH] D157269: [Clang][AArch64] Diagnostics for SME attributes when target doesn't have 'sme'

2023-08-08 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:6762
+Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
+if (!CallerFeatureMap.count("sme"))
+  Diag(Loc, diag::err_sme_call_in_non_sme_target);

`contains("sme")` seems more appropriate here?



Comment at: clang/lib/Sema/SemaDecl.cpp:12159
+  Context.getFunctionFeatureMap(FeatureMap, NewFD);
+  if (!FeatureMap.count("sme")) {
+if (UsesSM)

As above.



Comment at: clang/lib/Sema/SemaDecl.cpp:12163
+   diag::err_sme_definition_using_sm_in_non_sme_target);
+else if (UsesZA)
+  Diag(NewFD->getLocation(),

Can this be just `else` given by this point I believe you know `UsesZA` has to 
be true.



Comment at: clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp:1
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve 
-fsyntax-only -verify %s
+

Does the test require SVE to be enabled?



Comment at: clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp:3
+
+// This test is testing the diagnostic that Clang emits when compiling without 
'+sme'.
+

diagnostics



Comment at: 
clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp:13-17
+__attribute__((target("sme"))) void streaming_compatible_def_sme_attr() 
__arm_streaming_compatible {} // OK
+__attribute__((target("sme"))) void streaming_def_sme_attr() __arm_streaming { 
} // OK
+__attribute__((target("sme"))) void shared_za_def_sme_attr() __arm_shared_za { 
} // OK
+__arm_new_za __attribute__((target("sme"))) void new_za_def_sme_attr() {} // OK
+__arm_locally_streaming __attribute__((target("sme"))) void 
locally_streaming_def_sme_attr() {} // OK

Is it worth including tests where "sme2" is used? or are we already comfortable 
feature inheritance is well tested?



Comment at: llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td:144-163
 // It's tricky to using the existing pstate operand defined in
 // AArch64SystemOperands.td since it only encodes 5 bits including op1;op2,
 // when these fields are also encoded in CRm[3:1].
 def MSRpstatesvcrImm1
   : PstateWriteSimple<(ins svcr_op:$pstatefield, timm0_1:$imm), "msr",
   "\t$pstatefield, $imm">,
 Sched<[WriteSys]> {

Doesn't this class belong in SMEInstrFormats.td, then you'll not need to 
override `Predicates`?



Comment at: 
llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll:4
+
+; This that the following code can be compiled without +sme, because if the
+; call is not entered in streaming-SVE mode at runtime, the codepath leading

Verify the...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157269

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


[PATCH] D157384: [clang] Added Attr::getVariety function

2023-08-08 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 created this revision.
strimo378 added a reviewer: aaron.ballman.
Herald added a project: All.
strimo378 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The commit extends ClangAttrEmitter of tablegen to generate Attr*::getVariety() 
function. The function returns the variety of the attribute as an enum. I'll 
use the function in a follow up commit to improve the output of function 
attributes for ast-print.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157384

Files:
  clang/include/clang/AST/Attr.h
  clang/utils/TableGen/ClangAttrEmitter.cpp


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -1498,6 +1498,30 @@
   OS << "}\n\n";
 }
 
+static void writeGetVarietyFunction(const Record &R, raw_ostream &OS) {
+  std::vector Spellings = GetFlattenedSpellings(R);
+
+  OS << "Attr::Variety " << R.getName() << "Attr::getVariety() const {\n";
+  if (Spellings.empty()) {
+OS << "  return Variety::None;\n}\n\n";
+return;
+  }
+
+  OS << "  switch (getAttributeSpellingListIndex()) {\n"
+"  default:\n"
+"llvm_unreachable(\"Unknown attribute spelling!\");\n"
+"return Variety::None;\n";
+
+  for (unsigned I = 0; I < Spellings.size(); ++I) {
+OS << "  case " << I << ":\n";
+OS << "return Variety::" << Spellings[I].variety() << ";\n";
+  }
+  // End of the switch statement.
+  OS << "  }\n";
+  // End of the getVariety function.
+  OS << "}\n\n";
+}
+
 static void
 writePrettyPrintFunction(const Record &R,
  const std::vector> &Args,
@@ -2798,6 +2822,7 @@
   OS << "  void printPretty(raw_ostream &OS,\n"
  << "   const PrintingPolicy &Policy) const;\n";
   OS << "  const char *getSpelling() const;\n";
+  OS << "  Variety getVariety() const;\n";
 }
 
 if (!ElideSpelling) {
@@ -2872,6 +2897,7 @@
 
   writePrettyPrintFunction(R, Args, OS);
   writeGetSpellingFunction(R, OS);
+  writeGetVarietyFunction(R, OS);
 }
   }
 }
@@ -2919,6 +2945,9 @@
   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
   EmitFunc("clone(C)");
 
+  OS << "Attr::Variety Attr::getVariety() const {\n";
+  EmitFunc("getVariety()");
+
   OS << "void Attr::printPretty(raw_ostream &OS, "
 "const PrintingPolicy &Policy) const {\n";
   EmitFunc("printPretty(OS, Policy)");
Index: clang/include/clang/AST/Attr.h
===
--- clang/include/clang/AST/Attr.h
+++ clang/include/clang/AST/Attr.h
@@ -84,6 +84,20 @@
   }
   const char *getSpelling() const;
 
+  enum class Variety {
+None,
+GNU,  // __attribute__((...))
+Declspec, // __declspec(...)
+Microsoft,// [...]
+CXX11,// [[...]]
+C2x,  // [[...]]
+Keyword,  // e.g. _Noreturn, final, __fastcall, etc.
+Pragma,   // #pragma ...
+HLSLSemantic, // :...
+  };
+
+  Variety getVariety() const;
+
   SourceLocation getLocation() const { return getRange().getBegin(); }
 
   bool isInherited() const { return Inherited; }


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -1498,6 +1498,30 @@
   OS << "}\n\n";
 }
 
+static void writeGetVarietyFunction(const Record &R, raw_ostream &OS) {
+  std::vector Spellings = GetFlattenedSpellings(R);
+
+  OS << "Attr::Variety " << R.getName() << "Attr::getVariety() const {\n";
+  if (Spellings.empty()) {
+OS << "  return Variety::None;\n}\n\n";
+return;
+  }
+
+  OS << "  switch (getAttributeSpellingListIndex()) {\n"
+"  default:\n"
+"llvm_unreachable(\"Unknown attribute spelling!\");\n"
+"return Variety::None;\n";
+
+  for (unsigned I = 0; I < Spellings.size(); ++I) {
+OS << "  case " << I << ":\n";
+OS << "return Variety::" << Spellings[I].variety() << ";\n";
+  }
+  // End of the switch statement.
+  OS << "  }\n";
+  // End of the getVariety function.
+  OS << "}\n\n";
+}
+
 static void
 writePrettyPrintFunction(const Record &R,
  const std::vector> &Args,
@@ -2798,6 +2822,7 @@
   OS << "  void printPretty(raw_ostream &OS,\n"
  << "   const PrintingPolicy &Policy) const;\n";
   OS << "  const char *getSpelling() const;\n";
+  OS << "  Variety getVariety() const;\n";
 }
 
 if (!ElideSpelling) {
@@ -2872,6 +2897,7 @@
 
   writePrettyPrintFunction(R, Args, OS);
   writeGetSpellingFunction(R, OS);
+  writeGetVarietyFunction(R, OS);
 }
   }
 }
@@ -2919,6 +2945,9 @@
   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
   EmitFunc("clone(C)");
 
+  OS << "Attr::Variety Att

[PATCH] D156821: [CodeGen] [ubsan] Respect integer overflow handling in abs builtin

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: efriedma, rjmccall, rsmith.
aaron.ballman added a comment.

Adding codegen and ubsan code owners for opinions.




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:1791
+  // Try to eliminate overflow check.
+  if (auto *VCI = dyn_cast(ArgValue)) {
+if (!VCI->isMinSignedValue()) {




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

https://reviews.llvm.org/D156821

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


[PATCH] D157270: [Clang][AArch64] Add diagnostic for calls from non-ZA to shared-ZA functions.

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM aside from a nit.




Comment at: clang/lib/Sema/SemaChecking.cpp:6773
+  bool CallerHasZAState = false;
+  if (auto *CallerFD = dyn_cast(CurContext)) {
+if (CallerFD->hasAttr())




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157270

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


[PATCH] D157385: [clang][CFG] Cleanup functions

2023-08-08 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaronpuchert, NoQ, clang.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This might be a little light on the testing side.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157385

Files:
  clang/include/clang/Analysis/CFG.h
  clang/lib/Analysis/CFG.cpp
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/Analysis/scopes-cfg-output.cpp

Index: clang/test/Analysis/scopes-cfg-output.cpp
===
--- clang/test/Analysis/scopes-cfg-output.cpp
+++ clang/test/Analysis/scopes-cfg-output.cpp
@@ -1419,3 +1419,15 @@
 }
   }
 }
+
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(i)
+// CHECK-NEXT:   2: int i __attribute__((cleanup(cleanup_int)));
+// CHECK-NEXT:   3: CleanupFunction (cleanup_int)
+// CHECK-NEXT:   4: CFGScopeEnd(i)
+void cleanup_int(int *i) {
+}
+
+void test_cleanup_functions() {
+  int i __attribute__((cleanup(cleanup_int)));
+}
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2426,6 +2426,16 @@
 AD.getTriggerStmt()->getEndLoc());
   break;
 }
+
+case CFGElement::CleanupFunction: {
+  const CFGCleanupFunction &CF = BI.castAs();
+
+  LocksetBuilder.handleCall(nullptr, CF.getFunctionDecl(),
+SxBuilder.createVariable(CF.getVarDecl()),
+CF.getVarDecl()->getLocation());
+  break;
+}
+
 case CFGElement::TemporaryDtor: {
   auto TD = BI.castAs();
 
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -881,6 +881,10 @@
 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
   }
 
+  void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
+B->appendCleanupFunction(VD, cfg->getBumpVectorContext());
+  }
+
   void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
   }
@@ -1321,7 +1325,8 @@
 return {};
   }
 
-  bool hasTrivialDestructor(VarDecl *VD);
+  bool hasTrivialDestructor(VarDecl *VD) const;
+  bool needsAutomaticDestruction(const VarDecl *VD) const;
 };
 
 } // namespace
@@ -1840,32 +1845,39 @@
   DeclsNonTrivial.reserve(B.distance(E));
 
   for (VarDecl* D : llvm::make_range(B, E))
-if (!hasTrivialDestructor(D))
+if (needsAutomaticDestruction(D))
   DeclsNonTrivial.push_back(D);
 
   for (VarDecl *VD : llvm::reverse(DeclsNonTrivial)) {
+QualType Ty = VD->getType();
+
+bool IsCXXRecordType = (Ty->getAsCXXRecordDecl() != nullptr);
 if (BuildOpts.AddImplicitDtors) {
   // If this destructor is marked as a no-return destructor, we need to
   // create a new block for the destructor which does not have as a
   // successor anything built thus far: control won't flow out of this
   // block.
-  QualType Ty = VD->getType();
   if (Ty->isReferenceType())
 Ty = getReferenceInitTemporaryType(VD->getInit());
   Ty = Context->getBaseElementType(Ty);
 
-  if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
+  if (IsCXXRecordType &&
+  Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
 Block = createNoReturnBlock();
 }
 
 autoCreateBlock();
 
+bool HasCleanupAttr = VD->hasAttr();
+
 // Add LifetimeEnd after automatic obj with non-trivial destructors,
 // as they end their lifetime when the destructor returns. For trivial
 // objects, we end lifetime with scope end.
 if (BuildOpts.AddLifetime)
   appendLifetimeEnds(Block, VD, S);
-if (BuildOpts.AddImplicitDtors)
+if (HasCleanupAttr)
+  appendCleanupFunction(Block, VD);
+if (BuildOpts.AddImplicitDtors && !hasTrivialDestructor(VD))
   appendAutomaticObjDtor(Block, VD, S);
   }
 }
@@ -2070,7 +2082,12 @@
   return Scope;
 }
 
-bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
+bool CFGBuilder::needsAutomaticDestruction(const VarDecl *VD) const {
+  return !hasTrivialDestructor(const_cast(VD)) ||
+ VD->hasAttr();
+}
+
+bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) const {
   // Check for const references bound to temporary. Set type to pointee.
   QualType QT = VD->getType();
   if (QT->isReferenceType()) {
@@ -2124,7 +2141,7 @@
 return Scope;
 
   if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes &&
-  hasTrivialDestructor(VD)) {
+  !needsAutomaticDestruction(VD)) {
 assert(BuildOpts.AddImplicitDtors);
 return Scope;
   }
@@ -5262,8 +5279,9 @@
 case CFGElement::CXXRecordTypedCall:
 case CFGElement::ScopeBegin:
 case CFGElement::

[PATCH] D157383: [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-08 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Interp.h:530-535
   if (S.checkingForUndefinedBehavior()) {
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();

hazohelet wrote:
> I'm not sure whether this branch takes effect.
> I could not find codes that takes this block, so I haven't added tests for 
> this.
> 
> FWIW, the old interpreter does not have the corresponding 
> `warn_integer_constant_overflow` generated against overflowing increments.
Is is not this: https://godbolt.org/z/eqn4Gs13q?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157383

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


[PATCH] D157383: [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-08 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added inline comments.



Comment at: clang/lib/AST/Interp/Interp.h:530-535
   if (S.checkingForUndefinedBehavior()) {
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();

tbaeder wrote:
> hazohelet wrote:
> > I'm not sure whether this branch takes effect.
> > I could not find codes that takes this block, so I haven't added tests for 
> > this.
> > 
> > FWIW, the old interpreter does not have the corresponding 
> > `warn_integer_constant_overflow` generated against overflowing increments.
> Is is not this: https://godbolt.org/z/eqn4Gs13q?
That note is emitted from `S.CCEDiag` at L539.
This warning looks like it is intended to be emitted when the function is not 
constexpr, but it does not appear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157383

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


[PATCH] D157269: [Clang][AArch64] Diagnostics for SME attributes when target doesn't have 'sme'

2023-08-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen updated this revision to Diff 548168.
sdesmalen marked 10 inline comments as done.
sdesmalen added a comment.

Address further review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157269

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp
  llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/lib/Target/AArch64/SMEInstrFormats.td
  
llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll

Index: llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/sme-call-streaming-compatible-to-normal-fn-wihout-sme-attr.ll
@@ -0,0 +1,41 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 2
+; RUN: llc < %s | FileCheck %s
+
+; Verify that the following code can be compiled without +sme, because if the
+; call is not entered in streaming-SVE mode at runtime, the codepath leading
+; to the smstop/smstart pair will not be executed either.
+
+target triple = "aarch64"
+
+define void @streaming_compatible() #0 {
+; CHECK-LABEL: streaming_compatible:
+; CHECK:   // %bb.0:
+; CHECK-NEXT:stp d15, d14, [sp, #-80]! // 16-byte Folded Spill
+; CHECK-NEXT:stp d13, d12, [sp, #16] // 16-byte Folded Spill
+; CHECK-NEXT:stp d11, d10, [sp, #32] // 16-byte Folded Spill
+; CHECK-NEXT:stp d9, d8, [sp, #48] // 16-byte Folded Spill
+; CHECK-NEXT:stp x30, x19, [sp, #64] // 16-byte Folded Spill
+; CHECK-NEXT:bl __arm_sme_state
+; CHECK-NEXT:and x19, x0, #0x1
+; CHECK-NEXT:tbz x19, #0, .LBB0_2
+; CHECK-NEXT:  // %bb.1:
+; CHECK-NEXT:smstop sm
+; CHECK-NEXT:  .LBB0_2:
+; CHECK-NEXT:bl non_streaming
+; CHECK-NEXT:tbz x19, #0, .LBB0_4
+; CHECK-NEXT:  // %bb.3:
+; CHECK-NEXT:smstart sm
+; CHECK-NEXT:  .LBB0_4:
+; CHECK-NEXT:ldp x30, x19, [sp, #64] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d9, d8, [sp, #48] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d11, d10, [sp, #32] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d13, d12, [sp, #16] // 16-byte Folded Reload
+; CHECK-NEXT:ldp d15, d14, [sp], #80 // 16-byte Folded Reload
+; CHECK-NEXT:ret
+  call void @non_streaming()
+  ret void
+}
+
+declare void @non_streaming()
+
+attributes #0 = { nounwind "aarch64_pstate_sm_compatible" }
Index: llvm/lib/Target/AArch64/SMEInstrFormats.td
===
--- llvm/lib/Target/AArch64/SMEInstrFormats.td
+++ llvm/lib/Target/AArch64/SMEInstrFormats.td
@@ -190,6 +190,42 @@
 : Pat<(intrinsic imm_ty:$tile, (pg_ty PPR3bAny:$Pn), (pg_ty PPR3bAny:$Pm), vt:$Zn, vt:$Zm),
   (!cast(name # _PSEUDO) $tile, $Pn, $Pm, $Zn, $Zm)>;
 
+
+//===--===//
+// SME smstart/smstop
+//===--===//
+
+// SME defines three pstate fields to set or clear PSTATE.SM, PSTATE.ZA, or
+// both fields:
+//
+//   MSR SVCRSM, #
+//   MSR SVCRZA, #
+//   MSR SVCRSMZA, #
+//
+// It's tricky to using the existing pstate operand defined in
+// AArch64SystemOperands.td since it only encodes 5 bits including op1;op2,
+// when these fields are also encoded in CRm[3:1].
+def MSRpstatesvcrImm1
+  : PstateWriteSimple<(ins svcr_op:$pstatefield, timm0_1:$imm), "msr",
+  "\t$pstatefield, $imm">,
+Sched<[WriteSys]> {
+  bits<3> pstatefield;
+  bit imm;
+  let Inst{18-16} = 0b011; // op1
+  let Inst{11-9} = pstatefield;
+  let Inst{8} = imm;
+  let Inst{7-5} = 0b011; // op2
+}
+
+def : InstAlias<"smstart",(MSRpstatesvcrImm1 0b011, 0b1)>;
+def : InstAlias<"smstart sm", (MSRpstatesvcrImm1 0b001, 0b1)>;
+def : InstAlias<"smstart za", (MSRpstatesvcrImm1 0b010, 0b1)>;
+
+def : InstAlias<"smstop", (MSRpstatesvcrImm1 0b011, 0b0)>;
+def : InstAlias<"smstop sm",  (MSRpstatesvcrImm1 0b001, 0b0)>;
+def : InstAlias<"smstop za",  (MSRpstatesvcrImm1 0b010, 0b0)>;
+
+
 //===--===//
 // SME Outer Products
 //===--===//
Index: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
===
--- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
+++ llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
@@ -442,8 +442,6 @@
 
   assert((!StreamingSVEMode || I->hasSME()) &&
  "Expected SME to be available");
-  assert((!StreamingCompatibleSVEMode || I->hasSVEorSME()) &&
- "Expected SVE or SME to be available");
 
   return I.get();
 }

[PATCH] D157269: [Clang][AArch64] Diagnostics for SME attributes when target doesn't have 'sme'

2023-08-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: 
clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp:13-17
+__attribute__((target("sme"))) void streaming_compatible_def_sme_attr() 
__arm_streaming_compatible {} // OK
+__attribute__((target("sme"))) void streaming_def_sme_attr() __arm_streaming { 
} // OK
+__attribute__((target("sme"))) void shared_za_def_sme_attr() __arm_shared_za { 
} // OK
+__arm_new_za __attribute__((target("sme"))) void new_za_def_sme_attr() {} // OK
+__arm_locally_streaming __attribute__((target("sme"))) void 
locally_streaming_def_sme_attr() {} // OK

paulwalker-arm wrote:
> Is it worth including tests where "sme2" is used? or are we already 
> comfortable feature inheritance is well tested?
I'm not sure how well this is tested, but I guess there's no harm in adding an 
extra test for it.



Comment at: llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td:144-163
 // It's tricky to using the existing pstate operand defined in
 // AArch64SystemOperands.td since it only encodes 5 bits including op1;op2,
 // when these fields are also encoded in CRm[3:1].
 def MSRpstatesvcrImm1
   : PstateWriteSimple<(ins svcr_op:$pstatefield, timm0_1:$imm), "msr",
   "\t$pstatefield, $imm">,
 Sched<[WriteSys]> {

paulwalker-arm wrote:
> Doesn't this class belong in SMEInstrFormats.td, then you'll not need to 
> override `Predicates`?
Good point, I've moved the class over and the InstAliases as well (which I 
guess also shouldn't depend on SME being available)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157269

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


[PATCH] D156693: [clang][ASTImporter]Skip check friend template depth

2023-08-08 Thread Qizhi Hu via Phabricator via cfe-commits
jcsxky updated this revision to Diff 548166.
jcsxky edited the summary of this revision.
jcsxky added a comment.

update diff: add more conditions on when to ignore comparing depth of two 
template classes to minimize influence to others and fix name of test case to 
make easy understanding


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156693

Files:
  clang/include/clang/AST/ASTStructuralEquivalence.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -4212,6 +4212,56 @@
   EXPECT_TRUE(Imported->getPreviousDecl());
 }
 
+TEST_P(ImportFriendClasses, SkipComparingFriendTemplateDepth) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A;
+
+  template 
+  class A {
+  public:
+template 
+friend class A;
+
+A(T x)  :x(x) {}
+
+  private:
+T x;
+  };
+  )",
+  Lang_CXX11);
+
+  auto *Fwd = FirstDeclMatcher().match(
+  ToTU, classTemplateDecl(hasName("A")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A;
+
+  template 
+  class A {
+  public:
+template 
+friend class A;
+
+A(T x) : x(x) {}
+
+  private:
+T x;
+  };
+
+  A a1(0);
+  )",
+  Lang_CXX11, "input1.cc");
+  auto *FromA = FirstDeclMatcher().match(
+  FromTU, classTemplateDecl(hasName("A")));
+  auto *ToA = Import(FromA, Lang_CXX11);
+  EXPECT_TRUE(ToA);
+  EXPECT_EQ(Fwd->getTemplatedDecl()->getTypeForDecl(),
+ToA->getTemplatedDecl()->getTypeForDecl());
+}
+
 TEST_P(ImportFriendClasses,
ImportOfClassTemplateDefinitionShouldConnectToFwdFriend) {
   Decl *ToTU = getToTuDecl(
Index: clang/lib/AST/ASTStructuralEquivalence.cpp
===
--- clang/lib/AST/ASTStructuralEquivalence.cpp
+++ clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -1092,7 +1092,7 @@
   case Type::TemplateTypeParm: {
 const auto *Parm1 = cast(T1);
 const auto *Parm2 = cast(T2);
-if (Parm1->getDepth() != Parm2->getDepth())
+if (!Context.IgnoreDepth && Parm1->getDepth() != Parm2->getDepth())
   return false;
 if (Parm1->getIndex() != Parm2->getIndex())
   return false;
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -34,6 +34,7 @@
 #include "clang/AST/LambdaCapture.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/OperationKinds.h"
+#include "clang/AST/ParentMapContext.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtCXX.h"
 #include "clang/AST/StmtObjC.h"
@@ -506,7 +507,8 @@
 template 
 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
 
-bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true);
+bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true,
+   bool IgnoreDepth = true);
 ExpectedDecl VisitDecl(Decl *D);
 ExpectedDecl VisitImportDecl(ImportDecl *D);
 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
@@ -2243,7 +2245,8 @@
 : StructuralEquivalenceKind::Default;
 }
 
-bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
+bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
+bool IgnoreDepth) {
   // Eliminate a potential failure point where we attempt to re-import
   // something we're trying to import while completing ToRecord.
   Decl *ToOrigin = Importer.GetOriginalDecl(To);
@@ -2254,7 +2257,7 @@
   StructuralEquivalenceContext Ctx(
   Importer.getFromContext(), Importer.getToContext(),
   Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
-  false, Complain);
+  false, Complain, false, IgnoreDepth);
   return Ctx.IsEquivalent(From, To);
 }
 
@@ -5822,7 +5825,11 @@
 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
   continue;
 
-if (IsStructuralMatch(D, FoundTemplate)) {
+// FIXME: sufficient conditon for 'IgnoreDepth'?
+bool IgnoreDepth =
+FoundTemplate->getFriendObjectKind() != Decl::FOK_None &&
+!D->specializations().empty();
+if (IsStructuralMatch(D, FoundTemplate, true, IgnoreDepth)) {
   ClassTemplateDecl *TemplateWithDef =
   getTemplateDefinition(FoundTemplate);
   if (D->isThisDeclarationADefinition() && TemplateWithDef)
Index: clang/include/clang/AST/ASTStructuralEquivalence.h
=

[PATCH] D156320: [FLang] Add support for Rpass flag

2023-08-08 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 548175.
victorkingi added a comment.

changed enum to enum class


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,48 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Reverything implies -Rpass=.*.
+! RUN: %flang_fc1 %s -O1 -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Rpass implies -Rpass=.*
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass=loop-delete 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+
+! CHECK: remark: Loop deleted because it is invariant
+! CHECK-REMARKS-MISSED: remark: loop not vectorized
+! CHECK-REMARKS-ANALYSIS: remark: loop not vectorized: call instruction cannot be vectorized
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -22,6 +22,13 @@
 ! RUN: -fppc-native-vector-element-order \
 ! RUN: -mllvm -print-before-all \
 ! RUN: -save-temps=obj \
+! RUN: -Rpass \
+! RUN: -Rpass-missed \
+! RUN: -Rpass-analysis \
+! RUN: -Rno-pass \
+! RUN: -Reverything \
+! RUN: -Rno-everything \
+! RUN: -Rpass=inline \
 ! RUN: -P \
 ! RUN:   | FileCheck %s
 
@@ -44,5 +51,12 @@
 ! CHECK: "-flang-experimental-hlfir"
 ! CHECK: "-fno-ppc-native-vector-element-order"
 ! CHECK: "-fppc-native-vector-element-order"
+! CHECK: "-Rpass"
+! CHECK: "-Rpass-missed"
+! CHECK: "-Rpass-analysis"
+! CHECK: "-Rno-pass"
+! CHECK: "-Reverything"
+! CHECK: "-Rno-everything"
+! CHECK: "-Rpass=inline"
 ! CHECK: "-mllvm" "-print-before-all"
 ! CHECK: "-save-temps=obj"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -91,6 +91,10 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -R  Enable the specified remark
 ! HELP-NEXT: -save-temps=Save intermediate compilation results.
 ! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
@@ -214,6 +218,10 @@
 ! HELP-FC1-NEXT: -pic-level   Value for _

[PATCH] D156693: [clang][ASTImporter]Skip check friend template depth

2023-08-08 Thread Qizhi Hu via Phabricator via cfe-commits
jcsxky added a comment.

In D156693#4568941 , @balazske wrote:

> This fix can cause problems because the depth comparison is omitted all 
> times. It would be better to omit depth check if the imported template is a 
> friend, and has a `ClassTemplateSpecializationDecl` as context. Probably even 
> then it is possible to construct cases where the checked template has 
> references to other templates with different "depth" which should not omitted 
> in the check. But I have no idea of a better solution, only to pass a 
> `ClassTemplateDecl` or `ClassTemplateSpecializationDecl` to 
> `StructuralEquivalenceContext` and omit the depth check only at this object.

Thanks for your advice. More conditions are added to check when to ignore the 
comparison and minimize the influence to other.
Also I have tried to not increase depth in friend declaration in the template 
class, but the code affects others a lot. Only to skip the comparison can pass 
this special case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156693

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


[PATCH] D156320: [FLang] Add support for Rpass flag

2023-08-08 Thread victorkingi via Phabricator via cfe-commits
victorkingi added a comment.

In D156320#4559248 , 
@kiranchandramohan wrote:

>> rpass flag now prints remarks when requested but does not display
>> the passName used, i.e [-Rpass=inline]
>
> I think the location information is also not printed. Please check the 
> difference in implementation of the `TextDiagnosticPrinter::HandleDiagnostic` 
> function in clang 
> (https://github.com/llvm/llvm-project/blob/7240008c0afa3e2d12f3f51cfe0235668feb6ef3/clang/lib/Frontend/TextDiagnosticPrinter.cpp#L109)
>  and flang 
> (https://github.com/llvm/llvm-project/blob/7240008c0afa3e2d12f3f51cfe0235668feb6ef3/flang/lib/Frontend/TextDiagnosticPrinter.cpp#L32).
> In particular, the passName is printed in the printDiagnosticOptions function 
> https://github.com/llvm/llvm-project/blob/7240008c0afa3e2d12f3f51cfe0235668feb6ef3/clang/lib/Frontend/TextDiagnosticPrinter.cpp#L85

Hi @kiranchandramohan location now gets printed as the absolute path. In 
certain situations, clang preserves the dots e.g. if the user provides 
"../my_location/my_file" it will print the exact same, while flang expands to 
absolute path. So that would be one difference.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: VitaNuo.
Herald added subscribers: PiotrZSL, carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

We received some user feedback around this being disruptful rather than
useful in certain workflows so add an option to control the output behaviour.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157390

Files:
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -15,6 +15,8 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/Testing/Annotations/Annotations.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -108,6 +110,48 @@
)"}}));
 }
 
+TEST(IncludeCleanerCheckTest, DedupsMissingIncludes) {
+  llvm::Annotations Code(R"(
+#include "baz.h" // IWYU pragma: keep
+
+int BarResult1 = $diag^bar();
+int BarResult2 = bar();)");
+
+  {
+std::vector Errors;
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, ClangTidyOptions(),
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(1U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag"));
+  }
+  {
+std::vector Errors;
+ClangTidyOptions Opts;
+Opts.CheckOptions.insert({"DeduplicateFindings", "false"});
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, Opts,
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(2U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.back().Message.Message,
+  "no header providing \"bar\" is directly included");
+  }
+}
+
 TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
   const char *PreCode = R"(
 #include "bar.h"
Index: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
@@ -33,3 +33,8 @@
files that match this regex as a suffix.  E.g., `foo/.*` disables
insertion/removal for all headers under the directory `foo`. By default, no 
headers will be ignored.
+
+.. option:: DeduplicateFindings
+
+   A boolean that controls whether the check should deduplicate findings for the
+   same symbol. Defaults to true.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -163,6 +163,9 @@
   `, so that it does not warn
   on macros starting with underscore and lowercase letter.
 
+- Misc-include-cleaner check has option `DeduplicateFindings` to output one
+  finding per occurence of a symbol.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
+++ clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
@@ -44,6 +44,8 @@
   include_cleaner::PragmaIncludes RecordedPI;
   HeaderSearch *HS;
   std::vector IgnoreHeaders;
+  // Whether emit only one finding per usage of a symbol.
+  const bool EmitOnce;
   llvm::SmallVector IgnoreHeadersRegex;
   bool shouldIgnore(const include_cleaner::Header &H);
 };
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
===

[PATCH] D144831: Rebase D41416 on top of master

2023-08-08 Thread Shreyas via Phabricator via cfe-commits
SAtacker updated this revision to Diff 548183.
SAtacker added a comment.
Herald added a subscriber: cfe-commits.

[Clang][Modules] Optimized template arguments ODR hash search for modules/PCH


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144831

Files:
  clang/include/clang/AST/DeclTemplate.h
  clang/include/clang/AST/ExternalASTSource.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/AST/ExternalASTSource.cpp
  clang/lib/AST/ODRHash.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp

Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -177,11 +177,11 @@
   Record.AddSourceLocation(typeParams->getRAngleLoc());
 }
 
-/// Add to the record the first declaration from each module file that
-/// provides a declaration of D. The intent is to provide a sufficient
-/// set such that reloading this set will load all current redeclarations.
-void AddFirstDeclFromEachModule(const Decl *D, bool IncludeLocal) {
-  llvm::MapVector Firsts;
+/// Collect the first declaration from each module file that provides a
+/// declaration of D.
+void CollectFirstDeclFromEachModule(const Decl *D, bool IncludeLocal,
+llvm::MapVector &Firsts) {
+
   // FIXME: We can skip entries that we know are implied by others.
   for (const Decl *R = D->getMostRecentDecl(); R; R = R->getPreviousDecl()) {
 if (R->isFromASTFile())
@@ -189,10 +189,49 @@
 else if (IncludeLocal)
   Firsts[nullptr] = R;
   }
+}
+
+/// Add to the record the first declaration from each module file that
+/// provides a declaration of D. The intent is to provide a sufficient
+/// set such that reloading this set will load all current redeclarations.
+void AddFirstDeclFromEachModule(const Decl *D, bool IncludeLocal) {
+  llvm::MapVector Firsts;
+  CollectFirstDeclFromEachModule(D, IncludeLocal, Firsts);
+
   for (const auto &F : Firsts)
 Record.AddDeclRef(F.second);
 }
 
+/// Add to the record the first template specialization from each module
+/// file that provides a declaration of D. We store the DeclId and an
+/// ODRHash of the template arguments of D which should provide enough
+/// information to load D only if the template instantiator needs it.
+void AddFirstSpecializationDeclFromEachModule(const Decl *D,
+  bool IncludeLocal) {
+  assert(isa(D) ||
+ isa(D) || isa(D) &&
+ "Must not be called with other decls");
+  llvm::MapVector Firsts;
+  CollectFirstDeclFromEachModule(D, IncludeLocal, Firsts);
+
+  for (const auto &F : Firsts) {
+Record.AddDeclRef(F.second);
+ArrayRef Args;
+if (auto *CTSD = dyn_cast(D))
+  Args = CTSD->getTemplateArgs().asArray();
+else if (auto *VTSD = dyn_cast(D))
+  Args = VTSD->getTemplateArgs().asArray();
+else if (auto *FD = dyn_cast(D))
+  Args = FD->getTemplateSpecializationArgs()->asArray();
+assert(Args.size());
+Record.push_back(TemplateArgumentList::ComputeODRHash(Args));
+bool IsPartialSpecialization
+  = isa(D) ||
+  isa(D);
+Record.push_back(IsPartialSpecialization);
+  }
+}
+
 /// Get the specialization decl from an entry in the specialization list.
 template 
 typename RedeclarableTemplateDecl::SpecEntryTraits::DeclType *
@@ -205,7 +244,9 @@
 decltype(T::PartialSpecializations) &getPartialSpecializations(T *Common) {
   return Common->PartialSpecializations;
 }
-ArrayRef getPartialSpecializations(FunctionTemplateDecl::Common *) {
+
+MutableArrayRef
+getPartialSpecializations(FunctionTemplateDecl::Common *) {
   return std::nullopt;
 }
 
@@ -222,9 +263,11 @@
 assert(!Common->LazySpecializations);
   }
 
-  ArrayRef LazySpecializations;
+  using LazySpecializationInfo
+= RedeclarableTemplateDecl::LazySpecializationInfo;
+  ArrayRef LazySpecializations;
   if (auto *LS = Common->LazySpecializations)
-LazySpecializations = llvm::ArrayRef(LS + 1, LS[0]);
+LazySpecializations = llvm::makeArrayRef(LS + 1, LS[0].DeclID);
 
   // Add a slot to the record for the number of specializations.
   unsigned I = Record.size();
@@ -240,12 +283,20 @@
 
   for (auto *D : Specs) {
 assert(D->isCanonicalDecl() && "non-canonical decl in set");
-AddFirstDeclFr

[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo accepted this revision.
VitaNuo added a comment.
This revision is now accepted and ready to land.

Thanks.




Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h:48
+  // Whether emit only one finding per usage of a symbol.
+  const bool EmitOnce;
   llvm::SmallVector IgnoreHeadersRegex;

Nit: let's name this similar or same to the option, i.e., `const bool 
DeduplicateFindings`. It might be easier to digest.



Comment at: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp:150
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.back().Message.Message,
+  "no header providing \"bar\" is directly included");

Nit: check that these are actually different findings (i.e., stemming from 
different symbol refs).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

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


[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 548190.
kadircet marked 2 inline comments as done.
kadircet added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

Files:
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -15,6 +15,8 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/Testing/Annotations/Annotations.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -108,6 +110,50 @@
)"}}));
 }
 
+TEST(IncludeCleanerCheckTest, DedupsMissingIncludes) {
+  llvm::Annotations Code(R"(
+#include "baz.h" // IWYU pragma: keep
+
+int BarResult1 = $diag1^bar();
+int BarResult2 = $diag2^bar();)");
+
+  {
+std::vector Errors;
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, ClangTidyOptions(),
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(1U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+  }
+  {
+std::vector Errors;
+ClangTidyOptions Opts;
+Opts.CheckOptions.insert({"DeduplicateFindings", "false"});
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, Opts,
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(2U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+EXPECT_EQ(Errors.back().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.back().Message.FileOffset, Code.point("diag2"));
+  }
+}
+
 TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
   const char *PreCode = R"(
 #include "bar.h"
Index: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
@@ -33,3 +33,8 @@
files that match this regex as a suffix.  E.g., `foo/.*` disables
insertion/removal for all headers under the directory `foo`. By default, no 
headers will be ignored.
+
+.. option:: DeduplicateFindings
+
+   A boolean that controls whether the check should deduplicate findings for the
+   same symbol. Defaults to true.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -163,6 +163,9 @@
   `, so that it does not warn
   on macros starting with underscore and lowercase letter.
 
+- Misc-include-cleaner check has option `DeduplicateFindings` to output one
+  finding per occurence of a symbol.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
+++ clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
@@ -44,6 +44,8 @@
   include_cleaner::PragmaIncludes RecordedPI;
   HeaderSearch *HS;
   std::vector IgnoreHeaders;
+  // Whether emit only one finding per usage of a symbol.
+  const bool DeduplicateFindings;
   llvm::SmallVector IgnoreHeadersRegex;
   bool shouldIgnore(const include_cleaner::Header &H);
 };
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
+++ clang-tools-extra/clang-tidy/

[PATCH] D152054: [OpenMP] Codegen support for thread_limit on target directive

2023-08-08 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Please, use the script to generate the checks for the newly added tests


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

https://reviews.llvm.org/D152054

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


[clang] 247cc26 - [CUDA][HIP] Fix overloading resolution of delete operator

2023-08-08 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2023-08-08T09:50:24-04:00
New Revision: 247cc265e74e25164ee7ce85e6c9c53b3d177740

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

LOG: [CUDA][HIP] Fix overloading resolution of delete operator

Currently clang does not consider host/device preference
when resolving delete operator in the file scope, which
causes device operator delete selected for class member
initialization.

Reviewed by: Artem Belevich

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

Added: 
clang/test/CodeGenCUDA/member-init.cu
clang/test/SemaCUDA/member-init.cu

Modified: 
clang/lib/Sema/SemaExprCXX.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 423d5372a6f65a..82afb084efd0b1 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -1714,8 +1714,8 @@ namespace {
 
   // In CUDA, determine how much we'd like / dislike to call this.
   if (S.getLangOpts().CUDA)
-if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
-  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
+CUDAPref = S.IdentifyCUDAPreference(
+S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
 }
 
 explicit operator bool() const { return FD; }

diff  --git a/clang/test/CodeGenCUDA/member-init.cu 
b/clang/test/CodeGenCUDA/member-init.cu
new file mode 100644
index 00..8d1db494a40e4a
--- /dev/null
+++ b/clang/test/CodeGenCUDA/member-init.cu
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -fexceptions \
+// RUN:   -o - -x hip %s | FileCheck %s
+
+#include "Inputs/cuda.h"
+
+int* hvar;
+__device__ int* dvar;
+
+// CHECK-LABEL: define {{.*}}@_Znwm
+// CHECK:load ptr, ptr @hvar
+void* operator new(unsigned long size) {
+  return hvar;
+}
+// CHECK-LABEL: define {{.*}}@_ZdlPv
+// CHECK:store ptr inttoptr (i64 1 to ptr), ptr @hvar
+void operator delete(void *p) {
+  hvar = (int*)1;
+}
+
+__device__ void* operator new(unsigned long size) {
+  return dvar;
+}
+
+__device__ void operator delete(void *p) {
+  dvar = (int*)11;
+}
+
+class A {
+  int x;
+public:
+  A(){
+x = 123;
+  }
+};
+
+template
+class shared_ptr {
+   int id;
+   T *ptr;
+public:
+  shared_ptr(T *p) {
+id = 2;
+ptr = p;
+  }
+};
+
+// The constructor of B calls the delete operator to clean up
+// the memory allocated by the new operator when exceptions happen.
+// Make sure the host delete operator is used on host side.
+//
+// No need to do similar checks on the device side since it does
+// not support exception.
+
+// CHECK-LABEL: define {{.*}}@main
+// CHECK:call void @_ZN1BC1Ev
+
+// CHECK-LABEL: define {{.*}}@_ZN1BC1Ev
+// CHECK:call void @_ZN1BC2Ev
+
+// CHECK-LABEL: define {{.*}}@_ZN1BC2Ev
+// CHECK: call {{.*}}@_Znwm
+// CHECK:  invoke void @_ZN1AC1Ev
+// CHECK:  call void @_ZN10shared_ptrI1AEC1EPS0_
+// CHECK:  cleanup
+// CHECK:  call void @_ZdlPv
+
+struct B{
+  shared_ptr pa{new A};
+};
+
+int main() {
+  B b;
+}

diff  --git a/clang/test/SemaCUDA/member-init.cu 
b/clang/test/SemaCUDA/member-init.cu
new file mode 100644
index 00..a796a50e9c8768
--- /dev/null
+++ b/clang/test/SemaCUDA/member-init.cu
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fexceptions %s
+// expected-no-diagnostics
+
+#include "Inputs/cuda.h"
+
+__device__ void operator delete(void *p) {}
+
+class A {
+  int x;
+public:
+  A() {
+  x = 123;
+  }
+};
+
+template
+class shared_ptr {
+  T *ptr;
+public:
+  shared_ptr(T *p) {
+ptr = p;
+  }
+};
+
+// The constructor of B calls the delete operator to clean up
+// the memory allocated by the new operator when exceptions happen.
+// Make sure that there are no diagnostics due to the device delete
+// operator is used.
+//
+// No need to do similar checks on the device side since it does
+// not support exception.
+struct B{
+  shared_ptr pa{new A};
+};
+
+int main() {
+  B b;
+}



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


[PATCH] D156795: [CUDA][HIP] Fix overloading resolution of delete operator

2023-08-08 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG247cc265e74e: [CUDA][HIP] Fix overloading resolution of 
delete operator (authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D156795?vs=546045&id=548198#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156795

Files:
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CodeGenCUDA/member-init.cu
  clang/test/SemaCUDA/member-init.cu

Index: clang/test/SemaCUDA/member-init.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/member-init.cu
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fexceptions %s
+// expected-no-diagnostics
+
+#include "Inputs/cuda.h"
+
+__device__ void operator delete(void *p) {}
+
+class A {
+  int x;
+public:
+  A() {
+  x = 123;
+  }
+};
+
+template
+class shared_ptr {
+  T *ptr;
+public:
+  shared_ptr(T *p) {
+ptr = p;
+  }
+};
+
+// The constructor of B calls the delete operator to clean up
+// the memory allocated by the new operator when exceptions happen.
+// Make sure that there are no diagnostics due to the device delete
+// operator is used.
+//
+// No need to do similar checks on the device side since it does
+// not support exception.
+struct B{
+  shared_ptr pa{new A};
+};
+
+int main() {
+  B b;
+}
Index: clang/test/CodeGenCUDA/member-init.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/member-init.cu
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -fexceptions \
+// RUN:   -o - -x hip %s | FileCheck %s
+
+#include "Inputs/cuda.h"
+
+int* hvar;
+__device__ int* dvar;
+
+// CHECK-LABEL: define {{.*}}@_Znwm
+// CHECK:load ptr, ptr @hvar
+void* operator new(unsigned long size) {
+  return hvar;
+}
+// CHECK-LABEL: define {{.*}}@_ZdlPv
+// CHECK:store ptr inttoptr (i64 1 to ptr), ptr @hvar
+void operator delete(void *p) {
+  hvar = (int*)1;
+}
+
+__device__ void* operator new(unsigned long size) {
+  return dvar;
+}
+
+__device__ void operator delete(void *p) {
+  dvar = (int*)11;
+}
+
+class A {
+  int x;
+public:
+  A(){
+x = 123;
+  }
+};
+
+template
+class shared_ptr {
+   int id;
+   T *ptr;
+public:
+  shared_ptr(T *p) {
+id = 2;
+ptr = p;
+  }
+};
+
+// The constructor of B calls the delete operator to clean up
+// the memory allocated by the new operator when exceptions happen.
+// Make sure the host delete operator is used on host side.
+//
+// No need to do similar checks on the device side since it does
+// not support exception.
+
+// CHECK-LABEL: define {{.*}}@main
+// CHECK:call void @_ZN1BC1Ev
+
+// CHECK-LABEL: define {{.*}}@_ZN1BC1Ev
+// CHECK:call void @_ZN1BC2Ev
+
+// CHECK-LABEL: define {{.*}}@_ZN1BC2Ev
+// CHECK: call {{.*}}@_Znwm
+// CHECK:  invoke void @_ZN1AC1Ev
+// CHECK:  call void @_ZN10shared_ptrI1AEC1EPS0_
+// CHECK:  cleanup
+// CHECK:  call void @_ZdlPv
+
+struct B{
+  shared_ptr pa{new A};
+};
+
+int main() {
+  B b;
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -1714,8 +1714,8 @@
 
   // In CUDA, determine how much we'd like / dislike to call this.
   if (S.getLangOpts().CUDA)
-if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
-  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
+CUDAPref = S.IdentifyCUDAPreference(
+S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
 }
 
 explicit operator bool() const { return FD; }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157197: [clang][CodeGen][OpenMP] Fix if-clause for 'target teams loop'

2023-08-08 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:1570-1575
+  // If we are here with a 'target teams loop' then we are emitting the
+  // 'parallel' region of the 'target teams distribute parallel for'
+  // emitted in place of the 'target teams loop'. Based on the specification
+  // noted above, an if-clause associated with a 'target teams loop', be it
+  // 'if(val)' or an 'if(target:val)', will apply only to 'target' and not
+  // the 'parallel' of the 'target teams distribute parallel for'.

It does not match the spec. 
```
For a combined or composite construct, if no directive-name-modifier is 
specified then the if clause applies to all constituent constructs to which an 
if clause can apply.
```
So, if(val) should be applied to both target and parallel regions, no?


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

https://reviews.llvm.org/D157197

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


[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 548199.
kadircet added a comment.

- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

Files:
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -15,6 +15,8 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/Testing/Annotations/Annotations.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -108,6 +110,50 @@
)"}}));
 }
 
+TEST(IncludeCleanerCheckTest, DedupsMissingIncludes) {
+  llvm::Annotations Code(R"(
+#include "baz.h" // IWYU pragma: keep
+
+int BarResult1 = $diag1^bar();
+int BarResult2 = $diag2^bar();)");
+
+  {
+std::vector Errors;
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, ClangTidyOptions(),
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(1U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+  }
+  {
+std::vector Errors;
+ClangTidyOptions Opts;
+Opts.CheckOptions.insert({"DeduplicateFindings", "false"});
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, Opts,
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(2U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+EXPECT_EQ(Errors.back().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.back().Message.FileOffset, Code.point("diag2"));
+  }
+}
+
 TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
   const char *PreCode = R"(
 #include "bar.h"
Index: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
@@ -33,3 +33,8 @@
files that match this regex as a suffix.  E.g., `foo/.*` disables
insertion/removal for all headers under the directory `foo`. By default, no 
headers will be ignored.
+
+.. option:: DeduplicateFindings
+
+   A boolean that controls whether the check should deduplicate findings for the
+   same symbol. Defaults to true.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -192,6 +192,9 @@
   ` check to emit proper
   warnings when a type forward declaration precedes its definition.
 
+- Misc-include-cleaner check has option `DeduplicateFindings` to output one
+  finding per occurence of a symbol.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
+++ clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
@@ -44,6 +44,8 @@
   include_cleaner::PragmaIncludes RecordedPI;
   HeaderSearch *HS;
   std::vector IgnoreHeaders;
+  // Whether emit only one finding per usage of a symbol.
+  const bool DeduplicateFindings;
   llvm::SmallVector IgnoreHeadersRegex;
   bool shouldIgnore(const include_cleaner::Header &H);
 };
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
@@ -55,7 +55,9 @@

[PATCH] D157394: [clang][DeclPrinter] Improved AST print of function attributes

2023-08-08 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 created this revision.
Herald added a project: All.
strimo378 requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, wangpc, jplehr, sstefan1.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157394

Files:
  clang/lib/AST/DeclPrinter.cpp
  clang/test/AST/ast-print-no-sanitize.cpp
  clang/test/OpenMP/assumes_codegen.cpp
  clang/test/OpenMP/assumes_print.cpp
  clang/test/OpenMP/assumes_template_print.cpp
  clang/test/OpenMP/declare_simd_ast_print.cpp
  clang/test/SemaCXX/attr-no-sanitize.cpp
  clang/test/SemaCXX/cxx11-attr-print.cpp

Index: clang/test/SemaCXX/cxx11-attr-print.cpp
===
--- clang/test/SemaCXX/cxx11-attr-print.cpp
+++ clang/test/SemaCXX/cxx11-attr-print.cpp
@@ -42,21 +42,21 @@
 // CHECK: int f1() __attribute__((warn_unused_result("")));
 int f1() __attribute__((warn_unused_result));
 
-// CHECK: {{\[}}[clang::warn_unused_result("")]];
+// CHECK: {{\[}}[clang::warn_unused_result("")]]
 int f2 [[clang::warn_unused_result]] ();
 
-// CHECK: {{\[}}[gnu::warn_unused_result("")]];
+// CHECK: {{\[}}[gnu::warn_unused_result("")]]
 int f3 [[gnu::warn_unused_result]] ();
 
 // FIXME: ast-print need to print C++11
 // attribute after function declare-id.
-// CHECK: {{\[}}[noreturn]];
+// CHECK: {{\[}}[noreturn]]
 void f4 [[noreturn]] ();
 
 // CHECK: __attribute__((gnu_inline));
 inline void f6() __attribute__((gnu_inline));
 
-// CHECK: {{\[}}[gnu::gnu_inline]];
+// CHECK: {{\[}}[gnu::gnu_inline]]
 inline void f7 [[gnu::gnu_inline]] ();
 
 // arguments printing
@@ -66,8 +66,8 @@
 // CHECK: int m __attribute__((aligned(4
 // CHECK: int n alignas(4
 // CHECK: int p alignas(int
-// CHECK: static int f() __attribute__((pure))
-// CHECK: static int g() {{\[}}[gnu::pure]]
+// CHECK: __attribute__((pure)) static int f()
+// CHECK: {{\[}}[gnu::pure]] static int g()
 template  struct S {
   __attribute__((aligned(4))) int m;
   alignas(4) int n;
@@ -82,8 +82,8 @@
 
 // CHECK: int m __attribute__((aligned(4
 // CHECK: int n alignas(4
-// CHECK: static int f() __attribute__((pure))
-// CHECK: static int g() {{\[}}[gnu::pure]]
+// CHECK: __attribute__((pure)) static int f()
+// CHECK: {{\[}}[gnu::pure]] static int g()
 template struct S;
 
 // CHECK: using Small2 {{\[}}[gnu::mode(byte)]] = int;
Index: clang/test/SemaCXX/attr-no-sanitize.cpp
===
--- clang/test/SemaCXX/attr-no-sanitize.cpp
+++ clang/test/SemaCXX/attr-no-sanitize.cpp
@@ -16,12 +16,12 @@
 
 // DUMP-LABEL: FunctionDecl {{.*}} f4
 // DUMP: NoSanitizeAttr {{.*}} thread
-// PRINT: int f4() {{\[\[}}clang::no_sanitize("thread")]]
+// PRINT: {{\[\[}}clang::no_sanitize("thread")]] int f4()
 [[clang::no_sanitize("thread")]] int f4();
 
 // DUMP-LABEL: FunctionDecl {{.*}} f4
 // DUMP: NoSanitizeAttr {{.*}} hwaddress
-// PRINT: int f4() {{\[\[}}clang::no_sanitize("hwaddress")]]
+// PRINT: {{\[\[}}clang::no_sanitize("hwaddress")]] int f4()
 [[clang::no_sanitize("hwaddress")]] int f4();
 
 // DUMP-LABEL: FunctionDecl {{.*}} f5
@@ -36,5 +36,5 @@
 
 // DUMP-LABEL: FunctionDecl {{.*}} f7
 // DUMP: NoSanitizeAttr {{.*}} memtag
-// PRINT: int f7() {{\[\[}}clang::no_sanitize("memtag")]]
+// PRINT: {{\[\[}}clang::no_sanitize("memtag")]] int f7()
 [[clang::no_sanitize("memtag")]] int f7();
Index: clang/test/OpenMP/declare_simd_ast_print.cpp
===
--- clang/test/OpenMP/declare_simd_ast_print.cpp
+++ clang/test/OpenMP/declare_simd_ast_print.cpp
@@ -60,7 +60,7 @@
 
 class VV {
   // CHECK: #pragma omp declare simd uniform(this, a) linear(val(b): a)
-  // CHECK-NEXT: int add(int a, int b) __attribute__((cold)){
+  // CHECK-NEXT: __attribute__((cold)) int add(int a, int b)  {
   // CHECK-NEXT: return a + b;
   // CHECK-NEXT: }
   #pragma omp declare simd uniform(this, a) linear(val(b): a)
Index: clang/test/OpenMP/assumes_template_print.cpp
===
--- clang/test/OpenMP/assumes_template_print.cpp
+++ clang/test/OpenMP/assumes_template_print.cpp
@@ -17,7 +17,7 @@
 struct S {
   int a;
 // CHECK: template  struct S {
-// CHECK: void foo() __attribute__((assume("ompx_global_assumption"))) {
+// CHECK: __attribute__((assume("ompx_global_assumption")))  void foo()   {
   void foo() {
 #pragma omp parallel
 {}
@@ -25,15 +25,15 @@
 };
 
 // CHECK: template<> struct S {
-// CHECK: void foo() __attribute__((assume("ompx_global_assumption"))) {
+// CHECK: __attribute__((assume("ompx_global_assumption")))  void foo(){
 
 #pragma omp begin assumes no_openmp
-// CHECK: void S_with_assumes_no_call() __attribute__((assume("omp_no_openmp"))) __attribute__((assume("ompx_global_assumption"))) {
+// CHECK: __attribute__((assume("omp_no_openmp"))) __attribute__((assume("ompx_global_assumption"))) void S_

[PATCH] D155064: [clang][SemaCXX] Diagnose tautological uses of consteval if and is_constant_evaluated

2023-08-08 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 548197.
hazohelet added a comment.

- Tentatively disable the warning on macros so as not to make a fuss in libc++ 
tests.
- Fixed incorrect output in arguments.
- Fixed incorrect output in declaration of init-statement of constexpr-if 
condition.
- Added tests with FIXMEs about the limitation I mentioned before.


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

https://reviews.llvm.org/D155064

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/Interp/builtins.cpp
  clang/test/AST/Interp/if.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/CXX/expr/expr.const/p6-2a.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p4.cpp
  clang/test/Parser/pragma-fenv_access.c
  clang/test/SemaCXX/constant-conversion.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp
  clang/test/SemaCXX/cxx2b-consteval-if.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
  clang/test/SemaCXX/vartemplate-lambda.cpp
  clang/test/SemaCXX/warn-constant-evaluated-constexpr.cpp
  clang/test/SemaCXX/warn-tautological-meta-constant.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/unittests/Support/TimeProfilerTest.cpp
  libcxx/include/__type_traits/is_constant_evaluated.h
  
libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
  
libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp

Index: libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
===
--- libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
+++ libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
@@ -24,7 +24,7 @@
 #else
   // expected-error-re@+1 (static_assert|static assertion)}} failed}}
   static_assert(!std::is_constant_evaluated(), "");
-  // expected-warning@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression}}
+  // expected-warning-re@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to {{('true' in a manifestly constant-evaluated expression|true in this context)
 #endif
   return 0;
 }
Index: libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
===
--- libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
+++ libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
@@ -93,12 +93,10 @@
 }
 
 int main(int, char**) {
-  if (!std::is_constant_evaluated()) {
-test_containers, std::deque>();
-test_containers, std::vector>();
-test_containers, std::deque>();
-test_containers, std::vector>();
-  }
+  test_containers, std::deque>();
+  test_containers, std::vector>();
+  test_containers, std::deque>();
+  test_containers, std::vector>();
 
   types::for_each(types::forward_iterator_list{}, [] {
 test_join_view();
Index: libcxx/include/__type_traits/is_constant_evaluated.h
===
--- libcxx/include/__type_traits/is_constant_evaluated.h
+++ libcxx/include/__type_traits/is_constant_evaluated.h
@@ -24,7 +24,11 @@
 #endif
 
 _LIBCPP_HIDE_FROM_ABI inline _LIBCPP_CONSTEXPR bool __libcpp_is_constant_evaluated() _NOEXCEPT {
+#ifndef _LIBCPP_CXX03_LANG
   return __builtin_is_constant_evaluated();
+#else
+  return false;
+#endif
 }
 
 _LIBCPP_END_NAMESPACE_STD
Index: clang/unittests/Support/TimeProfilerTest.cpp
===
--- clang/unittests/Support/TimeProfilerTest.cpp
+++ clang/unittests/Support/TimeProfilerTest.cpp
@@ -188,7 +188,6 @@
 | EvaluateAsBooleanCondition ()
 | | EvaluateAsRValue ()
 | EvaluateAsInitializer (slow_value)
-| EvaluateAsConstantExpr ()
 | EvaluateAsConstantExpr ()
 | EvaluateAsRValue ()
 | EvaluateAsInitializer (slow_init_list)
Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -135,21 +135,21 @@
 
 namespace BuiltinIsConstantEvaluated {
   // Check that we 

[PATCH] D157395: [include-cleaner] Follow `IWYU pragma: export` links transitively.

2023-08-08 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a subscriber: kadircet.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157395

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -439,6 +439,25 @@
   PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
 }
 
+TEST_F(PragmaIncludeTest, IWYUTransitiveExport) {
+  Inputs.Code = R"cpp(
+#include "export1.h"
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+#include "export2.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["export2.h"] = R"cpp(
+#include "provider.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["provider.h"] = "";
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("provider.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("export2.h")));
+}
+
 TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
   Inputs.Code = R"cpp(
 #include "export.h"
@@ -483,13 +502,13 @@
   EXPECT_THAT(PI.getExporters(FM.getFile("private1.h").get(), FM),
   testing::UnorderedElementsAre(FileNamed("export1.h"),
 FileNamed("normal.h")));
-  EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
-  EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  // EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
+  // testing::UnorderedElementsAre(FileNamed("export1.h")));
+  // EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
+  // testing::UnorderedElementsAre(FileNamed("export1.h")));
 
-  EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
-  EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
+  // EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
+  // EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
 }
 
 TEST_F(PragmaIncludeTest, SelfContained) {
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -12,6 +12,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -24,16 +25,21 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
 #include "llvm/Support/StringSaver.h"
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -387,24 +393,44 @@
   return It->getSecond();
 }
 
+template 
 static llvm::SmallVector
-toFileEntries(llvm::ArrayRef FileNames, FileManager &FM) {
+toFileEntries(Iter FileNamesBegin, Iter FileNamesEnd, FileManager &FM) {
   llvm::SmallVector Results;
 
-  for (auto FName : FileNames) {
+  for (auto FNameIt = FileNamesBegin; FNameIt != FileNamesEnd; ++FNameIt) {
 // FIMXE: log the failing cases?
-if (auto FE = expectedToOptional(FM.getFileRef(FName)))
+if (auto FE = expectedToOptional(FM.getFileRef(*FNameIt)))
   Results.push_back(*FE);
   }
   return Results;
 }
-llvm::SmallVector
-PragmaIncludes::getExporters(const FileEntry *File, FileManager &FM) const {
-  auto It = IWYUExportBy.find(File->getUniqueID());
+
+void collectExportersRecursively(
+llvm::DenseMap>
+IWYUExportBy,
+const llvm::sys::fs::UniqueID &UID, std::set &Result,
+FileManager &FM) {
+  auto It = IWYUExportBy.find(UID);
   if (It == IWYUExportBy.end())
-return {};
+return;
+  auto Exporters =
+  toFileEntries(It->getSecond().begin(), It->getSecond().end(), FM);
+  for (const auto &E : Exporters) {
+Result.insert(E);
+collectExportersRecursively(IWYUExportBy, E->getUniqueID(), R

[clang-tools-extra] 89d0a76 - [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-08-08T16:01:33+02:00
New Revision: 89d0a76be68b866779ac41e56bc7f7b4fc452f47

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

LOG: [clang-tidy][include-cleaner] Add option to control deduplication of 
findings per symbol

We received some user feedback around this being disruptful rather than
useful in certain workflows so add an option to control the output behaviour.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
index c5cb18978b6497..f47609b19badfc 100644
--- a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
@@ -55,7 +55,9 @@ IncludeCleanerCheck::IncludeCleanerCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   IgnoreHeaders(utils::options::parseStringList(
-  Options.getLocalOrGlobal("IgnoreHeaders", ""))) {
+  Options.getLocalOrGlobal("IgnoreHeaders", ""))),
+  DeduplicateFindings(
+  Options.getLocalOrGlobal("DeduplicateFindings", true)) {
   for (const auto &Header : IgnoreHeaders) {
 if (!llvm::Regex{Header}.isValid())
   configurationDiag("Invalid ignore headers regex '%0'") << Header;
@@ -69,6 +71,7 @@ IncludeCleanerCheck::IncludeCleanerCheck(StringRef Name,
 void IncludeCleanerCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "IgnoreHeaders",
 utils::options::serializeStringList(IgnoreHeaders));
+  Options.store(Opts, "DeduplicateFindings", DeduplicateFindings);
 }
 
 bool IncludeCleanerCheck::isLanguageVersionSupported(
@@ -114,12 +117,26 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
 // FIXME: Filter out implicit template specializations.
 MainFileDecls.push_back(D);
   }
+  llvm::DenseSet SeenSymbols;
   // FIXME: Find a way to have less code duplication between include-cleaner
   // analysis implementation and the below code.
   walkUsed(MainFileDecls, RecordedPreprocessor.MacroReferences, &RecordedPI,
*SM,
[&](const include_cleaner::SymbolReference &Ref,
llvm::ArrayRef Providers) {
+ // Process each symbol once to reduce noise in the findings.
+ // Tidy checks are used in two 
diff erent workflows:
+ // - Ones that show all the findings for a given file. For such
+ // workflows there is not much point in showing all the 
occurences,
+ // as one is enough to indicate the issue.
+ // - Ones that show only the findings on changed pieces. For such
+ // workflows it's useful to show findings on every reference of a
+ // symbol as otherwise tools might give incosistent results
+ // depending on the parts of the file being edited. But it should
+ // still help surface findings for "new violations" (i.e.
+ // dependency did not exist in the code at all before).
+ if (DeduplicateFindings && !SeenSymbols.insert(Ref.Target).second)
+   return;
  bool Satisfied = false;
  for (const include_cleaner::Header &H : Providers) {
if (H.kind() == include_cleaner::Header::Physical &&

diff  --git a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h 
b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
index d5f75f2b1c7fa2..9641c7fd9dfcf6 100644
--- a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
+++ b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
@@ -44,6 +44,8 @@ class IncludeCleanerCheck : public ClangTidyCheck {
   include_cleaner::PragmaIncludes RecordedPI;
   HeaderSearch *HS;
   std::vector IgnoreHeaders;
+  // Whether emit only one finding per usage of a symbol.
+  const bool DeduplicateFindings;
   llvm::SmallVector IgnoreHeadersRegex;
   bool shouldIgnore(const include_cleaner::Header &H);
 };

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 2af86407069a68..815237656a4035 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -192,6 +192,9 @@ Changes in existing checks
   ` check to emit proper
   warnings when a type forward declarat

[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya 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 rG89d0a76be68b: [clang-tidy][include-cleaner] Add option to 
control deduplication of findings… (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

Files:
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -15,6 +15,8 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/Testing/Annotations/Annotations.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -108,6 +110,50 @@
)"}}));
 }
 
+TEST(IncludeCleanerCheckTest, DedupsMissingIncludes) {
+  llvm::Annotations Code(R"(
+#include "baz.h" // IWYU pragma: keep
+
+int BarResult1 = $diag1^bar();
+int BarResult2 = $diag2^bar();)");
+
+  {
+std::vector Errors;
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, ClangTidyOptions(),
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(1U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+  }
+  {
+std::vector Errors;
+ClangTidyOptions Opts;
+Opts.CheckOptions.insert({"DeduplicateFindings", "false"});
+runCheckOnCode(Code.code(), &Errors, "file.cpp",
+std::nullopt, Opts,
+{{"baz.h", R"(#pragma once
+  #include "bar.h"
+   )"},
+ {"bar.h", R"(#pragma once
+  int bar();
+   )"}});
+ASSERT_THAT(Errors.size(), testing::Eq(2U));
+EXPECT_EQ(Errors.front().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.front().Message.FileOffset, Code.point("diag1"));
+EXPECT_EQ(Errors.back().Message.Message,
+  "no header providing \"bar\" is directly included");
+EXPECT_EQ(Errors.back().Message.FileOffset, Code.point("diag2"));
+  }
+}
+
 TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
   const char *PreCode = R"(
 #include "bar.h"
Index: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
@@ -33,3 +33,8 @@
files that match this regex as a suffix.  E.g., `foo/.*` disables
insertion/removal for all headers under the directory `foo`. By default, no 
headers will be ignored.
+
+.. option:: DeduplicateFindings
+
+   A boolean that controls whether the check should deduplicate findings for the
+   same symbol. Defaults to true.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -192,6 +192,9 @@
   ` check to emit proper
   warnings when a type forward declaration precedes its definition.
 
+- Misc-include-cleaner check has option `DeduplicateFindings` to output one
+  finding per occurence of a symbol.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
===
--- clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
+++ clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
@@ -44,6 +44,8 @@
   include_cleaner::PragmaIncludes RecordedPI;
   HeaderSearch *HS;
   std::vector IgnoreHeaders;
+  // Whether emit only one finding per usage of a symbol.
+  const bool DeduplicateFindings;
   llvm::SmallVector IgnoreHeadersRegex;
   bool shouldIgnore(const include_cleaner::Header &H);
 };
Index: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
===

[PATCH] D157395: [include-cleaner] Follow `IWYU pragma: export` links transitively.

2023-08-08 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 548204.
VitaNuo added a comment.

Remove accidental comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157395

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -439,6 +439,25 @@
   PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
 }
 
+TEST_F(PragmaIncludeTest, IWYUTransitiveExport) {
+  Inputs.Code = R"cpp(
+#include "export1.h"
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+#include "export2.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["export2.h"] = R"cpp(
+#include "provider.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["provider.h"] = "";
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("provider.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("export2.h")));
+}
+
 TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
   Inputs.Code = R"cpp(
 #include "export.h"
@@ -484,9 +503,11 @@
   testing::UnorderedElementsAre(FileNamed("export1.h"),
 FileNamed("normal.h")));
   EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("normal.h")));
   EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("normal.h")));
 
   EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
   EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -12,6 +12,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -24,16 +25,21 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
 #include "llvm/Support/StringSaver.h"
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -387,24 +393,44 @@
   return It->getSecond();
 }
 
+template 
 static llvm::SmallVector
-toFileEntries(llvm::ArrayRef FileNames, FileManager &FM) {
+toFileEntries(Iter FileNamesBegin, Iter FileNamesEnd, FileManager &FM) {
   llvm::SmallVector Results;
 
-  for (auto FName : FileNames) {
+  for (auto FNameIt = FileNamesBegin; FNameIt != FileNamesEnd; ++FNameIt) {
 // FIMXE: log the failing cases?
-if (auto FE = expectedToOptional(FM.getFileRef(FName)))
+if (auto FE = expectedToOptional(FM.getFileRef(*FNameIt)))
   Results.push_back(*FE);
   }
   return Results;
 }
-llvm::SmallVector
-PragmaIncludes::getExporters(const FileEntry *File, FileManager &FM) const {
-  auto It = IWYUExportBy.find(File->getUniqueID());
+
+void collectExportersRecursively(
+llvm::DenseMap>
+IWYUExportBy,
+const llvm::sys::fs::UniqueID &UID, std::set &Result,
+FileManager &FM) {
+  auto It = IWYUExportBy.find(UID);
   if (It == IWYUExportBy.end())
-return {};
+return;
+  auto Exporters =
+  toFileEntries(It->getSecond().begin(), It->getSecond().end(), FM);
+  for (const auto &E : Exporters) {
+Result.insert(E);
+collectExportersRecursively(IWYUExportBy, E->getUniqueID(), Result, FM);
+  }
+}
 
-  return toFileEntries(It->getSecond(), FM);
+llvm::SmallVector
+PragmaIncludes::getExporters(const FileEntry *File, FileManager &FM) const {
+  std::set UniqueExporters;
+  collectExportersRecursively(IWYUExportBy, File->getUniqueID(),
+  UniqueExporters, FM);
+  llvm::SmallVector Ex

[PATCH] D152436: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha.

2023-08-08 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

I have checked the results on some projects 
(memcached,tmux,curl,twin,vim,openssl,sqlite,ffmpeg,postgres,xerces,bitcoin).

These results are more interesting, some look correct, some probably not:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=curl_curl-7_66_0_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-id=2243964&report-hash=d4a4bda38c5a6fdaabe2c1867158b106&report-filepath=%2atftpd.c
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=ffmpeg_n4.3.1_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=908f965d980d60292af95db0fa10cd5f&report-id=2252082&report-filepath=%2av4l2_buffers.c
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=postgres_REL_13_0_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=914e79646cb0de40dab434ba24c8c23c&report-id=2259781&report-filepath=%2adsm_impl.c
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=postgres_REL_13_0_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=58d8278be40f99597b44323d2574c053&report-id=2259789&report-filepath=%2asyslogger.c
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=postgres_REL_13_0_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=1928ba718d9742340937d425ec3978c6&report-id=2260011&report-filepath=%2apg_backup_custom.c
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=bitcoin_v0.20.1_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=6ad3a20f18f2850293b4cdd867e404e2&report-id=2266103&report-filepath=%2aenv_posix.cc

This is more questionable:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=twin_v0.8.1_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=50a98122502701302b7b75a6a56342e8&report-id=2244071&report-filepath=%2ashm.c

Correct but interesting, the note about failure of `ftell` is shown:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=xerces_v3.2.3_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions&report-hash=4ab640064066880ac7031727869c92f4&report-id=2260149&report-filepath=%2aThreadTest.cpp

I did not find results that are obvious false positive.
Many results are the case when `fileno` returns -1 and this value is used 
without check. The checker generates a note about failure of `fileno`. For 
example at these results:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_stdclibraryfunctions_alpha&is-unique=on&diff-type=New&checker-name=unix.StdCLibraryFunctions
(There are cases when `fileno(stderr)` is assumed to fail. This case can be 
eliminated if the `StreamChecker` is enabled, after an improvement of the 
checker. But for this `StreamChecker` must run before 
`StdCLibraryFunctionsChecker`?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152436

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


[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:195
 
+- Misc-include-cleaner check has option `DeduplicateFindings` to output one
+  finding per occurence of a symbol.

invalid release note should be something like:
```
Improved :doc:`misc-include-cleaner ` 
check by adding option `DeduplicateFindings` to output one finding per symbol 
occurence.
```

Also this list is sorted per check, so it should be before 
modernize-loop-convert.



Comment at: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst:40
+   A boolean that controls whether the check should deduplicate findings for 
the
+   same symbol. Defaults to true.

true -> `true`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

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


[clang-tools-extra] 724b40a - [clang-tidy][Docs] Update docs per post-commit review

2023-08-08 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-08-08T16:16:51+02:00
New Revision: 724b40a1379f7c116473a02a3cec4d341c475b46

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

LOG: [clang-tidy][Docs] Update docs per post-commit review

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 815237656a4035..dbd2fbf6de6d42 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -180,6 +180,10 @@ Changes in existing checks
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
 
+- Improved :doc:`misc-include-cleaner
+  ` check by adding option
+  `DeduplicateFindings` to output one finding per symbol occurence.
+
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``.
@@ -192,9 +196,6 @@ Changes in existing checks
   ` check to emit proper
   warnings when a type forward declaration precedes its definition.
 
-- Misc-include-cleaner check has option `DeduplicateFindings` to output one
-  finding per occurence of a symbol.
-
 Removed checks
 ^^
 

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst 
b/clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
index d56bb4526ff015..e40335b2543b29 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
@@ -37,4 +37,4 @@ Options
 .. option:: DeduplicateFindings
 
A boolean that controls whether the check should deduplicate findings for 
the
-   same symbol. Defaults to true.
+   same symbol. Defaults to `true`.



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


[PATCH] D157390: [clang-tidy][include-cleaner] Add option to control deduplication of findings per symbol

2023-08-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked 2 inline comments as done.
kadircet added a comment.

hi @PiotrZSL, addressed those in 724b40a1379f7c116473a02a3cec4d341c475b46 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157390

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


[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: efriedma.
aaron.ballman added a comment.

Round two of comments; I picked up from where I left off earlier and haven't 
checked your changes or responses yet. Precommit CI seems to have found a 
relevant failure from the patch.




Comment at: clang/lib/AST/ExprConstant.cpp:7768-7770
+bool HasThis =
+isa(FD) &&
+cast(FD)->isImplicitObjectMemberFunction();





Comment at: clang/lib/AST/JSONNodeDumper.cpp:846
   JOS.attribute("type", createQualType(VD->getType()));
+  if (const auto *P = dyn_cast(VD))
+attributeOnlyIfTrue("explicitObjectParameter",





Comment at: clang/lib/AST/MicrosoftMangle.cpp:2748
 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
+  // explicit object parameters are prefixed by "_V"
+  if (I == 0 && D && D->getParamDecl(0)->isExplicitObjectParameter())

aaron.ballman wrote:
> 
Still missing the full stop at the end of the sentence.



Comment at: clang/lib/AST/TextNodeDumper.cpp:1785
   dumpName(D);
+  if (const auto *P = dyn_cast(D);
+  P && P->isExplicitObjectParameter())

Oops, I missed this suggestion previously.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:2129-2140
   !D->hasAttr()) {
 const CXXMethodDecl *MD;
 // Variable pointer template parameters have a value that is the 
address
 // of the variable.
 if (const auto *VD = dyn_cast(D))
   V = CGM.GetAddrOfGlobalVar(VD);
 // Member function pointers have special support for building them,

Might as well clean this up since we're in the area.



Comment at: clang/lib/CodeGen/CGExpr.cpp:4275-4276
+  bool HasExplicitObjectParameter = false;
+  if (const CXXMethodDecl *MD =
+  dyn_cast_if_present(CurCodeDecl)) {
+HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();





Comment at: clang/lib/CodeGen/CGExpr.cpp:4283
+  if (HasExplicitObjectParameter) {
+const VarDecl *D = cast(CurCodeDecl)->getParamDecl(0);
+auto It = LocalDeclMap.find(D);

Above we did `dyn_cast_if_present(CurCodeDecl)` and here we're 
doing a straight-up `cast<>`. Which is incorrect?



Comment at: clang/lib/CodeGen/CGExpr.cpp:5015-5017
+  // a CXXOperatorCallExpr is created even for
+  // explicit object methods, but these should be treated
+  // like static function call





Comment at: clang/lib/CodeGen/CGExpr.cpp:5019-5020
   if (const auto *CE = dyn_cast(E))
 if (const CXXMethodDecl *MD =
-  dyn_cast_or_null(CE->getCalleeDecl()))
+dyn_cast_or_null(CE->getCalleeDecl());
+MD && MD->isImplicitObjectMemberFunction())





Comment at: clang/lib/CodeGen/CGExpr.cpp:4254
+ llvm::Value *ThisValue) {
+  bool HasExplicitObjectParameter = false;
+  if (const CXXMethodDecl *MD =

cor3ntin wrote:
> erichkeane wrote:
> > If there is a CodeGen expert in the house, I'd really hope they go through 
> > this :) 
> Oh, me too!
> I need to properly write tests for it too. And you know how terrible I am at 
> code gen tests...
CC @efriedma @rjmccall for codegen opinions.



Comment at: clang/lib/CodeGen/CGExprCXX.cpp:69-73
+unsigned ArgsToSkip = 0;
+if (auto *Op = llvm::dyn_cast(CE)) {
+  if (const CXXMethodDecl *M = 
dyn_cast(Op->getCalleeDecl()))
+ArgsToSkip = M->isExplicitObjectMemberFunction() ? 0 : 1;
+}





Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:1170
 
-  if (isa_and_nonnull(D) &&
-  cast(D)->isInstance()) {
-CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
-const CXXMethodDecl *MD = cast(D);
-if (MD->getParent()->isLambda() &&
-MD->getOverloadedOperator() == OO_Call) {
+  if (const CXXMethodDecl *MD = dyn_cast_if_present(D);
+  MD && !MD->isStatic()) {





Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2240-2241
   // need this sort of type metadata.
-  return !MD->isStatic() && !MD->isVirtual() && !isa(MD) &&
- !isa(MD);
+  return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
+ !isa(MD) && !isa(MD);
 }





Comment at: clang/lib/Parse/ParseDecl.cpp:5756
  const ParsedTemplateInfo *TemplateInfo) {
-  TentativeParsingAction TPA(*this);
-
+  RevertingTentativeParsingAction TPA(*this);
   // Parse the C++ scope specifier.

This is a good NFC cleanup; feel free to land this change separately if you'd 
like to get it out of this review.



Comment at: clang/lib/Parse/ParseDecl.cpp:7342-7347
+// Parse a C++23 Explicit 

[clang] 8e7f032 - [Clang][OpenMP] Support for Code Generation of loop bind clause.

2023-08-08 Thread Sandeep Kosuri via cfe-commits

Author: Sunil Kuravinakop
Date: 2023-08-08T09:23:00-05:00
New Revision: 8e7f0320ad7fb760fff598aba4b2c86528c58c2d

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

LOG: [Clang][OpenMP] Support for Code Generation of loop bind clause.

Added: 
clang/test/OpenMP/loop_bind_codegen.cpp
clang/test/OpenMP/loop_bind_enclosed.cpp
clang/test/OpenMP/loop_bind_messages.cpp

Modified: 
clang/include/clang/AST/StmtOpenMP.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/StmtOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/OpenMP/generic_loop_ast_print.cpp
clang/test/OpenMP/generic_loop_codegen.cpp
clang/test/OpenMP/nested_loop_codegen.cpp
clang/test/PCH/pragma-loop.cpp

Removed: 




diff  --git a/clang/include/clang/AST/StmtOpenMP.h 
b/clang/include/clang/AST/StmtOpenMP.h
index 2d37fdbf4ca8fb..20cd198f5f0cc5 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -281,6 +281,15 @@ class OMPExecutableDirective : public Stmt {
 return Data->getClauses();
   }
 
+  /// Was this directive mapped from an another directive?
+  /// e.g. 1) omp loop bind(parallel) is mapped to OMPD_for
+  ///  2) omp loop bind(teams) is mapped to OMPD_distribute
+  ///  3) omp loop bind(thread) is mapped to OMPD_simd
+  /// It was necessary to note it down in the Directive because of
+  /// clang::TreeTransform::TransformOMPExecutableDirective() pass in
+  /// the frontend.
+  OpenMPDirectiveKind PrevMappedDirective = llvm::omp::OMPD_unknown;
+
 protected:
   /// Data, associated with the directive.
   OMPChildren *Data = nullptr;
@@ -345,6 +354,10 @@ class OMPExecutableDirective : public Stmt {
 return Inst;
   }
 
+  void setMappedDirective(OpenMPDirectiveKind MappedDirective) {
+PrevMappedDirective = MappedDirective;
+  }
+
 public:
   /// Iterates over expressions/statements used in the construct.
   class used_clauses_child_iterator
@@ -598,6 +611,8 @@ class OMPExecutableDirective : public Stmt {
"Expected directive with the associated statement.");
 return Data->getRawStmt();
   }
+
+  OpenMPDirectiveKind getMappedDirective() const { return PrevMappedDirective; 
}
 };
 
 /// This represents '#pragma omp parallel' directive.
@@ -1604,7 +1619,8 @@ class OMPSimdDirective : public OMPLoopDirective {
   SourceLocation EndLoc, unsigned CollapsedNum,
   ArrayRef Clauses,
   Stmt *AssociatedStmt,
-  const HelperExprs &Exprs);
+  const HelperExprs &Exprs,
+  OpenMPDirectiveKind 
ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -1682,7 +1698,8 @@ class OMPForDirective : public OMPLoopDirective {
  SourceLocation EndLoc, unsigned CollapsedNum,
  ArrayRef Clauses,
  Stmt *AssociatedStmt, const HelperExprs 
&Exprs,
- Expr *TaskRedRef, bool HasCancel);
+ Expr *TaskRedRef, bool HasCancel,
+ OpenMPDirectiveKind ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -4406,7 +4423,8 @@ class OMPDistributeDirective : public OMPLoopDirective {
   static OMPDistributeDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
  unsigned CollapsedNum, ArrayRef Clauses,
- Stmt *AssociatedStmt, const HelperExprs &Exprs);
+ Stmt *AssociatedStmt, const HelperExprs &Exprs,
+ OpenMPDirectiveKind ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e6b1dc948fc6bd..12909d6b7903b2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9875,6 +9875,11 @@ def err_break_not_in_loop_or_switch : Error<
 def warn_loop_ctrl_binds_to_inner : Warning<
   "'%0' is bound to current loop, GCC binds it to the enclosing loop">,
   InGroup;
+def err_omp_bind_required_on_loop : Error<
+  "expected 'bind' clause for 'loop' construct without an enclosing OpenMP "
+  "construct">;
+def err_omp_loop_reduction_clause : Error<
+  "'reduction' clause not allowed with '#p

[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-08 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin marked an inline comment as done.
cor3ntin added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:4283
+  if (HasExplicitObjectParameter) {
+const VarDecl *D = cast(CurCodeDecl)->getParamDecl(0);
+auto It = LocalDeclMap.find(D);

aaron.ballman wrote:
> Above we did `dyn_cast_if_present(CurCodeDecl)` and here we're 
> doing a straight-up `cast<>`. Which is incorrect?
neither, once `HasExplicitObjectParameter` is true we know it's a CXXMethodDecl



Comment at: clang/test/SemaCXX/cxx2b-deducing-this.cpp:42
+int f(this B&, int); // expected-warning {{hides overloaded virtual 
function}}
+int f(this B&);  // expected-error {{an explicit object parameter cannot 
appear in a virtual function}}
+int g(this B&); // expected-warning {{hides overloaded virtual function}}

aaron.ballman wrote:
> According to the paper, this is accepted but `B::f()` does not override 
> `A::f()`.
> 
> https://eel.is/c++draft/dcl.fct#6.sentence-3
> 
> `B::f()` is not declared as virtual, only `A::f()` is.
> 
> When this gets corrected, please add some codegen tests to demonstrate that a 
> call to `f()` does not dispatch to `B::f()` unless the static type of the 
> object is `B`.
This is this is https://cplusplus.github.io/CWG/issues/2553.html, I will leave 
a comment to clarify


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-08 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin marked an inline comment as done.
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:11308
+
+  // There should be a CWG issue for that
+  if (Name.getNameKind() == DeclarationName::CXXConstructorName ||

aaron.ballman wrote:
> Do you know the core issue number so we can reference it here?
This is https://cplusplus.github.io/CWG/issues/2674.html - I'll edit the comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7280
+  "a %select{function|lambda}0 with an explicit object parameter cannot "
+  "%select{be const|be mutable|have reference qualifiers|be volatile}1">;
+def err_invalid_explicit_object_type_in_lambda: Error<

cor3ntin wrote:
> aaron.ballman wrote:
> > I think you're missing `restrict` here as well. Perhaps this is a case 
> > where it's better to diagnose the qualifiers generically and rely on the 
> > diagnostic's source range? e.g., `cannot have qualifiers` instead of the 
> > current %1 selection. This also works around weird with things like `void 
> > func() const &;` where it has multiple qualifiers.
> Forming a source range to the qualifiers may be challenging though.
> 
> In what case would `restrict` come into play?
> 
> ```
> struct test {
> void f() restrict;
> };
> ```
> does not seem valid, I'm assuming  it is in some language mode?
Ah, it's spelled `__restrict` in C++ mode, but we also support other qualifiers 
like `_Nonnull` as well. I left some examples in other comments that should 
demonstrate this.



Comment at: clang/lib/AST/ASTStructuralEquivalence.cpp:1365-1366
   Method1->isStatic() == Method2->isStatic() &&
+  Method1->isImplicitObjectMemberFunction() ==
+  Method2->isImplicitObjectMemberFunction() &&
   Method1->isConst() == Method2->isConst() &&

cor3ntin wrote:
> aaron.ballman wrote:
> > Is this correct for structural equivalence, or are these supposed to be 
> > structurally equivalent?
> > ```
> > void func(const this auto& R);
> > // and
> > void func() const &;
> > ```
> > I think these aren't equivalent, but I wanted to be sure.
> Yup, they have completely different type
Thank you for verifying.



Comment at: clang/lib/AST/DeclCXX.cpp:841
   const auto *ParamTy =
-  Method->getParamDecl(0)->getType()->getAs();
+  Method->getNonObjectParameter(0)->getType()->getAs();
   if (!ParamTy || ParamTy->getPointeeType().isConstQualified())

cor3ntin wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > Under what circumstances should existing calls to `getParamDecl()` be 
> > > converted to using `getNonObjectParameter()` instead? Similar for 
> > > `getNumParams()`.
> > everytime you want to ignore (or handle differently) the explicit object 
> > parameter. I'll do another survey at some point, to be sure i didn't miss a 
> > spot
> I found a bug https://github.com/cplusplus/CWG/issues/390 ! 
> (`AreSpecialMemberFunctionsSameKind`) - So far nothing else but I'll do 
> several passes
This adds an unfortunate amount of complexity to the compiler because now we 
have to explicitly remember to think about this weird scenario, but I'm not 
seeing much of a way around it. I suspect this will be a bit of a bug factory 
until we're used to thinking explicitly about this.

Be sure to double-check things like attributes that take arguments which 
represent an index into a function parameter list (like the `format` 
attribute), as those have to do a special dance to handle the implicit `this` 
parameter. I'm guessing the static analyzer and clang-tidy will both also run 
into this in some places as well.



Comment at: clang/lib/AST/ExprClassification.cpp:468
 
-  if (isa(D) && cast(D)->isInstance())
-return Cl::CL_MemberFunction;
+  if (auto *M = dyn_cast(D)) {
+if (M->isImplicitObjectMemberFunction())

cor3ntin wrote:
> aaron.ballman wrote:
> > Just to double-check -- an explicit object member function is a prvalue?
> This is my reading of https://eel.is/c++draft/expr.prim#id.qual-5 
> 
I read it the same way you are, but it's a bit hard because these functions are 
a bit like a static function and a bit like a member function.



Comment at: clang/lib/AST/ExprClassification.cpp:559-565
+  if (const auto *Method = dyn_cast(Member)) {
+if (Method->isStatic())
+  return Cl::CL_LValue;
+if (Method->isImplicitObjectMemberFunction())
+  return Cl::CL_MemberFunction;
+return Cl::CL_PRValue;
+  }

cor3ntin wrote:
> aaron.ballman wrote:
> > 
> Can you confirm? I know it's redundant, but it matches the comment and i 
> don't think removing it is an improvement
I'm fine leaving it in as well; I was on the fence about it to begin with,


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D157395: [include-cleaner] Follow `IWYU pragma: export` links transitively.

2023-08-08 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 548217.
VitaNuo added a comment.

Remove the preferred header hint for exporters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157395

Files:
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -439,6 +439,25 @@
   PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
 }
 
+TEST_F(PragmaIncludeTest, IWYUTransitiveExport) {
+  Inputs.Code = R"cpp(
+#include "export1.h"
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+#include "export2.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["export2.h"] = R"cpp(
+#include "provider.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["provider.h"] = "";
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("provider.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("export2.h")));
+}
+
 TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
   Inputs.Code = R"cpp(
 #include "export.h"
@@ -484,9 +503,11 @@
   testing::UnorderedElementsAre(FileNamed("export1.h"),
 FileNamed("normal.h")));
   EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("normal.h")));
   EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
-  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("normal.h")));
 
   EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
   EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -12,6 +12,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -24,16 +25,21 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
 #include "llvm/Support/StringSaver.h"
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -387,24 +393,44 @@
   return It->getSecond();
 }
 
+template 
 static llvm::SmallVector
-toFileEntries(llvm::ArrayRef FileNames, FileManager &FM) {
+toFileEntries(Iter FileNamesBegin, Iter FileNamesEnd, FileManager &FM) {
   llvm::SmallVector Results;
 
-  for (auto FName : FileNames) {
+  for (auto FNameIt = FileNamesBegin; FNameIt != FileNamesEnd; ++FNameIt) {
 // FIMXE: log the failing cases?
-if (auto FE = expectedToOptional(FM.getFileRef(FName)))
+if (auto FE = expectedToOptional(FM.getFileRef(*FNameIt)))
   Results.push_back(*FE);
   }
   return Results;
 }
-llvm::SmallVector
-PragmaIncludes::getExporters(const FileEntry *File, FileManager &FM) const {
-  auto It = IWYUExportBy.find(File->getUniqueID());
+
+void collectExportersRecursively(
+llvm::DenseMap>
+IWYUExportBy,
+const llvm::sys::fs::UniqueID &UID, std::set &Result,
+FileManager &FM) {
+  auto It = IWYUExportBy.find(UID);
   if (It == IWYUExportBy.end())
-return {};
+return;
+  auto Exporters =
+  toFileEntries(It->getSecond().begin(), It->getSecond().end(), FM);
+  for (const auto &E : Exporters) {
+Result.insert(E);
+collectExportersRecursively(IWYUExportBy, E->getUniqueID(), Result, FM);
+  }
+}
 
-  return toFileEntries(It->getSecond(), FM);
+llvm::SmallVector
+PragmaIncludes::getExporters(const FileEntry *File, FileManager &FM) const {
+  std::set UniqueExporters;
+  collectExportersRecursively(IWYUExportBy, File->getUniqueID(),

[PATCH] D157296: [AST][Coroutine] Fix CoyieldExpr missing end loc

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaCoroutine.cpp:322
+  auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
+  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);
 }

hokein wrote:
> aaron.ballman wrote:
> > hokein wrote:
> > > Thanks for the fast fix.
> > > 
> > > Reading the source code here, I'm not sure this is a correct fix (and put 
> > > the heuristic here). I assume the `Loc` points the the `co_yield` token 
> > > here, passing the `Loc` to the `LParenLoc` and `RParenLoc` parameters 
> > > seems wrong to me, there is no `(` and `)` written in the source code 
> > > here (because the member call expression is an implicit generated node in 
> > > the clang AST), we should pass an invalid source location 
> > > (`SourceLocation()`).
> > > 
> > > The `CallExpr::getEndLoc()` has implemented similar 
> > > [heuristic](https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Expr.cpp#L1662-L1664)
> > >  to handle the case where the RParenLoc is invalid.
> > >  passing the Loc to the LParenLoc and RParenLoc parameters seems wrong to 
> > > me
> > 
> > FWIW, I thought so as well, but I thought we have the same behavior for 
> > `CoreturnExpr` and `CoawaitExpr`. These statements are not really call 
> > expressions as far as the AST is concerned, so it's a bit hard to say 
> > whether there is a right or wrong answer for where the l- and r-paren 
> > locations are for the call.
> Agree, the coroutine is a hard case. I was concerned about the 
> `MemberCallExpr::getRParenLoc()` API, it returns a valid source location but 
> the token it points to is not a `)`, this could lead to subtle bugs in 
> tooling.
> 
> since this change is an improvement, I'm fine with the current change.
> Agree, the coroutine is a hard case. I was concerned about the 
> MemberCallExpr::getRParenLoc() API, it returns a valid source location but 
> the token it points to is not a ), this could lead to subtle bugs in tooling.

Yeah, that was actually my concern as well -- I'm glad we're both on the same 
page. :-)

I eventually convinced myself that folks are generally interested in the right 
paren location because they want to know when the argument list is complete, 
not because they specifically want the right paren token itself. But the reason 
they want to do that is because they want to insert a qualifier, a semi-colon, 
an attribute, etc (something that follows the closing paren) and in all of 
those cases, they'll be surprised here. Perhaps we should be marking this call 
expression as an implicit AST node so that it's more clear to users "this 
wasn't from source, don't expect fix-its to be a good idea?"



Comment at: clang/test/AST/coroutine-co_yield-source-range.cpp:4
+
+namespace std {
+template 

hokein wrote:
> nit: use the `test/AST/Inputs/std-coroutine.h` header to avoid repeating the 
> boilerplate code. 
Good call, I always forget that helper code exists!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157296

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


[PATCH] D154784: [clang] Fix crash caused by PseudoObjectExprBitfields::NumSubExprs overflow

2023-08-08 Thread Yurong via Phabricator via cfe-commits
yronglin marked 4 inline comments as done.
yronglin added inline comments.



Comment at: clang/include/clang/AST/Stmt.h:596-597
 
-// These don't need to be particularly wide, because they're
-// strictly limited by the forms of expressions we permit.
-unsigned NumSubExprs : 8;
-unsigned ResultIndex : 32 - 8 - NumExprBits;
+unsigned NumSubExprs : 16;
+unsigned ResultIndex : 16;
   };

dblaikie wrote:
> dblaikie wrote:
> > aaron.ballman wrote:
> > > dblaikie wrote:
> > > > Could/should we add some error checking in the ctor to assert that we 
> > > > don't overflow these longer values/just hit the bug later on?
> > > > 
> > > > (& could we use `unsigned short` here rather than bitfields?)
> > > We've already got them packed in with other bit-fields from the 
> > > expression bits, so I think it's reasonable to continue the pattern of 
> > > using bit-fields (that way we don't accidentally end up with padding 
> > > between the unnamed bits at the start and the named bits in this object).
> > > 
> > > I think adding some assertions would not be a bad idea as a follow-up.
> > Maybe some unconditional (rather than only in asserts builds) error 
> > handling? (report_fatal_error, if this is low priority enough to not have 
> > an elegant failure mode, but something where we don't just overflow and 
> > carry on would be good... )
> Ping on this? I worry this code has just punted the same bug further down, 
> but not plugged the hole/ensured we don't overflow on novel/larger inputs.
Sorry for the late reply, I was looking through the emails and found this. I 
agree add some assertions to check the value is a good idea, It's easy to help 
people catch bugs, at least with when `-DLLVM_ENABLE_ASSERTIONS=ON`, and I'm 
glad to work on it, but one thing that worries me is that, in ASTReader, we 
access this field directly, not through the constructor or accessor, and we 
have to add assertions everywhere. 
https://github.com/llvm/llvm-project/blob/05b4310c8aec7a050574277ced08a0ab86b27681/clang/lib/Serialization/ASTReaderStmt.cpp#L1382


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154784

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


[PATCH] D153114: [clangd] [C++20] [Modules] Support C++20 modules for clangd

2023-08-08 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

BTW, I have a question about supporting header modules (including clang header 
modules and C++20 header units) in static analysing tools (including clangd), 
"why can't we fallback to include the corresponding headers simply?". So I 
still feel it is not a problem to support header modules in static tools. Since 
I feel the semantics of header modules is almost transparent to other tools.


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

https://reviews.llvm.org/D153114

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


[PATCH] D156787: [analyzer][attr] Add docs to ownership_* attributes

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:1189
+``onwership_returns``: Functions with this annotation return dynamic memory.
+The second annotation parameter is the size of the returned memory in bytes.
+

donat.nagy wrote:
> Szelethus wrote:
> > aaron.ballman wrote:
> > > I'm a bit confused on this last bit; how is the user supposed to 
> > > statically know that value? I read this as claiming `my_malloc` returns 1 
> > > byte of dynamic storage; can the user tie the allocation to a parameter 
> > > value instead?
> > I share your confusion, I guess. What I've written here is my best 
> > understanding of how this works, unfortunately, these annotations were made 
> > in ~2010 (when I was still in elementary school) and abandoned since.
> > 
> > > I read this as claiming my_malloc returns 1 byte of dynamic storage;
> > 
> > Thats what the corresponding code in the Static Analyzer leads me to 
> > believe as well.
> > 
> > > can the user tie the allocation to a parameter value instead?
> > 
> > No. 
> I'd guess that this annotation was designed for factory functions that 
> construct an instance of a concrete struct type on the heap. Allowing 
> "generic" malloc variants (where the allocation size is specified by a 
> parameter) would be a good additional feature, but I think that the current 
> annotation also has its own uses.
> 
> Perhaps it would be good to provide examples like
> ```
>   void __attribute((ownership_takes(malloc, 1))) free_widget(struct widget *);
>   struct widget *__attribute((ownership_returns(malloc, sizeof(struct 
> widget create_widget(void);
>   void __attribute((ownership_holds(malloc, 1))) hold_widget(struct widget *);
> ```
> that correspond to this use case. (By the way, does the checker handle 
> non-`void*` pointers?)
> I share your confusion, I guess. What I've written here is my best 
> understanding of how this works, unfortunately, these annotations were made 
> in ~2010 (when I was still in elementary school) and abandoned since.

This comment came on the same week when I had someone much younger than me ask 
me what Tetris was. I'll go shake my cane at some passing clouds, now. ;-)



Comment at: clang/include/clang/Basic/AttrDocs.td:1189
+``onwership_returns``: Functions with this annotation return dynamic memory.
+The second annotation parameter is the size of the returned memory in bytes.
+

aaron.ballman wrote:
> donat.nagy wrote:
> > Szelethus wrote:
> > > aaron.ballman wrote:
> > > > I'm a bit confused on this last bit; how is the user supposed to 
> > > > statically know that value? I read this as claiming `my_malloc` returns 
> > > > 1 byte of dynamic storage; can the user tie the allocation to a 
> > > > parameter value instead?
> > > I share your confusion, I guess. What I've written here is my best 
> > > understanding of how this works, unfortunately, these annotations were 
> > > made in ~2010 (when I was still in elementary school) and abandoned since.
> > > 
> > > > I read this as claiming my_malloc returns 1 byte of dynamic storage;
> > > 
> > > Thats what the corresponding code in the Static Analyzer leads me to 
> > > believe as well.
> > > 
> > > > can the user tie the allocation to a parameter value instead?
> > > 
> > > No. 
> > I'd guess that this annotation was designed for factory functions that 
> > construct an instance of a concrete struct type on the heap. Allowing 
> > "generic" malloc variants (where the allocation size is specified by a 
> > parameter) would be a good additional feature, but I think that the current 
> > annotation also has its own uses.
> > 
> > Perhaps it would be good to provide examples like
> > ```
> >   void __attribute((ownership_takes(malloc, 1))) free_widget(struct widget 
> > *);
> >   struct widget *__attribute((ownership_returns(malloc, sizeof(struct 
> > widget create_widget(void);
> >   void __attribute((ownership_holds(malloc, 1))) hold_widget(struct widget 
> > *);
> > ```
> > that correspond to this use case. (By the way, does the checker handle 
> > non-`void*` pointers?)
> > I share your confusion, I guess. What I've written here is my best 
> > understanding of how this works, unfortunately, these annotations were made 
> > in ~2010 (when I was still in elementary school) and abandoned since.
> 
> This comment came on the same week when I had someone much younger than me 
> ask me what Tetris was. I'll go shake my cane at some passing clouds, now. ;-)
That code doesn't compile because the argument is somehow "out of bounds": 
https://godbolt.org/z/3e4TbhcT6

I did some digging and the second argument in all three cases is a parameter 
index, at least according to the attribute handling code: 
https://github.com/llvm/llvm-project/blob/895c4ac33fc8b21bd69b017d1cecf874ca47e178/clang/lib/Sema/SemaDeclAttr.cpp#L1857

The static analyzer uses that information to determine which expression

[PATCH] D157400: [include-cleaner] Dont boost private headers beyond public ones

2023-08-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: VitaNuo.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Private headers should be the last resort, even if they match the name
of a symbol. It's pretty common in umrella headers to have internal file names
that match the symbol (e.g. Eigen::Matrix, declared in private header Matrix.h,
and exposed in umbrella header Eigen/Core).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157400

Files:
  clang-tools-extra/include-cleaner/lib/TypesInternal.h
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -465,6 +465,22 @@
physicalHeader("foo.h")));
 }
 
+TEST_F(HeadersForSymbolTest, PublicOverPrivateWithoutUmbrella) {
+  Inputs.Code = R"cpp(
+#include "bar.h"
+#include "foo.h"
+  )cpp";
+  Inputs.ExtraFiles["bar.h"] =
+  guard(R"cpp(#include "foo.h" // IWYU pragma: export)cpp");
+  Inputs.ExtraFiles["foo.h"] = guard(R"cpp(
+// IWYU pragma: private
+struct foo {};
+  )cpp");
+  buildAST();
+  EXPECT_THAT(headersForFoo(),
+  ElementsAre(physicalHeader("bar.h"), physicalHeader("foo.h")));
+}
+
 TEST_F(HeadersForSymbolTest, AmbiguousStdSymbols) {
   struct {
 llvm::StringRef Code;
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -441,9 +441,9 @@
   };
   EXPECT_LT(Hinted(Hints::None), Hinted(Hints::CompleteSymbol));
   EXPECT_LT(Hinted(Hints::CompleteSymbol), Hinted(Hints::PublicHeader));
-  EXPECT_LT(Hinted(Hints::PublicHeader), Hinted(Hints::PreferredHeader));
-  EXPECT_LT(Hinted(Hints::CompleteSymbol | Hints::PublicHeader),
-Hinted(Hints::PreferredHeader));
+  EXPECT_LT(Hinted(Hints::PreferredHeader), Hinted(Hints::PublicHeader));
+  EXPECT_LT(Hinted(Hints::CompleteSymbol | Hints::PreferredHeader),
+Hinted(Hints::PublicHeader));
 }
 
 // Test ast traversal & redecl selection end-to-end for templates, as explicit
Index: clang-tools-extra/include-cleaner/lib/TypesInternal.h
===
--- clang-tools-extra/include-cleaner/lib/TypesInternal.h
+++ clang-tools-extra/include-cleaner/lib/TypesInternal.h
@@ -69,15 +69,15 @@
   /// Provides a generally-usable definition for the symbol. (a function decl,
   /// or class definition and not a forward declaration of a template).
   CompleteSymbol = 1 << 1,
-  /// Symbol is provided by a public file. Only absent in the cases where file
-  /// is explicitly marked as such, non self-contained or IWYU private
-  /// pragmas.
-  PublicHeader = 1 << 2,
   /// Header providing the symbol is explicitly marked as preferred, with an
   /// IWYU private pragma that points at this provider or header and symbol has
   /// ~the same name.
-  PreferredHeader = 1 << 3,
-  LLVM_MARK_AS_BITMASK_ENUM(PreferredHeader),
+  PreferredHeader = 1 << 2,
+  /// Symbol is provided by a public file. Only absent in the cases where file
+  /// is explicitly marked as such, non self-contained or IWYU private
+  /// pragmas.
+  PublicHeader = 1 << 3,
+  LLVM_MARK_AS_BITMASK_ENUM(PublicHeader),
 };
 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
 /// A wrapper to augment values with hints.


Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -465,6 +465,22 @@
physicalHeader("foo.h")));
 }
 
+TEST_F(HeadersForSymbolTest, PublicOverPrivateWithoutUmbrella) {
+  Inputs.Code = R"cpp(
+#include "bar.h"
+#include "foo.h"
+  )cpp";
+  Inputs.ExtraFiles["bar.h"] =
+  guard(R"cpp(#include "foo.h" // IWYU pragma: export)cpp");
+  Inputs.ExtraFiles["foo.h"] = guard(R"cpp(
+// IWYU pragma: private
+struct foo {};
+  )cpp");
+  buildAST();
+  EXPECT_THAT(headersForFoo(),
+  ElementsAre(physicalHeader("bar.h"), physicalHeader("foo.h")));
+}
+
 TEST_F(HeadersForSymbolTest, AmbiguousStdSymbols) {
   struct {
 llvm::StringRef Code;
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.

[clang] 58eba70 - [OpenMP] supporting additional case of declare target initializer expression list

2023-08-08 Thread Sandeep Kosuri via cfe-commits

Author: Ritanya B Bharadwaj
Date: 2023-08-08T10:14:59-05:00
New Revision: 58eba709a330e4c83de0a98b50fc0acf26cb4344

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

LOG: [OpenMP] supporting additional case of declare target initializer 
expression list

Added: 


Modified: 
clang/lib/Sema/SemaOpenMP.cpp
clang/test/OpenMP/declare_target_variables_ast_print.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 3482cafbc74aa1..404b21559559f1 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -23257,6 +23257,10 @@ void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, 
SourceLocation Loc,
   if (ASTMutationListener *ML = Context.getASTMutationListener())
 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
+  if (auto *VD = dyn_cast(ND);
+  LangOpts.OpenMP && VD && VD->hasAttr() &&
+  VD->hasGlobalStorage())
+ActOnOpenMPDeclareTargetInitializer(ND);
 }
 
 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,

diff  --git a/clang/test/OpenMP/declare_target_variables_ast_print.cpp 
b/clang/test/OpenMP/declare_target_variables_ast_print.cpp
index 1e37efe20989c7..cd5dfea56f8f35 100644
--- a/clang/test/OpenMP/declare_target_variables_ast_print.cpp
+++ b/clang/test/OpenMP/declare_target_variables_ast_print.cpp
@@ -27,6 +27,10 @@ struct target{
 };
 static target S;
 
+static int var3 = 100;
+static int *ptr_3 = &var3;
+static char c = 'a';
+
 #pragma omp declare target
 int target_var = variable;
 float target_var1 = variable2;
@@ -36,6 +40,9 @@ int (**ptr3)[2] = &arrptr;
 declare **obj3 = &obj2;
 target *S1 = &S;
 #pragma omp end declare target
+#pragma omp declare target(ptr_3)
+#pragma omp declare target to(c)
+
 // CHECK: #pragma omp declare target
 // CHECK-NEXT: static int variable = 100;
 // CHECK-NEXT: #pragma omp end declare target
@@ -87,7 +94,15 @@ target *S1 = &S;
 // CHECK-NEXT: #pragma omp declare target
 // CHECK-NEXT: static target S;
 // CHECK-NEXT: #pragma omp end declare target
-
+// CHECK-NEXT: #pragma omp declare target
+// CHECK-NEXT: static int var3 = 100;
+// CHECK-NEXT: #pragma omp end declare target
+// CHECK-NEXT: #pragma omp declare target
+// CHECK-NEXT: static int *ptr_3 = &var3;
+// CHECK-NEXT: #pragma omp end declare target
+// CHECK-NEXT: #pragma omp declare target
+// CHECK-NEXT: static char c = 'a';
+// CHECK-NEXT: #pragma omp end declare target
 // CHECK-NEXT: #pragma omp declare target
 // CHECK-NEXT: int target_var = variable;
 // CHECK-NEXT: #pragma omp end declare target



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


[PATCH] D157119: cmake: add missing dependencies on ClangDriverOptions tablegen

2023-08-08 Thread Jon Roelofs via Phabricator via cfe-commits
jroelofs added a comment.

Flaky test? Here's a later build where it succeeds, but the change has nothing 
to do with clangd: https://lab.llvm.org/buildbot/#/builders/168/builds/14997


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157119

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


[PATCH] D154130: [lit][clang] Avoid realpath on Windows due to MAX_PATH limitations

2023-08-08 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> @tahonermann are all your comments addressed at this point?

Apologies for the late response; I was on vacation last week.

No. I'm still skeptical that there is ever a desire to expand substitute drives.




Comment at: clang/test/Lexer/case-insensitive-include-win.c:5-9
+// Note: We must use the real path here, because the logic to detect case
+// mismatch relies on resolving the real path and checking that casing differs.
+// If we use %t and we are on a substitute drive S: mapping to C:\subst,
+// then we will compare "S:\test.dir\FOO.h" to "C:\subst\test.dir\foo.h"
+// and avoid emitting the diagnostic because the structure is different.

MrTrillian wrote:
> tahonermann wrote:
> > MrTrillian wrote:
> > > tahonermann wrote:
> > > > Hmm, is it really desirable or necessary that the case mismatch logic 
> > > > resolve substituted drives? I wouldn't think so. This seems like 
> > > > another case where our common canonicalization would be desired.
> > > I think it is necessary as I don't see how else we can retrieve the 
> > > original casing of the file path. Merely making the path absolute would 
> > > not do that. Searching for solutions on the internet finds ideas that are 
> > > worse like converting to a short path then back to a long path or 
> > > rebuilding the path one component at a time with a series directory 
> > > listing requests.
> > The warning this test checks for is diagnosed in 
> > `Preprocessor::HandleHeaderIncludeOrImport()`; search for 
> > `pp_nonportable_path` and/or `pp_nonportable_system_path`. I believe this 
> > warning will be issued if any component of the path does not match the case 
> > of the include directive. Since the file name differs in case, unless there 
> > is a bug in handling of the file name, this test isn't sensitive to case 
> > mismatches in `%t`.
> > 
> > From a user point of view, resolving a substitute drive doesn't seem 
> > desirableto me with respect to determining whether a non-portable path is 
> > being used; I don't think the behavior should be dependent on whether a 
> > substitute drive is being used or what its target is.
> @tahonermann I think the code is working by design and it would be an 
> unrelated change to modify its logic. See `trySimplifyPath` in 
> `PPDirectives.cpp`:
> 
> ```
>   // Below is a best-effort to handle ".." in paths. It is admittedly
>   // not 100% correct in the presence of symlinks.
> 
> // If these path components differ by more than just case, then we
> // may be looking at symlinked paths. Bail on this diagnostic to avoid
> // noisy false positives.
> ```
> 
> The test was previously implicitly requiring getting the realpath, and it 
> worked because `lit.py`'s logic of doing that. Now that requirement is 
> explicit in the test.
I'm still not following here. Are you saying that `trySimplifyPath()` will 
replace substitute drives? If so, that doesn't sound desirable and I would 
expect it to be problematic for your use case. I think we should follow this up 
... somewhere (now that this review is closed).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154130

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


[PATCH] D157379: [CodeGen] Restrict addEmittedDeferredDecl to incremental extensions

2023-08-08 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev added a comment.

This LGTM but I'd like to wait for @rjmccall for a week or so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157379

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


[PATCH] D156604: [clang][ExprConst] Use call source range for 'in call to' diags

2023-08-08 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


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

https://reviews.llvm.org/D156604

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


[PATCH] D157400: [include-cleaner] Dont boost private headers beyond public ones

2023-08-08 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo accepted this revision.
VitaNuo added a comment.
This revision is now accepted and ready to land.

Thanks.




Comment at: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp:474
+  Inputs.ExtraFiles["bar.h"] =
+  guard(R"cpp(#include "foo.h" // IWYU pragma: export)cpp");
+  Inputs.ExtraFiles["foo.h"] = guard(R"cpp(

nit: would be better to split this into multiple lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157400

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


[clang] 74c141a - [clang][ExprConst] Add RHS source range to div by zero diags

2023-08-08 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-08-08T17:59:13+02:00
New Revision: 74c141a467caf9ebb4835458bc4ffbedb172a63a

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

LOG: [clang][ExprConst] Add RHS source range to div by zero diags

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Interp.h
clang/test/Misc/constexpr-source-ranges.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 7d6796dd9d3598..c8d4258333f8fb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2805,9 +2805,9 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const 
Expr *E,
 }
 
 /// Perform the given binary integer operation.
-static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
-  BinaryOperatorKind Opcode, APSInt RHS,
-  APSInt &Result) {
+static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
+  const APSInt &LHS, APSInt RHS, APSInt &Result) {
+  BinaryOperatorKind Opcode = E->getOpcode();
   bool HandleOverflowResult = true;
   switch (Opcode) {
   default:
@@ -2828,7 +2828,8 @@ static bool handleIntIntBinOp(EvalInfo &Info, const Expr 
*E, const APSInt &LHS,
   case BO_Div:
   case BO_Rem:
 if (RHS == 0) {
-  Info.FFDiag(E, diag::note_expr_divide_by_zero);
+  Info.FFDiag(E, diag::note_expr_divide_by_zero)
+  << E->getRHS()->getSourceRange();
   return false;
 }
 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
@@ -3072,8 +3073,8 @@ static bool handleVectorVectorBinOp(EvalInfo &Info, const 
BinaryOperator *E,
   else if (BinaryOperator::isComparisonOp(Opcode))
 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
   else
-Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
-RHSElt.getInt(), EltResult);
+Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), RHSElt.getInt(),
+EltResult);
 
   if (!Success) {
 Info.FFDiag(E);
@@ -4473,7 +4474,7 @@ struct CompoundAssignSubobjectHandler {
 if (RHS.isInt()) {
   APSInt LHS =
   HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
-  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
+  if (!handleIntIntBinOp(Info, E, LHS, RHS.getInt(), LHS))
 return false;
   Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
   return true;
@@ -12892,8 +12893,7 @@ bool DataRecursiveIntBinOpEvaluator::
   // FIXME: Don't do this in the cases where we can deduce it.
   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
E->getType()->isUnsignedIntegerOrEnumerationType());
-  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
- RHSVal.getInt(), Value))
+  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), RHSVal.getInt(), Value))
 return false;
   return Success(Value, E, Result);
 }

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 4da5985e3b3d6f..9d7a9af01e8d11 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -148,8 +148,9 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const LT 
&LHS, const RT &RHS,
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
   if (RHS.isZero()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_expr_divide_by_zero);
+const auto *Op = cast(S.Current->getExpr(OpPC));
+S.FFDiag(Op, diag::note_expr_divide_by_zero)
+<< Op->getRHS()->getSourceRange();
 return false;
   }
 

diff  --git a/clang/test/Misc/constexpr-source-ranges.cpp 
b/clang/test/Misc/constexpr-source-ranges.cpp
index c4f83cbb0e23a4..b493fb37fb70d9 100644
--- a/clang/test/Misc/constexpr-source-ranges.cpp
+++ b/clang/test/Misc/constexpr-source-ranges.cpp
@@ -13,3 +13,15 @@ constexpr int I = 12;
 constexpr const int *P = &I;
 constexpr long L = (long)P;
 // CHECK: constexpr-source-ranges.cpp:14:20:{14:20-14:27}
+
+constexpr int zero() {
+  return 0;
+}
+constexpr int divByZero() {
+  return 1 / zero();
+}
+static_assert(divByZero() == 0, "");
+/// We see this twice. Once from sema and once when
+/// evaluating the static_assert above.
+// CHECK: constexpr-source-ranges.cpp:23:15:{23:15-23:31}
+// CHECK: constexpr-source-ranges.cpp:21:12:{21:14-21:20}



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

[PATCH] D157074: [clang][ExprConst] Add RHS source range to div by zero diags

2023-08-08 Thread Timm Bäder 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 rG74c141a467ca: [clang][ExprConst] Add RHS source range to div 
by zero diags (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D157074?vs=547660&id=548251#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157074

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/Interp.h
  clang/test/Misc/constexpr-source-ranges.cpp


Index: clang/test/Misc/constexpr-source-ranges.cpp
===
--- clang/test/Misc/constexpr-source-ranges.cpp
+++ clang/test/Misc/constexpr-source-ranges.cpp
@@ -13,3 +13,15 @@
 constexpr const int *P = &I;
 constexpr long L = (long)P;
 // CHECK: constexpr-source-ranges.cpp:14:20:{14:20-14:27}
+
+constexpr int zero() {
+  return 0;
+}
+constexpr int divByZero() {
+  return 1 / zero();
+}
+static_assert(divByZero() == 0, "");
+/// We see this twice. Once from sema and once when
+/// evaluating the static_assert above.
+// CHECK: constexpr-source-ranges.cpp:23:15:{23:15-23:31}
+// CHECK: constexpr-source-ranges.cpp:21:12:{21:14-21:20}
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -148,8 +148,9 @@
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
   if (RHS.isZero()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_expr_divide_by_zero);
+const auto *Op = cast(S.Current->getExpr(OpPC));
+S.FFDiag(Op, diag::note_expr_divide_by_zero)
+<< Op->getRHS()->getSourceRange();
 return false;
   }
 
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2805,9 +2805,9 @@
 }
 
 /// Perform the given binary integer operation.
-static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
-  BinaryOperatorKind Opcode, APSInt RHS,
-  APSInt &Result) {
+static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
+  const APSInt &LHS, APSInt RHS, APSInt &Result) {
+  BinaryOperatorKind Opcode = E->getOpcode();
   bool HandleOverflowResult = true;
   switch (Opcode) {
   default:
@@ -2828,7 +2828,8 @@
   case BO_Div:
   case BO_Rem:
 if (RHS == 0) {
-  Info.FFDiag(E, diag::note_expr_divide_by_zero);
+  Info.FFDiag(E, diag::note_expr_divide_by_zero)
+  << E->getRHS()->getSourceRange();
   return false;
 }
 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
@@ -3072,8 +3073,8 @@
   else if (BinaryOperator::isComparisonOp(Opcode))
 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
   else
-Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
-RHSElt.getInt(), EltResult);
+Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), RHSElt.getInt(),
+EltResult);
 
   if (!Success) {
 Info.FFDiag(E);
@@ -4473,7 +4474,7 @@
 if (RHS.isInt()) {
   APSInt LHS =
   HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
-  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
+  if (!handleIntIntBinOp(Info, E, LHS, RHS.getInt(), LHS))
 return false;
   Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
   return true;
@@ -12892,8 +12893,7 @@
   // FIXME: Don't do this in the cases where we can deduce it.
   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
E->getType()->isUnsignedIntegerOrEnumerationType());
-  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
- RHSVal.getInt(), Value))
+  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), RHSVal.getInt(), Value))
 return false;
   return Success(Value, E, Result);
 }


Index: clang/test/Misc/constexpr-source-ranges.cpp
===
--- clang/test/Misc/constexpr-source-ranges.cpp
+++ clang/test/Misc/constexpr-source-ranges.cpp
@@ -13,3 +13,15 @@
 constexpr const int *P = &I;
 constexpr long L = (long)P;
 // CHECK: constexpr-source-ranges.cpp:14:20:{14:20-14:27}
+
+constexpr int zero() {
+  return 0;
+}
+constexpr int divByZero() {
+  return 1 / zero();
+}
+static_assert(divByZero() == 0, "");
+/// We see this twice. Once from sema and once when
+/// evaluating the static_assert above.
+// CHECK: constexpr-source-ranges.cpp:23:15:{23:15-23:31}
+// CHECK: constexpr-source-ranges.cpp:21:12:{21:14-21:20}
Index: clang/

[PATCH] D157384: [clang] Added Attr::getVariety function

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/Attr.h:87-99
+  enum class Variety {
+None,
+GNU,  // __attribute__((...))
+Declspec, // __declspec(...)
+Microsoft,// [...]
+CXX11,// [[...]]
+C2x,  // [[...]]

I don't think either of these are needed -- `Attr` inherits from 
`AttributeCommonInfo` and that base class already has 
`AttributeCommonInfo::getSyntax()` for getting this information. Will that work 
for your needs?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157384

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


[PATCH] D157324: [clang] Move the Clang CI jobs off of the libc++ builders

2023-08-08 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik accepted this revision.
philnik added a comment.
This revision is now accepted and ready to land.

Thanks for working on this! I think it would make a lot of sense to unify this 
build and the Debian build,  since currently we are building Clang twice 
without a good reason.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157324

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


[PATCH] D157118: [NFC][Clang] Fix static analyzer concerns

2023-08-08 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann accepted this revision.
tahonermann added a comment.

I think this change is good as is, but I added some additional thoughts to 
Aaron's earlier comment.




Comment at: clang/lib/AST/StmtPrinter.cpp:178
 void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
+  assert(Node && "Compound statement cannot be null");
   OS << "{" << NL;

aaron.ballman wrote:
> Hmmm, I think this is what we're effectively already hoping is the case 
> today, but I don't think that's a safe assertion by itself. Consider: 
> https://github.com/llvm/llvm-project/blob/cd29ebb862b5c7a81c9f39c8c493f9246d6e5f0b/clang/lib/AST/StmtPrinter.cpp#L602
> 
> It might be worth looking at all the calls to `PrintRawCompoundStmt()` to see 
> which ones potentially can pass null in, and decide if there are additional 
> changes to make. e.g., should that `dyn_cast` be a `cast` instead so it 
> cannot return nullptr and we get the assertion a little bit earlier when 
> calling `cast<>`?
Another possibility would be to modify `ObjCAtFinallyStmt` to declare 
`AtFinallyStmt` as `CompoundStmt*` and to modify `getFinallyBody()` and 
`setFinallyBody()` accordingly. That would remove the need for that `dyn_cast` 
in `StmtPrinter::VisitObjCAtTryStmt()`. This would then require additional 
changes such as updates to `ASTStmtReader::VisitObjCAtFinallyStmt()` to perform 
a cast as is done in `ASTStmtReader::VisitStmtExpr()`. But none of that 
actually addresses the fact that this function has a precondition that `Node` 
is not null.


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

https://reviews.llvm.org/D157118

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


[PATCH] D156604: [clang][ExprConst] Use call source range for 'in call to' diags

2023-08-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM but please give a day or two for @hazohelet to weigh in.


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

https://reviews.llvm.org/D156604

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


[PATCH] D157129: [NFC] Fix unnecessary copy with auto.

2023-08-08 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann requested changes to this revision.
tahonermann added a comment.

I agree with the analysis done by @steakhal. The static analyzer being used 
(which I'm not allowed to name) is being too noisy in these cases; it complains 
about every case where an object of class type is copied regardless of size. An 
issue has been reported to the static analysis vendor about this. These 
complaints from the static analyzer will need to be moderated until the vendor 
satisfactorily addresses the reported issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157129

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


  1   2   3   >