[PATCH] D93829: [clangd] Support outgoing calls in call hierarchy

2023-10-22 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 557830.
nridge added a comment.

Address other review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93829

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/Ref.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/test/type-hierarchy-ext.test
  clang-tools-extra/clangd/test/type-hierarchy.test
  clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1417,6 +1417,12 @@
   return true; // has more references
 }
 
+bool containedRefs(const ContainedRefsRequest &Req,
+   llvm::function_ref
+   Callback) const override {
+  return false;
+}
+
 bool fuzzyFind(
 const FuzzyFindRequest &Req,
 llvm::function_ref Callback) const override {
@@ -1468,6 +1474,12 @@
   return false;
 }
 
+bool containedRefs(const ContainedRefsRequest &Req,
+   llvm::function_ref
+   Callback) const override {
+  return false;
+}
+
 bool fuzzyFind(const FuzzyFindRequest &,
llvm::function_ref) const override {
   return false;
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1644,6 +1644,12 @@
 return false;
   }
 
+  bool containedRefs(
+  const ContainedRefsRequest &,
+  llvm::function_ref) const override {
+return false;
+  }
+
   void relations(const RelationsRequest &,
  llvm::function_ref)
   const override {}
Index: clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp
===
--- clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp
+++ clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp
@@ -44,17 +44,27 @@
 
 // Helpers for matching call hierarchy data structures.
 MATCHER_P(withName, N, "") { return arg.name == N; }
+MATCHER_P(withDetail, N, "") { return arg.detail == N; }
 MATCHER_P(withSelectionRange, R, "") { return arg.selectionRange == R; }
 
 template 
 ::testing::Matcher from(ItemMatcher M) {
   return Field(&CallHierarchyIncomingCall::from, M);
 }
+template 
+::testing::Matcher to(ItemMatcher M) {
+  return Field(&CallHierarchyOutgoingCall::to, M);
+}
 template 
-::testing::Matcher fromRanges(RangeMatchers... M) {
+::testing::Matcher iFromRanges(RangeMatchers... M) {
   return Field(&CallHierarchyIncomingCall::fromRanges,
UnorderedElementsAre(M...));
 }
+template 
+::testing::Matcher oFromRanges(RangeMatchers... M) {
+  return Field(&CallHierarchyOutgoingCall::fromRanges,
+   UnorderedElementsAre(M...));
+}
 
 TEST(CallHierarchy, IncomingOneFileCpp) {
   Annotations Source(R"cpp(
@@ -79,21 +89,24 @@
   prepareCallHierarchy(AST, Source.point(), testPath(TU.Filename));
   ASSERT_THAT(Items, ElementsAre(withName("callee")));
   auto IncomingLevel1 = incomingCalls(Items[0], Index.get());
-  ASSERT_THAT(IncomingLevel1,
-  ElementsAre(AllOf(from(withName("caller1")),
-fromRanges(Source.range("Callee");
+  ASSERT_THAT(
+  IncomingLevel1,
+  ElementsAre(AllOf(from(AllOf(withName("caller1"), withDetail("caller1"))),
+iFromRanges(Source.range("Callee");
   auto IncomingLevel2 = incomingCalls(IncomingLevel1[0].from, Index.get());
-  ASSERT_THAT(IncomingLevel2,
-  ElementsAre(AllOf(from(withName("caller2")),
-fromRanges(Source.range("Caller1A"),
-   Source.range("Caller1B"))),
-  AllOf(from(withName("caller3")),
-f

[PATCH] D93829: [clangd] Support outgoing calls in call hierarchy

2023-10-22 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked 2 inline comments as done.
nridge added a comment.

@sammccall, how would you feel about proceeding with the patch in its current 
state, with the memory usage increase brought down from 8.2% to 2.5% thanks to 
the combination of the simple lookup optimization + RefKind filtering, and 
leaving the "deep lookup optimization" to be explored in a future change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93829

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


[clang] [clang][Sema] Avoid non-empty unexpanded pack assertion for FunctionParmPackExpr (PR #69224)

2023-10-22 Thread via cfe-commits

cor3ntin wrote:

> Instead of putting it inside an assertion, how about adding a check for 
> FunctionParmPackExpr separately? I mean,

If that works it would be fine with me, yes

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


[clang-tools-extra] [ConstantRange] Handle `Intrinsic::cttz` (PR #67917)

2023-10-22 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

Ping.

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


[clang] [ConstantRange] Handle `Intrinsic::cttz` (PR #67917)

2023-10-22 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

Ping.

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Owen Pan via cfe-commits

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

Fixes #44363.

>From fc955bc2730b52093d1e6d2bdd2dbf0400879edf Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 22 Oct 2023 01:36:17 -0700
Subject: [PATCH] [clang-format] Don't break between string literal operands of
 <<

Fixes #44363.
---
 clang/lib/Format/TokenAnnotator.cpp   | 4 
 clang/unittests/Format/FormatTest.cpp | 4 
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7f85f48de2ed2ed..e185afaa2885123 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
-  Right.Next->is(tok::string_literal)) {
-return true;
-  }
   if (Right.is(TT_RequiresClause)) {
 switch (Style.RequiresClausePosition) {
 case FormatStyle::RCPS_OwnLine:
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0a87cfc4f1d6af9..0841ea1bcb66fa9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26459,6 +26459,10 @@ TEST_F(FormatTest, AllowBreakBeforeNoexceptSpecifier) {
Style);
 }
 
+TEST_F(FormatTest, StreamOutputOperator) {
+  verifyFormat("std::cout << \"foo\" << \"bar\" << baz;");
+}
+
 } // namespace
 } // namespace test
 } // namespace format

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixes #44363.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (-4) 
- (modified) clang/unittests/Format/FormatTest.cpp (+4) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7f85f48de2ed2ed..e185afaa2885123 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
-  Right.Next->is(tok::string_literal)) {
-return true;
-  }
   if (Right.is(TT_RequiresClause)) {
 switch (Style.RequiresClausePosition) {
 case FormatStyle::RCPS_OwnLine:
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0a87cfc4f1d6af9..0841ea1bcb66fa9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26459,6 +26459,10 @@ TEST_F(FormatTest, AllowBreakBeforeNoexceptSpecifier) {
Style);
 }
 
+TEST_F(FormatTest, StreamOutputOperator) {
+  verifyFormat("std::cout << \"foo\" << \"bar\" << baz;");
+}
+
 } // namespace
 } // namespace test
 } // namespace format

``




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


[clang] [clang] Fix --entry command line option (PR #69114)

2023-10-22 Thread Tuur Martens via cfe-commits

JohnyTheCarrot wrote:

Ping. Requested changes were made. Apologies if this ping is misplaced, I made 
it in good faith.

> (Please make sure to edit the description before merging so that git log does 
> not contain irrelevant information.)

You mean during the merge phase, right?

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-22 Thread Utkarsh Saxena via cfe-commits

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-22 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/68922

>From 8aa439a97a56ef80bfc9ccc90a9f093680e455f5 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Sun, 22 Oct 2023 11:11:53 +0200
Subject: [PATCH] rebase...

---
 clang/docs/ReleaseNotes.rst   |  4 +
 clang/lib/Sema/SemaOverload.cpp   | 19 ++---
 .../over.match.oper/p3-2a.cpp | 78 +++
 3 files changed, 89 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..cef857244387e8b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -85,6 +85,10 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
+- Fixed a bug in finding matching `operator!=` while adding reversed 
`operator==` as
+  outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
+  Fixes (`#68901: `_).
+
 C++ Specific Potentially Breaking Changes
 -
 - The name mangling rules for function templates has been changed to take into
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d57a7ad8f46859a..75e4184c8aa6cb8 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -960,18 +960,13 @@ static bool shouldAddReversedEqEq(Sema &S, SourceLocation 
OpLoc,
 return true;
   }
   // Otherwise the search scope is the namespace scope of which F is a member.
-  LookupResult NonMembers(S, NotEqOp, OpLoc,
-  Sema::LookupNameKind::LookupOperatorName);
-  S.LookupName(NonMembers,
-   S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
-  NonMembers.suppressAccessDiagnostics();
-  for (NamedDecl *Op : NonMembers) {
-auto *FD = Op->getAsFunction();
-if(auto* UD = dyn_cast(Op))
-  FD = UD->getUnderlyingDecl()->getAsFunction();
-if (FunctionsCorrespond(S.Context, EqFD, FD) &&
-declaresSameEntity(cast(EqFD->getDeclContext()),
-   cast(Op->getDeclContext(
+  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
+auto *NotEqFD = Op->getAsFunction();
+if (auto *UD = dyn_cast(Op))
+  NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
+if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) &&
+declaresSameEntity(cast(EqFD->getEnclosingNamespaceContext()),
+   cast(Op->getLexicalDeclContext(
   return false;
   }
   return true;
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5727d506fe5e61d..9dc5ee8db565341 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -374,6 +374,84 @@ bool fine(A a, B b) { return a == b; } // Ok. Found a 
matching operator!=.
 }
 }
 
+
+namespace ADL_GH68901{
+namespace A {
+struct S {};
+bool operator==(S, int); // expected-note {{no known conversion from 'int' to 
'S' for 1st argument}}
+bool operator!=(S, int);
+} // namespace A
+bool a = 0 == A::S(); // expected-error {{invalid operands to binary 
expression ('int' and 'A::S')}}
+
+namespace B {
+struct Derived {};
+struct Base : Derived {};
+
+bool operator==(Derived& a, Base& b);
+bool operator!=(Derived& a, Base& b);
+}  // namespace B
+
+void foo() {
+  // B::Base{} == B::Base{};
+  B::Base a,b;
+  bool v = a == b;
+}
+
+namespace ns {
+template 
+struct A {
+};
+
+template 
+struct B : A {
+};
+
+template  bool operator == (B, A); // expected-note {{candidate 
template ignored: could not match 'B' against 'A'}}
+template  bool operator != (B, A);
+}
+
+void test() {
+ns::A a;
+ns::B b;
+a == b; // expected-error {{invalid operands to binary expression}}
+}
+
+
+} //namespace ADL_GH68901
+
+namespace function_scope_operator_eqeq {
+// For non-members, we always lookup for matching operator!= in the namespace 
scope of
+// operator== (and not in the scope of operator==).
+struct X { operator int(); };
+namespace test1{
+bool h(X x) {
+  bool operator==(X, int); // expected-note {{reversed}}
+  return x == x; // expected-warning {{ambiguous}}
+}
+
+bool g(X x) {
+  bool operator==(X, int); // expected-note {{reversed}}
+  bool operator!=(X, int);
+  return x == x;  // expected-warning {{ambiguous}}
+}
+} // namespace test1
+
+namespace test2 {
+bool operator!=(X, int);
+
+bool h(X x) {
+  bool operator==(X, int);
+  return x == x;
+}
+
+bool i(X x) {
+  bool operator==(X, int);
+  bool operator!=(X, int);
+  return x == x;
+}
+} // namespace test2
+} // namespace function_scope_operator_eqeq
+
 namespace non_member_temp

[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-22 Thread Balazs Benics via cfe-commits
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy 
Message-ID:
In-Reply-To: 


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


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


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);

steakhal wrote:

Then why aren't these part of the CallEvent API?

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


[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);

steakhal wrote:

Then why aren't these part of the CallEvent API?

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


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);
+
+// When invalidating regions, we also have to follow that by invalidating the
+// corresponding custom data in the program state.
+template 
+ProgramStateRef
+removeInformationStoredForDeadInstances(const CallEvent *Call,

steakhal wrote:

I don't understand how some other API might affect this one.
I thought you could always transform a reference to a pointer and the other way 
around using the deref and addrof operators.

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


[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);
+
+// When invalidating regions, we also have to follow that by invalidating the
+// corresponding custom data in the program state.
+template 
+ProgramStateRef
+removeInformationStoredForDeadInstances(const CallEvent *Call,

steakhal wrote:

I don't understand how some other API might affect this one.
I thought you could always transform a reference to a pointer and the other way 
around using the deref and addrof operators.

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits


@@ -94,7 +94,7 @@ class AttributeCommonInfo {
   IsRegularKeywordAttribute(IsRegularKeywordAttribute) {}
 constexpr Form(tok::TokenKind Tok)
 : SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
-  IsAlignas(Tok == tok::kw_alignas),
+  IsAlignas(Tok == tok::kw_alignas || Tok == tok::kw__Alignas),

jerinphilip wrote:

The other place to recover the `_Alignas` vs `alignas` is `SpellingIndex`. But 
the following (removed) comment still applies (regarding `SpellingIndex`):

[[clang] Reject non-declaration C++11 attributes on 
declarations](https://github.com/llvm/llvm-project/commit/8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb)

```cpp
// FIXME: Use a better mechanism to determine this
// We use this in `isCXX11Attribute` below, so it _should_ only return
// true for the `alignas` spelling, but it currently also returns true
// for the `_Alignas` spelling, which only exists in C11. Distinguishing
// between the two is important because they behave differently:
// - `alignas` may only appear in the attribute-specifier-seq before
//   the decl-specifier-seq and is therefore associated with the
//   declaration.
// - `_Alignas` may appear anywhere within the declaration-specifiers
//   and is therefore associated with the `DeclSpec`.
// It's not clear how best to fix this:
// - We have the necessary information in the form of the `SpellingIndex`,
//   but we would need to compare against AlignedAttr::Keyword_alignas,
//   and we can't depend on clang/AST/Attr.h here.
// - We could test `getAttrName()->getName() == "alignas"`, but this is
//   inefficient.
```

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


[clang-tools-extra] [clangd] Show alignment for records and fields decls (PR #67213)

2023-10-22 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Thank you @Endilll for the explanation. The remaining part looks good; 
@sr-tream Do you have access to land the PR? If not, I'm glad to help you. :)

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


[clang-tools-extra] [mlir] Verify TestBuiltinAttributeInterfaces eltype (PR #69878)

2023-10-22 Thread Rik Huijzer via cfe-commits

https://github.com/rikhuijzer created 
https://github.com/llvm/llvm-project/pull/69878

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

This PR fixes two small things. First and foremost, it throws a clear error in 
the `-test-elements-attr-interface` when those tests are called on elements 
which are not an integer. I've looked through the introduction of the attribute 
interface (https://reviews.llvm.org/D109190) and later commits and see no 
evidence that the interface (`attr.tryGetValues()`) is expected to handle 
mismatching types. 

For example, the case which is given in the issue is:
```mlir
arith.constant sparse<[[0, 0, 5]],  -2.0> : vector<1x1x10xf16>
```
So, a sparse vector containing `f16` elements. This will crash at various 
locations when called in the test because the test introduces integer types 
(`int64_t`, `uint64_t`, `APInt`, `IntegerAttr`), but as I said in the previous 
paragraph: I see no reason to believe that the interface is wrong here. The 
interface assumes that clients don't do things like
`attr.tryGetValues()` on a floating point `attr`.

Also I've added a test for the implementation of this interface by the `sparse` 
dialect. There were no problems there. Still, probably good to increase code 
coverage on that one (also, to avoid new issue reports like 
https://github.com/llvm/llvm-project/issues/61871).

>From 1d27516523cde11767705396b0ea5a9e1f264f50 Mon Sep 17 00:00:00 2001
From: Rik Huijzer 
Date: Sun, 22 Oct 2023 14:36:59 +0200
Subject: [PATCH] [mlir] Verify TestBuiltinAttributeInterfaces eltype

---
 mlir/test/IR/elements-attr-interface.mlir   | 13 +
 mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp |  5 +
 2 files changed, 18 insertions(+)

diff --git a/mlir/test/IR/elements-attr-interface.mlir 
b/mlir/test/IR/elements-attr-interface.mlir
index e5f17d043f1aace..5234c81bd841e39 100644
--- a/mlir/test/IR/elements-attr-interface.mlir
+++ b/mlir/test/IR/elements-attr-interface.mlir
@@ -20,6 +20,13 @@ arith.constant #test.i64_elements<[10, 11, 12, 13, 14]> : 
tensor<5xi64>
 // expected-error@below {{Test iterating `IntegerAttr`: 10 : i64, 11 : i64, 12 
: i64, 13 : i64, 14 : i64}}
 arith.constant dense<[10, 11, 12, 13, 14]> : tensor<5xi64>
 
+// This test is expected to only be called on integer elements.
+// expected-error@below {{Test iterating `int64_t`: expected element type to 
be an integer type}}
+// expected-error@below {{Test iterating `uint64_t`: expected element type to 
be an integer type}}
+// expected-error@below {{Test iterating `APInt`: expected element type to be 
an integer type}}
+// expected-error@below {{Test iterating `IntegerAttr`: expected element type 
to be an integer type}}
+arith.constant dense<[1.1, 1.2, 1.3]> : tensor<3xf32>
+
 // Check that we don't crash on empty element attributes.
 // expected-error@below {{Test iterating `int64_t`: }}
 // expected-error@below {{Test iterating `uint64_t`: }}
@@ -41,3 +48,9 @@ arith.constant #test.e1di64_elements : tensor<3xi64>
 }
   }
 #-}
+
+// expected-error@below {{Test iterating `int64_t`: 0, 0, 1}}
+// expected-error@below {{Test iterating `uint64_t`: 0, 0, 1}}
+// expected-error@below {{Test iterating `APInt`: 0, 0, 1}}
+// expected-error@below {{Test iterating `IntegerAttr`: 0 : i64, 0 : i64, 1 : 
i64}}
+arith.constant sparse<[[0, 0, 2]], 1> : vector <1x1x3xi64>
diff --git a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp 
b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
index 498de3d87bd4bc3..71ed30bfbe34cd0 100644
--- a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
+++ b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
@@ -51,6 +51,11 @@ struct TestElementsAttrInterface
 InFlightDiagnostic diag = op->emitError()
   << "Test iterating `" << type << "`: ";
 
+if (!attr.getElementType().isa()) {
+  diag << "expected element type to be an integer type";
+  return;
+}
+
 auto values = attr.tryGetValues();
 if (!values) {
   diag << "unable to iterate type";

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


[clang-tools-extra] [mlir] Verify TestBuiltinAttributeInterfaces eltype (PR #69878)

2023-10-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir

Author: Rik Huijzer (rikhuijzer)


Changes

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

This PR fixes two small things. First and foremost, it throws a clear error in 
the `-test-elements-attr-interface` when those tests are called on elements 
which are not an integer. I've looked through the introduction of the attribute 
interface (https://reviews.llvm.org/D109190) and later commits and see no 
evidence that the interface (`attr.tryGetValues()`) is expected to 
handle mismatching types. 

For example, the case which is given in the issue is:
```mlir
arith.constant sparse<[[0, 0, 5]],  -2.0> : vector<1x1x10xf16>
```
So, a sparse vector containing `f16` elements. This will crash at various 
locations when called in the test because the test introduces integer types 
(`int64_t`, `uint64_t`, `APInt`, `IntegerAttr`), but as I said in the previous 
paragraph: I see no reason to believe that the interface is wrong here. The 
interface assumes that clients don't do things like
`attr.tryGetValues()` on a floating point `attr`.

Also I've added a test for the implementation of this interface by the `sparse` 
dialect. There were no problems there. Still, probably good to increase code 
coverage on that one (also, to avoid new issue reports like 
https://github.com/llvm/llvm-project/issues/61871).

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


2 Files Affected:

- (modified) mlir/test/IR/elements-attr-interface.mlir (+13) 
- (modified) mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp (+5) 


``diff
diff --git a/mlir/test/IR/elements-attr-interface.mlir 
b/mlir/test/IR/elements-attr-interface.mlir
index e5f17d043f1aace..5234c81bd841e39 100644
--- a/mlir/test/IR/elements-attr-interface.mlir
+++ b/mlir/test/IR/elements-attr-interface.mlir
@@ -20,6 +20,13 @@ arith.constant #test.i64_elements<[10, 11, 12, 13, 14]> : 
tensor<5xi64>
 // expected-error@below {{Test iterating `IntegerAttr`: 10 : i64, 11 : i64, 12 
: i64, 13 : i64, 14 : i64}}
 arith.constant dense<[10, 11, 12, 13, 14]> : tensor<5xi64>
 
+// This test is expected to only be called on integer elements.
+// expected-error@below {{Test iterating `int64_t`: expected element type to 
be an integer type}}
+// expected-error@below {{Test iterating `uint64_t`: expected element type to 
be an integer type}}
+// expected-error@below {{Test iterating `APInt`: expected element type to be 
an integer type}}
+// expected-error@below {{Test iterating `IntegerAttr`: expected element type 
to be an integer type}}
+arith.constant dense<[1.1, 1.2, 1.3]> : tensor<3xf32>
+
 // Check that we don't crash on empty element attributes.
 // expected-error@below {{Test iterating `int64_t`: }}
 // expected-error@below {{Test iterating `uint64_t`: }}
