[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() [Cont.] (PR #95220)

2024-06-16 Thread Carlos Galvez via cfe-commits
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= ,
Paul =?utf-8?q?Heidekrüger?= 
Message-ID:
In-Reply-To: 


carlosgalvezp wrote:

> I specifically added container to both names because the check is in SL.con

Sounds good to me! My main goal is not constraining the check to only 
`operator[]`; in the future someone might want to also implement functionality 
to detect e.g. `std::memset` as you mentioned, and in that case it would be 
awkward to create a new check even though it covers the same rule.

Btw, I realize that this check is part of the [bounds 
profile](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-bounds)
 (Bounds.4), so for consistency it should probably be named 
`cppcoreguidelines-pro-bounds-...`. This becomes then the last remaining check 
to complete the bounds profile!

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


[clang] [Clang] fix access checking inside return-type-requirement of compound requirements (PR #95651)

2024-06-16 Thread Zhikai Zeng via cfe-commits

https://github.com/Backl1ght updated 
https://github.com/llvm/llvm-project/pull/95651

>From 49f0d1aff888b2a96ed3a19d8d2e30d367caf14f Mon Sep 17 00:00:00 2001
From: Backl1ght 
Date: Sat, 15 Jun 2024 16:56:00 +0800
Subject: [PATCH] fix

---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  2 +-
 .../expr.prim.req/compound-requirement.cpp| 36 +++
 3 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 36efeb8c70cca..3717e573419e7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -858,6 +858,7 @@ Bug Fixes to C++ Support
 - Fixed several bugs in capturing variables within unevaluated contexts. 
(#GH63845), (#GH67260), (#GH69307),
   (#GH88081), (#GH89496), (#GH90669) and (#GH91633).
 - Fixed handling of brace ellison when building deduction guides. (#GH64625), 
(#GH83368).
+- Fixed a bug in access checking inside return-type-requirement of compound 
requirements. (#GH93788).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 863cc53c55afa..1fe1fe9d4f833 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2735,7 +2735,7 @@ 
TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
 if (TPLInst.isInvalid())
   return nullptr;
 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
-if (!TPL)
+if (!TPL || Trap.hasErrorOccurred())
   TransRetReq.emplace(createSubstDiag(SemaRef, Info,
   [&] (llvm::raw_ostream& OS) {
   RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
diff --git 
a/clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp
index b7366207882f9..dc0e84280e056 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp
@@ -189,3 +189,39 @@ namespace std_example {
   template struct C5_check {}; // expected-note{{because 'short' does 
not satisfy 'C5'}}
   using c5 = C5_check; // expected-error{{constraints not satisfied for 
class template 'C5_check' [with T = short]}}
 }
+
+namespace access_checks {
+namespace in_return_type_requirement {
+
+// https://github.com/llvm/llvm-project/issues/93788
+template 
+concept is_assignable = requires(From from, To to) {
+  from = to;
+};
+
+template 
+class trait {
+ public:
+  using public_type = int;
+ private:
+  using private_type = int;
+};
+
+template 
+concept has_field = requires(T t) {
+  { t.field } -> is_assignable::private_type>;  // 
expected-note {{'private_type' is a private member}}
+};
+template 
+concept has_field2 = requires(T t) {
+  { t.field } -> is_assignable::public_type>;
+};
+
+struct A {
+  int field;
+};
+static_assert(has_field); // expected-error {{static assertion failed}} \
+ // expected-note {{because 'A' does not satisfy 
'has_field'}}
+static_assert(has_field2);
+
+}  // namespace access_checks
+}  // namespace in_return_type_requirement

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


[clang] [llvm] [RISCV] Add scheduling model for Syntacore SCR3 (PR #95427)

2024-06-16 Thread Anton Afanasyev via cfe-commits

https://github.com/anton-afanasyev approved this pull request.


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


[clang] [clang] SourceLocIdentKind::Function should not be dependent (PR #94942)

2024-06-16 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> So, looked into this more. You are correct that `Function` needs not be 
> dependent because we only ever show the name of the function unqualified. 
> However, `FunctionSig` does. Here is an example of what we are trying to 
> preserve https://godbolt.org/z/M3eTa8nn5 (the clang 17 behavior was incorrect)
> 
> I apologize for not realizing earlier that your change was actually sensible 
> in the case of `Function`

Never mind! After looking into the code a little bit more, `FunctionSig` indeed 
needs to be dependent.
```cpp
template
constexpr int g() {
  return N;
}

template 
struct S {
void f(auto) {
constexpr const char* F = __builtin_FUNCSIG();
static_assert(__builtin_strlen(F)==g<__builtin_strlen(F)>());
}

};

void f(){
S{}.f(0);
}
```
However, it still crash when we changed from  `__builtin_FUNCTION` to 
`__builtin_FUNCSIG` in the testcase from 
https://github.com/llvm/llvm-project/issues/80210. The underlying issue is that 
`CurContext` is `FunctionTemplateDecl` which is dependent and we used it as 
`ParentContext` of `SourceLocExpr` when transforming `decltype` of function 
`construct_at`. This makes transformed return type of `construct_at` dependent 
which is not what we want. I will close this patch since it  doesn't resolve 
the underlying issue.  Thanks for your time for the review! @cor3ntin 








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


[clang] [clang] SourceLocIdentKind::Function should not be dependent (PR #94942)

2024-06-16 Thread Qizhi Hu via cfe-commits

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/3] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine &Line) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken &RootToken) {
+  int getIndentOffset(const AnnotatedLine &Line) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, &RootToken]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken &RootToken) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.In

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

2024-06-16 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> This change has caused a regression in one of our systems integration tests 
> that test static analysis for the bstring lib project 
> (https://github.com/websnarf/bstrlib) with cross translation unit analysis 
> enabled. Unfortunately I do not have a simple reproducer that stands alone 
> just using clang, but I do have a reproducer that uses CodeChecker and can 
> paste in the crash signature here. Please consider reverting the change until 
> a proper fix can be made and this issue is addressed.
> 
> ```
> bstrwrap.cpp
>   1 #include "bstrwrap.h"
>   2 #include 
>   3
>   4 Bstrlib::CBString::CBString () {
>   5 } 
> 
> bstrwrap.h
>   1 #include 
>   2
>   3 namespace Bstrlib {
>   4 struct CBString {  
>   5CBString ();
>   6 };
>   7
>   8 extern std::istream& getline (std::istream& sin, CBString& b, char 
> terminator='\n');
>   9
>  10 } // namespace Bstrlib
> 
> 
> test.cpp
>   1 #include "bstrwrap.h"
>   2
>   3 int test0 (void) {
>   4   Bstrlib::CBString c0;
>   5   return 0;
>   6 }
> ```
> 
> Using CodeChecker from https://github.com/Ericsson/codechecker, Log the build
> 
> `CodeChecker log -b "g++ -c test.cpp bstrwrap.cpp" -o comp.json`
> 
> Repro step
> 
> ```
> ``env PATH=:$PATH CC_ANALYZERS_FROM_PATH=1 CodeChecker 
> analyze comp.json  --clean  --ctu -o report --analyzers clangsa``
> ```
> 
> The crash signature, appears to be crashing in AST Import.
> 
> ```
> 1.   parser at end of file
> 2.  While analyzing stack:
> #0 Calling test0()
> 3.  test.cpp:4:21: Error evaluating statement
> 4.  test.cpp:4:21: Error evaluating statement
>  #0 0x03cb7248 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
> (clang-19+0x3cb7248)
>  #1 0x03cb4f2c llvm::sys::CleanupOnSignal(unsigned long) 
> (clang-19+0x3cb4f2c)
>  #2 0x03bfd308 CrashRecoverySignalHandler(int) 
> CrashRecoveryContext.cpp:0:0
>  #3 0x7f9e5d53d630 __restore_rt sigaction.c:0:0
>  #4 0x7f9e5af39387 raise (/lib64/libc.so.6+0x36387)
>  #5 0x7f9e5af3aa78 abort (/lib64/libc.so.6+0x37a78)
>  #6 0x7f9e5af321a6 __assert_fail_base (/lib64/libc.so.6+0x2f1a6)
>  #7 0x7f9e5af32252 (/lib64/libc.so.6+0x2f252)
>  #8 0x072ada26 
> clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*)
>  (clang-19+0x72ada26)
>  #9 0x07190a56 
> clang::ASTNodeImporter::VisitFunctionTemplateDecl(clang::FunctionTemplateDecl*)
>  (clang-19+0x7190a56)
> #10 0x0716e998 clang::declvisitor::Base clang::ASTNodeImporter, llvm::Expected>::Visit(clang::Decl*) 
> crtstuff.c:0:0
> #11 0x0716eedb clang::ASTImporter::Import(clang::Decl*) 
> (clang-19+0x716eedb)
> #12 0x07172108 std::conditional clang::Decl>, llvm::Expected, 
> llvm::Expected>::type 
> clang::ASTNodeImporter::import(clang::Decl*) crtstuff.c:0:0
> #13 0x0717d072 
> clang::ASTNodeImporter::ImportDeclContext(clang::DeclContext*, bool) 
> (clang-19+0x717d072)
> #14 0x0718677b 
> clang::ASTNodeImporter::VisitNamespaceDecl(clang::NamespaceDecl*) 
> (clang-19+0x718677b)
> #15 0x0716ea38 clang::declvisitor::Base clang::ASTNodeImporter, llvm::Expected>::Visit(clang::Decl*) 
> crtstuff.c:0:0
> #16 0x0716eedb clang::ASTImporter::Import(clang::Decl*) 
> (clang-19+0x716eedb)
> #17 0x07175146 
> clang::ASTImporter::Import(clang::NestedNameSpecifier*) (clang-19+0x7175146)
> #18 0x0717a0bb 
> clang::ASTNodeImporter::VisitElaboratedType(clang::ElaboratedType const*) 
> (clang-19+0x717a0bb)
> #19 0x07174945 clang::TypeVisitor llvm::Expected>::Visit(clang::Type const*) crtstuff.c:0:0
> #20 0x07174c07 clang::ASTImporter::Import(clang::Type const*) 
> (clang-19+0x7174c07)
> #21 0x07175bd7 clang::ASTImporter::Import(clang::QualType) 
> (clang-19+0x7175bd7)
> #22 0x07177e20 
> clang::ASTNodeImporter::VisitLValueReferenceType(clang::LValueReferenceType 
> const*) (clang-19+0x7177e20)
> ```

Looks like ASTImporter issue. Could you please provider a reproducer using 
clang only? That would be better to catch the issue. Just reverting this patch 
may not crash any more, but it would lead to incorrect AST be imported and 
influenced the accuracy of static analysis.

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


[clang] [Clang] Remove some dead code in getNumTeamsExprForTargetDirective (PR #95695)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta created 
https://github.com/llvm/llvm-project/pull/95695

This was reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N9.

V523 The 'then' statement is equivalent to the subsequent code fragment. 
CGOpenMPRuntime.cpp:6040, 6036

>From 16fde316ba9bd8a54545d71b46df968ae1bb86d3 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 15:01:13 +0530
Subject: [PATCH] [Clang] Remove some dead code in
 getNumTeamsExprForTargetDirective

This was reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N9.

V523 The 'then' statement is equivalent to the subsequent code fragment. 
CGOpenMPRuntime.cpp:6040, 6036
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 2 --
 1 file changed, 2 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index f6d12d46cfc07..0c99ee3b8c4a9 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6037,8 +6037,6 @@ const Expr 
*CGOpenMPRuntime::getNumTeamsExprForTargetDirective(
 MinTeamsVal = MaxTeamsVal = 1;
 return nullptr;
   }
-  MinTeamsVal = MaxTeamsVal = 1;
-  return nullptr;
 }
 // A value of -1 is used to check if we need to emit no teams region
 MinTeamsVal = MaxTeamsVal = -1;

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


[clang] [Clang] Remove some dead code in getNumTeamsExprForTargetDirective (PR #95695)

2024-06-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang

Author: Shivam Gupta (xgupta)


Changes

This was reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N9.

V523 The 'then' statement is equivalent to the subsequent code fragment. 
CGOpenMPRuntime.cpp:6040, 6036

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGOpenMPRuntime.cpp (-2) 


``diff
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index f6d12d46cfc07..0c99ee3b8c4a9 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6037,8 +6037,6 @@ const Expr 
*CGOpenMPRuntime::getNumTeamsExprForTargetDirective(
 MinTeamsVal = MaxTeamsVal = 1;
 return nullptr;
   }
-  MinTeamsVal = MaxTeamsVal = 1;
-  return nullptr;
 }
 // A value of -1 is used to check if we need to emit no teams region
 MinTeamsVal = MaxTeamsVal = -1;

``




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


[clang] [clang] Clean up macOS version flags (PR #95374)

2024-06-16 Thread Gábor Horváth via cfe-commits

https://github.com/Xazax-hun updated 
https://github.com/llvm/llvm-project/pull/95374

From ad99b7f7587242060adf60d3e3f08711b0bc670d Mon Sep 17 00:00:00 2001
From: Gabor Horvath 
Date: Thu, 13 Jun 2024 09:46:05 +0100
Subject: [PATCH] [clang] Clean up macOS version flags

The -mmacos-version-min flag is preferred over -mmacosx-version-min. This patch
makes updates the tests and documentation to make this clear and also adds the
missing logic to scan build to handle the new flag.

Fixes #86376.
---
 clang/docs/CommandGuide/clang.rst  |  4 ++--
 clang/docs/LanguageExtensions.rst  |  4 ++--
 clang/include/clang/Driver/ToolChain.h |  2 +-
 clang/test/Coverage/targets.c  |  2 +-
 clang/test/Driver/arc.c|  2 +-
 clang/test/Driver/arclite-link.c   |  8 
 clang/test/Driver/darwin-objc-defaults.m   | 14 +++---
 clang/test/Driver/darwin-stdlib-dont-pass-in-c.c   |  2 +-
 clang/test/Driver/darwin-stdlib.cpp|  6 +++---
 clang/test/Driver/darwin-version.c | 10 +-
 clang/test/Driver/darwin-xarch.c   |  4 ++--
 clang/test/Driver/fsanitize.c  |  6 +++---
 ...s-apple-silicon-slice-link-libs-darwin-only.cpp |  4 ++--
 clang/test/Driver/sanitizer-ld.c   |  4 ++--
 clang/test/Driver/stack-protector.c| 14 +++---
 clang/test/Index/TestClassForwardDecl.m|  2 +-
 clang/test/Index/c-index-api-loadTU-test.m |  2 +-
 clang/test/Index/c-index-getCursor-test.m  |  2 +-
 clang/tools/scan-build/libexec/ccc-analyzer|  1 +
 19 files changed, 47 insertions(+), 46 deletions(-)

diff --git a/clang/docs/CommandGuide/clang.rst 
b/clang/docs/CommandGuide/clang.rst
index 643365215f875..14400c39e9190 100644
--- a/clang/docs/CommandGuide/clang.rst
+++ b/clang/docs/CommandGuide/clang.rst
@@ -362,7 +362,7 @@ number of cross compilers, or may only support a native 
target.
 
   Specify the architecture to build for (all platforms).
 
-.. option:: -mmacosx-version-min=
+.. option:: -mmacos-version-min=
 
   When building for macOS, specify the minimum version supported by your
   application.
@@ -723,7 +723,7 @@ ENVIRONMENT
 
 .. envvar:: MACOSX_DEPLOYMENT_TARGET
 
-  If :option:`-mmacosx-version-min` is unspecified, the default deployment
+  If :option:`-mmacos-version-min` is unspecified, the default deployment
   target is read from this environment variable. This option only affects
   Darwin targets.
 
diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index a49e4122ffc10..92e6025c95a8c 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2063,7 +2063,7 @@ Objective-C @available
 --
 
 It is possible to use the newest SDK but still build a program that can run on
-older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
+older versions of macOS and iOS by passing ``-mmacos-version-min=`` /
 ``-miphoneos-version-min=``.
 
 Before LLVM 5.0, when calling a function that exists only in the OS that's
@@ -2084,7 +2084,7 @@ When a method that's introduced in the OS newer than the 
target OS is called, a
 
   void my_fun(NSSomeClass* var) {
 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
-// built with -mmacosx-version-min=10.11, then this unconditional call
+// built with -mmacos-version-min=10.11, then this unconditional call
 // will emit a -Wunguarded-availability warning:
 [var fancyNewMethod];
   }
diff --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 9789cfacafd78..1f93bd612e9b0 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -639,7 +639,7 @@ class ToolChain {
 
   /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
   /// target, which may take into account the command line arguments. For
-  /// example, on Darwin the -mmacosx-version-min= command line argument (which
+  /// example, on Darwin the -mmacos-version-min= command line argument (which
   /// sets the deployment target) determines the version in the triple passed 
to
   /// Clang.
   virtual std::string ComputeEffectiveClangTriple(
diff --git a/clang/test/Coverage/targets.c b/clang/test/Coverage/targets.c
index a0ec2836874a6..15110eadb298e 100644
--- a/clang/test/Coverage/targets.c
+++ b/clang/test/Coverage/targets.c
@@ -14,4 +14,4 @@
 // RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-unknown 
-emit-llvm -o %t %s
 
 // clang 1.0 fails to compile Python 2.6
-// RUN: %clang -target x86_64-apple-darwin9 -### -S %s 
-mmacosx-version-min=10.4
+// RUN: %clang -target x86_64-apple-darwin9 -### -S %s -mmacos-version-min=10.4
diff --git a/clang/test/Driver/arc.c b/clang/test/Driver/arc.c
index 6c91a3b1c87c6..e5d1af5225662 100644
--- a/cla

[clang] [Clang] Fix a variable shadowing in MapLattice (NFC) (PR #95697)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta created 
https://github.com/llvm/llvm-project/pull/95697

Reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N10.

The PVS-Studio warning:
V570 The 'C' variable is assigned to itself. MapLattice.h:52

>From 60fdd988d16ea624d2fd732cf03ee0fc69a14abc Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 15:41:09 +0530
Subject: [PATCH] [Clang] Fix a variable shadowing in MapLattice (NFC)

Reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N10.

The PVS-Studio warning:
V570 The 'C' variable is assigned to itself. MapLattice.h:52
---
 clang/include/clang/Analysis/FlowSensitive/MapLattice.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 16b0c978779a7..9d7afbe6ae7bf 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -49,7 +49,7 @@ template  class 
MapLattice {
 
   MapLattice() = default;
 
-  explicit MapLattice(Container C) { C = std::move(C); }
+  explicit MapLattice(Container C) : C { std::move(C) } {};
 
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }

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


[clang] [Clang] Fix a variable shadowing in MapLattice (NFC) (PR #95697)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: Shivam Gupta (xgupta)


Changes

Reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N10.

The PVS-Studio warning:
V570 The 'C' variable is assigned to itself. MapLattice.h:52

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


1 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/MapLattice.h (+1-1) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 16b0c978779a7..9d7afbe6ae7bf 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -49,7 +49,7 @@ template  class 
MapLattice {
 
   MapLattice() = default;
 
-  explicit MapLattice(Container C) { C = std::move(C); }
+  explicit MapLattice(Container C) : C { std::move(C) } {};
 
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }

``




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


[clang] [Clang] Fix a variable shadowing in MapLattice (NFC) (PR #95697)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95697

>From 60fdd988d16ea624d2fd732cf03ee0fc69a14abc Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 15:41:09 +0530
Subject: [PATCH 1/2] [Clang] Fix a variable shadowing in MapLattice (NFC)

Reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N10.

The PVS-Studio warning:
V570 The 'C' variable is assigned to itself. MapLattice.h:52
---
 clang/include/clang/Analysis/FlowSensitive/MapLattice.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 16b0c978779a7..9d7afbe6ae7bf 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -49,7 +49,7 @@ template  class 
MapLattice {
 
   MapLattice() = default;
 
-  explicit MapLattice(Container C) { C = std::move(C); }
+  explicit MapLattice(Container C) : C { std::move(C) } {};
 
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }

>From bfa6cae6b4e01a7fb5fd599dc69a8a1ffa597878 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 15:42:53 +0530
Subject: [PATCH 2/2] clang-format

---
 clang/include/clang/Analysis/FlowSensitive/MapLattice.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 9d7afbe6ae7bf..b2d147e4ae444 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -49,7 +49,7 @@ template  class 
MapLattice {
 
   MapLattice() = default;
 
-  explicit MapLattice(Container C) : C { std::move(C) } {};
+  explicit MapLattice(Container C) : C{std::move(C)} {};
 
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }

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


[clang] [Clang] Fix a variable shadowing in MapLattice (NFC) (PR #95697)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 22530e7985083032fe708848abb88b77be78e5ce 
60fdd988d16ea624d2fd732cf03ee0fc69a14abc -- 
clang/include/clang/Analysis/FlowSensitive/MapLattice.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 9d7afbe6ae..b2d147e4ae 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -49,7 +49,7 @@ public:
 
   MapLattice() = default;
 
-  explicit MapLattice(Container C) : C { std::move(C) } {};
+  explicit MapLattice(Container C) : C{std::move(C)} {};
 
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }

``




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


[clang] edabb5c - [clang] Clean up macOS version flags (#95374)

2024-06-16 Thread via cfe-commits

Author: Gábor Horváth
Date: 2024-06-16T12:25:25+02:00
New Revision: edabb5c12ed9312c3366286a69e881f625102a85

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

LOG: [clang] Clean up macOS version flags (#95374)

The -mmacos-version-min flag is preferred over -mmacosx-version-min.
This patch updates the tests and documentation to make this clear and
also adds the missing logic to scan build to handle the new flag.

Fixes #86376.

Co-authored-by: Gabor Horvath 

Added: 


Modified: 
clang/docs/CommandGuide/clang.rst
clang/docs/LanguageExtensions.rst
clang/include/clang/Driver/ToolChain.h
clang/test/Coverage/targets.c
clang/test/Driver/arc.c
clang/test/Driver/arclite-link.c
clang/test/Driver/darwin-objc-defaults.m
clang/test/Driver/darwin-stdlib-dont-pass-in-c.c
clang/test/Driver/darwin-stdlib.cpp
clang/test/Driver/darwin-version.c
clang/test/Driver/darwin-xarch.c
clang/test/Driver/fsanitize.c
clang/test/Driver/macos-apple-silicon-slice-link-libs-darwin-only.cpp
clang/test/Driver/sanitizer-ld.c
clang/test/Driver/stack-protector.c
clang/test/Index/TestClassForwardDecl.m
clang/test/Index/c-index-api-loadTU-test.m
clang/test/Index/c-index-getCursor-test.m
clang/tools/scan-build/libexec/ccc-analyzer

Removed: 




diff  --git a/clang/docs/CommandGuide/clang.rst 
b/clang/docs/CommandGuide/clang.rst
index 643365215f875..14400c39e9190 100644
--- a/clang/docs/CommandGuide/clang.rst
+++ b/clang/docs/CommandGuide/clang.rst
@@ -362,7 +362,7 @@ number of cross compilers, or may only support a native 
target.
 
   Specify the architecture to build for (all platforms).
 
-.. option:: -mmacosx-version-min=
+.. option:: -mmacos-version-min=
 
   When building for macOS, specify the minimum version supported by your
   application.
@@ -723,7 +723,7 @@ ENVIRONMENT
 
 .. envvar:: MACOSX_DEPLOYMENT_TARGET
 
-  If :option:`-mmacosx-version-min` is unspecified, the default deployment
+  If :option:`-mmacos-version-min` is unspecified, the default deployment
   target is read from this environment variable. This option only affects
   Darwin targets.
 

diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index a49e4122ffc10..92e6025c95a8c 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2063,7 +2063,7 @@ Objective-C @available
 --
 
 It is possible to use the newest SDK but still build a program that can run on
-older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
+older versions of macOS and iOS by passing ``-mmacos-version-min=`` /
 ``-miphoneos-version-min=``.
 
 Before LLVM 5.0, when calling a function that exists only in the OS that's
@@ -2084,7 +2084,7 @@ When a method that's introduced in the OS newer than the 
target OS is called, a
 
   void my_fun(NSSomeClass* var) {
 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
-// built with -mmacosx-version-min=10.11, then this unconditional call
+// built with -mmacos-version-min=10.11, then this unconditional call
 // will emit a -Wunguarded-availability warning:
 [var fancyNewMethod];
   }

diff  --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 9789cfacafd78..1f93bd612e9b0 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -639,7 +639,7 @@ class ToolChain {
 
   /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
   /// target, which may take into account the command line arguments. For
-  /// example, on Darwin the -mmacosx-version-min= command line argument (which
+  /// example, on Darwin the -mmacos-version-min= command line argument (which
   /// sets the deployment target) determines the version in the triple passed 
to
   /// Clang.
   virtual std::string ComputeEffectiveClangTriple(

diff  --git a/clang/test/Coverage/targets.c b/clang/test/Coverage/targets.c
index a0ec2836874a6..15110eadb298e 100644
--- a/clang/test/Coverage/targets.c
+++ b/clang/test/Coverage/targets.c
@@ -14,4 +14,4 @@
 // RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-unknown 
-emit-llvm -o %t %s
 
 // clang 1.0 fails to compile Python 2.6
-// RUN: %clang -target x86_64-apple-darwin9 -### -S %s 
-mmacosx-version-min=10.4
+// RUN: %clang -target x86_64-apple-darwin9 -### -S %s -mmacos-version-min=10.4

diff  --git a/clang/test/Driver/arc.c b/clang/test/Driver/arc.c
index 6c91a3b1c87c6..e5d1af5225662 100644
--- a/clang/test/Driver/arc.c
+++ b/clang/test/Driver/arc.c
@@ -3,7 +3,7 @@
 // RUN: not %clang -x objective-c++ -target i386-apple-darwin10 
-stdlib=libstdc++ -m32 -fobjc-arc %s -fsyntax-only 2>&1 | FileCheck %s
 // RUN:

[clang] [clang] Clean up macOS version flags (PR #95374)

2024-06-16 Thread Gábor Horváth via cfe-commits

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/4] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine &Line) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken &RootToken) {
+  int getIndentOffset(const AnnotatedLine &Line) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, &RootToken]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken &RootToken) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.In

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

2024-06-16 Thread via cfe-commits

vabridgers wrote:

Hello @jcsxky , here's a simplified reproducer that drives the crash from a 
shell script. All you need to do is make sure your clang build is in the path. 
I repro'd this on a RHEL7 host, just in case that details matters (but I don't 
think it will). 

This script echos the simplified source files and the accompanying 
externalDefMap.txt needed to drive a CTU analysis. 

# remove, regen the ctu directory and externalDefMap.txt file. This file 
corresponds to 
# to the subsequently generated header and source files and is provided for 
simplicity of crash repro
rm -rf ctudir
mkdir ctudir
touch ctudir/externalDefMap.txt
echo '11:c:@F@test0# test.cpp.ast' >> ctudir/externalDefMap.txt
echo '35:c:@N@Bstrlib@S@CBString@F@CBString# bstrwrap.cpp.ast' >> 
ctudir/externalDefMap.txt

# remove, regen the cpp file
rm -rf test.cpp
echo '#include "bstrwrap.h"' >> test.cpp
echo 'int test0 (void) {' >> test.cpp
echo '  Bstrlib::CBString c0;' >> test.cpp
echo '  return 0;' >> test.cpp
echo '}' >> test.cpp

# remove, regen the cpp file
rm -rf bstrwrap.cpp
echo '#include "bstrwrap.h"' >> bstrwrap.cpp
echo '#include ' >> bstrwrap.cpp
echo 'Bstrlib::CBString::CBString () {' >> bstrwrap.cpp
echo '}' >> bstrwrap.cpp

# remove, regen the header file
rm -rf bstrwrap.h
echo '#include ' >> bstrwrap.h
echo 'namespace Bstrlib {' >> bstrwrap.h
echo 'struct CBString  {' >> bstrwrap.h
echo '  CBString ();' >> bstrwrap.h
echo '};' >> bstrwrap.h
echo 'extern std::istream& getline (void);' >> bstrwrap.h
echo '}' >> bstrwrap.h

# generate the ASTs
clang bstrwrap.cpp -emit-ast -D__clang_analyzer__ -w -o ctudir/bstrwrap.cpp.ast
clang test.cpp -emit-ast -D__clang_analyzer__ -w -o ctudir/test.cpp.ast
# drive the analysis exposing the AST import crash
#clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp
clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir test.cpp


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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread via cfe-commits

sstwcw wrote:

I suggest removing the second block.  The first block was intended for handling 
the backtick character.  The second block was intended for handling the hash 
character.  I messed things up when I made the code treat the backtick 
character like the hash character.  I will figure out if the second block is 
really needed and add a test if it is needed.

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


[clang] [Clang] Instantiate local constexpr functions eagerly (PR #95660)

2024-06-16 Thread Younan Zhang via cfe-commits

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

>From c288190c313d6990580048368c60a846919f98ae Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 15 Jun 2024 20:29:24 +0800
Subject: [PATCH 1/2] [Clang] Instantiate local constexpr functions eagerly

---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/lib/Sema/SemaExpr.cpp   |  3 ++-
 .../SemaTemplate/instantiate-local-class.cpp  | 24 +++
 3 files changed, 27 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8c2f737836a9d..a424554ed821d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -847,6 +847,7 @@ Bug Fixes to C++ Support
 - Fixed several bugs in capturing variables within unevaluated contexts. 
(#GH63845), (#GH67260), (#GH69307),
   (#GH88081), (#GH89496), (#GH90669) and (#GH91633).
 - Fixed handling of brace ellison when building deduction guides. (#GH64625), 
(#GH83368).
+- Clang now instantiates local constexpr functions eagerly for constant 
evaluators. (#GH35052), (#GH94849)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 99a8704298314..88e9b2b00f84d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18112,7 +18112,8 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
 
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
 Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
+  if (!Func->isConstexpr() &&
+  isa(Func->getDeclContext()) &&
   cast(Func->getDeclContext())->isLocalClass() &&
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
diff --git a/clang/test/SemaTemplate/instantiate-local-class.cpp 
b/clang/test/SemaTemplate/instantiate-local-class.cpp
index 47591045fd26e..7eee131e28d60 100644
--- a/clang/test/SemaTemplate/instantiate-local-class.cpp
+++ b/clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -verify -std=c++11 %s
 // RUN: %clang_cc1 -verify -std=c++11 -fdelayed-template-parsing %s
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
 
 template
 void f0() {
@@ -509,3 +510,26 @@ namespace LambdaInDefaultMemberInitializer {
   }
   template void f();
 }
+
+#if __cplusplus >= 201703L
+namespace GH35052 {
+
+template  constexpr int func(F f) {
+  if constexpr (f(1UL)) {
+return 1;
+  }
+  return 0;
+}
+
+int main() {
+  auto predicate = [](auto v) /*implicit constexpr*/ -> bool {
+return v == 1;
+  };
+
+  static_assert(predicate(1));
+  return func(predicate);
+}
+
+} // namespace GH35052
+
+#endif

>From cd7ef4f9680f2d43576a6710f448955cca6f800c Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 16 Jun 2024 20:56:54 +0800
Subject: [PATCH 2/2] Address feedback

---
 clang/lib/Sema/SemaExpr.cpp | 14 +++---
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 88e9b2b00f84d..4db8b4130c3c7 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18112,17 +18112,17 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
 
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
 Func->isConstexpr()) {
-  if (!Func->isConstexpr() &&
-  isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
-  CodeSynthesisContexts.size())
-PendingLocalImplicitInstantiations.push_back(
-std::make_pair(Func, PointOfInstantiation));
-  else if (Func->isConstexpr())
+  if (Func->isConstexpr())
 // Do not defer instantiations of constexpr functions, to avoid the
 // expression evaluator needing to call back into Sema if it sees a
 // call to such a function.
 InstantiateFunctionDefinition(PointOfInstantiation, Func);
+  else if (isa(Func->getDeclContext()) &&
+   cast(Func->getDeclContext())
+   ->isLocalClass() &&
+   CodeSynthesisContexts.size())
+PendingLocalImplicitInstantiations.push_back(
+std::make_pair(Func, PointOfInstantiation));
   else {
 Func->setInstantiationIsPending(true);
 PendingInstantiations.push_back(

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


[clang] [Clang] Instantiate local constexpr functions eagerly (PR #95660)

2024-06-16 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Thanks for the review! I will commit when CI turns green.

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread via cfe-commits

https://github.com/sstwcw created 
https://github.com/llvm/llvm-project/pull/95703

I made a mistake when I tried to make the code handle the backtick character 
like the hash character.  The code did not recognize the delay control 
structure.  It caused net names in the declaration to be aligned to the type 
name instead of the first net name.

new

```Verilog
wire logic #0 mynet, //
  mynet1;
```

old

```Verilog
wire logic #0 mynet, //
 mynet1;
```

>From 5982cfd24a59e165795ff8528901e31f80798074 Mon Sep 17 00:00:00 2001
From: sstwcw 
Date: Sun, 16 Jun 2024 13:04:27 +
Subject: [PATCH] [clang-format] Handle Verilog delay control

I made a mistake when I tried to make the code handle the backtick
character like the hash character.  The code did not recognize the delay
control structure.  It caused net names in the declaration to be aligned
to the type name instead of the first net name.

new

```Verilog
wire logic #0 mynet, //
  mynet1;
```

old

```Verilog
wire logic #0 mynet, //
 mynet1;
```
---
 clang/lib/Format/TokenAnnotator.cpp  | 3 ++-
 clang/unittests/Format/FormatTestVerilog.cpp | 9 +
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..82c101a24a998 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3410,7 +3410,8 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
+  } else if (Tok->is(Keywords.kw_verilogHash)) {
+// Delay control.
 if (Next->is(tok::l_paren))
   Next = Next->MatchingParen;
 if (Next)
diff --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index b5241a4e0d6ae..fbaf289fbc4d6 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -391,6 +391,15 @@ TEST_F(FormatTestVerilog, Declaration) {
   verifyFormat("wire mynet, mynet1;");
   verifyFormat("wire mynet, //\n"
" mynet1;");
+  verifyFormat("wire #0 mynet, mynet1;");
+  verifyFormat("wire logic #0 mynet, mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, mynet1;");
+  verifyFormat("wire #0 mynet, //\n"
+   "mynet1;");
+  verifyFormat("wire logic #0 mynet, //\n"
+   "  mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, //\n"
+   "mynet1;");
   verifyFormat("wire mynet = enable;");
   verifyFormat("wire mynet = enable, mynet1;");
   verifyFormat("wire mynet = enable, //\n"

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: None (sstwcw)


Changes

I made a mistake when I tried to make the code handle the backtick character 
like the hash character.  The code did not recognize the delay control 
structure.  It caused net names in the declaration to be aligned to the type 
name instead of the first net name.

new

```Verilog
wire logic #0 mynet, //
  mynet1;
```

old

```Verilog
wire logic #0 mynet, //
 mynet1;
```

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+2-1) 
- (modified) clang/unittests/Format/FormatTestVerilog.cpp (+9) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..82c101a24a998 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3410,7 +3410,8 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
+  } else if (Tok->is(Keywords.kw_verilogHash)) {
+// Delay control.
 if (Next->is(tok::l_paren))
   Next = Next->MatchingParen;
 if (Next)
diff --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index b5241a4e0d6ae..fbaf289fbc4d6 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -391,6 +391,15 @@ TEST_F(FormatTestVerilog, Declaration) {
   verifyFormat("wire mynet, mynet1;");
   verifyFormat("wire mynet, //\n"
" mynet1;");
+  verifyFormat("wire #0 mynet, mynet1;");
+  verifyFormat("wire logic #0 mynet, mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, mynet1;");
+  verifyFormat("wire #0 mynet, //\n"
+   "mynet1;");
+  verifyFormat("wire logic #0 mynet, //\n"
+   "  mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, //\n"
+   "mynet1;");
   verifyFormat("wire mynet = enable;");
   verifyFormat("wire mynet = enable, mynet1;");
   verifyFormat("wire mynet = enable, //\n"

``




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


[clang] [Clang] Instantiate local constexpr functions eagerly (PR #95660)

2024-06-16 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Linux CI failed with an unrelated error.
```
TIMEOUT: lldb-api :: 
functionalities/fork/concurrent_vfork/TestConcurrentVFork.py (87750 of 87750)
  |  TEST 'lldb-api :: 
functionalities/fork/concurrent_vfork/TestConcurrentVFork.py' FAILED 

```

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


[clang] 5548ea3 - [Clang] Instantiate local constexpr functions eagerly (#95660)

2024-06-16 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-06-16T21:54:19+08:00
New Revision: 5548ea34341e9d0ae645719c34b466ca3b9eaa5a

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

LOG: [Clang] Instantiate local constexpr functions eagerly (#95660)

We had a code path in `Sema::MarkFunctionReferenced()` that deferred
local lambda instantiation even for constexprs. This resulted in any
calls to them referring to function decls that lack bodies and hence
failures at constant evaluation.

The issue doesn't occur when the lambda has no explicit return type
because the return type deduction requires instantiation.

Fixes https://github.com/llvm/llvm-project/issues/35052
Fixes https://github.com/llvm/llvm-project/issues/94849

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaTemplate/instantiate-local-class.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 36efeb8c70cca..69aea6c21ad39 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -858,6 +858,7 @@ Bug Fixes to C++ Support
 - Fixed several bugs in capturing variables within unevaluated contexts. 
(#GH63845), (#GH67260), (#GH69307),
   (#GH88081), (#GH89496), (#GH90669) and (#GH91633).
 - Fixed handling of brace ellison when building deduction guides. (#GH64625), 
(#GH83368).
+- Clang now instantiates local constexpr functions eagerly for constant 
evaluators. (#GH35052), (#GH94849)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 99a8704298314..4db8b4130c3c7 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18112,16 +18112,17 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
 
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
 Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
-  CodeSynthesisContexts.size())
-PendingLocalImplicitInstantiations.push_back(
-std::make_pair(Func, PointOfInstantiation));
-  else if (Func->isConstexpr())
+  if (Func->isConstexpr())
 // Do not defer instantiations of constexpr functions, to avoid the
 // expression evaluator needing to call back into Sema if it sees a
 // call to such a function.
 InstantiateFunctionDefinition(PointOfInstantiation, Func);
+  else if (isa(Func->getDeclContext()) &&
+   cast(Func->getDeclContext())
+   ->isLocalClass() &&
+   CodeSynthesisContexts.size())
+PendingLocalImplicitInstantiations.push_back(
+std::make_pair(Func, PointOfInstantiation));
   else {
 Func->setInstantiationIsPending(true);
 PendingInstantiations.push_back(

diff  --git a/clang/test/SemaTemplate/instantiate-local-class.cpp 
b/clang/test/SemaTemplate/instantiate-local-class.cpp
index 47591045fd26e..7eee131e28d60 100644
--- a/clang/test/SemaTemplate/instantiate-local-class.cpp
+++ b/clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -verify -std=c++11 %s
 // RUN: %clang_cc1 -verify -std=c++11 -fdelayed-template-parsing %s
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
 
 template
 void f0() {
@@ -509,3 +510,26 @@ namespace LambdaInDefaultMemberInitializer {
   }
   template void f();
 }
+
+#if __cplusplus >= 201703L
+namespace GH35052 {
+
+template  constexpr int func(F f) {
+  if constexpr (f(1UL)) {
+return 1;
+  }
+  return 0;
+}
+
+int main() {
+  auto predicate = [](auto v) /*implicit constexpr*/ -> bool {
+return v == 1;
+  };
+
+  static_assert(predicate(1));
+  return func(predicate);
+}
+
+} // namespace GH35052
+
+#endif



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


[clang] [Clang] Instantiate local constexpr functions eagerly (PR #95660)

2024-06-16 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-16 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/15] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager &SM, SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext &Context;
+  const PrintingPolicy &PP;
+  std::vector &LabelChunks;
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder &Builder;
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder &Builder, QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto &Name = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto &TA = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument &TA) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+Source

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-16 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

@HighCommander4 Sorry for my delay. This is ready for the next round of review, 
and I'm prepared for a lot of feedback!

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/2] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/2] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

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


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

2024-06-16 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

```cpp
ls
bstrwrap.cpp  bstrwrap.h  ctudir  test.cpp  test.plist  test.sh

cat bstrwrap.cpp
#include "bstrwrap.h"
#include 
Bstrlib::CBString::CBString () {
}

cat bstrwrap.h
#include 
namespace Bstrlib {
struct CBString {
 CBString ();
};
extern std::istream& getline (void);
}

cat test.cpp
#include "bstrwrap.h"
int test0 (void) {
 Bstrlib::CBString c0;
 return 0;
}

cat ctudir/externalDefMap.txt 
11:c:@f@test0# test.cpp.ast
35:c:@n@Bstrlib@S@CBString@F@CBString# bstrwrap.cpp.ast

~/llvm-project/build/bin/clang test.cpp -emit-ast -D__clang_analyzer__ -w -o 
ctudir/test.cpp.ast
~/llvm-project/build/bin/clang bstrwrap.cpp -emit-ast -D__clang_analyzer__ -w 
-o ctudir/bstrwrap.cpp.ast
~/llvm-project/build/bin/clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp
```
I have tested locally using main branch with clang and it has no crash. Maybe I 
missed something? Could you please take a second look? @vabridgers 

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff fa9745e8d39498a7090b108dd2717ca0466189e3 
17e1c3561830866592fd3a55e7a296194b221a90 -- clang/lib/Format/TokenAnnotator.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95..4150c59ac5 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ private:
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

``




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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/3] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/3] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

>From 3928b8936f05562312e177443821f452829034db Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:18:49 +0530
Subject: [PATCH 3/3] clang-format

---
 clang/lib/Format/TokenAnnotator.cpp | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95529..4150c59ac5081 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/4] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/4] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

>From 3928b8936f05562312e177443821f452829034db Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:18:49 +0530
Subject: [PATCH 3/4] clang-format

---
 clang/lib/Format/TokenAnnotator.cpp | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95529..4150c59ac5081 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

>From 6f000eb0403847996b3da588f07b4506d4ec7c41 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:20:22 +0530
Subject: [PATCH 4/4] minor change

---
 clang/lib/Format/TokenAnnotator.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 4150c59ac5081..07599b6e1e3e1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3374,7 +3374,6 @@ class ExpressionParser {
 Tok = Next;
 if (Tok)
   Tok = Tok->getNextNonComment();
-  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

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


[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-16 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/16] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager &SM, SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext &Context;
+  const PrintingPolicy &PP;
+  std::vector &LabelChunks;
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder &Builder;
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder &Builder, QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto &Name = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto &TA = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument &TA) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+Source

[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space updated 
https://github.com/llvm/llvm-project/pull/95708

From d75a05030447e8bcb1dd0b575ff5e7aa5c89f0bb Mon Sep 17 00:00:00 2001
From: Andrzej Warzynski 
Date: Sun, 16 Jun 2024 13:58:41 +0100
Subject: [PATCH 1/3] [llvm] Remove the Legacy PM Hello example

The Legacy PM was deprecated for the optimization pipeline in LLVM 14
[1] (the support was removed altogether in the following release). This
patch removes the original Hello example that was introduced to
illustrate the Legacy PM. The Hello example no longer works and hence is
deleted. The corresponding documentation is also removed.

Note, Hello example for new PM is located in
  * llvm/lib/Transforms/Utils/HelloWorld.cpp
and documented in
  * WritingAnLLVMNewPMPass.rst.

[1] 
https://releases.llvm.org/14.0.0/docs/ReleaseNotes.html#changes-to-the-llvm-ir
---
 llvm/lib/Transforms/CMakeLists.txt   |  1 -
 llvm/lib/Transforms/Hello/CMakeLists.txt | 20 
 llvm/lib/Transforms/Hello/Hello.cpp  | 64 
 llvm/lib/Transforms/Hello/Hello.exports  |  0
 4 files changed, 85 deletions(-)
 delete mode 100644 llvm/lib/Transforms/Hello/CMakeLists.txt
 delete mode 100644 llvm/lib/Transforms/Hello/Hello.cpp
 delete mode 100644 llvm/lib/Transforms/Hello/Hello.exports

diff --git a/llvm/lib/Transforms/CMakeLists.txt 
b/llvm/lib/Transforms/CMakeLists.txt
index 84a7e34147d08..7046f2f4b1d2c 100644
--- a/llvm/lib/Transforms/CMakeLists.txt
+++ b/llvm/lib/Transforms/CMakeLists.txt
@@ -5,7 +5,6 @@ add_subdirectory(InstCombine)
 add_subdirectory(Scalar)
 add_subdirectory(IPO)
 add_subdirectory(Vectorize)
-add_subdirectory(Hello)
 add_subdirectory(ObjCARC)
 add_subdirectory(Coroutines)
 add_subdirectory(CFGuard)
diff --git a/llvm/lib/Transforms/Hello/CMakeLists.txt 
b/llvm/lib/Transforms/Hello/CMakeLists.txt
deleted file mode 100644
index 9510c31f633fe..0
--- a/llvm/lib/Transforms/Hello/CMakeLists.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# If we don't need RTTI or EH, there's no reason to export anything
-# from the hello plugin.
-if( NOT LLVM_REQUIRES_RTTI )
-  if( NOT LLVM_REQUIRES_EH )
-set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/Hello.exports)
-  endif()
-endif()
-
-if(WIN32 OR CYGWIN OR ZOS)
-  set(LLVM_LINK_COMPONENTS Core Support)
-endif()
-
-add_llvm_library( LLVMHello MODULE BUILDTREE_ONLY
-  Hello.cpp
-
-  DEPENDS
-  intrinsics_gen
-  PLUGIN_TOOL
-  opt
-  )
diff --git a/llvm/lib/Transforms/Hello/Hello.cpp 
b/llvm/lib/Transforms/Hello/Hello.cpp
deleted file mode 100644
index b0adb5401f891..0
--- a/llvm/lib/Transforms/Hello/Hello.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-//===- Hello.cpp - Example code from "Writing an LLVM Pass" 
---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file implements two versions of the LLVM "Hello World" pass described
-// in docs/WritingAnLLVMPass.html
-//
-//===--===//
-
-#include "llvm/ADT/Statistic.h"
-#include "llvm/IR/Function.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
-
-#define DEBUG_TYPE "hello"
-
-STATISTIC(HelloCounter, "Counts number of functions greeted");
-
-namespace {
-  // Hello - The first implementation, without getAnalysisUsage.
-  struct Hello : public FunctionPass {
-static char ID; // Pass identification, replacement for typeid
-Hello() : FunctionPass(ID) {}
-
-bool runOnFunction(Function &F) override {
-  ++HelloCounter;
-  errs() << "Hello: ";
-  errs().write_escaped(F.getName()) << '\n';
-  return false;
-}
-  };
-}
-
-char Hello::ID = 0;
-static RegisterPass X("hello", "Hello World Pass");
-
-namespace {
-  // Hello2 - The second implementation with getAnalysisUsage implemented.
-  struct Hello2 : public FunctionPass {
-static char ID; // Pass identification, replacement for typeid
-Hello2() : FunctionPass(ID) {}
-
-bool runOnFunction(Function &F) override {
-  ++HelloCounter;
-  errs() << "Hello: ";
-  errs().write_escaped(F.getName()) << '\n';
-  return false;
-}
-
-// We don't modify the program, so we preserve all analyses.
-void getAnalysisUsage(AnalysisUsage &AU) const override {
-  AU.setPreservesAll();
-}
-  };
-}
-
-char Hello2::ID = 0;
-static RegisterPass
-Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");
diff --git a/llvm/lib/Transforms/Hello/Hello.exports 
b/llvm/lib/Transforms/Hello/Hello.exports
deleted file mode 100644
index e69de29bb2d1d..0

From bed0a86befc6f6b88a28a0eec53499e02b8bddad Mon Sep 17 00:00:00 2001
From: Andrzej Warzynski 
Date: Sun, 16 Jun 2024 17:10:37 +0100
Subject: [PATCH 2/3] fixup! [llvm]

[clang] [Clang][AArch64] Generalise streaming mode checks for builtins. (PR #93802)

2024-06-16 Thread Sander de Smalen via cfe-commits

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Tor Shepherd via cfe-commits

https://github.com/torshepherd created 
https://github.com/llvm/llvm-project/pull/95712

Title. This PR adds support for showing implicit lambda captures:

![image](https://github.com/llvm/llvm-project/assets/49597791/d0150817-f71e-4971-8d8b-e25d2b1e8bf8)

and defaulted function arguments:

![image](https://github.com/llvm/llvm-project/assets/49597791/2a6b83a9-b918-4363-be67-d79ce244b067)

as inlay hints.

If the list of captures (or default args) is too long (based on TypeNameLimit), 
shows "..." instead:

![image](https://github.com/llvm/llvm-project/assets/49597791/9bd5ee8c-ed73-44f9-821f-f2b29e612432)

![image](https://github.com/llvm/llvm-project/assets/49597791/c48acd28-091a-4d7d-9344-01e12c622024)

Note: I wrote this before https://github.com/llvm/llvm-project/pull/85497 
landed. With this we should probably also follow up with go-to-definition on 
the lambda captures at least; I could see that being helpful

>From 741921857955983e1bce2ba828ec369568948688 Mon Sep 17 00:00:00 2001
From: Tor Shepherd 
Date: Sun, 16 Jun 2024 10:54:43 -0400
Subject: [PATCH] Add default arguments and lambda captures only

---
 clang-tools-extra/clangd/Config.h |  2 +
 clang-tools-extra/clangd/ConfigCompile.cpp| 19 ++--
 clang-tools-extra/clangd/ConfigFragment.h |  5 ++
 clang-tools-extra/clangd/ConfigYAML.cpp   |  9 +-
 clang-tools-extra/clangd/InlayHints.cpp   | 87 ++-
 clang-tools-extra/clangd/Protocol.cpp |  8 +-
 clang-tools-extra/clangd/Protocol.h   | 33 +--
 .../clangd/unittests/InlayHintTests.cpp   | 66 +-
 8 files changed, 206 insertions(+), 23 deletions(-)

diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 41143b9ebc8d2..5100214244454 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -148,6 +148,8 @@ struct Config {
 bool DeducedTypes = true;
 bool Designators = true;
 bool BlockEnd = false;
+bool LambdaCaptures = false;
+bool DefaultArguments = false;
 // Limit the length of type names in inlay hints. (0 means no limit)
 uint32_t TypeNameLimit = 32;
   } InlayHints;
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index f32f674443ffe..dcdb71ea01bb2 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -43,7 +43,6 @@
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/SMLoc.h"
 #include "llvm/Support/SourceMgr.h"
-#include 
 #include 
 #include 
 #include 
@@ -504,10 +503,10 @@ struct FragmentCompiler {
   auto Fast = isFastTidyCheck(Str);
   if (!Fast.has_value()) {
 diag(Warning,
- llvm::formatv(
- "Latency of clang-tidy check '{0}' is not known. "
- "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
- Str)
+ llvm::formatv("Latency of clang-tidy check '{0}' is not known. "
+   "It will only run if ClangTidy.FastCheckFilter is "
+   "Loose or None",
+   Str)
  .str(),
  Arg.Range);
   } else if (!*Fast) {
@@ -654,6 +653,16 @@ struct FragmentCompiler {
   Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config &C) {
 C.InlayHints.BlockEnd = Value;
   });
+if (F.LambdaCaptures)
+  Out.Apply.push_back(
+  [Value(**F.LambdaCaptures)](const Params &, Config &C) {
+C.InlayHints.LambdaCaptures = Value;
+  });
+if (F.DefaultArguments)
+  Out.Apply.push_back(
+  [Value(**F.DefaultArguments)](const Params &, Config &C) {
+C.InlayHints.DefaultArguments = Value;
+  });
 if (F.TypeNameLimit)
   Out.Apply.push_back(
   [Value(**F.TypeNameLimit)](const Params &, Config &C) {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index f3e51a9b6dbc4..ad30b43f34874 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -331,6 +331,11 @@ struct Fragment {
 std::optional> Designators;
 /// Show defined symbol names at the end of a definition block.
 std::optional> BlockEnd;
+/// Show names of captured variables by default capture groups in lambdas.
+std::optional> LambdaCaptures;
+/// Show parameter names and default values of default arguments after all
+/// of the explicit arguments.
+std::optional> DefaultArguments;
 /// Limit the length of type name hints. (0 means no limit)
 std::optional> TypeNameLimit;
   };
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 3e9b6a07d3b32..58e5f8bead101 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -14,7 +14,6 @@
 #include "llvm/Support/YAML

[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Tor Shepherd (torshepherd)


Changes

Title. This PR adds support for showing implicit lambda captures:

![image](https://github.com/llvm/llvm-project/assets/49597791/d0150817-f71e-4971-8d8b-e25d2b1e8bf8)

and defaulted function arguments:

![image](https://github.com/llvm/llvm-project/assets/49597791/2a6b83a9-b918-4363-be67-d79ce244b067)

as inlay hints.

If the list of captures (or default args) is too long (based on TypeNameLimit), 
shows "..." instead:

![image](https://github.com/llvm/llvm-project/assets/49597791/9bd5ee8c-ed73-44f9-821f-f2b29e612432)

![image](https://github.com/llvm/llvm-project/assets/49597791/c48acd28-091a-4d7d-9344-01e12c622024)

Note: I wrote this before https://github.com/llvm/llvm-project/pull/85497 
landed. With this we should probably also follow up with go-to-definition on 
the lambda captures at least; I could see that being helpful

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


8 Files Affected:

- (modified) clang-tools-extra/clangd/Config.h (+2) 
- (modified) clang-tools-extra/clangd/ConfigCompile.cpp (+14-5) 
- (modified) clang-tools-extra/clangd/ConfigFragment.h (+5) 
- (modified) clang-tools-extra/clangd/ConfigYAML.cpp (+8-1) 
- (modified) clang-tools-extra/clangd/InlayHints.cpp (+84-3) 
- (modified) clang-tools-extra/clangd/Protocol.cpp (+7-1) 
- (modified) clang-tools-extra/clangd/Protocol.h (+24-9) 
- (modified) clang-tools-extra/clangd/unittests/InlayHintTests.cpp (+62-4) 


``diff
diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 41143b9ebc8d2..5100214244454 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -148,6 +148,8 @@ struct Config {
 bool DeducedTypes = true;
 bool Designators = true;
 bool BlockEnd = false;
+bool LambdaCaptures = false;
+bool DefaultArguments = false;
 // Limit the length of type names in inlay hints. (0 means no limit)
 uint32_t TypeNameLimit = 32;
   } InlayHints;
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index f32f674443ffe..dcdb71ea01bb2 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -43,7 +43,6 @@
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/SMLoc.h"
 #include "llvm/Support/SourceMgr.h"
-#include 
 #include 
 #include 
 #include 
@@ -504,10 +503,10 @@ struct FragmentCompiler {
   auto Fast = isFastTidyCheck(Str);
   if (!Fast.has_value()) {
 diag(Warning,
- llvm::formatv(
- "Latency of clang-tidy check '{0}' is not known. "
- "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
- Str)
+ llvm::formatv("Latency of clang-tidy check '{0}' is not known. "
+   "It will only run if ClangTidy.FastCheckFilter is "
+   "Loose or None",
+   Str)
  .str(),
  Arg.Range);
   } else if (!*Fast) {
@@ -654,6 +653,16 @@ struct FragmentCompiler {
   Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config &C) {
 C.InlayHints.BlockEnd = Value;
   });
+if (F.LambdaCaptures)
+  Out.Apply.push_back(
+  [Value(**F.LambdaCaptures)](const Params &, Config &C) {
+C.InlayHints.LambdaCaptures = Value;
+  });
+if (F.DefaultArguments)
+  Out.Apply.push_back(
+  [Value(**F.DefaultArguments)](const Params &, Config &C) {
+C.InlayHints.DefaultArguments = Value;
+  });
 if (F.TypeNameLimit)
   Out.Apply.push_back(
   [Value(**F.TypeNameLimit)](const Params &, Config &C) {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index f3e51a9b6dbc4..ad30b43f34874 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -331,6 +331,11 @@ struct Fragment {
 std::optional> Designators;
 /// Show defined symbol names at the end of a definition block.
 std::optional> BlockEnd;
+/// Show names of captured variables by default capture groups in lambdas.
+std::optional> LambdaCaptures;
+/// Show parameter names and default values of default arguments after all
+/// of the explicit arguments.
+std::optional> DefaultArguments;
 /// Limit the length of type name hints. (0 means no limit)
 std::optional> TypeNameLimit;
   };
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 3e9b6a07d3b32..58e5f8bead101 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -14,7 +14,6 @@
 #include "llvm/Support/YAMLParser.h"
 #include 
 #include 
-#include 
 
 namespace clang {
 namespace clangd {
@@ -264,6 +263,14 @@ class 

[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

> You also need to remove the use of this pass (for testing purposes) from 
> clang-tools-extra.

Done, thanks!

I don't understand why CI still fails:
```bash
Total Discovered Tests: 60135
--
  | Skipped  :15 (0.02%)
  | Unsupported  :  1005 (1.67%)
  | Passed   : 58946 (98.02%)
  | Expectedly Failed:   169 (0.28%)
  | ninja: build stopped: cannot make progress due to previous errors.
  | + show-stats
  | + mkdir -p artifacts
  | + ccache --print-stats
  | 🚨 Error: The command exited with status 1
```

Can you see the actual failure? Looks like all tests passed, right?

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


[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> > You also need to remove the use of this pass (for testing purposes) from 
> > clang-tools-extra.
> 
> Done, thanks!
> 
> I don't understand why CI still fails:
> 
> ```shell
> Total Discovered Tests: 60135
> --
>   | Skipped  :15 (0.02%)
>   | Unsupported  :  1005 (1.67%)
>   | Passed   : 58946 (98.02%)
>   | Expectedly Failed:   169 (0.28%)
>   | ninja: build stopped: cannot make progress due to previous errors.
>   | + show-stats
>   | + mkdir -p artifacts
>   | + ccache --print-stats
>   | 🚨 Error: The command exited with status 1
> ```
> 
> Can you see the actual failure? Looks like all tests passed, right?

It is caused by libc/lldb test failures. Don't worry :)


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


[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta created 
https://github.com/llvm/llvm-project/pull/95715

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= Range.getEnd()' 
to the left and to the right of the '||' operator. HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' to 
the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left and 
to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '&&' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod->isStatic()' to the left 
and to the right of the '&&' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'&&' operator: !BFI &&!BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI->isConditional()' to the left and 
to the right of the '&&' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

>From f80cc3b6ee218e954d68e867637c38211f344d83 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 23:39:47 +0530
Subject: [PATCH] [clang][lldb][mlir] Fix some identical sub-expressions
 warnings (NFC)

This is actually reported in 
https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of 
the '!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of 
the '<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical 

[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Shivam Gupta (xgupta)


Changes

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '&&' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod->isStatic()' to the 
left and to the right of the '&&' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'&&' operator: !BFI &&!BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI->isConditional()' to the left 
and to the right of the '&&' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/ASTUtils.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+3-4) 
- (modified) clang/lib/Sema/SemaCast.cpp (+1-2) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/JumpThreading.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (+1-1) 
- (modified) mlir/lib/Analysis/Presburger/Simplex.cpp (+2-1) 
- (modified) mlir/lib/Interfaces/ValueBoundsOpInterface.cpp (+6-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
index fd5dadc9b01db..0cdc7d08abc99 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
@@ -96,7 +96,7 @@ bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt 
*SecondStmt,
   if (FirstStmt == SecondStmt)
 return true;
 
-  if (FirstStmt->getStmtClass() != FirstStmt->getStmtClass())
+  if (FirstStmt->getStmtClass() != SecondStmt->getStmtClass())
 return false;
 
   if (isa(FirstStmt) && isa(SecondStmt)) {
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a36cb41a63dfb..323f9698dc2aa 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -430,11 +430,10 @@ class HTMLLogger : public Logger {
   AST.getSourceManager(), AST.getLangOpts());
   if (EltRange.isInvalid())
 continue;
-  if (EltRange.getBegin() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd() ||
-  EltRange.getEnd() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd())
+  if (EltRange.getEnd() <= Range.getBegin() ||
+  EltRange.getBegin() >= Range.getEnd())
 continue;
+
   unsigned Off = EltRange.getBegin().getRawEncoding() -
  Range.getBegin().getRawEncoding();

[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-clang

Author: Shivam Gupta (xgupta)


Changes

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '&&' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod->isStatic()' to the 
left and to the right of the '&&' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'&&' operator: !BFI &&!BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI->isConditional()' to the left 
and to the right of the '&&' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/ASTUtils.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+3-4) 
- (modified) clang/lib/Sema/SemaCast.cpp (+1-2) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/JumpThreading.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (+1-1) 
- (modified) mlir/lib/Analysis/Presburger/Simplex.cpp (+2-1) 
- (modified) mlir/lib/Interfaces/ValueBoundsOpInterface.cpp (+6-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
index fd5dadc9b01db..0cdc7d08abc99 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
@@ -96,7 +96,7 @@ bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt 
*SecondStmt,
   if (FirstStmt == SecondStmt)
 return true;
 
-  if (FirstStmt->getStmtClass() != FirstStmt->getStmtClass())
+  if (FirstStmt->getStmtClass() != SecondStmt->getStmtClass())
 return false;
 
   if (isa(FirstStmt) && isa(SecondStmt)) {
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a36cb41a63dfb..323f9698dc2aa 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -430,11 +430,10 @@ class HTMLLogger : public Logger {
   AST.getSourceManager(), AST.getLangOpts());
   if (EltRange.isInvalid())
 continue;
-  if (EltRange.getBegin() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd() ||
-  EltRange.getEnd() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd())
+  if (EltRange.getEnd() <= Range.getBegin() ||
+  EltRange.getBegin() >= Range.getEnd())
 continue;
+
   unsigned Off = EltRange.getBegin().getRawEncoding() -
  Range.getBegin().getR

[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

I think @sstwcw fixes this in #95703

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread Björn Schäpers via cfe-commits

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


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


[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

xgupta wrote:

> I think @sstwcw fixes this in #95703

Oh nice then, I will close this PR.

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


[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok created 
https://github.com/llvm/llvm-project/pull/95718

Used to implement CWG2191 where `typeid` for a polymorphic glvalue only becomes 
potentially-throwing if the `typeid` operand was already potentially throwing 
or a `nullptr` check was inserted: 
https://cplusplus.github.io/CWG/issues/2191.html

Also change `Expr::hasSideEffects` for `CXXTypeidExpr` to check the operand for 
side-effects instead of always reporting that there are side-effects

Remove `IsDeref` parameter of `CGCXXABI::shouldTypeidBeNullChecked` because it 
should never return `true` if `!IsDeref` (we shouldn't add a null check that 
wasn't there in the first place)

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  ret

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang

Author: Mital Ashok (MitalAshok)


Changes

Used to implement CWG2191 where `typeid` for a polymorphic glvalue only becomes 
potentially-throwing if the `typeid` operand was already potentially throwing 
or a `nullptr` check was inserted: 
https://cplusplus.github.io/CWG/issues/2191.html

Also change `Expr::hasSideEffects` for `CXXTypeidExpr` to check the operand for 
side-effects instead of always reporting that there are side-effects

Remove `IsDeref` parameter of `CGCXXABI::shouldTypeidBeNullChecked` because it 
should never return `true` if `!IsDeref` (we shouldn't add a null check that 
wasn't there in the first place)

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


11 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/AST/ExprCXX.h (+4) 
- (modified) clang/lib/AST/Expr.cpp (+12-4) 
- (modified) clang/lib/AST/ExprCXX.cpp (+49) 
- (modified) clang/lib/CodeGen/CGCXXABI.h (+1-2) 
- (modified) clang/lib/CodeGen/CGExprCXX.cpp (+9-44) 
- (modified) clang/lib/CodeGen/ItaniumCXXABI.cpp (+3-4) 
- (modified) clang/lib/CodeGen/MicrosoftCXXABI.cpp (+3-5) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+5-15) 
- (modified) clang/test/CXX/drs/cwg21xx.cpp (+13) 
- (modified) clang/test/SemaCXX/warn-unused-value.cpp (+8) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/5] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine &Line) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken &RootToken) {
+  int getIndentOffset(const AnnotatedLine &Line) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, &RootToken]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken &RootToken) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.In

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

You need to run `clang/www/make_cxx_dr_status` script.

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95503)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread Owen Pan via cfe-commits

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


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


[clang] a106131 - [clang-format] Handle AttributeMacro before access modifiers (#95634)

2024-06-16 Thread via cfe-commits

Author: Owen Pan
Date: 2024-06-16T13:50:59-07:00
New Revision: a106131a34ed87f597c78183ada56f01fd17641d

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

LOG: [clang-format] Handle AttributeMacro before access modifiers (#95634)

Closes #95094.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/TokenAnnotator.h
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..1332445070314 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1419,6 +1419,8 @@ class AnnotatingParser {
 Tok->setType(TT_CtorInitializerColon);
 } else {
   Tok->setType(TT_InheritanceColon);
+  if (Prev->isOneOf(tok::kw_public, tok::kw_private, 
tok::kw_protected))
+Line.Type = LT_AccessModifier;
 }
   } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
@@ -1998,6 +2000,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (Line.Type == LT_AccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)

diff  --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..f4f2bba0eb217 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,8 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  // Contains public/private/protected followed by TT_InheritanceColon.
+  LT_AccessModifier,
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
@@ -45,7 +47,7 @@ enum ScopeType {
 class AnnotatedLine {
 public:
   AnnotatedLine(const UnwrappedLine &Line)
-  : First(Line.Tokens.front().Tok), Level(Line.Level),
+  : First(Line.Tokens.front().Tok), Type(LT_Other), Level(Line.Level),
 PPLevel(Line.PPLevel),
 MatchingOpeningBlockLineIndex(Line.MatchingOpeningBlockLineIndex),
 MatchingClosingBlockLineIndex(Line.MatchingClosingBlockLineIndex),

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine &Line) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken &RootToken) {
+  int getIndentOffset(const AnnotatedLine &Line) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, &RootToken]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken &RootToken) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  re

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH 1/3] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, parentheses and other such constru

[clang] fe9aef0 - [clang-format] Add DiagHandler parameter to format::getStyle() (#91317)

2024-06-16 Thread via cfe-commits

Author: pointhex
Date: 2024-06-16T13:58:26-07:00
New Revision: fe9aef05c2dcfbde6e29e2edb2d49e29a54bea4d

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

LOG: [clang-format] Add DiagHandler parameter to format::getStyle() (#91317)

It allows to control of error output for the function.

Closes #94205.

-

Co-authored-by: Owen Pan 

Added: 


Modified: 
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index f9299ce89a624..7d257be10af42 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5387,10 +5387,11 @@ extern const char *DefaultFallbackStyle;
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyle, StringRef Code = "",
-   llvm::vfs::FileSystem *FS = nullptr,
-   bool AllowUnknownOptions = false);
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c015e03fa15e7..cd21fbb2221ac 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3946,20 +3946,24 @@ const char *DefaultFallbackStyle = "LLVM";
 
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
-   FormatStyle *Style, bool AllowUnknownOptions) {
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   llvm::ErrorOr> Text =
   FS->getBufferForFile(ConfigFile.str());
   if (auto EC = Text.getError())
 return EC;
-  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+   DiagHandler)) {
 return EC;
+  }
   return Text;
 }
 
 Expected getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyleName, StringRef Code,
llvm::vfs::FileSystem *FS,
-   bool AllowUnknownOptions) {
+   bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
@@ -3972,7 +3976,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 StringRef Source = "";
 if (std::error_code ec =
 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), 
&Style,
-   AllowUnknownOptions)) {
+   AllowUnknownOptions, DiagHandler)) {
   return make_string_error("Error parsing -style: " + ec.message());
 }
 
@@ -3992,7 +3996,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   StyleName.starts_with_insensitive("file:")) {
 auto ConfigFile = StyleName.substr(5);
 llvm::ErrorOr> Text =
-loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
+loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
+   DiagHandler);
 if (auto EC = Text.getError()) {
   return make_string_error("Error reading " + ConfigFile + ": " +
EC.message());
@@ -4031,8 +4036,9 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
-  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+  auto EC =
+  parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+ DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
@@ -4066,7 +4072,8 @@ Expected getStyle(St

[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



@pointhex Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits

https://github.com/huixie90 updated 
https://github.com/llvm/llvm-project/pull/75371

>From cb64639669286e5f48421ae8f569208e1e9717be Mon Sep 17 00:00:00 2001
From: zoecarver 
Date: Sat, 2 Dec 2023 20:00:30 +
Subject: [PATCH 1/2] [Builtin] Add __builtin_clear_padding

Adds `__builtin_clear_padding` to zero all padding bits of a struct. This 
builtin should match the behavior of those in NVCC and GCC (and MSVC?). There 
are some tests in this patch but hopefully we'll also get tests from other 
compilers (so all builtins can be as similar as possible).

I'm planning to add support for unions, bitfields (both as members and members 
of sub-objects), and booleans as follow up patches.

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

overlapping subobjects + opague pointer

union, rename, scalar types
---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   | 207 +
 clang/lib/Sema/SemaChecking.cpp   |  31 +
 .../builtin-clear-padding-codegen.cpp | 112 +++
 clang/test/SemaCXX/builtin-clear-padding.cpp  |  15 +
 .../atomics/builtin_clear_padding.pass.cpp| 807 ++
 6 files changed, 1178 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/builtin-clear-padding-codegen.cpp
 create mode 100644 clang/test/SemaCXX/builtin-clear-padding.cpp
 create mode 100644 libcxx/test/libcxx/atomics/builtin_clear_padding.pass.cpp

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 11982af3fa609..44a239e50d5d8 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -932,6 +932,12 @@ def IsConstantEvaluated : LangBuiltin<"CXX_LANG"> {
   let Prototype = "bool()";
 }
 
+def ClearPadding : LangBuiltin<"CXX_LANG"> {
+  let Spellings = ["__builtin_clear_padding"];
+  let Attributes = [NoThrow];
+  let Prototype = "void(...)";
+}
+
 // GCC exception builtins
 def EHReturn : Builtin {
   let Spellings = ["__builtin_eh_return"];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index c16b69ba87567..e1d8135933bb3 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -63,6 +63,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/X86TargetParser.h"
+#include 
 #include 
 #include 
 
@@ -2538,6 +2539,205 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType Ty,
+ size_t CurrentStartOffset,
+ size_t &RunningOffset, T &&WriteZeroAtOffset,
+ bool VisitVirtualBase);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty,
+StructType *ST, size_t CurrentStartOffset,
+size_t &RunningOffset, T &&WriteZeroAtOffset,
+bool VisitVirtualBase) {
+  llvm::dbgs() << "clear padding struct: " << ST->getName().data() << '\n';
+  const auto &DL = CGF.CGM.getModule().getDataLayout();
+  auto *SL = DL.getStructLayout(ST);
+  auto *R = dyn_cast(Ty->getAsRecordDecl());
+  if (!R) {
+llvm::dbgs() << "Not a CXXRecordDecl\n";
+return;
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  if (ASTLayout.hasOwnVFPtr()) {
+llvm::dbgs() << "vtable ptr. Incrementing RunningOffset from "
+ << RunningOffset << " to "
+ << RunningOffset + DL.getPointerSizeInBits() / 8 << '\n';
+RunningOffset += DL.getPointerSizeInBits() / 8;
+  }
+  std::vector> Bases;
+  Bases.reserve(R->getNumBases());
+  // todo get vbases
+  for (auto Base : R->bases()) {
+auto *BaseRecord = cast(Base.getType()->getAsRecordDecl());
+if (!Base.isVirtual()) {
+  auto Offset = static_cast(
+  ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+  Bases.emplace_back(Offset, Base);
+}
+  }
+
+  auto VisitBases =
+  [&](std::vector> &BasesToVisit) {
+std::sort(
+BasesToVisit.begin(), BasesToVisit.end(),
+[](const auto &P1, const auto &P2) { return P1.first < P2.first; 
});
+for (const auto &Pair : BasesToVisit) {
+  // is it OK to use structured binding in clang? what is the language
+  // version?
+  auto Offset = Pair.first;
+  auto Base = Pair.second;
+
+  llvm::dbgs() << "visiting base at offset " << Offset << '\n';
+  // Recursively zero out base classes.
+  auto Index = SL->getElementContainingOffset(Offset);
+  Value *Idx = CGF.Builder.getSize(Index);
+  llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+  Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, 

[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t &RunningOffset, T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t &RunningOffset, T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {

huixie90 wrote:

anyway. I changed the approach now.the new approach should work regardless of 
the orders

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t &RunningOffset, T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t &RunningOffset, T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);

huixie90 wrote:

I removed all the code using LLVM layouts

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t &RunningOffset, T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t &RunningOffset, T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);

huixie90 wrote:

It is almost working now. I managed to get all the Padding in bits now. the 
remaining thing is to zeroing them out, instead of current generating store 
instruction with zeros, i need to basically do this for the bits that don't 
occupy the entire byte
```
byte &= ~PaddingBitMask
```
How can I generate that IR ?

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t &RunningOffset, T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t &RunningOffset, T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentFieldType = 
CGF.ConvertTypeForMem(CurrentField->getType());
+Value *Element = CGF.Builder.CreateGEP(CurrentFieldType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, Element, CurrentField->getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+}
+
+template 
+void ClearPaddingConstantArray(CodeGenFunction &CGF, Value *Ptr, llvm::Type 
*Type, ConstantArrayType const *AT, 
+   size_t CurrentStartOffset, size_t 
&RunningOffset, T&& WriteZeroAtOffset) {
+  for (size_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
+   ++ArrIndex) {
+
+QualType ElementQualType = AT->getElementType();
+
+auto *ElementRecord = ElementQualType->getAsRecordDecl();
+if(!ElementRecord){
+  std::cerr<< "\n\n null!" << std::endl;
+}
+auto ElementAlign =ElementRecord?
+CGF.getContext().getASTRecordLayout(ElementRecord).getAlignment():

huixie90 wrote:

removed

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t &RunningOffset, T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t &RunningOffset, T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentFieldType = 
CGF.ConvertTypeForMem(CurrentField->getType());
+Value *Element = CGF.Builder.CreateGEP(CurrentFieldType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, Element, CurrentField->getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+}
+
+template 
+void ClearPaddingConstantArray(CodeGenFunction &CGF, Value *Ptr, llvm::Type 
*Type, ConstantArrayType const *AT, 
+   size_t CurrentStartOffset, size_t 
&RunningOffset, T&& WriteZeroAtOffset) {
+  for (size_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
+   ++ArrIndex) {
+
+QualType ElementQualType = AT->getElementType();
+
+auto *ElementRecord = ElementQualType->getAsRecordDecl();
+if(!ElementRecord){
+  std::cerr<< "\n\n null!" << std::endl;
+}
+auto ElementAlign =ElementRecord?
+CGF.getContext().getASTRecordLayout(ElementRecord).getAlignment():
+CGF.getContext().getTypeAlignInChars(ElementQualType);
+
+  std::cerr<< "\n\n align: " << ElementAlign.getQuantity() << std::endl;
+
+// Value *Idx = CGF.Builder.getSize(0);
+// Value *ArrayElement = CGF.Builder.CreateGEP(ElementType, Ptr, Idx);
+
+Address FieldElementAddr{Ptr, Type, ElementAlign};
+
+auto Element =
+CGF.Builder.CreateConstArrayGEP(FieldElementAddr, ArrIndex);
+auto *ElementType = CGF.ConvertTypeForMem(ElementQualType);
+auto AllocSize = 
CGF.CGM.getModule().getDataLayout().getTypeAllocSize(ElementType);
+std::cerr << "\n\n clearing array index! " << ArrIndex << std::endl;
+RecursivelyClearPaddingImpl(CGF, Element.getPointer(), ElementQualType, 
CurrentStartOffset + ArrIndex * AllocSize.getKnownMinValue(), RunningOffset, 
WriteZeroAtOffset);
+  }
+}
+
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, 
+ size_t& RunningOffset, T&& WriteZeroAtOffset) 
{
+
+  std::cerr << "\n\n  zero padding before current  ["<< RunningOffset << ", " 
<< CurrentStartOffset<< ")"<< std::endl;
+  for (; RunningOffset < CurrentStartOffset; ++RunningOffset) {
+WriteZeroAtOffset(RunningOffset);
+  }
+  auto Type = CGF.ConvertTypeForMem(Ty);
+  auto Size = CGF.CGM.getModule()
+.getDataLayout()
+.getTypeSizeInBits(Type)
+.getKnownMinValue() / 8;
+
+  if (auto *AT = dyn_cast(Ty)) {
+ClearPaddingConstantArray(CGF, Ptr, Type, AT, CurrentStartOffset, 
RunningOffset, WriteZeroAtOffset);
+  }
+  else if (auto *ST = dyn_cast(Type); ST && Ty->isRecordType()) {
+ClearPaddingStruct(CGF, Ptr, Ty, ST, CurrentStartOffset, RunningOffset, 
WriteZeroAtOffset);
+  } else if (Ty->isAtomicType()) {
+RecursivelyClearPaddingImpl(CGF, Ptr, Ty.getAtomicUnqualifiedType(), 
CurrentStartOffset, RunningOffset, WriteZeroAtOffset);
+  } else {
+std::cerr << "\n\n increment running offset from: " << RunningOffset << " 
to "

[clang] d340f62 - [clang][NFC] Update C++ DR issues list

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-06-17T00:22:47+03:00
New Revision: d340f6283a3d242bad190ed9b95baa03e5607639

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

LOG: [clang][NFC] Update C++ DR issues list

Added: 


Modified: 
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index a7b1e652330e4..c00d022b86446 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -15598,7 +15598,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2632.html";>2632
-review
+drafting
 'user-declared' is not defined
 Not resolved
   
@@ -16691,7 +16691,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2814.html";>2814
-review
+tentatively ready
 Alignment requirement of incomplete class type
 Not resolved
   
@@ -17147,7 +17147,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2890.html";>2890
-open
+review
 Defining members of local classes
 Not resolved
   
@@ -17163,27 +17163,27 @@ C++ defect report implementation 
status
 Unclear usual arithmetic conversions
 Not resolved
   
-  
+  
 https://cplusplus.github.io/CWG/issues/2893.html";>2893
-open
+NAD
 Instantiations in discarded if constexpr substatements
-Not resolved
+Unknown
   
   
 https://cplusplus.github.io/CWG/issues/2894.html";>2894
-open
+review
 Functional casts create prvalues of reference type
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2895.html";>2895
-open
+tentatively ready
 Initialization should ignore the destination type's 
cv-qualification
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2896.html";>2896
-open
+review
 Template argument deduction involving exception specifications
 Not resolved
   
@@ -17204,6 +17204,30 @@ C++ defect report implementation 
status
 open
 Bad value representations should cause undefined behavior
 Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2900.html";>2900
+open
+Deduction of non-type template arguments with placeholder types
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2901.html";>2901
+open
+Unclear semantics for near-match aliased access
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2902.html";>2902
+review
+Implicit this transformation outside of permitted 
contexts
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2903.html";>2903
+tentatively ready
+Can we omit the template disambiguator in 
nested-name-specifiers in type-only contexts?
+Not resolved
   
 
 



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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2538,6 +2539,205 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction &CGF, Value *Ptr, QualType Ty,
+ size_t CurrentStartOffset,
+ size_t &RunningOffset, T &&WriteZeroAtOffset,
+ bool VisitVirtualBase);
+
+template 
+void ClearPaddingStruct(CodeGenFunction &CGF, Value *Ptr, QualType Ty,
+StructType *ST, size_t CurrentStartOffset,
+size_t &RunningOffset, T &&WriteZeroAtOffset,
+bool VisitVirtualBase) {
+  llvm::dbgs() << "clear padding struct: " << ST->getName().data() << '\n';
+  const auto &DL = CGF.CGM.getModule().getDataLayout();
+  auto *SL = DL.getStructLayout(ST);
+  auto *R = dyn_cast(Ty->getAsRecordDecl());
+  if (!R) {
+llvm::dbgs() << "Not a CXXRecordDecl\n";
+return;
+  }
+  const ASTRecordLayout &ASTLayout = CGF.getContext().getASTRecordLayout(R);
+  if (ASTLayout.hasOwnVFPtr()) {
+llvm::dbgs() << "vtable ptr. Incrementing RunningOffset from "
+ << RunningOffset << " to "
+ << RunningOffset + DL.getPointerSizeInBits() / 8 << '\n';
+RunningOffset += DL.getPointerSizeInBits() / 8;
+  }
+  std::vector> Bases;
+  Bases.reserve(R->getNumBases());
+  // todo get vbases
+  for (auto Base : R->bases()) {
+auto *BaseRecord = cast(Base.getType()->getAsRecordDecl());
+if (!Base.isVirtual()) {
+  auto Offset = static_cast(

huixie90 wrote:

removed `size_t`

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

If you update the branch, you should be able to get rid of unrelated changes to 
`cxx_dr_status.html`.

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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread via cfe-commits

pointhex wrote:

@owenca  Thanks a lot!

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits

huixie90 wrote:

@efriedma-quic 

I refactored the code which does the following
1. Breadth first search the AST type, fill in "occupied bits intervals"
2. sort and merge the occupied bits interval and work out the "padding" bits 
intervals
3. clear the padding intervals.  current converting to the byte level and write 
zeros byte. todo: need to deal with bits that don't occupy the full byte. need 
to generate instructions like `Byte &= ~PaddingBitMask` . How to generate such 
an IR instruction ?

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH 1/4] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, parentheses and other such constru

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits


@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.

Endilll wrote:

```suggestion
- Clang now considers ``noexcept(typeid(expr))`` more carefully, instead of 
always assuming that ``std::bad_typeid`` can be thrown.
```

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits


@@ -15598,7 +15598,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2632.html";>2632
-review
+drafting

Endilll wrote:

Update you branch with the latest `main` changes, and those unrelated changes 
will go away.

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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

DR test looks good, but wait for more approvals.

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From c3912611dd63f81ea7067a4b26ef5450f6f01f75 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 22:35:38 +0100
Subject: [PATCH] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp | 10 +
 clang/www/cxx_dr_status.html |  2 +-
 12 files changed, 113 insertions(+), 75 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  /

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From c3912611dd63f81ea7067a4b26ef5450f6f01f75 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 22:35:38 +0100
Subject: [PATCH 1/2] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp | 10 +
 clang/www/cxx_dr_status.html |  2 +-
 12 files changed, 113 insertions(+), 75 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(&const_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
&Context) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional

[clang] 527e732 - [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

2024-06-16 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-06-16T14:56:02-07:00
New Revision: 527e7328607ea0a55855e53a59c5030a7d07a554

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

LOG: [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

Added: 


Modified: 
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 2513ab3939595..aded3ed2a6596 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -15,6 +15,7 @@ namespace clang {
 namespace format {
 namespace {
 
+void dropDiagnosticHandler(const llvm::SMDiagnostic &, void *) {}
 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
 
 #define EXPECT_ALL_STYLES_EQUAL(Styles)
\
@@ -1240,7 +1241,8 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   llvm::consumeError(Style4.takeError());
 
   // Test 5: error on invalid yaml on command line
-  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS);
+  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS,
+ /*AllowUnknownOptions=*/false, dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style5);
   llvm::consumeError(Style5.takeError());
 
@@ -1256,11 +1258,13 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   "InvalidKey: 
InvalidValue")));
   ASSERT_TRUE(
   FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int 
i;")));
-  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
+  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS,
+  /*AllowUnknownOptions=*/false, 
dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style7a);
   llvm::consumeError(Style7a.takeError());
 
-  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
+  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS,
+  /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   ASSERT_TRUE((bool)Style7b);
 
   // Test 8: inferred per-language defaults apply.
@@ -1466,8 +1470,7 @@ TEST(ConfigParseTest, GetStyleOutput) {
   // Suppress stderr.
   testing::internal::CaptureStderr();
   Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS,
-   /*AllowUnknownOptions=*/true,
-   [](const llvm::SMDiagnostic &, void *) {});
+   /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   Output = testing::internal::GetCapturedStderr();
   ASSERT_TRUE((bool)Style);
   ASSERT_TRUE(Output.empty());



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


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

2024-06-16 Thread via cfe-commits

vabridgers wrote:

Hi @jcsxky , I fetched and rebased to origin/main just now (6/16/2024 at 4:30pm 
Central US time), and rebuilt - and I see the crash. Did you try rebasing to 
latest source and rebuilding?

`$ clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp`
`CTU loaded AST file: bstrwrap.cpp.ast`
`clang: clang/lib/AST/Decl.cpp:4045: void 
clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*):
 Assertion `TemplateOrSpecialization.isNull() && "Member function is already a 
specialization"' failed.`
`PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.`
`Stack dump:`
`0.  Program arguments: clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp`
`1.   parser at end of file`
`2.  While analyzing stack:`
`#0 Calling test0()`
`3.  test.cpp:3:21: Error evaluating statement`
`4.  test.cpp:3:21: Error evaluating statement`
`  #0 0x0683ef4a llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
llvm/lib/Support/Unix/Signals.inc:723:22`
`  #1 0x0683f384 PrintStackTraceSignalHandler(void*) 
llvm/lib/Support/Unix/Signals.inc:798:1`
`  #2 0x0683cc9d llvm::sys::RunSignalHandlers() 
llvm/lib/Support/Signals.cpp:105:20`
`  #3 0x0683e84b llvm::sys::CleanupOnSignal(unsgned long) 
llvm/lib/Support/Unix/Signals.inc:367:31`
`  #4 0x0677a190 (anonymous 
namespace)::CrashRecoveryContextImpl::HandleCrash(int, unsigned long) 
llvm/lib/Support/CrashRecoveryContext.cpp:73:5`
`  #5 0x0677a623 CrashRecoverySignalHandler(int) 
llvm/lib/Support/CrashRecoveryContext.cpp:391:1`
`  #6 0x7fbb10acd630 __restore_rt sigaction.c:0:0`
`  #7 0x7fbb0f80b387 raise (/lib64/libc.so.6+0x36387)`
`  #8 0x7fbb0f80ca78 abort (/lib64/libc.so.6+0x37a78)`
`  #9 0x7fbb0f8041a6 __assert_fail_base (/lib64/libc.so.6+0x2f1a6)`
` #10 0x7fbb0f804252 (/lib64/libc.so.6+0x2f252)`
` #11 0x0c2b9f73 
clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*) 
clang/lib/AST/Decl.cpp:4045:3`



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


[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

https://github.com/Veeloxfire created 
https://github.com/llvm/llvm-project/pull/95726

For the somewhat easy mistake of `template ...` clang outputs a 
partially cryptic error

This patch changes this to assume the programmer intended `typename` in cases 
where `template` is illegal, and emit diagnostics (and forward parsing) 
accordingly

This mirrors the behaviour of `typedef` handling, so I feel its a reasonable 
qol change

Apologies if I missed any broken tests. Currently my local setup is messed up 
and fails on 100-200 tests eroniously, so I did my best to search through the 
errors and find the ones that needed updating

>From 44620330cd5238de549d3d77ddc447cd3bc51e60 Mon Sep 17 00:00:00 2001
From: Veeloxfire <58116051+veeloxf...@users.noreply.github.com>
Date: Mon, 17 Jun 2024 01:20:32 +0100
Subject: [PATCH] [clang][Parser] "Better" error messages for invalid template
 template

For the somewhat easy mistake of `template ...` clang outputs a 
partially cryptic error
Change this to assume the programmer intended `typename` in cases where 
`template` is illegal, and emit diagnostics (and forward parsing) accordingly
This mirrors the behaviour of `typedef` handling
---
 clang/lib/Parse/ParseTemplate.cpp   | 17 +
 clang/test/CXX/drs/cwg1xx.cpp   |  2 ++
 clang/test/Parser/cxx-template-decl.cpp |  2 +-
 3 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index a5130f56600e5..e5308d9edac5f 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -787,6 +787,23 @@ NamedDecl *Parser::ParseTemplateTemplateParameter(unsigned 
Depth,
   unsigned Position) {
   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
 
+  if (Token ahead = GetLookAheadToken(1);
+  ahead.isOneOf(tok::identifier, tok::ellipsis,
+tok::equal, tok::comma,
+tok::greater, tok::greatergreater, 
tok::greatergreatergreater)) {
+// Maybe they intended `typename` instead of `template` (given thats more 
common)
+// Error early, to add a fixit hint
+
+Diag(ahead.getLocation(), diag::err_expected_less_after) << "template";
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+  << 
FixItHint::CreateReplacement(CharSourceRange::getTokenRange(Tok.getLocation()),
+  "typename");
+
+Tok.setKind(tok::kw_typename);
+return ParseTypeParameter(Depth, Position);
+  }
+
   // Handle the template <...> part.
   SourceLocation TemplateLoc = ConsumeToken();
   SmallVector TemplateParams;
diff --git a/clang/test/CXX/drs/cwg1xx.cpp b/clang/test/CXX/drs/cwg1xx.cpp
index e71ea9278..72b3ff40152d5 100644
--- a/clang/test/CXX/drs/cwg1xx.cpp
+++ b/clang/test/CXX/drs/cwg1xx.cpp
@@ -1145,8 +1145,10 @@ namespace cwg181 { // cwg181: yes
   namespace X {
 template  > struct A { };
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
 template  > void f(A) { }
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
   }
 
   namespace Y {
diff --git a/clang/test/Parser/cxx-template-decl.cpp 
b/clang/test/Parser/cxx-template-decl.cpp
index 734438069b9ae..69b9ab012b478 100644
--- a/clang/test/Parser/cxx-template-decl.cpp
+++ b/clang/test/Parser/cxx-template-decl.cpp
@@ -22,7 +22,7 @@ template> struct x3; // expected-error 
{{expected ',' or '>' in t
  cpp14-error {{template template 
parameter requires 'class' after the parameter list}} \
  cpp17-error {{template template 
parameter requires 'class' or 'typename' after the parameter list}}
 template  struct Err1; // expected-error {{expected '<' after 
'template'}} \
-// expected-error{{extraneous}}
+// expected-note{{did you mean to use 'typename'?}}
 template  > struct Err2;   // cpp14-error {{template 
template parameter requires 'class' after the parameter list}}
 // cpp17-error@-1{{template template parameter requires 'class' or 'typename' 
after the parameter list}}
 template  Foo> struct Err3;// cpp14-error {{template 
template parameter requires 'class' after the parameter list}}

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


[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (Veeloxfire)


Changes

For the somewhat easy mistake of `template