[clang] [clang][DebugInfo] Attach DW_AT_const_value to static data-member definitions if available (PR #72730)

2023-11-17 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/72730

>From 6dcb09dcc50a9b9e92640412242927b3e226929e Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Sat, 18 Nov 2023 00:20:05 +
Subject: [PATCH 1/4] [clang][DebugInfo][NFC] Create
 evaluateConstantInitializer helper function

---
 clang/lib/CodeGen/CGDebugInfo.cpp | 18 ++
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0b52d99ad07f164..4840581b5d03f89 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -69,6 +69,19 @@ static uint32_t getDeclAlignIfRequired(const Decl *D, const 
ASTContext &Ctx) {
   return D->hasAttr() ? D->getMaxAlignment() : 0;
 }
 
+APValue const * evaluateConstantInitializer(clang::VarDecl const * VD) {
+  assert (VD != nullptr);
+
+  VD = VD->getCanonicalDecl();
+  if (!VD)
+return nullptr;
+
+  if (!VD->hasConstantInitialization() || !VD->hasInit())
+return nullptr;
+
+  return VD->evaluateValue();
+}
+
 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
   DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
@@ -5596,14 +5609,11 @@ void CGDebugInfo::EmitGlobalVariable(const VarDecl *VD) 
{
   if (VD->hasAttr())
 return;
 
-  if (!VD->hasInit())
-return;
-
   const auto CacheIt = DeclCache.find(VD);
   if (CacheIt != DeclCache.end())
 return;
 
-  auto const *InitVal = VD->evaluateValue();
+  auto const * InitVal = evaluateConstantInitializer(VD);
   if (!InitVal)
 return;
 

>From fcc6e19d108798fb18c1973e4d4cc3800da07f9f Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Sat, 18 Nov 2023 00:52:24 +
Subject: [PATCH 2/4] fixup! clang-format

---
 clang/lib/CodeGen/CGDebugInfo.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 4840581b5d03f89..9bba6e6b13e9318 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -69,8 +69,8 @@ static uint32_t getDeclAlignIfRequired(const Decl *D, const 
ASTContext &Ctx) {
   return D->hasAttr() ? D->getMaxAlignment() : 0;
 }
 
-APValue const * evaluateConstantInitializer(clang::VarDecl const * VD) {
-  assert (VD != nullptr);
+APValue const *evaluateConstantInitializer(clang::VarDecl const *VD) {
+  assert(VD != nullptr);
 
   VD = VD->getCanonicalDecl();
   if (!VD)
@@ -5613,7 +5613,7 @@ void CGDebugInfo::EmitGlobalVariable(const VarDecl *VD) {
   if (CacheIt != DeclCache.end())
 return;
 
-  auto const * InitVal = evaluateConstantInitializer(VD);
+  auto const *InitVal = evaluateConstantInitializer(VD);
   if (!InitVal)
 return;
 

>From 148ab1793a866111060f77807ff065040fad92d8 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Sat, 18 Nov 2023 00:22:06 +
Subject: [PATCH 3/4] [clang][DebugInfo] Attach DW_AT_const_value to static
 data-member definitions if available

---
 clang/lib/CodeGen/CGDebugInfo.cpp  | 10 --
 .../CodeGenCXX/debug-info-static-inline-member.cpp |  2 +-
 clang/test/CodeGenCXX/inline-dllexport-member.cpp  |  2 +-
 3 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 9bba6e6b13e9318..e01c57baef19931 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5516,11 +5516,17 @@ void 
CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
 }
 AppendAddressSpaceXDeref(AddressSpace, Expr);
 
+llvm::DIExpression *E = nullptr;
+if (Expr.empty()) {
+  if (auto const *InitVal = evaluateConstantInitializer(D))
+E = createConstantValueExpression(D, *InitVal);
+} else
+  E = DBuilder.createExpression(Expr);
+
 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
 GVE = DBuilder.createGlobalVariableExpression(
 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, 
Unit),
-Var->hasLocalLinkage(), true,
-Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
+Var->hasLocalLinkage(), true, E,
 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
 Align, Annotations);
 Var->addDebugInfo(GVE);
diff --git a/clang/test/CodeGenCXX/debug-info-static-inline-member.cpp 
b/clang/test/CodeGenCXX/debug-info-static-inline-member.cpp
index f2d4d9408a8297a..950ea9b302b290c 100644
--- a/clang/test/CodeGenCXX/debug-info-static-inline-member.cpp
+++ b/clang/test/CodeGenCXX/debug-info-static-inline-member.cpp
@@ -43,7 +43,7 @@ int main() {
 // CHECK:  @{{.*}}cexpr_struct_with_addr{{.*}} = 
 // CHECK-SAME!dbg ![[EMPTY_GLOBAL:[0-9]+]]
 
-// CHECK:  !DIGlobalVariableExpression(var: ![[INT_VAR:[0-9]+]], expr: 
!DIExpression())
+// CHECK:  !DIGlobalVariableExpression(var: ![[INT_VAR:[

[clang] [clang][DebugInfo] Attach DW_AT_const_value to static data-member definitions if available (PR #72730)

2023-11-17 Thread Michael Buch via cfe-commits

Michael137 wrote:

@ilovepi 

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


[clang] [clang][DebugInfo] Attach DW_AT_const_value to static data-member definitions if available (PR #72730)

2023-11-17 Thread Paul Kirth via cfe-commits

ilovepi wrote:

This looks great, thanks for keeping me in the loop. :)

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


[clang] [AVR] make the AVR ABI Swift compatible (PR #72298)

2023-11-17 Thread Carl Peto via cfe-commits

carlos4242 wrote:

Thanks, that sounds like it's worth looking into and might avoid issues with 
AVR.

I'm still nowhere near enough of an LLVM expert to follow all the aspects of 
the discussion. Although from our perspective, I've never seen an issue that I 
know, using the above patch for the last few years in our LLVM back end for the 
swift compile (not in our build of clang). The code produced by the back end 
has always followed the AVR GCC ABI calling convention 
(https://gcc.gnu.org/wiki/avr-gcc ...roughly... registers assigned to 
parameters starting at r24 and working backward r22, r20, etc. to r8 then the 
rest on stack) when I have examined the generated assembly. But maybe that is 
because, until now, only our swift code has been emitted with the swift calling 
convention, until #71986 is merged, clang can't emit code with that calling 
convention and that's the issue?

Stupid question... Is it possible that our AVR LLVM back end is basically 
ignoring the swift calling convention when it actually emits our code? Doesn't 
usually the front end (clang/swift) just specify parameter types and the back 
end decides whether to put something in registers or on the stack? Sorry if I'm 
being dumb!

---

It might be that I just don't understand enough about LLVM and clang to really 
understand what all the surrounding code is doing properly, and maybe the right 
answer is for me to close this PR and wait for someone more experienced to come 
along when the time is right. We can always maintain this as a local patch in 
our builds instead, as we have for the past few years? I don't want to lay down 
issues for anyone using this in the future.

Or as an alternative, we can merge this PR as-is and deal with AVR problems 
later as an optimisation. I am neutral about what is the best approach and 
happy to take the advice of all the experts on here. (At the very least, the 
discussion has been enlightening for me!)

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


[libcxx] [libunwind] [llvm] [libc++] Allow running the test suite with optimizations (PR #68753)

2023-11-17 Thread via cfe-commits


@@ -87,6 +87,21 @@ def getStdFlag(cfg, std):
 return "-std=" + fallbacks[std]
 return None
 
+def getSpeedOptimizationFlag(cfg):
+if _isClang(cfg) or _isAppleClang(cfg) or _isGCC(cfg):
+return "-O3"
+elif _isMSVC(cfg):
+return "/O2"
+else:
+raise RuntimeError("Can't figure out what compiler is used in the 
configuration")
+
+def getSizeOptimizationFlag(cfg):
+if _isClang(cfg) or _isAppleClang(cfg) or _isGCC(cfg):
+return "-Os"
+elif _isMSVC(cfg):
+return "/O1"

philnik777 wrote:

There seems to also be `/Os`. @mstorsjo @StephanTLavavej @CaseyCarter Do you 
know which is the correct one?

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


[llvm] [libcxx] [libunwind] [libc++] Allow running the test suite with optimizations (PR #68753)

2023-11-17 Thread via cfe-commits

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


[libunwind] [llvm] [libcxx] [libc++] Allow running the test suite with optimizations (PR #68753)

2023-11-17 Thread via cfe-commits


@@ -0,0 +1,28 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef SUPPORT_DO_NOT_OPTIMIZE_H
+#define SUPPORT_DO_NOT_OPTIMIZE_H
+
+#include "test_macros.h"
+
+namespace support {
+// This function can be used to hide some objects from compiler optimizations.
+//
+// For example, this is useful to hide the result of a call to `new` and ensure
+// that the compiler doesn't elide the call to new/delete. Otherwise, elliding
+// calls to new/delete is allowed by the Standard and compilers actually do it
+// when optimizations are enabled.
+template 
+TEST_CONSTEXPR __attribute__((noinline)) T* do_not_optimize(T* ptr) 
TEST_NOEXCEPT {

philnik777 wrote:

We have `DoNotOptimize` already in `test_macros.h`(!?). I think we should use 
that version instead, since it properly clobbers things and works for more 
compilers. We'll have to make it `constexpr` though. 

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


[llvm] [libcxx] [libunwind] [libc++] Allow running the test suite with optimizations (PR #68753)

2023-11-17 Thread via cfe-commits

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


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


[clang] [clang] Sema::isSimpleTypeSpecifier return true for _Bool in c99 (PR #72204)

2023-11-17 Thread Carl Peto via cfe-commits

carlos4242 wrote:

The dup  in Format seems to have already drifted from the one in Sema so 
putting them together might be a significant change, a bit more than I'm 
comfortable taking on... I don't want to break or alter behaviour for someone's 
formatter just to fix a tiny issue I found in a backwater part of Sema. :)

I'm thinking this probably isn't a testable patch TBH. I came across this issue 
due to the swift compiler linking into libClang and calling this function. 
Within clang itself, it looks like it's only used for some obscure objective C 
case and an equally obscure error case. The only "test" I can envisage is 
building some kind of artificial stand-alone command line tool that links into 
libClang and tests it, doesn't seem like a sensible use of anyone's CPU for 
such a straight bufix?

---

But it's a decision for the maintainer?

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


[clang] f603369 - [clang-format][NFC] Remove a redundant isLiteral() call

2023-11-17 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-11-17T18:18:49-08:00
New Revision: f6033699646b7650123a273c043a93e5eeaac6d8

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

LOG: [clang-format][NFC] Remove a redundant isLiteral() call

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1d376cd8b5794dd..a6cd3c68e30bcaf 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3407,10 +3407,8 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken &Current,
 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
   return true;
 }
-if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
-Tok->Tok.isLiteral()) {
+if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
   return false;
-}
   }
   return false;
 }



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


[clang] [clang-format] Correctly annotate braces of empty functions (PR #72733)

2023-11-17 Thread Owen Pan via cfe-commits

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

Also fixed some existing test cases.

Fixed #57305.
Fixed #58251.

>From 519c21da642026b917c2e51c95cc4347f85163ca Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 17 Nov 2023 17:51:33 -0800
Subject: [PATCH] [clang-format] Correctly annotate braces of empty functions

Also fixed some existing test cases.

Fixed #57305.
Fixed #58251.
---
 clang/lib/Format/TokenAnnotator.cpp   | 13 +
 clang/unittests/Format/FormatTest.cpp | 38 ++---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 54 +++
 3 files changed, 86 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1d376cd8b5794dd..fed5ed88743ffb9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3477,6 +3477,19 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
 }
   }
 
+  if (IsCpp && LineIsFunctionDeclaration &&
+  Line.endsWith(tok::semi, tok::r_brace)) {
+auto *Tok = Line.Last->Previous;
+while (Tok->isNot(tok::r_brace))
+  Tok = Tok->Previous;
+if (auto *LBrace = Tok->MatchingParen; LBrace) {
+  assert(LBrace->is(tok::l_brace));
+  Tok->setBlockKind(BK_Block);
+  LBrace->setBlockKind(BK_Block);
+  LBrace->setFinalizedType(TT_FunctionLBrace);
+}
+  }
+
   if (IsCpp && SeenName && AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
 AfterLastAttribute->MustBreakBefore = true;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b5021f924a80904..10b991c6926879c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3415,7 +3415,7 @@ TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
   verifyFormat("myFunc(public);");
   verifyFormat("std::vector testVec = {private};");
   verifyFormat("private.p = 1;");
-  verifyFormat("void function(private...){};");
+  verifyFormat("void function(private...) {};");
   verifyFormat("if (private && public)");
   verifyFormat("private &= true;");
   verifyFormat("int x = private * public;");
@@ -16093,16 +16093,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
   Tab.IndentWidth = 8;
   Tab.UseTab = FormatStyle::UT_Never;
   Tab.TabWidth = 0;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16110,16 +16110,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_ForIndentation;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16127,16 +16127,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16144,16 +16144,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\

[clang] [clang-format] Correctly annotate braces of empty functions (PR #72733)

2023-11-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Also fixed some existing test cases.

Fixed #57305.
Fixed #58251.

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


3 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+13) 
- (modified) clang/unittests/Format/FormatTest.cpp (+19-19) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+54) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1d376cd8b5794dd..fed5ed88743ffb9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3477,6 +3477,19 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
 }
   }
 
+  if (IsCpp && LineIsFunctionDeclaration &&
+  Line.endsWith(tok::semi, tok::r_brace)) {
+auto *Tok = Line.Last->Previous;
+while (Tok->isNot(tok::r_brace))
+  Tok = Tok->Previous;
+if (auto *LBrace = Tok->MatchingParen; LBrace) {
+  assert(LBrace->is(tok::l_brace));
+  Tok->setBlockKind(BK_Block);
+  LBrace->setBlockKind(BK_Block);
+  LBrace->setFinalizedType(TT_FunctionLBrace);
+}
+  }
+
   if (IsCpp && SeenName && AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
 AfterLastAttribute->MustBreakBefore = true;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b5021f924a80904..10b991c6926879c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3415,7 +3415,7 @@ TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
   verifyFormat("myFunc(public);");
   verifyFormat("std::vector testVec = {private};");
   verifyFormat("private.p = 1;");
-  verifyFormat("void function(private...){};");
+  verifyFormat("void function(private...) {};");
   verifyFormat("if (private && public)");
   verifyFormat("private &= true;");
   verifyFormat("int x = private * public;");
@@ -16093,16 +16093,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
   Tab.IndentWidth = 8;
   Tab.UseTab = FormatStyle::UT_Never;
   Tab.TabWidth = 0;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16110,16 +16110,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_ForIndentation;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16127,16 +16127,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16144,16 +16144,16 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t// line starts with '\t'\n"
"};",
Tab);
 
-  verifyFormat("void a(){\n"
-   "// line starts with '\t'\n"
+  verifyFormat("void a() {\n"
+   "// line starts with '\t'\n"
"};",
"void a(){\n"
"\t\t// line starts with '\t'\n"
@@ -16161,7 +16161,7 @@ TEST_F(FormatTest, ZeroTabWidth) {
Tab);
 
   Tab.UseTab = FormatStyle::UT_Always;

[clang] fix: compatible C++ empty record with align UB with gcc (PR #72197)

2023-11-17 Thread via cfe-commits

https://github.com/hstk30-hw updated 
https://github.com/llvm/llvm-project/pull/72197

>From 76b86014cb4af9fe5b163d61a96597217d6e843c Mon Sep 17 00:00:00 2001
From: hstk30-hw 
Date: Sat, 18 Nov 2023 11:00:29 +
Subject: [PATCH] fix: empty record size > 64 with align let va_list get out of
 sync

---
 clang/lib/CodeGen/Targets/AArch64.cpp |  8 +++-
 clang/test/CodeGen/aarch64-args.cpp   | 13 +
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index be5145daa00b7f5..50e94306d370e6e 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -307,7 +307,13 @@ AArch64ABIInfo::classifyArgumentType(QualType Ty, bool 
IsVariadic,
 // 0.
 if (IsEmpty && Size == 0)
   return ABIArgInfo::getIgnore();
-return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
+// An empty struct can have size greater than one byte if alignment is
+// involved.
+// When size <= 64, we still hold it by i8 in IR for compatible,
+// and it lowering to registers.
+// When Size > 64, just fall through to avoid va_list out of sync.
+if (Size <= 64)
+  return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
   }
 
   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
diff --git a/clang/test/CodeGen/aarch64-args.cpp 
b/clang/test/CodeGen/aarch64-args.cpp
index fe1298cc683a404..a528156d173571f 100644
--- a/clang/test/CodeGen/aarch64-args.cpp
+++ b/clang/test/CodeGen/aarch64-args.cpp
@@ -65,3 +65,16 @@ EXTERNC struct SortOfEmpty sort_of_empty_ret(void) {
   struct SortOfEmpty e;
   return e;
 }
+
+// CHECK-GNU-CXX: define{{.*}} i32 @empty_align8_arg(i8 %a.coerce, i32 noundef 
%b)
+struct EmptyAlign8 { int __attribute__((aligned(8))) : 0; };
+EXTERNC int empty_align8_arg(struct EmptyAlign8 a, int b) {
+  return b;
+}
+
+// CHECK-GNU-CXX: define{{.*}} i32 @empty_align16_arg(i128 %a.coerce, i32 
noundef %b)
+struct EmptyAlign16 { long long int __attribute__((aligned(16))) : 0; };
+EXTERNC int empty_align16_arg(struct EmptyAlign16 a, int b) {
+  return b;
+}
+

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


[llvm] [libunwind] [libcxx] [libc++] Allow running the test suite with optimizations (PR #68753)

2023-11-17 Thread Stephan T. Lavavej via cfe-commits


@@ -87,6 +87,21 @@ def getStdFlag(cfg, std):
 return "-std=" + fallbacks[std]
 return None
 
+def getSpeedOptimizationFlag(cfg):
+if _isClang(cfg) or _isAppleClang(cfg) or _isGCC(cfg):
+return "-O3"
+elif _isMSVC(cfg):
+return "/O2"
+else:
+raise RuntimeError("Can't figure out what compiler is used in the 
configuration")
+
+def getSizeOptimizationFlag(cfg):
+if _isClang(cfg) or _isAppleClang(cfg) or _isGCC(cfg):
+return "-Os"
+elif _isMSVC(cfg):
+return "/O1"

StephanTLavavej wrote:

`/O1` versus `/O2` are better to use than the fine-grained options.

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


[clang] [Driver] Make ELF -nopie specific to OpenBSD (PR #72578)

2023-11-17 Thread Brad Smith via cfe-commits

brad0 wrote:

> > -nopie is for the linker. We only use -fno-pie for the compiler.
> 
> OK. Then it seems that the driver option `-nopie` for linking should be 
> removed even for OpenBSD?

Let me check something before I say anything further.

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-17 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

> Out of curiosity, I dialled into today's LLVM office hours and asked Aaron 
> Ballman about this

Thank you so much for making the effort on this issue. :)

> ...just change the code for building the invented CallExprs to give them an 
> invalid SourceLocation

Interesting idea and I'll explore it.


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


[libc] [clang-tools-extra] [mlir] [compiler-rt] [lld] [libcxx] [clang] [flang] [lldb] [llvm] [MLIR] Enable GPU Dialect to SYCL runtime integration (PR #71430)

2023-11-17 Thread Mehdi Amini via cfe-commits


@@ -61,6 +63,7 @@ registerAllGPUToLLVMIRTranslations(DialectRegistry ®istry) 
{
   registerLLVMDialectTranslation(registry);
   registerNVVMDialectTranslation(registry);
   registerROCDLDialectTranslation(registry);
+  registerSPIRVDialectTranslation(registry);

joker-eph wrote:

Which muir-translate test requires that? I don't find it by skimming the patch.

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


[libc] [clang-tools-extra] [mlir] [compiler-rt] [lld] [libcxx] [clang] [flang] [lldb] [llvm] [MLIR] Enable GPU Dialect to SYCL runtime integration (PR #71430)

2023-11-17 Thread Mehdi Amini via cfe-commits

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


[clang] [flang] [flang][Driver] Support -nodefaultlibs, -nostartfiles and -nostdlib (PR #72601)

2023-11-17 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/72601

>From 8d478b98effa8b6bb5d59605034ce35086cc0112 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Wed, 15 Nov 2023 14:24:11 -0500
Subject: [PATCH] [flang][Driver] Support -nodefaultlibs, -nostartfiles and
 -nostdlib

---
 clang/include/clang/Driver/Options.td |  9 ---
 flang/test/Driver/dynamic-linker.f90  | 36 +--
 2 files changed, 40 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 811550416110b3d..a0eb04a5cd9c6a7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5131,7 +5131,8 @@ def : Flag<["-"], "nocudalib">, Alias;
 def gpulibc : Flag<["-"], "gpulibc">, Visibility<[ClangOption, CC1Option]>,
   HelpText<"Link the LLVM C Library for GPUs">;
 def nogpulibc : Flag<["-"], "nogpulibc">, Visibility<[ClangOption, CC1Option]>;
-def nodefaultlibs : Flag<["-"], "nodefaultlibs">;
+def nodefaultlibs : Flag<["-"], "nodefaultlibs">,
+  Visibility<[ClangOption, CLOption, DXCOption, FlangOption]>;
 def nodriverkitlib : Flag<["-"], "nodriverkitlib">;
 def nofixprebinding : Flag<["-"], "nofixprebinding">;
 def nolibc : Flag<["-"], "nolibc">;
@@ -5141,7 +5142,8 @@ def no_pie : Flag<["-"], "no-pie">, 
Visibility<[ClangOption, FlangOption]>, Alia
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">, Group;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group,
+  Visibility<[ClangOption, CLOption, DXCOption, FlangOption]>;
 def nostdinc : Flag<["-"], "nostdinc">,
   Visibility<[ClangOption, CLOption, DXCOption]>, Group;
 def nostdlibinc : Flag<["-"], "nostdlibinc">, Group;
@@ -5149,7 +5151,8 @@ def nostdincxx : Flag<["-"], "nostdinc++">, 
Visibility<[ClangOption, CC1Option]>
   Group,
   HelpText<"Disable standard #include directories for the C++ standard 
library">,
   MarshallingInfoNegativeFlag>;
-def nostdlib : Flag<["-"], "nostdlib">, Group;
+def nostdlib : Flag<["-"], "nostdlib">, Group,
+  Visibility<[ClangOption, CLOption, DXCOption, FlangOption]>;
 def nostdlibxx : Flag<["-"], "nostdlib++">;
 def object : Flag<["-"], "object">;
 def o : JoinedOrSeparate<["-"], "o">,
diff --git a/flang/test/Driver/dynamic-linker.f90 
b/flang/test/Driver/dynamic-linker.f90
index 2745822dc107769..e7e00f637858edf 100644
--- a/flang/test/Driver/dynamic-linker.f90
+++ b/flang/test/Driver/dynamic-linker.f90
@@ -1,5 +1,5 @@
-! Verify that certain linker flags are known to the frontend and are passed on
-! to the linker.
+! Verify that certain linker flags are known to the frontend and are passed or
+! not passed on to the linker.
 
 ! RUN: %flang -### --target=x86_64-linux-gnu -rpath /path/to/dir -shared \
 ! RUN: -static %s 2>&1 | FileCheck \
@@ -18,3 +18,35 @@
 ! MSVC-LINKER-OPTIONS: "{{.*}}link.exe"
 ! MSVC-LINKER-OPTIONS-SAME: "-dll"
 ! MSVC-LINKER-OPTIONS-SAME: "-rpath" "/path/to/dir"
+
+! RUN: %flang -### --target=x86_64-unknown-freebsd -nostdlib %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NOSTDLIB %s
+! RUN: %flang -### --target=x86_64-unknown-netbsd -nostdlib %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NOSTDLIB %s
+! RUN: %flang -### --target=i386-pc-solaris2.11 -nostdlib %s 2>&1 | FileCheck \
+! RUN: --check-prefixes=NOSTDLIB %s
+
+! NOSTDLIB: "{{.*}}ld{{(.exe)?}}"
+! NOSTDLIB-NOT: crt{{[^.]+}}.o
+! NOSTDLIB-NOT: "-lFortran_main" "-lFortranRuntime" "-lFortranDecimal" "-lm"
+
+! RUN: %flang -### --target=x86_64-unknown-freebsd -nodefaultlibs %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NODEFAULTLIBS %s
+! RUN: %flang -### --target=x86_64-unknown-netbsd -nodefaultlibs %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NODEFAULTLIBS %s
+! RUN: %flang -### --target=i386-pc-solaris2.11 -nodefaultlibs %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NODEFAULTLIBS %s
+
+! NODEFAULTLIBS: "{{.*}}ld{{(.exe)?}}"
+! NODEFAULTLIBS-NOT: "-lFortran_main" "-lFortranRuntime" "-lFortranDecimal" 
"-lm"
+
+! RUN: %flang -### --target=x86_64-unknown-freebsd -nostartfiles %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NOSTARTFILES %s
+! RUN: %flang -### --target=x86_64-unknown-netbsd -nostartfiles %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NOSTARTFILES %s
+! RUN: %flang -### --target=i386-pc-solaris2.11 -nostartfiles %s 2>&1 | 
FileCheck \
+! RUN: --check-prefixes=NOSTARTFILES %s
+
+! NOSTARTFILES: "{{.*}}ld{{(.exe)?}}"
+! NOSTARTFILES-NOT: crt{{[^.]+}}.o
+! NOSTARTFILES: "-lFortran_main" "-lFortranRuntime" "-lFortranDecimal" "-lm"

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread via cfe-commits

https://github.com/sr-tream updated 
https://github.com/llvm/llvm-project/pull/72479

>From 06eaf30b75ac4209bdb5768511053d648ac55a55 Mon Sep 17 00:00:00 2001
From: SR_team 
Date: Thu, 16 Nov 2023 07:15:10 +0200
Subject: [PATCH] Add includes from source to non-self-contained headers

---
 clang-tools-extra/clangd/TUScheduler.cpp | 50 ++--
 1 file changed, 47 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 324ba1fc8cb8952..6e6e0836b83af04 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -52,6 +52,7 @@
 #include "Config.h"
 #include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
+#include "HeaderSourceSwitch.h"
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "clang-include-cleaner/Record.h"
@@ -64,6 +65,7 @@
 #include "support/Threading.h"
 #include "support/Trace.h"
 #include "clang/Basic/Stack.h"
+#include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/FunctionExtras.h"
@@ -881,10 +883,24 @@ void ASTWorker::update(ParseInputs Inputs, 
WantDiagnostics WantDiags,
 }
   }
 }
-if (Cmd)
+if (!Cmd)
+  Cmd = CDB.getFallbackCommand(FileName);
+if (Cmd) {
+  if (!Inputs.CompileCommand.CommandLine.empty()) {
+auto PosArg =
+std::find(Cmd->CommandLine.begin(), Cmd->CommandLine.end(), "--");
+auto UsePushBack = PosArg == Cmd->CommandLine.end();
+for (auto &&Arg : Inputs.CompileCommand.CommandLine) {
+  if (Arg.find("-include") != 0)
+continue;
+  if (UsePushBack)
+Cmd->CommandLine.push_back(std::move(Arg));
+  else
+PosArg = std::next(Cmd->CommandLine.insert(PosArg, 
std::move(Arg)));
+}
+  }
   Inputs.CompileCommand = std::move(*Cmd);
-else
-  Inputs.CompileCommand = CDB.getFallbackCommand(FileName);
+}
 
 bool InputsAreTheSame =
 std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
@@ -1684,6 +1700,34 @@ bool TUScheduler::update(PathRef File, ParseInputs 
Inputs,
 ContentChanged = true;
 FD->Contents = Inputs.Contents;
   }
+  if (isHeaderFile(File)) {
+std::string SourceFile;
+auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
+if (auto CorrespondingFile =
+clang::clangd::getCorrespondingHeaderOrSource(File, 
std::move(VFS)))
+  SourceFile = *CorrespondingFile;
+if (SourceFile.empty())
+  SourceFile = HeaderIncluders->get(File);
+if (!SourceFile.empty() && Files.contains(SourceFile)) {
+  std::unique_ptr &FD = Files[SourceFile];
+  if (FD && FD->Worker->isASTCached()) {
+if (auto AST = IdleASTs->take(FD->Worker.lock().get())) {
+  auto &Headers = AST.value()->getIncludeStructure().MainFileIncludes;
+  Inputs.CompileCommand.CommandLine.reserve(Headers.size());
+  for (const auto &H : Headers) {
+if (H.Resolved == File) {
+  if (isSystem(H.FileKind))
+Inputs.CompileCommand.CommandLine.clear();
+  break;
+}
+auto CmdLine = "-include" + H.Resolved;
+Inputs.CompileCommand.CommandLine.push_back(std::move(CmdLine));
+  }
+  IdleASTs->put(FD->Worker.lock().get(), std::move(AST.value()));
+}
+  }
+}
+  }
   FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged);
   // There might be synthetic update requests, don't change the LastActiveFile
   // in such cases.

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread via cfe-commits

https://github.com/sr-tream updated 
https://github.com/llvm/llvm-project/pull/72479

>From c85ae981ba584df754057e89703a7b1c1554e5aa Mon Sep 17 00:00:00 2001
From: SR_team 
Date: Thu, 16 Nov 2023 07:15:10 +0200
Subject: [PATCH] Add includes from source to non-self-contained headers

---
 clang-tools-extra/clangd/TUScheduler.cpp | 52 ++--
 1 file changed, 49 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 324ba1fc8cb8952..8988a09cffea2c7 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -52,6 +52,7 @@
 #include "Config.h"
 #include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
+#include "HeaderSourceSwitch.h"
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "clang-include-cleaner/Record.h"
@@ -64,6 +65,7 @@
 #include "support/Threading.h"
 #include "support/Trace.h"
 #include "clang/Basic/Stack.h"
+#include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/FunctionExtras.h"
@@ -881,10 +883,26 @@ void ASTWorker::update(ParseInputs Inputs, 
WantDiagnostics WantDiags,
 }
   }
 }
-if (Cmd)
+if (!Cmd)
+  Cmd = CDB.getFallbackCommand(FileName);
+if (Cmd) {
+  if (!Inputs.CompileCommand.CommandLine.empty()) {
+Cmd->CommandLine.reserve(Cmd->CommandLine.size() +
+ Inputs.CompileCommand.CommandLine.size());
+auto PosArg =
+std::find(Cmd->CommandLine.begin(), Cmd->CommandLine.end(), "--");
+auto UsePushBack = PosArg == Cmd->CommandLine.end();
+for (auto &&Arg : Inputs.CompileCommand.CommandLine) {
+  if (Arg.find("-include") != 0)
+continue;
+  if (UsePushBack)
+Cmd->CommandLine.push_back(std::move(Arg));
+  else
+PosArg = std::next(Cmd->CommandLine.insert(PosArg, 
std::move(Arg)));
+}
+  }
   Inputs.CompileCommand = std::move(*Cmd);
-else
-  Inputs.CompileCommand = CDB.getFallbackCommand(FileName);
+}
 
 bool InputsAreTheSame =
 std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
@@ -1684,6 +1702,34 @@ bool TUScheduler::update(PathRef File, ParseInputs 
Inputs,
 ContentChanged = true;
 FD->Contents = Inputs.Contents;
   }
+  if (isHeaderFile(File)) {
+std::string SourceFile;
+auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
+if (auto CorrespondingFile =
+clang::clangd::getCorrespondingHeaderOrSource(File, 
std::move(VFS)))
+  SourceFile = *CorrespondingFile;
+if (SourceFile.empty())
+  SourceFile = HeaderIncluders->get(File);
+if (!SourceFile.empty() && Files.contains(SourceFile)) {
+  std::unique_ptr &FD = Files[SourceFile];
+  if (FD && FD->Worker->isASTCached()) {
+if (auto AST = IdleASTs->take(FD->Worker.lock().get())) {
+  auto &Headers = AST.value()->getIncludeStructure().MainFileIncludes;
+  Inputs.CompileCommand.CommandLine.reserve(Headers.size());
+  for (const auto &H : Headers) {
+if (H.Resolved == File) {
+  if (isSystem(H.FileKind))
+Inputs.CompileCommand.CommandLine.clear();
+  break;
+}
+auto CmdLine = "-include" + H.Resolved;
+Inputs.CompileCommand.CommandLine.push_back(std::move(CmdLine));
+  }
+  IdleASTs->put(FD->Worker.lock().get(), std::move(AST.value()));
+}
+  }
+}
+  }
   FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged);
   // There might be synthetic update requests, don't change the LastActiveFile
   // in such cases.

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread via cfe-commits

https://github.com/sr-tream updated 
https://github.com/llvm/llvm-project/pull/72479

>From 35456a46409862a31014161978e56f9ad184a7f1 Mon Sep 17 00:00:00 2001
From: SR_team 
Date: Thu, 16 Nov 2023 07:15:10 +0200
Subject: [PATCH] Add includes from source to non-self-contained headers

---
 clang-tools-extra/clangd/TUScheduler.cpp | 60 +---
 1 file changed, 54 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 324ba1fc8cb8952..df9b5e715ab03bd 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -52,6 +52,7 @@
 #include "Config.h"
 #include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
+#include "HeaderSourceSwitch.h"
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "clang-include-cleaner/Record.h"
@@ -64,6 +65,7 @@
 #include "support/Threading.h"
 #include "support/Trace.h"
 #include "clang/Basic/Stack.h"
+#include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/FunctionExtras.h"
@@ -622,7 +624,7 @@ class ASTWorker {
  const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks);
   ~ASTWorker();
 
-  void update(ParseInputs Inputs, WantDiagnostics, bool ContentChanged);
+  void update(ParseInputs Inputs, WantDiagnostics, bool ContentChanged, 
std::optional> SourceInclides);
   void
   runWithAST(llvm::StringRef Name,
  llvm::unique_function)> Action,
@@ -857,7 +859,7 @@ ASTWorker::~ASTWorker() {
 }
 
 void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags,
-   bool ContentChanged) {
+   bool ContentChanged, 
std::optional> SourceInclides) {
   llvm::StringLiteral TaskName = "Update";
   auto Task = [=]() mutable {
 // Get the actual command as `Inputs` does not have a command.
@@ -881,10 +883,24 @@ void ASTWorker::update(ParseInputs Inputs, 
WantDiagnostics WantDiags,
 }
   }
 }
-if (Cmd)
+if (!Cmd)
+  Cmd = CDB.getFallbackCommand(FileName);
+if (Cmd) {
+  if (SourceInclides && !SourceInclides->empty()) {
+Cmd->CommandLine.reserve(Cmd->CommandLine.size() +
+ SourceInclides->size());
+auto PosArg =
+std::find(Cmd->CommandLine.begin(), Cmd->CommandLine.end(), "--");
+auto UsePushBack = PosArg == Cmd->CommandLine.end();
+for (auto &&Arg : *SourceInclides) {
+  if (UsePushBack)
+Cmd->CommandLine.push_back(std::move(Arg));
+  else
+PosArg = std::next(Cmd->CommandLine.insert(PosArg, 
std::move(Arg)));
+}
+  }
   Inputs.CompileCommand = std::move(*Cmd);
-else
-  Inputs.CompileCommand = CDB.getFallbackCommand(FileName);
+}
 
 bool InputsAreTheSame =
 std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
@@ -1684,7 +1700,39 @@ bool TUScheduler::update(PathRef File, ParseInputs 
Inputs,
 ContentChanged = true;
 FD->Contents = Inputs.Contents;
   }
-  FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged);
+  std::optional> SourceInclides;
+  if (isHeaderFile(File)) {
+std::string SourceFile;
+auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
+if (auto CorrespondingFile =
+clang::clangd::getCorrespondingHeaderOrSource(File, 
std::move(VFS)))
+  SourceFile = *CorrespondingFile;
+if (SourceFile.empty())
+  SourceFile = HeaderIncluders->get(File);
+if (!SourceFile.empty() && Files.contains(SourceFile)) {
+  std::unique_ptr &FD = Files[SourceFile];
+  if (FD && FD->Worker->isASTCached()) {
+if (auto AST = IdleASTs->take(FD->Worker.lock().get())) {
+  auto &Headers = AST.value()->getIncludeStructure().MainFileIncludes;
+  std::vector Includes;
+  Includes.reserve(Headers.size());
+  for (const auto &H : Headers) {
+if (H.Resolved == File) {
+  if (isSystem(H.FileKind))
+Includes.clear();
+  break;
+}
+auto Include = "-include" + H.Resolved;
+Includes.push_back(std::move(Include));
+  }
+  if (!Includes.empty())
+SourceInclides = std::move(Includes);
+  IdleASTs->put(FD->Worker.lock().get(), std::move(AST.value()));
+}
+  }
+}
+  }
+  FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged, 
SourceInclides);
   // There might be synthetic update requests, don't change the LastActiveFile
   // in such cases.
   if (ContentChanged)

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

@sr-tream just so you know, every time you force-push a PR, github sends every 
subscriber an email notification

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread via cfe-commits

sr-tream wrote:

> @sr-tream just so you know, every time you force-push a PR, github sends 
> every subscriber an email notification

Sorry for flood, I will try to avoid this from now on

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


[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Björn Schäpers via cfe-commits


@@ -1316,6 +1316,8 @@ void 
WhitespaceManager::alignArrayInitializersRightJustified(
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next;
  Next = Next->NextColumnElement) {
+  if (RowCount >= CellDescs.CellCounts.size())
+break;

HazardyKnusperkeks wrote:

I would change the other lines too. I think it's better to see the condition in 
the `for`, but it's your call.

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


[clang] [clang][Interp] Implement builtin_expect (PR #69713)

2023-11-17 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/69713

>From e11a956d0389b1c0ed4ed54a908c3498dba2aba7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 20 Oct 2023 14:16:22 +0200
Subject: [PATCH] [clang][Interp] Implement builtin_expect

---
 clang/lib/AST/Interp/InterpBuiltin.cpp| 52 +++
 clang/test/AST/Interp/builtin-functions.cpp   |  8 +++
 .../Sema/builtin-expect-with-probability.cpp  |  1 +
 3 files changed, 61 insertions(+)

diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index bb3e13599b01d4e..2cfd19a02c0c33c 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -33,6 +33,19 @@ PrimType getIntPrimType(const InterpState &S) {
   llvm_unreachable("Int isn't 16 or 32 bit?");
 }
 
+PrimType getLongPrimType(const InterpState &S) {
+  const TargetInfo &TI = S.getCtx().getTargetInfo();
+  unsigned LongWidth = TI.getLongWidth();
+
+  if (LongWidth == 64)
+return PT_Sint64;
+  else if (LongWidth == 32)
+return PT_Sint32;
+  else if (LongWidth == 16)
+return PT_Sint16;
+  llvm_unreachable("long isn't 16, 32 or 64 bit?");
+}
+
 /// Peek an integer value from the stack into an APSInt.
 static APSInt peekToAPSInt(InterpStack &Stk, PrimType T, size_t Offset = 0) {
   if (Offset == 0)
@@ -109,6 +122,19 @@ static void pushAPSInt(InterpState &S, const APSInt &Val) {
   }
 }
 
+/// Pushes \p Val to the stack, as a target-dependent 'long'.
+static void pushLong(InterpState &S, int64_t Val) {
+  PrimType LongType = getLongPrimType(S);
+  if (LongType == PT_Sint64)
+S.Stk.push>(Integral<64, true>::from(Val));
+  else if (LongType == PT_Sint32)
+S.Stk.push>(Integral<32, true>::from(Val));
+  else if (LongType == PT_Sint16)
+S.Stk.push>(Integral<16, true>::from(Val));
+  else
+llvm_unreachable("Long isn't 16, 32 or 64 bit?");
+}
+
 static void pushSizeT(InterpState &S, uint64_t Val) {
   const TargetInfo &TI = S.getCtx().getTargetInfo();
   unsigned SizeTWidth = TI.getTypeWidth(TI.getSizeType());
@@ -517,6 +543,26 @@ static bool interp__builtin_bitreverse(InterpState &S, 
CodePtr OpPC,
   return true;
 }
 
+// __builtin_expect(long, long)
+// __builtin_expect_with_probability(long, long, double)
+static bool interp__builtin_expect(InterpState &S, CodePtr OpPC,
+   const InterpFrame *Frame,
+   const Function *Func, const CallExpr *Call) 
{
+  // The return value is simply the value of the first parameter.
+  // We ignore the probability.
+  unsigned NumArgs = Call->getNumArgs();
+  assert(NumArgs == 2 || NumArgs == 3);
+
+  PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
+  unsigned Offset = align(primSize(getLongPrimType(S))) * 2;
+  if (NumArgs == 3)
+Offset += align(primSize(PT_Float));
+
+  APSInt Val = peekToAPSInt(S.Stk, ArgT, Offset);
+  pushLong(S, Val.getSExtValue());
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call) {
   InterpFrame *Frame = S.Current;
@@ -681,6 +727,12 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
   return false;
 break;
 
+  case Builtin::BI__builtin_expect:
+  case Builtin::BI__builtin_expect_with_probability:
+if (!interp__builtin_expect(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
   default:
 return false;
   }
diff --git a/clang/test/AST/Interp/builtin-functions.cpp 
b/clang/test/AST/Interp/builtin-functions.cpp
index 0726dab37cb4eb0..35a1f9a75092a05 100644
--- a/clang/test/AST/Interp/builtin-functions.cpp
+++ b/clang/test/AST/Interp/builtin-functions.cpp
@@ -331,3 +331,11 @@ namespace bitreverse {
   char bitreverse3[__builtin_bitreverse32(0x12345678) == 0x1E6A2C48 ? 1 : -1];
   char bitreverse4[__builtin_bitreverse64(0x0123456789ABCDEFULL) == 
0xF7B3D591E6A2C480 ? 1 : -1];
 }
+
+namespace expect {
+  constexpr int a() {
+return 12;
+  }
+  static_assert(__builtin_expect(a(),1) == 12, "");
+  static_assert(__builtin_expect_with_probability(a(), 1, 1.0) == 12, "");
+}
diff --git a/clang/test/Sema/builtin-expect-with-probability.cpp 
b/clang/test/Sema/builtin-expect-with-probability.cpp
index 2b72c7b27ae93e8..c55cde84b254834 100644
--- a/clang/test/Sema/builtin-expect-with-probability.cpp
+++ b/clang/test/Sema/builtin-expect-with-probability.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify 
-fexperimental-new-constant-interpreter %s
 
 __attribute__((noreturn)) extern void bar();
 

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2023-11-17 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

This PR is not related to [cwg2804](https://wg21.link/cwg2804). We are already 
aware of the mentioned issue and are tracking it in 
https://github.com/llvm/llvm-project/issues/70210.

This PR is different and it fixes an implementation bug in rewriting template 
non-member operators (the conversion seq was computed incorrectly and 
associated to incorrect index). The difference in compilers 
([godbolt](https://godbolt.org/z/11331KW6e)) you currently see is because of 
this bug and clang would also correctly consider the example as ambiguous.

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


[libcxx] [llvm] [clang-tools-extra] [flang] [lldb] [lld] [clang] [compiler-rt] [libunwind] [AMDGPU] - Add constant folding for s_quadmask (PR #72381)

2023-11-17 Thread Matt Arsenault via cfe-commits


@@ -50,13 +49,10 @@ define i64 @test_quadmask_constant_i64() {
 ; GFX11-LABEL: test_quadmask_constant_i64:
 ; GFX11:   ; %bb.0: ; %entry
 ; GFX11-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)
-; GFX11-NEXT:s_mov_b32 s0, 0x85fe3a92
-; GFX11-NEXT:s_mov_b32 s1, 0x67de48fc
-; GFX11-NEXT:s_quadmask_b64 s[0:1], s[0:1]
-; GFX11-NEXT:v_dual_mov_b32 v0, s0 :: v_dual_mov_b32 v1, s1
+; GFX11-NEXT:v_dual_mov_b32 v0, 0xe3e6 :: v_dual_mov_b32 v1, 0
 ; GFX11-NEXT:s_setpc_b64 s[30:31]
 entry:
-  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67DE48FC85FE3A92)
+  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67D000FC85F00A90)

arsenm wrote:

Test some additional values, especially 0, -1, undef and poison 

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


[clang] [AArch64][SME2] Add FCLAMP, CNTP builtins for SME2 (PR #72487)

2023-11-17 Thread Dinar Temirbulatov via cfe-commits

https://github.com/dtemirbulatov updated 
https://github.com/llvm/llvm-project/pull/72487

>From dc691934814029de64494272697d562ddb86dfee Mon Sep 17 00:00:00 2001
From: Dinar Temirbulatov 
Date: Thu, 16 Nov 2023 07:21:17 +
Subject: [PATCH 1/4] [AArch64][SME2] Add FCLAMP, CNTP builtins for SME2

This change enables FCLAMP, FCLAMP_BF16, CNTP builtins for SME2 target.
---
 clang/include/clang/Basic/arm_sve.td  | 10 +++---
 .../acle_sve2p1_bfclamp.c | 35 +++
 .../acle_sve2p1_cntp.c|  3 ++
 .../acle_sve2p1_fclamp.c  |  8 +
 4 files changed, 52 insertions(+), 4 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfclamp.c

diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 40e474d5f0a8f4e..5947a1a1054cc16 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1860,7 +1860,6 @@ def SVBGRP_N : SInst<"svbgrp[_n_{d}]", "dda", "UcUsUiUl", 
MergeNone, "aarch64_sv
 }
 
 let TargetGuard = "sve2p1" in {
-def SVFCLAMP   : SInst<"svclamp[_{d}]", "", "hfd", MergeNone, 
"aarch64_sve_fclamp", [], []>;
 def SVPTRUE_COUNT  : SInst<"svptrue_{d}", "}v", "QcQsQiQl", MergeNone, 
"aarch64_sve_ptrue_{d}", [IsOverloadNone], []>;
 def SVPFALSE_COUNT_ALIAS : SInst<"svpfalse_c", "}v", "", MergeNone, "", 
[IsOverloadNone]>;
 
@@ -1970,17 +1969,20 @@ def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", 
"dd$$i", "f", MergeNone, "aar
 let TargetGuard = "sve2p1" in {
 def SVSCLAMP : SInst<"svclamp[_{d}]", "", "csil", MergeNone, 
"aarch64_sve_sclamp", [], []>;
 def SVUCLAMP : SInst<"svclamp[_{d}]", "", "UcUsUiUl", MergeNone, 
"aarch64_sve_uclamp", [], []>;
-
 def SVPSEL_B : SInst<"svpsel_lane_b8",  "PPPm", "Pc", MergeNone, "", [], []>;
 def SVPSEL_H : SInst<"svpsel_lane_b16", "PPPm", "Ps", MergeNone, "", [], []>;
 def SVPSEL_S : SInst<"svpsel_lane_b32", "PPPm", "Pi", MergeNone, "", [], []>;
 def SVPSEL_D : SInst<"svpsel_lane_b64", "PPPm", "Pl", MergeNone, "", [], []>;
 
-def SVCNTP_COUNT : SInst<"svcntp_{d}", "n}i", "QcQsQiQl", MergeNone, 
"aarch64_sve_cntp_{d}", [IsOverloadNone], [ImmCheck<1, ImmCheck2_4_Mul2>]>;
-
 defm SVREVD : SInstZPZ<"svrevd", "csilUcUsUiUl", "aarch64_sve_revd">;
 }
 
+let TargetGuard = "sve2p1|sme2" in {
+  def SVFCLAMP   : SInst<"svclamp[_{d}]", "", "hfd", MergeNone, 
"aarch64_sve_fclamp", [IsStreamingCompatible], []>;
+  def SVFCLAMP_BF   : SInst<"svclamp[_{d}]", "", "b", MergeNone, 
"aarch64_sve_fclamp", [IsStreamingCompatible], []>;
+  def SVCNTP_COUNT : SInst<"svcntp_{d}", "n}i", "QcQsQiQl", MergeNone, 
"aarch64_sve_cntp_{d}", [IsOverloadNone, IsStreamingCompatible], [ImmCheck<1, 
ImmCheck2_4_Mul2>]>;
+}
+
 

 // SME2
 
diff --git a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfclamp.c 
b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfclamp.c
new file mode 100644
index 000..4cd5627eb5c4dd8
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfclamp.c
@@ -0,0 +1,35 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve2p1 
-target-feature +bf16 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | 
opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve2p1 
-target-feature +bf16 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -target-feature +bf16 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -target-feature +bf16 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 
-target-feature +sve -target-feature +bf16 -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 
-target-feature +sve -target-feature +bf16 -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +sve -target-feature +bf16 -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | opt -S -p 
me

[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Owen Pan via cfe-commits


@@ -1316,6 +1316,8 @@ void 
WhitespaceManager::alignArrayInitializersRightJustified(
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next;
  Next = Next->NextColumnElement) {
+  if (RowCount >= CellDescs.CellCounts.size())
+break;

owenca wrote:

The same/similar code appeared twice in this file and once in the header file. 
If I were to refactor it, I might not use the same for-loop, so I'll leave it 
as is for now. (There are also much more cleanup that can be done with this 
option, but I don't know if it's worthwhile as it's so buggy even after 
@mydeveloperday limited it to matrices.)

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


[clang] [AMDGPU] Treat printf as builtin for OpenCL (PR #72554)

2023-11-17 Thread Vikram Hegde via cfe-commits

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


[clang] [clang] fix emitvaarg when struct is null (PR #72624)

2023-11-17 Thread via cfe-commits

https://github.com/Jolyon0202 created 
https://github.com/llvm/llvm-project/pull/72624

Fix bug when emit null struct with attribute aligned(16) and ICE of debugbuild.

>From f0245b42534f423edaba45c2b3b2dffeb86e3074 Mon Sep 17 00:00:00 2001
From: Jian Yang 
Date: Wed, 15 Nov 2023 15:44:35 +0800
Subject: [PATCH] [clang] fix emitvaarg when struct is null

Fix bug when emit null struct with attribute aligned(16) and ICE of debugbuild.
---
 clang/lib/CodeGen/Targets/AArch64.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index be5145daa00b7f5..49dff102b7d554a 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -526,7 +526,7 @@ Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 
QualType Ty,
   llvm::Type *BaseTy = CGF.ConvertType(Ty);
   if (IsIndirect)
 BaseTy = llvm::PointerType::getUnqual(BaseTy);
-  else if (AI.getCoerceToType())
+  else if (AI.canHaveCoerceToType() && AI.getCoerceToType())
 BaseTy = AI.getCoerceToType();
 
   unsigned NumRegs = 1;
@@ -594,7 +594,7 @@ Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 
QualType Ty,
   // Integer arguments may need to correct register alignment (for example a
   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
   // align __gr_offs to calculate the potential address.
-  if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
+  if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8 && !TySize.isZero()) {
 int Align = TyAlign.getQuantity();
 
 reg_offs = CGF.Builder.CreateAdd(

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


[clang] [clang] fix emitvaarg when struct is null (PR #72624)

2023-11-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Jolyon (Jolyon0202)


Changes

Fix bug when emit null struct with attribute aligned(16) and ICE of debugbuild.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+2-2) 


``diff
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index be5145daa00b7f5..49dff102b7d554a 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -526,7 +526,7 @@ Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 
QualType Ty,
   llvm::Type *BaseTy = CGF.ConvertType(Ty);
   if (IsIndirect)
 BaseTy = llvm::PointerType::getUnqual(BaseTy);
-  else if (AI.getCoerceToType())
+  else if (AI.canHaveCoerceToType() && AI.getCoerceToType())
 BaseTy = AI.getCoerceToType();
 
   unsigned NumRegs = 1;
@@ -594,7 +594,7 @@ Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 
QualType Ty,
   // Integer arguments may need to correct register alignment (for example a
   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
   // align __gr_offs to calculate the potential address.
-  if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
+  if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8 && !TySize.isZero()) {
 int Align = TyAlign.getQuantity();
 
 reg_offs = CGF.Builder.CreateAdd(

``




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


[clang-tools-extra] [include-cleaner] Make sure exports of stdlib also works for physical files (PR #72246)

2023-11-17 Thread kadir çetinkaya via cfe-commits


@@ -232,6 +232,17 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
   void checkForExport(FileID IncludingFile, int HashLine,
   std::optional IncludedHeader,
   OptionalFileEntryRef IncludedFile) {
+auto AddExport = [&] {

kadircet wrote:

this was preparation for a follow-up change, but I guess it's better to do it 
there.

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


[clang-tools-extra] [include-cleaner] Make sure exports of stdlib also works for physical files (PR #72246)

2023-11-17 Thread kadir çetinkaya via cfe-commits


@@ -232,6 +232,17 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
   void checkForExport(FileID IncludingFile, int HashLine,
   std::optional IncludedHeader,
   OptionalFileEntryRef IncludedFile) {
+auto AddExport = [&] {
+  auto ExportingFileName = SM.getFileEntryForID(IncludingFile)->getName();
+  if (IncludedFile) {

kadircet wrote:

i'd rather use the name from file entry, and get rid of `Path` stored in Top 
(in a follow-up change), as it's not needed anymore.

which later on should bring us 1-step closer to making `PragmaIncludes` 
copyable, so that clangd can easily make a copy and extend the one from 
Preamble build, with pragmas inside the main-file AST.

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


[clang] [coroutines] Introduce [[clang::coro_return_type]] and [[clang::coro_wrapper]] (PR #71945)

2023-11-17 Thread Haojian Wu via cfe-commits

https://github.com/hokein commented:

Thanks, the change looks good from my side. I will leave the final stamp to 
@ChuanqiXu9 and @ilya-biryukov.

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


[clang-tools-extra] [include-cleaner] Make sure exports of stdlib also works for physical files (PR #72246)

2023-11-17 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang] fix emitvaarg when struct is null (PR #72624)

2023-11-17 Thread via cfe-commits

Jolyon0202 wrote:

demo:
```
#include 
extern void *memset (void *__s, int __c, size_t __n);
typedef __builtin_va_list va_list;

struct S94 {
  struct __attribute__((aligned(16))) {
  } a;
};

struct S94 s94;

void check94va(int z, ...) {
  va_list ap;
  __builtin_va_start(ap, z);
  struct S94 arg1 =  __builtin_va_arg(ap, struct S94);
  long long int tmp = __builtin_va_arg(ap, long long);
  printf("result = %lld\n", tmp);
  if (tmp != 2LL) {
printf("Fails\n");
  }
  __builtin_va_end(ap);
}

int main(void) {
  memset(&s94, '\0', sizeof(s94));
  printf("sizeof(s94) = %ld\n", sizeof(s94));
  check94va(1, s94, 2LL);
  return 0;
}
```
found two bug need to fix:
1  If the alignment of S94(null struct) is less than 16, the result is correct. 
2  ICE of AI.getCoerceToType() in debugbuild.(AI can not getcoerceTotype when 
it's null)



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


[clang] [coroutines] Introduce [[clang::coro_return_type]] and [[clang::coro_wrapper]] (PR #71945)

2023-11-17 Thread Chuanqi Xu via cfe-commits

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

LGTM. Please wait for 3~5 days in case @ilya-biryukov has more comments.

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2023-11-17 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

I wanted to note down the challenges of landing this and the strategy to move 
forward.

 Challenges
* Landing this would make old code ambiguous 
([example](https://godbolt.org/z/11331KW6e)). This is not unexpected, and it is 
ambiguous in C++20.
* This would break LLVM in C++20 
([breakage](https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/STLExtras.h#L1293-L1303)).
 We do not want to break LLVM at head.
* But it would not be possible to resolve ambiguity also for **template friend 
functions** because of 
[cwg2804](https://cplusplus.github.io/CWG/issues/2804.html).
* In order to resolve this ambiguity, one solution is to make the operator 
non-friend and add a matching `operator!=` 
([P2468R2](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2468r2.html)).
 This is done in https://github.com/llvm/llvm-project/pull/72348. The solution 
would look like:
  ```cpp
  namespace N{
  struct P {};
  template bool operator==(const P&, const S &);
  template bool operator!=(const P&, const S &);
  struct A : public P {};
  struct B : public P {};
  }
  bool x = N::A{} == N::B{};
  ```
* The catch is that clang only recently fixed its  
([P2468R2](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2468r2.html))
 implementation for `operators==` found through ADL in 
https://github.com/llvm/llvm-project/commit/9330261143ccbe947ef0687fd20747ba47f26879.
* Without the above fix, LLVM would still be broken in clang-17 (because 
clang-17 doesn't have 
https://github.com/llvm/llvm-project/commit/9330261143ccbe947ef0687fd20747ba47f26879).

 Strategy
1. Wait for cherrypicking 
https://github.com/llvm/llvm-project-release-prs/pull/778 into clang-17.0.6.
2. Land https://github.com/llvm/llvm-project/pull/72348 to unbreak LLVM.
3. Update the latest revision to build LLVM in C++20 to **17.0.6**.
4. Land this PR https://github.com/llvm/llvm-project/pull/72213 
5. Implement [cwg2804](https://cplusplus.github.io/CWG/issues/2804.html) 
proposal when finalised.
6. **clang-18** would have correct behaviour for template operators, i.e., 
correct ambiguities surfaced with the option of resolving through adding 
matching `operator!=`.


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


[clang-tools-extra] [include-cleaner] Make sure exports of stdlib also works for physical files (PR #72246)

2023-11-17 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/72246

From 84f320a1c746eddea3171bd984613464a5872cbb Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Tue, 14 Nov 2023 13:08:52 +0100
Subject: [PATCH] [include-cleaner] Make sure exports of stdlib also works for
 physical files

This was creating discrepancy in cases where we might have a physical
file entry (e.g. because we followed a source location from a stdlib
file) and tried to find its exporters.
---
 .../include-cleaner/lib/Record.cpp | 18 --
 .../include-cleaner/unittests/RecordTest.cpp   |  2 ++
 2 files changed, 6 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index 7a8e10a9c675496..6e00ff93a7fe2fa 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -240,20 +240,10 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
 // Make sure current include is covered by the export pragma.
 if ((Top.Block && HashLine > Top.SeenAtLine) ||
 Top.SeenAtLine == HashLine) {
-  if (IncludedHeader) {
-switch (IncludedHeader->kind()) {
-case Header::Physical:
-  Out->IWYUExportBy[IncludedHeader->physical().getUniqueID()]
-  .push_back(Top.Path);
-  break;
-case Header::Standard:
-  Out->StdIWYUExportBy[IncludedHeader->standard()].push_back(Top.Path);
-  break;
-case Header::Verbatim:
-  assert(false && "unexpected Verbatim header");
-  break;
-}
-  }
+  if (IncludedFile)
+Out->IWYUExportBy[IncludedFile->getUniqueID()].push_back(Top.Path);
+  if (IncludedHeader && IncludedHeader->kind() == Header::Standard)
+Out->StdIWYUExportBy[IncludedHeader->standard()].push_back(Top.Path);
   // main-file #include with export pragma should never be removed.
   if (Top.SeenAtFile == SM.getMainFileID() && IncludedFile)
 Out->ShouldKeep.insert(IncludedFile->getUniqueID());
diff --git a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
index 36850731d514539..dfefa66887b0f24 100644
--- a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -452,6 +452,8 @@ TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
   auto &FM = Processed.fileManager();
   EXPECT_THAT(PI.getExporters(*tooling::stdlib::Header::named(""), FM),
   testing::UnorderedElementsAre(FileNamed("export.h")));
+  EXPECT_THAT(PI.getExporters(llvm::cantFail(FM.getFileRef("string")), FM),
+  testing::UnorderedElementsAre(FileNamed("export.h")));
 }
 
 TEST_F(PragmaIncludeTest, IWYUExportBlock) {

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


[clang-tools-extra] fd2d5ad - [include-cleaner] Make sure exports of stdlib also works for physical files (#72246)

2023-11-17 Thread via cfe-commits

Author: kadir çetinkaya
Date: 2023-11-17T10:11:21+01:00
New Revision: fd2d5add437b2b324492b1bc29374699fe7b614b

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

LOG: [include-cleaner] Make sure exports of stdlib also works for physical 
files (#72246)

This was creating discrepancy in cases where we might have a physical
file entry (e.g. because we followed a source location from a stdlib
file) and tried to find its exporters.

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index 7a8e10a9c675496..6e00ff93a7fe2fa 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -240,20 +240,10 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
 // Make sure current include is covered by the export pragma.
 if ((Top.Block && HashLine > Top.SeenAtLine) ||
 Top.SeenAtLine == HashLine) {
-  if (IncludedHeader) {
-switch (IncludedHeader->kind()) {
-case Header::Physical:
-  Out->IWYUExportBy[IncludedHeader->physical().getUniqueID()]
-  .push_back(Top.Path);
-  break;
-case Header::Standard:
-  Out->StdIWYUExportBy[IncludedHeader->standard()].push_back(Top.Path);
-  break;
-case Header::Verbatim:
-  assert(false && "unexpected Verbatim header");
-  break;
-}
-  }
+  if (IncludedFile)
+Out->IWYUExportBy[IncludedFile->getUniqueID()].push_back(Top.Path);
+  if (IncludedHeader && IncludedHeader->kind() == Header::Standard)
+Out->StdIWYUExportBy[IncludedHeader->standard()].push_back(Top.Path);
   // main-file #include with export pragma should never be removed.
   if (Top.SeenAtFile == SM.getMainFileID() && IncludedFile)
 Out->ShouldKeep.insert(IncludedFile->getUniqueID());

diff  --git a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
index 36850731d514539..dfefa66887b0f24 100644
--- a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -452,6 +452,8 @@ TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
   auto &FM = Processed.fileManager();
   EXPECT_THAT(PI.getExporters(*tooling::stdlib::Header::named(""), FM),
   testing::UnorderedElementsAre(FileNamed("export.h")));
+  EXPECT_THAT(PI.getExporters(llvm::cantFail(FM.getFileRef("string")), FM),
+  testing::UnorderedElementsAre(FileNamed("export.h")));
 }
 
 TEST_F(PragmaIncludeTest, IWYUExportBlock) {



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


[clang-tools-extra] [include-cleaner] Make sure exports of stdlib also works for physical files (PR #72246)

2023-11-17 Thread kadir çetinkaya via cfe-commits

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


[clang] 76a441a - [MC] Fix compression header size check in ELF writer

2023-11-17 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-11-17T01:13:38-08:00
New Revision: 76a441a6efa5b7e73d96a3d67512493f3873b1cb

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

LOG: [MC] Fix compression header size check in ELF writer

This is #66888 with a test. For MC we only use a zstd test, as zlib has
a lot of versions/forks with different speed/size tradeoff, which would
make the test more brittle. If clang/test/Misc/cc1as-compress.s turns
out to be brittle, we could make the string longer.

Added: 


Modified: 
clang/test/Misc/cc1as-compress.s
llvm/lib/MC/ELFObjectWriter.cpp
llvm/test/MC/ELF/compress-debug-sections-zstd.s

Removed: 




diff  --git a/clang/test/Misc/cc1as-compress.s 
b/clang/test/Misc/cc1as-compress.s
index 54563c33bd165cb..4c81c5ca0f7f26f 100644
--- a/clang/test/Misc/cc1as-compress.s
+++ b/clang/test/Misc/cc1as-compress.s
@@ -12,4 +12,4 @@
 // ZSTD:  0200 
 
 .section.debug_str,"MS",@progbits,1
-.asciz  "perfectly compressable data sample 
*"
+.asciz  "perfectly compressable data sample 
**"

diff  --git a/llvm/lib/MC/ELFObjectWriter.cpp b/llvm/lib/MC/ELFObjectWriter.cpp
index 8490fefe7ff5351..e4d18d8a7dd5b54 100644
--- a/llvm/lib/MC/ELFObjectWriter.cpp
+++ b/llvm/lib/MC/ELFObjectWriter.cpp
@@ -843,7 +843,7 @@ bool ELFWriter::maybeWriteCompression(
 uint32_t ChType, uint64_t Size,
 SmallVectorImpl &CompressedContents, Align Alignment) {
   uint64_t HdrSize =
-  is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
+  is64Bit() ? sizeof(ELF::Elf64_Chdr) : sizeof(ELF::Elf32_Chdr);
   if (Size <= HdrSize + CompressedContents.size())
 return false;
   // Platform specific header is followed by compressed data.

diff  --git a/llvm/test/MC/ELF/compress-debug-sections-zstd.s 
b/llvm/test/MC/ELF/compress-debug-sections-zstd.s
index 01ae21a2b8abb7b..a05c5015728156a 100644
--- a/llvm/test/MC/ELF/compress-debug-sections-zstd.s
+++ b/llvm/test/MC/ELF/compress-debug-sections-zstd.s
@@ -10,7 +10,8 @@
 # SEC: .debug_line   PROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 00   C 0 0  8
 # SEC: .debug_abbrev PROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 00 0 0  1
 # SEC: .debug_info   PROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 00 0 0  1
-# SEC: .debug_strPROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 01 MSC 0 0  8
+## .debug_str is uncompressed becuase sizeof(Elf64_Chdr)+len(compressed) >= 
len(uncompressed).
+# SEC: .debug_strPROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 01 MS  0 0  1
 # SEC: .debug_frame  PROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 00   C 0 0  8
 
 # CHECK:  Contents of section .debug_line
@@ -23,6 +24,12 @@
 # RUN: llvm-objcopy --decompress-debug-sections %t %t.decom
 # RUN: cmp %t.uncom %t.decom
 
+## .debug_str is compressed becuase sizeof(Elf32_Chdr)+len(compressed) < 
len(uncompressed).
+# RUN: llvm-mc -filetype=obj -triple=i386 --defsym I386=1 
-compress-debug-sections=zstd --defsym LONG=1 %s -o %t1
+# RUN: llvm-readelf -S %t1 | FileCheck %s --check-prefix=SEC1
+
+# SEC1: .debug_strPROGBITS [[#%x,]] [[#%x,]] [[#%x,]] 01 MSC 0 0  4
+
 ## Don't compress a section not named .debug_*.
.section .nonalloc,"",@progbits
 .rept 50



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


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

2023-11-17 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 558120.
koops added a comment.

Moving the declaration and definition of checkFailClauseParameter to 
include/clang/Basic/OpenMPKinds.h & lib/Basic/OpenMPKinds.cpp respectively.
2 other minor changes suggested by Alexey.


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

https://reviews.llvm.org/D123235

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

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

[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-17 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/72627

None

>From 87563994d96519bef69cb14c284a9a1273ab343c Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 17 Nov 2023 17:22:10 +0800
Subject: [PATCH] [clang][analyzer] Support `fgetc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 70 -
 .../Analysis/Inputs/system-header-simulator.h |  1 +
 clang/test/Analysis/stream-error.c| 75 ++-
 clang/test/Analysis/stream.c  |  6 ++
 4 files changed, 131 insertions(+), 21 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 1d53e59ca067c27..3acf23f090cb397 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -250,9 +250,12 @@ class StreamChecker : public Checker PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
+  SVB.makeZeroVal(C.getASTContext().IntTy),
+  SVB.getConditionType())
+.getAs();
+if (!Cond)
+  return;
+StateNotFailed = StateNotFailed->assume(*Cond, true);
+if (!StateNotFailed)
+  return;
+C.addTransition(StateNotFailed);
+  }
 
   // Add transition for the failed state.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
   // If a (non-EOF) error occurs, the resulting value of the file position
   // indicator for the stream is indeterminate.
-  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
-  StreamState NewSS = StreamState::getOpened(
-  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StreamErrorState NewES;
+  if (IsRead)
+NewES =
+OldSS->ErrorState == ErrorFEof ? ErrorFEof : ErrorFEof | ErrorFError;
+  else
+NewES = ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
   StateFailed = StateFailed->set(StreamSym, NewSS);
-  C.addTransition(StateFailed);
+  if (IsRead && OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
 }
 
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 8924103f5046ea2..fc57e8bdc3d30c3 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -48,6 +48,7 @@ FILE *freopen(const char *restrict pathname, const char 
*restrict mode, FILE *re
 int fclose(FILE *fp);
 size_t fread(void *restrict, size_t, size_t, FILE *restrict);
 size_t fwrite(const void *restrict, size_t, size_t, FILE *restrict);
+int fgetc(FILE *stream);
 int fputc(int ch, FILE *stream);
 int fseek(FILE *__stream, long int __off, int __whence);
 long int ftell(FILE *__stream);
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 5ebdc32bb1b92ff..521bdb15f706bc3 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,30 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fgetc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fgetc(F);
+  if (Ret >= 0) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+  } else {
+clang_analyzer_eval(Ret == EOF);  // expected-warning {{TRUE}}
+if (feof(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fgetc(F);   // expected-warning {{Read function 
called when stream is in EOF state}}
+  clang_analyzer_eval(feof(F));   // expected-warning {{TRUE}}
+  clang_analyze

[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-static-analyzer-1

Author: Ben Shi (benshi001)


Changes



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


4 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+52-18) 
- (modified) clang/test/Analysis/Inputs/system-header-simulator.h (+1) 
- (modified) clang/test/Analysis/stream-error.c (+72-3) 
- (modified) clang/test/Analysis/stream.c (+6) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 1d53e59ca067c27..3acf23f090cb397 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -250,9 +250,12 @@ class StreamChecker : public Checker PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
+  SVB.makeZeroVal(C.getASTContext().IntTy),
+  SVB.getConditionType())
+.getAs();
+if (!Cond)
+  return;
+StateNotFailed = StateNotFailed->assume(*Cond, true);
+if (!StateNotFailed)
+  return;
+C.addTransition(StateNotFailed);
+  }
 
   // Add transition for the failed state.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
   // If a (non-EOF) error occurs, the resulting value of the file position
   // indicator for the stream is indeterminate.
-  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
-  StreamState NewSS = StreamState::getOpened(
-  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StreamErrorState NewES;
+  if (IsRead)
+NewES =
+OldSS->ErrorState == ErrorFEof ? ErrorFEof : ErrorFEof | ErrorFError;
+  else
+NewES = ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
   StateFailed = StateFailed->set(StreamSym, NewSS);
-  C.addTransition(StateFailed);
+  if (IsRead && OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
 }
 
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 8924103f5046ea2..fc57e8bdc3d30c3 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -48,6 +48,7 @@ FILE *freopen(const char *restrict pathname, const char 
*restrict mode, FILE *re
 int fclose(FILE *fp);
 size_t fread(void *restrict, size_t, size_t, FILE *restrict);
 size_t fwrite(const void *restrict, size_t, size_t, FILE *restrict);
+int fgetc(FILE *stream);
 int fputc(int ch, FILE *stream);
 int fseek(FILE *__stream, long int __off, int __whence);
 long int ftell(FILE *__stream);
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 5ebdc32bb1b92ff..521bdb15f706bc3 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,30 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fgetc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fgetc(F);
+  if (Ret >= 0) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+  } else {
+clang_analyzer_eval(Ret == EOF);  // expected-warning {{TRUE}}
+if (feof(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fgetc(F);   // expected-warning {{Read function 
called when stream is in EOF state}}
+  clang_analyzer_eval(feof(F));   // expected-warning {{TRUE}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
+}
+if (ferror(F)) {
+  clang_analyzer_warnI

[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-17 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/72627

>From d3ce61fecbe922f09ad1228a3305f484e8e1dcfc Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 17 Nov 2023 17:22:10 +0800
Subject: [PATCH] [clang][analyzer] Support `fgetc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 70 +-
 .../Analysis/Inputs/system-header-simulator.h |  1 +
 clang/test/Analysis/stream-error.c| 71 ++-
 clang/test/Analysis/stream.c  |  6 ++
 4 files changed, 129 insertions(+), 19 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 1d53e59ca067c27..3acf23f090cb397 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -250,9 +250,12 @@ class StreamChecker : public Checker PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
+  SVB.makeZeroVal(C.getASTContext().IntTy),
+  SVB.getConditionType())
+.getAs();
+if (!Cond)
+  return;
+StateNotFailed = StateNotFailed->assume(*Cond, true);
+if (!StateNotFailed)
+  return;
+C.addTransition(StateNotFailed);
+  }
 
   // Add transition for the failed state.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
   // If a (non-EOF) error occurs, the resulting value of the file position
   // indicator for the stream is indeterminate.
-  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
-  StreamState NewSS = StreamState::getOpened(
-  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StreamErrorState NewES;
+  if (IsRead)
+NewES =
+OldSS->ErrorState == ErrorFEof ? ErrorFEof : ErrorFEof | ErrorFError;
+  else
+NewES = ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
   StateFailed = StateFailed->set(StreamSym, NewSS);
-  C.addTransition(StateFailed);
+  if (IsRead && OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
 }
 
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 8924103f5046ea2..fc57e8bdc3d30c3 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -48,6 +48,7 @@ FILE *freopen(const char *restrict pathname, const char 
*restrict mode, FILE *re
 int fclose(FILE *fp);
 size_t fread(void *restrict, size_t, size_t, FILE *restrict);
 size_t fwrite(const void *restrict, size_t, size_t, FILE *restrict);
+int fgetc(FILE *stream);
 int fputc(int ch, FILE *stream);
 int fseek(FILE *__stream, long int __off, int __whence);
 long int ftell(FILE *__stream);
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 5ebdc32bb1b92ff..c86e2bb71172692 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,30 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fgetc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fgetc(F);
+  if (Ret >= 0) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+  } else {
+clang_analyzer_eval(Ret == EOF);  // expected-warning {{TRUE}}
+if (feof(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fgetc(F);   // expected-warning {{Read function 
called when stream is in EOF state}}
+  clang_analyzer_eval(feof(F));   // expected-warning {{TRUE}}
+  clang_analyzer_eva

[clang-tools-extra] [clang-tidy][NFC][DOC] Add missing HICPP rule id's (PR #72553)

2023-11-17 Thread Björn Svensson via cfe-commits

https://github.com/bjosv updated https://github.com/llvm/llvm-project/pull/72553

From 2644f2a71fb144190f67dfd515746f9d185496c6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Svensson?= 
Date: Thu, 16 Nov 2023 18:36:34 +0100
Subject: [PATCH 1/2] [clang-tidy][NFC][DOC] Add missing HICPP rule id's

Add HICPP rule identities to the documentation for `hicpp-avoid-c-arrays`
and `hicpp-no-assembler`.
Includes an update of `hicpp-avoid-goto` to look like other aliased checks.

References:
* avoid-c-arrays
  Commit: 2634bd599567842385e11d1fd70f5486c166f935
---
 .../docs/clang-tidy/checks/hicpp/avoid-c-arrays.rst|  1 +
 .../docs/clang-tidy/checks/hicpp/avoid-goto.rst|  9 +++--
 .../docs/clang-tidy/checks/hicpp/no-assembler.rst  | 10 +-
 3 files changed, 9 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-c-arrays.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-c-arrays.rst
index 5d125a89e7f4324..789235980ad7b78 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-c-arrays.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-c-arrays.rst
@@ -8,3 +8,4 @@ hicpp-avoid-c-arrays
 The hicpp-avoid-c-arrays check is an alias, please see
 :doc:`modernize-avoid-c-arrays <../modernize/avoid-c-arrays>`
 for more information.
+It partly enforces the `rule 4.1.1 
`_.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
index ffef01ca5d4eb17..91ecaf0594d1f44 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
@@ -5,10 +5,7 @@
 hicpp-avoid-goto
 
 
-The `hicpp-avoid-goto` check is an alias to
+The `hicpp-avoid-goto` check is an alias, please see
 :doc:`cppcoreguidelines-avoid-goto <../cppcoreguidelines/avoid-goto>`.
-Rule `6.3.1 High Integrity C++ 
`_
-requires that ``goto`` only skips parts of a block and is not used for other
-reasons.
-
-Both coding guidelines implement the same exception to the usage of ``goto``.
+for more information.
+It enforces the `rule 6.3.1 
`_.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/hicpp/no-assembler.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/no-assembler.rst
index 381fb365e800ea3..cfc6e9b6ec3477a 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/hicpp/no-assembler.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/no-assembler.rst
@@ -1,10 +1,10 @@
 .. title:: clang-tidy - hicpp-no-assembler
 
 hicpp-no-assembler
-===
+==
 
-Check for assembler statements. No fix is offered.
+Checks for assembler statements. Use of inline assembly should be avoided since
+it restricts the portability of the code.
 
-Inline assembler is forbidden by the `High Integrity C++ Coding Standard
-`_
-as it restricts the portability of code.
+This enforces `rule 7.5.1 
`_
+of the High Integrity C++ Coding Standard.

From 009b82f6263616ee96c2de20957d05e135e19b8b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Svensson?= 
Date: Fri, 17 Nov 2023 10:39:32 +0100
Subject: [PATCH 2/2] Fixup: remove overlooked period

---
 clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
index 91ecaf0594d1f44..ccc2a7b34efe540 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/avoid-goto.rst
@@ -6,6 +6,6 @@ hicpp-avoid-goto
 
 
 The `hicpp-avoid-goto` check is an alias, please see
-:doc:`cppcoreguidelines-avoid-goto <../cppcoreguidelines/avoid-goto>`.
+:doc:`cppcoreguidelines-avoid-goto <../cppcoreguidelines/avoid-goto>`
 for more information.
 It enforces the `rule 6.3.1 
`_.

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


[libcxxabi] [libcxx] [lld] [clang-tools-extra] [lldb] [compiler-rt] [mlir] [libunwind] [clang] [libc] [llvm] [flang] [lldb][test] Add the ability to extract the variable value out of the summary. (PR

2023-11-17 Thread via cfe-commits

https://github.com/santhoshe447 created 
https://github.com/llvm/llvm-project/pull/72631

When it comes to test infrastructure the test (TestDAP_variables.py: 
test_scopes_variables_setVariable_evaluate_with_descriptive_summaries) will 
fail if the variable has a summary along with value.

I just tried to add a summary to a variable before we set a value to the 
variable using below expression from “request_setVariable” function.
RunLLDBCommands(llvm::StringRef(), {std::string("type summary add 
--summary-string "{sample summary}" (const char **) argv")});

As value has nonnumeric characters where we are trying to convert into integer, 
python is throwing an error. We did not see this issue in upstream as we are 
not adding summary explicitly, by default we are getting empty summary & value 
for all children’s of argv parameter (even after auto summary).

The test is failing with below error:
ERROR: test_scopes_variables_setVariable_evaluate_with_descriptive_summaries 
(TestDAP_variables.TestDAP_variables)
Traceback (most recent call last):
File 
"/llvm/llvm-project/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py",
 line 372, in 
test_scopes_variables_setVariable_evaluate_with_descriptive_summaries
enableAutoVariableSummaries=True
File 
"/llvm/llvm-project/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py",
 line 266, in do_test_scopes_variables_setVariable_evaluate
argv = self.get_local_as_int("argv")
File 
"//llvm/llvm-project/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py",
 line 199, in get_local_as_int
return int(value, 16)
ValueError: invalid literal for int() with base 16: '0x1234 sample 
summary'
Config=x86_64-//llvm/llvm-build/bin/clang

>From 960351c9abf51f42d92604ac6297aa5b76ddfba5 Mon Sep 17 00:00:00 2001
From: Santhosh Kumar Ellendula 
Date: Fri, 17 Nov 2023 15:09:10 +0530
Subject: [PATCH] [lldb][test] Add the ability to extract the variable value
 out of the summary.

---
 .../Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py   | 3 +++
 1 file changed, 3 insertions(+)

diff --git 
a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py 
b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
index 9d79872b029a334..0cf9d4fde49488f 100644
--- a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
+++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
@@ -195,6 +195,9 @@ def collect_console(self, duration):
 
 def get_local_as_int(self, name, threadId=None):
 value = self.dap_server.get_local_variable_value(name, 
threadId=threadId)
+# 'value' may have the variable value and summary.
+# Extract the variable value since summary can have nonnumeric 
characters.
+value = value.split(" ")[0]
 if value.startswith("0x"):
 return int(value, 16)
 elif value.startswith("0"):

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


[libcxxabi] [libcxx] [lld] [clang-tools-extra] [lldb] [compiler-rt] [mlir] [libunwind] [clang] [libc] [llvm] [flang] [lldb][test] Add the ability to extract the variable value out of the summary. (PR

2023-11-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-lldb

Author: None (santhoshe447)


Changes

When it comes to test infrastructure the test (TestDAP_variables.py: 
test_scopes_variables_setVariable_evaluate_with_descriptive_summaries) will 
fail if the variable has a summary along with value.

I just tried to add a summary to a variable before we set a value to the 
variable using below expression from “request_setVariable” function.
RunLLDBCommands(llvm::StringRef(), {std::string("type summary add 
--summary-string "{sample summary}" (const char **) argv")});

As value has nonnumeric characters where we are trying to convert into integer, 
python is throwing an error. We did not see this issue in upstream as we are 
not adding summary explicitly, by default we are getting empty summary & 
value for all children’s of argv parameter (even after auto summary).

The test is failing with below error:
ERROR: test_scopes_variables_setVariable_evaluate_with_descriptive_summaries 
(TestDAP_variables.TestDAP_variables)
Traceback (most recent call last):
File 
"/llvm/llvm-project/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py",
 line 372, in 
test_scopes_variables_setVariable_evaluate_with_descriptive_summaries
enableAutoVariableSummaries=True
File 
"/llvm/llvm-project/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py",
 line 266, in do_test_scopes_variables_setVariable_evaluate
argv = self.get_local_as_int("argv")
File 
"//llvm/llvm-project/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py",
 line 199, in get_local_as_int
return int(value, 16)
ValueError: invalid literal for int() with base 16: '0x1234 sample 
summary'
Config=x86_64-//llvm/llvm-build/bin/clang

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


1 Files Affected:

- (modified) 
lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py (+3) 


``diff
diff --git 
a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py 
b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
index 9d79872b029a334..0cf9d4fde49488f 100644
--- a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
+++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py
@@ -195,6 +195,9 @@ def collect_console(self, duration):
 
 def get_local_as_int(self, name, threadId=None):
 value = self.dap_server.get_local_variable_value(name, 
threadId=threadId)
+# 'value' may have the variable value and summary.
+# Extract the variable value since summary can have nonnumeric 
characters.
+value = value.split(" ")[0]
 if value.startswith("0x"):
 return int(value, 16)
 elif value.startswith("0"):

``




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


[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Owen Pan via cfe-commits

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


[clang-tools-extra] [clang-tidy][NFC][DOC] Add missing HICPP rule id's (PR #72553)

2023-11-17 Thread Congcong Cai via cfe-commits
=?utf-8?q?Bj=C3=B6rn?= Svensson 
Message-ID:
In-Reply-To: 


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


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


[compiler-rt] [lldb] [clang-tools-extra] [llvm] [libc] [libcxx] [clang] [libcxxabi] [libunwind] [lld] [flang] [mlir] [lldb][test] Add the ability to extract the variable value out of the summary. (PR

2023-11-17 Thread via cfe-commits

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


[clang] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2023-11-17 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/72428

>From ac06843b97cb93d476f0bf8e0474fa270d80631f Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 15 Nov 2023 20:31:12 +0100
Subject: [PATCH 1/2] [clang][AST] Invalidate DecompositionDecl if it has
 invalid initializer.

Fix #67495, #72198
---
 clang/lib/Sema/SemaDecl.cpp |  9 +
 clang/test/AST/ast-dump-invalid-initialized.cpp | 15 ++-
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 3876eb501083acb..b89031425e4b5ac 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13540,6 +13540,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
   CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
   if (RecoveryExpr.get())
 VDecl->setInit(RecoveryExpr.get());
+  // In general, for error recovery purposes, the initalizer doesn't play
+  // part in the valid bit of the declaration. There are a few exceptions:
+  //  1) if the var decl has a deduced auto type, and the type cannot be
+  // deduced by an invalid initializer;
+  //  2) if the var decl is decompsition decl with a concrete type (e.g.
+  //`int [a, b] = 1;`), and the initializer is invalid;
+  // Case 1) is already handled earlier in this function.
+  if (llvm::isa(VDecl)) // Case 2)
+VDecl->setInvalidDecl();
   return;
 }
 
diff --git a/clang/test/AST/ast-dump-invalid-initialized.cpp 
b/clang/test/AST/ast-dump-invalid-initialized.cpp
index 1c374ae716a9db5..a71a02f0f60039e 100644
--- a/clang/test/AST/ast-dump-invalid-initialized.cpp
+++ b/clang/test/AST/ast-dump-invalid-initialized.cpp
@@ -24,4 +24,17 @@ void test() {
   auto b4 = A(1);
   // CHECK: `-VarDecl {{.*}} invalid b5 'auto'
   auto b5 = A{1};
-}
\ No newline at end of file
+}
+
+void pr72198() {
+  // CHECK: DecompositionDecl {{.*}} invalid 'int'
+  int [_, b] = {0, 0};
+  [b]{};
+}
+
+int get_point();
+void pr67495() {
+  // CHECK: DecompositionDecl {{.*}} invalid 'int &'
+  auto& [x, y] = get_point();
+  [x, y] {};
+}

>From 067a93ae9aea8a3032091fbbb19d5748ece22361 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 17 Nov 2023 10:54:33 +0100
Subject: [PATCH 2/2] Address comments.

---
 clang/lib/Sema/SemaDecl.cpp | 6 +++---
 clang/test/AST/ast-dump-invalid-initialized.cpp | 6 --
 2 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b89031425e4b5ac..27b485119ae8615 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13544,9 +13544,9 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
   // part in the valid bit of the declaration. There are a few exceptions:
   //  1) if the var decl has a deduced auto type, and the type cannot be
   // deduced by an invalid initializer;
-  //  2) if the var decl is decompsition decl with a concrete type (e.g.
-  //`int [a, b] = 1;`), and the initializer is invalid;
-  // Case 1) is already handled earlier in this function.
+  //  2) if the var decl is decompsition decl with a non-deduced type, and
+  // the initialization fails (e.g. `int [a] = {1, 2};`);
+  // Case 1) was already handled elsewhere.
   if (llvm::isa(VDecl)) // Case 2)
 VDecl->setInvalidDecl();
   return;
diff --git a/clang/test/AST/ast-dump-invalid-initialized.cpp 
b/clang/test/AST/ast-dump-invalid-initialized.cpp
index a71a02f0f60039e..7fcbc41a7be4001 100644
--- a/clang/test/AST/ast-dump-invalid-initialized.cpp
+++ b/clang/test/AST/ast-dump-invalid-initialized.cpp
@@ -26,15 +26,17 @@ void test() {
   auto b5 = A{1};
 }
 
-void pr72198() {
+void GH72198() {
   // CHECK: DecompositionDecl {{.*}} invalid 'int'
   int [_, b] = {0, 0};
   [b]{};
 }
 
+namespace GH67495 {
 int get_point();
-void pr67495() {
+void f() {
   // CHECK: DecompositionDecl {{.*}} invalid 'int &'
   auto& [x, y] = get_point();
   [x, y] {};
 }
+}

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


[clang] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2023-11-17 Thread Haojian Wu via cfe-commits


@@ -13540,6 +13540,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
   CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
   if (RecoveryExpr.get())
 VDecl->setInit(RecoveryExpr.get());
+  // In general, for error recovery purposes, the initalizer doesn't play
+  // part in the valid bit of the declaration. There are a few exceptions:
+  //  1) if the var decl has a deduced auto type, and the type cannot be
+  // deduced by an invalid initializer;
+  //  2) if the var decl is decompsition decl with a concrete type (e.g.
+  //`int [a, b] = 1;`), and the initializer is invalid;
+  // Case 1) is already handled earlier in this function.
+  if (llvm::isa(VDecl)) // Case 2)
+VDecl->setInvalidDecl();

hokein wrote:

I think this comment is helpful (especially the context is not obvious here). 
I'd like to keep it.

The code handling the case `1)` is 
https://github.com/llvm/llvm-project/blob/1c05fe350064aa3a1784bb09829a07d501842d97/clang/lib/Sema/SemaDecl.cpp#L13363C3-L13384,
 and it is easier to understand the purpose by reading the code. I'd avoid 
having two similar comments in the codebase.


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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2023-11-17 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/71709

>From 2823d38544d18213b5bf48c67e4eedd52acce850 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 8 Nov 2023 20:30:37 +0300
Subject: [PATCH 1/3] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID`

This patch refactors how values are stored inside 
`IdentifierInfo::ObjcOrBuiltinID` bit-field, and annotates it with 
`preferred_type`. In order to make the value easier to interpret by debuggers, 
a new `ObjCKeywordOrInterestingOrBuiltin` is added. Previous "layout" of this 
fields couldn't be represented with this new enum, because it skipped over some 
arbitrary enumerators, so a new "layout" was invented based on 
`ObjCKeywordOrInterestingOrBuiltin` enum. I believe the new layout is simpler 
than the new one.
---
 clang/include/clang/Basic/IdentifierTable.h | 117 
 1 file changed, 73 insertions(+), 44 deletions(-)

diff --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index 0898e7d39dd7dee..fa76228da2b143a 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TokenKinds.h"
@@ -86,19 +87,26 @@ enum { IdentifierInfoAlignment = 8 };
 static constexpr int ObjCOrBuiltinIDBits = 16;
 
 /// The "layout" of ObjCOrBuiltinID is:
-///  - The first value (0) represents "not a special identifier".
-///  - The next (NUM_OBJC_KEYWORDS - 1) values represent ObjCKeywordKinds (not
-///including objc_not_keyword).
-///  - The next (NUM_INTERESTING_IDENTIFIERS - 1) values represent
-///InterestingIdentifierKinds (not including not_interesting).
-///  - The rest of the values represent builtin IDs (not including NotBuiltin).
-static constexpr int FirstObjCKeywordID = 1;
-static constexpr int LastObjCKeywordID =
-FirstObjCKeywordID + tok::NUM_OBJC_KEYWORDS - 2;
-static constexpr int FirstInterestingIdentifierID = LastObjCKeywordID + 1;
-static constexpr int LastInterestingIdentifierID =
-FirstInterestingIdentifierID + tok::NUM_INTERESTING_IDENTIFIERS - 2;
-static constexpr int FirstBuiltinID = LastInterestingIdentifierID + 1;
+///  - ObjCKeywordKind enumerators
+///  - InterestingIdentifierKind enumerators
+///  - Builtin::ID enumerators
+///  - NonSpecialIdentifier
+enum class ObjCKeywordOrInterestingOrBuiltin {
+#define OBJC_AT_KEYWORD(X) objc_##X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS,
+
+#define INTERESTING_IDENTIFIER(X) X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS_AND_INTERESTING_IDENTIFIERS,
+
+  NotBuiltin,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/Builtins.def"
+  FirstTSBuiltin,
+
+  NonSpecialIdentifier = 65534
+};
 
 /// One of these records is kept for each identifier that
 /// is lexed.  This contains information about whether the token was 
\#define'd,
@@ -113,9 +121,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   LLVM_PREFERRED_TYPE(tok::TokenKind)
   unsigned TokenID : 9;
 
-  // ObjC keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
-  // First NUM_OBJC_KEYWORDS values are for Objective-C,
-  // the remaining values are for builtins.
+  LLVM_PREFERRED_TYPE(ObjCKeywordOrInterestingOrBuiltin)
   unsigned ObjCOrBuiltinID : ObjCOrBuiltinIDBits;
 
   // True if there is a #define for this.
@@ -198,13 +204,16 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   llvm::StringMapEntry *Entry = nullptr;
 
   IdentifierInfo()
-  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),
-HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
-IsPoisoned(false), IsCPPOperatorKeyword(false),
-NeedsHandleIdentifier(false), IsFromAST(false), 
ChangedAfterLoad(false),
-FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
-IsModulesImport(false), IsMangledOpenMPVariantName(false),
-IsDeprecatedMacro(false), IsRestrictExpansion(false), IsFinal(false) {}
+  : TokenID(tok::identifier),
+ObjCOrBuiltinID(llvm::to_underlying(
+ObjCKeywordOrInterestingOrBuiltin::NonSpecialIdentifier)),
+HasMacro(false), HadMacro(false), IsExtension(false),
+IsFutureCompatKeyword(false), IsPoisoned(false),
+IsCPPOperatorKeyword(false), NeedsHandleIdentifier(false),
+IsFromAST(false), ChangedAfterLoad(false), FEChangedAfterLoad(false),
+RevertedTokenID(false), OutOfDate(false), IsModulesImport(false),
+IsMangledOpenMPVariantName(false), IsDeprecatedMacro(false),
+IsRestrictExpansion(false), IsFinal(false) {}
 
 public:
   IdentifierInfo(const IdentifierInfo &) = delete;
@@ -332,42 +341,62 @@ class alignas(IdentifierInfoAlignment

[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Owen Pan via cfe-commits

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

>From efdf321e9447e8b3f1c27ccdf6da842107deb6dd Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 16 Nov 2023 06:36:41 -0800
Subject: [PATCH 1/3] [clang-format] Fix crashes in AlignArrayOfStructures

Fixed #55493.
Fixed #68431.
---
 clang/lib/Format/WhitespaceManager.cpp |  4 +++-
 clang/lib/Format/WhitespaceManager.h   |  2 +-
 clang/unittests/Format/FormatTest.cpp  | 18 ++
 3 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 32d8b97cc8dadb1..3bc6915b8df0a70 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1316,6 +1316,8 @@ void 
WhitespaceManager::alignArrayInitializersRightJustified(
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next;
  Next = Next->NextColumnElement) {
+  if (RowCount >= CellDescs.CellCounts.size())
+break;
   auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
   auto *End = Start + Offset;
   ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
@@ -1379,7 +1381,7 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next;
  Next = Next->NextColumnElement) {
-  if (RowCount > CellDescs.CellCounts.size())
+  if (RowCount >= CellDescs.CellCounts.size())
 break;
   auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
   auto *End = Start + Offset;
diff --git a/clang/lib/Format/WhitespaceManager.h 
b/clang/lib/Format/WhitespaceManager.h
index df7e9add1cd446f..69398fe411502f1 100644
--- a/clang/lib/Format/WhitespaceManager.h
+++ b/clang/lib/Format/WhitespaceManager.h
@@ -317,7 +317,7 @@ class WhitespaceManager {
 auto Offset = std::distance(CellStart, CellStop);
 for (const auto *Next = CellStop->NextColumnElement; Next;
  Next = Next->NextColumnElement) {
-  if (RowCount > MaxRowCount)
+  if (RowCount >= MaxRowCount)
 break;
   auto Start = (CellStart + RowCount * CellCount);
   auto End = Start + Offset;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a12a20359c2fad2..cd4c93e8427723f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21140,6 +21140,24 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   "that really, in any just world, ought to be split over multiple "
   "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
   Style);
+
+  Style.ColumnLimit = 25;
+  verifyNoCrash("Type object[X][Y] = {\n"
+"{{val}, {val}, {val}},\n"
+"{{val}, {val}, // some comment\n"
+"   {val}}\n"
+"};",
+Style);
+
+  Style.ColumnLimit = 120;
+  verifyNoCrash(
+  "T v[] {\n"
+  "{ A::aaa, "
+  "A::, 1, 0.0f, "
+  "\""
+  "\" },\n"
+  "};",
+  Style);
 }
 
 TEST_F(FormatTest, UnderstandsPragmas) {

>From 4a73cc6c52be6824d34f4ba5608a008a3dfdedf0 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 16 Nov 2023 18:46:23 -0800
Subject: [PATCH 2/3] Added tests from #54815 and #55269.

---
 clang/unittests/Format/FormatTest.cpp | 15 +++
 1 file changed, 15 insertions(+)

diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index cd4c93e8427723f..a579746fd4b68e8 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -20709,6 +20709,12 @@ TEST_F(FormatTest, CatchExceptionReferenceBinding) {
 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
   auto Style = getLLVMStyle();
   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
+
+  verifyNoCrash("f({\n"
+"table({}, table({{\"\", false}}, {}))\n"
+"});",
+Style);
+
   Style.AlignConsecutiveAssignments.Enabled = true;
   Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("struct test demo[] = {\n"
@@ -21142,6 +21148,15 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   Style);
 
   Style.ColumnLimit = 25;
+  verifyNoCrash("Type foo{\n"
+"{\n"
+"1,  // A\n"
+"2,  // B\n"
+"3,  // C\n"
+"},\n"
+"\"hello\",\n"
+"};",
+Style);
   ve

[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2023-11-17 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

Aaron suggested to me offline that `IsInterestingIdentifier` that I recently 
changed could be implemented in a simpler way retaining the intent. That's what 
the latest update about.

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


[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Owen Pan via cfe-commits

owenca wrote:

We probably should backport it to 17.0.6. What do you all think? @tru 

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


[clang] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2023-11-17 Thread Haojian Wu via cfe-commits

hokein wrote:

> What differentiates the DecompositionDecl such that we need to mark the decl 
> invalid when there's an error in the RHS, while for other decls we don't? It 
> seems inconsistent.

DecompositionDecl (aka structure binding) is special here, a legal 
DecompositionDecl must be declared with a deduced `auto` type, so the its 
initializer should play part of the decl's invalid bit. For the error case 
where a DecompositionDecl with a non-deduced type, clang still builds the Decl 
AST node (with invalid bit) for better recovery. There are some oversight 
cases. This patch is fixing those.

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-11-17 Thread Balazs Benics via cfe-commits


@@ -492,11 +492,13 @@ void check_required_cast() {
 
 void check_cast_behavior(OSObject *obj) {
   OSArray *arr1 = OSDynamicCast(OSArray, obj);
-  clang_analyzer_eval(arr1 == obj); // expected-warning{{TRUE}}
-// expected-note@-1{{TRUE}}
-// expected-note@-2{{Assuming 'arr1' is 
not equal to 'obj'}}
-// expected-warning@-3{{FALSE}}
-// expected-note@-4   {{FALSE}}
+  clang_analyzer_eval(arr1 == obj); // #check_cast_behavior_1
+  // expected-warning@#check_cast_behavior_1 {{TRUE}}
+  // expected-note@#check_cast_behavior_1{{TRUE}}
+  // expected-note@#check_cast_behavior_1{{Assuming 'arr1' is equal to 'obj'}}

steakhal wrote:

Ping @haoNoQ

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


[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #71540)

2023-11-17 Thread Paulo Matos via cfe-commits

https://github.com/pmatos updated 
https://github.com/llvm/llvm-project/pull/71540

>From 31adeded0d1767e1ce43fbfcba5fe72c4e34121d Mon Sep 17 00:00:00 2001
From: Paulo Matos 
Date: Tue, 7 Nov 2023 08:28:36 +0100
Subject: [PATCH 1/4] [WebAssembly] Refactor Wasm Reference Types as
 TargetExtType

Originally reference types were designed as pointers to different
address spaces.

More recently TargetExtType were added to LLVM IR making it easier
to represent reference types. This refactoring gets rid of wasm
reftypes as pointers and just uses target extension types to
represent them.
---
 .../test/CodeGen/WebAssembly/builtins-table.c | 16 ++--
 .../test/CodeGen/WebAssembly/wasm-externref.c |  8 +-
 clang/test/CodeGen/builtins-wasm.c|  2 +-
 llvm/include/llvm/IR/Intrinsics.h |  1 +
 llvm/include/llvm/IR/Type.h   |  2 +
 llvm/lib/CodeGen/ValueTypes.cpp   |  2 +
 llvm/lib/IR/Function.cpp  |  8 +-
 llvm/lib/IR/Type.cpp  |  7 +-
 llvm/lib/Target/WebAssembly/CMakeLists.txt|  1 -
 .../WebAssembly/Utils/WasmAddressSpaces.h |  2 -
 .../Utils/WebAssemblyTypeUtilities.h  |  5 +-
 llvm/lib/Target/WebAssembly/WebAssembly.h |  2 -
 .../WebAssembly/WebAssemblyISelLowering.cpp   |  4 -
 .../WebAssemblyLowerRefTypesIntPtrConv.cpp| 86 ---
 .../WebAssembly/WebAssemblyTargetMachine.cpp  |  2 -
 .../WebAssembly/externref-globalget.ll|  2 +-
 .../WebAssembly/externref-globalset.ll|  2 +-
 .../CodeGen/WebAssembly/externref-inttoptr.ll | 12 +--
 .../CodeGen/WebAssembly/externref-ptrtoint.ll | 11 +--
 .../CodeGen/WebAssembly/externref-tableget.ll |  2 +-
 .../CodeGen/WebAssembly/externref-tableset.ll |  2 +-
 .../WebAssembly/externref-unsized-load.ll |  4 +-
 .../WebAssembly/externref-unsized-store.ll|  4 +-
 llvm/test/CodeGen/WebAssembly/ref-null.ll |  2 +-
 llvm/test/CodeGen/WebAssembly/table-copy.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-fill.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-grow.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-size.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-types.ll  |  2 +-
 .../llvm/lib/Target/WebAssembly/BUILD.gn  |  1 -
 30 files changed, 51 insertions(+), 149 deletions(-)
 delete mode 100644 
llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

diff --git a/clang/test/CodeGen/WebAssembly/builtins-table.c 
b/clang/test/CodeGen/WebAssembly/builtins-table.c
index 74bb2442fe552fc..eeed335855e4089 100644
--- a/clang/test/CodeGen/WebAssembly/builtins-table.c
+++ b/clang/test/CodeGen/WebAssembly/builtins-table.c
@@ -7,17 +7,17 @@ static __externref_t table[0];
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_get
 // CHECK-SAME: (i32 noundef [[INDEX:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call ptr addrspace(10) 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
-// CHECK-NEXT:ret ptr addrspace(10) [[TMP0]]
+// CHECK-NEXT:[[TMP0:%.*]] = call target("wasm.externref") 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
+// CHECK-NEXT:ret target("wasm.externref") [[TMP0]]
 //
 __externref_t test_builtin_wasm_table_get(int index) {
   return __builtin_wasm_table_get(table, index);
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_set
-// CHECK-SAME: (i32 noundef [[INDEX:%.*]], ptr addrspace(10) [[REF:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (i32 noundef [[INDEX:%.*]], target("wasm.externref") 
[[REF:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], ptr addrspace(10) [[REF]])
+// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], target("wasm.externref") [[REF]])
 // CHECK-NEXT:ret void
 //
 void test_builtin_wasm_table_set(int index, __externref_t ref) {
@@ -35,9 +35,9 @@ int test_builtin_wasm_table_size() {
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_grow
-// CHECK-SAME: (ptr addrspace(10) [[REF:%.*]], i32 noundef [[NELEM:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (target("wasm.externref") [[REF:%.*]], i32 noundef 
[[NELEM:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call i32 @llvm.wasm.table.grow.externref(ptr 
addrspace(1) @table, ptr addrspace(10) [[REF]], i32 [[NELEM]])
+// CHECK-NEXT:[[TMP0:%.*]] = call i32 @llvm.wasm.table.grow.externref(ptr 
addrspace(1) @table, target("wasm.externref") [[REF]], i32 [[NELEM]])
 // CHECK-NEXT:ret i32 [[TMP0]]
 //
 int test_builtin_wasm_table_grow(__externref_t ref, int nelem) {
@@ -45,9 +45,9 @@ int test_builtin_wasm_table_grow(__externref_t ref, int 
nelem) {
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_fill
-// CHECK-SAME: (i32 noundef [[INDEX:%.*]], ptr addrspace(10) [[REF:%.*]], i32 
noundef [[NELEM:%.*]]) #[[ATTR0]] {
+// CHECK-SAME: (i3

[clang-tools-extra] 7aaa86b - [include-cleaner] Add regression tests for outliving File&Source Manager

2023-11-17 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-11-17T11:32:51+01:00
New Revision: 7aaa86b28ddc3deded6e357b27f2bbebb97a3864

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

LOG: [include-cleaner] Add regression tests for outliving File&Source Manager

Added: 


Modified: 
clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
index dfefa66887b0f24..0f2ded5f1834531 100644
--- a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -558,5 +558,35 @@ TEST_F(PragmaIncludeTest, ExportInUnnamedBuffer) {
   PI.getExporters(llvm::cantFail(FM->getFileRef("foo.h")), *FM),
   testing::ElementsAre(llvm::cantFail(FM->getFileRef("exporter.h";
 }
+
+TEST_F(PragmaIncludeTest, OutlivesFMAndSM) {
+  Inputs.Code = R"cpp(
+#include "public.h"
+  )cpp";
+  Inputs.ExtraFiles["public.h"] = R"cpp(
+#include "private.h"
+#include "private2.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "public.h"
+  )cpp";
+  Inputs.ExtraFiles["private2.h"] = R"cpp(
+// IWYU pragma: private
+  )cpp";
+  build(); // Fills up PI, file/source manager used is destroyed afterwards.
+  Inputs.MakeAction = nullptr; // Don't populate PI anymore.
+
+  // Now this build gives us a new File&Source Manager.
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+  auto PrivateFE = FM.getFile("private.h");
+  assert(PrivateFE);
+  EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public.h\"");
+
+  auto Private2FE = FM.getFile("private2.h");
+  assert(Private2FE);
+  EXPECT_THAT(PI.getExporters(Private2FE.get(), FM),
+  testing::ElementsAre(llvm::cantFail(FM.getFileRef("public.h";
+}
 } // namespace
 } // namespace clang::include_cleaner



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


[clang-tools-extra] [clangd] Add way to remove file from CDB via LSP (PR #72635)

2023-11-17 Thread via cfe-commits

https://github.com/sr-tream created 
https://github.com/llvm/llvm-project/pull/72635

Currently, impossible to remove irrelevant files from CDB via LSP notification 
`workspace/didChangeConfiguration`. This PR change clangd behavior to remove 
file from CDB, when LSP pass empty parameters for them.

>From 587dbb0a2329a0fe06894271405acae5f03bbd7d Mon Sep 17 00:00:00 2001
From: SR_team 
Date: Fri, 17 Nov 2023 11:58:13 +0200
Subject: [PATCH] Add way to remove file from CDB via LSP

---
 clang-tools-extra/clangd/ClangdLSPServer.cpp | 5 -
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index a87da252b7a7e9b..0a228df4f0b5f4c 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1385,7 +1385,10 @@ void ClangdLSPServer::applyConfiguration(
 std::move(Entry.second.compilationCommand),
 /*Output=*/"");
 if (Old != New) {
-  CDB->setCompileCommand(File, std::move(New));
+  if (New.CommandLine.empty() && New.Directory.empty())
+CDB->setCompileCommand(File, std::nullopt);
+  else
+CDB->setCompileCommand(File, std::move(New));
   ModifiedFiles.insert(File);
 }
   }

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


[clang-tools-extra] [clangd] Add way to remove file from CDB via LSP (PR #72635)

2023-11-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: SR_team (sr-tream)


Changes

Currently, impossible to remove irrelevant files from CDB via LSP notification 
`workspace/didChangeConfiguration`. This PR change clangd behavior to remove 
file from CDB, when LSP pass empty parameters for them.

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


1 Files Affected:

- (modified) clang-tools-extra/clangd/ClangdLSPServer.cpp (+4-1) 


``diff
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index a87da252b7a7e9b..0a228df4f0b5f4c 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1385,7 +1385,10 @@ void ClangdLSPServer::applyConfiguration(
 std::move(Entry.second.compilationCommand),
 /*Output=*/"");
 if (Old != New) {
-  CDB->setCompileCommand(File, std::move(New));
+  if (New.CommandLine.empty() && New.Directory.empty())
+CDB->setCompileCommand(File, std::nullopt);
+  else
+CDB->setCompileCommand(File, std::move(New));
   ModifiedFiles.insert(File);
 }
   }

``




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


[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Tobias Hieta via cfe-commits

tru wrote:

> We probably should backport it to 17.0.6. What do you all think? @tru

Yep - seems like a good and small fix to have in 17.x

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


[clang] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2023-11-17 Thread Henrik G. Olsson via cfe-commits

hnrklssn wrote:

> > What differentiates the DecompositionDecl such that we need to mark the 
> > decl invalid when there's an error in the RHS, while for other decls we 
> > don't? It seems inconsistent.
> 
> 
> 
> DecompositionDecl (aka structure binding) is special here, a legal 
> DecompositionDecl must be declared with a deduced `auto` type, so the its 
> initializer should play part of the decl's invalid bit. For the error case 
> where a DecompositionDecl with a non-deduced type, clang still builds the 
> Decl AST node (with invalid bit) for better recovery. There are some 
> oversight cases. This patch is fixing those.

Ah that makes sense then. I didn't realise it had to be `auto`.

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


[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Tobias Hieta via cfe-commits

tru wrote:

@owenca I picked da1b1fba5cfd41521a840202d8cf4c3796c5e10b on top of the 17.x 
branch and my test case was not fixed, it still crashes in the same way as 
described in #72628 

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


[clang] [clang][Interp] Handle std::move etc. builtins (PR #70772)

2023-11-17 Thread Henrik G. Olsson via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


hnrklssn wrote:

LGTM, but someone else should approve also.

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


[libunwind] [clang-tools-extra] [clang] [llvm] [lldb] [libcxx] [compiler-rt] [flang] [lld] [AMDGPU] - Add constant folding for s_quadmask (PR #72381)

2023-11-17 Thread Jessica Del via cfe-commits

https://github.com/OutOfCache updated 
https://github.com/llvm/llvm-project/pull/72381

>From 00d0f99207242befc8022031ccd8faf573cbf014 Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Tue, 14 Nov 2023 22:17:26 +0100
Subject: [PATCH 1/4] [AMDGPU] - Add constant folding for s_quadmask

If the input is a constant we can constant fold the `s_quadmask`
intrinsic.
---
 llvm/lib/Analysis/ConstantFolding.cpp| 14 ++
 llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll | 12 
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 966a65ac26b8017..40b5938fcda0c2a 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -1533,6 +1533,7 @@ bool llvm::canConstantFoldCallTo(const CallBase *Call, 
const Function *F) {
   case Intrinsic::amdgcn_perm:
   case Intrinsic::amdgcn_wave_reduce_umin:
   case Intrinsic::amdgcn_wave_reduce_umax:
+  case Intrinsic::amdgcn_s_quadmask:
   case Intrinsic::arm_mve_vctp8:
   case Intrinsic::arm_mve_vctp16:
   case Intrinsic::arm_mve_vctp32:
@@ -2422,6 +2423,19 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
 
   return ConstantFP::get(Ty->getContext(), Val);
 }
+
+case Intrinsic::amdgcn_s_quadmask: {
+  uint64_t Val = Op->getZExtValue();
+  uint64_t QuadMask = 0;
+  for (unsigned i = 0; i < Op->getBitWidth() / 4; ++i, Val >>= 4) {
+if (!(Val & 0xF))
+  continue;
+
+QuadMask |= (1 << i);
+  }
+  return ConstantInt::get(Ty, QuadMask);
+}
+
 default:
   return nullptr;
 }
diff --git a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll 
b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
index 65443a6efa789d9..0f500c0999ad9a8 100644
--- a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
+++ b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
@@ -9,11 +9,10 @@ define i32 @test_quadmask_constant_i32() {
 ; GFX11-LABEL: test_quadmask_constant_i32:
 ; GFX11:   ; %bb.0: ; %entry
 ; GFX11-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)
-; GFX11-NEXT:s_quadmask_b32 s0, 0x85fe3a92
-; GFX11-NEXT:v_mov_b32_e32 v0, s0
+; GFX11-NEXT:v_mov_b32_e32 v0, 0xcb
 ; GFX11-NEXT:s_setpc_b64 s[30:31]
 entry:
-  %qm = call i32 @llvm.amdgcn.s.quadmask.i32(i32 u0x85FE3A92)
+  %qm = call i32 @llvm.amdgcn.s.quadmask.i32(i32 u0x85003092)
   ret i32 %qm
 }
 
@@ -50,13 +49,10 @@ define i64 @test_quadmask_constant_i64() {
 ; GFX11-LABEL: test_quadmask_constant_i64:
 ; GFX11:   ; %bb.0: ; %entry
 ; GFX11-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)
-; GFX11-NEXT:s_mov_b32 s0, 0x85fe3a92
-; GFX11-NEXT:s_mov_b32 s1, 0x67de48fc
-; GFX11-NEXT:s_quadmask_b64 s[0:1], s[0:1]
-; GFX11-NEXT:v_dual_mov_b32 v0, s0 :: v_dual_mov_b32 v1, s1
+; GFX11-NEXT:v_dual_mov_b32 v0, 0xe3e6 :: v_dual_mov_b32 v1, 0
 ; GFX11-NEXT:s_setpc_b64 s[30:31]
 entry:
-  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67DE48FC85FE3A92)
+  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67D000FC85F00A90)
   ret i64 %qm
 }
 

>From 144c4dc164ec137e518cfd647c116373e7a61b8f Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Wed, 15 Nov 2023 15:59:56 +0100
Subject: [PATCH 2/4] fixup! [AMDGPU] - Add constant folding for s_quadmask

---
 llvm/lib/Analysis/ConstantFolding.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 40b5938fcda0c2a..39bbb04fbcf26cc 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -2427,11 +2427,11 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
 case Intrinsic::amdgcn_s_quadmask: {
   uint64_t Val = Op->getZExtValue();
   uint64_t QuadMask = 0;
-  for (unsigned i = 0; i < Op->getBitWidth() / 4; ++i, Val >>= 4) {
+  for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
 if (!(Val & 0xF))
   continue;
 
-QuadMask |= (1 << i);
+QuadMask |= (1 << I);
   }
   return ConstantInt::get(Ty, QuadMask);
 }

>From 65bb0b1164ff9b7491589cb88decb1d135504c1b Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Thu, 16 Nov 2023 11:22:52 +0100
Subject: [PATCH 3/4] fixup! Merge branch 'main' into quadmask-folding

---
 llvm/lib/Analysis/ConstantFolding.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 64d088ea7a46404..2771a3d574f7799 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -2425,7 +2425,6 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
   return ConstantFP::get(Ty->getContext(), Val);
 }
 
-
 case Intrinsic::amdgcn_s_quadmask: {
   uint64_t Val = Op->getZExtValue();
   uint64_t QuadMask = 0;
@@ -2436,6 +2435,7 @@ static Constant

[llvm] [clang] Fix python escapes (PR #71170)

2023-11-17 Thread Zufu Liu via cfe-commits

zufuliu wrote:

Duplicate of #72538.

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


[clang] [flang] [Flang] Add code-object-version option (PR #72638)

2023-11-17 Thread Dominik Adamski via cfe-commits

https://github.com/DominikAdamski created 
https://github.com/llvm/llvm-project/pull/72638

Information about code object version can be configured by the user for AMD GPU 
target and it needs to be placed in LLVM IR generated by Flang.

Information about code object version in MLIR generated by the parser can be 
reused by other tools. There is no need to specify extra flags if we want to 
invoke MLIR tools (like fir-opt) separately.

>From eb2710b0f736860dac62cc2ff8907fcefc64a8d6 Mon Sep 17 00:00:00 2001
From: Dominik Adamski 
Date: Fri, 17 Nov 2023 03:02:49 -0600
Subject: [PATCH] [Flang] Add code-object-version option

Information about code object version can be configured by the user
for AMD GPU target and it needs to be placed in LLVM IR generated
by Flang.

Information about code object version in MLIR generated by the
parser can be reused by other tools. There is no need to specify
extra flags if we want to invoke MLIR tools separately.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 11 ++
 clang/lib/Driver/ToolChains/Flang.h   |  7 
 flang/include/flang/Frontend/CodeGenOptions.h | 13 +++
 flang/lib/Frontend/CompilerInvocation.cpp |  9 +
 flang/lib/Frontend/FrontendActions.cpp| 38 +--
 flang/test/Driver/code-object-version.f90 |  8 
 flang/test/Driver/driver-help-hidden.f90  |  2 +
 flang/test/Driver/driver-help.f90 |  4 ++
 flang/test/Lower/AMD/code_object_version.f90  | 11 ++
 10 files changed, 101 insertions(+), 4 deletions(-)
 create mode 100644 flang/test/Driver/code-object-version.f90
 create mode 100644 flang/test/Lower/AMD/code_object_version.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 811550416110b3d..e7eb94d174e75f8 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4688,7 +4688,7 @@ defm amdgpu_ieee : BoolOption<"m", "amdgpu-ieee",
 
 def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, 
Group,
   HelpText<"Specify code object ABI version. Defaults to 4. (AMDGPU only)">,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, FlangOption, CC1Option, FC1Option]>,
   Values<"none,4,5">,
   NormalizedValuesScope<"TargetOptions">,
   NormalizedValues<["COV_None", "COV_4", "COV_5"]>,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8bdd920c3dcbb79..e60c11bfbe8e38b 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -204,6 +204,14 @@ void Flang::AddAArch64TargetArgs(const ArgList &Args,
   }
 }
 
+void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
+ArgStringList &CmdArgs) const {
+  if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
+StringRef Val = A->getValue();
+CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
+  }
+}
+
 void Flang::addTargetOptions(const ArgList &Args,
  ArgStringList &CmdArgs) const {
   const ToolChain &TC = getToolChain();
@@ -227,6 +235,9 @@ void Flang::addTargetOptions(const ArgList &Args,
 
   case llvm::Triple::r600:
   case llvm::Triple::amdgcn:
+getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
+AddAMDGPUTargetArgs(Args, CmdArgs);
+break;
   case llvm::Triple::riscv64:
   case llvm::Triple::x86_64:
 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
diff --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index 0141240b5d3ac90..8d35080e1c0c88b 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -63,6 +63,13 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   void AddAArch64TargetArgs(const llvm::opt::ArgList &Args,
 llvm::opt::ArgStringList &CmdArgs) const;
 
+  /// Add specific options for AMDGPU target.
+  ///
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void AddAMDGPUTargetArgs(const llvm::opt::ArgList &Args,
+   llvm::opt::ArgStringList &CmdArgs) const;
+
   /// Extract offload options from the driver arguments and add them to
   /// the command arguments.
   /// \param [in] C The current compilation for the driver invocation
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b86bb88610a9a4a..8d938c361a0aa23 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -85,6 +85,19 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  /// \brief Enumeration value for AMDGPU code object version, which is the
+  /// code object version times 100.

[flang] [clang] [Flang] Add code-object-version option (PR #72638)

2023-11-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-driver

@llvm/pr-subscribers-flang-driver

Author: Dominik Adamski (DominikAdamski)


Changes

Information about code object version can be configured by the user for AMD GPU 
target and it needs to be placed in LLVM IR generated by Flang.

Information about code object version in MLIR generated by the parser can be 
reused by other tools. There is no need to specify extra flags if we want to 
invoke MLIR tools (like fir-opt) separately.

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


10 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+11) 
- (modified) clang/lib/Driver/ToolChains/Flang.h (+7) 
- (modified) flang/include/flang/Frontend/CodeGenOptions.h (+13) 
- (modified) flang/lib/Frontend/CompilerInvocation.cpp (+9) 
- (modified) flang/lib/Frontend/FrontendActions.cpp (+35-3) 
- (added) flang/test/Driver/code-object-version.f90 (+8) 
- (modified) flang/test/Driver/driver-help-hidden.f90 (+2) 
- (modified) flang/test/Driver/driver-help.f90 (+4) 
- (added) flang/test/Lower/AMD/code_object_version.f90 (+11) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 811550416110b3d..e7eb94d174e75f8 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4688,7 +4688,7 @@ defm amdgpu_ieee : BoolOption<"m", "amdgpu-ieee",
 
 def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, 
Group,
   HelpText<"Specify code object ABI version. Defaults to 4. (AMDGPU only)">,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, FlangOption, CC1Option, FC1Option]>,
   Values<"none,4,5">,
   NormalizedValuesScope<"TargetOptions">,
   NormalizedValues<["COV_None", "COV_4", "COV_5"]>,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8bdd920c3dcbb79..e60c11bfbe8e38b 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -204,6 +204,14 @@ void Flang::AddAArch64TargetArgs(const ArgList &Args,
   }
 }
 
+void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
+ArgStringList &CmdArgs) const {
+  if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
+StringRef Val = A->getValue();
+CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
+  }
+}
+
 void Flang::addTargetOptions(const ArgList &Args,
  ArgStringList &CmdArgs) const {
   const ToolChain &TC = getToolChain();
@@ -227,6 +235,9 @@ void Flang::addTargetOptions(const ArgList &Args,
 
   case llvm::Triple::r600:
   case llvm::Triple::amdgcn:
+getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
+AddAMDGPUTargetArgs(Args, CmdArgs);
+break;
   case llvm::Triple::riscv64:
   case llvm::Triple::x86_64:
 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
diff --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index 0141240b5d3ac90..8d35080e1c0c88b 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -63,6 +63,13 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   void AddAArch64TargetArgs(const llvm::opt::ArgList &Args,
 llvm::opt::ArgStringList &CmdArgs) const;
 
+  /// Add specific options for AMDGPU target.
+  ///
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void AddAMDGPUTargetArgs(const llvm::opt::ArgList &Args,
+   llvm::opt::ArgStringList &CmdArgs) const;
+
   /// Extract offload options from the driver arguments and add them to
   /// the command arguments.
   /// \param [in] C The current compilation for the driver invocation
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b86bb88610a9a4a..8d938c361a0aa23 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -85,6 +85,19 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  /// \brief Enumeration value for AMDGPU code object version, which is the
+  /// code object version times 100.
+  enum class CodeObjectVersionKind {
+COV_None,
+COV_2 = 200, // Unsupported.
+COV_3 = 300, // Unsupported.
+COV_4 = 400,
+COV_5 = 500,
+  };
+
+  /// \brief Code object version for AMDGPU.
+  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_None;
+
   /// Optimization remark with an optional regular expression pattern.
   struct OptRemark {
 RemarkKind Kind = RemarkKind::RK_Missing;
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index cb4f

[flang] [clang] [Flang] Add code-object-version option (PR #72638)

2023-11-17 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 a67b85ef63c7ec29c2076294e3f7c7f923144a53 
eb2710b0f736860dac62cc2ff8907fcefc64a8d6 -- 
clang/lib/Driver/ToolChains/Flang.cpp clang/lib/Driver/ToolChains/Flang.h 
flang/include/flang/Frontend/CodeGenOptions.h 
flang/lib/Frontend/CompilerInvocation.cpp flang/lib/Frontend/FrontendActions.cpp
``





View the diff from clang-format here.


``diff
diff --git a/flang/lib/Frontend/FrontendActions.cpp 
b/flang/lib/Frontend/FrontendActions.cpp
index 6184f80eda..6888ba1cd8 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -244,8 +244,7 @@ static void setMLIRDataLayout(mlir::ModuleOp &mlirModule,
   mlirModule->setAttr(mlir::DLTIDialect::kDataLayoutAttrName, dlSpec);
 }
 
-static void addDependentLibs(mlir::ModuleOp &mlirModule,
-  CompilerInstance &ci) {
+static void addDependentLibs(mlir::ModuleOp &mlirModule, CompilerInstance &ci) 
{
   const std::vector &libs =
   ci.getInvocation().getCodeGenOpts().DependentLibs;
   if (libs.empty()) {

``




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


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

2023-11-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


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

https://reviews.llvm.org/D123235

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


[lld] [libunwind] [libcxx] [compiler-rt] [llvm] [flang] [clang-tools-extra] [lldb] [clang] [AMDGPU] - Add constant folding for s_quadmask (PR #72381)

2023-11-17 Thread Jessica Del via cfe-commits

https://github.com/OutOfCache updated 
https://github.com/llvm/llvm-project/pull/72381

>From 00d0f99207242befc8022031ccd8faf573cbf014 Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Tue, 14 Nov 2023 22:17:26 +0100
Subject: [PATCH 1/5] [AMDGPU] - Add constant folding for s_quadmask

If the input is a constant we can constant fold the `s_quadmask`
intrinsic.
---
 llvm/lib/Analysis/ConstantFolding.cpp| 14 ++
 llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll | 12 
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 966a65ac26b8017..40b5938fcda0c2a 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -1533,6 +1533,7 @@ bool llvm::canConstantFoldCallTo(const CallBase *Call, 
const Function *F) {
   case Intrinsic::amdgcn_perm:
   case Intrinsic::amdgcn_wave_reduce_umin:
   case Intrinsic::amdgcn_wave_reduce_umax:
+  case Intrinsic::amdgcn_s_quadmask:
   case Intrinsic::arm_mve_vctp8:
   case Intrinsic::arm_mve_vctp16:
   case Intrinsic::arm_mve_vctp32:
@@ -2422,6 +2423,19 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
 
   return ConstantFP::get(Ty->getContext(), Val);
 }
+
+case Intrinsic::amdgcn_s_quadmask: {
+  uint64_t Val = Op->getZExtValue();
+  uint64_t QuadMask = 0;
+  for (unsigned i = 0; i < Op->getBitWidth() / 4; ++i, Val >>= 4) {
+if (!(Val & 0xF))
+  continue;
+
+QuadMask |= (1 << i);
+  }
+  return ConstantInt::get(Ty, QuadMask);
+}
+
 default:
   return nullptr;
 }
diff --git a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll 
b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
index 65443a6efa789d9..0f500c0999ad9a8 100644
--- a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
+++ b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.quadmask.ll
@@ -9,11 +9,10 @@ define i32 @test_quadmask_constant_i32() {
 ; GFX11-LABEL: test_quadmask_constant_i32:
 ; GFX11:   ; %bb.0: ; %entry
 ; GFX11-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)
-; GFX11-NEXT:s_quadmask_b32 s0, 0x85fe3a92
-; GFX11-NEXT:v_mov_b32_e32 v0, s0
+; GFX11-NEXT:v_mov_b32_e32 v0, 0xcb
 ; GFX11-NEXT:s_setpc_b64 s[30:31]
 entry:
-  %qm = call i32 @llvm.amdgcn.s.quadmask.i32(i32 u0x85FE3A92)
+  %qm = call i32 @llvm.amdgcn.s.quadmask.i32(i32 u0x85003092)
   ret i32 %qm
 }
 
@@ -50,13 +49,10 @@ define i64 @test_quadmask_constant_i64() {
 ; GFX11-LABEL: test_quadmask_constant_i64:
 ; GFX11:   ; %bb.0: ; %entry
 ; GFX11-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)
-; GFX11-NEXT:s_mov_b32 s0, 0x85fe3a92
-; GFX11-NEXT:s_mov_b32 s1, 0x67de48fc
-; GFX11-NEXT:s_quadmask_b64 s[0:1], s[0:1]
-; GFX11-NEXT:v_dual_mov_b32 v0, s0 :: v_dual_mov_b32 v1, s1
+; GFX11-NEXT:v_dual_mov_b32 v0, 0xe3e6 :: v_dual_mov_b32 v1, 0
 ; GFX11-NEXT:s_setpc_b64 s[30:31]
 entry:
-  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67DE48FC85FE3A92)
+  %qm = call i64 @llvm.amdgcn.s.quadmask.i64(i64 u0x67D000FC85F00A90)
   ret i64 %qm
 }
 

>From 144c4dc164ec137e518cfd647c116373e7a61b8f Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Wed, 15 Nov 2023 15:59:56 +0100
Subject: [PATCH 2/5] fixup! [AMDGPU] - Add constant folding for s_quadmask

---
 llvm/lib/Analysis/ConstantFolding.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 40b5938fcda0c2a..39bbb04fbcf26cc 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -2427,11 +2427,11 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
 case Intrinsic::amdgcn_s_quadmask: {
   uint64_t Val = Op->getZExtValue();
   uint64_t QuadMask = 0;
-  for (unsigned i = 0; i < Op->getBitWidth() / 4; ++i, Val >>= 4) {
+  for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
 if (!(Val & 0xF))
   continue;
 
-QuadMask |= (1 << i);
+QuadMask |= (1 << I);
   }
   return ConstantInt::get(Ty, QuadMask);
 }

>From 65bb0b1164ff9b7491589cb88decb1d135504c1b Mon Sep 17 00:00:00 2001
From: Jessica Del 
Date: Thu, 16 Nov 2023 11:22:52 +0100
Subject: [PATCH 3/5] fixup! Merge branch 'main' into quadmask-folding

---
 llvm/lib/Analysis/ConstantFolding.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index 64d088ea7a46404..2771a3d574f7799 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -2425,7 +2425,6 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
   return ConstantFP::get(Ty->getContext(), Val);
 }
 
-
 case Intrinsic::amdgcn_s_quadmask: {
   uint64_t Val = Op->getZExtValue();
   uint64_t QuadMask = 0;
@@ -2436,6 +2435,7 @@ static Constant

[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Nicolas van Kempen via cfe-commits

https://github.com/nicovank updated 
https://github.com/llvm/llvm-project/pull/72385

>From ddac6dc91c443bf81d4b6cc3f75686ea56801094 Mon Sep 17 00:00:00 2001
From: Nicolas van Kempen 
Date: Wed, 15 Nov 2023 01:13:10 -0800
Subject: [PATCH] [clang-tidy] Add new performance-use-starts-ends-with check

Match .find() and .rfind() calls compared to 0, and suggests replacing them with
starts_with.
---
 .../abseil/StringFindStartswithCheck.h|   5 +-
 .../clang-tidy/performance/CMakeLists.txt |   1 +
 .../performance/PerformanceTidyModule.cpp |   3 +
 .../performance/UseStartsEndsWithCheck.cpp| 109 +
 .../performance/UseStartsEndsWithCheck.h  |  37 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   7 +
 .../checks/abseil/string-find-startswith.rst  |   4 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../performance/use-starts-ends-with.rst  |  22 +++
 .../checkers/Inputs/Headers/stddef.h  |   2 +-
 .../clang-tidy/checkers/Inputs/Headers/string |  16 +-
 .../abseil/string-find-startswith.cpp |   2 +-
 .../performance/use-starts-ends-with.cpp  | 151 ++
 .../readability/container-size-empty.cpp  |   4 +-
 14 files changed, 358 insertions(+), 6 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/performance/use-starts-ends-with.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/performance/use-starts-ends-with.cpp

diff --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
index 923b5caece5439b..09773139daa1d66 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
@@ -21,7 +21,6 @@ namespace clang::tidy::abseil {
 
 // Find string.find(...) == 0 comparisons and suggest replacing with 
StartsWith.
 // FIXME(niko): Add similar check for EndsWith
-// FIXME(niko): Add equivalent modernize checks for C++20's std::starts_With
 class StringFindStartswithCheck : public ClangTidyCheck {
 public:
   using ClangTidyCheck::ClangTidyCheck;
@@ -31,6 +30,10 @@ class StringFindStartswithCheck : public ClangTidyCheck {
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+// Prefer performance-use-starts-ends-with when C++20 is available.
+return LangOpts.CPlusPlus && !LangOpts.CPlusPlus20;
+  }
 
 private:
   const std::vector StringLikeClasses;
diff --git a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
index 81128ff086021ed..fc88156d8c5f395 100644
--- a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
@@ -25,6 +25,7 @@ add_clang_library(clangTidyPerformanceModule
   TypePromotionInMathFnCheck.cpp
   UnnecessaryCopyInitialization.cpp
   UnnecessaryValueParamCheck.cpp
+  UseStartsEndsWithCheck.cpp
 
   LINK_LIBS
   clangTidy
diff --git a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp 
b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
index 9e0fa6f88b36a00..3405b5514cbce44 100644
--- a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
@@ -28,6 +28,7 @@
 #include "TypePromotionInMathFnCheck.h"
 #include "UnnecessaryCopyInitialization.h"
 #include "UnnecessaryValueParamCheck.h"
+#include "UseStartsEndsWithCheck.h"
 
 namespace clang::tidy {
 namespace performance {
@@ -70,6 +71,8 @@ class PerformanceModule : public ClangTidyModule {
 "performance-unnecessary-copy-initialization");
 CheckFactories.registerCheck(
 "performance-unnecessary-value-param");
+CheckFactories.registerCheck(
+"performance-use-starts-ends-with");
   }
 };
 
diff --git 
a/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
new file mode 100644
index 000..74cba350663b0a6
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
@@ -0,0 +1,109 @@
+//===--- UseStartsEndsWithCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+

[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Nicolas van Kempen via cfe-commits

nicovank wrote:

Major changes:
 -  Now matching on any class that has a `starts_with`, `startsWith`, or 
`startswith` function. This is done in order (prioritising functions in 
subclasses, but this could be changed). Experimenting on making this an option, 
not sure it's worth it without controlling class names as well.
 -  Not using `Lexer::getSourceText` anymore.

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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Nicolas van Kempen via cfe-commits


@@ -12,4 +12,4 @@
 typedef __PTRDIFF_TYPE__ ptrdiff_t;
 typedef __SIZE_TYPE__ size_t;
 
-#endif _STDDEF_H_
+#endif // _STDDEF_H_

nicovank wrote:

This was just issuing a warning in some tests.

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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Nicolas van Kempen via cfe-commits


@@ -0,0 +1,109 @@
+//===--- UseStartsEndsWithCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStartsEndsWithCheck.h"
+
+#include "../utils/OptionsUtils.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name,
+   ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {}
+
+void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
+  const auto ZeroLiteral = integerLiteral(equals(0));
+  const auto HasStartsWithMethod = anyOf(
+  hasMethod(cxxMethodDecl(hasName("starts_with")).bind("starts_with_fun")),
+  hasMethod(cxxMethodDecl(hasName("startsWith")).bind("starts_with_fun")),
+  hasMethod(cxxMethodDecl(hasName("startswith")).bind("starts_with_fun")));

nicovank wrote:

Using `hasAnyName` will match the first declared function. With this setup 
there is a precedence, I thought this was better. IIRC `llvm::StringRef` has 
`startswith` and `starts_with` and the latter is preferred.

This could maybe be an option, e.g. `OrderedStartsWithFunctions`. The code gets 
a bit trickier because this is the opposite of `mapAnyOf`, and AFAIK `anyOf` 
doesn't take a vector or other kind of collection, only varargs. Suggestions 
welcome.

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


[clang] b2d62c9 - [clang] Ensure fixed point conversions work in C++ (#68344)

2023-11-17 Thread via cfe-commits

Author: PiJoules
Date: 2023-11-16T13:11:15-08:00
New Revision: b2d62c9a58433e2a2ca8d2c9cd6b0b612dca2e76

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

LOG: [clang] Ensure fixed point conversions work in C++ (#68344)

Added: 


Modified: 
clang/include/clang/Sema/Overload.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/Frontend/fixed_point_conversions.c

Removed: 




diff  --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index a97968dc7b20967..09a3686a1f9 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -192,6 +192,9 @@ class Sema;
 /// C-only conversion between pointers with incompatible types
 ICK_Incompatible_Pointer_Conversion,
 
+/// Fixed point type conversions according to N1169.
+ICK_Fixed_Point_Conversion,
+
 /// The number of conversion kinds
 ICK_Num_Conversion_Kinds,
   };

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index a6cd0bb9ea2a829..da8e2db36aaabb8 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -148,6 +148,9 @@ bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const 
{
   case tok::kw___ibm128:
   case tok::kw_wchar_t:
   case tok::kw_bool:
+  case tok::kw__Accum:
+  case tok::kw__Fract:
+  case tok::kw__Sat:
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
 #include "clang/Basic/TransformTypeTraits.def"
   case tok::kw___auto_type:

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 023411c7edc946b..081b568762ae228 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4506,6 +4506,36 @@ Sema::PerformImplicitConversion(Expr *From, QualType 
ToType,
  .get();
 break;
 
+  case ICK_Fixed_Point_Conversion:
+assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
+   "Attempting implicit fixed point conversion without a fixed "
+   "point operand");
+if (FromType->isFloatingType())
+  From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+else if (ToType->isFloatingType())
+  From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+else if (FromType->isIntegralType(Context))
+  From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+else if (ToType->isIntegralType(Context))
+  From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+else if (ToType->isBooleanType())
+  From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+else
+  From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
+   VK_PRValue,
+   /*BasePath=*/nullptr, CCK).get();
+break;
+
   case ICK_Compatible_Conversion:
 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
  /*BasePath=*/nullptr, CCK).get();

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 858654e35cbb6bd..9800d7f1c9cfee9 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -158,7 +158,8 @@ ImplicitConversionRank 
clang::GetConversionRank(ImplicitConversionKind Kind) {
  // it was omitted by the patch that added
  // ICK_Zero_Queue_Conversion
 ICR_C_Conversion,
-ICR_C_Conversion_Extension
+ICR_C_Conversion_Extension,
+ICR_Conversion,
   };
   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
   return Rank[(int)Kind];
@@ -197,7 +198,8 @@ static const char* 
GetImplicitConversionName(ImplicitConversionKind Kind) {
 "OpenCL Zero Event Conversion",
 "OpenCL Zero Queue Conversion",
 "C specific type conversion",
-"Incompatible pointer conversion"
+"Incompatible pointer conversion",
+"Fixed point conversion",
   };
   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
   return Name[Kind];
@@ -2189,6 +2191,9 @@ static bool IsStandardConversion(Sema &S, Expr* From, 
QualType ToType,
  From->isIntegerConstantExpr(S.getASTContext())) {
   

[clang] ae623d1 - [Driver,Gnu] Simplify -static -static-pie -shared -pie handling and suppress -shared -rdynamic warning

2023-11-17 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-11-16T13:48:04-08:00
New Revision: ae623d16d50c9f12de7ae7ac1aa11c9d6857e081

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

LOG: [Driver,Gnu] Simplify -static -static-pie -shared -pie handling and 
suppress -shared -rdynamic warning

These options select different link modes (note: -shared -static can be
used together for musl and mingw). It makes sense to place them
together, which enables some simplification. The relevant ld options
are now consistently placed after -m, similar to GCC.

While here, suppress -Wunused-command-line-argument warning when -shared
-rdynamic are used together (introduced by commit
291f4a00232b5742940d67e2ecf9168631251317). It can be argued either way
whether the warning is justified (in ELF linkers --export-dynamic
functionality is subsumed by -shared), but it is not useful (users can
do -Wl,--export-dynamic, bypassing the driver diagnostic).

Added: 


Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/test/Driver/dynamic-linker.c
clang/test/Driver/linux-ld.c
clang/test/Driver/ohos.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 76986481686adc6..ba95ce9c5a28153 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -292,18 +292,6 @@ static const char *getLDMOption(const llvm::Triple &T, 
const ArgList &Args) {
   }
 }
 
-static bool getPIE(const ArgList &Args, const ToolChain &TC) {
-  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
-  Args.hasArg(options::OPT_r) || Args.hasArg(options::OPT_static_pie))
-return false;
-
-  Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
-   options::OPT_nopie);
-  if (!A)
-return TC.isPIEDefault(Args);
-  return A->getOption().matches(options::OPT_pie);
-}
-
 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
   bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
   // -no-pie is an alias for -nopie. So, handling -nopie takes care of
@@ -386,7 +374,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
   const bool isAndroid = ToolChain.getTriple().isAndroid();
   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
   const bool IsVE = ToolChain.getTriple().isVE();
-  const bool IsPIE = getPIE(Args, ToolChain);
   const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
   const bool IsStatic = getStatic(Args);
   const bool HasCRTBeginEndFiles =
@@ -406,17 +393,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
   if (!D.SysRoot.empty())
 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
 
-  if (IsPIE)
-CmdArgs.push_back("-pie");
-
-  if (IsStaticPIE) {
-CmdArgs.push_back("-static");
-CmdArgs.push_back("-pie");
-CmdArgs.push_back("--no-dynamic-linker");
-CmdArgs.push_back("-z");
-CmdArgs.push_back("text");
-  }
-
   if (Args.hasArg(options::OPT_s))
 CmdArgs.push_back("-s");
 
@@ -451,19 +427,32 @@ void tools::gnutools::Linker::ConstructJob(Compilation 
&C, const JobAction &JA,
   if (Triple.isRISCV())
 CmdArgs.push_back("-X");
 
-  if (Args.hasArg(options::OPT_shared))
+  const bool IsShared = Args.hasArg(options::OPT_shared);
+  if (IsShared)
 CmdArgs.push_back("-shared");
-
-  if (IsStatic) {
+  bool IsPIE = false;
+  if (IsStaticPIE) {
+CmdArgs.push_back("-static");
+CmdArgs.push_back("-pie");
+CmdArgs.push_back("--no-dynamic-linker");
+CmdArgs.push_back("-z");
+CmdArgs.push_back("text");
+  } else if (IsStatic) {
 CmdArgs.push_back("-static");
-  } else if (!Args.hasArg(options::OPT_r) &&
- !Args.hasArg(options::OPT_shared) && !IsStaticPIE) {
+  } else if (!Args.hasArg(options::OPT_r)) {
 if (Args.hasArg(options::OPT_rdynamic))
   CmdArgs.push_back("-export-dynamic");
-
-CmdArgs.push_back("-dynamic-linker");
-CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
- ToolChain.getDynamicLinker(Args)));
+if (!IsShared) {
+  Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
+   options::OPT_nopie);
+  IsPIE = A ? A->getOption().matches(options::OPT_pie)
+: ToolChain.isPIEDefault(Args);
+  if (IsPIE)
+CmdArgs.push_back("-pie");
+  CmdArgs.push_back("-dynamic-linker");
+  CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
+   ToolChain.getDynamicLinker(Args)));
+}
   }
 
   CmdArgs.push_back("-o");

diff  --git a/clang/test/Driver/dynamic-linker.c 
b/clang/test/Driver/dynamic-linker.c
index 555e46aba5f069b..9

[clang] 066c452 - [AArch64] Add support for Cortex-A520, Cortex-A720 and Cortex-X4 CPUs (#72395)

2023-11-17 Thread via cfe-commits

Author: Jonathan Thackray
Date: 2023-11-16T22:08:58Z
New Revision: 066c4524bc1d91b49048e7f05dc6e045bb3c9eef

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

LOG: [AArch64] Add support for Cortex-A520, Cortex-A720 and Cortex-X4 CPUs 
(#72395)

Cortex-A520, Cortex-A720 and Cortex-X4 are Armv9.2 AArch64 CPUs.

Technical Reference Manual for Cortex-A520:
   https://developer.arm.com/documentation/102517/latest/

Technical Reference Manual for Cortex-A720:
   https://developer.arm.com/documentation/102530/latest/

Technical Reference Manual for Cortex-X4:
   https://developer.arm.com/documentation/102484/latest/

Patch co-authored by: Sivan Shani 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/test/Driver/aarch64-mcpu.c
clang/test/Misc/target-invalid-cpu-note.c
llvm/docs/ReleaseNotes.rst
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/lib/Target/AArch64/AArch64.td
llvm/lib/Target/AArch64/AArch64Subtarget.cpp
llvm/lib/Target/AArch64/AArch64Subtarget.h
llvm/lib/TargetParser/Host.cpp
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed1a978b5382d71..31ebe89fb0cafd6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -760,6 +760,12 @@ Arm and AArch64 Support
 
 - New AArch64 asm constraints have been added for r8-r11(Uci) and r12-r15(Ucj).
 
+  Support has been added for the following processors (-mcpu identifiers in 
parenthesis):
+
+  * Arm Cortex-A520 (cortex-a520).
+  * Arm Cortex-A720 (cortex-a720).
+  * Arm Cortex-X4 (cortex-x4).
+
 Android Support
 ^^^
 

diff  --git a/clang/test/Driver/aarch64-mcpu.c 
b/clang/test/Driver/aarch64-mcpu.c
index 321d3a739b35350..511482a420da268 100644
--- a/clang/test/Driver/aarch64-mcpu.c
+++ b/clang/test/Driver/aarch64-mcpu.c
@@ -44,12 +44,16 @@
 // CORTEXX1C: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-x1c"
 // RUN: %clang --target=aarch64 -mcpu=cortex-x3 -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEXX3 %s
 // CORTEXX3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-x3"
+// RUN: %clang --target=aarch64 -mcpu=cortex-x4 -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEX-X4 %s
+// CORTEX-X4: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-x4"
 // RUN: %clang --target=aarch64 -mcpu=cortex-a78  -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEXA78 %s
 // CORTEXA78: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-a78"
 // RUN: %clang --target=aarch64 -mcpu=cortex-a78c  -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEX-A78C %s
 // CORTEX-A78C: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"cortex-a78c"
 // RUN: %clang --target=aarch64 -mcpu=cortex-a715  -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEX-A715 %s
 // CORTEX-A715: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"cortex-a715"
+// RUN: %clang --target=aarch64 -mcpu=cortex-a720  -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEX-A720 %s
+// CORTEX-A720: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"cortex-a720"
 // RUN: %clang --target=aarch64 -mcpu=neoverse-e1  -### -c %s 2>&1 | FileCheck 
-check-prefix=NEOVERSE-E1 %s
 // NEOVERSE-E1: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"neoverse-e1"
 // RUN: %clang --target=aarch64 -mcpu=neoverse-v1  -### -c %s 2>&1 | FileCheck 
-check-prefix=NEOVERSE-V1 %s
@@ -62,6 +66,8 @@
 // NEOVERSE-N2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"neoverse-n2"
 // RUN: %clang --target=aarch64 -mcpu=neoverse-512tvb -### -c %s 2>&1 | 
FileCheck -check-prefix=NEOVERSE-512TVB %s
 // NEOVERSE-512TVB: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"neoverse-512tvb"
+// RUN: %clang --target=aarch64 -mcpu=cortex-a520 -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEX-A520 %s
+// CORTEX-A520: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"cortex-a520"
 
 // RUN: %clang --target=aarch64 -mcpu=cortex-r82  -### -c %s 2>&1 | FileCheck 
-check-prefix=CORTEXR82 %s
 // CORTEXR82: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-r82"

diff  --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index 8e91eb4c62dd259..25ff51e071b69b3 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -5,11 +5,11 @@
 
 // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix AARCH64
 // AARCH64: error: unknown target CPU 'not-a-cpu'
-// AARCH64-NEXT: note: valid target CPU values are: cortex-a34, cortex-a35, 
cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, cortex-a65ae, 
cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76

[clang] f0ad9ea - [clang-format] Handle lambdas in QualifierAlignment (#72456)

2023-11-17 Thread via cfe-commits

Author: Owen Pan
Date: 2023-11-16T15:00:09-08:00
New Revision: f0ad9ea36ad65cec8c5e5d1d59c00192b87f287d

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

LOG: [clang-format] Handle lambdas in QualifierAlignment (#72456)

Fixed #62780.

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/QualifierAlignmentFixer.h
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index e2fab1c1e3c2a37..84941746f0df71b 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -535,14 +535,21 @@ LeftRightQualifierAlignmentFixer::analyze(
 SmallVectorImpl &AnnotatedLines,
 FormatTokenLexer &Tokens) {
   tooling::Replacements Fixes;
-  const AdditionalKeywords &Keywords = Tokens.getKeywords();
-  const SourceManager &SourceMgr = Env.getSourceManager();
   AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+  fixQualifierAlignment(AnnotatedLines, Tokens, Fixes);
+  return {Fixes, 0};
+}
 
+void LeftRightQualifierAlignmentFixer::fixQualifierAlignment(
+SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens,
+tooling::Replacements &Fixes) {
+  const AdditionalKeywords &Keywords = Tokens.getKeywords();
+  const SourceManager &SourceMgr = Env.getSourceManager();
   tok::TokenKind QualifierToken = getTokenFromQualifier(Qualifier);
   assert(QualifierToken != tok::identifier && "Unrecognised Qualifier");
 
   for (AnnotatedLine *Line : AnnotatedLines) {
+fixQualifierAlignment(Line->Children, Tokens, Fixes);
 if (!Line->Affected || Line->InPPDirective)
   continue;
 FormatToken *First = Line->First;
@@ -565,7 +572,6 @@ LeftRightQualifierAlignmentFixer::analyze(
   }
 }
   }
-  return {Fixes, 0};
 }
 
 void prepareLeftRightOrderingForQualifierAlignmentFixer(

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.h 
b/clang/lib/Format/QualifierAlignmentFixer.h
index a72d135179f1ece..e922d8005595103 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.h
+++ b/clang/lib/Format/QualifierAlignmentFixer.h
@@ -52,6 +52,10 @@ class LeftRightQualifierAlignmentFixer : public 
TokenAnalyzer {
 
   static tok::TokenKind getTokenFromQualifier(const std::string &Qualifier);
 
+  void fixQualifierAlignment(SmallVectorImpl &AnnotatedLines,
+ FormatTokenLexer &Tokens,
+ tooling::Replacements &Fixes);
+
   const FormatToken *analyzeRight(const SourceManager &SourceMgr,
   const AdditionalKeywords &Keywords,
   tooling::Replacements &Fixes,

diff  --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index a56323a88f4a04d..324366ca7f5e511 100644
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -357,6 +357,9 @@ TEST_F(QualifierFixerTest, RightQualifier) {
   verifyFormat("void f(std::integral auto const &x);",
"void f(const std::integral auto &x);", Style);
 
+  verifyFormat("auto lambda = [] { int const i = 0; };",
+   "auto lambda = [] { const int i = 0; };", Style);
+
   verifyFormat("Foo const> P;\n#if 0\n#else\n#endif",
"Foo> P;\n#if 0\n#else\n#endif", Style);
 
@@ -663,6 +666,9 @@ TEST_F(QualifierFixerTest, LeftQualifier) {
   verifyFormat("void f(const std::integral auto &x);",
"void f(std::integral auto const &x);", Style);
 
+  verifyFormat("auto lambda = [] { const int i = 0; };",
+   "auto lambda = [] { int const i = 0; };", Style);
+
   verifyFormat("Foo> P;\n#if 0\n#else\n#endif",
"Foo const> P;\n#if 0\n#else\n#endif", Style);
 



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


[lld] [libunwind] [libcxxabi] [libcxx] [compiler-rt] [llvm] [flang] [mlir] [clang-tools-extra] [lldb] [clang] [Passes] Disable code sinking in InstCombine early on. (PR #72567)

2023-11-17 Thread Florian Hahn via cfe-commits

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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Nicolas van Kempen via cfe-commits

https://github.com/nicovank updated 
https://github.com/llvm/llvm-project/pull/72385

>From 7a9703f27897af0846d272ca7393bc72eff11e55 Mon Sep 17 00:00:00 2001
From: Nicolas van Kempen 
Date: Wed, 15 Nov 2023 01:13:10 -0800
Subject: [PATCH] [clang-tidy] Add new performance-use-starts-ends-with check

Match .find() and .rfind() calls compared to 0, and suggests replacing them with
starts_with.
---
 .../abseil/StringFindStartswithCheck.h|   5 +-
 .../clang-tidy/performance/CMakeLists.txt |   1 +
 .../performance/PerformanceTidyModule.cpp |   3 +
 .../performance/UseStartsEndsWithCheck.cpp| 109 +
 .../performance/UseStartsEndsWithCheck.h  |  37 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   7 +
 .../checks/abseil/string-find-startswith.rst  |   4 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../performance/use-starts-ends-with.rst  |  22 +++
 .../checkers/Inputs/Headers/stddef.h  |   2 +-
 .../clang-tidy/checkers/Inputs/Headers/string |  16 +-
 .../abseil/string-find-startswith.cpp |   2 +-
 .../performance/use-starts-ends-with.cpp  | 151 ++
 .../readability/container-size-empty.cpp  |   4 +-
 14 files changed, 358 insertions(+), 6 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/performance/use-starts-ends-with.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/performance/use-starts-ends-with.cpp

diff --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
index 923b5caece5439b..09773139daa1d66 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
@@ -21,7 +21,6 @@ namespace clang::tidy::abseil {
 
 // Find string.find(...) == 0 comparisons and suggest replacing with 
StartsWith.
 // FIXME(niko): Add similar check for EndsWith
-// FIXME(niko): Add equivalent modernize checks for C++20's std::starts_With
 class StringFindStartswithCheck : public ClangTidyCheck {
 public:
   using ClangTidyCheck::ClangTidyCheck;
@@ -31,6 +30,10 @@ class StringFindStartswithCheck : public ClangTidyCheck {
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+// Prefer performance-use-starts-ends-with when C++20 is available.
+return LangOpts.CPlusPlus && !LangOpts.CPlusPlus20;
+  }
 
 private:
   const std::vector StringLikeClasses;
diff --git a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
index 81128ff086021ed..fc88156d8c5f395 100644
--- a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
@@ -25,6 +25,7 @@ add_clang_library(clangTidyPerformanceModule
   TypePromotionInMathFnCheck.cpp
   UnnecessaryCopyInitialization.cpp
   UnnecessaryValueParamCheck.cpp
+  UseStartsEndsWithCheck.cpp
 
   LINK_LIBS
   clangTidy
diff --git a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp 
b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
index 9e0fa6f88b36a00..3405b5514cbce44 100644
--- a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
@@ -28,6 +28,7 @@
 #include "TypePromotionInMathFnCheck.h"
 #include "UnnecessaryCopyInitialization.h"
 #include "UnnecessaryValueParamCheck.h"
+#include "UseStartsEndsWithCheck.h"
 
 namespace clang::tidy {
 namespace performance {
@@ -70,6 +71,8 @@ class PerformanceModule : public ClangTidyModule {
 "performance-unnecessary-copy-initialization");
 CheckFactories.registerCheck(
 "performance-unnecessary-value-param");
+CheckFactories.registerCheck(
+"performance-use-starts-ends-with");
   }
 };
 
diff --git 
a/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
new file mode 100644
index 000..74cba350663b0a6
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/UseStartsEndsWithCheck.cpp
@@ -0,0 +1,109 @@
+//===--- UseStartsEndsWithCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+

[flang] [clang] [Flang] Add code-object-version option (PR #72638)

2023-11-17 Thread Dominik Adamski via cfe-commits

https://github.com/DominikAdamski updated 
https://github.com/llvm/llvm-project/pull/72638

>From e5d339c24193e4e37013b3b25460009418d6ce6d Mon Sep 17 00:00:00 2001
From: Dominik Adamski 
Date: Fri, 17 Nov 2023 03:02:49 -0600
Subject: [PATCH] [Flang] Add code-object-version option

Information about code object version can be configured by the user
for AMD GPU target and it needs to be placed in LLVM IR generated
by Flang.

Information about code object version in MLIR generated by the
parser can be reused by other tools. There is no need to specify
extra flags if we want to invoke MLIR tools separately.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 11 ++
 clang/lib/Driver/ToolChains/Flang.h   |  7 
 flang/include/flang/Frontend/CodeGenOptions.h | 13 +++
 flang/lib/Frontend/CompilerInvocation.cpp |  9 +
 flang/lib/Frontend/FrontendActions.cpp| 39 +--
 flang/test/Driver/code-object-version.f90 |  8 
 flang/test/Driver/driver-help-hidden.f90  |  2 +
 flang/test/Driver/driver-help.f90 |  4 ++
 flang/test/Lower/AMD/code_object_version.f90  | 11 ++
 10 files changed, 101 insertions(+), 5 deletions(-)
 create mode 100644 flang/test/Driver/code-object-version.f90
 create mode 100644 flang/test/Lower/AMD/code_object_version.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 811550416110b3d..e7eb94d174e75f8 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4688,7 +4688,7 @@ defm amdgpu_ieee : BoolOption<"m", "amdgpu-ieee",
 
 def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, 
Group,
   HelpText<"Specify code object ABI version. Defaults to 4. (AMDGPU only)">,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, FlangOption, CC1Option, FC1Option]>,
   Values<"none,4,5">,
   NormalizedValuesScope<"TargetOptions">,
   NormalizedValues<["COV_None", "COV_4", "COV_5"]>,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8bdd920c3dcbb79..e60c11bfbe8e38b 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -204,6 +204,14 @@ void Flang::AddAArch64TargetArgs(const ArgList &Args,
   }
 }
 
+void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
+ArgStringList &CmdArgs) const {
+  if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
+StringRef Val = A->getValue();
+CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
+  }
+}
+
 void Flang::addTargetOptions(const ArgList &Args,
  ArgStringList &CmdArgs) const {
   const ToolChain &TC = getToolChain();
@@ -227,6 +235,9 @@ void Flang::addTargetOptions(const ArgList &Args,
 
   case llvm::Triple::r600:
   case llvm::Triple::amdgcn:
+getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
+AddAMDGPUTargetArgs(Args, CmdArgs);
+break;
   case llvm::Triple::riscv64:
   case llvm::Triple::x86_64:
 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
diff --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index 0141240b5d3ac90..8d35080e1c0c88b 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -63,6 +63,13 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   void AddAArch64TargetArgs(const llvm::opt::ArgList &Args,
 llvm::opt::ArgStringList &CmdArgs) const;
 
+  /// Add specific options for AMDGPU target.
+  ///
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void AddAMDGPUTargetArgs(const llvm::opt::ArgList &Args,
+   llvm::opt::ArgStringList &CmdArgs) const;
+
   /// Extract offload options from the driver arguments and add them to
   /// the command arguments.
   /// \param [in] C The current compilation for the driver invocation
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b86bb88610a9a4a..8d938c361a0aa23 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -85,6 +85,19 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  /// \brief Enumeration value for AMDGPU code object version, which is the
+  /// code object version times 100.
+  enum class CodeObjectVersionKind {
+COV_None,
+COV_2 = 200, // Unsupported.
+COV_3 = 300, // Unsupported.
+COV_4 = 400,
+COV_5 = 500,
+  };
+
+  /// \brief Code object version for AMDGPU.
+  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_None;
+
   /// Optimization remark with an optional regular expre

[clang] [clang-format] Fix crashes in AlignArrayOfStructures (PR #72520)

2023-11-17 Thread Owen Pan via cfe-commits

owenca wrote:

> @owenca I picked da1b1fba5cfd41521a840202d8cf4c3796c5e10b on top of the 17.x 
> branch and my test case was not fixed, it still crashes in the same way as 
> described in #72628

Thanks for trying it on 17.x. We can't backport it then.

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-11-17 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov updated 
https://github.com/llvm/llvm-project/pull/68993

>From b42de31d5584cddb90c22c94e9d971feaaf0b624 Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Wed, 11 Oct 2023 17:22:51 +0100
Subject: [PATCH] [clang][AArch64] Pass down stack clash protection options to
 LLVM/Backend

---
 clang/lib/CodeGen/CodeGenModule.cpp | 12 +++-
 clang/lib/Driver/ToolChains/Clang.cpp   |  2 +-
 clang/test/CodeGen/stack-clash-protection.c | 16 
 3 files changed, 24 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index f1b900be74b2cdf..bbde22fb5d82ee3 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1085,6 +1085,16 @@ void CodeGenModule::Release() {
 "sign-return-address-with-bkey", 1);
   }
 
+  if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) {
+auto *InlineAsm = llvm::MDString::get(TheModule.getContext(), 
"inline-asm");
+if (CodeGenOpts.StackClashProtector)
+  getModule().addModuleFlag(llvm::Module::Override, "probe-stack",
+InlineAsm);
+if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
+  getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
+CodeGenOpts.StackProbeSize);
+  }
+
   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
 llvm::LLVMContext &Ctx = TheModule.getContext();
 getModule().addModuleFlag(
@@ -2296,7 +2306,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   if ((!D || !D->hasAttr()) && CodeGenOpts.UnwindTables)
 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
 
-  if (CodeGenOpts.StackClashProtector)
+  if (CodeGenOpts.StackClashProtector && !getTarget().getTriple().isAArch64())
 B.addAttribute("probe-stack", "inline-asm");
 
   if (!hasUnwindExceptions(LangOpts))
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index b462f5a44057d94..7add64ac6f2dfd5 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3507,7 +3507,7 @@ static void RenderSCPOptions(const ToolChain &TC, const 
ArgList &Args,
 return;
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
-  !EffectiveTriple.isPPC64())
+  !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
 return;
 
   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
diff --git a/clang/test/CodeGen/stack-clash-protection.c 
b/clang/test/CodeGen/stack-clash-protection.c
index 67571f5cdb2c14c..2f502ef453d42f4 100644
--- a/clang/test/CodeGen/stack-clash-protection.c
+++ b/clang/test/CodeGen/stack-clash-protection.c
@@ -1,10 +1,12 @@
 // Check the correct function attributes are generated
-// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s 
--check-prefixes CHECK-AARCH64
 
 // CHECK: define{{.*}} void @large_stack() #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @large_stack() #[[A:.*]] {
 void large_stack(void) {
   volatile int stack[2], i;
   for (i = 0; i < sizeof(stack) / sizeof(int); ++i)
@@ -12,14 +14,20 @@ void large_stack(void) {
 }
 
 // CHECK: define{{.*}} void @vla({{.*}}) #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @vla({{.*}}) #[[A:.*]] {
 void vla(int n) {
   volatile int vla[n];
   __builtin_memset(&vla[0], 0, 1);
 }
 
 // CHECK: define{{.*}} void @builtin_alloca({{.*}}) #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @builtin_alloca({{.*}}) #[[A:.*]] {
 void builtin_alloca(int n) {
   volatile void *mem = __builtin_alloca(n);
 }
 
 // CHECK: attributes #[[A]] = {{.*}} "probe-stack"="inline-asm"
+// CHECK-AARCH64-NOT: attributes #[[A]] = {{.*}} "probe-stack"
+
+// CHECK-AARCH64: !{i32 4, !"probe-stack", !"inline-asm"}
+// CHECK-AARCH64: !{i

[lld] [mlir] [llvm] [clang-tools-extra] [flang] [compiler-rt] [libc] [libcxx] [lldb] [clang] [MLIR] Enable GPU Dialect to SYCL runtime integration (PR #71430)

2023-11-17 Thread Fabian Mora via cfe-commits


@@ -61,6 +63,7 @@ registerAllGPUToLLVMIRTranslations(DialectRegistry ®istry) 
{
   registerLLVMDialectTranslation(registry);
   registerNVVMDialectTranslation(registry);
   registerROCDLDialectTranslation(registry);
+  registerSPIRVDialectTranslation(registry);

fabianmcg wrote:

The call to `registry.insert();` is needed so that 
`mlir-translate` can parse the code containing the SPIR-V target attribute, 
nothing more; there's no translation happening from SPIR-V to LLVM. If the call 
is not added, then `mlir-translate` throws an error because `SPIR-V` never gets 
registered.

The question is, should an empty translation to LLVM should be added to mirror 
all other * to LLVM translation code structure, or is inlining the call ok? I 
definitely prefer the second option -one less target.

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


Can't assign an issue - Add me collaborator/contributor list

2023-11-17 Thread Shahid Iqbal via cfe-commits
Hi
Please add me to a collaborator list , since I cannot assign an issue to
myself. I just want to ensure that no one works that particular issue.

My github handle is :  * shahidiqbal13*

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


[clang-tools-extra] [clangd] Allow "move function body out-of-line" in non-header files (PR #69704)

2023-11-17 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

Thanks! I believe the idea is great, but I am not really sure if this is useful 
enough without handling anon namespaces properly. It's very rare that someone 
has a class/struct in a cc file, that isn't in an anon-namespace.

Would you mind evolving the patch (and the infra) to work for 
method-definitions inside anon namespaces?

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


[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2023-11-17 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/72644

https://isocpp.org/files/papers/P2662R3.pdf

Because there is a slight chance the syntax might change slightly (see 
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2994r0.html), the 
feature is not exposed in other language modes.

>From ac0f8313637763fe0ffcaf7f45cf803babe1b65b Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 13 Sep 2022 18:29:34 +0200
Subject: [PATCH] [Clang][C++26] Implement Pack Indexing (P2662R3).

https://isocpp.org/files/papers/P2662R3.pdf

Because there is a slight chance the syntax might change slightly
(see https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2994r0.html),
the feature is not exposed in other language modes.
---
 clang/docs/ReleaseNotes.rst   |   2 +
 clang/include/clang-c/Index.h |   7 +-
 clang/include/clang/AST/ASTContext.h  |   8 +
 clang/include/clang/AST/ASTNodeTraverser.h|   6 +
 clang/include/clang/AST/ExprCXX.h | 106 ++
 clang/include/clang/AST/RecursiveASTVisitor.h |  11 +
 clang/include/clang/AST/Type.h|  66 ++
 clang/include/clang/AST/TypeLoc.h |  28 +++
 clang/include/clang/AST/TypeProperties.td |  14 ++
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Basic/Specifiers.h|   1 +
 clang/include/clang/Basic/StmtNodes.td|   1 +
 clang/include/clang/Basic/TokenKinds.def  |   2 +
 clang/include/clang/Basic/TypeNodes.td|   1 +
 clang/include/clang/Parse/Parser.h|   9 +
 clang/include/clang/Sema/DeclSpec.h   |  25 ++-
 clang/include/clang/Sema/Sema.h   |  25 +++
 .../include/clang/Serialization/ASTBitCodes.h |   1 +
 .../clang/Serialization/TypeBitCodes.def  |   2 +
 clang/lib/AST/ASTContext.cpp  |  43 
 clang/lib/AST/ASTImporter.cpp |  12 ++
 clang/lib/AST/ASTStructuralEquivalence.cpp|  10 +
 clang/lib/AST/Expr.cpp|   8 +
 clang/lib/AST/ExprCXX.cpp |  37 
 clang/lib/AST/ExprClassification.cpp  |   3 +
 clang/lib/AST/ExprConstant.cpp|   7 +
 clang/lib/AST/ItaniumMangle.cpp   |   9 +
 clang/lib/AST/MicrosoftMangle.cpp |   6 +
 clang/lib/AST/StmtPrinter.cpp |   4 +
 clang/lib/AST/StmtProfile.cpp |   6 +
 clang/lib/AST/Type.cpp|  40 
 clang/lib/AST/TypePrinter.cpp |  18 ++
 clang/lib/CodeGen/CGDebugInfo.cpp |   5 +
 clang/lib/CodeGen/CGExpr.cpp  |   2 +
 clang/lib/CodeGen/CGExprAgg.cpp   |   3 +
 clang/lib/CodeGen/CGExprComplex.cpp   |   4 +
 clang/lib/CodeGen/CGExprConstant.cpp  |   4 +
 clang/lib/CodeGen/CGExprScalar.cpp|   3 +
 clang/lib/CodeGen/CodeGenFunction.cpp |   1 +
 clang/lib/Parse/ParseCXXInlineMethods.cpp |  14 ++
 clang/lib/Parse/ParseDecl.cpp |   5 +
 clang/lib/Parse/ParseDeclCXX.cpp  | 101 +
 clang/lib/Parse/ParseExpr.cpp |  13 ++
 clang/lib/Parse/ParseExprCXX.cpp  |  68 +-
 clang/lib/Parse/ParseTentative.cpp|  13 ++
 clang/lib/Parse/Parser.cpp|   3 +-
 clang/lib/Sema/DeclSpec.cpp   |  21 ++
 clang/lib/Sema/SemaCXXScopeSpec.cpp   |  23 ++
 clang/lib/Sema/SemaDecl.cpp   |   1 +
 clang/lib/Sema/SemaDeclCXX.cpp|   4 +
 clang/lib/Sema/SemaExceptionSpec.cpp  |   1 +
 clang/lib/Sema/SemaExpr.cpp   |   3 +
 clang/lib/Sema/SemaExprCXX.cpp|  32 ++-
 clang/lib/Sema/SemaTemplate.cpp   |   5 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  16 ++
 clang/lib/Sema/SemaTemplateVariadic.cpp   |  66 +-
 clang/lib/Sema/SemaType.cpp   |  60 ++
 clang/lib/Sema/TreeTransform.h| 200 ++
 clang/lib/Serialization/ASTReader.cpp |   4 +
 clang/lib/Serialization/ASTReaderStmt.cpp |  22 ++
 clang/lib/Serialization/ASTWriter.cpp |   5 +
 clang/lib/Serialization/ASTWriterStmt.cpp |  16 ++
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |   1 +
 clang/test/PCH/pack_indexing.cpp  |  16 ++
 clang/test/Parser/cxx2b-pack-indexing.cpp |  65 ++
 clang/test/SemaCXX/cxx2b-pack-indexing.cpp| 115 ++
 clang/tools/libclang/CIndex.cpp   |   8 +
 clang/tools/libclang/CXCursor.cpp |   4 +
 clang/www/cxx_status.html |   2 +-
 69 files changed, 1438 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/PCH/pack_indexing.cpp
 create mode 100644 clang/test/Parser/cxx2b-pack-indexing.cpp
 create mode 100644 clang/test/SemaCXX/cxx2b-pack-indexing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed1a978b5382d71..d

[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2023-11-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang-modules

Author: cor3ntin (cor3ntin)


Changes

https://isocpp.org/files/papers/P2662R3.pdf

Because there is a slight chance the syntax might change slightly (see 
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2994r0.html), the 
feature is not exposed in other language modes.

---

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


69 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang-c/Index.h (+6-1) 
- (modified) clang/include/clang/AST/ASTContext.h (+8) 
- (modified) clang/include/clang/AST/ASTNodeTraverser.h (+6) 
- (modified) clang/include/clang/AST/ExprCXX.h (+106) 
- (modified) clang/include/clang/AST/RecursiveASTVisitor.h (+11) 
- (modified) clang/include/clang/AST/Type.h (+66) 
- (modified) clang/include/clang/AST/TypeLoc.h (+28) 
- (modified) clang/include/clang/AST/TypeProperties.td (+14) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+7-1) 
- (modified) clang/include/clang/Basic/Specifiers.h (+1) 
- (modified) clang/include/clang/Basic/StmtNodes.td (+1) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+2) 
- (modified) clang/include/clang/Basic/TypeNodes.td (+1) 
- (modified) clang/include/clang/Parse/Parser.h (+9) 
- (modified) clang/include/clang/Sema/DeclSpec.h (+23-2) 
- (modified) clang/include/clang/Sema/Sema.h (+25) 
- (modified) clang/include/clang/Serialization/ASTBitCodes.h (+1) 
- (modified) clang/include/clang/Serialization/TypeBitCodes.def (+2) 
- (modified) clang/lib/AST/ASTContext.cpp (+43) 
- (modified) clang/lib/AST/ASTImporter.cpp (+12) 
- (modified) clang/lib/AST/ASTStructuralEquivalence.cpp (+10) 
- (modified) clang/lib/AST/Expr.cpp (+8) 
- (modified) clang/lib/AST/ExprCXX.cpp (+37) 
- (modified) clang/lib/AST/ExprClassification.cpp (+3) 
- (modified) clang/lib/AST/ExprConstant.cpp (+7) 
- (modified) clang/lib/AST/ItaniumMangle.cpp (+9) 
- (modified) clang/lib/AST/MicrosoftMangle.cpp (+6) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+4) 
- (modified) clang/lib/AST/StmtProfile.cpp (+6) 
- (modified) clang/lib/AST/Type.cpp (+40) 
- (modified) clang/lib/AST/TypePrinter.cpp (+18) 
- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+5) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+2) 
- (modified) clang/lib/CodeGen/CGExprAgg.cpp (+3) 
- (modified) clang/lib/CodeGen/CGExprComplex.cpp (+4) 
- (modified) clang/lib/CodeGen/CGExprConstant.cpp (+4) 
- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+3) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+1) 
- (modified) clang/lib/Parse/ParseCXXInlineMethods.cpp (+14) 
- (modified) clang/lib/Parse/ParseDecl.cpp (+5) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+101) 
- (modified) clang/lib/Parse/ParseExpr.cpp (+13) 
- (modified) clang/lib/Parse/ParseExprCXX.cpp (+67-1) 
- (modified) clang/lib/Parse/ParseTentative.cpp (+13) 
- (modified) clang/lib/Parse/Parser.cpp (+2-1) 
- (modified) clang/lib/Sema/DeclSpec.cpp (+21) 
- (modified) clang/lib/Sema/SemaCXXScopeSpec.cpp (+23) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+1) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+4) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+1) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+3) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+24-8) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+5) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+16) 
- (modified) clang/lib/Sema/SemaTemplateVariadic.cpp (+64-2) 
- (modified) clang/lib/Sema/SemaType.cpp (+60) 
- (modified) clang/lib/Sema/TreeTransform.h (+200) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+4) 
- (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+22) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+5) 
- (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+16) 
- (modified) clang/lib/StaticAnalyzer/Core/ExprEngine.cpp (+1) 
- (added) clang/test/PCH/pack_indexing.cpp (+16) 
- (added) clang/test/Parser/cxx2b-pack-indexing.cpp (+65) 
- (added) clang/test/SemaCXX/cxx2b-pack-indexing.cpp (+115) 
- (modified) clang/tools/libclang/CIndex.cpp (+8) 
- (modified) clang/tools/libclang/CXCursor.cpp (+4) 
- (modified) clang/www/cxx_status.html (+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed1a978b5382d71..dab670409077678 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -182,6 +182,8 @@ C++2c Feature Support
   This is applied to both C++ standard attributes, and other attributes 
supported by Clang.
   This completes the implementation of `P2361R6 Unevaluated Strings 
`_
 
+- Implemented `P2662R3 Pack Indexing `_.
+
 
 Resolutions to C++ Defect Reports
 ^
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 64ab3378957c702..2c0b89a0d12b21e 100644
--- a/clang/inc

[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2023-11-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-debuginfo

Author: cor3ntin (cor3ntin)


Changes

https://isocpp.org/files/papers/P2662R3.pdf

Because there is a slight chance the syntax might change slightly (see 
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2994r0.html), the 
feature is not exposed in other language modes.

---

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


69 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang-c/Index.h (+6-1) 
- (modified) clang/include/clang/AST/ASTContext.h (+8) 
- (modified) clang/include/clang/AST/ASTNodeTraverser.h (+6) 
- (modified) clang/include/clang/AST/ExprCXX.h (+106) 
- (modified) clang/include/clang/AST/RecursiveASTVisitor.h (+11) 
- (modified) clang/include/clang/AST/Type.h (+66) 
- (modified) clang/include/clang/AST/TypeLoc.h (+28) 
- (modified) clang/include/clang/AST/TypeProperties.td (+14) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+7-1) 
- (modified) clang/include/clang/Basic/Specifiers.h (+1) 
- (modified) clang/include/clang/Basic/StmtNodes.td (+1) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+2) 
- (modified) clang/include/clang/Basic/TypeNodes.td (+1) 
- (modified) clang/include/clang/Parse/Parser.h (+9) 
- (modified) clang/include/clang/Sema/DeclSpec.h (+23-2) 
- (modified) clang/include/clang/Sema/Sema.h (+25) 
- (modified) clang/include/clang/Serialization/ASTBitCodes.h (+1) 
- (modified) clang/include/clang/Serialization/TypeBitCodes.def (+2) 
- (modified) clang/lib/AST/ASTContext.cpp (+43) 
- (modified) clang/lib/AST/ASTImporter.cpp (+12) 
- (modified) clang/lib/AST/ASTStructuralEquivalence.cpp (+10) 
- (modified) clang/lib/AST/Expr.cpp (+8) 
- (modified) clang/lib/AST/ExprCXX.cpp (+37) 
- (modified) clang/lib/AST/ExprClassification.cpp (+3) 
- (modified) clang/lib/AST/ExprConstant.cpp (+7) 
- (modified) clang/lib/AST/ItaniumMangle.cpp (+9) 
- (modified) clang/lib/AST/MicrosoftMangle.cpp (+6) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+4) 
- (modified) clang/lib/AST/StmtProfile.cpp (+6) 
- (modified) clang/lib/AST/Type.cpp (+40) 
- (modified) clang/lib/AST/TypePrinter.cpp (+18) 
- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+5) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+2) 
- (modified) clang/lib/CodeGen/CGExprAgg.cpp (+3) 
- (modified) clang/lib/CodeGen/CGExprComplex.cpp (+4) 
- (modified) clang/lib/CodeGen/CGExprConstant.cpp (+4) 
- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+3) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+1) 
- (modified) clang/lib/Parse/ParseCXXInlineMethods.cpp (+14) 
- (modified) clang/lib/Parse/ParseDecl.cpp (+5) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+101) 
- (modified) clang/lib/Parse/ParseExpr.cpp (+13) 
- (modified) clang/lib/Parse/ParseExprCXX.cpp (+67-1) 
- (modified) clang/lib/Parse/ParseTentative.cpp (+13) 
- (modified) clang/lib/Parse/Parser.cpp (+2-1) 
- (modified) clang/lib/Sema/DeclSpec.cpp (+21) 
- (modified) clang/lib/Sema/SemaCXXScopeSpec.cpp (+23) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+1) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+4) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+1) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+3) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+24-8) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+5) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+16) 
- (modified) clang/lib/Sema/SemaTemplateVariadic.cpp (+64-2) 
- (modified) clang/lib/Sema/SemaType.cpp (+60) 
- (modified) clang/lib/Sema/TreeTransform.h (+200) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+4) 
- (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+22) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+5) 
- (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+16) 
- (modified) clang/lib/StaticAnalyzer/Core/ExprEngine.cpp (+1) 
- (added) clang/test/PCH/pack_indexing.cpp (+16) 
- (added) clang/test/Parser/cxx2b-pack-indexing.cpp (+65) 
- (added) clang/test/SemaCXX/cxx2b-pack-indexing.cpp (+115) 
- (modified) clang/tools/libclang/CIndex.cpp (+8) 
- (modified) clang/tools/libclang/CXCursor.cpp (+4) 
- (modified) clang/www/cxx_status.html (+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed1a978b5382d71..dab670409077678 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -182,6 +182,8 @@ C++2c Feature Support
   This is applied to both C++ standard attributes, and other attributes 
supported by Clang.
   This completes the implementation of `P2361R6 Unevaluated Strings 
`_
 
+- Implemented `P2662R3 Pack Indexing `_.
+
 
 Resolutions to C++ Defect Reports
 ^
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 64ab3378957c702..2c0b89a0d12b21e 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/includ

[clang] [Clang][C++26] Implement Pack Indexing (P2662R3). (PR #72644)

2023-11-17 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 ec42d547eba5c0ad0bddbecc8902d35383968e78 
ac0f8313637763fe0ffcaf7f45cf803babe1b65b -- clang/test/PCH/pack_indexing.cpp 
clang/test/Parser/cxx2b-pack-indexing.cpp 
clang/test/SemaCXX/cxx2b-pack-indexing.cpp clang/include/clang-c/Index.h 
clang/include/clang/AST/ASTContext.h clang/include/clang/AST/ASTNodeTraverser.h 
clang/include/clang/AST/ExprCXX.h clang/include/clang/AST/RecursiveASTVisitor.h 
clang/include/clang/AST/Type.h clang/include/clang/AST/TypeLoc.h 
clang/include/clang/Basic/Specifiers.h clang/include/clang/Parse/Parser.h 
clang/include/clang/Sema/DeclSpec.h clang/include/clang/Sema/Sema.h 
clang/include/clang/Serialization/ASTBitCodes.h clang/lib/AST/ASTContext.cpp 
clang/lib/AST/ASTImporter.cpp clang/lib/AST/ASTStructuralEquivalence.cpp 
clang/lib/AST/Expr.cpp clang/lib/AST/ExprCXX.cpp 
clang/lib/AST/ExprClassification.cpp clang/lib/AST/ExprConstant.cpp 
clang/lib/AST/ItaniumMangle.cpp clang/lib/AST/MicrosoftMangle.cpp 
clang/lib/AST/StmtPrinter.cpp clang/lib/AST/StmtProfile.cpp 
clang/lib/AST/Type.cpp clang/lib/AST/TypePrinter.cpp 
clang/lib/CodeGen/CGDebugInfo.cpp clang/lib/CodeGen/CGExpr.cpp 
clang/lib/CodeGen/CGExprAgg.cpp clang/lib/CodeGen/CGExprComplex.cpp 
clang/lib/CodeGen/CGExprConstant.cpp clang/lib/CodeGen/CGExprScalar.cpp 
clang/lib/CodeGen/CodeGenFunction.cpp clang/lib/Parse/ParseCXXInlineMethods.cpp 
clang/lib/Parse/ParseDecl.cpp clang/lib/Parse/ParseDeclCXX.cpp 
clang/lib/Parse/ParseExpr.cpp clang/lib/Parse/ParseExprCXX.cpp 
clang/lib/Parse/ParseTentative.cpp clang/lib/Parse/Parser.cpp 
clang/lib/Sema/DeclSpec.cpp clang/lib/Sema/SemaCXXScopeSpec.cpp 
clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaDeclCXX.cpp 
clang/lib/Sema/SemaExceptionSpec.cpp clang/lib/Sema/SemaExpr.cpp 
clang/lib/Sema/SemaExprCXX.cpp clang/lib/Sema/SemaTemplate.cpp 
clang/lib/Sema/SemaTemplateDeduction.cpp 
clang/lib/Sema/SemaTemplateVariadic.cpp clang/lib/Sema/SemaType.cpp 
clang/lib/Sema/TreeTransform.h clang/lib/Serialization/ASTReader.cpp 
clang/lib/Serialization/ASTReaderStmt.cpp clang/lib/Serialization/ASTWriter.cpp 
clang/lib/Serialization/ASTWriterStmt.cpp 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp clang/tools/libclang/CIndex.cpp 
clang/tools/libclang/CXCursor.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Basic/Specifiers.h 
b/clang/include/clang/Basic/Specifiers.h
index bff4c1616c..54ef5dd634 100644
--- a/clang/include/clang/Basic/Specifiers.h
+++ b/clang/include/clang/Basic/Specifiers.h
@@ -79,14 +79,14 @@ namespace clang {
 TST_enum,
 TST_union,
 TST_struct,
-TST_class, // C++ class type
-TST_interface, // C++ (Microsoft-specific) __interface type
-TST_typename,  // Typedef, C++ class-name or enum name, etc.
+TST_class, // C++ class type
+TST_interface, // C++ (Microsoft-specific) __interface type
+TST_typename,  // Typedef, C++ class-name or enum name, etc.
 TST_typeofType,// C23 (and GNU extension) typeof(type-name)
 TST_typeofExpr,// C23 (and GNU extension) typeof(expression)
 TST_typeof_unqualType, // C23 typeof_unqual(type-name)
 TST_typeof_unqualExpr, // C23 typeof_unqual(expression)
-TST_decltype, // C++11 decltype
+TST_decltype,  // C++11 decltype
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
 #include "clang/Basic/TransformTypeTraits.def"
 TST_auto,// C++11 auto
@@ -95,7 +95,8 @@ namespace clang {
 TST_unknown_anytype, // __unknown_anytype extension
 TST_atomic,  // C11 _Atomic
 TST_indexed_typename_pack,
-#define GENERIC_IMAGE_TYPE(ImgType, Id) TST_##ImgType##_t, // OpenCL image 
types
+#define GENERIC_IMAGE_TYPE(ImgType, Id)  \
+TST_##ImgType##_t, // OpenCL image types
 #include "clang/Basic/OpenCLImageTypes.def"
 TST_error // erroneous type
   };

``




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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,109 @@
+//===--- UseStartsEndsWithCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStartsEndsWithCheck.h"
+
+#include "../utils/OptionsUtils.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name,
+   ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {}
+
+void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
+  const auto ZeroLiteral = integerLiteral(equals(0));
+  const auto HasStartsWithMethod = anyOf(
+  hasMethod(cxxMethodDecl(hasName("starts_with")).bind("starts_with_fun")),
+  hasMethod(cxxMethodDecl(hasName("startsWith")).bind("starts_with_fun")),
+  hasMethod(cxxMethodDecl(hasName("startswith")).bind("starts_with_fun")));
+  const auto ClassWithStartsWithFunction = cxxRecordDecl(anyOf(
+  HasStartsWithMethod, hasAnyBase(hasType(hasCanonicalType(hasDeclaration(
+   cxxRecordDecl(HasStartsWithMethod)));
+
+  const auto FindExpr = cxxMemberCallExpr(
+  // .find() call...
+  callee(cxxMethodDecl(hasName("find")).bind("find_fun")),
+  // ... on a class with a starts_with function...
+  on(hasType(
+  hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction,
+  // ... and either "0" as second argument or the default argument (also 
0).
+  anyOf(hasArgument(1, ZeroLiteral), argumentCountIs(1)));

PiotrZSL wrote:

consider putting this anyOf first, to exclude lot of calls that have more than 
1 argument

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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,151 @@
+// RUN: %check_clang_tidy -std=c++20 %s performance-use-starts-ends-with %t -- 
\
+// RUN:   -- -isystem %clang_tidy_headers
+
+#include 
+
+std::string foo(std::string);
+std::string bar();
+
+#define A_MACRO(x, y) ((x) == (y))
+#define STR(x) std::string(x)
+
+class sub_string : public std::string {};
+class sub_sub_string : public sub_string {};
+
+struct string_like {
+  bool starts_with(const char *s) const;
+  size_t find(const char *s, size_t pos = 0) const;
+};
+
+struct string_like_camel {
+  bool startsWith(const char *s) const;
+  size_t find(const char *s, size_t pos = 0) const;
+};
+
+struct prefer_underscore_version {
+  bool starts_with(const char *s) const;
+  bool startsWith(const char *s) const;
+  size_t find(const char *s, size_t pos = 0) const;
+};
+
+struct prefer_underscore_version_flip {
+  bool startsWith(const char *s) const;
+  bool starts_with(const char *s) const;
+  size_t find(const char *s, size_t pos = 0) const;
+};
+
+struct prefer_underscore_version_inherit : public string_like {
+  bool startsWith(const char *s) const;
+};
+
+void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string 
sss,
+  string_like sl, string_like_camel slc, prefer_underscore_version puv,
+  prefer_underscore_version_flip puvf,
+  prefer_underscore_version_inherit puvi) {
+  s.find("a") == 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead 
of find() == 0
+  // CHECK-FIXES: s.starts_with("a");
+
+  s.find(s) == 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: s.starts_with(s);
+
+  s.find("aaa") != 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with("aaa");
+
+  s.find(foo(foo(bar( != 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with(foo(foo(bar(;
+
+  if (s.find("") == 0) { /* do something */ }
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: if (s.starts_with(""))
+
+  0 != s.find("a");
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with("a");
+
+  s.rfind("a", 0) == 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead 
of rfind() == 0
+  // CHECK-FIXES: s.starts_with("a");
+
+  s.rfind(s, 0) == 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: s.starts_with(s);
+
+  s.rfind("aaa", 0) != 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with("aaa");
+
+  s.rfind(foo(foo(bar())), 0) != 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with(foo(foo(bar(;
+
+  if (s.rfind("", 0) == 0) { /* do something */ }
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: if (s.starts_with(""))
+
+  0 != s.rfind("a", 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: !s.starts_with("a");
+
+  0 == STR(s).find("a");
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with
+  // CHECK-FIXES: STR(s).starts_with("a");
+
+  #define STR str
+  std::string STR;
+  if (0 == STR.find("ala")) { /* do something */}

PiotrZSL wrote:

Add few more test withs macros:
- method name under macro
- argument under macro
- 0 under macro
- operator under macro  - #define EQ(x,y) (x) == (y)


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


[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

2023-11-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,37 @@
+//===--- UseStartsEndsWithCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_USESTARTSENDSWITHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_USESTARTSENDSWITHCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::performance {
+
+/// Checks whether a ``find`` or ``rfind`` result is compared with 0 and
+/// suggests replacing with ``starts_with`` when the method exists in the 
class.
+/// Notably, this will work with ``std::string`` and ``std::string_view``.
+///
+/// For the user-facing documentation see:
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/performance/use-starts-ends-with.html
+class UseStartsEndsWithCheck : public ClangTidyCheck {
+public:
+  UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context);
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus20;

PiotrZSL wrote:

We may not need this limitation anymore...
Simply llvm::StringRef will also work, and that's C++17.

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


  1   2   3   4   >