@@ -41,3 +48,9 @@ arith.constant #test.e1di64_elements : tensor<3xi64>
 }
   }
 #-}
+
+// expected-error@below {{Test iterating `int64_t`: 0, 0, 1}}
+// expected-error@below {{Test iterating `uint64_t`: 0, 0, 1}}
+// expected-error@below {{Test iterating `APInt`: 0, 0, 1}}
+// expected-error@below {{Test iterating `IntegerAttr`: 0 : i64, 0 : i64, 1 : 
i64}}
+arith.constant sparse<[[0, 0, 2]], 1> : vector <1x1x3xi64>
diff --git a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp 
b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
index 498de3d87bd4bc3..71ed30bfbe34cd0 100644
--- a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
+++ b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
@@ -51,6 +51,11 @@ struct TestElementsAttrInterface
 InFlightDiagnostic diag = op->emitError()
   << "Test iterating `" << type << "`: ";
 
+if (!attr.getElementType().isa()) {
+  diag << "expected element type to be an integer type";
+  return;
+}
+
 auto values = attr.tryGetValues();
 if (!values) {
   diag << "unable to iterate type";

``




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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-22 Thread via cfe-commits


@@ -847,7 +845,33 @@ template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
-  return this->visit(E->getSourceExpr());
+
+  PrimType CacheVariableTy = classify(E).value_or(PT_Ptr);

isuckatcs wrote:

I added a test case like that.

```
constexpr int foo() { return X(0) ?: X(0); }
```
```
`-OpaqueValueExpr ... 'X':'X' xvalue
   `-MaterializeTemporaryExpr ... 'X':'X' xvalue
 `-CXXFunctionalCastExpr ... 'X':'X' functional cast to X 
   `-CXXParenListInitExpr ... 'X':'X'
 `-IntegerLiteral ... 'int' 0
```

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-22 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/68039

>From 6748bd2171cca24c46ade12d57b57e97c3312501 Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:29:14 +0200
Subject: [PATCH 1/6] impl

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 21 +---
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 25 
 clang/test/AST/Interp/arrays.cpp |  6 +-
 3 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e9e20b222d5d34f..7d38d82f25331e4 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -810,9 +810,20 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 const ArrayInitLoopExpr *E) {
   assert(Initializing);
   assert(!DiscardResult);
-  // TODO: This compiles to quite a lot of bytecode if the array is larger.
-  //   Investigate compiling this to a loop, or at least try to use
-  //   the AILE's Common expr.
+
+  const auto *CommonExpr = E->getCommonExpr();
+  std::optional CommonTy = classify(CommonExpr);
+
+  std::optional LocalIndex = 
this->allocateLocalPrimitive(CommonExpr, *CommonTy, 
CommonExpr->getType().isConstQualified());
+  if (!LocalIndex)
+return false;
+  if (!this->visit(CommonExpr))
+return false;
+  if(!this->emitSetLocal(*CommonTy, *LocalIndex, E))
+return false;
+
+  StoredOpaqueValueScope KnownOpaqueScope(this, *LocalIndex);
+
   const Expr *SubExpr = E->getSubExpr();
   size_t Size = E->getArraySize().getZExtValue();
   std::optional ElemT = classify(SubExpr->getType());
@@ -845,8 +856,12 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if(IgnoreOpaqueValue)
+return this->emitGetLocal(*classify(E), *OpaqueValueIndex, E);
+
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
+  
   return this->visit(E->getSourceExpr());
 }
 
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 2049dab140eaaae..a6c546384580b9a 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -36,6 +36,7 @@ template  class DeclScope;
 template  class OptionScope;
 template  class ArrayIndexScope;
 template  class SourceLocScope;
+template  class StoredOpaqueValueScope;
 
 /// Compilation context for expressions.
 template 
@@ -220,6 +221,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class OptionScope;
   friend class ArrayIndexScope;
   friend class SourceLocScope;
+  friend class StoredOpaqueValueScope;
 
   /// Emits a zero initializer.
   bool visitZeroInitializer(PrimType T, QualType QT, const Expr *E);
@@ -304,6 +306,10 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   /// Flag inidicating if we're initializing an already created
   /// variable. This is set in visitInitializer().
   bool Initializing = false;
+
+  /// Flag indicating if we ignore an OpaqueValueExpr.
+  bool IgnoreOpaqueValue = false;
+  std::optional OpaqueValueIndex;
 };
 
 extern template class ByteCodeExprGen;
@@ -479,6 +485,25 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx, uint64_t LocalIndex, 
bool ignore = true)
+  : Ctx(Ctx), OldIgnoreValue(Ctx->IgnoreOpaqueValue), 
OldLocalIndex(Ctx->OpaqueValueIndex) {
+Ctx->IgnoreOpaqueValue = ignore;
+Ctx->OpaqueValueIndex = LocalIndex;
+  }
+
+  ~StoredOpaqueValueScope() {
+  Ctx->IgnoreOpaqueValue = OldIgnoreValue;
+  Ctx->OpaqueValueIndex = OldLocalIndex;
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  bool OldIgnoreValue;
+  std::optional OldLocalIndex;
+};
+
 } // namespace interp
 } // namespace clang
 
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..1f8908f2bed0b24 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -352,9 +352,6 @@ namespace ZeroInit {
 }
 
 namespace ArrayInitLoop {
-  /// FIXME: The ArrayInitLoop for the decomposition initializer in g() has
-  /// f(n) as its CommonExpr. We need to evaluate that exactly once and not
-  /// N times as we do right now.
   struct X {
   int arr[3];
   };
@@ -366,8 +363,7 @@ namespace ArrayInitLoop {
   auto [a, b, c] = f(n).arr;
   return a + b + c;
   }
-  static_assert(g() == 6); // expected-error {{failed}} \
-   // expected-note {{15 == 6}}
+  static_assert(g() == 6);
 }
 
 namespace StringZeroFill {

>From 98ac7bdc5b07fcb23b8852b39179ecb711431f7c Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:51:58 +0200
Subject: [PATCH 2/6] cleanup

---
 clang/lib/AST/Interp/By

[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Björn Schäpers via cfe-commits

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Björn Schäpers via cfe-commits


@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&

HazardyKnusperkeks wrote:

But why was that added? Alone from Github I can't navigate to the commit which 
introduced it.

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Björn Schäpers via cfe-commits

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


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


[PATCH] D156565: Diagnose use of VLAs in C++ by default

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

In D156565#4654773 , @nathanchance 
wrote:

> Is it expected that this introduces a warning for C code, as the commit 
> message and tests appear to only affect C++? A trivial example from the Linux 
> kernel:
>
> https://elixir.bootlin.com/linux/v6.5.8/source/tools/lib/bpf/btf_dump.c#L1678
>
>   #include 
>   #include 
>   #include 
>   
>   void foo(char *orig_name, char **cached_name, size_t dup_cnt)
>   {
>   const size_t max_len = 256;
>   char new_name[max_len];
>   
>   snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
>   *cached_name = strdup(new_name);
>   }
>
>
>
>   $ clang -std=gnu89 -Wall -fsyntax-only test.c
>   test.c:8:16: warning: variable length arrays are a C99 feature 
> [-Wvla-extension]
>   8 | char new_name[max_len];
> |   ^~~
>   1 warning generated.

No, that's unintended, I'll get that fixed. Thanks for letting me know!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156565

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


[clang] [clang][Interp] Fix `ArrayInitLoopExpr` handling (PR #67886)

2023-10-22 Thread via cfe-commits

isuckatcs wrote:

ping @tbaederr 

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From 941af68ab8dad68ed8df65f6e0559476f137bfe2 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH 01/14] Fix `Form` to recognize `_Alignas` in addition to
 `alignas`

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index e57adc4bf5b99a2..36f4eb885cf12f8 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -94,7 +94,7 @@ class AttributeCommonInfo {
   IsRegularKeywordAttribute(IsRegularKeywordAttribute) {}
 constexpr Form(tok::TokenKind Tok)
 : SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
-  IsAlignas(Tok == tok::kw_alignas),
+  IsAlignas(Tok == tok::kw_alignas || Tok == tok::kw__Alignas),
   IsRegularKeywordAttribute(tok::isRegularKeywordAttribute(Tok)) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }

>From 8c0bfe350dfa2d4d24988eb544f5c1a9eb1aec6d Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 18:53:57 +0530
Subject: [PATCH 02/14] Avoid mixing `isCXX11Attribute` with `isAlignAs`

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 36f4eb885cf12f8..669227589dfacd5 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,14 +186,14 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
-  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11 || IsAlignas; }
+  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
 
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
   /// attributes spelled with a keyword, like alignas.
   bool isStandardAttributeSyntax() const {
-return isCXX11Attribute() || isC23Attribute();
+return isCXX11Attribute() || isC23Attribute() || IsAlignas;
   }
 
   bool isGNUAttribute() const { return SyntaxUsed == AS_GNU; }

>From 8f699d5dfe62b2a1eb1f67f37ffa3d4ba1f2bfce Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 19:15:03 +0530
Subject: [PATCH 03/14] Fix diagnostic warning post `isAlignAs` decoupling

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 2 +-
 clang/lib/Parse/ParseDecl.cpp   | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 669227589dfacd5..f1e3325d44f0e1a 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,8 +186,8 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
+  bool isAlignas() const { return IsAlignas; }
   bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
-
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 4a9f2caf654713e..f91141f7cd39cbf 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3405,8 +3405,8 @@ void Parser::ParseDeclarationSpecifiers(
   else {
 // Reject C++11 / C23 attributes that aren't type attributes.
 for (const ParsedAttr &PA : attrs) {
-  if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
-  !PA.isRegularKeywordAttribute())
+  if (!PA.isAlignas() && !PA.isCXX11Attribute() &&
+  !PA.isC23Attribute() && !PA.isRegularKeywordAttribute())
 continue;
   if (PA.getKind() == ParsedAttr::UnknownAttribute)
 // We will warn about the unknown attribute elsewhere (in

>From e7ddd755f1a873421809a05a4d5d999b7a15f62e Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:44:51 +0530
Subject: [PATCH 04/14] Add attribute-ignored diagnostic warning variant

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..f76f872a98288f7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3491,10 +3491,14 @@ def err_attribute_invalid_on_decl : Error<
 def warn_type_attribute_deprecated_on_decl : Warning<
   "applying attribute %0 to a declaration is de

[clang] [Clang][LoongArch] Support builtin functions for LSX and LASX (PR #69313)

2023-10-22 Thread WÁNG Xuěruì via cfe-commits

xen0n wrote:

According to [the *LLVM GitHub user 
guide*](https://llvm.org/docs/GitHub.html#creating-pull-requests):

> If you have multiple changes you want to introduce, it’s recommended to 
> create separate pull requests for each change.

Given you've already split your changes into several smaller commits, it's 
probably better to file them as separate PRs, so each one is smaller than the 
current 3+-line diff, and become more reviewable that way.

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


[PATCH] D156565: Diagnose use of VLAs in C++ by default

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

In D156565#4654818 , @aaron.ballman 
wrote:

> In D156565#4654773 , @nathanchance 
> wrote:
>
>> Is it expected that this introduces a warning for C code, as the commit 
>> message and tests appear to only affect C++? A trivial example from the 
>> Linux kernel:
>>
>> https://elixir.bootlin.com/linux/v6.5.8/source/tools/lib/bpf/btf_dump.c#L1678
>>
>>   #include 
>>   #include 
>>   #include 
>>   
>>   void foo(char *orig_name, char **cached_name, size_t dup_cnt)
>>   {
>>   const size_t max_len = 256;
>>   char new_name[max_len];
>>   
>>   snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
>>   *cached_name = strdup(new_name);
>>   }
>>
>>
>>
>>   $ clang -std=gnu89 -Wall -fsyntax-only test.c
>>   test.c:8:16: warning: variable length arrays are a C99 feature 
>> [-Wvla-extension]
>>   8 | char new_name[max_len];
>> |   ^~~
>>   1 warning generated.
>
> No, that's unintended, I'll get that fixed. Thanks for letting me know!

Unfortunately, this will require complicating the diagnostic groups slightly 
more. We don't have facilities that allow us to say that a single diagnostic is 
grouped under `-Wall` in one language mode but not another, and we don't have a 
way for diagnostic groups to share the same string (so we can't have `def 
VLACxxExtension : DiagGroup<"vla-extension", [VLAUseStaticAssert]>;` and `def 
VLAExtension : DiagGroup<"vla-extension", [VLACxxExtension]>;`).

I think I will address this by adding `-Wvla-cxx-extension` and putting the C++ 
warnings under it, and that warning group will be added to `-Wall`. e.g.,

  diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
  index dcdae38013d2..4cb792132d6e 100644
  --- a/clang/include/clang/Basic/DiagnosticGroups.td
  +++ b/clang/include/clang/Basic/DiagnosticGroups.td
  @@ -849,7 +849,8 @@ def VariadicMacros : DiagGroup<"variadic-macros">;
   def VectorConversion : DiagGroup<"vector-conversion">;  // clang specific
   def VexingParse : DiagGroup<"vexing-parse">;
   def VLAUseStaticAssert : DiagGroup<"vla-extension-static-assert">;
  -def VLAExtension : DiagGroup<"vla-extension", [VLAUseStaticAssert]>;
  +def VLACxxExtension : DiagGroup<"vla-cxx-extension", [VLAUseStaticAssert]>;
  +def VLAExtension : DiagGroup<"vla-extension", [VLACxxExtension]>;
   def VLA : DiagGroup<"vla", [VLAExtension]>;
   def VolatileRegisterVar : DiagGroup<"volatile-register-var">;
   def Visibility : DiagGroup<"visibility">;
  @@ -1086,7 +1087,8 @@ def Consumed   : DiagGroup<"consumed">;
   // warning should be active _only_ when -Wall is passed in, mark it as
   // DefaultIgnore in addition to putting it here.
   def All : DiagGroup<"all", [Most, Parentheses, Switch, SwitchBool,
  -MisleadingIndentation, PackedNonPod, 
VLAExtension]>;
  +MisleadingIndentation, PackedNonPod,
  +VLACxxExtension]>;
  
   // Warnings that should be in clang-cl /w4.
   def : DiagGroup<"CL4", [All, Extra]>;
  diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
  index a4c1cb08de94..3bcbb003d6de 100644
  --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
  +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
  @@ -141,9 +141,9 @@ def ext_vla : Extension<"variable length arrays are a C99 
feature">,
   // language modes, we warn as an extension but add the warning group to 
-Wall.
   def ext_vla_cxx : ExtWarn<
 "variable length arrays in C++ are a Clang extension">,
  -  InGroup;
  +  InGroup;
   def ext_vla_cxx_in_gnu_mode : Extension,
  -  InGroup;
  +  InGroup;
   def ext_vla_cxx_static_assert : ExtWarn<
 "variable length arrays in C++ are a Clang extension; did you mean to use "
 "'static_assert'?">, InGroup;

Any concerns with this approach?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156565

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From 941af68ab8dad68ed8df65f6e0559476f137bfe2 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH 01/18] Fix `Form` to recognize `_Alignas` in addition to
 `alignas`

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index e57adc4bf5b99a2..36f4eb885cf12f8 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -94,7 +94,7 @@ class AttributeCommonInfo {
   IsRegularKeywordAttribute(IsRegularKeywordAttribute) {}
 constexpr Form(tok::TokenKind Tok)
 : SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
-  IsAlignas(Tok == tok::kw_alignas),
+  IsAlignas(Tok == tok::kw_alignas || Tok == tok::kw__Alignas),
   IsRegularKeywordAttribute(tok::isRegularKeywordAttribute(Tok)) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }

>From 8c0bfe350dfa2d4d24988eb544f5c1a9eb1aec6d Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 18:53:57 +0530
Subject: [PATCH 02/18] Avoid mixing `isCXX11Attribute` with `isAlignAs`

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 36f4eb885cf12f8..669227589dfacd5 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,14 +186,14 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
-  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11 || IsAlignas; }
+  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
 
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
   /// attributes spelled with a keyword, like alignas.
   bool isStandardAttributeSyntax() const {
-return isCXX11Attribute() || isC23Attribute();
+return isCXX11Attribute() || isC23Attribute() || IsAlignas;
   }
 
   bool isGNUAttribute() const { return SyntaxUsed == AS_GNU; }

>From 8f699d5dfe62b2a1eb1f67f37ffa3d4ba1f2bfce Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 19:15:03 +0530
Subject: [PATCH 03/18] Fix diagnostic warning post `isAlignAs` decoupling

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 2 +-
 clang/lib/Parse/ParseDecl.cpp   | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 669227589dfacd5..f1e3325d44f0e1a 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,8 +186,8 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
+  bool isAlignas() const { return IsAlignas; }
   bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
-
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 4a9f2caf654713e..f91141f7cd39cbf 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3405,8 +3405,8 @@ void Parser::ParseDeclarationSpecifiers(
   else {
 // Reject C++11 / C23 attributes that aren't type attributes.
 for (const ParsedAttr &PA : attrs) {
-  if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
-  !PA.isRegularKeywordAttribute())
+  if (!PA.isAlignas() && !PA.isCXX11Attribute() &&
+  !PA.isC23Attribute() && !PA.isRegularKeywordAttribute())
 continue;
   if (PA.getKind() == ParsedAttr::UnknownAttribute)
 // We will warn about the unknown attribute elsewhere (in

>From e7ddd755f1a873421809a05a4d5d999b7a15f62e Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:44:51 +0530
Subject: [PATCH 04/18] Add attribute-ignored diagnostic warning variant

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..f76f872a98288f7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3491,10 +3491,14 @@ def err_attribute_invalid_on_decl : Error<
 def warn_type_attribute_deprecated_on_decl : Warning<
   "applying attribute %0 to a declaration is de

[PATCH] D156565: Diagnose use of VLAs in C++ by default

2023-10-22 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

> Any concerns with this approach?

Sounds reasonable to me


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156565

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Emilia Kond via cfe-commits


@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&

rymiel wrote:

https://github.com/llvm/llvm-project/commit/2603ee0dc6003be0fbe43038b34580864d1e0c85
Here, 11 years ago

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


[clang-tools-extra] [clangd] Show alignment for records and fields decls (PR #67213)

2023-10-22 Thread via cfe-commits

sr-tream wrote:

> Do you have access to land the PR

No, help me please to merge this PR

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From cce937359c918246cdf515045808e8868b1944d4 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH] [clang] Improve _Alignas on declaration diagnostic

Adds `isAlignas()` method on `AttributeCommonInfo` which accounts for
C++ `alignas` as well as C11 `_Alignas`.

The method is used to improve diagnostic in C when `_Alignas` is used in
C at the wrong location.  This corrects the previously suggested move
of `_Alignas` past the declaration specifier, now warns attribute
`_Alignas` is ignored.
---
 clang/docs/ReleaseNotes.rst   |  5 
 .../include/clang/Basic/AttributeCommonInfo.h |  8 ++-
 clang/lib/Sema/SemaDecl.cpp   | 24 ---
 clang/test/C/drs/dr4xx.c  |  2 +-
 clang/test/Parser/c1x-alignas.c   |  1 +
 clang/test/Parser/c2x-alignas.c   | 11 +
 clang/test/Parser/cxx0x-attributes.cpp|  2 ++
 7 files changed, 42 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Parser/c2x-alignas.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..860818b2e69e483 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -264,6 +264,11 @@ Attribute Changes in Clang
   supports but that are never the result of default argument promotion, such as
   ``float``. (`#59824: `_)
 
+- Clang now warns you that the ``_Alignas`` attribute on declaration specifiers
+  is ignored, changed from the former incorrect suggestion to move it past
+  declaration specifiers.
+
+
 Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 7dc05418498d0ae..3f63b31b45ac3c9 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -188,8 +188,14 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
-  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11 || IsAlignas; }
+  bool isAlignas() const {
+// In the current state of code, IsAlignas is only configured to return
+// true on C++ `alignas` keyword and alternate spellings, not `_Alignas`.
+// The following evaluation includes otherwise lost `_Alignas` information.
+return (getParsedKind() == AT_Aligned && isKeywordAttribute());
+  }
 
