[clang] [Support] Rename HashBuilderImpl to HashBuilder (NFC) (PR #68173)

2023-10-03 Thread Markus Böck via cfe-commits

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


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


[clang] 7e856d1 - Reland "[clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (#67955)"

2023-10-03 Thread via cfe-commits

Author: Owen Pan
Date: 2023-10-03T22:26:48-07:00
New Revision: 7e856d18943f637b8c83f0bf8cbb506c5f7e94af

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

LOG: Reland "[clang-format] Annotate ctors/dtors as CtorDtorDeclName instead 
(#67955)"

Reland 6a621ed8e4cb which failed on Windows but not macOS.

The failures were caused by moving the annotation of the children from the
top to the bottom of TokenAnnotator::annotate(), resulting in invalid lines
including incomplete ones being skipped.

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestMacroExpansion.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index dbd3a6e70f037ef..5877b0a6124742a 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -61,6 +61,7 @@ namespace format {
   TYPE(CSharpStringLiteral)
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
+  TYPE(CtorDtorDeclName)   
\
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ea65707da90369..6f879006465ecf5 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3210,12 +3210,12 @@ static bool isCtorOrDtorName(const FormatToken *Tok) {
 }
 
 void TokenAnnotator::annotate(AnnotatedLine ) {
-  for (auto  : Line.Children)
-annotate(*Child);
-
   AnnotatingParser Parser(Style, Line, Keywords, Scopes);
   Line.Type = Parser.parseLine();
 
+  for (auto  : Line.Children)
+annotate(*Child);
+
   // With very deep nesting, ExpressionParser uses lots of stack and the
   // formatting algorithm is very slow. We're not going to do a good job here
   // anyway - it's probably generated code being formatted by mistake.
@@ -3233,7 +3233,7 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 auto *Tok = getFunctionName(Line);
 if (Tok && ((!Scopes.empty() && Scopes.back() == ST_Class) ||
 Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
-  Tok->setFinalizedType(TT_FunctionDeclarationName);
+  Tok->setFinalizedType(TT_CtorDtorDeclName);
 }
   }
 
@@ -3447,9 +3447,13 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
Tok = Tok->Next) {
 if (Tok->Previous->EndsCppAttributeGroup)
   AfterLastAttribute = Tok;
-if (isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
-  LineIsFunctionDeclaration = true;
-  Tok->setFinalizedType(TT_FunctionDeclarationName);
+if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
+IsCtorOrDtor ||
+isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
+  if (!IsCtorOrDtor) {
+LineIsFunctionDeclaration = true;
+Tok->setFinalizedType(TT_FunctionDeclarationName);
+  }
   if (AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
 AfterLastAttribute->MustBreakBefore = true;

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 2cbde3da212ec65..9061e07add545b9 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -975,11 +975,7 @@ void WhitespaceManager::alignConsecutiveDeclarations() {
   AlignTokens(
   Style,
   [](Change const ) {
-if (C.Tok->is(TT_FunctionDeclarationName) && C.Tok->Previous &&
-C.Tok->Previous->isNot(tok::tilde)) {
-  return true;
-}
-if (C.Tok->is(TT_FunctionTypeLParen))
+if (C.Tok->isOneOf(TT_FunctionDeclarationName, TT_FunctionTypeLParen))
   return true;
 if (C.Tok->isNot(TT_StartOfName))
   return false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 246de2f89fccc9d..2ef3c9b299bcad4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10622,6 +10622,12 @@ TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
   verifyFormat("a::\n"
"

[clang-tools-extra] [clang-tidy]: Add TagDecl into LastTagDeclRanges in UseUsingCheck only when it is a definition (PR #67639)

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

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

LGTM

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


[PATCH] D155610: [Clang][Sema] Fix display of characters on static assertion failure

2023-10-03 Thread Takuya Shimizu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2176c5e510e3: [Clang][Sema] Fix display of characters on 
static assertion failure (authored by hazohelet).

Changed prior to commit:
  https://reviews.llvm.org/D155610?vs=557524=557581#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155610

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Diagnostic.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/Lexer/cxx1z-trigraphs.cpp
  clang/test/SemaCXX/static-assert-cxx26.cpp
  clang/test/SemaCXX/static-assert.cpp

Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -268,7 +268,31 @@
 return 'c';
   }
   static_assert(getChar() == 'a', ""); // expected-error {{failed}} \
-   // expected-note {{evaluates to ''c' == 'a''}}
+   // expected-note {{evaluates to ''c' (0x63, 99) == 'a' (0x61, 97)'}}
+  static_assert((char)9 == '\x61', ""); // expected-error {{failed}} \
+// expected-note {{evaluates to ''\t' (0x09, 9) == 'a' (0x61, 97)'}}
+  static_assert((char)10 == '\0', ""); // expected-error {{failed}} \
+   // expected-note {{n' (0x0A, 10) == '' (0x00, 0)'}}
+  // The note above is intended to match "evaluates to '\n' (0x0A, 10) == '' (0x00, 0)'", but if we write it as it is,
+  // the "\n" cannot be consumed by the diagnostic consumer.
+  static_assert((signed char)10 == (char)-123, ""); // expected-error {{failed}} \
+// expected-note {{evaluates to '10 == '<85>' (0x85, -123)'}}
+  static_assert((char)-4 == (unsigned char)-8, ""); // expected-error {{failed}} \
+// expected-note {{evaluates to ''' (0xFC, -4) == 248'}}
+  static_assert((char)-128 == (char)-123, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to ''<80>' (0x80, -128) == '<85>' (0x85, -123)'}}
+  static_assert('\xA0' == (char)'\x20', ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to ''' (0xA0, -96) == ' ' (0x20, 32)'}}
+  static_assert((char16_t)L'ゆ' == L"C̵̭̯̠̎͌ͅť̺"[1], ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'u'ゆ' (0x3086, 12422) == L'̵' (0x335, 821)'}}
+  static_assert(L"\/"[1] == u'\xFFFD', ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'L'/' (0xFF0F, 65295) == u'�' (0xFFFD, 65533)'}}
+  static_assert(L"⚾"[0] == U'🌍', ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'L'⚾' (0x26BE, 9918) == U'🌍' (0x1F30D, 127757)'}}
+  static_assert(U"\a"[0] == (wchar_t)9, ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'U'\a' (0x07, 7) == L'\t' (0x09, 9)'}}
+  static_assert(L"§"[0] == U'Ö', ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'L'§' (0xA7, 167) == U'Ö' (0xD6, 214)'}}
 
   /// Bools are printed as bools.
   constexpr bool invert(bool b) {
Index: clang/test/SemaCXX/static-assert-cxx26.cpp
===
--- clang/test/SemaCXX/static-assert-cxx26.cpp
+++ clang/test/SemaCXX/static-assert-cxx26.cpp
@@ -298,3 +298,12 @@
 Bad b; // expected-note {{in instantiation}}
 
 }
+
+namespace EscapeInDiagnostic {
+static_assert('\u{9}' == (char)1, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to ''\t' (0x09, 9) == '' (0x01, 1)'}}
+static_assert((char8_t)-128 == (char8_t)-123, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to 'u8'<80>' (0x80, 128) == u8'<85>' (0x85, 133)'}}
+static_assert((char16_t)0xFEFF == (char16_t)0xDB93, ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'u'' (0xFEFF, 65279) == u'\xDB93' (0xDB93, 56211)'}}
+}
Index: clang/test/Lexer/cxx1z-trigraphs.cpp
===
--- clang/test/Lexer/cxx1z-trigraphs.cpp
+++ clang/test/Lexer/cxx1z-trigraphs.cpp
@@ -21,7 +21,7 @@
 
 #if !ENABLED_TRIGRAPHS
 // expected-error@11 {{}} expected-warning@11 {{trigraph ignored}}
-// expected-error@13 {{failed}} expected-warning@13 {{trigraph ignored}} expected-note@13 {{evaluates to ''?' == '#''}}
+// 

[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-10-03 Thread via cfe-commits

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

>From ef66dbe5f9a5b9071e994a5d8f2b6b48b6d5b446 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 18 Sep 2023 19:55:45 +0800
Subject: [PATCH 1/2] [clang] Preserve UDL nodes in
 RemoveNestedImmediateInvocation

D63960 performs a tree transformation on AST to prevent evaluating
constant expressions eagerly by removing recorded immediate consteval
invocations from subexpressions. (See 
https://reviews.llvm.org/D63960#inline-600736
for its motivation.)

However, the UDL node has been replaced with a CallExpr in the default
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd
as it relies on the exact AST node type to decide whether or not to
present inlay hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression
as-is during the transformation: We've bound it to temporary
in its construction, and there's no ConstantExpr to visit under a UDL.

Fixes https://github.com/llvm/llvm-project/issues/63898.
---
 clang/lib/Sema/SemaExpr.cpp   |  5 -
 clang/test/AST/ast-dump-udl-consteval.cpp | 17 +
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/AST/ast-dump-udl-consteval.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 797b71bffbb451e..304aa7d105e269b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18468,7 +18468,10 @@ static void RemoveNestedImmediateInvocation(
   DRSet.erase(cast(E->getCallee()->IgnoreImplicit()));
   return Base::TransformCXXOperatorCallExpr(E);
 }
-/// Base::TransformInitializer skip ConstantExpr so we need to visit them
+/// Base::TransformUserDefinedLiteral doesn't preserve the
+/// UserDefinedLiteral node.
+ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
+/// Base::TransformInitializer skips ConstantExpr so we need to visit them
 /// here.
 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
   if (!Init)
diff --git a/clang/test/AST/ast-dump-udl-consteval.cpp 
b/clang/test/AST/ast-dump-udl-consteval.cpp
new file mode 100644
index 000..9da53f725172aba
--- /dev/null
+++ b/clang/test/AST/ast-dump-udl-consteval.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -xc++ -std=c++23 -ast-dump %s | FileCheck %s
+
+int inline consteval operator""_u32(unsigned long long val) {
+  return val;
+}
+
+void udl() {
+  (void)(0_u32 + 1_u32);
+}
+
+// CHECK: `-BinaryOperator {{.+}}  'int' '+'
+// CHECK-NEXT: |-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT: | |-value: Int 0
+// CHECK-NEXT: | `-UserDefinedLiteral {{.+}}  'int'
+// CHECK: `-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT:   |-value: Int 1
+// CHECK-NEXT:   `-UserDefinedLiteral {{.+}}  'int'

>From b14cce301cc2d12c66171faa3c0add0114b23c50 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 4 Oct 2023 13:04:22 +0800
Subject: [PATCH 2/2] Add a release note

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..425e15c747491d5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -290,6 +290,8 @@ Bug Fixes in This Version
   (`#67722 `_).
 - Fixes a crash when instantiating a lambda with requires clause.
   (`#64462 `_)
+- Fixes a regression where the ``UserDefinedLiteral`` was not properly 
preserved
+  while evaluating consteval functions. (`#63898 
`_).
 
 Bug Fixes to Compiler Builtins
 ^^

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


[clang] 2176c5e - [Clang][Sema] Fix display of characters on static assertion failure

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

Author: Takuya Shimizu
Date: 2023-10-04T14:09:06+09:00
New Revision: 2176c5e510e3bfcbc75afb13e78d287141f239a7

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

LOG: [Clang][Sema] Fix display of characters on static assertion failure

This patch fixes the display of characters appearing in LHS or RHS of == 
expression in notes to static assertion failure.
This applies C-style escape if the printed character is a special character. 
This also adds a numerical value displayed next to the character representation.
This also tries to print multi-byte characters if the user-provided expression 
is multi-byte char type.

Reviewed By: cor3ntin
Differential Revision: https://reviews.llvm.org/D155610

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Diagnostic.h
clang/lib/Basic/Diagnostic.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/Lexer/cxx1z-trigraphs.cpp
clang/test/SemaCXX/static-assert-cxx26.cpp
clang/test/SemaCXX/static-assert.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..4c8b85fc29755c1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -222,6 +222,41 @@ Improvements to Clang's diagnostics
 - ``-Wfixed-enum-extension`` and ``-Wmicrosoft-fixed-enum`` diagnostics are no 
longer
   emitted when building as C23, since C23 standardizes support for enums with a
   fixed underlying type.
+- When describing the failure of static assertion of `==` expression, clang 
prints the integer
+  representation of the value as well as its character representation when
+  the user-provided expression is of character type. If the character is
+  non-printable, clang now shows the escpaed character.
+  Clang also prints multi-byte characters if the user-provided expression
+  is of multi-byte character type.
+
+  *Example Code*:
+
+  .. code-block:: c++
+
+ static_assert("A\n"[1] == U'');
+
+  *BEFORE*:
+
+  .. code-block:: text
+
+source:1:15: error: static assertion failed due to requirement '"A\n"[1] 
== U'\U0001f30d''
+1 | static_assert("A\n"[1] == U'');
+  |   ^
+source:1:24: note: expression evaluates to ''
+' == 127757'
+1 | static_assert("A\n"[1] == U'');
+  |   ~^~~~
+
+  *AFTER*:
+
+  .. code-block:: text
+
+source:1:15: error: static assertion failed due to requirement '"A\n"[1] 
== U'\U0001f30d''
+1 | static_assert("A\n"[1] == U'');
+  |   ^
+source:1:24: note: expression evaluates to ''\n' (0x0A, 10) == U'' 
(0x1F30D, 127757)'
+1 | static_assert("A\n"[1] == U'');
+  |   ~^~~~
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 5606a22fe9d68b4..3df037b793b3946 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -1840,7 +1840,7 @@ const char ToggleHighlight = 127;
 void ProcessWarningOptions(DiagnosticsEngine ,
const DiagnosticOptions ,
bool ReportDiags = true);
-
+void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl );
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H

diff  --git a/clang/lib/Basic/Diagnostic.cpp b/clang/lib/Basic/Diagnostic.cpp
index 7a54d27ef9d8ee2..0208ccc31bd7fc0 100644
--- a/clang/lib/Basic/Diagnostic.cpp
+++ b/clang/lib/Basic/Diagnostic.cpp
@@ -800,9 +800,10 @@ FormatDiagnostic(SmallVectorImpl ) const {
   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
 }
 
-/// pushEscapedString - Append Str to the diagnostic buffer,
+/// EscapeStringForDiagnostic - Append Str to the diagnostic buffer,
 /// escaping non-printable characters and ill-formed code unit sequences.
-static void pushEscapedString(StringRef Str, SmallVectorImpl ) {
+void clang::EscapeStringForDiagnostic(StringRef Str,
+  SmallVectorImpl ) {
   OutStr.reserve(OutStr.size() + Str.size());
   auto *Begin = reinterpret_cast(Str.data());
   llvm::raw_svector_ostream OutStream(OutStr);
@@ -854,7 +855,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
   StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
   getArgKind(0) == DiagnosticsEngine::ak_std_string) {
 const std::string  = getArgStdStr(0);
-pushEscapedString(S, OutStr);
+EscapeStringForDiagnostic(S, OutStr);
 return;
   }
 
@@ -961,7 +962,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
 case DiagnosticsEngine::ak_std_string: {
   const std::string  = getArgStdStr(ArgNo);
   assert(ModifierLen == 0 && "No 

[clang] [clang][tidy] Ensure rewriter has the correct CWD (PR #67839)

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

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

Clang part looks fine.
For a clang-tidy part, is there a way to test this part ? What changes because 
we use now a absolute build directory.
I'm missing some tests for that part.

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


[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-10-03 Thread via cfe-commits

zyn0217 wrote:

No problem! And here it is.
PTAL, thanks! @cor3ntin 

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


[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-10-03 Thread via cfe-commits

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

>From ba9aa0ffe006ecdd8685c7e62be8c4c776391ec2 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 18 Sep 2023 19:55:45 +0800
Subject: [PATCH 1/2] [clang] Preserve UDL nodes in
 RemoveNestedImmediateInvocation

D63960 performs a tree transformation on AST to prevent evaluating
constant expressions eagerly by removing recorded immediate consteval
invocations from subexpressions. (See 
https://reviews.llvm.org/D63960#inline-600736
for its motivation.)

However, the UDL node has been replaced with a CallExpr in the default
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd
as it relies on the exact AST node type to decide whether or not to
present inlay hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression
as-is during the transformation: We've bound it to temporary
in its construction, and there's no ConstantExpr to visit under a UDL.

Fixes https://github.com/llvm/llvm-project/issues/63898.
---
 clang/lib/Sema/SemaExpr.cpp   |  5 -
 clang/test/AST/ast-dump-udl-consteval.cpp | 17 +
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/AST/ast-dump-udl-consteval.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 92496b03ecabe54..104da822aae2930 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18438,7 +18438,10 @@ static void RemoveNestedImmediateInvocation(
   DRSet.erase(cast(E->getCallee()->IgnoreImplicit()));
   return Base::TransformCXXOperatorCallExpr(E);
 }
-/// Base::TransformInitializer skip ConstantExpr so we need to visit them
+/// Base::TransformUserDefinedLiteral doesn't preserve the
+/// UserDefinedLiteral node.
+ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
+/// Base::TransformInitializer skips ConstantExpr so we need to visit them
 /// here.
 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
   if (!Init)
diff --git a/clang/test/AST/ast-dump-udl-consteval.cpp 
b/clang/test/AST/ast-dump-udl-consteval.cpp
new file mode 100644
index 000..9da53f725172aba
--- /dev/null
+++ b/clang/test/AST/ast-dump-udl-consteval.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -xc++ -std=c++23 -ast-dump %s | FileCheck %s
+
+int inline consteval operator""_u32(unsigned long long val) {
+  return val;
+}
+
+void udl() {
+  (void)(0_u32 + 1_u32);
+}
+
+// CHECK: `-BinaryOperator {{.+}}  'int' '+'
+// CHECK-NEXT: |-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT: | |-value: Int 0
+// CHECK-NEXT: | `-UserDefinedLiteral {{.+}}  'int'
+// CHECK: `-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT:   |-value: Int 1
+// CHECK-NEXT:   `-UserDefinedLiteral {{.+}}  'int'

>From f54698e248240063625a636273e6eab27710a1fc Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 4 Oct 2023 13:04:22 +0800
Subject: [PATCH 2/2] Add a release note

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 500f9c9a0cda741..fde53ccfcae09f6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -226,6 +226,8 @@ Bug Fixes in This Version
   an invalid conversion during method function overload resolution.
 - Fix parser crash when dealing with ill-formed objective C++ header code. 
Fixes
   (`#64836 `_)
+- Fixed a regression where the ``UserDefinedLiteral`` was not properly 
preserved while
+  evaluating consteval functions. (`#63898 
`_).
 
 Bug Fixes to Compiler Builtins
 ^^

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

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

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

Order of changes, test, documentation is missing

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

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

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

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


@@ -45,18 +45,20 @@ void CalleeNamespaceCheck::check(const 
MatchFinder::MatchResult ) {
   if (FuncDecl->getBuiltinID() != 0)
 return;
 
-  // If the outermost namespace of the function is __llvm_libc, we're good.
+  // If the outermost namespace of the function starts with __llvm_libc, we're
+  // good.
   const auto *NS = dyn_cast(getOutermostNamespace(FuncDecl));
-  if (NS && NS->getName() == "__llvm_libc")
+  if (NS && NS->getName().starts_with("__llvm_libc"))
 return;
 
   const DeclarationName  = FuncDecl->getDeclName();
   if (Name.isIdentifier() &&
   IgnoredFunctions.contains(Name.getAsIdentifierInfo()->getName()))
 return;
 
-  diag(UsageSiteExpr->getBeginLoc(), "%0 must resolve to a function declared "
- "within the '__llvm_libc' namespace")
+  diag(UsageSiteExpr->getBeginLoc(),
+   "%0 must resolve to a function declared "
+   "within the '__llvm_libc' namespace (use macro `LIBC_NAMESPACE`)")

PiotrZSL wrote:

Macro LIBC_NAMESPACE is not referenced in check documentation.

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

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


@@ -45,18 +45,20 @@ void CalleeNamespaceCheck::check(const 
MatchFinder::MatchResult ) {
   if (FuncDecl->getBuiltinID() != 0)
 return;
 
-  // If the outermost namespace of the function is __llvm_libc, we're good.
+  // If the outermost namespace of the function starts with __llvm_libc, we're
+  // good.
   const auto *NS = dyn_cast(getOutermostNamespace(FuncDecl));
-  if (NS && NS->getName() == "__llvm_libc")
+  if (NS && NS->getName().starts_with("__llvm_libc"))

PiotrZSL wrote:

Missing test for this change, anyway why this is changed ?

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

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


@@ -321,6 +321,11 @@ Changes in existing checks
   ` check to
   identify calls to static member functions with out-of-class inline 
definitions.
 
+- Improved :doc:`llvmlibc-callee-namespace

PiotrZSL wrote:

Put this in alphabetical order.

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


[clang-tools-extra] llvm-canon (PR #68176)

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

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/15] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[clang] llvm-canon (PR #68176)

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

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/15] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[clang-tools-extra] llvm-canon (PR #68176)

2023-10-03 Thread Michal Paszkowski via cfe-commits


@@ -0,0 +1,638 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer {
+public:
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  bool runOnFunction(Function );
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+  DenseSet NamedInstructions;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions (including pre-outputs)"));
+cl::opt IRCanonicalizer::ReorderOperands(
+"reorder-operands", cl::Hidden,
+cl::desc("Sorts and reorders operands in commutative instructions"));
+
+/// Entry method to the IRCanonicalizer.
+///
+/// \param M Module to canonicalize.
+bool IRCanonicalizer::runOnFunction(Function ) {
+  nameFunctionArguments(F);
+  nameBasicBlocks(F);
+
+  SmallVector Outputs = collectOutputInstructions(F);
+
+  if (!PreserveOrder)
+reorderInstructions(Outputs);
+
+  for (auto  : Outputs)
+nameInstruction(I);
+
+  for (auto  : instructions(F)) {
+if (!PreserveOrder) {
+  if (ReorderOperands && I.isCommutative())
+reorderInstructionOperandsByNames();
+
+  if (auto *PN = dyn_cast())
+reorderPHIIncomingValues(PN);
+}
+
+foldInstructionName();
+  }
+
+  return true;
+}
+
+/// Numbers arguments.
+///
+/// \param F Function whose arguments will be renamed.
+void IRCanonicalizer::nameFunctionArguments(Function ) {
+  int ArgumentCounter = 0;
+  for (auto  : F.args()) {
+if (RenameAll || A.getName().empty()) {
+  A.setName("a" + Twine(ArgumentCounter));
+  ++ArgumentCounter;
+}
+  }
+}
+
+/// Names basic blocks using a generated hash for each basic block in
+/// a function considering the opcode and the order of output instructions.
+///
+/// \param F Function containing basic blocks to rename.
+void IRCanonicalizer::nameBasicBlocks(Function ) {
+  for (auto  : F) {
+

[clang] llvm-canon (PR #68176)

2023-10-03 Thread Michal Paszkowski via cfe-commits


@@ -0,0 +1,638 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer {
+public:
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  bool runOnFunction(Function );
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+  DenseSet NamedInstructions;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions (including pre-outputs)"));
+cl::opt IRCanonicalizer::ReorderOperands(
+"reorder-operands", cl::Hidden,
+cl::desc("Sorts and reorders operands in commutative instructions"));
+
+/// Entry method to the IRCanonicalizer.
+///
+/// \param M Module to canonicalize.
+bool IRCanonicalizer::runOnFunction(Function ) {
+  nameFunctionArguments(F);
+  nameBasicBlocks(F);
+
+  SmallVector Outputs = collectOutputInstructions(F);
+
+  if (!PreserveOrder)
+reorderInstructions(Outputs);
+
+  for (auto  : Outputs)
+nameInstruction(I);
+
+  for (auto  : instructions(F)) {
+if (!PreserveOrder) {
+  if (ReorderOperands && I.isCommutative())
+reorderInstructionOperandsByNames();
+
+  if (auto *PN = dyn_cast())
+reorderPHIIncomingValues(PN);
+}
+
+foldInstructionName();
+  }
+
+  return true;
+}
+
+/// Numbers arguments.
+///
+/// \param F Function whose arguments will be renamed.
+void IRCanonicalizer::nameFunctionArguments(Function ) {
+  int ArgumentCounter = 0;
+  for (auto  : F.args()) {
+if (RenameAll || A.getName().empty()) {
+  A.setName("a" + Twine(ArgumentCounter));
+  ++ArgumentCounter;
+}
+  }
+}
+
+/// Names basic blocks using a generated hash for each basic block in
+/// a function considering the opcode and the order of output instructions.
+///
+/// \param F Function containing basic blocks to rename.
+void IRCanonicalizer::nameBasicBlocks(Function ) {
+  for (auto  : F) {
+

[clang-tools-extra] llvm-canon (PR #68176)

2023-10-03 Thread Michal Paszkowski via cfe-commits

michalpaszkowski wrote:

Thank you @justinfargnoli and @AidanGoldfarb for taking over this work and 
reaching out! I will review your changes in the coming week.

CC @ChrisCummins FYI

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


[clang] llvm-canon (PR #68176)

2023-10-03 Thread Michal Paszkowski via cfe-commits

michalpaszkowski wrote:

Thank you @justinfargnoli and @AidanGoldfarb for taking over this work and 
reaching out! I will review your changes in the coming week.

CC @ChrisCummins FYI

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


[clang-tools-extra] llvm-canon (PR #68176)

2023-10-03 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 8641cdf397d86f33ac45e4c691ca4f843c359370 
90912d2b40121936c239f9275bebd52db5d3a116 -- 
llvm/include/llvm/Transforms/Utils/IRCanonicalizer.h 
llvm/lib/Transforms/Utils/IRCanonicalizer.cpp llvm/lib/Passes/PassBuilder.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index 8a495e6d7dc1..7fc17ab31a11 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -233,14 +233,14 @@
 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
 #include "llvm/Transforms/Utils/CountVisits.h"
-#include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/DXILUpgrade.h"
+#include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/FixIrreducible.h"
 #include "llvm/Transforms/Utils/HelloWorld.h"
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
 #include "llvm/Transforms/Utils/InstructionNamer.h"
-#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/Transforms/Utils/LCSSA.h"
 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
 #include "llvm/Transforms/Utils/LoopSimplify.h"
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
index 45dc954f97b9..1a4edadec42f 100644
--- a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -14,6 +14,7 @@
 ///
 
//===--===//
 
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
@@ -28,7 +29,6 @@
 #include "llvm/PassRegistry.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Transforms/Utils.h"
-#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include 
 #include 
 
@@ -174,12 +174,12 @@ void IRCanonicalizer::nameBasicBlocks(Function ) {
 ///
 /// \param I Instruction to be renamed.
 void IRCanonicalizer::nameInstruction(Instruction *I) {
-  //ensure instructions are not renamed. This is done
-  //to prevent situation where instructions are used
-  //before their definition (in phi nodes)
+  // ensure instructions are not renamed. This is done
+  // to prevent situation where instructions are used
+  // before their definition (in phi nodes)
   if (NamedInstructions.contains(I))
 return;
-  NamedInstructions.insert(I); 
+  NamedInstructions.insert(I);
   // Determine the type of instruction to name.
   if (isInitialInstruction(I)) {
 // This is an initial instruction.
@@ -441,7 +441,7 @@ void IRCanonicalizer::reorderInstructions(
 void IRCanonicalizer::reorderInstruction(
 Instruction *Used, Instruction *User,
 SmallPtrSet ) {
-  if(isa(Used))
+  if (isa(Used))
 return;
   if (Visited.contains(Used))
 return;

``




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


[clang] llvm-canon (PR #68176)

2023-10-03 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 8641cdf397d86f33ac45e4c691ca4f843c359370 
90912d2b40121936c239f9275bebd52db5d3a116 -- 
llvm/include/llvm/Transforms/Utils/IRCanonicalizer.h 
llvm/lib/Transforms/Utils/IRCanonicalizer.cpp llvm/lib/Passes/PassBuilder.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index 8a495e6d7dc1..7fc17ab31a11 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -233,14 +233,14 @@
 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
 #include "llvm/Transforms/Utils/CountVisits.h"
-#include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/DXILUpgrade.h"
+#include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/FixIrreducible.h"
 #include "llvm/Transforms/Utils/HelloWorld.h"
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
 #include "llvm/Transforms/Utils/InstructionNamer.h"
-#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/Transforms/Utils/LCSSA.h"
 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
 #include "llvm/Transforms/Utils/LoopSimplify.h"
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
index 45dc954f97b9..1a4edadec42f 100644
--- a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -14,6 +14,7 @@
 ///
 
//===--===//
 
+#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
@@ -28,7 +29,6 @@
 #include "llvm/PassRegistry.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Transforms/Utils.h"
-#include "llvm/Transforms/Utils/IRCanonicalizer.h"
 #include 
 #include 
 
@@ -174,12 +174,12 @@ void IRCanonicalizer::nameBasicBlocks(Function ) {
 ///
 /// \param I Instruction to be renamed.
 void IRCanonicalizer::nameInstruction(Instruction *I) {
-  //ensure instructions are not renamed. This is done
-  //to prevent situation where instructions are used
-  //before their definition (in phi nodes)
+  // ensure instructions are not renamed. This is done
+  // to prevent situation where instructions are used
+  // before their definition (in phi nodes)
   if (NamedInstructions.contains(I))
 return;
-  NamedInstructions.insert(I); 
+  NamedInstructions.insert(I);
   // Determine the type of instruction to name.
   if (isInitialInstruction(I)) {
 // This is an initial instruction.
@@ -441,7 +441,7 @@ void IRCanonicalizer::reorderInstructions(
 void IRCanonicalizer::reorderInstruction(
 Instruction *Used, Instruction *User,
 SmallPtrSet ) {
-  if(isa(Used))
+  if (isa(Used))
 return;
   if (Visited.contains(Used))
 return;

``




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


[clang-tools-extra] [clangd] Adapt Inlay Hint support for Deducing This (PR #68177)

2023-10-03 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 8641cdf397d86f33ac45e4c691ca4f843c359370 
5e75d4d99cec39fdc3139f1e92036712aea90f57 -- 
clang-tools-extra/clangd/InlayHints.cpp 
clang-tools-extra/clangd/unittests/InlayHintTests.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index 590261d98a04..379e187c424a 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -872,7 +872,8 @@ private:
 else
   ForwardedParams = {Params.begin(), Params.end()};
 
-auto ForwardedParamsRef = 
maybeDropCxxExplicitObjectParameters(ForwardedParams);
+auto ForwardedParamsRef =
+maybeDropCxxExplicitObjectParameters(ForwardedParams);
 NameVec ParameterNames = chooseParameterNames(ForwardedParamsRef);
 
 // Exclude setters (i.e. functions with one argument whose name begins with

``




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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

2023-10-03 Thread via cfe-commits

EugeneZelenko wrote:

Shouldn't documentation be updated too?

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


[clang-tools-extra] [clangd] Adapt Inlay Hint support for Deducing This (PR #68177)

2023-10-03 Thread via cfe-commits

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

>From 5e75d4d99cec39fdc3139f1e92036712aea90f57 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 4 Oct 2023 11:59:31 +0800
Subject: [PATCH 1/2] [clangd] Adapt Inlay Hint support for Deducing This

This is a follow-up for D140828, making Clangd omit the explicit
object parameter in a call to member function with Deducing This.

Given that the parent patch is still in its infancy and might undergo
several reverting-relanding processes, one can feel free to revert
this if encountering any CI failure. And please let me know if I
should alter anything.
---
 clang-tools-extra/clangd/InlayHints.cpp   | 41 +--
 .../clangd/unittests/InlayHintTests.cpp   | 28 +
 2 files changed, 56 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index e6e5e11b889bff8..590261d98a0474f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -528,6 +528,13 @@ static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) {
   return {};
 }
 
+ArrayRef
+maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
+  if (!Params.empty() && Params.front()->isExplicitObjectParameter())
+Params = Params.drop_front(1);
+  return Params;
+}
+
 struct Callee {
   // Only one of Decl or Loc is set.
   // Loc is for calls through function pointers.
@@ -614,15 +621,21 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 // argument expressions present in the function call syntax preceded by the
 // implied object argument (E).
 //
-// However, we don't have the implied object argument for static
-// operator() per clang::Sema::BuildCallToObjectOfClassType.
+// As well as the provision from P0847R7 Deducing This [expr.call]p7:
+// ...If the function is an explicit object member function and there is an
+// implied object argument ([over.call.func]), the list of provided
+// arguments is preceded by the implied object argument for the purposes of
+// this correspondence...
+//
+// However, we don't have the implied object argument
+// for static operator() per clang::Sema::BuildCallToObjectOfClassType.
 llvm::ArrayRef Args = {E->getArgs(), E->getNumArgs()};
-if (IsFunctor)
-  // We don't have the implied object argument through
-  // a function pointer either.
-  if (const CXXMethodDecl *Method =
-  dyn_cast_or_null(Callee.Decl);
-  Method && Method->isInstance())
+// We don't have the implied object argument through a function pointer
+// either.
+if (const CXXMethodDecl *Method =
+dyn_cast_or_null(Callee.Decl))
+  if (Method->isInstance() &&
+  (IsFunctor || Method->hasCXXExplicitFunctionObjectParameter()))
 Args = Args.drop_front(1);
 processCall(Callee, Args);
 return true;
@@ -849,8 +862,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 if (Ctor->isCopyOrMoveConstructor())
   return;
 
-auto Params =
-Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams();
+auto Params = maybeDropCxxExplicitObjectParameters(
+Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams());
 
 // Resolve parameter packs to their forwarded parameter
 SmallVector ForwardedParams;
@@ -859,7 +872,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 else
   ForwardedParams = {Params.begin(), Params.end()};
 
-NameVec ParameterNames = chooseParameterNames(ForwardedParams);
+auto ForwardedParamsRef = 
maybeDropCxxExplicitObjectParameters(ForwardedParams);
+NameVec ParameterNames = chooseParameterNames(ForwardedParamsRef);
 
 // Exclude setters (i.e. functions with one argument whose name begins with
 // "set"), and builtins like std::move/forward/... as their parameter name
@@ -878,7 +892,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 
   StringRef Name = ParameterNames[I];
   bool NameHint = shouldHintName(Args[I], Name);
-  bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
+  bool ReferenceHint =
+  shouldHintReference(Params[I], ForwardedParamsRef[I]);
 
   if (NameHint || ReferenceHint) {
 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
@@ -1018,7 +1033,7 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 return {};
   }
 
-  NameVec chooseParameterNames(SmallVector Parameters) {
+  NameVec chooseParameterNames(ArrayRef Parameters) {
 NameVec ParameterNames;
 for (const auto *P : Parameters) {
   if (isExpandedFromParameterPack(P)) {
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp 
b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index a8c3546eb80cc85..20c1cdd985dbc01 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ 

[clang-tools-extra] [clangd] Adapt Inlay Hint support for Deducing This (PR #68177)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd


Changes

This is a follow-up for D140828, making Clangd omit the explicit object 
parameter in a call to member function with Deducing This.

Given that the parent patch is still in its infancy and might undergo several 
reverting-relanding processes, one can feel free to revert this if encountering 
any CI failure. And please let me know if I should alter anything.

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/InlayHints.cpp (+28-13) 
- (modified) clang-tools-extra/clangd/unittests/InlayHintTests.cpp (+28) 


``diff
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index e6e5e11b889bff8..590261d98a0474f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -528,6 +528,13 @@ static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) {
   return {};
 }
 
+ArrayRef
+maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
+  if (!Params.empty() && Params.front()->isExplicitObjectParameter())
+Params = Params.drop_front(1);
+  return Params;
+}
+
 struct Callee {
   // Only one of Decl or Loc is set.
   // Loc is for calls through function pointers.
@@ -614,15 +621,21 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 // argument expressions present in the function call syntax preceded by the
 // implied object argument (E).
 //
-// However, we don't have the implied object argument for static
-// operator() per clang::Sema::BuildCallToObjectOfClassType.
+// As well as the provision from P0847R7 Deducing This [expr.call]p7:
+// ...If the function is an explicit object member function and there is an
+// implied object argument ([over.call.func]), the list of provided
+// arguments is preceded by the implied object argument for the purposes of
+// this correspondence...
+//
+// However, we don't have the implied object argument
+// for static operator() per clang::Sema::BuildCallToObjectOfClassType.
 llvm::ArrayRef Args = {E->getArgs(), E->getNumArgs()};
-if (IsFunctor)
-  // We don't have the implied object argument through
-  // a function pointer either.
-  if (const CXXMethodDecl *Method =
-  dyn_cast_or_null(Callee.Decl);
-  Method && Method->isInstance())
+// We don't have the implied object argument through a function pointer
+// either.
+if (const CXXMethodDecl *Method =
+dyn_cast_or_null(Callee.Decl))
+  if (Method->isInstance() &&
+  (IsFunctor || Method->hasCXXExplicitFunctionObjectParameter()))
 Args = Args.drop_front(1);
 processCall(Callee, Args);
 return true;
@@ -849,8 +862,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 if (Ctor->isCopyOrMoveConstructor())
   return;
 
-auto Params =
-Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams();
+auto Params = maybeDropCxxExplicitObjectParameters(
+Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams());
 
 // Resolve parameter packs to their forwarded parameter
 SmallVector ForwardedParams;
@@ -859,7 +872,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 else
   ForwardedParams = {Params.begin(), Params.end()};
 
-NameVec ParameterNames = chooseParameterNames(ForwardedParams);
+auto ForwardedParamsRef = 
maybeDropCxxExplicitObjectParameters(ForwardedParams);
+NameVec ParameterNames = chooseParameterNames(ForwardedParamsRef);
 
 // Exclude setters (i.e. functions with one argument whose name begins with
 // "set"), and builtins like std::move/forward/... as their parameter name
@@ -878,7 +892,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 
   StringRef Name = ParameterNames[I];
   bool NameHint = shouldHintName(Args[I], Name);
-  bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
+  bool ReferenceHint =
+  shouldHintReference(Params[I], ForwardedParamsRef[I]);
 
   if (NameHint || ReferenceHint) {
 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
@@ -1018,7 +1033,7 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 return {};
   }
 
-  NameVec chooseParameterNames(SmallVector Parameters) {
+  NameVec chooseParameterNames(ArrayRef Parameters) {
 NameVec ParameterNames;
 for (const auto *P : Parameters) {
   if (isExpandedFromParameterPack(P)) {
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp 
b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index a8c3546eb80cc85..20c1cdd985dbc01 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -843,6 +843,34 @@ TEST(ParameterHints, FunctionCallOperator) {
ExpectedHint{"a: ", "11"}, 

[clang-tools-extra] [clangd] Adapt Inlay Hint support for Deducing This (PR #68177)

2023-10-03 Thread via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/68177

This is a follow-up for D140828, making Clangd omit the explicit object 
parameter in a call to member function with Deducing This.

Given that the parent patch is still in its infancy and might undergo several 
reverting-relanding processes, one can feel free to revert this if encountering 
any CI failure. And please let me know if I should alter anything.

>From 5e75d4d99cec39fdc3139f1e92036712aea90f57 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 4 Oct 2023 11:59:31 +0800
Subject: [PATCH] [clangd] Adapt Inlay Hint support for Deducing This

This is a follow-up for D140828, making Clangd omit the explicit
object parameter in a call to member function with Deducing This.

Given that the parent patch is still in its infancy and might undergo
several reverting-relanding processes, one can feel free to revert
this if encountering any CI failure. And please let me know if I
should alter anything.
---
 clang-tools-extra/clangd/InlayHints.cpp   | 41 +--
 .../clangd/unittests/InlayHintTests.cpp   | 28 +
 2 files changed, 56 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index e6e5e11b889bff8..590261d98a0474f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -528,6 +528,13 @@ static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) {
   return {};
 }
 
+ArrayRef
+maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
+  if (!Params.empty() && Params.front()->isExplicitObjectParameter())
+Params = Params.drop_front(1);
+  return Params;
+}
+
 struct Callee {
   // Only one of Decl or Loc is set.
   // Loc is for calls through function pointers.
@@ -614,15 +621,21 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 // argument expressions present in the function call syntax preceded by the
 // implied object argument (E).
 //
-// However, we don't have the implied object argument for static
-// operator() per clang::Sema::BuildCallToObjectOfClassType.
+// As well as the provision from P0847R7 Deducing This [expr.call]p7:
+// ...If the function is an explicit object member function and there is an
+// implied object argument ([over.call.func]), the list of provided
+// arguments is preceded by the implied object argument for the purposes of
+// this correspondence...
+//
+// However, we don't have the implied object argument
+// for static operator() per clang::Sema::BuildCallToObjectOfClassType.
 llvm::ArrayRef Args = {E->getArgs(), E->getNumArgs()};
-if (IsFunctor)
-  // We don't have the implied object argument through
-  // a function pointer either.
-  if (const CXXMethodDecl *Method =
-  dyn_cast_or_null(Callee.Decl);
-  Method && Method->isInstance())
+// We don't have the implied object argument through a function pointer
+// either.
+if (const CXXMethodDecl *Method =
+dyn_cast_or_null(Callee.Decl))
+  if (Method->isInstance() &&
+  (IsFunctor || Method->hasCXXExplicitFunctionObjectParameter()))
 Args = Args.drop_front(1);
 processCall(Callee, Args);
 return true;
@@ -849,8 +862,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 if (Ctor->isCopyOrMoveConstructor())
   return;
 
-auto Params =
-Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams();
+auto Params = maybeDropCxxExplicitObjectParameters(
+Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams());
 
 // Resolve parameter packs to their forwarded parameter
 SmallVector ForwardedParams;
@@ -859,7 +872,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 else
   ForwardedParams = {Params.begin(), Params.end()};
 
-NameVec ParameterNames = chooseParameterNames(ForwardedParams);
+auto ForwardedParamsRef = 
maybeDropCxxExplicitObjectParameters(ForwardedParams);
+NameVec ParameterNames = chooseParameterNames(ForwardedParamsRef);
 
 // Exclude setters (i.e. functions with one argument whose name begins with
 // "set"), and builtins like std::move/forward/... as their parameter name
@@ -878,7 +892,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 
   StringRef Name = ParameterNames[I];
   bool NameHint = shouldHintName(Args[I], Name);
-  bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
+  bool ReferenceHint =
+  shouldHintReference(Params[I], ForwardedParamsRef[I]);
 
   if (NameHint || ReferenceHint) {
 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
@@ -1018,7 +1033,7 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 return {};
   }
 
-  NameVec chooseParameterNames(SmallVector Parameters) {
+  NameVec chooseParameterNames(ArrayRef 

[clang] llvm-canon (PR #68176)

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

https://github.com/justinfargnoli created 
https://github.com/llvm/llvm-project/pull/68176

Add the llvm-canon tool. Description from the [original 
PR](https://reviews.llvm.org/D66029#change-wZv3yOpDdxIu):

> Added a new llvm-canon tool which aims to transform LLVM Modules into a 
> canonical form by reordering and renaming instructions while preserving the 
> same semantics. This tool makes it easier to spot semantic differences while 
> diffing two modules which have undergone different transformation passes.

This code was originally written by @michalpaszkowski and [submitted to 
mainline 
LLVM](https://reviews.llvm.org/rG14d358537f124a732adad1ec6edf3981dc9baece). 
However, it was quickly 
[reverted](https://reviews.llvm.org/rG335de55fa3384946f1e62050f2545c0966163236) 
to do some BuildBot errors. 

@AidanGoldfarb and I ported the code to the new pass manager, added more tests, 
and fixed some bugs related to PHI nodes that may have been the root cause of 
the BuildBot errors that caused the patch to be reverted. 

Note that this is @AidanGoldfarb and I's first time submitting to LLVM. Please 
liberally critique the PR! 

CC @plotfi for initial review. 

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/14] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void 

[clang] [Support] Rename HashBuilderImpl to HashBuilder (NFC) (PR #68173)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Commit 9370271ec5debcb59e34629d5bd357c44213b2d3 made HashBuilder an
alias for HashBuilderImpl:

  template class HasherT, support::endianness Endianness
  using HashBuilder = HashBuilderImplHasherT, Endianness;

This patch renames HashBuilderImpl to HashBuilder while removing the
alias above.


---

Patch is 20.37 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/68173.diff


8 Files Affected:

- (modified) clang/include/clang/Basic/ObjCRuntime.h (+1-1) 
- (modified) clang/include/clang/Basic/Sanitizers.h (+1-1) 
- (modified) clang/include/clang/Lex/HeaderSearchOptions.h (+2-2) 
- (modified) clang/include/clang/Serialization/ModuleFileExtension.h (+1-2) 
- (modified) llvm/include/llvm/Support/HashBuilder.h (+73-81) 
- (modified) llvm/include/llvm/Support/VersionTuple.h (+2-3) 
- (modified) llvm/unittests/ADT/HashingTest.cpp (+2-2) 
- (modified) llvm/unittests/Support/HashBuilderTest.cpp (+4-4) 


``diff
diff --git a/clang/include/clang/Basic/ObjCRuntime.h 
b/clang/include/clang/Basic/ObjCRuntime.h
index 0f714ed3ad603a5..d783154c3f9f135 100644
--- a/clang/include/clang/Basic/ObjCRuntime.h
+++ b/clang/include/clang/Basic/ObjCRuntime.h
@@ -483,7 +483,7 @@ class ObjCRuntime {
   }
 
   template 
-  friend void addHash(llvm::HashBuilderImpl ,
+  friend void addHash(llvm::HashBuilder ,
   const ObjCRuntime ) {
 HBuilder.add(OCR.getKind(), OCR.getVersion());
   }
diff --git a/clang/include/clang/Basic/Sanitizers.h 
b/clang/include/clang/Basic/Sanitizers.h
index 4659e45c7883419..090a3a7fa907625 100644
--- a/clang/include/clang/Basic/Sanitizers.h
+++ b/clang/include/clang/Basic/Sanitizers.h
@@ -78,7 +78,7 @@ class SanitizerMask {
   llvm::hash_code hash_value() const;
 
   template 
-  friend void addHash(llvm::HashBuilderImpl ,
+  friend void addHash(llvm::HashBuilder ,
   const SanitizerMask ) {
 HBuilder.addRange([0], [kNumElem]);
   }
diff --git a/clang/include/clang/Lex/HeaderSearchOptions.h 
b/clang/include/clang/Lex/HeaderSearchOptions.h
index 126659f3ac00223..206bc69d7b2cdcb 100644
--- a/clang/include/clang/Lex/HeaderSearchOptions.h
+++ b/clang/include/clang/Lex/HeaderSearchOptions.h
@@ -268,7 +268,7 @@ inline llvm::hash_code hash_value(const 
HeaderSearchOptions::Entry ) {
 }
 
 template 
-inline void addHash(llvm::HashBuilderImpl ,
+inline void addHash(llvm::HashBuilder ,
 const HeaderSearchOptions::Entry ) {
   HBuilder.add(E.Path, E.Group, E.IsFramework, E.IgnoreSysRoot);
 }
@@ -279,7 +279,7 @@ hash_value(const HeaderSearchOptions::SystemHeaderPrefix 
) {
 }
 
 template 
-inline void addHash(llvm::HashBuilderImpl ,
+inline void addHash(llvm::HashBuilder ,
 const HeaderSearchOptions::SystemHeaderPrefix ) {
   HBuilder.add(SHP.Prefix, SHP.IsSystemHeader);
 }
diff --git a/clang/include/clang/Serialization/ModuleFileExtension.h 
b/clang/include/clang/Serialization/ModuleFileExtension.h
index 2168ce2ce607c08..528e0aeed2fb341 100644
--- a/clang/include/clang/Serialization/ModuleFileExtension.h
+++ b/clang/include/clang/Serialization/ModuleFileExtension.h
@@ -86,8 +86,7 @@ class ModuleFileExtension
   /// The default implementation of this function simply does nothing, so the
   /// presence/absence of this extension does not distinguish module files.
   using ExtensionHashBuilder =
-  llvm::HashBuilderImpl;
+  llvm::HashBuilder;
   virtual void hashExtension(ExtensionHashBuilder ) const;
 
   /// Create a new module file extension writer, which will be
diff --git a/llvm/include/llvm/Support/HashBuilder.h 
b/llvm/include/llvm/Support/HashBuilder.h
index c3fa011b6aa7e9c..91738b63912a637 100644
--- a/llvm/include/llvm/Support/HashBuilder.h
+++ b/llvm/include/llvm/Support/HashBuilder.h
@@ -85,20 +85,67 @@ template  class HashBuilderBase {
   HasherT 
 };
 
-/// Implementation of the `HashBuilder` interface.
+/// Interface to help hash various types through a hasher type.
+///
+/// Via provided specializations of `add`, `addRange`, and `addRangeElements`
+/// functions, various types (e.g. `ArrayRef`, `StringRef`, etc.) can be hashed
+/// without requiring any knowledge of hashed types from the hasher type.
+///
+/// The only method expected from the templated hasher type `HasherT` is:
+/// * void update(ArrayRef Data)
+///
+/// Additionally, the following methods will be forwarded to the hasher type:
+/// * decltype(std::declval().final()) final()
+/// * decltype(std::declval().result()) result()
+///
+/// From a user point of view, the interface provides the following:
+/// * `template add(const T )`
+///   The `add` function implements hashing of various types.
+/// * `template  void addRange(ItT First, ItT Last)`
+///   The `addRange` function is designed to aid hashing a range of values.
+///   It explicitly adds the size of the range in the hash.
+/// * `template  void addRangeElements(ItT First, ItT Last)`

[clang] [Support] Rename HashBuilderImpl to HashBuilder (NFC) (PR #68173)

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

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/68173

Commit 9370271ec5debcb59e34629d5bd357c44213b2d3 made HashBuilder an
alias for HashBuilderImpl:

  template 
  using HashBuilder = HashBuilderImpl;

This patch renames HashBuilderImpl to HashBuilder while removing the
alias above.


>From bd22d02280110c1abb7e3a66d3cf5d613f5a47e6 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Tue, 3 Oct 2023 18:50:25 -0700
Subject: [PATCH] [Support] Rename HashBuilderImpl to HashBuilder (NFC)

Commit 9370271ec5debcb59e34629d5bd357c44213b2d3 made HashBuilder an
alias for HashBuilderImpl:

  template 
  using HashBuilder = HashBuilderImpl;

This patch renames HashBuilderImpl to HashBuilder while removing the
alias above.
---
 clang/include/clang/Basic/ObjCRuntime.h   |   2 +-
 clang/include/clang/Basic/Sanitizers.h|   2 +-
 clang/include/clang/Lex/HeaderSearchOptions.h |   4 +-
 .../clang/Serialization/ModuleFileExtension.h |   3 +-
 llvm/include/llvm/Support/HashBuilder.h   | 154 +-
 llvm/include/llvm/Support/VersionTuple.h  |   5 +-
 llvm/unittests/ADT/HashingTest.cpp|   4 +-
 llvm/unittests/Support/HashBuilderTest.cpp|   8 +-
 8 files changed, 86 insertions(+), 96 deletions(-)

diff --git a/clang/include/clang/Basic/ObjCRuntime.h 
b/clang/include/clang/Basic/ObjCRuntime.h
index 0f714ed3ad603a5..d783154c3f9f135 100644
--- a/clang/include/clang/Basic/ObjCRuntime.h
+++ b/clang/include/clang/Basic/ObjCRuntime.h
@@ -483,7 +483,7 @@ class ObjCRuntime {
   }
 
   template 
-  friend void addHash(llvm::HashBuilderImpl ,
+  friend void addHash(llvm::HashBuilder ,
   const ObjCRuntime ) {
 HBuilder.add(OCR.getKind(), OCR.getVersion());
   }
diff --git a/clang/include/clang/Basic/Sanitizers.h 
b/clang/include/clang/Basic/Sanitizers.h
index 4659e45c7883419..090a3a7fa907625 100644
--- a/clang/include/clang/Basic/Sanitizers.h
+++ b/clang/include/clang/Basic/Sanitizers.h
@@ -78,7 +78,7 @@ class SanitizerMask {
   llvm::hash_code hash_value() const;
 
   template 
-  friend void addHash(llvm::HashBuilderImpl ,
+  friend void addHash(llvm::HashBuilder ,
   const SanitizerMask ) {
 HBuilder.addRange([0], [kNumElem]);
   }
diff --git a/clang/include/clang/Lex/HeaderSearchOptions.h 
b/clang/include/clang/Lex/HeaderSearchOptions.h
index 126659f3ac00223..206bc69d7b2cdcb 100644
--- a/clang/include/clang/Lex/HeaderSearchOptions.h
+++ b/clang/include/clang/Lex/HeaderSearchOptions.h
@@ -268,7 +268,7 @@ inline llvm::hash_code hash_value(const 
HeaderSearchOptions::Entry ) {
 }
 
 template 
-inline void addHash(llvm::HashBuilderImpl ,
+inline void addHash(llvm::HashBuilder ,
 const HeaderSearchOptions::Entry ) {
   HBuilder.add(E.Path, E.Group, E.IsFramework, E.IgnoreSysRoot);
 }
@@ -279,7 +279,7 @@ hash_value(const HeaderSearchOptions::SystemHeaderPrefix 
) {
 }
 
 template 
-inline void addHash(llvm::HashBuilderImpl ,
+inline void addHash(llvm::HashBuilder ,
 const HeaderSearchOptions::SystemHeaderPrefix ) {
   HBuilder.add(SHP.Prefix, SHP.IsSystemHeader);
 }
diff --git a/clang/include/clang/Serialization/ModuleFileExtension.h 
b/clang/include/clang/Serialization/ModuleFileExtension.h
index 2168ce2ce607c08..528e0aeed2fb341 100644
--- a/clang/include/clang/Serialization/ModuleFileExtension.h
+++ b/clang/include/clang/Serialization/ModuleFileExtension.h
@@ -86,8 +86,7 @@ class ModuleFileExtension
   /// The default implementation of this function simply does nothing, so the
   /// presence/absence of this extension does not distinguish module files.
   using ExtensionHashBuilder =
-  llvm::HashBuilderImpl;
+  llvm::HashBuilder;
   virtual void hashExtension(ExtensionHashBuilder ) const;
 
   /// Create a new module file extension writer, which will be
diff --git a/llvm/include/llvm/Support/HashBuilder.h 
b/llvm/include/llvm/Support/HashBuilder.h
index c3fa011b6aa7e9c..91738b63912a637 100644
--- a/llvm/include/llvm/Support/HashBuilder.h
+++ b/llvm/include/llvm/Support/HashBuilder.h
@@ -85,20 +85,67 @@ template  class HashBuilderBase {
   HasherT 
 };
 
-/// Implementation of the `HashBuilder` interface.
+/// Interface to help hash various types through a hasher type.
+///
+/// Via provided specializations of `add`, `addRange`, and `addRangeElements`
+/// functions, various types (e.g. `ArrayRef`, `StringRef`, etc.) can be hashed
+/// without requiring any knowledge of hashed types from the hasher type.
+///
+/// The only method expected from the templated hasher type `HasherT` is:
+/// * void update(ArrayRef Data)
+///
+/// Additionally, the following methods will be forwarded to the hasher type:
+/// * decltype(std::declval().final()) final()
+/// * decltype(std::declval().result()) result()
+///
+/// From a user point of view, the interface provides the following:
+/// * `template add(const T )`
+///   The `add` function implements hashing of various types.

[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-03 Thread Rajkumar Ananthu via cfe-commits

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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-03 Thread Rajkumar Ananthu via cfe-commits


@@ -4628,6 +4628,12 @@ ASTFileSignature ASTWriter::WriteAST(Sema , 
StringRef OutputFile,
   WritingAST = true;
 
   ASTHasCompilerErrors = hasErrors;
+  bool trueHasErrors = 
SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred();

rajkumarananthu wrote:

Hi @shafik, thanks for your time for the review.

The scenario here is that, at line 4630 you can see the `ASTHasCompilerErrors` 
is being set using `hasErrors` which is an input to the method here 
`ASTWriter::WriteAST()`.

And if you see the description of the issue reported, the user is purposely 
passing the `hasErrors` as `false` even when there is a compiler error in the 
input file, because of this clang is giving a crashing pch file.

So, if the `hasErrors` is not a valid value, I am setting it to the correct 
value. May be I can just remove all the unnecessary code and just directly 
assign `ASTHasCompilerErrors = 
SemaRef.PP.getDiagnostics().hasUncompilableErrorOccured();` which will be 
correct.

And assertion I have added to detect this in debug build early, may be I am 
wrong, sorry for the confusion, it should not behave differently in release and 
debug builds.

Let me know what you think of this?

Thanks
Rajkumar Ananthu.

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


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-03 Thread Matheus Izvekov via cfe-commits

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


[clang] [CLang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/68172

None

>From 4aec8113bc23d361164f1e164c8e4e36a9eb0ad0 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..1e1433589ddd7c9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fdisable-llvm-verifier`` and it's complement 
``-fno-disable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..6911acb7420ec60 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fdisable_llvm_verifier : Flag<["-"], "fdisable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_disable_llvm_verifier : Flag<["-"], "fno-disable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Do not disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..1f1afee57ba4259 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fdisable_llvm_verifier,
+   options::OPT_fno_disable_llvm_verifier, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..f9882c2604cbb18 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fdisable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISABLE-LLVM-VERIFIER %s
+// RUN: %clang -### -S -fno-disable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISABLE-LLVM-VERIFIER %s
+// CHECK-DISABLE-LLVM-VERIFIER: "-disable-llvm-verifier"
+// CHECK-NO-DISABLE-LLVM-VERIFIER-NOT: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

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


[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

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


[clang] 548d67a - [clang][Sema] Fix a bug when instantiating a lambda with requires clause (#65193)

2023-10-03 Thread via cfe-commits

Author: Sheng
Date: 2023-10-04T10:19:35+08:00
New Revision: 548d67a0393c7bd200e335ada0a3d684750c2697

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

LOG: [clang][Sema] Fix a bug when instantiating a lambda with requires clause 
(#65193)

Instantiating a lambda at a scope different from where it is defined
will paralyze clang if the trailing require clause refers to local
variables. This patch fixes this by re-adding the local variables to
`LocalInstantiationScope`.

Fixes #64462

Added: 
clang/test/SemaCXX/pr64462.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3a029e3a0e1ea63..3dce7f6a8f9d56e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -288,6 +288,8 @@ Bug Fixes in This Version
   Fixes (`#67603 `_)
 - Fixes a crash caused by a multidimensional array being captured by a lambda
   (`#67722 `_).
+- Fixes a crash when instantiating a lambda with requires clause.
+  (`#64462 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5bef0335f7891c9..bb05c45391b5473 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7383,7 +7383,8 @@ class Sema final {
   public:
 LambdaScopeForCallOperatorInstantiationRAII(
 Sema , FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
-LocalInstantiationScope );
+LocalInstantiationScope ,
+bool ShouldAddDeclsFromParentScope = true);
   };
 
   /// Check whether the given expression is a valid constraint expression.
@@ -7409,6 +7410,11 @@ class Sema final {
   llvm::ContextualFoldingSet
   SatisfactionCache;
 
+  /// Introduce the instantiated local variables into the local
+  /// instantiation scope.
+  void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
+   const FunctionDecl *PatternDecl,
+   LocalInstantiationScope );
   /// Introduce the instantiated function parameters into the local
   /// instantiation scope, and set the parameter names to those used
   /// in the template.

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 036548b68247bfa..0ef03293b46ffb7 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -702,8 +702,7 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   }
 
   ContextRAII SavedContext{*this, CtxToSave};
-  LocalInstantiationScope Scope(*this, !ForOverloadResolution ||
-   isLambdaCallOperator(FD));
+  LocalInstantiationScope Scope(*this, !ForOverloadResolution);
   std::optional MLTAL =
   SetupConstraintCheckingTemplateArgumentsAndScope(
   const_cast(FD), {}, Scope);
@@ -720,7 +719,8 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
 
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
-  *this, const_cast(FD), *MLTAL, Scope);
+  *this, const_cast(FD), *MLTAL, Scope,
+  ForOverloadResolution);
 
   return CheckConstraintSatisfaction(
   FD, {FD->getTrailingRequiresClause()}, *MLTAL,

diff  --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 6fd91bda61af5a7..421048aaff5c90c 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -2296,33 +2296,55 @@ ExprResult 
Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
   return BuildBlock;
 }
 
+static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) {
+  if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) {
+while (FD->getInstantiatedFromMemberFunction())
+  FD = FD->getInstantiatedFromMemberFunction();
+return FD;
+  }
+
+  if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
+return FD->getInstantiatedFromDecl();
+
+  FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
+  if (!FTD)
+return nullptr;
+
+  while (FTD->getInstantiatedFromMemberTemplate())
+FTD = FTD->getInstantiatedFromMemberTemplate();
+
+  return FTD->getTemplatedDecl();
+}
+
 Sema::LambdaScopeForCallOperatorInstantiationRAII::
 LambdaScopeForCallOperatorInstantiationRAII(
-Sema , FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
-

[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

0x59616e wrote:

Thank you for your review. I appreciate your feedback ;)

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


[clang] [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (PR #67955)

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

owenca wrote:

Reverted in d08fcc817eba.

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


[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Patch by Ryosuke Niwa!

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


5 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
(+62-28) 
- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
(+9-4) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
(+43-4) 
- (added) 
clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor-ref-deref-on-diff-classes.cpp
 (+22) 
- (added) 
clang/test/Analysis/Checkers/WebKit/uncounted-members-ref-deref-on-diff-classes.cpp
 (+23) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 9b1d7ae3e6a320c..a66fa38315f4d11 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -18,24 +18,26 @@ using namespace clang;
 
 namespace {
 
-bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
+bool hasPublicRefMethod(const CXXRecordDecl *R) {
   assert(R);
   assert(R->hasDefinition());
 
-  bool hasRef = false;
-  bool hasDeref = false;
   for (const CXXMethodDecl *MD : R->methods()) {
 const auto MethodName = safeGetName(MD);
+if (MethodName == "ref" && MD->getAccess() == AS_public)
+  return true;
+  }
+  return false;
+}
 
-if (MethodName == "ref" && MD->getAccess() == AS_public) {
-  if (hasDeref)
-return true;
-  hasRef = true;
-} else if (MethodName == "deref" && MD->getAccess() == AS_public) {
-  if (hasRef)
-return true;
-  hasDeref = true;
-}
+bool hasPublicDerefMethod(const CXXRecordDecl *R) {
+  assert(R);
+  assert(R->hasDefinition());
+
+  for (const CXXMethodDecl *MD : R->methods()) {
+const auto MethodName = safeGetName(MD);
+if (MethodName == "deref" && MD->getAccess() == AS_public)
+  return true;
   }
   return false;
 }
@@ -44,9 +46,25 @@ bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
 
 namespace clang {
 
-std::optional
-isRefCountable(const CXXBaseSpecifier* Base)
-{
+std::optional
+hasPublicRefInBase(const CXXBaseSpecifier *Base) {
+  assert(Base);
+
+  const Type *T = Base->getType().getTypePtrOrNull();
+  if (!T)
+return std::nullopt;
+
+  const CXXRecordDecl *R = T->getAsCXXRecordDecl();
+  if (!R)
+return std::nullopt;
+  if (!R->hasDefinition())
+return std::nullopt;
+
+  return hasPublicRefMethod(R) ? R : nullptr;
+}
+
+std::optional
+hasPublicDerefInBase(const CXXBaseSpecifier *Base) {
   assert(Base);
 
   const Type *T = Base->getType().getTypePtrOrNull();
@@ -59,7 +77,7 @@ isRefCountable(const CXXBaseSpecifier* Base)
   if (!R->hasDefinition())
 return std::nullopt;
 
-  return hasPublicRefAndDeref(R) ? R : nullptr;
+  return hasPublicDerefMethod(R) ? R : nullptr;
 }
 
 std::optional isRefCountable(const CXXRecordDecl* R)
@@ -70,29 +88,45 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   if (!R)
 return std::nullopt;
 
-  if (hasPublicRefAndDeref(R))
+  bool hasRef = hasPublicRefMethod(R);
+  bool hasDeref = hasPublicDerefMethod(R);
+  if (hasRef && hasDeref)
 return true;
 
   CXXBasePaths Paths;
   Paths.setOrigin(const_cast(R));
 
   bool AnyInconclusiveBase = false;
-  const auto isRefCountableBase =
-  [](const CXXBaseSpecifier* Base, CXXBasePath&) {
-  std::optional IsRefCountable = 
clang::isRefCountable(Base);
-  if (!IsRefCountable) {
-  AnyInconclusiveBase = true;
-  return false;
-  }
-  return (*IsRefCountable) != nullptr;
+  const auto hasPublicRefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasRefInBase = clang::hasPublicRefInBase(Base);
+if (!hasRefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasRefInBase) != nullptr;
   };
 
-  bool BasesResult = R->lookupInBases(isRefCountableBase, Paths,
-  /*LookupInDependent =*/true);
+  hasRef =
+  R->lookupInBases(hasPublicRefInBase, Paths, /*LookupInDependent =*/true);
+  if (AnyInconclusiveBase)
+return std::nullopt;
+
+  const auto hasPublicDerefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasDerefInBase = clang::hasPublicDerefInBase(Base);
+if (!hasDerefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasDerefInBase) != nullptr;
+  };
+  hasDeref = R->lookupInBases(hasPublicDerefInBase, Paths,
+  /*LookupInDependent =*/true);
   if (AnyInconclusiveBase)
 return std::nullopt;
 
-  return BasesResult;
+  return hasRef && hasDeref;
 }
 
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 

[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)

2023-10-03 Thread Artem Dergachev via cfe-commits

https://github.com/haoNoQ created 
https://github.com/llvm/llvm-project/pull/68170

Patch by Ryosuke Niwa!

>From fc5a447a0dd4203ee69a506cfc791255d555462a Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Tue, 3 Oct 2023 18:13:21 -0700
Subject: [PATCH] [analyzer] WebKit checkers: support ref and deref defined on
 different classes.

---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 90 +--
 .../Checkers/WebKit/PtrTypesSemantics.h   | 13 ++-
 .../WebKit/RefCntblBaseVirtualDtorChecker.cpp | 47 +-
 ...virtual-dtor-ref-deref-on-diff-classes.cpp | 22 +
 ...nted-members-ref-deref-on-diff-classes.cpp | 23 +
 5 files changed, 159 insertions(+), 36 deletions(-)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor-ref-deref-on-diff-classes.cpp
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/uncounted-members-ref-deref-on-diff-classes.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 9b1d7ae3e6a320c..a66fa38315f4d11 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -18,24 +18,26 @@ using namespace clang;
 
 namespace {
 
-bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
+bool hasPublicRefMethod(const CXXRecordDecl *R) {
   assert(R);
   assert(R->hasDefinition());
 
-  bool hasRef = false;
-  bool hasDeref = false;
   for (const CXXMethodDecl *MD : R->methods()) {
 const auto MethodName = safeGetName(MD);
+if (MethodName == "ref" && MD->getAccess() == AS_public)
+  return true;
+  }
+  return false;
+}
 
-if (MethodName == "ref" && MD->getAccess() == AS_public) {
-  if (hasDeref)
-return true;
-  hasRef = true;
-} else if (MethodName == "deref" && MD->getAccess() == AS_public) {
-  if (hasRef)
-return true;
-  hasDeref = true;
-}
+bool hasPublicDerefMethod(const CXXRecordDecl *R) {
+  assert(R);
+  assert(R->hasDefinition());
+
+  for (const CXXMethodDecl *MD : R->methods()) {
+const auto MethodName = safeGetName(MD);
+if (MethodName == "deref" && MD->getAccess() == AS_public)
+  return true;
   }
   return false;
 }
@@ -44,9 +46,25 @@ bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
 
 namespace clang {
 
-std::optional
-isRefCountable(const CXXBaseSpecifier* Base)
-{
+std::optional
+hasPublicRefInBase(const CXXBaseSpecifier *Base) {
+  assert(Base);
+
+  const Type *T = Base->getType().getTypePtrOrNull();
+  if (!T)
+return std::nullopt;
+
+  const CXXRecordDecl *R = T->getAsCXXRecordDecl();
+  if (!R)
+return std::nullopt;
+  if (!R->hasDefinition())
+return std::nullopt;
+
+  return hasPublicRefMethod(R) ? R : nullptr;
+}
+
+std::optional
+hasPublicDerefInBase(const CXXBaseSpecifier *Base) {
   assert(Base);
 
   const Type *T = Base->getType().getTypePtrOrNull();
@@ -59,7 +77,7 @@ isRefCountable(const CXXBaseSpecifier* Base)
   if (!R->hasDefinition())
 return std::nullopt;
 
-  return hasPublicRefAndDeref(R) ? R : nullptr;
+  return hasPublicDerefMethod(R) ? R : nullptr;
 }
 
 std::optional isRefCountable(const CXXRecordDecl* R)
@@ -70,29 +88,45 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   if (!R)
 return std::nullopt;
 
-  if (hasPublicRefAndDeref(R))
+  bool hasRef = hasPublicRefMethod(R);
+  bool hasDeref = hasPublicDerefMethod(R);
+  if (hasRef && hasDeref)
 return true;
 
   CXXBasePaths Paths;
   Paths.setOrigin(const_cast(R));
 
   bool AnyInconclusiveBase = false;
-  const auto isRefCountableBase =
-  [](const CXXBaseSpecifier* Base, CXXBasePath&) {
-  std::optional IsRefCountable = 
clang::isRefCountable(Base);
-  if (!IsRefCountable) {
-  AnyInconclusiveBase = true;
-  return false;
-  }
-  return (*IsRefCountable) != nullptr;
+  const auto hasPublicRefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasRefInBase = clang::hasPublicRefInBase(Base);
+if (!hasRefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasRefInBase) != nullptr;
   };
 
-  bool BasesResult = R->lookupInBases(isRefCountableBase, Paths,
-  /*LookupInDependent =*/true);
+  hasRef =
+  R->lookupInBases(hasPublicRefInBase, Paths, /*LookupInDependent =*/true);
+  if (AnyInconclusiveBase)
+return std::nullopt;
+
+  const auto hasPublicDerefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasDerefInBase = clang::hasPublicDerefInBase(Base);
+if (!hasDerefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasDerefInBase) != nullptr;
+  };
+  hasDeref = R->lookupInBases(hasPublicDerefInBase, Paths,
+  /*LookupInDependent =*/true);
   if 

[clang] d08fcc8 - Revert "[clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (#67955)"

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

Author: Owen Pan
Date: 2023-10-03T18:19:23-07:00
New Revision: d08fcc817eba7f0186620688eee73f6d25fa90e8

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

LOG: Revert "[clang-format] Annotate ctors/dtors as CtorDtorDeclName instead 
(#67955)"

This reverts commit 6a621ed8e4cb02bd55fe4a4a0254615576b70a55 as it caused
buildbots to fail.

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestMacroExpansion.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 5877b0a6124742a..dbd3a6e70f037ef 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -61,7 +61,6 @@ namespace format {
   TYPE(CSharpStringLiteral)
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
-  TYPE(CtorDtorDeclName)   
\
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e1c85d8a08fbf09..3ea65707da90369 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3210,6 +3210,9 @@ static bool isCtorOrDtorName(const FormatToken *Tok) {
 }
 
 void TokenAnnotator::annotate(AnnotatedLine ) {
+  for (auto  : Line.Children)
+annotate(*Child);
+
   AnnotatingParser Parser(Style, Line, Keywords, Scopes);
   Line.Type = Parser.parseLine();
 
@@ -3230,7 +3233,7 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 auto *Tok = getFunctionName(Line);
 if (Tok && ((!Scopes.empty() && Scopes.back() == ST_Class) ||
 Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
-  Tok->setFinalizedType(TT_CtorDtorDeclName);
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
 }
   }
 
@@ -3243,9 +3246,6 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 
   Line.First->SpacesRequiredBefore = 1;
   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
-
-  for (auto  : Line.Children)
-annotate(*Child);
 }
 
 // This function heuristically determines whether 'Current' starts the name of 
a
@@ -3447,13 +3447,9 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
Tok = Tok->Next) {
 if (Tok->Previous->EndsCppAttributeGroup)
   AfterLastAttribute = Tok;
-if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
-IsCtorOrDtor ||
-isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
-  if (!IsCtorOrDtor) {
-LineIsFunctionDeclaration = true;
-Tok->setFinalizedType(TT_FunctionDeclarationName);
-  }
+if (isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
+  LineIsFunctionDeclaration = true;
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
   if (AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
 AfterLastAttribute->MustBreakBefore = true;

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 9061e07add545b9..2cbde3da212ec65 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -975,7 +975,11 @@ void WhitespaceManager::alignConsecutiveDeclarations() {
   AlignTokens(
   Style,
   [](Change const ) {
-if (C.Tok->isOneOf(TT_FunctionDeclarationName, TT_FunctionTypeLParen))
+if (C.Tok->is(TT_FunctionDeclarationName) && C.Tok->Previous &&
+C.Tok->Previous->isNot(tok::tilde)) {
+  return true;
+}
+if (C.Tok->is(TT_FunctionTypeLParen))
   return true;
 if (C.Tok->isNot(TT_StartOfName))
   return false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2ef3c9b299bcad4..246de2f89fccc9d 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10622,12 +10622,6 @@ TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
   verifyFormat("a::\n"
"a\n"
".();");
-
-  

[clang] [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (PR #67955)

2023-10-03 Thread via cfe-commits

dyung wrote:

I'm seeing the same failures on our linux/Windows build bots:
https://lab.llvm.org/buildbot/#/builders/139/builds/50966
https://lab.llvm.org/buildbot/#/builders/216/builds/28315

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


[clang] [Clang][CodeGen] Fix use of CXXThisValue with StrictVTablePointers (PR #68169)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen


Changes

When emitting non-virtual base initializers for the constructor prologue,
we would potentially use a re-laundered this pointer value from a
previous block, which subsequently would not dominate this use.

With this fix, we always launder the original CXXThisValue.

This fixes https://github.com/llvm/llvm-project/issues/67937


Note: First commit just adds the test, which will be fixed by the second 
commit. I will land the test separately after the first round.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGClass.cpp (+3-4) 
- (added) clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp (+22) 


``diff
diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index 57a424c6f176c47..d18f186ce5b4157 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -28,6 +28,7 @@
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Metadata.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "llvm/Transforms/Utils/SanitizerStats.h"
 #include 
 
@@ -1291,10 +1292,10 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 assert(BaseCtorContinueBB);
   }
 
-  llvm::Value *const OldThis = CXXThisValue;
   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
 if (!ConstructVBases)
   continue;
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1311,7 +1312,7 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
   // Then, non-virtual base initializers.
   for (; B != E && (*B)->isBaseInitializer(); B++) {
 assert(!(*B)->isBaseVirtual());
-
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1319,8 +1320,6 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 EmitBaseInitializer(*this, ClassDecl, *B);
   }
 
-  CXXThisValue = OldThis;
-
   InitializeVTablePointers(ClassDecl);
 
   // And finally, initialize class members.
diff --git a/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp 
b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
new file mode 100644
index 000..692ca23a69abe6a
--- /dev/null
+++ b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 %s -I%S -triple=x86_64-pc-windows-msvc 
-fstrict-vtable-pointers -disable-llvm-passes -O1 -emit-llvm -o %t.ll
+// RUN: FileCheck %s < %t.ll
+
+struct A {
+  virtual ~A();
+};
+struct B : virtual A {};
+class C : B {};
+C foo;
+
+// CHECK-LABEL: define {{.*}} @"??0C@@QEAA@XZ"(ptr {{.*}} %this, i32 {{.*}} 
%is_most_derived)
+// CHECK: ctor.init_vbases:
+// CHECK-NEXT: %0 = getelementptr inbounds i8, ptr %this1, i64 0
+// CHECK-NEXT: store ptr @"??_8C@@7B@", ptr %0
+// CHECK-NEXT: %1 = call ptr @llvm.launder.invariant.group.p0(ptr %this1)
+// CHECK-NEXT: %2 = getelementptr inbounds i8, ptr %1, i64 8
+// CHECK-NEXT: %call = call noundef ptr @"??0A@@QEAA@XZ"(ptr {{.*}} %2) #2
+// CHECK-NEXT: br label %ctor.skip_vbases
+// CHECK-EMPTY:
+// CHECK-NEXT: ctor.skip_vbases:
+// CHECK-NEXT: %3 = call ptr @llvm.launder.invariant.group.p0(ptr %this1)
+// CHECK-NEXT: %call3 = call noundef ptr @"??0B@@QEAA@XZ"(ptr {{.*}} %3, i32 
noundef 0) #2

``




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


[clang] [Clang][CodeGen] Fix use of CXXThisValue with StrictVTablePointers (PR #68169)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/68169

When emitting non-virtual base initializers for the constructor prologue,
we would potentially use a re-laundered this pointer value from a
previous block, which subsequently would not dominate this use.

With this fix, we always launder the original CXXThisValue.

This fixes https://github.com/llvm/llvm-project/issues/67937


Note: First commit just adds the test, which will be fixed by the second 
commit. I will land the test separately after the first round.

>From 456b3d4e38fb80c599959d6b1ff5c93d94232394 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 02:34:31 +0200
Subject: [PATCH 1/2] [Clang][CodeGen][NFC] Add (broken) test case for GH67937

This adds a test case for yet unfixed 
https://github.com/llvm/llvm-project/issues/67937
---
 .../strict-vtable-pointers-GH67937.cpp| 29 +++
 1 file changed, 29 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp

diff --git a/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp 
b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
new file mode 100644
index 000..6fb1e68c288b181
--- /dev/null
+++ b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 %s -I%S -triple=x86_64-pc-windows-msvc 
-fstrict-vtable-pointers -disable-llvm-passes -disable-llvm-verifier -O1 
-emit-llvm -o %t.ll
+// RUN: FileCheck %s < %t.ll
+// RUN: not llvm-as < %t.ll -o /dev/null 2>&1 | FileCheck %s 
--check-prefix=CHECK-VERIFIER
+
+struct A {
+  virtual ~A();
+};
+struct B : virtual A {};
+class C : B {};
+C foo;
+
+// FIXME: This is not supposed to generate invalid IR!
+// CHECK-VERIFIER: Instruction does not dominate all uses!
+// CHECK-VERIFIER-NEXT: %1 = call ptr @llvm.launder.invariant.group.p0(ptr 
%this1)
+// CHECK-VERIFIER-NEXT: %3 = call ptr @llvm.launder.invariant.group.p0(ptr %1)
+
+// CHECK-LABEL: define {{.*}} @"??0C@@QEAA@XZ"(ptr {{.*}} %this, i32 {{.*}} 
%is_most_derived)
+// CHECK: ctor.init_vbases:
+// CHECK-NEXT: %0 = getelementptr inbounds i8, ptr %this1, i64 0
+// CHECK-NEXT: store ptr @"??_8C@@7B@", ptr %0
+// CHECK-NEXT: %1 = call ptr @llvm.launder.invariant.group.p0(ptr %this1)
+// CHECK-NEXT: %2 = getelementptr inbounds i8, ptr %1, i64 8
+// CHECK-NEXT: %call = call noundef ptr @"??0A@@QEAA@XZ"(ptr {{.*}} %2) #2
+// CHECK-NEXT: br label %ctor.skip_vbases
+// CHECK-EMPTY:
+// CHECK-NEXT: ctor.skip_vbases:
+// FIXME: Should be using '%this1' instead of %1 below.
+// CHECK-NEXT: %3 = call ptr @llvm.launder.invariant.group.p0(ptr %1)
+// CHECK-NEXT: %call3 = call noundef ptr @"??0B@@QEAA@XZ"(ptr {{.*}} %3, i32 
noundef 0) #2

>From 4073aca154fe55e56b0025509ce85690eba061df Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 02:40:25 +0200
Subject: [PATCH 2/2] [Clang][CodeGen] Fix use of CXXThisValue with
 StrictVTablePointers

When emitting non-virtual base initializers for the constructor prologue,
we would potentially use a re-laundered this pointer value from a
previous block, which subsequently would not dominate this use.

With this fix, we always launder the original CXXThisValue.

This fixes https://github.com/llvm/llvm-project/issues/67937
---
 clang/lib/CodeGen/CGClass.cpp |  7 +++
 .../CodeGenCXX/strict-vtable-pointers-GH67937.cpp | 11 ++-
 2 files changed, 5 insertions(+), 13 deletions(-)

diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index 57a424c6f176c47..d18f186ce5b4157 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -28,6 +28,7 @@
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Metadata.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "llvm/Transforms/Utils/SanitizerStats.h"
 #include 
 
@@ -1291,10 +1292,10 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 assert(BaseCtorContinueBB);
   }
 
-  llvm::Value *const OldThis = CXXThisValue;
   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
 if (!ConstructVBases)
   continue;
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1311,7 +1312,7 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
   // Then, non-virtual base initializers.
   for (; B != E && (*B)->isBaseInitializer(); B++) {
 assert(!(*B)->isBaseVirtual());
-
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1319,8 +1320,6 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 EmitBaseInitializer(*this, ClassDecl, *B);
   }
 
-  CXXThisValue = 

[clang] [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (PR #67955)

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

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


[clang] 6a621ed - [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (#67955)

2023-10-03 Thread via cfe-commits

Author: Owen Pan
Date: 2023-10-03T18:02:09-07:00
New Revision: 6a621ed8e4cb02bd55fe4a4a0254615576b70a55

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

LOG: [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (#67955)

After annotating constructors/destructors as FunctionDeclarationName in
commit 08630512088, we have seen several issues because ctors/dtors had
been treated differently than functions in aligning, wrapping, and
indenting.

This patch annotates ctors/dtors as CtorDtorDeclName instead and would
effectively revert commit 0468fa07f87f, which is obsolete now.

Fixed #67903.
Fixed #67907.

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestMacroExpansion.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index dbd3a6e70f037ef..5877b0a6124742a 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -61,6 +61,7 @@ namespace format {
   TYPE(CSharpStringLiteral)
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
+  TYPE(CtorDtorDeclName)   
\
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ea65707da90369..e1c85d8a08fbf09 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3210,9 +3210,6 @@ static bool isCtorOrDtorName(const FormatToken *Tok) {
 }
 
 void TokenAnnotator::annotate(AnnotatedLine ) {
-  for (auto  : Line.Children)
-annotate(*Child);
-
   AnnotatingParser Parser(Style, Line, Keywords, Scopes);
   Line.Type = Parser.parseLine();
 
@@ -3233,7 +3230,7 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 auto *Tok = getFunctionName(Line);
 if (Tok && ((!Scopes.empty() && Scopes.back() == ST_Class) ||
 Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
-  Tok->setFinalizedType(TT_FunctionDeclarationName);
+  Tok->setFinalizedType(TT_CtorDtorDeclName);
 }
   }
 
@@ -3246,6 +3243,9 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 
   Line.First->SpacesRequiredBefore = 1;
   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
+
+  for (auto  : Line.Children)
+annotate(*Child);
 }
 
 // This function heuristically determines whether 'Current' starts the name of 
a
@@ -3447,9 +3447,13 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
Tok = Tok->Next) {
 if (Tok->Previous->EndsCppAttributeGroup)
   AfterLastAttribute = Tok;
-if (isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
-  LineIsFunctionDeclaration = true;
-  Tok->setFinalizedType(TT_FunctionDeclarationName);
+if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
+IsCtorOrDtor ||
+isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
+  if (!IsCtorOrDtor) {
+LineIsFunctionDeclaration = true;
+Tok->setFinalizedType(TT_FunctionDeclarationName);
+  }
   if (AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
 AfterLastAttribute->MustBreakBefore = true;

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 2cbde3da212ec65..9061e07add545b9 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -975,11 +975,7 @@ void WhitespaceManager::alignConsecutiveDeclarations() {
   AlignTokens(
   Style,
   [](Change const ) {
-if (C.Tok->is(TT_FunctionDeclarationName) && C.Tok->Previous &&
-C.Tok->Previous->isNot(tok::tilde)) {
-  return true;
-}
-if (C.Tok->is(TT_FunctionTypeLParen))
+if (C.Tok->isOneOf(TT_FunctionDeclarationName, TT_FunctionTypeLParen))
   return true;
 if (C.Tok->isNot(TT_StartOfName))
   return false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 246de2f89fccc9d..2ef3c9b299bcad4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10622,6 

[clang-tools-extra] [libc++] Implement ranges::contains (PR #65148)

2023-10-03 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>

var-const wrote:

Sorry, what I mean is that a good and easy way to see if we're testing every 
constraint is to simply remove or comment out a constraint, run the tests and 
see if any tests fail. If we're testing everything properly, at least one test 
will fail -- conversely, if everything passes, that means a lack of test 
coverage. So what I'm suggesting is to temporarily remove the `projected` 
constraint in your local copy, run the tests and see if there are any failures. 
If there are no failures, please see if it's possible to add a test that checks 
we are using the `projected` concept there as required by the Standard. Happy 
to help if this explanation isn't clear!

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


[clang] [libc++] Implement ranges::contains (PR #65148)

2023-10-03 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>

var-const wrote:

Sorry, what I mean is that a good and easy way to see if we're testing every 
constraint is to simply remove or comment out a constraint, run the tests and 
see if any tests fail. If we're testing everything properly, at least one test 
will fail -- conversely, if everything passes, that means a lack of test 
coverage. So what I'm suggesting is to temporarily remove the `projected` 
constraint in your local copy, run the tests and see if there are any failures. 
If there are no failures, please see if it's possible to add a test that checks 
we are using the `projected` concept there as required by the Standard. Happy 
to help if this explanation isn't clear!

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


[libunwind] [libc++] Implement ranges::contains (PR #65148)

2023-10-03 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>

var-const wrote:

Sorry, what I mean is that a good and easy way to see if we're testing every 
constraint is to simply remove or comment out a constraint, run the tests and 
see if any tests fail. If we're testing everything properly, at least one test 
will fail -- conversely, if everything passes, that means a lack of test 
coverage. So what I'm suggesting is to temporarily remove the `projected` 
constraint in your local copy, run the tests and see if there are any failures. 
If there are no failures, please see if it's possible to add a test that checks 
we are using the `projected` concept there as required by the Standard. Happy 
to help if this explanation isn't clear!

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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-03 Thread Shafik Yaghmour via cfe-commits


@@ -4628,6 +4628,12 @@ ASTFileSignature ASTWriter::WriteAST(Sema , 
StringRef OutputFile,
   WritingAST = true;
 
   ASTHasCompilerErrors = hasErrors;
+  bool trueHasErrors = 
SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred();

shafik wrote:

So this logic seems wrong. You are on one hand asserting `ASTHasCompilerErrors 
== trueHasErrors` and yet checking if they are not equal.


Is `getDiagnostics().hasUncompilableErrorOccurred()` in `ASTUnit::serialize` 
not the same as `SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred()`? 


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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-03 Thread Shafik Yaghmour via cfe-commits

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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-03 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

The fix does not look correct but perhaps someone else will have more insight.

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


[clang] 1dceba3 - [analyzer] Fix false negative when accessing a nonnull property from … (#67563)

2023-10-03 Thread via cfe-commits

Author: tripleCC
Date: 2023-10-04T08:38:10+08:00
New Revision: 1dceba3a3684d12394731e09a6cf3efcebf07a3a

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

LOG: [analyzer] Fix false negative when accessing a nonnull property from … 
(#67563)

```
@interface A : NSObject
@property (nonnull, nonatomic, strong) NSString *name;
+ (nullable instancetype)shared;
@end

@[[A shared].name];
```
Consider the code above, the nullability of the name property should
depend on the result of the shared method. A warning is expected because
of adding a nullable object to array.
ObjCMessageExpr gets the actual type through
Sema::getMessageSendResultType, instead of using the return type of
MethodDecl directly. The final type is generated by considering the
nullability of receiver and MethodDecl together.
Thus, the RetType in NullabilityChecker should all be replaced with
M.getOriginExpr()->getType().

Co-authored-by: tripleCC 

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
clang/test/Analysis/nullability.mm

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
index 906f4e85a8e5b5b..627b51af6bd44af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -899,6 +899,14 @@ void NullabilityChecker::checkPostCall(const CallEvent 
,
   const NullabilityState *TrackedNullability =
   State->get(Region);
 
+  // ObjCMessageExpr gets the actual type through
+  // Sema::getMessageSendResultType, instead of using the return type of
+  // MethodDecl directly. The final type is generated by considering the
+  // nullability of receiver and MethodDecl together. Thus, The type of
+  // ObjCMessageExpr is prefer.
+  if (const Expr *E = Call.getOriginExpr())
+ReturnType = E->getType();
+
   if (!TrackedNullability &&
   getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
 State = State->set(Region, Nullability::Nullable);
@@ -1053,7 +1061,7 @@ void NullabilityChecker::checkPostObjCMessage(const 
ObjCMethodCall ,
   }
 
   // No tracked information. Use static type information for return value.
-  Nullability RetNullability = getNullabilityAnnotation(RetType);
+  Nullability RetNullability = getNullabilityAnnotation(Message->getType());
 
   // Properties might be computed, which means the property value could
   // theoretically change between calls even in commonly-observed cases like

diff  --git a/clang/test/Analysis/nullability.mm 
b/clang/test/Analysis/nullability.mm
index 06bb9912296e32f..d69116d03df7465 100644
--- a/clang/test/Analysis/nullability.mm
+++ b/clang/test/Analysis/nullability.mm
@@ -55,6 +55,7 @@ - (void)takesUnspecified:(int *)p;
 @property(readonly, nullable) void (^propReturnsNullableBlock)(void);
 @property(readonly, nullable) int *propReturnsNullable;
 @property(readonly) int *propReturnsUnspecified;
++ (nullable TestObject *)getNullableObject;
 @end
 
 TestObject * getUnspecifiedTestObject();
@@ -256,6 +257,12 @@ void testObjCPropertyReadNullability() {
   case 8:
 [o takesNonnullBlock:o.propReturnsNullableBlock]; // expected-warning 
{{Nullable pointer is passed to a callee that requires a non-null 1st 
parameter}}
 break;
+  case 9:
+[o takesNonnull:getNullableTestObject().propReturnsNonnull]; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+break;
+  case 10:
+[o takesNonnull:[TestObject getNullableObject].propReturnsNonnull]; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+break;
   }
 }
 



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


[clang] [analyzer] Fix false negative when accessing a nonnull property from … (PR #67563)

2023-10-03 Thread via cfe-commits

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


[PATCH] D133361: [BPF] Attribute preserve_static_offset for structs

2023-10-03 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:3701
+  QualType PointeeType = E->getType()->getPointeeType();
+  if (PointeeType.isNull())
+return false;

erichkeane wrote:
> We override `operator bool` to make this work.
Sorry, just to clarify, currently such modification fails with the following 
error:

```
lang=c++
clang/lib/CodeGen/CGExpr.cpp:3710:7: error: invalid argument type 'QualType' to 
unary expression
  if (!PointeeType)
  ^~~~
1 error generated.
```

And you want me to modify `QualType` as follows:

```
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -796,6 +796,8 @@ public:
 return getTypePtr();
   }
 
+  explicit operator bool() const { return isNull(); }
+
   bool isCanonical() const;
   bool isCanonicalAsParam() const;
```

Right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133361

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


[clang] [libc++] Implement ranges::contains (PR #65148)

2023-10-03 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/65148

>From 02e9afd761228f401df4d9f8dfaaca44ffae0c6e Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 31 Aug 2023 20:08:32 +
Subject: [PATCH 01/12] [libc++] Implement ranges::contains

Differential Revision: https://reviews.llvm.org/D159232
---
 libcxx/include/CMakeLists.txt |   1 +
 libcxx/include/__algorithm/ranges_contains.h  |  60 ++
 libcxx/include/algorithm  |   9 +
 ...obust_against_copying_projections.pass.cpp |   4 +
 .../alg.contains/ranges.contains.pass.cpp | 190 ++
 .../niebloid.compile.pass.cpp |   1 +
 6 files changed, 265 insertions(+)
 create mode 100644 libcxx/include/__algorithm/ranges_contains.h
 create mode 100644 
libcxx/test/std/algorithms/alg.nonmodifying/alg.contains/ranges.contains.pass.cpp

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 77a7269121ec142..024aa8959fb7200 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -104,6 +104,7 @@ set(files
   __algorithm/ranges_any_of.h
   __algorithm/ranges_binary_search.h
   __algorithm/ranges_clamp.h
+  __algorithm/ranges_contains.h
   __algorithm/ranges_copy.h
   __algorithm/ranges_copy_backward.h
   __algorithm/ranges_copy_if.h
diff --git a/libcxx/include/__algorithm/ranges_contains.h 
b/libcxx/include/__algorithm/ranges_contains.h
new file mode 100644
index 000..647b7ea34be3421
--- /dev/null
+++ b/libcxx/include/__algorithm/ranges_contains.h
@@ -0,0 +1,60 @@
+//===--===//
+//
+// 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 _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>
+#include <__algorithm/ranges_find.h>
+#include <__config>
+#include <__functional/identity.h>
+#include <__functional/ranges_operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/indirectly_comparable.h>
+#include <__iterator/projected.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+#if _LIBCPP_STD_VER >= 23
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+namespace ranges {
+namespace __contains {
+struct __fn {
+  template  _Sent, class _Type, 
class _Proj = identity>
+requires indirect_binary_predicate, const _Type*>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool
+  operator()(_Iter __first, _Sent __last, const _Type& __value, _Proj __proj = 
{}) const {
+return ranges::find(std::move(__first), std::move(__last), __value, 
std::ref(__proj)) != __last;
+  }
+
+  template 
+requires indirect_binary_predicate, _Proj>, const _Type*>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool
+  operator()(_Range&& __range, const _Type& __value, _Proj __proj = {}) const {
+return ranges::find(ranges::begin(__range), ranges::end(__range), __value, 
std::ref(__proj)) != ranges::end(__range);
+  }
+};
+} // namespace __contains
+inline namespace __cpo {
+inline constexpr auto contains = __contains::__fn{};
+} // namespace __cpo
+} // namespace ranges
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP_STD_VER >= 23
+
+#endif // _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
diff --git a/libcxx/include/algorithm b/libcxx/include/algorithm
index 76e0d22bf73ef85..003bf132b38b4d8 100644
--- a/libcxx/include/algorithm
+++ b/libcxx/include/algorithm
@@ -226,6 +226,14 @@ namespace ranges {
   template
 using copy_backward_result = in_out_result;
 // since C++20
 
+  template S, class T, class Proj = identity>
+requires indirect_binary_predicate, 
const T*>
+constexpr bool ranges::contains(I first, S last, const T& value, Proj proj 
= {});   // since C++23
+
+  template
+requires indirect_binary_predicate, Proj>, const T*>
+constexpr bool ranges::contains(R&& r, const T& value, Proj proj = {});
 // since C++23
+
   template S, weakly_incrementable O>
 requires indirectly_copyable
 constexpr ranges::copy_result ranges::copy(I first, S last, O 
result);// since C++20
@@ -1827,6 +1835,7 @@ template 
 #include <__algorithm/ranges_any_of.h>
 #include <__algorithm/ranges_binary_search.h>
 #include <__algorithm/ranges_clamp.h>
+#include <__algorithm/ranges_contains.h>
 #include <__algorithm/ranges_copy.h>
 #include <__algorithm/ranges_copy_backward.h>
 #include <__algorithm/ranges_copy_if.h>
diff --git 

[clang] 496d00b - [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (#67755)

2023-10-03 Thread via cfe-commits

Author: PiJoules
Date: 2023-10-03T17:05:21-07:00
New Revision: 496d00b2677593066f5119e93cf0e9316a04277a

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

LOG: [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of 
External linkage (#67755)

This way, it the rtti_proxies can be candidates for being replaced
altogether with GOTPCREL relocations because they are discardable.
Functionally, this shouldn't change the final ELF linkage of the
proxies.

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp
clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
clang/test/CodeGenCXX/RelativeVTablesABI/simple-vtable-definition.cpp
clang/test/CodeGenCXX/RelativeVTablesABI/type-info.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index c81b67ecf4fee0d..25e4b1c27932026 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -640,8 +640,16 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder ,
   // want the stub/proxy to be emitted for properly calculating the offset.
   // Examples where there would be no symbol emitted are available_externally
   // and private linkages.
-  auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
-   : 
llvm::GlobalValue::ExternalLinkage;
+  //
+  // `internal` linkage results in STB_LOCAL Elf binding while still 
manifesting a
+  // local symbol.
+  //
+  // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also 
allows for
+  // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
+  // target that supports this replacement.
+  auto stubLinkage = vtableHasLocalLinkage
+ ? llvm::GlobalValue::InternalLinkage
+ : llvm::GlobalValue::LinkOnceODRLinkage;
 
   llvm::Constant *target;
   if (auto *func = dyn_cast(globalVal)) {

diff  --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
index 48b1d8ed65d7e55..950921f67509f42 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
@@ -8,7 +8,6 @@
 // CHECK-DAG: $_ZTS1B = comdat any
 // CHECK-DAG: $_ZTI1B = comdat any
 // CHECK-DAG: $_ZTI1B.rtti_proxy = comdat any
-// CHECK-DAG: $_ZTI1A.rtti_proxy = comdat any
 
 // VTable for B is emitted here since we access it when creating an instance 
of B. The VTable is also linkonce_odr and in its own comdat.
 // CHECK-DAG: @_ZTV1B.local = linkonce_odr hidden unnamed_addr constant { [3 x 
i32] } { [3 x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr 
@_ZTI1B.rtti_proxy to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x 
i32] }, ptr @_ZTV1B.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc 
(i64 sub (i64 ptrtoint (ptr dso_local_equivalent @_ZN1B3fooEv to i64), i64 
ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B.local, i32 0, 
i32 0, i32 2) to i64)) to i32)] }, comdat($_ZTV1B), align 4
@@ -18,7 +17,7 @@
 // CHECK-DAG: @_ZTS1B =
 // CHECK-DAG: @_ZTI1A =
 // CHECK-DAG: @_ZTI1B =
-// CHECK-DAG: @_ZTI1B.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1B, 
comdat
+// CHECK-DAG: @_ZTI1B.rtti_proxy = linkonce_odr hidden unnamed_addr constant 
ptr @_ZTI1B, comdat
 
 // We will emit a vtable for B here, so it does have an alias, but we will not
 // emit one for A.

diff  --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
index 5f5f9edf411a809..ee710100152bfac 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
@@ -18,7 +18,7 @@
 // CHECK: @_ZTVN10__cxxabiv117__class_type_infoE = external global [0 x ptr]
 // CHECK: @_ZTS1A = linkonce_odr constant [3 x i8] c"1A\00", comdat, align 1
 // CHECK: @_ZTI1A = linkonce_odr constant { ptr, ptr } { ptr getelementptr 
inbounds (i8, ptr @_ZTVN10__cxxabiv117__class_type_infoE, i32 8), ptr @_ZTS1A 
}, comdat, align 8
-// CHECK: @_ZTI1A.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1A, comdat
+// CHECK: @_ZTI1A.rtti_proxy = linkonce_odr hidden unnamed_addr constant ptr 
@_ZTI1A, comdat
 // CHECK: @_ZTV1A = linkonce_odr unnamed_addr alias { [3 x i32] }, ptr 
@_ZTV1A.local
 
 // CHECK:  define linkonce_odr void @_ZN1A3fooEv(ptr {{.*}}%this) 
unnamed_addr #{{[0-9]+}} comdat

diff  --git 

[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread via cfe-commits

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread via cfe-commits

https://github.com/PiJoules updated 
https://github.com/llvm/llvm-project/pull/67755

>From 2607a99be986215fa27c053755e96c81bb2033e7 Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Fri, 29 Sep 2023 00:25:44 +
Subject: [PATCH] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR
 instead of External linkage

This way, it the rtti_proxies can be candidates for being replaced
altogether with GOTPCREL relocations because they are discardable.
Functionally, this shouldn't change the final ELF linkage of the
proxies.
---
 clang/lib/CodeGen/CGVTables.cpp  | 12 ++--
 .../RelativeVTablesABI/child-vtable-in-comdat.cpp|  3 +--
 .../RelativeVTablesABI/parent-vtable-in-comdat.cpp   |  2 +-
 .../RelativeVTablesABI/relative-vtables-hwasan.cpp   |  4 ++--
 .../RelativeVTablesABI/simple-vtable-definition.cpp  |  2 +-
 .../test/CodeGenCXX/RelativeVTablesABI/type-info.cpp |  4 ++--
 6 files changed, 17 insertions(+), 10 deletions(-)

diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 23cfcdd138439f0..3cf88b1caa30ad4 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -639,8 +639,16 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder ,
   // want the stub/proxy to be emitted for properly calculating the offset.
   // Examples where there would be no symbol emitted are available_externally
   // and private linkages.
-  auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
-   : 
llvm::GlobalValue::ExternalLinkage;
+  //
+  // `internal` linkage results in STB_LOCAL Elf binding while still 
manifesting a
+  // local symbol.
+  //
+  // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also 
allows for
+  // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
+  // target that supports this replacement.
+  auto stubLinkage = vtableHasLocalLinkage
+ ? llvm::GlobalValue::InternalLinkage
+ : llvm::GlobalValue::LinkOnceODRLinkage;
 
   llvm::Constant *target;
   if (auto *func = dyn_cast(globalVal)) {
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
index 48b1d8ed65d7e55..950921f67509f42 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
@@ -8,7 +8,6 @@
 // CHECK-DAG: $_ZTS1B = comdat any
 // CHECK-DAG: $_ZTI1B = comdat any
 // CHECK-DAG: $_ZTI1B.rtti_proxy = comdat any
-// CHECK-DAG: $_ZTI1A.rtti_proxy = comdat any
 
 // VTable for B is emitted here since we access it when creating an instance 
of B. The VTable is also linkonce_odr and in its own comdat.
 // CHECK-DAG: @_ZTV1B.local = linkonce_odr hidden unnamed_addr constant { [3 x 
i32] } { [3 x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr 
@_ZTI1B.rtti_proxy to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x 
i32] }, ptr @_ZTV1B.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc 
(i64 sub (i64 ptrtoint (ptr dso_local_equivalent @_ZN1B3fooEv to i64), i64 
ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B.local, i32 0, 
i32 0, i32 2) to i64)) to i32)] }, comdat($_ZTV1B), align 4
@@ -18,7 +17,7 @@
 // CHECK-DAG: @_ZTS1B =
 // CHECK-DAG: @_ZTI1A =
 // CHECK-DAG: @_ZTI1B =
-// CHECK-DAG: @_ZTI1B.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1B, 
comdat
+// CHECK-DAG: @_ZTI1B.rtti_proxy = linkonce_odr hidden unnamed_addr constant 
ptr @_ZTI1B, comdat
 
 // We will emit a vtable for B here, so it does have an alias, but we will not
 // emit one for A.
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
index 5f5f9edf411a809..ee710100152bfac 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
@@ -18,7 +18,7 @@
 // CHECK: @_ZTVN10__cxxabiv117__class_type_infoE = external global [0 x ptr]
 // CHECK: @_ZTS1A = linkonce_odr constant [3 x i8] c"1A\00", comdat, align 1
 // CHECK: @_ZTI1A = linkonce_odr constant { ptr, ptr } { ptr getelementptr 
inbounds (i8, ptr @_ZTVN10__cxxabiv117__class_type_infoE, i32 8), ptr @_ZTS1A 
}, comdat, align 8
-// CHECK: @_ZTI1A.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1A, comdat
+// CHECK: @_ZTI1A.rtti_proxy = linkonce_odr hidden unnamed_addr constant ptr 
@_ZTI1A, comdat
 // CHECK: @_ZTV1A = linkonce_odr unnamed_addr alias { [3 x i32] }, ptr 
@_ZTV1A.local
 
 // CHECK:  define linkonce_odr void @_ZN1A3fooEv(ptr {{.*}}%this) 
unnamed_addr #{{[0-9]+}} comdat
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
index 

[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

2023-10-03 Thread Jan Svoboda via cfe-commits

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


[clang-tools-extra] [libc++] Implement ranges::contains (PR #65148)

2023-10-03 Thread via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>
+#include <__algorithm/ranges_find.h>
+#include <__config>
+#include <__functional/identity.h>
+#include <__functional/ranges_operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/indirectly_comparable.h>
+#include <__iterator/projected.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+#if _LIBCPP_STD_VER >= 23
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+namespace ranges {
+namespace __contains {
+struct __fn {
+  template  _Sent, class _Type, 
class _Proj = identity>
+requires indirect_binary_predicate, const _Type*>

ZijunZhaoCCK wrote:

I copied from here https://eel.is/c++draft/alg.nonmodifying#alg.contains

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

2023-10-03 Thread Jan Svoboda via cfe-commits

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


[PATCH] D158561: [-Wunsafe-buffer-usage] Add AST info to the unclaimed DRE debug notes for analysis

2023-10-03 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 557579.
ziqingluo-90 added a comment.

address comments


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

https://reviews.llvm.org/D158561

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
  
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
  clang/utils/analyze_safe_buffer_debug_notes.py

Index: clang/utils/analyze_safe_buffer_debug_notes.py
===
--- /dev/null
+++ clang/utils/analyze_safe_buffer_debug_notes.py
@@ -0,0 +1,39 @@
+import sys
+from collections import OrderedDict
+
+class Trie:
+def __init__(self, name):
+self.name = name
+self.children = OrderedDict()
+self.count = 1
+
+def add(self, name):
+if name in self.children:
+self.children[name].count += 1
+else:
+self.children[name] = Trie(name)
+return self.children[name]
+
+def print(self, depth):
+if depth > 0:
+print('|', end="")
+for i in range(depth):
+print('-', end="")
+if depth > 0:
+print(end=" ")
+print(self.name, '#', self.count)
+for key, child in self.children.items():
+child.print(depth + 1)
+
+
+Root = Trie("Root")
+
+if __name__ == "__main__":
+for line in sys.stdin:
+words = line.split('==>')
+words = [word.strip() for word in words]
+MyTrie = Root;
+for word in words:
+MyTrie = MyTrie.add(word)
+
+Root.print(0)
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 -verify=expected %s
+
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 %s  \
+// RUN:2>&1 | grep 'The unclaimed DRE trace:' \
+// RUN: | sed 's/^The unclaimed DRE trace://' \
+// RUN: | %analyze_safe_buffer_debug_notes \
+// RUN: | FileCheck %s
+
+// This debugging facility is only available in debug builds.
+//
+// REQUIRES: asserts
+// REQUIRES: shell
+
+void test_unclaimed_use(int *p) { // expected-warning{{'p' is an unsafe pointer used for buffer access}}
+  p++;   //  expected-note{{used in pointer arithmetic here}} \
+ expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+ The unclaimed DRE trace: DeclRefExpr, UnaryOperator(++), CompoundStmt}}
+  *((p + 1) + 1); // expected-warning{{unsafe pointer arithmetic}}  \
+ expected-note{{used in pointer arithmetic here}}			\
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, ImplicitCastExpr(LValueToRValue), BinaryOperator(+), ParenExpr, BinaryOperator(+), ParenExpr, UnaryOperator(*), CompoundStmt}}
+  p -= 1; // expected-note{{used in pointer arithmetic here}} \
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, BinaryOperator(-=), CompoundStmt}}
+  p--;// expected-note{{used in pointer arithmetic here}} \
+ 		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, UnaryOperator(--), CompoundStmt}}
+  p[5] = 5;   // expected-note{{used in buffer access here}}
+}
+
+// CHECK: Root # 1
+// CHECK: |- DeclRefExpr # 4
+// CHECK: |-- UnaryOperator(++) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- ImplicitCastExpr(LValueToRValue) # 1
+// CHECK: |--- BinaryOperator(+) # 1
+// CHECK: | ParenExpr # 1
+// CHECK: |- BinaryOperator(+) # 1
+// CHECK: |-- ParenExpr # 1
+// CHECK: |--- UnaryOperator(*) # 1
+// CHECK: | CompoundStmt # 1
+// CHECK: |-- BinaryOperator(-=) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- UnaryOperator(--) # 1
+// CHECK: |--- CompoundStmt # 1
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
@@ -0,0 +1,11 @@
+# -*- Python -*-
+
+config.substitutions.append(
+  (
+

[clang] [IRPGO][ValueProfile] Instrument virtual table address that could be used to do virtual table address comparision for indirect-call-promotion. (PR #66825)

2023-10-03 Thread via cfe-commits

modiking wrote:

> Yes there are tradeoffs to doing this purely with whole program class 
> hierarchy analysis vs with profiled type info, and in fact they can be 
> complementary. For example, the profile info can indicate what order to do 
> the vtable comparisons (i.e. descending order of hotness, as we do for vfunc 
> comparisons in current ICP), while WP CHA can be used to determine when no 
> fallback is required. Also, another advantage of doing this with profiling is 
> also that it does not require WP visibility, which may be difficult to 
> guarantee.

Gotcha, that makes sense. Are there plans on your side to extend this level of 
value profiling/WP CHA to AutoFDO? I'm looking into trying out the WP CHA 
approach on my side since it looks like there are cases it can catch in our 
internal workloads.

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


[clang] [IRPGO][ValueProfile] Instrument virtual table address that could be used to do virtual table address comparision for indirect-call-promotion. (PR #66825)

2023-10-03 Thread via cfe-commits


@@ -43,19 +45,15 @@ int main(int argc, const char *argv[]) {
   uint64_t bufsize = __llvm_profile_get_size_for_buffer_internal(
   __llvm_profile_begin_data(), __llvm_profile_end_data(),
   __llvm_profile_begin_counters(), __llvm_profile_end_counters(),
-  __llvm_profile_begin_names(), __llvm_profile_end_names());
+  __llvm_profile_begin_names(), __llvm_profile_end_names(), NULL, NULL,
+  NULL, NULL);
 
   char *buf = malloc(bufsize);
   int ret = __llvm_profile_write_buffer_internal(buf,
   __llvm_profile_begin_data(), __llvm_profile_end_data(),
   __llvm_profile_begin_counters(), __llvm_profile_end_counters(),
   __llvm_profile_begin_names(), __llvm_profile_end_names());
 
-  if (ret != 0) {

modiking wrote:

Looks like this early return got deleted, intentional?

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


[clang] [IRPGO][ValueProfile] Instrument virtual table address that could be used to do virtual table address comparision for indirect-call-promotion. (PR #66825)

2023-10-03 Thread via cfe-commits


@@ -19,20 +19,38 @@ namespace llvm {
 // Visitor class that finds all indirect call.
 struct PGOIndirectCallVisitor : public InstVisitor {
   std::vector IndirectCalls;
+  std::vector VTableAddrs;
   PGOIndirectCallVisitor() = default;
 
   void visitCallBase(CallBase ) {
 if (Call.isIndirectCall())
-  IndirectCalls.push_back();
+  if (Call.isIndirectCall()) {
+IndirectCalls.push_back();
+
+LoadInst *LI = dyn_cast(Call.getCalledOperand());

modiking wrote:

Taking a dependency on `-fwhole-program-vtables` for this does mean 
instrumentation fails when the flag is not enabled. Might make sense to detect 
this scenario and warn/message to the user that this is happening.

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


[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Peiming Liu via cfe-commits


@@ -586,30 +586,56 @@ Attribute SparseTensorEncodingAttr::parse(AsmParser 
, Type type) {
 }
 
 void SparseTensorEncodingAttr::print(AsmPrinter ) const {
-  // Print the struct-like storage in dictionary fashion.
-  printer << "<{ lvlTypes = [ ";
-  llvm::interleaveComma(getLvlTypes(), printer, [&](DimLevelType dlt) {
-printer << "\"" << toMLIRString(dlt) << "\"";
-  });
-  printer << " ]";
+  auto map = static_cast(getDimToLvl());
+  auto lvlTypes = getLvlTypes();
+  // Empty affine map indicates identity map
+  if (!map) {
+map = AffineMap::getMultiDimIdentityMap(getLvlTypes().size(), 
getContext());
+  }
+  // Modified version of AsmPrinter::Impl::printAffineMap.
+  printer << "<{ map = ";
+  // Symbolic identifiers.
+  if (map.getNumSymbols() != 0) {
+printer << '[';
+for (unsigned i = 0; i < map.getNumSymbols() - 1; ++i)
+  printer << 's' << i << ", ";
+if (map.getNumSymbols() >= 1)
+  printer << 's' << map.getNumSymbols() - 1;
+printer << ']';
+  }
+  // Dimension identifiers.
+  printer << '(';
+  auto dimSlices = getDimSlices();
+  if (!dimSlices.empty()) {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << " : " << dimSlices[i] << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1 << " : "
+  << dimSlices[map.getNumDims() - 1];
+  } else {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1;
+  }
+  printer << ')';
+  // Level format and properties.
+  printer << " -> (";
+  for (unsigned i = 0; i < map.getNumResults() - 1; ++i) {
+map.getResult(i).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[i]) << ", ";
+  }
+  if (map.getNumResults() >= 1) {
+auto lastIndex = map.getNumResults() - 1;
+map.getResult(lastIndex).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[lastIndex]);
+  }
+  printer << ')';

PeimingLiu wrote:

I would suggest you break these into smaller functions.

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


[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Aart Bik via cfe-commits


@@ -586,30 +586,56 @@ Attribute SparseTensorEncodingAttr::parse(AsmParser 
, Type type) {
 }
 
 void SparseTensorEncodingAttr::print(AsmPrinter ) const {
-  // Print the struct-like storage in dictionary fashion.
-  printer << "<{ lvlTypes = [ ";
-  llvm::interleaveComma(getLvlTypes(), printer, [&](DimLevelType dlt) {
-printer << "\"" << toMLIRString(dlt) << "\"";
-  });
-  printer << " ]";
+  auto map = static_cast(getDimToLvl());
+  auto lvlTypes = getLvlTypes();
+  // Empty affine map indicates identity map
+  if (!map) {
+map = AffineMap::getMultiDimIdentityMap(getLvlTypes().size(), 
getContext());
+  }
+  // Modified version of AsmPrinter::Impl::printAffineMap.

aartbik wrote:

I would remove this. This is diverged sufficiently to no longer refer to 
printAffineMap

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


[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Aart Bik via cfe-commits


@@ -472,8 +472,11 @@ class SparseInsertGenerator
 llvm::raw_svector_ostream nameOstream(nameBuffer);
 nameOstream << kInsertFuncNamePrefix;
 const Level lvlRank = stt.getLvlRank();
-for (Level l = 0; l < lvlRank; l++)
-  nameOstream << toMLIRString(stt.getLvlType(l)) << "_";
+for (Level l = 0; l < lvlRank; l++) {
+  std::string lvlType = toMLIRString(stt.getLvlType(l));
+  replaceWithUnderscore(lvlType);

aartbik wrote:

std::string::replace ?

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

2023-10-03 Thread Jan Svoboda via cfe-commits


@@ -701,6 +701,10 @@ class SourceManager : public RefCountedBase 
{
   /// use (-ID - 2).
   SmallVector LoadedSLocEntryTable;
 
+  /// For each allocation in LoadedSLocEntryTable, we keep the new size. This
+  /// can be used to determine whether two FileIDs come from the same AST file.
+  SmallVector LoadedSLocEntryTableSegments;

jansvoboda11 wrote:

Or this?

```c++
SmallVector LoadedSLocEntryTableSegments{
  FileID(-1),   // represents FileIDs from -10 to -2
  FileID(-10),  // represents FileIDs from -50 to -11
  FileID(-50)}; // represents FileIDs from -90 to -51

llvm::upper_bound(llvm::reverse(LoadedSLocEntryTableSegments), FID);
```

The stored `FileIDs` have pretty weird values, though...

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread Petr Hosek via cfe-commits


@@ -639,8 +639,16 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder ,
   // want the stub/proxy to be emitted for properly calculating the offset.
   // Examples where there would be no symbol emitted are available_externally
   // and private linkages.
-  auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
-   : 
llvm::GlobalValue::ExternalLinkage;
+  //
+  // `internal` linkage results in LOCAL Elf linkage while still manifesting a
+  // local symbol.
+  //
+  // `linkonce_odr` linkage results in a DEFAULT Elf linkage but also allows 
for

petrhosek wrote:

The same here, use ELF and `STB_GLOBAL` binding (there's no default binding).

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread Petr Hosek via cfe-commits


@@ -639,8 +639,16 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder ,
   // want the stub/proxy to be emitted for properly calculating the offset.
   // Examples where there would be no symbol emitted are available_externally
   // and private linkages.
-  auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
-   : 
llvm::GlobalValue::ExternalLinkage;
+  //
+  // `internal` linkage results in LOCAL Elf linkage while still manifesting a

petrhosek wrote:

This is just a nit, but ELF is usually spelled in all caps since it's an 
acronym. I'd also use `STB_LOCAL` rather than `LOCAL` to be more explicit and 
use "binding" rather than "linkage".

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


[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Shafik Yaghmour via cfe-commits


@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{

shafik wrote:

I apologize for asking you to do additional work here but can you add the rest 
of the examples from [over.match.best.general 
p2.13](http://eel.is/c++draft/over.match.best.general#2.13).

It looks like we get all the test correct: https://godbolt.org/z/5MPrErPrq

and it would be nice to have those tests to prevent any possible future 
regressions.

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


[clang] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-10-03 Thread Hubert Tong via cfe-commits


@@ -660,14 +671,16 @@ void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
  "GETtls[ld]ADDR[32] must read GPR3");
 
   if (Subtarget->isAIXABI()) {
-// On AIX, the variable offset should already be in R4 and the region 
handle
-// should already be in R3.
-// For TLSGD, which currently is the only supported access model, we only
-// need to generate an absolute branch to .__tls_get_addr.
+// For TLSGD, the variable offset should already be in R4 and the region
+// handle should already be in R3. We generate an absolute branch to
+// .__tls_get_addr. For TLSLD, the module handle should already be in R3.
+// We generate an absolute branch to .__tls_get_mod.
 Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
 (void)VarOffsetReg;
-assert(MI->getOperand(2).isReg() &&
-   MI->getOperand(2).getReg() == VarOffsetReg &&
+assert((MI->getOpcode() == PPC::GETtlsMOD32AIX ||
+MI->getOpcode() == PPC::GETtlsMOD64AIX ||
+(MI->getOperand(2).isReg() &&
+ MI->getOperand(2).getReg() == VarOffsetReg)) &&
"GETtls[ld]ADDR[32] must read GPR4");
 EmitAIXTlsCallHelper(MI);

hubert-reinterpretcast wrote:

The helper functions have special calling convention properties. For example, 
they do not use the FP registers. The IBM XL compiler was able to take 
advantage of that.

For:
```c
__attribute__((tls_model("local-dynamic"))) __thread int x;
double g(int, double);
void f() {
  double gg = g(0, 1.);
  g(x, gg);
}
```

The IBM XL compilers were able to make use of the returned `double` staying in 
the register:
```
  28: 48 00 00 03   bla 0
0028:  R_RBA(idx: 36) .__tls_get_mod[PR]
  2c: 7c 66 18 2e   lwzx 3, 6, 3
  30: 4b ff ff d1   bl 0x0 <.f>
0030:  R_RBR(idx: 34) .g[PR]
```

Clang/LLVM loads the value from the stack:
```
  24: 48 00 00 03   bla 0
0024:  R_RBA(idx: 3) .__tls_get_mod[PR]
  28: e8 82 00 08   ld 4, 8(2)
002a:  R_TOC(idx: 17) x[TC]
  2c: 7c 63 22 aa   lwax 3, 3, 4
  30: 4b ff ff d1   bl 0x0 <.f>
0030:  R_RBR(idx: 1) .g[PR]
```

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread Petr Hosek via cfe-commits

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


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


[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-10-03 Thread Med Ismail Bennani via Phabricator via cfe-commits
mib added a comment.

Hey @iana, I think this broke the lldb bot 
https://green.lab.llvm.org/green/view/LLDB/job/as-lldb-cmake/6698/

Can you take a look ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159064

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 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 40c1f5b2fb88b17c6ed6911466002824d1880871 
0e798f3fdd7dc8816a71e3e147ca14616ad4a123 -- clang/lib/CodeGen/CGVTables.cpp 
clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp 
clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp 
clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp 
clang/test/CodeGenCXX/RelativeVTablesABI/simple-vtable-definition.cpp 
clang/test/CodeGenCXX/RelativeVTablesABI/type-info.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 1eec9ab29133..b093edbd84af 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -200,9 +200,8 @@ CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
 
   // Find the first store of "this", which will be to the alloca associated
   // with "this".
-  Address ThisPtr =
-  Address(&*AI, ConvertTypeForMem(MD->getThisObjectType()),
-  CGM.getClassPointerAlignment(MD->getParent()));
+  Address ThisPtr = Address(&*AI, ConvertTypeForMem(MD->getThisObjectType()),
+CGM.getClassPointerAlignment(MD->getParent()));
   llvm::BasicBlock *EntryBB = >front();
   llvm::BasicBlock::iterator ThisStore =
   llvm::find_if(*EntryBB, [&](llvm::Instruction ) {
@@ -1324,30 +1323,30 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 AP.second.AddressPointIndex));
 
   // Sort the address points for determinism.
-  llvm::sort(AddressPoints, [this](const AddressPoint ,
-   const AddressPoint ) {
-if ( == )
-  return false;
-
-std::string S1;
-llvm::raw_string_ostream O1(S1);
-getCXXABI().getMangleContext().mangleTypeName(
-QualType(AP1.first->getTypeForDecl(), 0), O1);
-O1.flush();
-
-std::string S2;
-llvm::raw_string_ostream O2(S2);
-getCXXABI().getMangleContext().mangleTypeName(
-QualType(AP2.first->getTypeForDecl(), 0), O2);
-O2.flush();
-
-if (S1 < S2)
-  return true;
-if (S1 != S2)
-  return false;
-
-return AP1.second < AP2.second;
-  });
+  llvm::sort(AddressPoints,
+ [this](const AddressPoint , const AddressPoint ) {
+   if ( == )
+ return false;
+
+   std::string S1;
+   llvm::raw_string_ostream O1(S1);
+   getCXXABI().getMangleContext().mangleTypeName(
+   QualType(AP1.first->getTypeForDecl(), 0), O1);
+   O1.flush();
+
+   std::string S2;
+   llvm::raw_string_ostream O2(S2);
+   getCXXABI().getMangleContext().mangleTypeName(
+   QualType(AP2.first->getTypeForDecl(), 0), O2);
+   O2.flush();
+
+   if (S1 < S2)
+ return true;
+   if (S1 != S2)
+ return false;
+
+   return AP1.second < AP2.second;
+ });
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {

``




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


[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Shafik Yaghmour via cfe-commits

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

Thank you for the follow-up work.

LGTM

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


[clang] [Inliner] Add argument/function attribute propagation before inlining. (PR #68164)

2023-10-03 Thread via cfe-commits

goldsteinn wrote:

Note on compile time affect: 
https://llvm-compile-time-tracker.com/compare.php?from=2da4960f20f7e5d88a68ce25636a895284dc66d8=f8c9f5bce65756598da22e8aec5d91fb66b16d5c=instructions%3Au

Minimal for normal O3, a bit more significant for LTO.

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


[clang] [Inliner] Add argument/function attribute propagation before inlining. (PR #68164)

2023-10-03 Thread via cfe-commits

https://github.com/goldsteinn updated 
https://github.com/llvm/llvm-project/pull/68164

>From 73290d5992e6a395fc953a9223173e9fd60a8775 Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 7 Sep 2023 18:48:26 -0500
Subject: [PATCH 1/2] [Inliner] Propagate callee function memory access
 attributes before inlining

To avoid losing information, we can propagate some access attribute
from the to-be-inlined callee to its callsites.

This patch is conservative and only does so for callsites that have no
preceding alloca as memory access attribute don't apply to allocas.

Assuming no preceeding allocas, we can directly add memory access
attributes for `other` and `inaccessible` memory to callsites. We can
cannot, however, blindly add `argmem` attributes as the callsite may
have different arguments (a follow up patch to add them if the
underlying object of all the callsites arguments are also arguments to
the callee could be added).
---
 llvm/include/llvm/Support/ModRef.h|  7 ++
 llvm/lib/Transforms/Utils/InlineFunction.cpp  | 74 +++
 .../Inline/access-attributes-prop.ll  | 12 +--
 llvm/test/Transforms/Inline/byval.ll  |  2 +-
 4 files changed, 88 insertions(+), 7 deletions(-)

diff --git a/llvm/include/llvm/Support/ModRef.h 
b/llvm/include/llvm/Support/ModRef.h
index 7687280111a1f86..dd8e8f36cca203d 100644
--- a/llvm/include/llvm/Support/ModRef.h
+++ b/llvm/include/llvm/Support/ModRef.h
@@ -180,6 +180,13 @@ template  class MemoryEffectsBase {
 return ME;
   }
 
+  /// Get new MemoryEffectsBase with ModRef on the given Loc.
+  MemoryEffectsBase getWithLocUnknown(Location Loc) const {
+MemoryEffectsBase ME = *this;
+ME.setModRef(Loc, ModRefInfo::ModRef);
+return ME;
+  }
+
   /// Get ModRefInfo for any location.
   ModRefInfo getModRef() const {
 ModRefInfo MR = ModRefInfo::NoModRef;
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp 
b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 6d5312c5a081ce9..02dd779f81c8fe9 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -61,6 +61,7 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/ModRef.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/Local.h"
@@ -1374,6 +1375,77 @@ static AttrBuilder 
IdentifyValidPoisonGeneratingAttributes(CallBase ) {
   return Valid;
 }
 
+// Recursively check BB for a preceding alloca. An alive alloca at the callsite
+// essentially makes propagating any memory effects impossible. While scanning
+// for the alloca also collect and callsites we may be able to modify.
+static const std::pair> &
+GetBBAllocaAndCallsiteInfo(
+BasicBlock *BB,
+DenseMap>>
+*FirstAllocaAndCBs,
+MemoryEffects ME) {
+  auto InsertRes = FirstAllocaAndCBs->insert({BB, {false, {}}});
+  if (!InsertRes.second)
+return InsertRes.first->second;
+
+  for (BasicBlock *PBB : predecessors(BB)) {
+auto PBBInfo = GetBBAllocaAndCallsiteInfo(PBB, FirstAllocaAndCBs, ME);
+if (PBBInfo.first) {
+  auto BBInfo = FirstAllocaAndCBs->find(BB);
+  assert(BBInfo != FirstAllocaAndCBs->end());
+  BBInfo->second.first = true;
+  // We have an alloca in a preceding BB, we can't propagate any memory
+  // effects.
+  return BBInfo->second;
+}
+  }
+
+  auto BBInfo = FirstAllocaAndCBs->find(BB);
+  assert(BBInfo != FirstAllocaAndCBs->end());
+  for (auto  : *BB) {
+if (isa()) {
+  BBInfo->second.first = true;
+  // Dominating alloca in the BB, we can propagate to any callsites prior 
to
+  // the alloca but none after.
+  return BBInfo->second;
+}
+// Add callsite.
+if (auto *OtherCB = dyn_cast())
+  BBInfo->second.second.push_back(OtherCB);
+  }
+  return BBInfo->second;
+}
+
+// Propagate memory effects from the to-be-inlined function to any callsites in
+// the function.
+static void AddFnAccessAttributes(CallBase , ValueToValueMapTy ) {
+  auto *CalledFunction = CB.getCalledFunction();
+  MemoryEffects ME = CB.getMemoryEffects();
+  if (ME == MemoryEffects::unknown())
+return;
+  DenseMap>>
+  FirstAllocaAndCBs;
+
+  for (BasicBlock  : *CalledFunction) {
+auto BBInfo = GetBBAllocaAndCallsiteInfo(, , ME);
+// We found no callsites that we can propagate memory effects to.
+if (BBInfo.second.empty())
+  continue;
+for (CallBase *OtherCB : BBInfo.second) {
+  assert(OtherCB->getParent() == );
+  if (auto *NewOtherCB = dyn_cast_or_null(VMap.lookup(OtherCB))) 
{
+MemoryEffects NewME = NewOtherCB->getMemoryEffects();
+// ArgMem memory effects don't directly apply.
+NewME &= ME.getWithLocUnknown(IRMemLocation::ArgMem);
+// If we have complete coverage of some ModRef then we can apply to
+// ArgMem as well.
+NewME 

[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Yinying Li via cfe-commits

https://github.com/yinying-lisa-li updated 
https://github.com/llvm/llvm-project/pull/68130

>From 47b34bb327e1078678d3ba0c96ebce3fc89cf2ae Mon Sep 17 00:00:00 2001
From: Yinying Li 
Date: Tue, 3 Oct 2023 16:43:50 +
Subject: [PATCH 1/4] [mlir][sparse] Print new syntax

Printing changes from #sparse_tensor.encoding<{ lvlTypes = [ "compressed" ] }> 
to map = (d0) -> (d0 : compressed). Level properties, ELL and slice are also 
supported.
---
 .../mlir/Dialect/SparseTensor/IR/Enums.h  |  20 +--
 .../SparseTensor/IR/SparseTensorDialect.cpp   |  64 ---
 mlir/test/Dialect/SparseTensor/codegen.mlir   |   8 +-
 .../SparseTensor/roundtrip_encoding.mlir  |  32 ++--
 .../Dialect/SparseTensor/sparse_reshape.mlir  |   8 +-
 .../SparseTensor/sparse_tensor_reshape.mlir   |   2 +-
 .../python/dialects/sparse_tensor/dialect.py  | 160 +-
 7 files changed, 159 insertions(+), 135 deletions(-)

diff --git a/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h 
b/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
index bc351ec52c0946b..2920ef79f461c6a 100644
--- a/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
+++ b/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
@@ -215,29 +215,29 @@ constexpr const char *toMLIRString(DimLevelType dlt) {
   case DimLevelType::Compressed:
 return "compressed";
   case DimLevelType::CompressedNu:
-return "compressed_nu";
+return "compressed(nonunique)";
   case DimLevelType::CompressedNo:
-return "compressed_no";
+return "compressed(nonordered)";
   case DimLevelType::CompressedNuNo:
-return "compressed_nu_no";
+return "compressed(nonunique, nonordered)";
   case DimLevelType::Singleton:
 return "singleton";
   case DimLevelType::SingletonNu:
-return "singleton_nu";
+return "singleton(nonunique)";
   case DimLevelType::SingletonNo:
-return "singleton_no";
+return "singleton(nonordered)";
   case DimLevelType::SingletonNuNo:
-return "singleton_nu_no";
+return "singleton(nonunique, nonordered)";
   case DimLevelType::LooseCompressed:
 return "loose_compressed";
   case DimLevelType::LooseCompressedNu:
-return "loose_compressed_nu";
+return "loose_compressed(nonunique)";
   case DimLevelType::LooseCompressedNo:
-return "loose_compressed_no";
+return "loose_compressed(nonordered)";
   case DimLevelType::LooseCompressedNuNo:
-return "loose_compressed_nu_no";
+return "loose_compressed(nonunique, nonordered)";
   case DimLevelType::TwoOutOfFour:
-return "compressed24";
+return "block2_4";
   }
   return "";
 }
diff --git a/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp 
b/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
index 3897e1b9ea3597c..4c8dccdda6c0c7c 100644
--- a/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
+++ b/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
@@ -586,30 +586,56 @@ Attribute SparseTensorEncodingAttr::parse(AsmParser 
, Type type) {
 }
 
 void SparseTensorEncodingAttr::print(AsmPrinter ) const {
-  // Print the struct-like storage in dictionary fashion.
-  printer << "<{ lvlTypes = [ ";
-  llvm::interleaveComma(getLvlTypes(), printer, [&](DimLevelType dlt) {
-printer << "\"" << toMLIRString(dlt) << "\"";
-  });
-  printer << " ]";
+  auto map = static_cast(getDimToLvl());
+  auto lvlTypes = getLvlTypes();
+  // Empty affine map indicates identity map
+  if (!map) {
+map = AffineMap::getMultiDimIdentityMap(getLvlTypes().size(), 
getContext());
+  }
+  // Modified version of AsmPrinter::Impl::printAffineMap.
+  printer << "<{ map = ";
+  // Symbolic identifiers.
+  if (map.getNumSymbols() != 0) {
+printer << '[';
+for (unsigned i = 0; i < map.getNumSymbols() - 1; ++i)
+  printer << 's' << i << ", ";
+if (map.getNumSymbols() >= 1)
+  printer << 's' << map.getNumSymbols() - 1;
+printer << ']';
+  }
+  // Dimension identifiers.
+  printer << '(';
+  auto dimSlices = getDimSlices();
+  if (!dimSlices.empty()) {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << " : " << dimSlices[i] << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1 << " : "
+  << dimSlices[map.getNumDims() - 1];
+  } else {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1;
+  }
+  printer << ')';
+  // Level format and properties.
+  printer << " -> (";
+  for (unsigned i = 0; i < map.getNumResults() - 1; ++i) {
+map.getResult(i).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[i]) << ", ";
+  }
+  if (map.getNumResults() >= 1) {
+auto lastIndex = map.getNumResults() - 1;
+map.getResult(lastIndex).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[lastIndex]);
+  }
+  printer << ')';
   // Print remaining members only for non-default values.
-  if 

[clang] Fix the Modules/compiler_builtins.m test (PR #68163)

2023-10-03 Thread Ian Anderson via cfe-commits

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


[clang] b855ae9 - Fix the Modules/compiler_builtins.m test (#68163)

2023-10-03 Thread via cfe-commits

Author: Ian Anderson
Date: 2023-10-03T15:58:38-07:00
New Revision: b855ae99036085267b4f7482f996c7d83d0d2983

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

LOG: Fix the Modules/compiler_builtins.m test (#68163)

Sometimes unwind.h needs uint32_t also.

Added: 


Modified: 
clang/test/Modules/Inputs/System/usr/include/stdint.h

Removed: 




diff  --git a/clang/test/Modules/Inputs/System/usr/include/stdint.h 
b/clang/test/Modules/Inputs/System/usr/include/stdint.h
index e3592fe359a4a32..209d54cd411ad55 100644
--- a/clang/test/Modules/Inputs/System/usr/include/stdint.h
+++ b/clang/test/Modules/Inputs/System/usr/include/stdint.h
@@ -30,6 +30,7 @@ typedef unsigned int uintmax_t;
 
 // additional types for unwind.h
 
+typedef unsigned int uint32_t;
 typedef unsigned long long uint64_t;
 
 #endif /* STDINT_H */



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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread via cfe-commits

PiJoules wrote:

> The change to `clang/test/CodeGenCXX/fixed-point-mangle.cpp` is unrelated.

Woops. Yeah, removed.

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


[clang] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR instead of External linkage (PR #67755)

2023-10-03 Thread via cfe-commits

https://github.com/PiJoules updated 
https://github.com/llvm/llvm-project/pull/67755

>From 0e798f3fdd7dc8816a71e3e147ca14616ad4a123 Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Fri, 29 Sep 2023 00:25:44 +
Subject: [PATCH] [clang][RelativeVTables] Make the rtti_proxy LinkOnceODR
 instead of External linkage

This way, it the rtti_proxies can be candidates for being replaced
altogether with GOTPCREL relocations because they are discardable.
Functionally, this shouldn't change the final ELF linkage of the
proxies.
---
 clang/lib/CodeGen/CGVTables.cpp  | 12 ++--
 .../RelativeVTablesABI/child-vtable-in-comdat.cpp|  3 +--
 .../RelativeVTablesABI/parent-vtable-in-comdat.cpp   |  2 +-
 .../RelativeVTablesABI/relative-vtables-hwasan.cpp   |  4 ++--
 .../RelativeVTablesABI/simple-vtable-definition.cpp  |  2 +-
 .../test/CodeGenCXX/RelativeVTablesABI/type-info.cpp |  4 ++--
 6 files changed, 17 insertions(+), 10 deletions(-)

diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 23cfcdd138439f0..1eec9ab29133f5c 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -639,8 +639,16 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder ,
   // want the stub/proxy to be emitted for properly calculating the offset.
   // Examples where there would be no symbol emitted are available_externally
   // and private linkages.
-  auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
-   : 
llvm::GlobalValue::ExternalLinkage;
+  //
+  // `internal` linkage results in LOCAL Elf linkage while still manifesting a
+  // local symbol.
+  //
+  // `linkonce_odr` linkage results in a DEFAULT Elf linkage but also allows 
for
+  // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
+  // target that supports this replacement.
+  auto stubLinkage = vtableHasLocalLinkage
+ ? llvm::GlobalValue::InternalLinkage
+ : llvm::GlobalValue::LinkOnceODRLinkage;
 
   llvm::Constant *target;
   if (auto *func = dyn_cast(globalVal)) {
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
index 48b1d8ed65d7e55..950921f67509f42 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/child-vtable-in-comdat.cpp
@@ -8,7 +8,6 @@
 // CHECK-DAG: $_ZTS1B = comdat any
 // CHECK-DAG: $_ZTI1B = comdat any
 // CHECK-DAG: $_ZTI1B.rtti_proxy = comdat any
-// CHECK-DAG: $_ZTI1A.rtti_proxy = comdat any
 
 // VTable for B is emitted here since we access it when creating an instance 
of B. The VTable is also linkonce_odr and in its own comdat.
 // CHECK-DAG: @_ZTV1B.local = linkonce_odr hidden unnamed_addr constant { [3 x 
i32] } { [3 x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr 
@_ZTI1B.rtti_proxy to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x 
i32] }, ptr @_ZTV1B.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc 
(i64 sub (i64 ptrtoint (ptr dso_local_equivalent @_ZN1B3fooEv to i64), i64 
ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B.local, i32 0, 
i32 0, i32 2) to i64)) to i32)] }, comdat($_ZTV1B), align 4
@@ -18,7 +17,7 @@
 // CHECK-DAG: @_ZTS1B =
 // CHECK-DAG: @_ZTI1A =
 // CHECK-DAG: @_ZTI1B =
-// CHECK-DAG: @_ZTI1B.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1B, 
comdat
+// CHECK-DAG: @_ZTI1B.rtti_proxy = linkonce_odr hidden unnamed_addr constant 
ptr @_ZTI1B, comdat
 
 // We will emit a vtable for B here, so it does have an alias, but we will not
 // emit one for A.
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
index 5f5f9edf411a809..ee710100152bfac 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/parent-vtable-in-comdat.cpp
@@ -18,7 +18,7 @@
 // CHECK: @_ZTVN10__cxxabiv117__class_type_infoE = external global [0 x ptr]
 // CHECK: @_ZTS1A = linkonce_odr constant [3 x i8] c"1A\00", comdat, align 1
 // CHECK: @_ZTI1A = linkonce_odr constant { ptr, ptr } { ptr getelementptr 
inbounds (i8, ptr @_ZTVN10__cxxabiv117__class_type_infoE, i32 8), ptr @_ZTS1A 
}, comdat, align 8
-// CHECK: @_ZTI1A.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1A, comdat
+// CHECK: @_ZTI1A.rtti_proxy = linkonce_odr hidden unnamed_addr constant ptr 
@_ZTI1A, comdat
 // CHECK: @_ZTV1A = linkonce_odr unnamed_addr alias { [3 x i32] }, ptr 
@_ZTV1A.local
 
 // CHECK:  define linkonce_odr void @_ZN1A3fooEv(ptr {{.*}}%this) 
unnamed_addr #{{[0-9]+}} comdat
diff --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
index 

[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Yinying Li via cfe-commits


@@ -533,7 +533,7 @@ func.func @sparse_compression(%tensor: tensor<8x8xf64, 
#CSR>,
 //   CHECK: %[[A13:.*]]:4 = scf.for %[[A14:.*]] = %[[A11]] to %[[A7]] 
step %[[A12]] iter_args(%[[A15:.*]] = %[[A0]], %[[A16:.*]] = %[[A1]], 
%[[A17:.*]] = %[[A2]], %[[A18:.*]] = %[[A3]]) -> (memref, 
memref, memref, !sparse_tensor.storage_specifier
 //   CHECK:   %[[A19:.*]] = memref.load %[[A6]]{{\[}}%[[A14]]] : 
memref
 //   CHECK:   %[[A20:.*]] = memref.load %[[A4]]{{\[}}%[[A19]]] : 
memref
-//   CHECK:   %[[A21:.*]]:4 = func.call 
@_insert_dense_compressed_no_8_8_f64_0_0(%[[A15]], %[[A16]], %[[A17]], 
%[[A18]], %[[A8]], %[[A19]], %[[A20]]) : (memref, memref, 
memref, !sparse_tensor.storage_specifier
+//   CHECK:   %[[A21:.*]]:4 = func.call 
@"_insert_dense_compressed(nonordered)_8_8_f64_0_0"(%[[A15]], %[[A16]], 
%[[A17]], %[[A18]], %[[A8]], %[[A19]], %[[A20]]) : (memref, 
memref, memref, !sparse_tensor.storage_specifier

yinying-lisa-li wrote:

Done!

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


[clang] [mlir][sparse] Print new syntax (PR #68130)

2023-10-03 Thread Yinying Li via cfe-commits

https://github.com/yinying-lisa-li updated 
https://github.com/llvm/llvm-project/pull/68130

>From 47b34bb327e1078678d3ba0c96ebce3fc89cf2ae Mon Sep 17 00:00:00 2001
From: Yinying Li 
Date: Tue, 3 Oct 2023 16:43:50 +
Subject: [PATCH 1/3] [mlir][sparse] Print new syntax

Printing changes from #sparse_tensor.encoding<{ lvlTypes = [ "compressed" ] }> 
to map = (d0) -> (d0 : compressed). Level properties, ELL and slice are also 
supported.
---
 .../mlir/Dialect/SparseTensor/IR/Enums.h  |  20 +--
 .../SparseTensor/IR/SparseTensorDialect.cpp   |  64 ---
 mlir/test/Dialect/SparseTensor/codegen.mlir   |   8 +-
 .../SparseTensor/roundtrip_encoding.mlir  |  32 ++--
 .../Dialect/SparseTensor/sparse_reshape.mlir  |   8 +-
 .../SparseTensor/sparse_tensor_reshape.mlir   |   2 +-
 .../python/dialects/sparse_tensor/dialect.py  | 160 +-
 7 files changed, 159 insertions(+), 135 deletions(-)

diff --git a/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h 
b/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
index bc351ec52c0946b..2920ef79f461c6a 100644
--- a/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
+++ b/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h
@@ -215,29 +215,29 @@ constexpr const char *toMLIRString(DimLevelType dlt) {
   case DimLevelType::Compressed:
 return "compressed";
   case DimLevelType::CompressedNu:
-return "compressed_nu";
+return "compressed(nonunique)";
   case DimLevelType::CompressedNo:
-return "compressed_no";
+return "compressed(nonordered)";
   case DimLevelType::CompressedNuNo:
-return "compressed_nu_no";
+return "compressed(nonunique, nonordered)";
   case DimLevelType::Singleton:
 return "singleton";
   case DimLevelType::SingletonNu:
-return "singleton_nu";
+return "singleton(nonunique)";
   case DimLevelType::SingletonNo:
-return "singleton_no";
+return "singleton(nonordered)";
   case DimLevelType::SingletonNuNo:
-return "singleton_nu_no";
+return "singleton(nonunique, nonordered)";
   case DimLevelType::LooseCompressed:
 return "loose_compressed";
   case DimLevelType::LooseCompressedNu:
-return "loose_compressed_nu";
+return "loose_compressed(nonunique)";
   case DimLevelType::LooseCompressedNo:
-return "loose_compressed_no";
+return "loose_compressed(nonordered)";
   case DimLevelType::LooseCompressedNuNo:
-return "loose_compressed_nu_no";
+return "loose_compressed(nonunique, nonordered)";
   case DimLevelType::TwoOutOfFour:
-return "compressed24";
+return "block2_4";
   }
   return "";
 }
diff --git a/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp 
b/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
index 3897e1b9ea3597c..4c8dccdda6c0c7c 100644
--- a/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
+++ b/mlir/lib/Dialect/SparseTensor/IR/SparseTensorDialect.cpp
@@ -586,30 +586,56 @@ Attribute SparseTensorEncodingAttr::parse(AsmParser 
, Type type) {
 }
 
 void SparseTensorEncodingAttr::print(AsmPrinter ) const {
-  // Print the struct-like storage in dictionary fashion.
-  printer << "<{ lvlTypes = [ ";
-  llvm::interleaveComma(getLvlTypes(), printer, [&](DimLevelType dlt) {
-printer << "\"" << toMLIRString(dlt) << "\"";
-  });
-  printer << " ]";
+  auto map = static_cast(getDimToLvl());
+  auto lvlTypes = getLvlTypes();
+  // Empty affine map indicates identity map
+  if (!map) {
+map = AffineMap::getMultiDimIdentityMap(getLvlTypes().size(), 
getContext());
+  }
+  // Modified version of AsmPrinter::Impl::printAffineMap.
+  printer << "<{ map = ";
+  // Symbolic identifiers.
+  if (map.getNumSymbols() != 0) {
+printer << '[';
+for (unsigned i = 0; i < map.getNumSymbols() - 1; ++i)
+  printer << 's' << i << ", ";
+if (map.getNumSymbols() >= 1)
+  printer << 's' << map.getNumSymbols() - 1;
+printer << ']';
+  }
+  // Dimension identifiers.
+  printer << '(';
+  auto dimSlices = getDimSlices();
+  if (!dimSlices.empty()) {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << " : " << dimSlices[i] << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1 << " : "
+  << dimSlices[map.getNumDims() - 1];
+  } else {
+for (unsigned i = 0; i < map.getNumDims() - 1; ++i)
+  printer << 'd' << i << ", ";
+if (map.getNumDims() >= 1)
+  printer << 'd' << map.getNumDims() - 1;
+  }
+  printer << ')';
+  // Level format and properties.
+  printer << " -> (";
+  for (unsigned i = 0; i < map.getNumResults() - 1; ++i) {
+map.getResult(i).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[i]) << ", ";
+  }
+  if (map.getNumResults() >= 1) {
+auto lastIndex = map.getNumResults() - 1;
+map.getResult(lastIndex).print(printer.getStream());
+printer << " : " << toMLIRString(lvlTypes[lastIndex]);
+  }
+  printer << ')';
   // Print remaining members only for non-default values.
-  if 

[clang-tools-extra] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-03 Thread via cfe-commits

shraiysh wrote:

Ping for review!

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


[clang] [clang] Ignore GCC 11 `[[malloc(x)]]` attribute (PR #68059)

2023-10-03 Thread Alois Klink via cfe-commits


@@ -4122,6 +4122,9 @@ def RestrictDocs : Documentation {
 The ``malloc`` attribute indicates that the function acts like a system memory
 allocation function, returning a pointer to allocated storage disjoint from the
 storage for any other object accessible to the caller.
+
+The form of ``malloc`` with one or two arguments (supported by GCC 11) is
+currently ignored by Clang.

aloisklink wrote:

In this PR, it's completely ignored, it's not even added to the Clang AST.

It just reaches the end of this function where nothing happens (let me know if 
I can improve the comment!):

https://github.com/llvm/llvm-project/blob/f9c914729a5f5ac7f8b61ea2d39509ff0236a228/clang/lib/Sema/SemaDeclAttr.cpp#L2084-L2087

We can't treat it as if has no arguments because in GCC it means two different 
things:
  - `__attribute__((malloc))` with no args means the return value is guaranteed 
not to alias to any other pointer (aka like [`__declspec(restrict)` in 
MSVC](https://learn.microsoft.com/en-us/cpp/cpp/restrict?view=msvc-170)) and 
that the function will normally return non-`NULL`, allowing optimizations,
  - `__attribute__((malloc(deallocator)))` instead says the returned pointer 
should be deallocated by the specified deallocator, allowing a static analyzer 
to print warnings.

See the `malloc` section of 
https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html for more 
info.

To be honest, I feel like GCC should have given the one/two argument form a 
different attribute name to make things less confusing, but GCC 11 has already 
been out for years unfortunately.

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


[clang] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-03 Thread via cfe-commits

shraiysh wrote:

Ping for review!

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


[clang] [Inliner] Add argument/function attribute propagation before inlining. (PR #68164)

2023-10-03 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 1cfaa863bc36d25625114b432e2ddf35d2302452 
f8c9f5bce65756598da22e8aec5d91fb66b16d5c -- 
clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c 
clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c 
llvm/include/llvm/Support/ModRef.h llvm/lib/Transforms/Utils/InlineFunction.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp 
b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 02b80bfc8e17..091bbe02c520 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -30,8 +30,8 @@
 #include "llvm/Analysis/ProfileSummaryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Analysis/VectorUtils.h"
-#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Argument.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/CFG.h"
@@ -1418,8 +1418,7 @@ static void AddParamAndFnBasicAttributes(const CallBase 
,
 if (const Argument *Arg = dyn_cast(UnderlyingV)) {
   unsigned ArgNo = Arg->getArgNo();
   // If so, propagate its access attributes.
-  AL = AL.addParamAttributes(Context, I,
- ValidParamAttrs[ArgNo]);
+  AL = AL.addParamAttributes(Context, I, ValidParamAttrs[ArgNo]);
 }
   }
   NewInnerCB->setAttributes(AL);

``




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


[libunwind] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread via cfe-commits

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


[libclc] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread via cfe-commits

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

2023-10-03 Thread via cfe-commits

https://github.com/michaelrj-google updated 
https://github.com/llvm/llvm-project/pull/68134

>From baf9d8e19d2b064c05527757c6173f875b59b286 Mon Sep 17 00:00:00 2001
From: Michael Jones 
Date: Tue, 3 Oct 2023 10:39:02 -0700
Subject: [PATCH 1/2] [clang-tidy][libc] Fix namespace check with macro

The name of the namespace for LLVM's libc is now provided by a macro.
The ImplementationNamespaceCheck was updated to handle this, but the
CalleeNamespaceCheck was missed. This patch updates the
CalleeNamespaceCheck to handle the macro.
---
 .../clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp   | 10 ++
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp 
b/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp
index 98ae857b589fd64..7ad4b5fb7f043ab 100644
--- a/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp
@@ -45,9 +45,10 @@ void CalleeNamespaceCheck::check(const 
MatchFinder::MatchResult ) {
   if (FuncDecl->getBuiltinID() != 0)
 return;
 
-  // If the outermost namespace of the function is __llvm_libc, we're good.
+  // If the outermost namespace of the function starts with __llvm_libc, we're
+  // good.
   const auto *NS = dyn_cast(getOutermostNamespace(FuncDecl));
-  if (NS && NS->getName() == "__llvm_libc")
+  if (NS && NS->getName().starts_with("__llvm_libc"))
 return;
 
   const DeclarationName  = FuncDecl->getDeclName();
@@ -55,8 +56,9 @@ void CalleeNamespaceCheck::check(const 
MatchFinder::MatchResult ) {
   IgnoredFunctions.contains(Name.getAsIdentifierInfo()->getName()))
 return;
 
-  diag(UsageSiteExpr->getBeginLoc(), "%0 must resolve to a function declared "
- "within the '__llvm_libc' namespace")
+  diag(UsageSiteExpr->getBeginLoc(),
+   "%0 must resolve to a function declared "
+   "within the '__llvm_libc' namespace (use macro `LIBC_NAMESPACE`)")
   << FuncDecl;
 
   diag(FuncDecl->getLocation(), "resolves to this declaration",

>From b3c710beda5b45dc18a5cbd74e141c1169971450 Mon Sep 17 00:00:00 2001
From: Michael Jones 
Date: Tue, 3 Oct 2023 15:35:32 -0700
Subject: [PATCH 2/2] update release notes

---
 clang-tools-extra/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 8fc28c090341802..36cc58f4ab91b21 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -321,6 +321,11 @@ Changes in existing checks
   ` check to
   identify calls to static member functions with out-of-class inline 
definitions.
 
+- Improved :doc:`llvmlibc-callee-namespace
+  ` to support
+  customizable namespace. This matches the change made to implementation in
+  namespace.
+
 Removed checks
 ^^
 

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


[clang] Fix the Modules/compiler_builtins.m test (PR #68163)

2023-10-03 Thread Michael Spencer via cfe-commits

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


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


Re: [PATCH] D148381: [Clang] Implement the 'counted_by' attribute

2023-10-03 Thread Bill Wendling via cfe-commits
Yes, I mean to do it as a direct follow-up. 

-bw

On Tue, Oct 3, 2023, 6:31 AM Aaron Ballman via Phabricator <
revi...@reviews.llvm.org> wrote:

> aaron.ballman added inline comments.
>
>
> 
> Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8420-8428
> +if (Result.getResultKind() == LookupResult::Found) {
> +  SourceRange SR = CBA->getCountedByFieldLoc();
> +  Diag(SR.getBegin(),
> +
>  diag::err_flexible_array_counted_by_attr_field_not_found_in_struct)
> +  << CBA->getCountedByField() << SR;
> +
> +  SR = Result.getAsSingle()->getSourceRange();
> 
> void wrote:
> > aaron.ballman wrote:
> > > The logic here still seems incorrect. I was expecting the code to look
> more like this:
> > > ```
> > > bool Sema::CheckCountedByAttr(Scope *S, const FieldDecl *FD) {
> > >   const RecordDecl *RD = FD->getParent();
> > >   const auto *CBA = FD->getAttr();
> > >   const IdentifierInfo *FieldName = CBA->getCountedByField();
> > >   DeclarationNameInfo NameInfo(FieldName,
> > >CBA->getCountedByFieldLoc().getBegin());
> > >   LookupResult Result(*this, NameInfo, Sema::LookupMemberName);
> > >
> > >   LookupName(Result, S);
> > >   if (Result.empty()) {
> > > CXXScopeSpec SS;
> > > DeclFilterCCC Filter(const_cast *>(FieldName));
> > > if (DiagnoseEmptyLookup(S, SS, Result, Filter, nullptr,
> std::nullopt,
> > > const_cast *>(FD->getDeclContext(
> > >   return true;
> > >   }
> > >
> > >   const FieldDecl *Field = Result.getAsSingle();
> > >   LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
> > >   Context.getLangOpts().getStrictFlexArraysLevel();
> > >   ...
> > > ```
> > > I tested this locally on code like:
> > > ```
> > > struct not_a_fam {
> > >   int foo;
> > >   int fam[] __attribute__((counted_by(fob)));
> > > };
> > > ```
> > > and get a diagnostic like:
> > > ```
> > > C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:3:39:
> error: use of undeclared identifier 'fob'; did you
> > >   mean 'foo'?
> > > 3 |   int fam[] __attribute__((counted_by(fob)));
> > >   |   ^~~
> > >   |   foo
> > > C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:2:7:
> note: 'foo' declared here
> > > 2 |   int foo;
> > >   |   ^
> > > 1 error generated.
> > > ```
> > > Note, I had to add a constructor to `DeclFilterCCC` to expose the base
> class constructor, and modify `DiagnoseEmptyLookup()` like this:
> > > ```
> > > diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
> > > index 2ed31a90c5dc..3c4ade391a5e 100644
> > > --- a/clang/lib/Sema/SemaExpr.cpp
> > > +++ b/clang/lib/Sema/SemaExpr.cpp
> > > @@ -2458,7 +2458,8 @@ bool Sema::DiagnoseDependentMemberLookup(const
> LookupResult ) {
> > >  bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec ,
> LookupResult ,
> > > CorrectionCandidateCallback ,
> > > TemplateArgumentListInfo
> *ExplicitTemplateArgs,
> > > -   ArrayRef Args, TypoExpr **Out)
> {
> > > +   ArrayRef Args, DeclContext
> *LookupCtx,
> > > +   TypoExpr **Out) {
> > >DeclarationName Name = R.getLookupName();
> > >
> > >unsigned diagnostic = diag::err_undeclared_var_use;
> > > @@ -2474,7 +2475,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S,
> CXXScopeSpec , LookupResult ,
> > >// unqualified lookup.  This is useful when (for example) the
> > >// original lookup would not have found something because it was a
> > >// dependent name.
> > > -  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
> > > +  DeclContext *DC =
> > > +  LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
> > > +  DeclContext *OrigLookupCtx = DC;
> > >while (DC) {
> > >  if (isa(DC)) {
> > >LookupQualifiedName(R, DC);
> > > @@ -2517,12 +2520,12 @@ bool Sema::DiagnoseEmptyLookup(Scope *S,
> CXXScopeSpec , LookupResult ,
> > >emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc,
> Args,
> > >  diagnostic,
> diagnostic_suggest);
> > >  },
> > > -nullptr, CTK_ErrorRecovery);
> > > +nullptr, CTK_ErrorRecovery, OrigLookupCtx);
> > >  if (*Out)
> > >return true;
> > > -  } else if (S &&
> > > - (Corrected = CorrectTypo(R.getLookupNameInfo(),
> R.getLookupKind(),
> > > -  S, , CCC,
> CTK_ErrorRecovery))) {
> > > +  } else if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(),
> > > +   R.getLookupKind(), S, ,
> CCC,
> > > +   CTK_ErrorRecovery,
> OrigLookupCtx))) {
> > >  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
> > >  

[clang] [Inliner] Add argument/function attribute propagation before inlining. (PR #68164)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

- [Inliner] Propagate callee function memory access attributes before inlining
- [Inliner] Propagate callee argument memory access attributes before inlining


---

Patch is 24.83 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/68164.diff


8 Files Affected:

- (modified) clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c (+9-9) 
- (modified) clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c (+4-4) 
- (modified) llvm/include/llvm/Support/ModRef.h (+7) 
- (modified) llvm/lib/Transforms/Utils/InlineFunction.cpp (+129) 
- (modified) llvm/test/Transforms/Inline/access-attributes-prop.ll (+18-18) 
- (modified) llvm/test/Transforms/Inline/byval.ll (+1-1) 
- (modified) llvm/test/Transforms/Inline/noalias-calls-always.ll (+6-6) 
- (modified) llvm/test/Transforms/Inline/noalias-calls.ll (+6-6) 


``diff
diff --git a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c
index 44f8cbe2cc01739..642b08ac68ef122 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector.c
@@ -636,31 +636,31 @@ void test_core(void) {
   // CHECK-ASM: vlbb
 
   vsc = vec_load_len(cptrsc, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vuc = vec_load_len(cptruc, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vss = vec_load_len(cptrss, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vus = vec_load_len(cptrus, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vsi = vec_load_len(cptrsi, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vui = vec_load_len(cptrui, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vsl = vec_load_len(cptrsl, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vul = vec_load_len(cptrul, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vd = vec_load_len(cptrd, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
 
   vec_store_len(vsc, ptrsc, idx);
diff --git a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c
index 416ca0ddd1b4fe2..3f02565dfb488ce 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c
@@ -207,10 +207,10 @@ void test_core(void) {
   // CHECK-ASM: vlbb
 
   vf = vec_load_len(cptrf, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
   vd = vec_load_len(cptrd, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vll
 
   vec_store_len(vf, ptrf, idx);
@@ -221,10 +221,10 @@ void test_core(void) {
   // CHECK-ASM: vstl
 
   vuc = vec_load_len_r(cptruc, 0);
-  // CHECK: call <16 x i8> @llvm.s390.vlrl(i32 0, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vlrl(i32 0, ptr readonly %{{.*}})
   // CHECK-ASM: vlrl %{{.*}}, 0(%{{.*}}), 0
   vuc = vec_load_len_r(cptruc, idx);
-  // CHECK: call <16 x i8> @llvm.s390.vlrl(i32 %{{.*}}, ptr %{{.*}})
+  // CHECK: call <16 x i8> @llvm.s390.vlrl(i32 %{{.*}}, ptr readonly %{{.*}})
   // CHECK-ASM: vlrlr
 
   vec_store_len_r(vuc, ptruc, 0);
diff --git a/llvm/include/llvm/Support/ModRef.h 
b/llvm/include/llvm/Support/ModRef.h
index 7687280111a1f86..dd8e8f36cca203d 100644
--- a/llvm/include/llvm/Support/ModRef.h
+++ b/llvm/include/llvm/Support/ModRef.h
@@ -180,6 +180,13 @@ template  class MemoryEffectsBase {
 return ME;
   }
 
+  /// Get new MemoryEffectsBase with ModRef on the given Loc.
+  MemoryEffectsBase getWithLocUnknown(Location Loc) const {
+MemoryEffectsBase ME = *this;
+ME.setModRef(Loc, ModRefInfo::ModRef);
+return 

[clang] [Inliner] Add argument/function attribute propagation before inlining. (PR #68164)

2023-10-03 Thread via cfe-commits

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


[clang] goldsteinn/inliner attrs next next (PR #68164)

2023-10-03 Thread via cfe-commits

https://github.com/goldsteinn created 
https://github.com/llvm/llvm-project/pull/68164

- [Inliner] Propagate callee function memory access attributes before inlining
- [Inliner] Propagate callee argument memory access attributes before inlining


>From 73290d5992e6a395fc953a9223173e9fd60a8775 Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 7 Sep 2023 18:48:26 -0500
Subject: [PATCH 1/2] [Inliner] Propagate callee function memory access
 attributes before inlining

To avoid losing information, we can propagate some access attribute
from the to-be-inlined callee to its callsites.

This patch is conservative and only does so for callsites that have no
preceding alloca as memory access attribute don't apply to allocas.

Assuming no preceeding allocas, we can directly add memory access
attributes for `other` and `inaccessible` memory to callsites. We can
cannot, however, blindly add `argmem` attributes as the callsite may
have different arguments (a follow up patch to add them if the
underlying object of all the callsites arguments are also arguments to
the callee could be added).
---
 llvm/include/llvm/Support/ModRef.h|  7 ++
 llvm/lib/Transforms/Utils/InlineFunction.cpp  | 74 +++
 .../Inline/access-attributes-prop.ll  | 12 +--
 llvm/test/Transforms/Inline/byval.ll  |  2 +-
 4 files changed, 88 insertions(+), 7 deletions(-)

diff --git a/llvm/include/llvm/Support/ModRef.h 
b/llvm/include/llvm/Support/ModRef.h
index 7687280111a1f86..dd8e8f36cca203d 100644
--- a/llvm/include/llvm/Support/ModRef.h
+++ b/llvm/include/llvm/Support/ModRef.h
@@ -180,6 +180,13 @@ template  class MemoryEffectsBase {
 return ME;
   }
 
+  /// Get new MemoryEffectsBase with ModRef on the given Loc.
+  MemoryEffectsBase getWithLocUnknown(Location Loc) const {
+MemoryEffectsBase ME = *this;
+ME.setModRef(Loc, ModRefInfo::ModRef);
+return ME;
+  }
+
   /// Get ModRefInfo for any location.
   ModRefInfo getModRef() const {
 ModRefInfo MR = ModRefInfo::NoModRef;
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp 
b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 6d5312c5a081ce9..02dd779f81c8fe9 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -61,6 +61,7 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/ModRef.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/Local.h"
@@ -1374,6 +1375,77 @@ static AttrBuilder 
IdentifyValidPoisonGeneratingAttributes(CallBase ) {
   return Valid;
 }
 
+// Recursively check BB for a preceding alloca. An alive alloca at the callsite
+// essentially makes propagating any memory effects impossible. While scanning
+// for the alloca also collect and callsites we may be able to modify.
+static const std::pair> &
+GetBBAllocaAndCallsiteInfo(
+BasicBlock *BB,
+DenseMap>>
+*FirstAllocaAndCBs,
+MemoryEffects ME) {
+  auto InsertRes = FirstAllocaAndCBs->insert({BB, {false, {}}});
+  if (!InsertRes.second)
+return InsertRes.first->second;
+
+  for (BasicBlock *PBB : predecessors(BB)) {
+auto PBBInfo = GetBBAllocaAndCallsiteInfo(PBB, FirstAllocaAndCBs, ME);
+if (PBBInfo.first) {
+  auto BBInfo = FirstAllocaAndCBs->find(BB);
+  assert(BBInfo != FirstAllocaAndCBs->end());
+  BBInfo->second.first = true;
+  // We have an alloca in a preceding BB, we can't propagate any memory
+  // effects.
+  return BBInfo->second;
+}
+  }
+
+  auto BBInfo = FirstAllocaAndCBs->find(BB);
+  assert(BBInfo != FirstAllocaAndCBs->end());
+  for (auto  : *BB) {
+if (isa()) {
+  BBInfo->second.first = true;
+  // Dominating alloca in the BB, we can propagate to any callsites prior 
to
+  // the alloca but none after.
+  return BBInfo->second;
+}
+// Add callsite.
+if (auto *OtherCB = dyn_cast())
+  BBInfo->second.second.push_back(OtherCB);
+  }
+  return BBInfo->second;
+}
+
+// Propagate memory effects from the to-be-inlined function to any callsites in
+// the function.
+static void AddFnAccessAttributes(CallBase , ValueToValueMapTy ) {
+  auto *CalledFunction = CB.getCalledFunction();
+  MemoryEffects ME = CB.getMemoryEffects();
+  if (ME == MemoryEffects::unknown())
+return;
+  DenseMap>>
+  FirstAllocaAndCBs;
+
+  for (BasicBlock  : *CalledFunction) {
+auto BBInfo = GetBBAllocaAndCallsiteInfo(, , ME);
+// We found no callsites that we can propagate memory effects to.
+if (BBInfo.second.empty())
+  continue;
+for (CallBase *OtherCB : BBInfo.second) {
+  assert(OtherCB->getParent() == );
+  if (auto *NewOtherCB = dyn_cast_or_null(VMap.lookup(OtherCB))) 
{
+MemoryEffects NewME = NewOtherCB->getMemoryEffects();
+// ArgMem memory effects don't directly apply.
+NewME &= 

[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

2023-10-03 Thread Congcong Cai via cfe-commits

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

LGTM. Please update the release notes.

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


  1   2   3   4   5   >