+  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11 || IsAlignas; }
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..a96cb7bcb53dc64 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5339,16 +5339,22 @@ Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, 
AccessSpecifier AS,
 TypeSpecType == DeclSpec::TST_interface ||
 TypeSpecType == DeclSpec::TST_union ||
 TypeSpecType == DeclSpec::TST_enum) {
-  for (const ParsedAttr &AL : DS.getAttributes())
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
-<< AL << GetDiagnosticTypeSpecifierID(DS);
-  for (const ParsedAttr &AL : DeclAttrs)
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
+
+  auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
+unsigned DiagnosticId;
+if (AL.isAlignas() && !getLangOpts().CPlusPlus) {
+  DiagnosticId = diag::warn_attribute_ignored;
+} else if (AL.isRegularKeywordAttribute()) {
+  DiagnosticId = diag::err_declspec_keyword_has_no_effect;
+} else {
+  DiagnosticId = diag::warn_declspec_attribute_ignored;
+}
+Diag(AL.getLoc(), DiagnosticId)
 << AL << GetDiagnosticTypeSpecifierID(DS);
+  };
+
+  llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
+  llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
 }
   }
 
diff --git a/clang/test/C/drs/dr4xx.c b/clang/test/C/drs/dr4xx.c
index b8ccceaad12c59f..d4d212d680862a4 100644
--- a/clang/test/C/drs/dr4xx.c
+++ b/clang/test/C/drs/dr4xx.c
@@ -168,7 +168,7 @@ void dr444(void) {
   * where the diagnostic recommends causes a different, more inscrutable error
   * about anonymous structures.
   */
-  _Alignas(int) struct T { /* expected-warning {{attribute '_Alignas' is 

[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

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


[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);
+
+// When invalidating regions, we also have to follow that by invalidating the
+// corresponding custom data in the program state.
+template 
+ProgramStateRef
+removeInformationStoredForDeadInstances(const CallEvent *Call,

spaits wrote:

Then I will modify my function accordingly. Should I take a look at the 
`checkRegionChanges` callback in general and consider modifying it to take 
`const CallEvent &` instead of `const CallEvent *` ? Do you think that would be 
a good task? I think I would have time for it and I would enjoy doing it.

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


[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From ce62d3e1924b497b3e7160579a87557119c9e35d Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/3] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..052cf5f884f2773 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index ae849f59f90d3d9..d7cb51e1a0819a8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From ce62d3e1924b497b3e7160579a87557119c9e35d Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/4] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..052cf5f884f2773 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index ae849f59f90d3d9..d7cb51e1a0819a8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang-tools-extra] c300884 - [clangd] Show alignment for records and fields decls (#67213)

2023-10-22 Thread via cfe-commits

Author: SR_team
Date: 2023-10-22T20:37:12+04:00
New Revision: c3008842bf19e3a00db1f8adbd95d43f71b4f09f

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

LOG: [clangd] Show alignment for records and fields decls (#67213)

Shows align for records and fields declarations in hover information.

Example:
```cpp
struct A {
  char a;
  short b;
};
```

For this struct hover informations shows:
```
Size: 4 bytes, alignment 2 bytes
```


![image](https://github.com/llvm/llvm-project/assets/12231048/a130b353-f3f6-4203-b0d7-3d592b7a7855)

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/Hover.h
clang-tools-extra/clangd/unittests/HoverTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 0ec85fc24df151b..933c69294b40926 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -1001,6 +1001,8 @@ void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
   if (auto *RD = llvm::dyn_cast(&ND)) {
 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
   HI.Size = Size->getQuantity() * 8;
+if (!RD->isDependentType() && RD->isCompleteDefinition())
+  HI.Align = Ctx.getTypeAlign(RD->getTypeForDecl());
 return;
   }
 
@@ -1009,6 +1011,7 @@ void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
 if (Record)
   Record = Record->getDefinition();
 if (Record && !Record->isInvalidDecl() && !Record->isDependentType()) {
+  HI.Align = Ctx.getTypeAlign(FD->getType());
   const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
   HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
   if (FD->isBitField())
@@ -1487,6 +1490,8 @@ markup::Document HoverInfo::present() const {
   P.appendText(
   llvm::formatv(" (+{0} padding)", formatSize(*Padding)).str());
 }
+if (Align)
+  P.appendText(", alignment " + formatSize(*Align));
   }
 
   if (CalleeArgInfo) {

diff  --git a/clang-tools-extra/clangd/Hover.h 
b/clang-tools-extra/clangd/Hover.h
index 6a61100912918ea..fe689de44732ebe 100644
--- a/clang-tools-extra/clangd/Hover.h
+++ b/clang-tools-extra/clangd/Hover.h
@@ -97,6 +97,8 @@ struct HoverInfo {
   std::optional Offset;
   /// Contains the padding following a field within the enclosing class.
   std::optional Padding;
+  /// Contains the alignment of fields and types where it's interesting.
+  std::optional Align;
   // Set when symbol is inside function call. Contains information extracted
   // from the callee definition about the argument this is passed as.
   std::optional CalleeArgInfo;

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 8c88cd52574536c..063a60db044060e 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -92,6 +92,7 @@ TEST(Hover, Structured) {
  HI.Offset = 0;
  HI.Size = 8;
  HI.Padding = 56;
+ HI.Align = 8;
  HI.AccessSpecifier = "private";
}},
   // Union field
@@ -110,6 +111,7 @@ TEST(Hover, Structured) {
  HI.Type = "char";
  HI.Size = 8;
  HI.Padding = 120;
+ HI.Align = 8;
  HI.AccessSpecifier = "public";
}},
   // Bitfield
@@ -128,6 +130,7 @@ TEST(Hover, Structured) {
  HI.Type = "int";
  HI.Offset = 0;
  HI.Size = 1;
+ HI.Align = 32;
  HI.AccessSpecifier = "public";
}},
   // Local to class method.
@@ -192,6 +195,7 @@ TEST(Hover, Structured) {
  HI.Type = "char";
  HI.Offset = 0;
  HI.Size = 8;
+ HI.Align = 8;
  HI.AccessSpecifier = "public";
}},
   // Struct definition shows size.
@@ -204,6 +208,7 @@ TEST(Hover, Structured) {
  HI.Kind = index::SymbolKind::Struct;
  HI.Definition = "struct X {}";
  HI.Size = 8;
+ HI.Align = 8;
}},
   // Variable with template type
   {R"cpp(
@@ -1375,6 +1380,7 @@ class Foo final {})cpp";
  HI.Offset = 8;
  HI.Size = 1;
  HI.Padding = 23;
+ HI.Align = 8;
  HI.AccessSpecifier = "public";
}}};
   for (const auto &Case : Cases) {
@@ -1411,6 +1417,7 @@ class Foo final {})cpp";
 EXPECT_EQ(H->Value, Expected.Value);
 EXPECT_EQ(H->Size, Expected.Size);
 EXPECT_EQ(H->Offset, Expected.Offset);
+EXPECT_EQ(H->Align, Expected.Align);
 EXPECT_EQ(H->AccessSpecifier, Expected.AccessSpecifier);
 EXPECT_EQ(H->CalleeArgInfo, Expected.CalleeArgInfo);
 EXPECT_EQ(H->CallPassType, Expected.CallPassType);
@@ -3448,13 +3455,14 @@ template  class Foo {})",
 HI.

[clang-tools-extra] [clangd] Show alignment for records and fields decls (PR #67213)

2023-10-22 Thread Vlad Serebrennikov via cfe-commits

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


[clang-tools-extra] [ConstantRange] Handle `Intrinsic::cttz` (PR #67917)

2023-10-22 Thread via cfe-commits

goldsteinn wrote:

LGTM.

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


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From ce62d3e1924b497b3e7160579a87557119c9e35d Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/4] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..052cf5f884f2773 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index ae849f59f90d3d9..d7cb51e1a0819a8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From 74b62efe15496e0024271fe93418f0963c8aedd0 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH] [clang] Improve _Alignas on declaration diagnostic

Adds `isAlignas()` method on `AttributeCommonInfo` which accounts for
C++ `alignas` as well as C11 `_Alignas`.

The method is used to improve diagnostic in C when `_Alignas` is used in
C at the wrong location.  This corrects the previously suggested move
of `_Alignas` past the declaration specifier, now warns attribute
`_Alignas` is ignored.
---
 clang/docs/ReleaseNotes.rst   |  5 
 .../include/clang/Basic/AttributeCommonInfo.h |  7 ++
 clang/lib/Sema/SemaDecl.cpp   | 24 ---
 clang/test/C/drs/dr4xx.c  |  2 +-
 clang/test/Parser/c1x-alignas.c   |  1 +
 clang/test/Parser/c2x-alignas.c   | 11 +
 clang/test/Parser/cxx0x-attributes.cpp|  2 ++
 7 files changed, 42 insertions(+), 10 deletions(-)
 create mode 100644 clang/test/Parser/c2x-alignas.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..860818b2e69e483 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -264,6 +264,11 @@ Attribute Changes in Clang
   supports but that are never the result of default argument promotion, such as
   ``float``. (`#59824: `_)
 
+- Clang now warns you that the ``_Alignas`` attribute on declaration specifiers
+  is ignored, changed from the former incorrect suggestion to move it past
+  declaration specifiers.
+
+
 Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 7dc05418498d0ae..8fb388b779c7308 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -192,6 +192,13 @@ class AttributeCommonInfo {
 
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
+  bool isAlignas() const {
+// In the current state of code, IsAlignas is only configured to return
+// true on C++ `alignas` keyword and alternate spellings, not `_Alignas`.
+// The following evaluation includes otherwise lost `_Alignas` information.
+return (getParsedKind() == AT_Aligned && isKeywordAttribute());
+  }
+
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
   /// attributes spelled with a keyword, like alignas.
   bool isStandardAttributeSyntax() const {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..a96cb7bcb53dc64 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5339,16 +5339,22 @@ Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, 
AccessSpecifier AS,
 TypeSpecType == DeclSpec::TST_interface ||
 TypeSpecType == DeclSpec::TST_union ||
 TypeSpecType == DeclSpec::TST_enum) {
-  for (const ParsedAttr &AL : DS.getAttributes())
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
-<< AL << GetDiagnosticTypeSpecifierID(DS);
-  for (const ParsedAttr &AL : DeclAttrs)
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
+
+  auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
+unsigned DiagnosticId;
+if (AL.isAlignas() && !getLangOpts().CPlusPlus) {
+  DiagnosticId = diag::warn_attribute_ignored;
+} else if (AL.isRegularKeywordAttribute()) {
+  DiagnosticId = diag::err_declspec_keyword_has_no_effect;
+} else {
+  DiagnosticId = diag::warn_declspec_attribute_ignored;
+}
+Diag(AL.getLoc(), DiagnosticId)
 << AL << GetDiagnosticTypeSpecifierID(DS);
+  };
+
+  llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
+  llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
 }
   }
 
diff --git a/clang/test/C/drs/dr4xx.c b/clang/test/C/drs/dr4xx.c
index b8ccceaad12c59f..d4d212d680862a4 100644
--- a/clang/test/C/drs/dr4xx.c
+++ b/clang/test/C/drs/dr4xx.c
@@ -168,7 +168,7 @@ void dr444(void) {
   * where the diagnostic recommends causes a different, more inscrutable error
   * about anonymous structures.
   */
-  _Alignas(int) struct T { /* expected-warning {{attribute '_Alignas' is 
ignored, place it after "struct" to apply attribute to type declaration}} */
+  _Alignas(int) struct T { /* expected-war

[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From 1948d226de16bda2899ca562276370d20ceba236 Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/4] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index be813bde8be41ea..a93e97348606f28 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index d849649c96a0d13..4443ffd09293881 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread via cfe-commits
=?utf-8?q?Gábor?= Spaits
Message-ID:
In-Reply-To: 


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 ce8b8b1639bc9592d2db291db4bb289b0434de26 
1042ac6fdde192aa7fa1a74f707a4fede9861b38 -- 
clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h 
clang/test/Analysis/std-variant-checker.cpp 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
clang/test/Analysis/Inputs/system-header-simulator-cxx.h 
clang/test/Analysis/diagnostics/explicit-suppression.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 3aa27fd1d..653ab446f 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -455,7 +455,7 @@ public:
   /// If the call returns a C++ record type then the region of its return value
   /// can be retrieved from its construction context.
   std::optional getReturnValueUnderConstruction() const;
-  
+
   // Returns the CallEvent representing the caller of this function
   const CallEventRef<> getCaller() const;
 

``




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


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From 1948d226de16bda2899ca562276370d20ceba236 Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/5] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index be813bde8be41ea..a93e97348606f28 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index d849649c96a0d13..4443ffd09293881 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From 1948d226de16bda2899ca562276370d20ceba236 Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH 1/6] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index be813bde8be41ea..a93e97348606f28 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index d849649c96a0d13..4443ffd09293881 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallE

[clang] Added removal of file extension when guessing the toolchain (PR #69887)

2023-10-22 Thread via cfe-commits

https://github.com/Overhatted created 
https://github.com/llvm/llvm-project/pull/69887

I'm using Buck2 to create the compile_commands.json and since it uses a cl.bat 
wrapper around cl.exe, that's what shows up in the compile_commands.json. Of 
course Buck2 could be changed to create a compile_commands.json with the cl.exe 
path but I think this change to clang is better.

Please let me know what you think.

>From 29715f3a97f077d1a8aaf2042de91ac08d6cc1a9 Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Sun, 22 Oct 2023 18:59:46 +0100
Subject: [PATCH] Added removal of file extension when guessing the toolchain

---
 clang/lib/Driver/ToolChain.cpp   |  7 ---
 clang/unittests/Driver/ToolChainTest.cpp | 12 
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index ab19166f18c2dcf..c8bb6ffe0a9bc7d 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -345,10 +345,11 @@ static const DriverSuffix *parseDriverSuffix(StringRef 
ProgName, size_t &Pos) {
   // added via -target as implicit first argument.
   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
 
-  if (!DS && ProgName.endswith(".exe")) {
-// Try again after stripping the executable suffix:
+  if (!DS) {
+// Try again after stripping the file extension suffix:
 // clang++.exe -> clang++
-ProgName = ProgName.drop_back(StringRef(".exe").size());
+// cl.bat -> cl
+ProgName = ProgName.slice(0, ProgName.find('.'));
 DS = FindDriverSuffix(ProgName, Pos);
   }
 
diff --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index acbbb87390d5e9a..f193706adf2cd2d 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -509,6 +509,18 @@ TEST(ToolChainTest, GetTargetAndMode) {
   EXPECT_TRUE(Res.ModeSuffix == "clang-dxc");
   EXPECT_STREQ(Res.DriverMode, "--driver-mode=dxc");
   EXPECT_FALSE(Res.TargetIsValid);
+
+  Res = ToolChain::getTargetAndModeFromProgramName("cl.exe");
+  EXPECT_TRUE(Res.TargetPrefix.empty());
+  EXPECT_TRUE(Res.ModeSuffix == "cl");
+  EXPECT_STREQ(Res.DriverMode, "--driver-mode=cl");
+  EXPECT_FALSE(Res.TargetIsValid);
+
+  Res = ToolChain::getTargetAndModeFromProgramName("cl.bat");
+  EXPECT_TRUE(Res.TargetPrefix.empty());
+  EXPECT_TRUE(Res.ModeSuffix == "cl");
+  EXPECT_STREQ(Res.DriverMode, "--driver-mode=cl");
+  EXPECT_FALSE(Res.TargetIsValid);
 }
 
 TEST(ToolChainTest, CommandOutput) {

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


[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Björn Schäpers via cfe-commits


@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&

HazardyKnusperkeks wrote:

Thanks.

And the test doesn't need to be changed?

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-22 Thread Björn Schäpers via cfe-commits

https://github.com/HazardyKnusperkeks updated 
https://github.com/llvm/llvm-project/pull/68743

From 2efda4c7d5e99b3506a874d514adcb16fe46adce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Tue, 10 Oct 2023 22:50:43 +0200
Subject: [PATCH] [clang-format] Don't align comments over scopes

We now stop aligning trailing comments on all closing braces, for
classes etc. we even check for the semicolon between the comment and the
brace.

Fixes #67906.
---
 clang/lib/Format/WhitespaceManager.cpp|  53 +-
 clang/unittests/Format/FormatTestComments.cpp | 161 --
 2 files changed, 193 insertions(+), 21 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index dc81060671c1712..d4d66f0a9b2ab95 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1048,6 +1048,9 @@ void WhitespaceManager::alignChainedConditionals() {
 }
 
 void WhitespaceManager::alignTrailingComments() {
+  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
+return;
+
   const int Size = Changes.size();
   int MinColumn = 0;
   int StartOfSequence = 0;
@@ -1118,16 +1121,48 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+auto DontAlignThisComment = [](const auto *Tok) {
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->is(tok::r_paren)) {
+// Back up past the parentheses and a `TT_DoWhile` that may precede.
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+if (Tok->is(TT_DoWhile)) {
+  const auto *Prev = Tok->getPreviousNonComment();
+  if (!Prev) {
+// A do-while-loop without braces.
+return true;
+  }
+  Tok = Prev;
+}
+  }
+
+  if (Tok->isNot(tok::r_brace))
+return false;
+
+  while (Tok->Previous && Tok->Previous->is(tok::r_brace))
+Tok = Tok->Previous;
+  return Tok->NewlinesBefore > 0;
+};
+
+if (I > 0 && C.NewlinesBefore == 0 &&
+DontAlignThisComment(Changes[I - 1].Tok)) {
   alignTrailingComments(StartOfSequence, I, MinColumn);
-  MinColumn = ChangeMinColumn;
-  MaxColumn = ChangeMinColumn;
-  StartOfSequence = I;
+  // Reset to initial values, but skip this change for the next alignment
+  // pass.
+  MinColumn = 0;
+  MaxColumn = INT_MAX;
+  StartOfSequence = I + 1;
 } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
(ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
// Break the comment sequence if the previous line did not end
diff --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 1198329b7b5a8f0..1e3ed1f0783130a 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -182,7 +182,7 @@ TEST_F(FormatTestComments, UnderstandsSingleLineComments) {
"int   a; // This is unrelated"));
   EXPECT_EQ("class C {\n"
 "  void f() { // This does something ..\n"
-"  }  // awesome..\n"
+"  } // awesome..\n"
 "\n"
 "  int a; // This is unrelated\n"
 "};",
@@ -3102,7 +3102,8 @@ TEST_F(FormatTestComments, DontAlignNamespaceComments) {
   StringRef Input = "namespace A {\n"
 "  TESTSUITE(B) {\n"
 "namespace C {\n"
-"  namespace D {} // namespace D\n"
+"  namespace D { //\n"
+"  } // namespace D\n"
 "  std::string Foo = Bar; // Comment\n"
 "  std::string BazString = Baz;   // C2\n"
 "}  // namespace C\n"
@@ -3114,7 +3115,8 @@ TEST_F(FormatTestComments, DontAlignNamespaceComments) {
   verifyFormat("namespace A {\n"
"  TESTSUITE(B) {\n"
"namespace C {\n"
-   "  namespace D {} // namespace D\n"
+   "  namespace D { //\n"
+   "  } // namespace D\n"
"  std::string Foo = Bar;   // Comment\n"
"  std::string BazString = Baz; // C2\n"
"} // namespace C\n"
@@ -3126,7 +3128,8 @@ TES

[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-22 Thread Björn Schäpers via cfe-commits


@@ -1118,16 +1121,48 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+auto DontAlignThisComment = [](const auto *Tok) {
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->is(tok::r_paren)) {
+// Back up past the parentheses and a `TT_DoWhile` that may precede.
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+if (Tok->is(TT_DoWhile)) {
+  auto Prev = Tok->getPreviousNonComment();
+  if (!Prev) {
+// A do-while-loop without braces.
+return Tok->NewlinesBefore > 0;
+  }

HazardyKnusperkeks wrote:

I did keep the comment.

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


[clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2023-10-22 Thread via cfe-commits

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From 919be6b69cf12e5d9dd9f74a4570ea0a87c9a265 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH] [clang] Improve _Alignas on declaration diagnostic

Adds `isAlignas()` method on `AttributeCommonInfo` which accounts for
C++ `alignas` as well as C11 `_Alignas`.

The method is used to improve diagnostic in C when `_Alignas` is used in
C at the wrong location.  This corrects the previously suggested move
of `_Alignas` past the declaration specifier, now warns attribute
`_Alignas` is ignored.
---
 clang/docs/ReleaseNotes.rst   |  5 
 .../include/clang/Basic/AttributeCommonInfo.h |  7 ++
 clang/lib/Sema/SemaDecl.cpp   | 24 ---
 clang/test/C/drs/dr4xx.c  |  6 +
 clang/test/Parser/c1x-alignas.c   |  1 +
 clang/test/Parser/c2x-alignas.c   | 11 +
 clang/test/Parser/cxx0x-attributes.cpp|  2 ++
 7 files changed, 42 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/Parser/c2x-alignas.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..860818b2e69e483 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -264,6 +264,11 @@ Attribute Changes in Clang
   supports but that are never the result of default argument promotion, such as
   ``float``. (`#59824: `_)
 
+- Clang now warns you that the ``_Alignas`` attribute on declaration specifiers
+  is ignored, changed from the former incorrect suggestion to move it past
+  declaration specifiers.
+
+
 Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 7dc05418498d0ae..8fb388b779c7308 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -192,6 +192,13 @@ class AttributeCommonInfo {
 
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
+  bool isAlignas() const {
+// In the current state of code, IsAlignas is only configured to return
+// true on C++ `alignas` keyword and alternate spellings, not `_Alignas`.
+// The following evaluation includes otherwise lost `_Alignas` information.
+return (getParsedKind() == AT_Aligned && isKeywordAttribute());
+  }
+
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
   /// attributes spelled with a keyword, like alignas.
   bool isStandardAttributeSyntax() const {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..a96cb7bcb53dc64 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5339,16 +5339,22 @@ Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, 
AccessSpecifier AS,
 TypeSpecType == DeclSpec::TST_interface ||
 TypeSpecType == DeclSpec::TST_union ||
 TypeSpecType == DeclSpec::TST_enum) {
-  for (const ParsedAttr &AL : DS.getAttributes())
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
-<< AL << GetDiagnosticTypeSpecifierID(DS);
-  for (const ParsedAttr &AL : DeclAttrs)
-Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
-  ? diag::err_declspec_keyword_has_no_effect
-  : diag::warn_declspec_attribute_ignored)
+
+  auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
+unsigned DiagnosticId;
+if (AL.isAlignas() && !getLangOpts().CPlusPlus) {
+  DiagnosticId = diag::warn_attribute_ignored;
+} else if (AL.isRegularKeywordAttribute()) {
+  DiagnosticId = diag::err_declspec_keyword_has_no_effect;
+} else {
+  DiagnosticId = diag::warn_declspec_attribute_ignored;
+}
+Diag(AL.getLoc(), DiagnosticId)
 << AL << GetDiagnosticTypeSpecifierID(DS);
+  };
+
+  llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
+  llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
 }
   }
 
diff --git a/clang/test/C/drs/dr4xx.c b/clang/test/C/drs/dr4xx.c
index b8ccceaad12c59f..30145dcfeef1686 100644
--- a/clang/test/C/drs/dr4xx.c
+++ b/clang/test/C/drs/dr4xx.c
@@ -164,11 +164,7 @@ void dr444(void) {
   /* FIXME: This should be accepted as per this DR. */
   int j = (_Alignas(int) int){12}; /* expected-error {{expected expression}} */
 
- /* FIXME: The diagnostic in this case is really bad; moving the specifier to
-  * where the diagnostic recommends causes a different, more inscrutable error
-  * about a

[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-22 Thread Jerin Philip via cfe-commits

jerinphilip wrote:

I have rebased the PR with main (which appears to fix the formatting workflow). 
For the time being, I have left the C23 test using `alignas` in with the active 
error message and a `FIXME`.

I've altered the state of this PR to be close to 
[D141177](https://reviews.llvm.org/D141177), using the existing attribute 
warning for reduced complexity (happy to provide attribution). Key difference 
`isAlignas` instead of `isC23AlignasAttribute()`, thinking the former should be 
more future-proof. In the current state, `isCXX11Attribute()` and 
`isStandardAttributeSyntax()` is not modified, and the net improvement (in 
diagnostics) in changes here should be useful when C23 `alignas` comes in, I 
hope.

The following routes were also considered:

1. Store `tok::TokenKind` to resolve `_Alignas` vs `alignas`. This requires 
adding one more field to `Form` and `AttributeCommonInfo`, while the 
information is already present via (`IsAlignas`, `SpellingIndex`) tuple (This 
approach is in 
[jerinphilip/llvm-project#1](https://github.com/jerinphilip/llvm-project/pull/1)
 mixed with other things). 
2. Use `calculateAttributeSpellingIndex` (also discussed in meeting). This 
suffers from inability to use `AlignedAttr::Keyword_Alignas` 
(`clang/AST/Attrs.h`) - See [#65638 
(comment)](https://github.com/llvm/llvm-project/pull/65638#discussion_r1367880789).
 Absent this, the `SpellingIndex` value `5` (`Keyword_Alignas`) will have to be 
maintained separately here to resolve `_Alignas`. Looking at the source 
requires string operations, which are inefficient.

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


[clang-tools-extra] Fix #68492: point to the correct const location (PR #69103)

2023-10-22 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69103

>From 354a8e4034afd82e6ea854848a86b9011e26269b Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Fri, 13 Oct 2023 19:27:15 +0100
Subject: [PATCH 1/4] Fix #68492: point to the correct const location

---
 .../readability/AvoidConstParamsInDecls.cpp   | 43 ---
 .../avoid-const-params-in-decls.cpp   | 14 +++---
 2 files changed, 34 insertions(+), 23 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp 
b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
index 6476f1d7fdf2b81..24cbbd8bc60a2b5 100644
--- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
+++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
@@ -21,6 +21,24 @@ SourceRange getTypeRange(const ParmVarDecl &Param) {
   return {Param.getBeginLoc(), Param.getLocation().getLocWithOffset(-1)};
 }
 
+// Finds the location of the qualifying `const` token in the `ParmValDecl`'s
+// return type. Returns `std::nullopt` when the parm type is not
+// `const`-qualified like when the type is an alias or a macro.
+static std::optional
+findConstToRemove(const ParmVarDecl &Param,
+  const MatchFinder::MatchResult &Result) {
+
+  CharSourceRange FileRange = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(getTypeRange(Param)),
+  *Result.SourceManager, Result.Context->getLangOpts());
+
+  if (FileRange.isInvalid())
+return std::nullopt;
+
+  return tidy::utils::lexer::getQualifyingToken(
+  tok::kw_const, FileRange, *Result.Context, *Result.SourceManager);
+}
+
 } // namespace
 
 void AvoidConstParamsInDecls::storeOptions(ClangTidyOptions::OptionMap &Opts) {
@@ -30,11 +48,10 @@ void 
AvoidConstParamsInDecls::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 void AvoidConstParamsInDecls::registerMatchers(MatchFinder *Finder) {
   const auto ConstParamDecl =
   parmVarDecl(hasType(qualType(isConstQualified(.bind("param");
-  Finder->addMatcher(
-  functionDecl(unless(isDefinition()),
-   has(typeLoc(forEach(ConstParamDecl
-  .bind("func"),
-  this);
+  Finder->addMatcher(functionDecl(unless(isDefinition()),
+  has(typeLoc(forEach(ConstParamDecl
+ .bind("func"),
+ this);
 }
 
 void AvoidConstParamsInDecls::check(const MatchFinder::MatchResult &Result) {
@@ -50,7 +67,10 @@ void AvoidConstParamsInDecls::check(const 
MatchFinder::MatchResult &Result) {
 return;
   }
 
-  auto Diag = diag(Param->getBeginLoc(),
+  const auto Tok = findConstToRemove(*Param, Result);
+  const auto ConstLocation = Tok ? Tok->getLocation() : Param->getBeginLoc();
+
+  auto Diag = diag(ConstLocation,
"parameter %0 is const-qualified in the function "
"declaration; const-qualification of parameters only has an 
"
"effect in function definitions");
@@ -70,18 +90,9 @@ void AvoidConstParamsInDecls::check(const 
MatchFinder::MatchResult &Result) {
 // from a macro.
 return;
   }
-
-  CharSourceRange FileRange = Lexer::makeFileCharRange(
-  CharSourceRange::getTokenRange(getTypeRange(*Param)),
-  *Result.SourceManager, getLangOpts());
-
-  if (!FileRange.isValid())
-return;
-
-  auto Tok = tidy::utils::lexer::getQualifyingToken(
-  tok::kw_const, FileRange, *Result.Context, *Result.SourceManager);
   if (!Tok)
 return;
+
   Diag << FixItHint::CreateRemoval(
   CharSourceRange::getTokenRange(Tok->getLocation(), Tok->getLocation()));
 }
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
index d521fd238b7d521..bc098efe3044a5d 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
@@ -9,15 +9,15 @@ void F1(const int i);
 // CHECK-FIXES: void F1(int i);
 
 void F2(const int *const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F2(const int *i);
 
 void F3(int const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:13: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F3(int i);
 
 void F4(alias_type const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F4(alias_type i);
 
 void F5(const int);
@@ -25,7 +25,7 @@ void F5(const int);
 // CHECK-FIXES: void F5(int);
 
 void F6(const int *const);
-// CHECK-MESSAGES: :[[@LIN

[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread via cfe-commits


@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.

Da-Viper wrote:

Would it be preferred to make this an option ? 

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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69102

>From 21156656433fb8d2dc5a805d97cbd20fa916fff9 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 15 Oct 2023 11:39:42 +0100
Subject: [PATCH 1/3] Fix #35272: Don't replace typedefs in extern c scope

---
 .../clang-tidy/modernize/UseUsingCheck.cpp   | 16 
 .../clang-tidy/checkers/modernize/use-using.cpp  | 14 ++
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index e6293ed48bfddbb..841ffb4c9bfe66e 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -11,6 +11,12 @@
 #include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
+namespace {
+
+AST_MATCHER(clang::LinkageSpecDecl, isExternCLinkage) {
+  return Node.getLanguage() == clang::LinkageSpecDecl::lang_c;
+}
+} // namespace
 
 namespace clang::tidy::modernize {
 
@@ -27,10 +33,12 @@ void 
UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(typedefDecl(unless(isInstantiated()),
- hasParent(decl().bind(ParentDeclName)))
- .bind(TypedefName),
- this);
+  Finder->addMatcher(
+  typedefDecl(unless(anyOf(isInstantiated(), hasAncestor(linkageSpecDecl(
+ isExternCLinkage(),
+  hasParent(decl().bind(ParentDeclName)))
+  .bind(TypedefName),
+  this);
 
   // This matcher is used to find tag declarations in source code within
   // typedefs. They appear in the AST just *prior* to the typedefs.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 422abee11a71962..0f8f14502d5ca3c 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -325,3 +325,17 @@ typedef bool (*ISSUE_65055_2)(int);
 typedef class ISSUE_67529_1 *ISSUE_67529;
 // CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
 // CHECK-FIXES: using ISSUE_67529 = class ISSUE_67529_1 *;
+
+// Some Header
+extern "C" {
+
+typedef int InExternC;
+}
+
+extern "C++" {
+
+typedef int InExternCPP;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef' 
[modernize-use-using]
+// CHECK-FIXES: using InExternCPP = int;
+
+}

>From 521dec9325285d1e1819a8bee1bd20eadb7c4158 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Mon, 16 Oct 2023 23:26:25 +0100
Subject: [PATCH 2/3] Add: Update docs with the new changes. Update
 ReleaseNotes.rst with the changes made

---
 clang-tools-extra/docs/ReleaseNotes.rst  | 5 +
 .../docs/clang-tidy/checks/modernize/use-using.rst   | 9 +
 2 files changed, 14 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c1b926b296b055a..af6b20369c9dcff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -285,6 +285,10 @@ Changes in existing checks
   ` check to fix function pointer and
   forward declared ``typedef`` correctly.
 
+- Improved :doc:`modernize-use-using
+  ` by ignoring ``typedef`` declaration 
in
+  ``extern "C"`` scope.
+
 - Improved :doc:`performance-faster-string-find
   ` check to properly escape
   single quotes.
@@ -325,6 +329,7 @@ Changes in existing checks
   identify calls to static member functions with out-of-class inline 
definitions.
 
 
+
 Removed checks
 ^^
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
index eeddaf8d8d65abe..048fc26617b7b73 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.
+
+.. code-block:: c++
+
+  extern "C" {
+
+typedef int InExternC; // Left intact.
+  }
+
 This check requires using C++11 or higher to run.
 
 Options

>From 3426e0a36606a7e3eeb38c0f436c25aa2fde2b36 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 22 Oct 2023 20:02:20 +0100
Subject: [PATCH 3/3] Update: commit with review requested changes

---
 clang-tools-extra/docs/ReleaseNotes.rst | 6 +-
 .../docs/clang-tidy/checks/modernize/use-using.rst  | 2 --
 2 files changed, 1 insertion(+), 7 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index

[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread via cfe-commits


@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.
+
+.. code-block:: c++
+
+  extern "C" {
+

Da-Viper wrote:

done

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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread via cfe-commits


@@ -285,6 +285,10 @@ Changes in existing checks
   ` check to fix function pointer and
   forward declared ``typedef`` correctly.
 
+- Improved :doc:`modernize-use-using

Da-Viper wrote:

done

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-22 Thread Utkarsh Saxena via cfe-commits


@@ -960,18 +960,13 @@ static bool shouldAddReversedEqEq(Sema &S, SourceLocation 
OpLoc,
 return true;
   }
   // Otherwise the search scope is the namespace scope of which F is a member.
-  LookupResult NonMembers(S, NotEqOp, OpLoc,
-  Sema::LookupNameKind::LookupOperatorName);
-  S.LookupName(NonMembers,
-   S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
-  NonMembers.suppressAccessDiagnostics();
-  for (NamedDecl *Op : NonMembers) {
-auto *FD = Op->getAsFunction();
-if(auto* UD = dyn_cast(Op))
-  FD = UD->getUnderlyingDecl()->getAsFunction();
-if (FunctionsCorrespond(S.Context, EqFD, FD) &&
-declaresSameEntity(cast(EqFD->getDeclContext()),
-   cast(Op->getDeclContext(
+  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
+auto *NotEqFD = Op->getAsFunction();
+if (auto *UD = dyn_cast(Op))
+  NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
+if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) &&
+declaresSameEntity(cast(EqFD->getEnclosingNamespaceContext()),
+   cast(Op->getLexicalDeclContext(

usx95 wrote:

I do not think we have to follow ADL rules here. We only have to lookup in the 
NS. For visibility, `isVisible()` should suffice. Rest of the involved 
visibility rules are specific to ADL and should not concern the lookup for !=.

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-22 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/68922

>From 8aa439a97a56ef80bfc9ccc90a9f093680e455f5 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Sun, 22 Oct 2023 11:11:53 +0200
Subject: [PATCH 1/2] rebase...

---
 clang/docs/ReleaseNotes.rst   |  4 +
 clang/lib/Sema/SemaOverload.cpp   | 19 ++---
 .../over.match.oper/p3-2a.cpp | 78 +++
 3 files changed, 89 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..cef857244387e8b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -85,6 +85,10 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
+- Fixed a bug in finding matching `operator!=` while adding reversed 
`operator==` as
+  outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
+  Fixes (`#68901: `_).
+
 C++ Specific Potentially Breaking Changes
 -
 - The name mangling rules for function templates has been changed to take into
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d57a7ad8f46859a..75e4184c8aa6cb8 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -960,18 +960,13 @@ static bool shouldAddReversedEqEq(Sema &S, SourceLocation 
OpLoc,
 return true;
   }
   // Otherwise the search scope is the namespace scope of which F is a member.
-  LookupResult NonMembers(S, NotEqOp, OpLoc,
-  Sema::LookupNameKind::LookupOperatorName);
-  S.LookupName(NonMembers,
-   S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
-  NonMembers.suppressAccessDiagnostics();
-  for (NamedDecl *Op : NonMembers) {
-auto *FD = Op->getAsFunction();
-if(auto* UD = dyn_cast(Op))
-  FD = UD->getUnderlyingDecl()->getAsFunction();
-if (FunctionsCorrespond(S.Context, EqFD, FD) &&
-declaresSameEntity(cast(EqFD->getDeclContext()),
-   cast(Op->getDeclContext(
+  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
+auto *NotEqFD = Op->getAsFunction();
+if (auto *UD = dyn_cast(Op))
+  NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
+if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) &&
+declaresSameEntity(cast(EqFD->getEnclosingNamespaceContext()),
+   cast(Op->getLexicalDeclContext(
   return false;
   }
   return true;
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5727d506fe5e61d..9dc5ee8db565341 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -374,6 +374,84 @@ bool fine(A a, B b) { return a == b; } // Ok. Found a 
matching operator!=.
 }
 }
 
+
+namespace ADL_GH68901{
+namespace A {
+struct S {};
+bool operator==(S, int); // expected-note {{no known conversion from 'int' to 
'S' for 1st argument}}
+bool operator!=(S, int);
+} // namespace A
+bool a = 0 == A::S(); // expected-error {{invalid operands to binary 
expression ('int' and 'A::S')}}
+
+namespace B {
+struct Derived {};
+struct Base : Derived {};
+
+bool operator==(Derived& a, Base& b);
+bool operator!=(Derived& a, Base& b);
+}  // namespace B
+
+void foo() {
+  // B::Base{} == B::Base{};
+  B::Base a,b;
+  bool v = a == b;
+}
+
+namespace ns {
+template 
+struct A {
+};
+
+template 
+struct B : A {
+};
+
+template  bool operator == (B, A); // expected-note {{candidate 
template ignored: could not match 'B' against 'A'}}
+template  bool operator != (B, A);
+}
+
+void test() {
+ns::A a;
+ns::B b;
+a == b; // expected-error {{invalid operands to binary expression}}
+}
+
+
+} //namespace ADL_GH68901
+
+namespace function_scope_operator_eqeq {
+// For non-members, we always lookup for matching operator!= in the namespace 
scope of
+// operator== (and not in the scope of operator==).
+struct X { operator int(); };
+namespace test1{
+bool h(X x) {
+  bool operator==(X, int); // expected-note {{reversed}}
+  return x == x; // expected-warning {{ambiguous}}
+}
+
+bool g(X x) {
+  bool operator==(X, int); // expected-note {{reversed}}
+  bool operator!=(X, int);
+  return x == x;  // expected-warning {{ambiguous}}
+}
+} // namespace test1
+
+namespace test2 {
+bool operator!=(X, int);
+
+bool h(X x) {
+  bool operator==(X, int);
+  return x == x;
+}
+
+bool i(X x) {
+  bool operator==(X, int);
+  bool operator!=(X, int);
+  return x == x;
+}
+} // namespace test2
+} // namespace function_scope_operator_eqeq
+
 namespace non_member_

[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread Piotr Zegar via cfe-commits


@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.

PiotrZSL wrote:

I think so, for example I would like to enable this for my projects.
Ignoring extern "C" makes only sense if same header is compile in C and C++ 
mode.
If header is compiled only in C++ mode, but uses extern "C" simply to properly 
handle symbols mangling, then there is no need to ignore such typedefs.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-22 Thread Owen Pan via cfe-commits

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


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


[clang] [Driver] Hook up Haiku PowerPC support (PR #69134)

2023-10-22 Thread Fangrui Song via cfe-commits

MaskRay wrote:

It seems that there is no usable Haiku kernel: 
https://www.haiku-os.org/guides/building/port_status/ Then we shouldn't add 
this?

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


[clang] [Clang][LTO][GISel] Propagate `-fglobal-siel` to LTO (PR #69747)

2023-10-22 Thread Fangrui Song via cfe-commits

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


[clang] [Clang][LTO][GISel] Propagate `-fglobal-siel` to LTO (PR #69747)

2023-10-22 Thread Fangrui Song via cfe-commits


@@ -694,6 +694,16 @@ void tools::addLTOOptions(const ToolChain &ToolChain, 
const ArgList &Args,
 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
  ParallelismOpt + Parallelism));
 
+  // Pass down GlobalISel options.
+  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
+   options::OPT_fno_global_isel)) {
+// Parsing -fno-global-isel explicitly gives architectures that enable 
GISel
+// by default (e.g. AArch64) a chance to disable it.

MaskRay wrote:

"e.g. AArch64" in "architectures that enable GISel by default (e.g. AArch64)" 
is not accurate. It's the default for -O0 and not for some code models. Perhaps 
just omit the "e.g." part.



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


[clang] [Clang][LTO][GISel] Propagate `-fglobal-siel` to LTO (PR #69747)

2023-10-22 Thread Fangrui Song via cfe-commits

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


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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-22 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69102

>From 21156656433fb8d2dc5a805d97cbd20fa916fff9 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 15 Oct 2023 11:39:42 +0100
Subject: [PATCH 1/3] Fix #35272: Don't replace typedefs in extern c scope

---
 .../clang-tidy/modernize/UseUsingCheck.cpp   | 16 
 .../clang-tidy/checkers/modernize/use-using.cpp  | 14 ++
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index e6293ed48bfddbb..841ffb4c9bfe66e 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -11,6 +11,12 @@
 #include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
+namespace {
+
+AST_MATCHER(clang::LinkageSpecDecl, isExternCLinkage) {
+  return Node.getLanguage() == clang::LinkageSpecDecl::lang_c;
+}
+} // namespace
 
 namespace clang::tidy::modernize {
 
@@ -27,10 +33,12 @@ void 
UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(typedefDecl(unless(isInstantiated()),
- hasParent(decl().bind(ParentDeclName)))
- .bind(TypedefName),
- this);
+  Finder->addMatcher(
+  typedefDecl(unless(anyOf(isInstantiated(), hasAncestor(linkageSpecDecl(
+ isExternCLinkage(),
+  hasParent(decl().bind(ParentDeclName)))
+  .bind(TypedefName),
+  this);
 
   // This matcher is used to find tag declarations in source code within
   // typedefs. They appear in the AST just *prior* to the typedefs.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 422abee11a71962..0f8f14502d5ca3c 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -325,3 +325,17 @@ typedef bool (*ISSUE_65055_2)(int);
 typedef class ISSUE_67529_1 *ISSUE_67529;
 // CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
 // CHECK-FIXES: using ISSUE_67529 = class ISSUE_67529_1 *;
+
+// Some Header
+extern "C" {
+
+typedef int InExternC;
+}
+
+extern "C++" {
+
+typedef int InExternCPP;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef' 
[modernize-use-using]
+// CHECK-FIXES: using InExternCPP = int;
+
+}

>From 521dec9325285d1e1819a8bee1bd20eadb7c4158 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Mon, 16 Oct 2023 23:26:25 +0100
Subject: [PATCH 2/3] Add: Update docs with the new changes. Update
 ReleaseNotes.rst with the changes made

---
 clang-tools-extra/docs/ReleaseNotes.rst  | 5 +
 .../docs/clang-tidy/checks/modernize/use-using.rst   | 9 +
 2 files changed, 14 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c1b926b296b055a..af6b20369c9dcff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -285,6 +285,10 @@ Changes in existing checks
   ` check to fix function pointer and
   forward declared ``typedef`` correctly.
 
+- Improved :doc:`modernize-use-using
+  ` by ignoring ``typedef`` declaration 
in
+  ``extern "C"`` scope.
+
 - Improved :doc:`performance-faster-string-find
   ` check to properly escape
   single quotes.
@@ -325,6 +329,7 @@ Changes in existing checks
   identify calls to static member functions with out-of-class inline 
definitions.
 
 
+
 Removed checks
 ^^
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
index eeddaf8d8d65abe..048fc26617b7b73 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.
+
+.. code-block:: c++
+
+  extern "C" {
+
+typedef int InExternC; // Left intact.
+  }
+
 This check requires using C++11 or higher to run.
 
 Options

>From 3426e0a36606a7e3eeb38c0f436c25aa2fde2b36 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 22 Oct 2023 20:02:20 +0100
Subject: [PATCH 3/3] Update: commit with review requested changes

---
 clang-tools-extra/docs/ReleaseNotes.rst | 6 +-
 .../docs/clang-tidy/checks/modernize/use-using.rst  | 2 --
 2 files changed, 1 insertion(+), 7 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index

[clang-tools-extra] Fix #41439: Update the documentation with the correct information. (PR #69377)

2023-10-22 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69377

>From 0e0a3e7ad1a0a7098e05a5164413369eaa58c55b Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Tue, 17 Oct 2023 20:49:47 +0100
Subject: [PATCH] Fix #41439: Update the documentation with the correct
 information.

---
 .../clang-tidy/checks/readability/named-parameter.rst| 9 +++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/readability/named-parameter.rst 
b/clang-tools-extra/docs/clang-tidy/checks/readability/named-parameter.rst
index 8d28c0aa02169a7..7e7099b3df251d1 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/readability/named-parameter.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability/named-parameter.rst
@@ -10,7 +10,12 @@ Guide:
 
 
https://google.github.io/styleguide/cppguide.html#Function_Declarations_and_Definitions
 
-All parameters should be named, with identical names in the declaration and
-implementation.
+A parameter name may be omitted only if the parameter is not used in the
+function's definition.
+
+.. code-block:: c++
+int doingSomething(int a, int b, int) {  // Ok: the third paramet is not used
+return a + b;
+}
 
 Corresponding cpplint.py check name: `readability/function`.

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


[clang-tools-extra] Fix #68492: point to the correct const location (PR #69103)

2023-10-22 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69103

>From 354a8e4034afd82e6ea854848a86b9011e26269b Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Fri, 13 Oct 2023 19:27:15 +0100
Subject: [PATCH 1/4] Fix #68492: point to the correct const location

---
 .../readability/AvoidConstParamsInDecls.cpp   | 43 ---
 .../avoid-const-params-in-decls.cpp   | 14 +++---
 2 files changed, 34 insertions(+), 23 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp 
b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
index 6476f1d7fdf2b81..24cbbd8bc60a2b5 100644
--- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
+++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
@@ -21,6 +21,24 @@ SourceRange getTypeRange(const ParmVarDecl &Param) {
   return {Param.getBeginLoc(), Param.getLocation().getLocWithOffset(-1)};
 }
 
+// Finds the location of the qualifying `const` token in the `ParmValDecl`'s
+// return type. Returns `std::nullopt` when the parm type is not
+// `const`-qualified like when the type is an alias or a macro.
+static std::optional
+findConstToRemove(const ParmVarDecl &Param,
+  const MatchFinder::MatchResult &Result) {
+
+  CharSourceRange FileRange = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(getTypeRange(Param)),
+  *Result.SourceManager, Result.Context->getLangOpts());
+
+  if (FileRange.isInvalid())
+return std::nullopt;
+
+  return tidy::utils::lexer::getQualifyingToken(
+  tok::kw_const, FileRange, *Result.Context, *Result.SourceManager);
+}
+
 } // namespace
 
 void AvoidConstParamsInDecls::storeOptions(ClangTidyOptions::OptionMap &Opts) {
@@ -30,11 +48,10 @@ void 
AvoidConstParamsInDecls::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 void AvoidConstParamsInDecls::registerMatchers(MatchFinder *Finder) {
   const auto ConstParamDecl =
   parmVarDecl(hasType(qualType(isConstQualified(.bind("param");
-  Finder->addMatcher(
-  functionDecl(unless(isDefinition()),
-   has(typeLoc(forEach(ConstParamDecl
-  .bind("func"),
-  this);
+  Finder->addMatcher(functionDecl(unless(isDefinition()),
+  has(typeLoc(forEach(ConstParamDecl
+ .bind("func"),
+ this);
 }
 
 void AvoidConstParamsInDecls::check(const MatchFinder::MatchResult &Result) {
@@ -50,7 +67,10 @@ void AvoidConstParamsInDecls::check(const 
MatchFinder::MatchResult &Result) {
 return;
   }
 
-  auto Diag = diag(Param->getBeginLoc(),
+  const auto Tok = findConstToRemove(*Param, Result);
+  const auto ConstLocation = Tok ? Tok->getLocation() : Param->getBeginLoc();
+
+  auto Diag = diag(ConstLocation,
"parameter %0 is const-qualified in the function "
"declaration; const-qualification of parameters only has an 
"
"effect in function definitions");
@@ -70,18 +90,9 @@ void AvoidConstParamsInDecls::check(const 
MatchFinder::MatchResult &Result) {
 // from a macro.
 return;
   }
-
-  CharSourceRange FileRange = Lexer::makeFileCharRange(
-  CharSourceRange::getTokenRange(getTypeRange(*Param)),
-  *Result.SourceManager, getLangOpts());
-
-  if (!FileRange.isValid())
-return;
-
-  auto Tok = tidy::utils::lexer::getQualifyingToken(
-  tok::kw_const, FileRange, *Result.Context, *Result.SourceManager);
   if (!Tok)
 return;
+
   Diag << FixItHint::CreateRemoval(
   CharSourceRange::getTokenRange(Tok->getLocation(), Tok->getLocation()));
 }
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
index d521fd238b7d521..bc098efe3044a5d 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-const-params-in-decls.cpp
@@ -9,15 +9,15 @@ void F1(const int i);
 // CHECK-FIXES: void F1(int i);
 
 void F2(const int *const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F2(const int *i);
 
 void F3(int const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:13: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F3(int i);
 
 void F4(alias_type const i);
-// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is const-qualified
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: parameter 'i' is const-qualified
 // CHECK-FIXES: void F4(alias_type i);
 
 void F5(const int);
@@ -25,7 +25,7 @@ void F5(const int);
 // CHECK-FIXES: void F5(int);
 
 void F6(const int *const);
-// CHECK-MESSAGES: :[[@LIN

[clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2023-10-22 Thread via cfe-commits

https://github.com/Overhatted updated 
https://github.com/llvm/llvm-project/pull/69856

>From 01c1271b9e0f9583262bf00d5853ef362764909a Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Sat, 21 Oct 2023 14:16:38 +0100
Subject: [PATCH] In compilation databases, add support for relative
 directories

---
 .../clangd/GlobalCompilationDatabase.cpp  |  2 +-
 clang/docs/JSONCompilationDatabase.rst|  4 +++-
 .../clang/Tooling/JSONCompilationDatabase.h   | 10 
 clang/lib/Tooling/JSONCompilationDatabase.cpp | 24 ++-
 .../Tooling/CompilationDatabaseTest.cpp   |  8 +++
 5 files changed, 32 insertions(+), 16 deletions(-)

diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index d1833759917a30f..3e81308316d55cd 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -243,7 +243,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 return tooling::inferMissingCompileCommands(std::move(CDB));
   }
   return nullptr;
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e4..41219a554dfdeaa 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d588..3ec0e36c196d2e4 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1d..c8c7f46e1fb3e66 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -202,21 +202,26 @@ JSONCompilationDatabase::loadFromFile(StringRef FilePath,
 ErrorMessage = "Error while opening JSON database: " + Result.message();
 return nullptr;
   }
-  std::unique_ptr Database(
-  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
+  SmallString<128> FolderPath = FilePath;
+  llvm::sys::path::remove_filename(FolderPath);
+  std::unique_ptr Database(new 
JSONCompilationDatabase(
+  FolderPath, std::move(*DatabaseBuffer), Syntax));
   if (!Database->parse(ErrorMessage))
 return nullptr;
   return Database;
 }
 
 std::unique_ptr
-JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
+JSONCompilationDataba

[clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2023-10-22 Thread via cfe-commits

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


[clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2023-10-22 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 f3ff0a67be46f2380ca597d21fe551cf2bbf41fd 
01c1271b9e0f9583262bf00d5853ef362764909a -- 
clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
clang/include/clang/Tooling/JSONCompilationDatabase.h 
clang/lib/Tooling/JSONCompilationDatabase.cpp 
clang/unittests/Tooling/CompilationDatabaseTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/Tooling/CompilationDatabaseTest.cpp 
b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
index 86bbe74bfdc4..9479d02532de 100644
--- a/clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -27,8 +27,8 @@ using testing::UnorderedElementsAreArray;
 static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
   std::string ErrorMessage;
   EXPECT_EQ(nullptr,
-JSONCompilationDatabase::loadFromBuffer("", JSONDatabase, 
ErrorMessage,
-
JSONCommandLineSyntax::Gnu))
+JSONCompilationDatabase::loadFromBuffer(
+"", JSONDatabase, ErrorMessage, JSONCommandLineSyntax::Gnu))
   << "Expected an error because of: " << Explanation.str();
 }
 

``




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


[clang] 3e86cc4 - [clang-format][NFC] Simplify the logic in a return statement

2023-10-22 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-10-22T13:46:32-07:00
New Revision: 3e86cc4b864f609720c12cc97ff70a20aabb956f

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

LOG: [clang-format][NFC] Simplify the logic in a return statement

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7f85f48de2ed2ed..a457ced9f886846 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4197,8 +4197,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
   (Right.is(tok::r_brace) && Right.MatchingParen &&
Right.MatchingParen->isNot(BK_Block))) {
-return Style.Cpp11BracedListStyle ? Style.SpacesInParensOptions.Other
-  : true;
+return !Style.Cpp11BracedListStyle || Style.SpacesInParensOptions.Other;
   }
   if (Left.is(TT_BlockComment)) {
 // No whitespace in x(/*foo=*/1), except for JavaScript.



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


[clang] In compilation databases, add support for relative directories (PR #69856)

2023-10-22 Thread via cfe-commits

https://github.com/Overhatted updated 
https://github.com/llvm/llvm-project/pull/69856

>From 5d4642378e6f74da0b15d8524aeb1ed1fa257568 Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Sat, 21 Oct 2023 14:16:38 +0100
Subject: [PATCH] In compilation databases, add support for relative
 directories

---
 .../clangd/GlobalCompilationDatabase.cpp  |  2 +-
 clang/docs/JSONCompilationDatabase.rst|  4 +++-
 .../clang/Tooling/JSONCompilationDatabase.h   | 10 
 clang/lib/Tooling/JSONCompilationDatabase.cpp | 24 ++-
 .../Tooling/CompilationDatabaseTest.cpp   | 10 
 5 files changed, 33 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index d1833759917a30f..3e81308316d55cd 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -243,7 +243,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 return tooling::inferMissingCompileCommands(std::move(CDB));
   }
   return nullptr;
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e4..41219a554dfdeaa 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d588..3ec0e36c196d2e4 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1d..c8c7f46e1fb3e66 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -202,21 +202,26 @@ JSONCompilationDatabase::loadFromFile(StringRef FilePath,
 ErrorMessage = "Error while opening JSON database: " + Result.message();
 return nullptr;
   }
-  std::unique_ptr Database(
-  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
+  SmallString<128> FolderPath = FilePath;
+  llvm::sys::path::remove_filename(FolderPath);
+  std::unique_ptr Database(new 
JSONCompilationDatabase(
+  FolderPath, std::move(*DatabaseBuffer), Syntax));
   if (!Database->parse(ErrorMessage))
 return nullptr;
   return Database;
 }
 
 std::unique_ptr
-JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
+JSONCompilationDatab

[clang] [clang-format] Don't break between string literal operands of << (PR #69871)

2023-10-22 Thread Owen Pan via cfe-commits


@@ -5118,10 +5118,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
-  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&

owenca wrote:

No, it still passes.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-22 Thread Owen Pan via cfe-commits


@@ -1118,16 +1121,48 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+auto DontAlignThisComment = [](const auto *Tok) {
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->is(tok::r_paren)) {
+// Back up past the parentheses and a `TT_DoWhile` that may precede.
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+if (Tok->is(TT_DoWhile)) {
+  auto Prev = Tok->getPreviousNonComment();
+  if (!Prev) {
+// A do-while-loop without braces.
+return Tok->NewlinesBefore > 0;
+  }

owenca wrote:

That's fine, though the do-while loop may still have braces, e.g. with the 
closing brace on its own line.

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


[clang-tools-extra] [mlir] Verify TestBuiltinAttributeInterfaces eltype (PR #69878)

2023-10-22 Thread Mehdi Amini via cfe-commits

https://github.com/joker-eph approved this pull request.


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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-22 Thread Owen Pan via cfe-commits


@@ -3191,20 +3198,150 @@ TEST_F(FormatTestComments, DontAlignNamespaceComments) 
{
   "}\n"
   "// Comment";
 
-#if 0
-  // FIXME: The following comment is aligned with the namespace comment.
   verifyFormat("namespace A {\n"
"  int Foo;\n"
"  int Bar;\n"
"} // namespace A\n"
-   " // Comment",
+   "// Comment",
Input, Style);
-#endif
 
   Style.FixNamespaceComments = false;
   verifyFormat(Input, Style);
 }
 
+TEST_F(FormatTestComments, DontAlignOverScope) {
+  verifyFormat("if (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("if (foo) {\n"
+   "  // something\n"
+   "} else {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("if (foo) {\n"
+   "  // something\n"
+   "} else if (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("while (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("for (;;) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("do {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} while (foo); // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("do\n"
+   "  int aLongVariable; // with comment\n"
+   "while (foo); // not aigned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("do\n"
+   "  int aLongVariable; // with comment\n"
+   "/**/ while (foo); // not aigned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("switch (foo) {\n"
+   "case 7: {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // case not aligned\n"
+   "} // switch also not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("switch (foo) {\n"
+   "default: {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // case not aligned\n"
+   "} // switch also not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("class C {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("struct S {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("union U {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("enum E {\n"
+   "  aLongVariable, // with comment\n"
+   "  f  // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("void foo() {\n"
+   "  {\n"
+   "int aLongVariable; // with comment\n"
+   "int f; // aligned\n"
+   "  } // not aligned\n"
+   "  int bar;// new align\n"
+   "  int foobar; // group\n"
+   "}");
+
+  verifyFormat("auto longLambda = [] { // comment\n"
+   "  int aLongVariable;   // with comment\n"
+   "  int f;   // ali

[clang] [mlir] Verify TestBuiltinAttributeInterfaces eltype (PR #69878)

2023-10-22 Thread Mehdi Amini via cfe-commits

https://github.com/joker-eph approved this pull request.


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


[clang-tools-extra] [mlir][DeadCodeAnalysis] Don't Require `RegionBranchTerminatorOpInterface` in `visitRegionTerminator()` (PR #69043)

2023-10-22 Thread Justin Fargnoli via cfe-commits

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


[clang] [MLIR][scf.parallel] Don't allow a tile size of 0 (PR #68762)

2023-10-22 Thread Justin Fargnoli via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: mlir-opt %s 
-pass-pipeline='builtin.module(func.func(scf-parallel-loop-tiling{parallel-loop-tile-sizes=0,0}))'
 -split-input-file -verify-diagnostics
+
+// XFAIL: *

justinfargnoli wrote:

It looks like it isn't possible to use `expected-error` to check for an error 
at an `UnknownLoc`. If this is true, am I good to go forward with using 
`XFAIL`? 

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


[clang-tools-extra] [MLIR][scf.parallel] Don't allow a tile size of 0 (PR #68762)

2023-10-22 Thread Matthias Springer via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: mlir-opt %s 
-pass-pipeline='builtin.module(func.func(scf-parallel-loop-tiling{parallel-loop-tile-sizes=0,0}))'
 -split-input-file -verify-diagnostics
+
+// XFAIL: *

matthias-springer wrote:

I didn't know that. Sounds good!

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


[clang] [Clang][LoongArch] Support builtin functions for LSX and LASX (PR #69313)

2023-10-22 Thread Lu Weining via cfe-commits

SixWeining wrote:

> Given you've already split your changes into several smaller commits, it's 
> probably better to file them as separate PRs, so each one is smaller than the 
> current 3+-line diff, and become more reviewable that way.

I'm not sure seperate PRs are appropriate since some of these 6 commits depend 
on the others. If creating 6 PRs, we will see:
PR1 consists of 1 commit
PR2 consists of 2 commits
...
PR6 consists of 6 commits

In fact, we can review each of these 6 commits in one PR by clicking the 
`Changes from all commits` button and `Select commit` in the `Files changed` 
tab.





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


[clang] [Clang][LoongArch] Support builtin functions for LSX and LASX (PR #69313)

2023-10-22 Thread Lu Weining via cfe-commits

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

- For the commits `[LoongArch][CodeGen][clang] Add builtin functions test cases 
for LASX` and `[LoongArch][CodeGen][clang] Add builtin functions test cases for 
LSX`, `Change-Id`s can be removed.
- Please fix the test failure.

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-22 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Ping

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


[clang] [C++20] [Modules] [Driver] Don't enable -fdelayed-template-parsing by default on windows with C++20 modules (PR #69431)

2023-10-22 Thread Chuanqi Xu via cfe-commits

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

>From 9c0d81ef5fdae40d378170eebd848f099902dc98 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Wed, 18 Oct 2023 15:58:03 +0800
Subject: [PATCH] [C++20] [Modules] [Driver] Don't enable
 -fdelayed-template-parsing by default on windows after c++20

There are already 3 issues about the broken state of
-fdelayed-template-parsing and C++20 modules:
- https://github.com/llvm/llvm-project/issues/61068
- https://github.com/llvm/llvm-project/issues/64810
- https://github.com/llvm/llvm-project/issues/65027

The problem is more complex than I thought. I am not sure how to fix it
properly now. Given the complexities and -fdelayed-template-parsing is
actually an extension to support old MS codes, I think it may make sense
to not enable the -fdelayed-template-parsing option by default with
C++20 modules to give more user friendly experience. Users who still want
-fdelayed-template-parsing can specify it explicitly.

Given the discussion in https://github.com/llvm/llvm-project/pull/69551,
we decide to not enable -fdelayed-template-parsing by default on windows
after c++20
---
 clang/docs/ReleaseNotes.rst   |  4 ++
 .../clang/Basic/DiagnosticDriverKinds.td  |  4 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 54 +++
 .../cl-delayed-template-parsing-cxx20.cpp | 10 
 4 files changed, 51 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/Driver/cl-delayed-template-parsing-cxx20.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 99525b00239a4ca..09406adcb5b87f2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -100,6 +100,10 @@ C++ Specific Potentially Breaking Changes
   system headers and macros. It will be turned into a hard (non-downgradable)
   error in the next Clang release.
 
+- The flag `-fdelayed-template-parsing` won't be enabled by default with C++20
+  when targetting MSVC to match the behavior of MSVC. 
+  (`MSVC Docs 
`_)
+
 ABI Changes in This Version
 ---
 - Following the SystemV ABI for x86-64, ``__int128`` arguments will no longer
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 9c00fa50bb95580..6110c6d6ea195b8 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -527,6 +527,10 @@ def err_test_module_file_extension_format : Error<
 def err_drv_module_output_with_multiple_arch : Error<
   "option '-fmodule-output' can't be used with multiple arch options">;
 
+def warn_drv_delayed_template_parsing_after_cxx20 : Warning<
+  "-fdelayed-template-parsing is deprecated after C++20">,
+  InGroup>;
+
 def err_drv_extract_api_wrong_kind : Error<
   "header file '%0' input '%1' does not match the type of prior input "
   "in api extraction; use '-x %2' to override">;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 94c184435ae14de..5d77f69ae703f6c 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3724,20 +3724,10 @@ bool 
Driver::getDefaultModuleCachePath(SmallVectorImpl &Result) {
 
 static bool RenderModulesOptions(Compilation &C, const Driver &D,
  const ArgList &Args, const InputInfo &Input,
- const InputInfo &Output, const Arg *Std,
+ const InputInfo &Output, bool HaveStd20,
  ArgStringList &CmdArgs) {
   bool IsCXX = types::isCXX(Input.getType());
-  // FIXME: Find a better way to determine whether the input has standard c++
-  // modules support by default.
-  bool HaveStdCXXModules =
-  IsCXX && Std &&
-  (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
-   Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
-   Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
-   Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
-   Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
-   Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
-   Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
+  bool HaveStdCXXModules = IsCXX && HaveStd20;
   bool HaveModules = HaveStdCXXModules;
 
   // -fmodules enables the use of precompiled modules (off by default).
@@ -6842,14 +6832,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 (!IsWindowsMSVC || IsMSVC2015Compatible)))
 CmdArgs.push_back("-fno-threadsafe-statics");
 
-  // -fno-delayed-template-parsing is default, except when targeting MSVC.
-  // Many old Windows SDK versions require this to parse.
-  // FIXME: 

[clang] [C++20] [Modules] [Driver] Don't enable -fdelayed-template-parsing by default on windows with C++20 modules (PR #69431)

2023-10-22 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Comments addressed.

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


[clang] [C++20] [Modules] [Driver] Don't enable -fdelayed-template-parsing by default on windows with C++20 modules (PR #69431)

2023-10-22 Thread Chuanqi Xu via cfe-commits

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


[clang] 366ffba - [C++20] [Modules] [Driver] Don't enable -fdelayed-template-parsing by default on windows with C++20 (#69431)

2023-10-22 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2023-10-23T10:06:16+08:00
New Revision: 366ffbaf627d0b6867299458cf57f8464259e550

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

LOG: [C++20] [Modules] [Driver] Don't enable -fdelayed-template-parsing by 
default on windows with C++20 (#69431)

There are already 3 issues about the broken state of
-fdelayed-template-parsing and C++20 modules:
- https://github.com/llvm/llvm-project/issues/61068
- https://github.com/llvm/llvm-project/issues/64810
- https://github.com/llvm/llvm-project/issues/65027

The problem is more complex than I thought. I am not sure how to fix it
properly now. Given the complexities and -fdelayed-template-parsing is
actually an extension to support old MS codes, I think it may make sense
to not enable the -fdelayed-template-parsing option by default with
C++20 modules to give more user friendly experience. Users who still
want -fdelayed-template-parsing can specify it explicitly.

Also according to 
https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
 MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
not enable -fdelayed-template-parsing by default after C++20.

Added: 
clang/test/Driver/cl-delayed-template-parsing-cxx20.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a9a67f7451c092..de1ab29d3182f20 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -121,6 +121,10 @@ C++ Specific Potentially Breaking Changes
   system headers and macros. It will be turned into a hard (non-downgradable)
   error in the next Clang release.
 
+- The flag `-fdelayed-template-parsing` won't be enabled by default with C++20
+  when targetting MSVC to match the behavior of MSVC. 
+  (`MSVC Docs 
`_)
+
 ABI Changes in This Version
 ---
 - Following the SystemV ABI for x86-64, ``__int128`` arguments will no longer

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 9c00fa50bb95580..6110c6d6ea195b8 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -527,6 +527,10 @@ def err_test_module_file_extension_format : Error<
 def err_drv_module_output_with_multiple_arch : Error<
   "option '-fmodule-output' can't be used with multiple arch options">;
 
+def warn_drv_delayed_template_parsing_after_cxx20 : Warning<
+  "-fdelayed-template-parsing is deprecated after C++20">,
+  InGroup>;
+
 def err_drv_extract_api_wrong_kind : Error<
   "header file '%0' input '%1' does not match the type of prior input "
   "in api extraction; use '-x %2' to override">;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 3df2cb694fd918e..b9c54a324b0fd4d 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3724,20 +3724,10 @@ bool 
Driver::getDefaultModuleCachePath(SmallVectorImpl &Result) {
 
 static bool RenderModulesOptions(Compilation &C, const Driver &D,
  const ArgList &Args, const InputInfo &Input,
- const InputInfo &Output, const Arg *Std,
+ const InputInfo &Output, bool HaveStd20,
  ArgStringList &CmdArgs) {
   bool IsCXX = types::isCXX(Input.getType());
-  // FIXME: Find a better way to determine whether the input has standard c++
-  // modules support by default.
-  bool HaveStdCXXModules =
-  IsCXX && Std &&
-  (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
-   Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
-   Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
-   Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
-   Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
-   Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
-   Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
+  bool HaveStdCXXModules = IsCXX && HaveStd20;
   bool HaveModules = HaveStdCXXModules;
 
   // -fmodules enables the use of precompiled modules (off by default).
@@ -6840,14 +6830,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 (!IsWindowsMSVC || IsMSVC2015Compatible)))
 CmdArgs

[clang] 05b5188 - [Clang][RISCV] Support CSRs in clobbered registers of inline assembly (#67646)

2023-10-22 Thread via cfe-commits

Author: Wang Pengcheng
Date: 2023-10-23T11:15:20+08:00
New Revision: 05b5188c1257785c4138834b81ec86047517376d

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

LOG: [Clang][RISCV] Support CSRs in clobbered registers of inline assembly 
(#67646)

To match GCC's behaviors.

Fixes #67596

Added: 
clang/test/CodeGen/RISCV/riscv-inline-asm-clobber.c

Modified: 
clang/lib/Basic/Targets/RISCV.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/RISCV.cpp 
b/clang/lib/Basic/Targets/RISCV.cpp
index d55ab76395c8271..5f75619b745546c 100644
--- a/clang/lib/Basic/Targets/RISCV.cpp
+++ b/clang/lib/Basic/Targets/RISCV.cpp
@@ -23,6 +23,7 @@ using namespace clang;
 using namespace clang::targets;
 
 ArrayRef RISCVTargetInfo::getGCCRegNames() const {
+  // clang-format off
   static const char *const GCCRegNames[] = {
   // Integer registers
   "x0",  "x1",  "x2",  "x3",  "x4",  "x5",  "x6",  "x7",
@@ -40,7 +41,12 @@ ArrayRef RISCVTargetInfo::getGCCRegNames() 
const {
   "v0",  "v1",  "v2",  "v3",  "v4",  "v5",  "v6",  "v7",
   "v8",  "v9",  "v10", "v11", "v12", "v13", "v14", "v15",
   "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
-  "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"};
+  "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
+
+  // CSRs
+  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm"
+};
+  // clang-format on
   return llvm::ArrayRef(GCCRegNames);
 }
 

diff  --git a/clang/test/CodeGen/RISCV/riscv-inline-asm-clobber.c 
b/clang/test/CodeGen/RISCV/riscv-inline-asm-clobber.c
new file mode 100644
index 000..8aa80386f205f8a
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/riscv-inline-asm-clobber.c
@@ -0,0 +1,44 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv32 -O2 -emit-llvm %s -o - \
+// RUN: | FileCheck %s
+// RUN: %clang_cc1 -triple riscv64 -O2 -emit-llvm %s -o - \
+// RUN: | FileCheck %s
+
+// Test RISC-V specific clobbered registers in inline assembly.
+
+// CHECK-LABEL: define {{.*}} void @test_fflags
+// CHECK:tail call void asm sideeffect "", "~{fflags}"()
+void test_fflags(void) {
+  asm volatile ("" :::"fflags");
+}
+
+// CHECK-LABEL: define {{.*}} void @test_frm
+// CHECK:tail call void asm sideeffect "", "~{frm}"()
+void test_frm(void) {
+  asm volatile ("" :::"frm");
+}
+
+// CHECK-LABEL: define {{.*}} void @test_vtype
+// CHECK:tail call void asm sideeffect "", "~{vtype}"()
+void test_vtype(void) {
+  asm volatile ("" :::"vtype");
+}
+
+// CHECK-LABEL: define {{.*}} void @test_vl
+// CHECK:tail call void asm sideeffect "", "~{vl}"()
+void test_vl(void) {
+  asm volatile ("" :::"vl");
+}
+
+// CHECK-LABEL: define {{.*}} void @test_vxsat
+// CHECK:tail call void asm sideeffect "", "~{vxsat}"()
+void test_vxsat(void) {
+  asm volatile ("" :::"vxsat");
+}
+
+// CHECK-LABEL: define {{.*}} void @test_vxrm
+// CHECK:tail call void asm sideeffect "", "~{vxrm}"()
+void test_vxrm(void) {
+  asm volatile ("" :::"vxrm");
+}



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


[clang] [Clang][RISCV] Support CSRs in clobbered registers of inline assembly (PR #67646)

2023-10-22 Thread Wang Pengcheng via cfe-commits

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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-22 Thread Nathan Ridge via cfe-commits


@@ -76,7 +82,7 @@ bool RawStringLiteral::prepare(const Selection &Inputs) {
   if (!N)
 return false;
   Str = dyn_cast_or_null(N->ASTNode.get());
-  return Str &&
+  return Str && isFeatureAvailable(Inputs) &&

HighCommander4 wrote:

I would move this language mode check to the very top of `prepare()` (e.g. 
there is no point doing the work of `commonAncestor()` if this check fails).

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


[clang] a5dca53 - Use llvm::count (NFC)

2023-10-22 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-10-22T21:18:23-07:00
New Revision: a5dca533bdc32258d3f3334cdec44f0ac9028251

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

LOG: Use llvm::count (NFC)

Added: 


Modified: 
clang/utils/TableGen/SveEmitter.cpp
llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp

Removed: 




diff  --git a/clang/utils/TableGen/SveEmitter.cpp 
b/clang/utils/TableGen/SveEmitter.cpp
index ab2b22233987a3c..1421a5b03ed6665 100644
--- a/clang/utils/TableGen/SveEmitter.cpp
+++ b/clang/utils/TableGen/SveEmitter.cpp
@@ -195,7 +195,7 @@ class Intrinsic {
   ArrayRef getTypes() const { return Types; }
   SVEType getParamType(unsigned I) const { return Types[I + 1]; }
   unsigned getNumParams() const {
-return Proto.size() - (2 * std::count(Proto.begin(), Proto.end(), '.')) - 
1;
+return Proto.size() - (2 * llvm::count(Proto, '.')) - 1;
   }
 
   uint64_t getFlags() const { return Flags; }

diff  --git a/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp 
b/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
index 3ab21ad26d85e6f..e06c1552e14aa07 100644
--- a/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
+++ b/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
@@ -2093,8 +2093,7 @@ void CallsiteContextGraph::identifyClones(
 for (auto &Edge : CallerEdges) {
   // Skip any that have been removed by an earlier recursive call.
   if (Edge->Callee == nullptr && Edge->Caller == nullptr) {
-assert(!std::count(Node->CallerEdges.begin(), Node->CallerEdges.end(),
-   Edge));
+assert(!llvm::count(Node->CallerEdges, Edge));
 continue;
   }
   // Ignore any caller we previously visited via another edge.



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


[clang] clangd: Show argument names for function pointer struct fields (PR #69011)

2023-10-22 Thread Nathan Ridge via cfe-commits

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

Thanks for the patch!

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


[clang-tools-extra] clangd: Show argument names for function pointer struct fields (PR #69011)

2023-10-22 Thread Nathan Ridge via cfe-commits

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


[clang] clangd: Show argument names for function pointer struct fields (PR #69011)

2023-10-22 Thread Nathan Ridge via cfe-commits


@@ -6133,7 +6133,17 @@ ProduceSignatureHelp(Sema &SemaRef, 
MutableArrayRef Candidates,
 // so that we can recover argument names from it.
 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
   TypeLoc Target;
-  if (const auto *T = Fn->getType().getTypePtr()->getAs()) {
+
+  if (const auto *ME = dyn_cast(Fn)) {
+const auto *MD = ME->getMemberDecl();
+if (const auto *FD = dyn_cast(MD)) {
+  if (const auto *T = FD->getType().getTypePtr()->getAs()) {

HighCommander4 wrote:

This case is actually handled by the `if (const auto *T = 
Fn->getType().getTypePtr()->getAs())` branch, as long as it runs 
before the check for `MemberExpr`.

So:
 * let's move the `MemberExpr` branch below the `DeclRefExpr` branch
 * let's simplify it to omit this check for `TypedefType`

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


[clang-tools-extra] `clangd`: support `-stdlib=` flags from `compile_commands.json`. (PR #69283)

2023-10-22 Thread Nathan Ridge via cfe-commits


@@ -203,6 +214,7 @@ template <> struct DenseMapInfo {
 Val.Driver,
 Val.StandardIncludes,
 Val.StandardCXXIncludes,
+Val.Stdlib,

HighCommander4 wrote:

nit: it looks like the previous patch which introduced `Target` forgot to add 
it here, could you add please?

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


  1   2   >