[PATCH] D147686: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:450
+void test() {
+  1s;
+}

hokein wrote:
> here is the `UserDefinedLiteral` AST node:
> 
> ```
> `-UserDefinedLiteral 0x5556682e4500  'int'
>   |-ImplicitCastExpr 0x5556682e44e8  'int (*)(unsigned long long)' 
> 
>   | `-DeclRefExpr 0x5556682e44a0  'int (unsigned long long)' 
> lvalue Function 0x5556682e4290 'operator""s' 'int (unsigned long long)'
>   `-IntegerLiteral 0x5556682e4480  'unsigned long long' 1
> ```
> 
> The source location of the `UserDefinedLiteral` points to `^1s`, while the 
> source location of the inner `DeclRefExpr` points to `1^s` (1 offset shift). 
> In the token buffer, we only have a single spelled token `1s`, thus 
> `AST.getTokens().spelledTokenAt` can not find any token that starts at `1^s` 
> source loc.
thanks, that makes sense!

then instead of "suppressing" these, can we use 
`spelledTokensTouching().front()` (and asserting that it isn't empty?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147686

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


[clang] fd8745c - [clang] Do not require GNUInlineAttr for inline builtins

2023-04-13 Thread via cfe-commits

Author: serge-sans-paille
Date: 2023-04-13T09:03:58+02:00
New Revision: fd8745c252bcd4bc974ce3ff30c19f1cc5c4e3e0

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

LOG: [clang] Do not require GNUInlineAttr for inline builtins

Fix #61691

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

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/test/CodeGen/memcpy-inline-builtin.c
clang/test/CodeGen/pr9614.c

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index cbee553715f5e..bf41262f0641b 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -3302,8 +3302,7 @@ bool FunctionDecl::isInlineBuiltinDeclaration() const {
 
   const FunctionDecl *Definition;
   return hasBody(Definition) && Definition->isInlineSpecified() &&
- Definition->hasAttr() &&
- Definition->hasAttr();
+ Definition->hasAttr();
 }
 
 bool FunctionDecl::isDestroyingOperatorDelete() const {

diff  --git a/clang/test/CodeGen/memcpy-inline-builtin.c 
b/clang/test/CodeGen/memcpy-inline-builtin.c
index cb126ec7f9417..8fce67a81a405 100644
--- a/clang/test/CodeGen/memcpy-inline-builtin.c
+++ b/clang/test/CodeGen/memcpy-inline-builtin.c
@@ -3,18 +3,27 @@
 // RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -o - %s | FileCheck %s
 //
 // Verifies that clang detects memcpy inline version and uses it instead of 
the builtin.
+// Checks alternate version with the `artificial` attribute.
 
 typedef unsigned long size_t;
 
 // Clang requires these attributes for a function to be redefined.
 #define AVAILABLE_EXTERNALLY extern inline __attribute__((always_inline)) 
__attribute__((gnu_inline))
 
+#define AVAILABLE_EXTERNALLY_ALTERNATE extern inline 
__attribute__((__always_inline__)) __attribute__((__artificial__))
+
 // Clang recognizes an inline builtin and renames it to prevent conflict with 
builtins.
 AVAILABLE_EXTERNALLY void *memcpy(void *a, const void *b, size_t c) {
   asm("# memcpy.inline marker");
   return __builtin_memcpy(a, b, c);
 }
 
+// Clang recognizes an inline builtin and renames it to prevent conflict with 
builtins.
+AVAILABLE_EXTERNALLY_ALTERNATE void *memmove(void *a, const void *b, size_t c) 
{
+  asm("# memmove.inline marker");
+  return __builtin_memmove(a, b, c);
+}
+
 // CHECK-LABEL: @foo(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[A_ADDR_I:%.*]] = alloca ptr, align 8
@@ -43,6 +52,34 @@ void *foo(void *a, const void *b, size_t c) {
   return memcpy(a, b, c);
 }
 
+// CHECK-LABEL: @foo_alt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR_I:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR_I:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR_I:%.*]] = alloca i64, align 8
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR:%.*]] = alloca i64, align 8
+// CHECK-NEXT:store ptr [[A:%.*]], ptr [[A_ADDR]], align 8
+// CHECK-NEXT:store ptr [[B:%.*]], ptr [[B_ADDR]], align 8
+// CHECK-NEXT:store i64 [[C:%.*]], ptr [[C_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[B_ADDR]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = load i64, ptr [[C_ADDR]], align 8
+// CHECK-NEXT:store ptr [[TMP0]], ptr [[A_ADDR_I]], align 8
+// CHECK-NEXT:store ptr [[TMP1]], ptr [[B_ADDR_I]], align 8
+// CHECK-NEXT:store i64 [[TMP2]], ptr [[C_ADDR_I]], align 8
+// CHECK-NEXT:call void asm sideeffect "# memmove.inline marker", 
"~{dirflag},~{fpsr},~{flags}"() #[[ATTR3]], !srcloc !3
+// CHECK-NEXT:[[TMP3:%.*]] = load ptr, ptr [[A_ADDR_I]], align 8
+// CHECK-NEXT:[[TMP4:%.*]] = load ptr, ptr [[B_ADDR_I]], align 8
+// CHECK-NEXT:[[TMP5:%.*]] = load i64, ptr [[C_ADDR_I]], align 8
+// CHECK-NEXT:call void @llvm.memmove.p0.p0.i64(ptr align 1 [[TMP3]], ptr 
align 1 [[TMP4]], i64 [[TMP5]], i1 false)
+// CHECK-NEXT:ret ptr [[TMP3]]
+//
+void *foo_alt(void *a, const void *b, size_t c) {
+  return memmove(a, b, c);
+}
+
 // CHECK-LABEL: @bar(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
@@ -68,3 +105,29 @@ void bar(void *a, const void *b, size_t c) {
   void *(*cpy)(void *, const void *, size_t) = c > 10 ? memcpy : foo;
   cpy(a, b, c);
 }
+
+// CHECK-LABEL: @bar_alt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR:%.*]] = alloca i64, align 8
+// CHECK-NEXT:[[CPY:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:store ptr [[A:%.*]], ptr [[A_ADDR]], align 8
+// CHECK-NEXT:store ptr [[B:%.*]], ptr [[B_ADDR]], align 8
+// CHECK-NEXT:store i64 [[C:%.*]], ptr [[C_ADDR]], align 8
+// CHECK-NEXT:

[PATCH] D147307: [clang] Do not require GNUInlineAttr for inline builtins

2023-04-13 Thread serge via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd8745c252bc: [clang] Do not require GNUInlineAttr for 
inline builtins (authored by serge-sans-paille).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147307

Files:
  clang/lib/AST/Decl.cpp
  clang/test/CodeGen/memcpy-inline-builtin.c
  clang/test/CodeGen/pr9614.c

Index: clang/test/CodeGen/pr9614.c
===
--- clang/test/CodeGen/pr9614.c
+++ clang/test/CodeGen/pr9614.c
@@ -32,7 +32,7 @@
 
 // CHECK-LABEL: define{{.*}} void @f()
 // CHECK: call void @foo()
-// CHECK: call i32 @abs(i32 noundef 0)
+// CHECK: call i32 @abs(i32 noundef %0)
 // CHECK: call ptr @strrchr(
 // CHECK: call void @llvm.prefetch.p0(
 // CHECK: call ptr @memchr(
Index: clang/test/CodeGen/memcpy-inline-builtin.c
===
--- clang/test/CodeGen/memcpy-inline-builtin.c
+++ clang/test/CodeGen/memcpy-inline-builtin.c
@@ -3,18 +3,27 @@
 // RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -o - %s | FileCheck %s
 //
 // Verifies that clang detects memcpy inline version and uses it instead of the builtin.
+// Checks alternate version with the `artificial` attribute.
 
 typedef unsigned long size_t;
 
 // Clang requires these attributes for a function to be redefined.
 #define AVAILABLE_EXTERNALLY extern inline __attribute__((always_inline)) __attribute__((gnu_inline))
 
+#define AVAILABLE_EXTERNALLY_ALTERNATE extern inline __attribute__((__always_inline__)) __attribute__((__artificial__))
+
 // Clang recognizes an inline builtin and renames it to prevent conflict with builtins.
 AVAILABLE_EXTERNALLY void *memcpy(void *a, const void *b, size_t c) {
   asm("# memcpy.inline marker");
   return __builtin_memcpy(a, b, c);
 }
 
+// Clang recognizes an inline builtin and renames it to prevent conflict with builtins.
+AVAILABLE_EXTERNALLY_ALTERNATE void *memmove(void *a, const void *b, size_t c) {
+  asm("# memmove.inline marker");
+  return __builtin_memmove(a, b, c);
+}
+
 // CHECK-LABEL: @foo(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[A_ADDR_I:%.*]] = alloca ptr, align 8
@@ -43,6 +52,34 @@
   return memcpy(a, b, c);
 }
 
+// CHECK-LABEL: @foo_alt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR_I:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR_I:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR_I:%.*]] = alloca i64, align 8
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR:%.*]] = alloca i64, align 8
+// CHECK-NEXT:store ptr [[A:%.*]], ptr [[A_ADDR]], align 8
+// CHECK-NEXT:store ptr [[B:%.*]], ptr [[B_ADDR]], align 8
+// CHECK-NEXT:store i64 [[C:%.*]], ptr [[C_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[B_ADDR]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = load i64, ptr [[C_ADDR]], align 8
+// CHECK-NEXT:store ptr [[TMP0]], ptr [[A_ADDR_I]], align 8
+// CHECK-NEXT:store ptr [[TMP1]], ptr [[B_ADDR_I]], align 8
+// CHECK-NEXT:store i64 [[TMP2]], ptr [[C_ADDR_I]], align 8
+// CHECK-NEXT:call void asm sideeffect "# memmove.inline marker", "~{dirflag},~{fpsr},~{flags}"() #[[ATTR3]], !srcloc !3
+// CHECK-NEXT:[[TMP3:%.*]] = load ptr, ptr [[A_ADDR_I]], align 8
+// CHECK-NEXT:[[TMP4:%.*]] = load ptr, ptr [[B_ADDR_I]], align 8
+// CHECK-NEXT:[[TMP5:%.*]] = load i64, ptr [[C_ADDR_I]], align 8
+// CHECK-NEXT:call void @llvm.memmove.p0.p0.i64(ptr align 1 [[TMP3]], ptr align 1 [[TMP4]], i64 [[TMP5]], i1 false)
+// CHECK-NEXT:ret ptr [[TMP3]]
+//
+void *foo_alt(void *a, const void *b, size_t c) {
+  return memmove(a, b, c);
+}
+
 // CHECK-LABEL: @bar(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
@@ -68,3 +105,29 @@
   void *(*cpy)(void *, const void *, size_t) = c > 10 ? memcpy : foo;
   cpy(a, b, c);
 }
+
+// CHECK-LABEL: @bar_alt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[C_ADDR:%.*]] = alloca i64, align 8
+// CHECK-NEXT:[[CPY:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:store ptr [[A:%.*]], ptr [[A_ADDR]], align 8
+// CHECK-NEXT:store ptr [[B:%.*]], ptr [[B_ADDR]], align 8
+// CHECK-NEXT:store i64 [[C:%.*]], ptr [[C_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[C_ADDR]], align 8
+// CHECK-NEXT:[[CMP:%.*]] = icmp ugt i64 [[TMP0]], 10
+// CHECK-NEXT:[[TMP1:%.*]] = zext i1 [[CMP]] to i64
+// CHECK-NEXT:[[COND:%.*]] = select i1 [[CMP]], ptr @memmove, ptr @foo_alt
+// CHECK-NEXT:store ptr [[COND]], ptr [[CPY]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[CPY]], align 8
+// CHECK-NEXT:[[TMP3:%.*]] = load ptr, ptr [[A_A

[clang] c1f7636 - [C++20] [Modules] Continue parsing after we found reserved module names

2023-04-13 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-04-13T15:14:34+08:00
New Revision: c1f76363e0db41ab6eb9ebedd687ee098491e9b7

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

LOG: [C++20] [Modules] Continue parsing after we found reserved module names

Close https://github.com/llvm/llvm-project/issues/62112

In the previous change, we'll stop parsing directly after we found
reserved module names. But this may be too aggressive. This patch
changes this. Note that the parsing will still be stopped if the module
name is `module` or `import`.

Added: 
clang/test/Modules/reserved-names-1.cppm
clang/test/Modules/reserved-names-2.cppm
clang/test/Modules/reserved-names-3.cppm
clang/test/Modules/reserved-names-4.cppm

Modified: 
clang/lib/Sema/SemaModule.cpp

Removed: 
clang/test/Modules/reserved-names-1.cpp
clang/test/Modules/reserved-names-2.cpp
clang/test/Modules/reserved-names-3.cpp
clang/test/Modules/reserved-names-4.cpp



diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index 6c39cc0b44ca4..84a1fd854d804 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -162,7 +162,8 @@ static bool DiagReservedModuleName(Sema &S, const 
IdentifierInfo *II,
   case Invalid:
 return S.Diag(Loc, diag::err_invalid_module_name) << II;
   case Reserved:
-return S.Diag(Loc, diag::warn_reserved_module_name) << II;
+S.Diag(Loc, diag::warn_reserved_module_name) << II;
+return false;
   }
   llvm_unreachable("fell off a fully covered switch");
 }
@@ -267,10 +268,8 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, 
SourceLocation ModuleLoc,
   if (!getSourceManager().isInSystemHeader(Path[0].second) &&
   (FirstComponentName == "std" ||
(FirstComponentName.startswith("std") &&
-llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit {
+llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit
 Diag(Path[0].second, diag::warn_reserved_module_name) << Path[0].first;
-return nullptr;
-  }
 
   // Then test all of the components in the path to see if any of them are
   // using another kind of reserved or invalid identifier.

diff  --git a/clang/test/Modules/reserved-names-1.cpp 
b/clang/test/Modules/reserved-names-1.cpp
deleted file mode 100644
index a92c2244f1cb6..0
--- a/clang/test/Modules/reserved-names-1.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,loud %s
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected 
-Wno-reserved-module-identifier %s
-
-// expected-note@1 15{{add 'module;' to the start of the file to introduce a 
global module fragment}}
-
-module std;// loud-warning {{'std' is a reserved name for a module}}
-module _Test;  // loud-warning {{'_Test' is a reserved name for a module}} \
-  expected-error {{module declaration must occur at the start 
of the translation unit}}
-module module; // expected-error {{'module' is an invalid name for a module}} \
-  expected-error {{module declaration must occur at the start 
of the translation unit}}
-module std0;   // loud-warning {{'std0' is a reserved name for a module}} \
-  expected-error {{module declaration must occur at the start 
of the translation unit}}
-
-export module module; // expected-error {{'module' is an invalid name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module import; // expected-error {{'import' is an invalid name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module _Test;  // loud-warning {{'_Test' is a reserved name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module __test; // loud-warning {{'__test' is a reserved name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module te__st; // loud-warning {{'te__st' is a reserved name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module std;// loud-warning {{'std' is a reserved name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module std.foo;// loud-warning {{'std' is a reserved name for a 
module}} \
- expected-error {{module declaration must occur at the 
start of the translation unit}}
-export module std0;   // loud-warning {{'std0' is a reserved name f

[clang] 9d0b55f - [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-13 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2023-04-13T09:25:12+02:00
New Revision: 9d0b55f0e4ca55d04ee8abfdf021913ea3c30082

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

LOG: [clang][ASTImporter] Fix import of typedef with unnamed structures

Fix crash in ASTImporter related to import of unnamed structures and typedefs
to these maybe with pointer.
There was a series of problems exposed by https://reviews.llvm.org/D133468
(commit 69a6417406a1b0316a1fa6aeb63339d0e1d2abbd) in the ASTImporter breaking
cross-translation unit analysis. This change fixes one of the problems exposed
by that change for importing unnamed structures. The problem was
discovered when running clang static analysis on open source projects
using cross-translation unit analysis.

Simple test command. Produces crash without change, passes all tests
with change.

```
ninja ASTTests && ./tools/clang/unittests/AST/ASTTests
  --gtest_filter="*/*ImportAnonymousStruct/0"
```

Formatted crash stack:

```
ASTTests: /clang/lib/AST/ASTContext.cpp:4787:
  clang::QualType clang::ASTContext::getTypedefType(const 
clang::TypedefNameDecl*,
  clang::QualType) const: Assertion `hasSameType(Decl->getUnderlyingType(), 
Underlying)' failed.
...
 #9  clang::ASTContext::getTypedefType(clang::TypedefNameDecl const*, 
clang::QualType) const
 /clang/lib/AST/ASTContext.cpp:4789:26
 /clang/lib/AST/ASTImporter.cpp:1374:71
 /tools/clang/include/clang/AST/TypeNodes.inc:75:1
 /clang/lib/AST/ASTImporter.cpp:8663:8
```

Reviewed By: donat.nagy

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

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 337c14a0038ce..320c302f7492c 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -1365,12 +1365,16 @@ ExpectedType ASTNodeImporter::VisitTypedefType(const 
TypedefType *T) {
   Expected ToDeclOrErr = import(T->getDecl());
   if (!ToDeclOrErr)
 return ToDeclOrErr.takeError();
+
+  TypedefNameDecl *ToDecl = *ToDeclOrErr;
+  if (ToDecl->getTypeForDecl())
+return QualType(ToDecl->getTypeForDecl(), 0);
+
   ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
   if (!ToUnderlyingTypeOrErr)
 return ToUnderlyingTypeOrErr.takeError();
 
-  return Importer.getToContext().getTypedefType(*ToDeclOrErr,
-*ToUnderlyingTypeOrErr);
+  return Importer.getToContext().getTypedefType(ToDecl, 
*ToUnderlyingTypeOrErr);
 }
 
 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index ebdb81b98734a..b90a18d539668 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -8576,6 +8576,69 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportTwoTypedefsToUnnamedRecord) {
 Typedef2->getUnderlyingType().getTypePtr());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportExistingTypedefToUnnamedRecordPtr) {
+  const char *Code =
+  R"(
+  typedef const struct { int fff; } * const T;
+  extern T x;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_C99);
+  Decl *FromTU = getTuDecl(Code, Lang_C99);
+
+  auto *FromX =
+  FirstDeclMatcher().match(FromTU, varDecl(hasName("x")));
+  auto *ToX = Import(FromX, Lang_C99);
+  EXPECT_TRUE(ToX);
+
+  auto *Typedef1 =
+  FirstDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  auto *Typedef2 =
+  LastDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  // FIXME: These should be imported separately, like in the test above.
+  // Or: In the test above these should be merged too.
+  EXPECT_EQ(Typedef1, Typedef2);
+
+  auto *FromR = FirstDeclMatcher().match(
+  FromTU, recordDecl(hasDescendant(fieldDecl(hasName("fff");
+  auto *ToRExisting = FirstDeclMatcher().match(
+  ToTU, recordDecl(hasDescendant(fieldDecl(hasName("fff");
+  ASSERT_TRUE(FromR);
+  auto *ToRImported = Import(FromR, Lang_C99);
+  // FIXME: If typedefs are not imported separately, do not import ToRImported
+  // separately.
+  EXPECT_NE(ToRExisting, ToRImported);
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTypedefWithDifferentUnderlyingType) {
+  const char *Code =
+  R"(
+  using X1 = int;
+  using Y1 = int;
+
+  using RPB1 = X1*;
+  typedef RPB1 RPX1;
+  using RPB1 = Y1*; // redeclared
+  typedef RPB1 RPY1;
+
+  auto X = 0 ? (RPX1){} : (RPY1){};
+  )";
+  Decl *ToTU = getToTuDecl("", Lang_CXX11);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);
+
+  auto *FromX =
+  FirstD

[PATCH] D145868: [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-13 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9d0b55f0e4ca: [clang][ASTImporter] Fix import of typedef 
with unnamed structures (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145868

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8576,6 +8576,69 @@
 Typedef2->getUnderlyingType().getTypePtr());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportExistingTypedefToUnnamedRecordPtr) {
+  const char *Code =
+  R"(
+  typedef const struct { int fff; } * const T;
+  extern T x;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_C99);
+  Decl *FromTU = getTuDecl(Code, Lang_C99);
+
+  auto *FromX =
+  FirstDeclMatcher().match(FromTU, varDecl(hasName("x")));
+  auto *ToX = Import(FromX, Lang_C99);
+  EXPECT_TRUE(ToX);
+
+  auto *Typedef1 =
+  FirstDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  auto *Typedef2 =
+  LastDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  // FIXME: These should be imported separately, like in the test above.
+  // Or: In the test above these should be merged too.
+  EXPECT_EQ(Typedef1, Typedef2);
+
+  auto *FromR = FirstDeclMatcher().match(
+  FromTU, recordDecl(hasDescendant(fieldDecl(hasName("fff");
+  auto *ToRExisting = FirstDeclMatcher().match(
+  ToTU, recordDecl(hasDescendant(fieldDecl(hasName("fff");
+  ASSERT_TRUE(FromR);
+  auto *ToRImported = Import(FromR, Lang_C99);
+  // FIXME: If typedefs are not imported separately, do not import ToRImported
+  // separately.
+  EXPECT_NE(ToRExisting, ToRImported);
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTypedefWithDifferentUnderlyingType) {
+  const char *Code =
+  R"(
+  using X1 = int;
+  using Y1 = int;
+
+  using RPB1 = X1*;
+  typedef RPB1 RPX1;
+  using RPB1 = Y1*; // redeclared
+  typedef RPB1 RPY1;
+
+  auto X = 0 ? (RPX1){} : (RPY1){};
+  )";
+  Decl *ToTU = getToTuDecl("", Lang_CXX11);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);
+
+  auto *FromX =
+  FirstDeclMatcher().match(FromTU, varDecl(hasName("X")));
+
+  auto *FromXType = FromX->getType()->getAs();
+  EXPECT_FALSE(FromXType->typeMatchesDecl());
+
+  auto *ToX = Import(FromX, Lang_CXX11);
+  auto *ToXType = ToX->getType()->getAs();
+  // FIXME: This should be false.
+  EXPECT_TRUE(ToXType->typeMatchesDecl());
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -1365,12 +1365,16 @@
   Expected ToDeclOrErr = import(T->getDecl());
   if (!ToDeclOrErr)
 return ToDeclOrErr.takeError();
+
+  TypedefNameDecl *ToDecl = *ToDeclOrErr;
+  if (ToDecl->getTypeForDecl())
+return QualType(ToDecl->getTypeForDecl(), 0);
+
   ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
   if (!ToUnderlyingTypeOrErr)
 return ToUnderlyingTypeOrErr.takeError();
 
-  return Importer.getToContext().getTypedefType(*ToDeclOrErr,
-*ToUnderlyingTypeOrErr);
+  return Importer.getToContext().getTypedefType(ToDecl, 
*ToUnderlyingTypeOrErr);
 }
 
 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8576,6 +8576,69 @@
 Typedef2->getUnderlyingType().getTypePtr());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportExistingTypedefToUnnamedRecordPtr) {
+  const char *Code =
+  R"(
+  typedef const struct { int fff; } * const T;
+  extern T x;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_C99);
+  Decl *FromTU = getTuDecl(Code, Lang_C99);
+
+  auto *FromX =
+  FirstDeclMatcher().match(FromTU, varDecl(hasName("x")));
+  auto *ToX = Import(FromX, Lang_C99);
+  EXPECT_TRUE(ToX);
+
+  auto *Typedef1 =
+  FirstDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  auto *Typedef2 =
+  LastDeclMatcher().match(ToTU, typedefDecl(hasName("T")));
+  // FIXME: These should be imported separately, like in the test above.
+  // Or: In the test above these should be merged too.
+  EXPECT_EQ(Typedef1, Typedef2);
+
+  auto *FromR = FirstDeclMatcher().match(
+  FromTU, recordDecl(hasDescendant(fieldDecl(hasName("fff");
+  auto *ToRExisting = FirstDeclMatcher().match(
+  ToTU, recordDec

[PATCH] D148200: [clang-format] Correctly handle "// clang-format off" above macros

2023-04-13 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: MyDeveloperDay, HazardyKnusperkeks, rymiel.
owenpan added a project: clang-format.
Herald added projects: All, clang.
Herald added a subscriber: cfe-commits.
owenpan requested review of this revision.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148200

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestComments.cpp


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -1059,6 +1059,13 @@
"#endif\n"
"  }\n"
"}"));
+
+  const StringRef Code("void func() {\n"
+   "  // clang-format off\n"
+   "  #define KV(value) #value, value\n"
+   "  // clang-format on\n"
+   "}");
+  EXPECT_EQ(Code, format(Code));
 }
 
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2975,8 +2975,8 @@
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && Line->isComment() &&
-NextNonCommentLine->First->NewlinesBefore <= 1 &&
+if (NextNonCommentLine && !NextNonCommentLine->First->Finalized &&
+Line->isComment() && NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {
   const bool PPDirectiveOrImportStmt =


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -1059,6 +1059,13 @@
"#endif\n"
"  }\n"
"}"));
+
+  const StringRef Code("void func() {\n"
+   "  // clang-format off\n"
+   "  #define KV(value) #value, value\n"
+   "  // clang-format on\n"
+   "}");
+  EXPECT_EQ(Code, format(Code));
 }
 
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2975,8 +2975,8 @@
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && Line->isComment() &&
-NextNonCommentLine->First->NewlinesBefore <= 1 &&
+if (NextNonCommentLine && !NextNonCommentLine->First->Finalized &&
+Line->isComment() && NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {
   const bool PPDirectiveOrImportStmt =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147520: Fix a time-trace issue of incorrect header hierarchy when a header contains a template function for its last symbol.

2023-04-13 Thread Ying Yi via Phabricator via cfe-commits
MaggieYi added a comment.

Gentle ping ...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147520

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

Thank you for the reports and revert, I will dig into it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D146941: [clangd] Use all inputs to SystemIncludeExtractor in cache key

2023-04-13 Thread Nathan Ridge via Phabricator via cfe-commits
nridge accepted this revision.
nridge added a comment.
This revision is now accepted and ready to land.

Thanks!

Do you have any thoughts on merging D147905  
first, with a view to backporting D147905  to 
the 16.x branch?




Comment at: clang-tools-extra/clangd/SystemIncludeExtractor.cpp:81
+struct DriverArgs {
+  // Name of the driver prgoram to execute or absolute path to it.
+  std::string Driver;

nit: typo ("prgoram")


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146941

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


[PATCH] D145868: [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-13 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:8627
+  )";
+  Decl *ToTU = getToTuDecl("", Lang_CXX11);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);

With Werror we get:

```
../../clang/unittests/AST/ASTImporterTest.cpp:8627:9: error: unused variable 
'ToTU' [-Werror,-Wunused-variable]
  Decl *ToTU = getToTuDecl("", Lang_CXX11);
^

```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145868

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


[PATCH] D147905: [clangd] Avoid passing -xobjective-c++-header to the system include extractor

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/SystemIncludeExtractor.cpp:340
+// is not installed.
+if (Lang == "objective-c++-header") {
+  Lang = "c++-header";

this feels like too much of a layering violation and might (will?) go wrong in 
cases where language was explicitly set to `objective-c++-header`.

if the user is relying on fallback commands with an overwrite of `Compiler:` in 
the config && --query-driver globs, would it be too much of a hassle to expect 
them to have a `CompileFlags: Add: ...` block too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147905

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


[PATCH] D146941: [clangd] Use all inputs to SystemIncludeExtractor in cache key

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 513098.
kadircet marked an inline comment as done.
kadircet added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146941

Files:
  clang-tools-extra/clangd/SystemIncludeExtractor.cpp
  clang-tools-extra/clangd/test/system-include-extractor.test

Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -14,8 +14,8 @@
 # Check that clangd preserves certain flags like `-nostdinc` from
 # original invocation in compile_commands.json.
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> %t.dir/bin/my_driver.sh
-# RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"-isysroot /isysroot"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> %t.dir/bin/my_driver.sh
@@ -32,7 +32,7 @@
 
 # Generate a compile_commands.json that will query the mock driver we've
 # created. Which should add a.h and b.h into include search path.
-# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # RUN: sed -e "s|INPUT_DIR|%/t.dir|g" %s > %t.test.1
 # On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
@@ -70,7 +70,7 @@
 {"jsonrpc":"2.0","method":"exit"}
 
 # Generate a different compile_commands.json which does not point to the mock driver
-# RUN: echo '[{"directory": "%/t.dir", "command": "gcc the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "gcc the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # Generate a clangd config file which points to the mock driver instead
 # RUN: echo 'CompileFlags:' > %t.dir/.clangd
Index: clang-tools-extra/clangd/SystemIncludeExtractor.cpp
===
--- clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -32,32 +32,44 @@
 #include "CompileCommands.h"
 #include "GlobalCompilationDatabase.h"
 #include "support/Logger.h"
-#include "support/Path.h"
+#include "support/Threading.h"
 #include "support/Trace.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Driver/Types.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/ScopedPrinter.h"
-#include 
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
 #include 
-#include 
+#include 
 #include 
 #include 
+#include 
+#include 
 #include 
 
-namespace clang {
-namespace clangd {
+namespace clang::clangd {
 namespace {
 
 struct DriverInfo {
@@ -65,12 +77,138 @@
   std::string Target;
 };
 
+struct DriverArgs {
+  // Name of the driver program to execute or absolute path to it.
+  std::string Driver;
+  // Whether certain includes should be part of query.
+  bool StandardIncludes = true;
+  bool StandardCXXIncludes = true;
+  bool BuiltinIncludes = true;
+  // Language to use while querying.
+  std::string Lang;
+  std::string Sysroot;
+  std::string ISysroot;
+
+  bool operator==(const DriverArgs &RHS) const {
+return std::tie(Driver, StandardIncludes, StandardCXXIncludes,
+BuiltinIncludes, Lang, Sysroot, ISysroot) ==
+   std::tie(RHS.Driver, RHS.StandardIncludes, RHS.StandardCXXIncludes,
+ 

[clang] 39938f2 - Fix warn-unsafe-buffer-usage-fixits-pre-increment.cpp for Windows

2023-04-13 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2023-04-13T10:21:15+02:00
New Revision: 39938f2d096ca9ed03ecc17ea169ed3195682f18

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

LOG: Fix warn-unsafe-buffer-usage-fixits-pre-increment.cpp for Windows

long is 32-bits on windows, so the test was failing with:

  error: cast from pointer to smaller type 'unsigned long' loses
  information

see e.g. https://lab.llvm.org/buildbot/#/builders/123/builds/18361

This is a follow-up to D144304

Added: 


Modified: 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pre-increment.cpp

Removed: 




diff  --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pre-increment.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pre-increment.cpp
index 9bad7cb55835..d3d7e8fe821f 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pre-increment.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pre-increment.cpp
@@ -9,8 +9,8 @@ void simple() {
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:24-[[@LINE-3]]:24}:", 10}"
   bool b = ++p;
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:12-[[@LINE-1]]:15}:"(p = 
p.subspan(1)).data()"
-  unsigned long n = (unsigned long) ++p;
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:37-[[@LINE-1]]:40}:"(p = 
p.subspan(1)).data()"
+  unsigned long long n = (unsigned long long) ++p;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:47-[[@LINE-1]]:50}:"(p = 
p.subspan(1)).data()"
   if (++p) {
 // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:10}:"(p = 
p.subspan(1)).data()"
   }



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


[libunwind] 5b9d969 - [libunwind] [SEH] Allow setting/getting the register UNW_X86_64_RIP

2023-04-13 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2023-04-13T12:03:35+03:00
New Revision: 5b9d969e7c07d720080eac386467c1112c45a76f

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

LOG: [libunwind] [SEH] Allow setting/getting the register UNW_X86_64_RIP

This fixes libunwind_01.pass.cpp for x86_64 Windows.

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

Added: 


Modified: 
libunwind/src/UnwindCursor.hpp

Removed: 




diff  --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index ac690badc2618..9ea0cf1465e8d 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -686,7 +686,7 @@ template 
 bool UnwindCursor::validReg(int regNum) {
   if (regNum == UNW_REG_IP || regNum == UNW_REG_SP) return true;
 #if defined(_LIBUNWIND_TARGET_X86_64)
-  if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
+  if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_RIP) return true;
 #elif defined(_LIBUNWIND_TARGET_ARM)
   if ((regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) ||
   regNum == UNW_ARM_RA_AUTH_CODE)
@@ -701,6 +701,7 @@ template 
 unw_word_t UnwindCursor::getReg(int regNum) {
   switch (regNum) {
 #if defined(_LIBUNWIND_TARGET_X86_64)
+  case UNW_X86_64_RIP:
   case UNW_REG_IP: return _msContext.Rip;
   case UNW_X86_64_RAX: return _msContext.Rax;
   case UNW_X86_64_RDX: return _msContext.Rdx;
@@ -751,6 +752,7 @@ template 
 void UnwindCursor::setReg(int regNum, unw_word_t value) {
   switch (regNum) {
 #if defined(_LIBUNWIND_TARGET_X86_64)
+  case UNW_X86_64_RIP:
   case UNW_REG_IP: _msContext.Rip = value; break;
   case UNW_X86_64_RAX: _msContext.Rax = value; break;
   case UNW_X86_64_RDX: _msContext.Rdx = value; break;



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


[libunwind] ebae562 - [libunwind] [SEH] Initialize _msContext with RtlCaptureContext

2023-04-13 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2023-04-13T12:03:35+03:00
New Revision: ebae5622d11655feaa74e64151067897153f9c71

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

LOG: [libunwind] [SEH] Initialize _msContext with RtlCaptureContext

When we initialize the UnwindCursor (unw_cursor_t) based on
an existing Registers object (unw_context_t), we only initialize
a subset of the class.

Fill the struct properly for the current thread with RtlCaptureContext,
followed by overwriting of the subset of registers that we do have
available in the Registers class.

One might think that it's enough to initialize specifically the
registers that we signal availability for with ContextFlags,
however in practice, that's not enough.

This fixes crashes when restoring the context via RtlRestoreContext
(via UnwindCursor::jumpto), via __unw_resume.

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

Added: 


Modified: 
libunwind/src/UnwindCursor.hpp

Removed: 




diff  --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index 9ea0cf1465e8..8b6451c68b46 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -579,6 +579,7 @@ UnwindCursor::UnwindCursor(unw_context_t *context, A 
&as)
   _dispContext.HistoryTable = &_histTable;
   // Initialize MS context from ours.
   R r(context);
+  RtlCaptureContext(&_msContext);
   _msContext.ContextFlags = 
CONTEXT_CONTROL|CONTEXT_INTEGER|CONTEXT_FLOATING_POINT;
 #if defined(_LIBUNWIND_TARGET_X86_64)
   _msContext.Rax = r.getRegister(UNW_X86_64_RAX);



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


[PATCH] D145214: [TSAN] add support for riscv64

2023-04-13 Thread Alex Fan via Phabricator via cfe-commits
alexfanqi added a comment.

friendly ping?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145214

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

In D146987#4263139 , @aeubanks wrote:

> I'm seeing
>
>   llc: ../../llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:6214: void 
> llvm::SelectionDAGBuilder::visitIntrinsicCall(const CallInst &, unsigned 
> int): Assertion `AssignmentTrackingEnabled && "expected assignment tracking 
> to be enabled"' failed.   
>  
>
> with this patch on the following IR (just run `llc` on it)
> F27123156: b.ll.txt 

This one is interesting... there's a `dbg.assign` (an assignment tracking debug 
intrinsic) there:

  define void @_ZN3gfx31PointTest_VectorArithmetic_Test8TestBodyEv() {
  entry:
call void @llvm.dbg.assign(metadata i1 undef, metadata !204, metadata 
!DIExpression(), metadata !210, metadata ptr null, metadata !DIExpression()), 
!dbg !211
ret void
  }

but the module flags don't contain the "assignment tracking is turned on" flag 
(`!{i32 7, !"debug-info-assignment-tracking", i1 true}`).

  !llvm.module.flags = !{!203}
  !203 = !{i32 2, !"Debug Info Version", i32 3}

If the reproducer below is the one used to create this one then I think the 
reduction process may have just cut the module flag. Do you know if you've hit 
this assertion from a source code reproducer?

In D146987#4263757 , @aeubanks wrote:

> F27125556: a.tgz 
>
> this is the original repro that crashed but maybe differently (you'll need to 
> remove the plugin arguments since our clang has some custom plugins)

This is indeed a different issue to the first one - D148203 
 fixes this one.

Thanks for these reproducers!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[clang] e841d50 - [clang] Ensure that Attr::Create(Implicit) chooses a valid syntax

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:48+01:00
New Revision: e841d50926347c3596009dd4fbc4cbd1a1a2e0b8

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

LOG: [clang] Ensure that Attr::Create(Implicit) chooses a valid syntax

The purpose of this patch and follow-on patches is to ensure that
AttributeCommonInfos always have a syntax that is appropriate for
their kind (i.e. that it matches one of the entries in Attr.td).

The attribute-specific Create and CreateImplicit methods had four
overloads, based on their tail arguments:

(1) no extra arguments
(2) an AttributeCommonInfo
(3) a SourceRange
(4) a SourceRange, a syntax, and (where necessary) a spelling

When (4) had a spelling argument, it defaulted to
SpellingNotCalculated.

One disadvantage of this was that (1) and (3) zero-initialized
the syntax field of the AttributeCommonInfo, which corresponds
to AS_GNU.  But AS_GNU isn't always listed as a possibility
in Attr.td.

This patch therefore removes (1) and (3) and instead provides
the same functionality using default arguments on (4) (a bit
like the existing default argument for the spelling).
The default syntax is taken from the attribute's first valid
spelling.

Doing that raises the question: what should happen for attributes
like AlignNatural and CUDAInvalidTarget that are only ever created
implicitly, and so have no source-code manifestation at all?
The patch adds a new AS_Implicit "syntax" for that case.
The patch also removes the syntax argument for these attributes,
since the syntax must always be AS_Implicit.

For similar reasons, the patch removes the syntax argument if
there is exactly one valid spelling.

Doing this means that AttributeCommonInfo no longer needs the
single-argument constructors.  It is always given a syntax instead.

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttributeCommonInfo.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/unittests/AST/DeclTest.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 79da53aba39ff..a23dd5ce3634b 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -834,7 +834,7 @@ def Annotate : InheritableParamAttr {
 return AnnotateAttr::Create(Ctx, Annotation, nullptr, 0, CommonInfo);
   }
   static AnnotateAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef 
Annotation, \
-  const AttributeCommonInfo &CommonInfo = 
AttributeCommonInfo{SourceRange{}}) {
+  const AttributeCommonInfo &CommonInfo) {
 return AnnotateAttr::CreateImplicit(Ctx, Annotation, nullptr, 0, 
CommonInfo);
   }
   }];

diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index f89bdbdaa0d28..f38f9687124b1 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -51,6 +51,10 @@ class AttributeCommonInfo {
 
 ///  : 
 AS_HLSLSemantic,
+
+/// The attibute has no source code manifestation and is only created
+/// implicitly.
+AS_Implicit
   };
   enum Kind {
 #define PARSED_ATTR(NAME) AT_##NAME,
@@ -76,14 +80,6 @@ class AttributeCommonInfo {
   static constexpr unsigned SpellingNotCalculated = 0xf;
 
 public:
-  explicit AttributeCommonInfo(SourceRange AttrRange)
-  : AttrRange(AttrRange), ScopeLoc(), AttrKind(0), SyntaxUsed(0),
-SpellingIndex(SpellingNotCalculated) {}
-
-  explicit AttributeCommonInfo(SourceLocation AttrLoc)
-  : AttrRange(AttrLoc), ScopeLoc(), AttrKind(0), SyntaxUsed(0),
-SpellingIndex(SpellingNotCalculated) {}
-
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
   SourceLocation ScopeLoc, Syntax SyntaxUsed)

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 6c6bf78ffc9c8..409c71662ee30 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -10125,9 +10125,8 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, 
DeclContext *DC,
   NewFD->setParams(Params);
 
   if (D.getDeclSpec().isNoreturnSpecified())
-NewFD->addAttr(C11NoReturnAttr::Create(Context,
-   
D.getDeclSpec().getNoreturnSpecLoc(),
-   AttributeCommonInfo::AS_Keyword));
+NewFD->addAttr(
+C11NoReturnAttr::Create(Context, 
D.getDeclSpec().getNoreturnSpecLoc()));
 
   // Functions returning a variably modified type viol

[clang] b6d4d51 - [clang] Specify attribute syntax & spelling with a single argument

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:49+01:00
New Revision: b6d4d51f8f5aab311df34c753b925760578729bd

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

LOG: [clang] Specify attribute syntax & spelling with a single argument

When constructing an attribute, the syntactic form was specified
using two arguments: an attribute-independent syntax type and an
attribute-specific spelling index.  This patch replaces them with
a single argument.

In most cases, that's done using a new Form class that combines the
syntax and spelling into a single object.  This has the minor benefit
of removing a couple of constructors.  But the main purpose is to allow
additional information to be stored as well, beyond just the syntax and
spelling enums.

In the case of the attribute-specific Create and CreateImplicit
functions, the patch instead uses the attribute-specific spelling
enum.  This helps to ensure that the syntax and spelling are
consistent with each other and with the Attr.td definition.

If a Create or CreateImplicit caller specified a syntax and
a spelling, the patch drops the syntax argument and keeps the
spelling.  If the caller instead specified only a syntax
(so that the spelling was SpellingNotCalculated), the patch
simply drops the syntax argument.

There were two cases of the latter: TargetVersion and Weak.
TargetVersionAttrs were created with GNU syntax, which matches
their definition in Attr.td, but which is also the default.
WeakAttrs were created with Pragma syntax, which does not match
their definition in Attr.td.  Dropping the argument switches
them to AS_GNU too (to match [GCC<"weak">]).

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

Added: 


Modified: 
clang/include/clang/Basic/AttributeCommonInfo.h
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/ParsedAttr.h
clang/lib/AST/ASTImporter.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Sema/HLSLExternalSemaSource.cpp
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaObjCProperty.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index f38f9687124b1..7925b9c01c299 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -80,50 +80,58 @@ class AttributeCommonInfo {
   static constexpr unsigned SpellingNotCalculated = 0xf;
 
 public:
-  AttributeCommonInfo(const IdentifierInfo *AttrName,
-  const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Syntax SyntaxUsed)
-  : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc),
-AttrKind(getParsedKind(AttrName, ScopeName, SyntaxUsed)),
-SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingNotCalculated) {}
+  /// Combines information about the source-code form of an attribute,
+  /// including its syntax and spelling.
+  class Form {
+  public:
+constexpr Form(Syntax SyntaxUsed,
+   unsigned SpellingIndex = SpellingNotCalculated)
+: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex) {}
+
+Syntax getSyntax() const { return Syntax(SyntaxUsed); }
+unsigned getSpellingIndex() const { return SpellingIndex; }
+
+  private:
+unsigned SyntaxUsed : 4;
+unsigned SpellingIndex : 4;
+  };
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Kind AttrKind, Syntax 
SyntaxUsed)
+  SourceLocation ScopeLoc, Form FormUsed)
   : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc), AttrKind(AttrKind), SyntaxUsed(SyntaxUsed),
-SpellingIndex(SpellingNotCalculated) {}
+ScopeLoc(ScopeLoc),
+AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
+SyntaxUsed(FormUsed.getSyntax()),
+SpellingIndex(FormUsed.getSpellingIndex()) {}
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Kind AttrKind, Syntax 
SyntaxUsed,
-  unsigned Spelling)
+  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
   : AttrName(AttrName), ScopeName(ScopeName), A

[clang] 265d87e - [clang] Allow attributes to be constructed from keyword tokens

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:49+01:00
New Revision: 265d87e46535bef2b718759ba39bb9fa30b1ef48

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

LOG: [clang] Allow attributes to be constructed from keyword tokens

This patch adds an extra AttributeCommonInfo::Form constructor
for keywords, represented by their TokenKind.  This isn't a
win on its own, but it helps with later patches.

No functional change intended.

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

Added: 


Modified: 
clang/include/clang/Basic/AttributeCommonInfo.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseExprCXX.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 7925b9c01c299..7b88ba1c461b1 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_BASIC_ATTRIBUTECOMMONINFO_H
 #define LLVM_CLANG_BASIC_ATTRIBUTECOMMONINFO_H
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
 
 namespace clang {
 class IdentifierInfo;
@@ -87,6 +88,8 @@ class AttributeCommonInfo {
 constexpr Form(Syntax SyntaxUsed,
unsigned SpellingIndex = SpellingNotCalculated)
 : SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex) {}
+constexpr Form(tok::TokenKind)
+: SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }
 unsigned getSpellingIndex() const { return SpellingIndex; }

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index e754081f9c0b4..a61a3ef662fdf 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -828,7 +828,8 @@ void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes 
&Attrs) {
 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
   // Treat these like attributes
   while (true) {
-switch (Tok.getKind()) {
+auto Kind = Tok.getKind();
+switch (Kind) {
 case tok::kw___fastcall:
 case tok::kw___stdcall:
 case tok::kw___thiscall:
@@ -843,7 +844,7 @@ void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes 
&attrs) {
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
   SourceLocation AttrNameLoc = ConsumeToken();
   attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
-   ParsedAttr::AS_Keyword);
+   Kind);
   break;
 }
 default:
@@ -865,7 +866,7 @@ void 
Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
   SourceLocation AttrNameLoc = ConsumeToken();
   attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
/*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
-   ParsedAttr::AS_Keyword);
+   tok::kw___funcref);
 }
 
 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
@@ -910,7 +911,7 @@ void Parser::ParseBorlandTypeAttributes(ParsedAttributes 
&attrs) {
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___pascal);
   }
 }
 
@@ -920,7 +921,7 @@ void Parser::ParseOpenCLKernelAttributes(ParsedAttributes 
&attrs) {
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___kernel);
   }
 }
 
@@ -929,7 +930,7 @@ void Parser::ParseCUDAFunctionAttributes(ParsedAttributes 
&attrs) {
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___noinline__);
   }
 }
 
@@ -937,7 +938,7 @@ void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) 
{
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
   SourceLocation AttrNameLoc = Tok.getLocation();
   Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
-   ParsedAttr::AS_Keyword);
+   Tok.getKind());
 }
 
 bool Parser::isHLSLQualifier(const Token &Tok) const {
@@ -946,15 +947,16 @@ bool Parser::isHLSLQualifier(const Token &Tok) const {
 
 void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
+  auto Kind = Tok.getKind();
   SourceLocation AttrNam

[clang] aec3f95 - [clang] Type safety tweak for AttributeCommonInfo::Form

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:49+01:00
New Revision: aec3f951bf368d45b441554dac6e027678f9f3ee

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

LOG: [clang] Type safety tweak for AttributeCommonInfo::Form

This patch adds static functions for constructing most
AttributeCommonInfo::Forms.  Direct construction is only retained where
all fields (currently the syntax and spelling) are specified explicitly.

This is a wash on its own.  The purpose is to allow extra fields
to be added to Form without disrupting all callers.  In particular,
it allows extra information to be stored about keywords without
affecting non-keyword uses.

No functional change intended.

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

Added: 


Modified: 
clang/include/clang/Basic/AttributeCommonInfo.h
clang/lib/Parse/ParseCXXInlineMethods.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseHLSL.cpp
clang/lib/Parse/ParseObjc.cpp
clang/lib/Parse/ParsePragma.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaType.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 7b88ba1c461b1..a5ba5715a60fa 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -85,8 +85,7 @@ class AttributeCommonInfo {
   /// including its syntax and spelling.
   class Form {
   public:
-constexpr Form(Syntax SyntaxUsed,
-   unsigned SpellingIndex = SpellingNotCalculated)
+constexpr Form(Syntax SyntaxUsed, unsigned SpellingIndex)
 : SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex) {}
 constexpr Form(tok::TokenKind)
 : SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated) {}
@@ -94,7 +93,21 @@ class AttributeCommonInfo {
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }
 unsigned getSpellingIndex() const { return SpellingIndex; }
 
+static Form GNU() { return AS_GNU; }
+static Form CXX11() { return AS_CXX11; }
+static Form C2x() { return AS_C2x; }
+static Form Declspec() { return AS_Declspec; }
+static Form Microsoft() { return AS_Microsoft; }
+static Form Keyword() { return AS_Keyword; }
+static Form Pragma() { return AS_Pragma; }
+static Form ContextSensitiveKeyword() { return AS_ContextSensitiveKeyword; 
}
+static Form HLSLSemantic() { return AS_HLSLSemantic; }
+static Form Implicit() { return AS_Implicit; }
+
   private:
+constexpr Form(Syntax SyntaxUsed)
+: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingNotCalculated) {}
+
 unsigned SyntaxUsed : 4;
 unsigned SpellingIndex : 4;
   };

diff  --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp 
b/clang/lib/Parse/ParseCXXInlineMethods.cpp
index 3a7f5426d4a70..930bb81a558fb 100644
--- a/clang/lib/Parse/ParseCXXInlineMethods.cpp
+++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp
@@ -748,7 +748,7 @@ void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
   }
 
   ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
-nullptr, SourceLocation(), ParsedAttr::AS_GNU,
+nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
 nullptr);
 
   if (HasFunScope)
@@ -757,7 +757,7 @@ void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
   // If there are multiple decls, then the decl cannot be within the
   // function scope.
   ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
-nullptr, SourceLocation(), ParsedAttr::AS_GNU,
+nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
 nullptr);
 }
   } else {

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index a61a3ef662fdf..18897188828f1 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -214,14 +214,14 @@ void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
 
   if (Tok.isNot(tok::l_paren)) {
 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_GNU);
+ ParsedAttr::Form::GNU());
 continue;
   }
 
   // Handle "parameterized" attributes
   if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
-  SourceLocation(), ParsedAttr::AS_GNU, D);
+  SourceLocation(), Pars

[clang] bd41371 - [clang] Fix FIXME in isAlignasAttribute()

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:50+01:00
New Revision: bd41371be02f6f5713459a2f6fe109cd3c01b4a4

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

LOG: [clang] Fix FIXME in isAlignasAttribute()

AttributeCommonInfo::isAlignasAttribute() was used in one place:
isCXX11Attribute().  The intention was for isAlignasAttribute()
to return true for the C++ alignas keyword.  However, as a FIXME
noted, the function also returned true for the C _Alignas keyword.
This meant that isCXX11Attribute() returned true for _Alignas as
well as for alignas.

AttributeCommonInfos are now always constructed with an
AttributeCommonInfo::Form.  We can use that Form to convey whether
a keyword is alignas or not.

The patch uses 1 bit of an 8-bit hole in the current layout
of AttributeCommonInfo.  This might not be the best long-term design,
but it should be easy to adapt the layout if necessary (that is,
if other uses are found for the spare bits).

I don't know of a way of testing this (other than grep -c FIXME)

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

Added: 


Modified: 
clang/include/clang/Basic/AttributeCommonInfo.h
clang/lib/Sema/SemaType.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index a5ba5715a60fa..a68f8d97e91a7 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -76,6 +76,7 @@ class AttributeCommonInfo {
   /// Corresponds to the Syntax enum.
   unsigned SyntaxUsed : 4;
   unsigned SpellingIndex : 4;
+  unsigned IsAlignas : 1;
 
 protected:
   static constexpr unsigned SpellingNotCalculated = 0xf;
@@ -85,20 +86,25 @@ class AttributeCommonInfo {
   /// including its syntax and spelling.
   class Form {
   public:
-constexpr Form(Syntax SyntaxUsed, unsigned SpellingIndex)
-: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex) {}
-constexpr Form(tok::TokenKind)
-: SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated) {}
+constexpr Form(Syntax SyntaxUsed, unsigned SpellingIndex, bool IsAlignas)
+: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex),
+  IsAlignas(IsAlignas) {}
+constexpr Form(tok::TokenKind Tok)
+: SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
+  IsAlignas(Tok == tok::kw_alignas) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }
 unsigned getSpellingIndex() const { return SpellingIndex; }
+bool isAlignas() const { return IsAlignas; }
 
 static Form GNU() { return AS_GNU; }
 static Form CXX11() { return AS_CXX11; }
 static Form C2x() { return AS_C2x; }
 static Form Declspec() { return AS_Declspec; }
 static Form Microsoft() { return AS_Microsoft; }
-static Form Keyword() { return AS_Keyword; }
+static Form Keyword(bool IsAlignas) {
+  return Form(AS_Keyword, SpellingNotCalculated, IsAlignas);
+}
 static Form Pragma() { return AS_Pragma; }
 static Form ContextSensitiveKeyword() { return AS_ContextSensitiveKeyword; 
}
 static Form HLSLSemantic() { return AS_HLSLSemantic; }
@@ -106,10 +112,12 @@ class AttributeCommonInfo {
 
   private:
 constexpr Form(Syntax SyntaxUsed)
-: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingNotCalculated) {}
+: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingNotCalculated),
+  IsAlignas(0) {}
 
 unsigned SyntaxUsed : 4;
 unsigned SpellingIndex : 4;
+unsigned IsAlignas : 1;
   };
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
@@ -119,7 +127,8 @@ class AttributeCommonInfo {
 ScopeLoc(ScopeLoc),
 AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
 SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()) {}
+SpellingIndex(FormUsed.getSpellingIndex()),
+IsAlignas(FormUsed.isAlignas()) {}
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
@@ -127,7 +136,8 @@ class AttributeCommonInfo {
   : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
 ScopeLoc(ScopeLoc), AttrKind(AttrKind),
 SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()) {}
+SpellingIndex(FormUsed.getSpellingIndex()),
+IsAlignas(FormUsed.isAlignas()) {}
 
   AttributeCommonInfo(const IdentifierInfo *AttrName, SourceRange AttrRange,
   Form FormUsed)
@@ -135,19 +145,21 @@ class AttributeCommonInfo {
 ScopeLoc(),
 AttrKind(getParsedKind

[clang] 053bdb7 - [clang] Bump AS_GNU to 1

2023-04-13 Thread Richard Sandiford via cfe-commits

Author: Richard Sandiford
Date: 2023-04-13T10:14:50+01:00
New Revision: 053bdb77b0ce4506d15ed381b6db0dddafe52c3e

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

LOG: [clang] Bump AS_GNU to 1

Following a suggestion from Erich in https://reviews.llvm.org/D148101,
this patch bumps AS_GNU to 1 so that syntax 0 is invalid.  It also
asserts that the syntax is in range.

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

Added: 


Modified: 
clang/include/clang/Basic/AttributeCommonInfo.h

Removed: 




diff  --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index a68f8d97e91a..a92dc0dad515 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -25,7 +25,7 @@ class AttributeCommonInfo {
   /// The style used to specify an attribute.
   enum Syntax {
 /// __attribute__((...))
-AS_GNU,
+AS_GNU = 1,
 
 /// [[...]]
 AS_CXX11,
@@ -122,37 +122,32 @@ class AttributeCommonInfo {
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Form FormUsed)
+  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
   : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc),
-AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
+ScopeLoc(ScopeLoc), AttrKind(AttrKind),
 SyntaxUsed(FormUsed.getSyntax()),
 SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+IsAlignas(FormUsed.isAlignas()) {
+assert(SyntaxUsed >= AS_GNU && SyntaxUsed <= AS_Implicit &&
+   "Invalid syntax!");
+  }
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
-  : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc), AttrKind(AttrKind),
-SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  SourceLocation ScopeLoc, Form FormUsed)
+  : AttributeCommonInfo(
+AttrName, ScopeName, AttrRange, ScopeLoc,
+getParsedKind(AttrName, ScopeName, FormUsed.getSyntax()),
+FormUsed) {}
 
   AttributeCommonInfo(const IdentifierInfo *AttrName, SourceRange AttrRange,
   Form FormUsed)
-  : AttrName(AttrName), ScopeName(nullptr), AttrRange(AttrRange),
-ScopeLoc(),
-AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
-SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  : AttributeCommonInfo(AttrName, nullptr, AttrRange, SourceLocation(),
+FormUsed) {}
 
   AttributeCommonInfo(SourceRange AttrRange, Kind K, Form FormUsed)
-  : AttrName(nullptr), ScopeName(nullptr), AttrRange(AttrRange), 
ScopeLoc(),
-AttrKind(K), SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  : AttributeCommonInfo(nullptr, nullptr, AttrRange, SourceLocation(), K,
+FormUsed) {}
 
   AttributeCommonInfo(AttributeCommonInfo &&) = default;
   AttributeCommonInfo(const AttributeCommonInfo &) = default;



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


[PATCH] D148101: [clang] Ensure that Attr::Create(Implicit) chooses a valid syntax

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe841d5092634: [clang] Ensure that Attr::Create(Implicit) 
chooses a valid syntax (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148101

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/unittests/AST/DeclTest.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2505,15 +2505,8 @@
   return &R == P.second;
 });
 
-enum class CreateKind {
-  WithAttributeCommonInfo,
-  WithSourceRange,
-  WithNoArgs,
-};
-
 // Emit CreateImplicit factory methods.
-auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly,
-  bool emitFake, CreateKind Kind) {
+auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
   if (Header)
 OS << "  static ";
   OS << R.getName() << "Attr *";
@@ -2537,10 +2530,7 @@
 OS << ", ";
 DelayedArgs->writeCtorParameters(OS);
   }
-  if (Kind == CreateKind::WithAttributeCommonInfo)
-OS << ", const AttributeCommonInfo &CommonInfo";
-  else if (Kind == CreateKind::WithSourceRange)
-OS << ", SourceRange R";
+  OS << ", const AttributeCommonInfo &CommonInfo";
   OS << ")";
   if (Header) {
 OS << ";\n";
@@ -2549,12 +2539,7 @@
 
   OS << " {\n";
   OS << "  auto *A = new (Ctx) " << R.getName();
-  if (Kind == CreateKind::WithAttributeCommonInfo)
-OS << "Attr(Ctx, CommonInfo";
-  else if (Kind == CreateKind::WithSourceRange)
-OS << "Attr(Ctx, AttributeCommonInfo{R}";
-  else if (Kind == CreateKind::WithNoArgs)
-OS << "Attr(Ctx, AttributeCommonInfo{SourceLocation{}}";
+  OS << "Attr(Ctx, CommonInfo";
 
   if (!DelayedArgsOnly) {
 for (auto const &ai : Args) {
@@ -2606,7 +2591,14 @@
 OS << ", ";
 DelayedArgs->writeCtorParameters(OS);
   }
-  OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
+  OS << ", SourceRange Range";
+  if (Header)
+OS << " = {}";
+  if (Spellings.size() > 1) {
+OS << ", AttributeCommonInfo::Syntax Syntax";
+if (Header)
+  OS << " = AttributeCommonInfo::AS_" << Spellings[0].variety();
+  }
   if (!ElideSpelling) {
 OS << ", " << R.getName() << "Attr::Spelling S";
 if (Header)
@@ -2626,7 +2618,13 @@
   else
 OS << "NoSemaHandlerAttribute";
 
-  OS << ", Syntax";
+  if (Spellings.size() == 0)
+OS << ", AttributeCommonInfo::AS_Implicit";
+  else if (Spellings.size() == 1)
+OS << ", AttributeCommonInfo::AS_" << Spellings[0].variety();
+  else
+OS << ", Syntax";
+
   if (!ElideSpelling)
 OS << ", S";
   OS << ");\n";
@@ -2651,19 +2649,9 @@
   OS << "}\n\n";
 };
 
-auto emitBothImplicitAndNonCreates = [&](bool DelayedArgsOnly,
- bool emitFake, CreateKind Kind) {
-  emitCreate(true, DelayedArgsOnly, emitFake, Kind);
-  emitCreate(false, DelayedArgsOnly, emitFake, Kind);
-};
-
 auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
-  emitBothImplicitAndNonCreates(DelayedArgsOnly, emitFake,
-CreateKind::WithNoArgs);
-  emitBothImplicitAndNonCreates(DelayedArgsOnly, emitFake,
-CreateKind::WithAttributeCommonInfo);
-  emitBothImplicitAndNonCreates(DelayedArgsOnly, emitFake,
-CreateKind::WithSourceRange);
+  emitCreate(true, DelayedArgsOnly, emitFake);
+  emitCreate(false, DelayedArgsOnly, emitFake);
   emitCreateNoCI(true, DelayedArgsOnly, emitFake);
   emitCreateNoCI(false, DelayedArgsOnly, emitFake);
 };
@@ -3468,6 +3456,10 @@
   OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
   OS << "  llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
   OS << "  return 0;\n";
+  OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
+  OS << "  llvm_unreachable (\"hasAttribute not supported for "
+"AS_Implicit\");\n";
+  OS << "  return 0;\n";
 
   OS << "}\n";
 }
Index: clang/unittests/AST/DeclTest.cpp
===
--- clang/unittests/AST/DeclTest.cpp
+++ clang/unittests/AST/DeclTest.cpp
@@ -88,12 +88,8 @@
   NamedDecl *DeclG = *(++DeclS->method_begin());
 
   // Attach asm labels to the decls: one literal, and one not.

[PATCH] D148102: [clang] Specify attribute syntax & spelling with a single argument

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb6d4d51f8f5a: [clang] Specify attribute syntax & 
spelling with a single argument (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148102

Files:
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/HLSLExternalSemaSource.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaObjCProperty.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2378,6 +2378,13 @@
   OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
 }
 
+static void emitFormInitializer(raw_ostream &OS,
+const FlattenedSpelling &Spelling,
+StringRef SpellingIndex) {
+  OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
+ << SpellingIndex << "}";
+}
+
 static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
bool Header) {
   std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
@@ -2595,14 +2602,9 @@
   if (Header)
 OS << " = {}";
   if (Spellings.size() > 1) {
-OS << ", AttributeCommonInfo::Syntax Syntax";
+OS << ", Spelling S";
 if (Header)
-  OS << " = AttributeCommonInfo::AS_" << Spellings[0].variety();
-  }
-  if (!ElideSpelling) {
-OS << ", " << R.getName() << "Attr::Spelling S";
-if (Header)
-  OS << " = static_cast(SpellingNotCalculated)";
+  OS << " = " << SemanticToSyntacticMap[0];
   }
   OS << ")";
   if (Header) {
@@ -2618,15 +2620,31 @@
   else
 OS << "NoSemaHandlerAttribute";
 
-  if (Spellings.size() == 0)
+  if (Spellings.size() == 0) {
 OS << ", AttributeCommonInfo::AS_Implicit";
-  else if (Spellings.size() == 1)
-OS << ", AttributeCommonInfo::AS_" << Spellings[0].variety();
-  else
-OS << ", Syntax";
+  } else if (Spellings.size() == 1) {
+OS << ", ";
+emitFormInitializer(OS, Spellings[0], "0");
+  } else {
+OS << ", (\n";
+std::set Uniques;
+unsigned Idx = 0;
+for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
+ ++I, ++Idx) {
+  const FlattenedSpelling &S = *I;
+  const auto &Name = SemanticToSyntacticMap[Idx];
+  if (Uniques.insert(Name).second) {
+OS << "S == " << Name << " ? AttributeCommonInfo::Form";
+emitFormInitializer(OS, S, Name);
+OS << " :\n";
+  }
+}
+OS << "(llvm_unreachable(\"Unknown attribute spelling!\"), "
+   << " AttributeCommonInfo::Form";
+emitFormInitializer(OS, Spellings[0], "0");
+OS << "))";
+  }
 
-  if (!ElideSpelling)
-OS << ", S";
   OS << ");\n";
   OS << "  return Create";
   if (Implicit)
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -3092,9 +3092,10 @@
   unsigned Syntax = Record.readInt();
   unsigned SpellingIndex = Record.readInt();
 
-  AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
-   AttributeCommonInfo::Kind(ParsedKind),
-   AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
+  AttributeCommonInfo Info(
+  AttrName, ScopeName, AttrRange, ScopeLoc,
+  AttributeCommonInfo::Kind(ParsedKind),
+  {AttributeCommonInfo::Syntax(Syntax), SpellingIndex});
 
 #include "clang/Serialization/AttrPCHRead.inc"
 
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -8970,8 +8970,7 @@
   ? S.ImplicitMSInheritanceAttrLoc
   : RD->getSourceRange();
 RD->addAttr(MSInheritanceAttr::CreateImplicit(
-S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
-MSInheritanceAttr::Spelling(IM)));
+S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
 S.Consumer.AssignInheritanceModel(RD);
   }
 }
Index: clang/lib/Sema/SemaOpenMP.cpp
==

[PATCH] D148103: [clang] Allow attributes to be constructed from keyword tokens

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG265d87e46535: [clang] Allow attributes to be constructed 
from keyword tokens (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148103

Files:
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExprCXX.cpp

Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -1300,7 +1300,7 @@
 SourceLocation AttrNameLoc = ConsumeToken();
 Attributes.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
   AttrNameLoc, /*ArgsUnion=*/nullptr,
-  /*numArgs=*/0, ParsedAttr::AS_Keyword);
+  /*numArgs=*/0, tok::kw___noinline__);
   } else if (Tok.is(tok::kw___attribute))
 ParseGNUAttributes(Attributes, /*LatePArsedAttrList=*/nullptr, &D);
   else
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -1370,9 +1370,9 @@
  tok::kw___multiple_inheritance,
  tok::kw___virtual_inheritance)) {
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
+auto Kind = Tok.getKind();
 SourceLocation AttrNameLoc = ConsumeToken();
-attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
   }
 }
 
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -828,7 +828,8 @@
 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
   // Treat these like attributes
   while (true) {
-switch (Tok.getKind()) {
+auto Kind = Tok.getKind();
+switch (Kind) {
 case tok::kw___fastcall:
 case tok::kw___stdcall:
 case tok::kw___thiscall:
@@ -843,7 +844,7 @@
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
   SourceLocation AttrNameLoc = ConsumeToken();
   attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
-   ParsedAttr::AS_Keyword);
+   Kind);
   break;
 }
 default:
@@ -865,7 +866,7 @@
   SourceLocation AttrNameLoc = ConsumeToken();
   attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
/*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
-   ParsedAttr::AS_Keyword);
+   tok::kw___funcref);
 }
 
 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
@@ -910,7 +911,7 @@
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___pascal);
   }
 }
 
@@ -920,7 +921,7 @@
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___kernel);
   }
 }
 
@@ -929,7 +930,7 @@
 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
 SourceLocation AttrNameLoc = ConsumeToken();
 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_Keyword);
+ tok::kw___noinline__);
   }
 }
 
@@ -937,7 +938,7 @@
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
   SourceLocation AttrNameLoc = Tok.getLocation();
   Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
-   ParsedAttr::AS_Keyword);
+   Tok.getKind());
 }
 
 bool Parser::isHLSLQualifier(const Token &Tok) const {
@@ -946,15 +947,16 @@
 
 void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
+  auto Kind = Tok.getKind();
   SourceLocation AttrNameLoc = ConsumeToken();
-  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
-   ParsedAttr::AS_Keyword);
+  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
 }
 
 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
   // Treat these like attributes, even though they're type specifiers.
   while (true) {
-switch (Tok.getKind()) {
+auto Kind = Tok.getKind();
+switch (Kind) {
 case tok::kw__Nonnull:
 case tok::kw__Nullable:
 case tok::kw__Nullable_result:
@@ -965,7 +967,7 @@
 Diag(AttrNameLoc, 

[PATCH] D148104: [clang] Type safety tweak for AttributeCommonInfo::Form

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaec3f951bf36: [clang] Type safety tweak for 
AttributeCommonInfo::Form (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148104

Files:
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseHLSL.cpp
  clang/lib/Parse/ParseObjc.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaType.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2621,7 +2621,7 @@
 OS << "NoSemaHandlerAttribute";
 
   if (Spellings.size() == 0) {
-OS << ", AttributeCommonInfo::AS_Implicit";
+OS << ", AttributeCommonInfo::Form::Implicit()";
   } else if (Spellings.size() == 1) {
 OS << ", ";
 emitFormInitializer(OS, Spellings[0], "0");
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -4893,12 +4893,12 @@
 
 // If we're supposed to infer nullability, do so now.
 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
-  ParsedAttr::Syntax syntax = inferNullabilityCS
-  ? ParsedAttr::AS_ContextSensitiveKeyword
-  : ParsedAttr::AS_Keyword;
+  ParsedAttr::Form form = inferNullabilityCS
+  ? ParsedAttr::Form::ContextSensitiveKeyword()
+  : ParsedAttr::Form::Keyword();
   ParsedAttr *nullabilityAttr = Pool.create(
   S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
-  nullptr, SourceLocation(), nullptr, 0, syntax);
+  nullptr, SourceLocation(), nullptr, 0, form);
 
   attrs.addAtEnd(nullabilityAttr);
 
@@ -6014,7 +6014,7 @@
   ParsedAttr *attr = D.getAttributePool().create(
   &S.Context.Idents.get("objc_ownership"), SourceLocation(),
   /*scope*/ nullptr, SourceLocation(),
-  /*args*/ &Args, 1, ParsedAttr::AS_GNU);
+  /*args*/ &Args, 1, ParsedAttr::Form::GNU());
   chunk.getAttrs().addAtEnd(attr);
   // TODO: mark whether we did this inference?
 }
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19862,7 +19862,7 @@
   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  LookupOrdinaryName);
   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
-   AttributeCommonInfo::AS_Pragma);
+   AttributeCommonInfo::Form::Pragma());
   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
   Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
 
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -860,7 +860,7 @@
 return;
 
   AttributeCommonInfo Info(Ident, SourceRange(Loc),
-   AttributeCommonInfo::AS_Pragma);
+   AttributeCommonInfo::Form::Pragma());
   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
 }
 
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -2411,7 +2411,7 @@
 ArgsUnion(Hint.ValueExpr)};
 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
  Hint.PragmaNameLoc->Loc, ArgHints, 4,
- ParsedAttr::AS_Pragma);
+ ParsedAttr::Form::Pragma());
   }
 
   // Get the next statement.
Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -1850,11 +1850,12 @@
 
   if (Tok.isNot(tok::l_paren))
 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
- ParsedAttr::AS_GNU);
+ ParsedAttr::Form::GNU());
   else
 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, /*EndLoc=*/nullptr,
   /*ScopeName=*/nullptr,
-  /*ScopeLoc=*/SourceLocation(), ParsedAttr::AS_GNU,
+  /*ScopeLoc=*/SourceLocation(),
+   

[PATCH] D148105: [clang] Fix FIXME in isAlignasAttribute()

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbd41371be02f: [clang] Fix FIXME in isAlignasAttribute() 
(authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148105

Files:
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2381,8 +2381,11 @@
 static void emitFormInitializer(raw_ostream &OS,
 const FlattenedSpelling &Spelling,
 StringRef SpellingIndex) {
+  bool IsAlignas =
+  (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
   OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
- << SpellingIndex << "}";
+ << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
+ << " /*IsAlignas*/}";
 }
 
 static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -3091,11 +3091,14 @@
   unsigned ParsedKind = Record.readInt();
   unsigned Syntax = Record.readInt();
   unsigned SpellingIndex = Record.readInt();
+  bool IsAlignas = (ParsedKind == AttributeCommonInfo::AT_Aligned &&
+Syntax == AttributeCommonInfo::AS_Keyword &&
+SpellingIndex == AlignedAttr::Keyword_alignas);
 
   AttributeCommonInfo Info(
   AttrName, ScopeName, AttrRange, ScopeLoc,
   AttributeCommonInfo::Kind(ParsedKind),
-  {AttributeCommonInfo::Syntax(Syntax), SpellingIndex});
+  {AttributeCommonInfo::Syntax(Syntax), SpellingIndex, IsAlignas});
 
 #include "clang/Serialization/AttrPCHRead.inc"
 
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -4893,9 +4893,9 @@
 
 // If we're supposed to infer nullability, do so now.
 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
-  ParsedAttr::Form form = inferNullabilityCS
-  ? ParsedAttr::Form::ContextSensitiveKeyword()
-  : ParsedAttr::Form::Keyword();
+  ParsedAttr::Form form =
+  inferNullabilityCS ? ParsedAttr::Form::ContextSensitiveKeyword()
+ : ParsedAttr::Form::Keyword(false /*IsAlignAs*/);
   ParsedAttr *nullabilityAttr = Pool.create(
   S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
   nullptr, SourceLocation(), nullptr, 0, form);
Index: clang/include/clang/Basic/AttributeCommonInfo.h
===
--- clang/include/clang/Basic/AttributeCommonInfo.h
+++ clang/include/clang/Basic/AttributeCommonInfo.h
@@ -76,6 +76,7 @@
   /// Corresponds to the Syntax enum.
   unsigned SyntaxUsed : 4;
   unsigned SpellingIndex : 4;
+  unsigned IsAlignas : 1;
 
 protected:
   static constexpr unsigned SpellingNotCalculated = 0xf;
@@ -85,20 +86,25 @@
   /// including its syntax and spelling.
   class Form {
   public:
-constexpr Form(Syntax SyntaxUsed, unsigned SpellingIndex)
-: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex) {}
-constexpr Form(tok::TokenKind)
-: SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated) {}
+constexpr Form(Syntax SyntaxUsed, unsigned SpellingIndex, bool IsAlignas)
+: SyntaxUsed(SyntaxUsed), SpellingIndex(SpellingIndex),
+  IsAlignas(IsAlignas) {}
+constexpr Form(tok::TokenKind Tok)
+: SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
+  IsAlignas(Tok == tok::kw_alignas) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }
 unsigned getSpellingIndex() const { return SpellingIndex; }
+bool isAlignas() const { return IsAlignas; }
 
 static Form GNU() { return AS_GNU; }
 static Form CXX11() { return AS_CXX11; }
 static Form C2x() { return AS_C2x; }
 static Form Declspec() { return AS_Declspec; }
 static Form Microsoft() { return AS_Microsoft; }
-static Form Keyword() { return AS_Keyword; }
+static Form Keyword(bool IsAlignas) {
+  return Form(AS_Keyword, SpellingNotCalculated, IsAlignas);
+}
 static Form Pragma() { return AS_Pragma; }
 static Form ContextSensitiveKeyword() { return AS_ContextSensitiveKeyword; }
 static Form HLSLSemantic() { return AS_HLSLSemantic; }
@@ -106,10 +112,12 @@
 
   private:
 constexpr Form(Syntax SyntaxUsed)
-:

[PATCH] D148148: [clang] Bump AS_GNU to 1

2023-04-13 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG053bdb77b0ce: [clang] Bump AS_GNU to 1 (authored by 
rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148148

Files:
  clang/include/clang/Basic/AttributeCommonInfo.h


Index: clang/include/clang/Basic/AttributeCommonInfo.h
===
--- clang/include/clang/Basic/AttributeCommonInfo.h
+++ clang/include/clang/Basic/AttributeCommonInfo.h
@@ -25,7 +25,7 @@
   /// The style used to specify an attribute.
   enum Syntax {
 /// __attribute__((...))
-AS_GNU,
+AS_GNU = 1,
 
 /// [[...]]
 AS_CXX11,
@@ -122,37 +122,32 @@
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Form FormUsed)
+  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
   : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc),
-AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
+ScopeLoc(ScopeLoc), AttrKind(AttrKind),
 SyntaxUsed(FormUsed.getSyntax()),
 SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+IsAlignas(FormUsed.isAlignas()) {
+assert(SyntaxUsed >= AS_GNU && SyntaxUsed <= AS_Implicit &&
+   "Invalid syntax!");
+  }
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
-  : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc), AttrKind(AttrKind),
-SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  SourceLocation ScopeLoc, Form FormUsed)
+  : AttributeCommonInfo(
+AttrName, ScopeName, AttrRange, ScopeLoc,
+getParsedKind(AttrName, ScopeName, FormUsed.getSyntax()),
+FormUsed) {}
 
   AttributeCommonInfo(const IdentifierInfo *AttrName, SourceRange AttrRange,
   Form FormUsed)
-  : AttrName(AttrName), ScopeName(nullptr), AttrRange(AttrRange),
-ScopeLoc(),
-AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
-SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  : AttributeCommonInfo(AttrName, nullptr, AttrRange, SourceLocation(),
+FormUsed) {}
 
   AttributeCommonInfo(SourceRange AttrRange, Kind K, Form FormUsed)
-  : AttrName(nullptr), ScopeName(nullptr), AttrRange(AttrRange), 
ScopeLoc(),
-AttrKind(K), SyntaxUsed(FormUsed.getSyntax()),
-SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+  : AttributeCommonInfo(nullptr, nullptr, AttrRange, SourceLocation(), K,
+FormUsed) {}
 
   AttributeCommonInfo(AttributeCommonInfo &&) = default;
   AttributeCommonInfo(const AttributeCommonInfo &) = default;


Index: clang/include/clang/Basic/AttributeCommonInfo.h
===
--- clang/include/clang/Basic/AttributeCommonInfo.h
+++ clang/include/clang/Basic/AttributeCommonInfo.h
@@ -25,7 +25,7 @@
   /// The style used to specify an attribute.
   enum Syntax {
 /// __attribute__((...))
-AS_GNU,
+AS_GNU = 1,
 
 /// [[...]]
 AS_CXX11,
@@ -122,37 +122,32 @@
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Form FormUsed)
+  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
   : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc),
-AttrKind(getParsedKind(AttrName, ScopeName, FormUsed.getSyntax())),
+ScopeLoc(ScopeLoc), AttrKind(AttrKind),
 SyntaxUsed(FormUsed.getSyntax()),
 SpellingIndex(FormUsed.getSpellingIndex()),
-IsAlignas(FormUsed.isAlignas()) {}
+IsAlignas(FormUsed.isAlignas()) {
+assert(SyntaxUsed >= AS_GNU && SyntaxUsed <= AS_Implicit &&
+   "Invalid syntax!");
+  }
 
   AttributeCommonInfo(const IdentifierInfo *AttrName,
   const IdentifierInfo *ScopeName, SourceRange AttrRange,
-  SourceLocation ScopeLoc, Kind AttrKind, Form FormUsed)
-  : AttrName(AttrName), ScopeName(ScopeName), AttrRange(AttrRange),
-ScopeLoc(ScopeLoc), AttrKind(AttrKin

[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

In D146987#4263263 , @rupprecht wrote:

> In D146987#4263048 , @MaskRay wrote:
>
>> The latest reland 3820e9a2b29a2e268319ed6635da0d59e18d736d 
>>  still 
>> caused some issues to our internal workloads. Stay tuned...
>>
>> So far we have only found crashes with ThinLTO workloads.
>
> More specifically, thinlto + split debug.
>
> I'm not sure if my reduction is the same issue as @aeubanks has. Here's mine: 
> F27123766: repro-D146987.ll 
>
> Repro w/ `clang -O1 -c reduced.ll -o /dev/null`
>
> I don't see any assertions going off for this one. The stack trace I have 
> just points to `llvm::Value::stripPointerCasts`. Lemme know if you need more 
> info, but I'm hoping that file reproduces for you.

Thanks for this. This one has a similar cause to @aeubanks's issue but 
manifests differently. Fixed in D148204 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D147686: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

2023-04-13 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 513134.
hokein marked an inline comment as not done.
hokein added a comment.

use syntax::spelledTokensTouching.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147686

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -413,6 +413,28 @@
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  Annotations MainCode(R"cpp(
+#include "all.h"
+void test() {
+  [[1s]];
+}
+)cpp");
+  TU.Code = MainCode.code();
+  TU.AdditionalFiles["foo.h"] =
+  guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  const auto &MissingIncludes =
+  computeIncludeCleanerFindings(AST).MissingIncludes;
+  EXPECT_THAT(MissingIncludes, testing::SizeIs(1));
+  auto &SM = AST.getSourceManager();
+  EXPECT_EQ(
+  halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)),
+  MainCode.range());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -403,9 +403,14 @@
 // through an #include.
 while (SM.getFileID(Loc) != SM.getMainFileID())
   Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-Providers};
+auto TouchingTokens =
+syntax::spelledTokensTouching(Loc, AST.getTokens());
+assert(!TouchingTokens.empty());
+// Loc points to the start offset of the ref token, here we use the 
last
+// element of the TouchingTokens, e.g. avoid getting the "::" for
+// "ns::^abc".
+MissingIncludeDiagInfo DiagInfo{
+Ref.Target, TouchingTokens.back().range(SM), Providers};
 MissingIncludes.push_back(std::move(DiagInfo));
   });
   std::vector UnusedIncludes =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -413,6 +413,28 @@
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  Annotations MainCode(R"cpp(
+#include "all.h"
+void test() {
+  [[1s]];
+}
+)cpp");
+  TU.Code = MainCode.code();
+  TU.AdditionalFiles["foo.h"] =
+  guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  const auto &MissingIncludes =
+  computeIncludeCleanerFindings(AST).MissingIncludes;
+  EXPECT_THAT(MissingIncludes, testing::SizeIs(1));
+  auto &SM = AST.getSourceManager();
+  EXPECT_EQ(
+  halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)),
+  MainCode.range());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -403,9 +403,14 @@
 // through an #include.
 while (SM.getFileID(Loc) != SM.getMainFileID())
   Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-Providers};
+auto TouchingTokens =
+syntax::spelledTokensTouching(Loc, AST.getTokens());
+assert(!TouchingTokens.empty());
+// Loc points to the start offset of the ref token, here we use the last
+// element of the TouchingTokens, e.g. avoid getting the "::" for
+// "ns::^abc".
+MissingIncludeDiagInfo DiagInfo{
+Ref.Target, TouchingTokens.back().range(SM), Providers};
 MissingIncludes.push_back(std::move(DiagInfo));
   });
   std::vector UnusedIncludes =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147686: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

2023-04-13 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:450
+void test() {
+  1s;
+}

kadircet wrote:
> hokein wrote:
> > here is the `UserDefinedLiteral` AST node:
> > 
> > ```
> > `-UserDefinedLiteral 0x5556682e4500  'int'
> >   |-ImplicitCastExpr 0x5556682e44e8  'int (*)(unsigned long 
> > long)' 
> >   | `-DeclRefExpr 0x5556682e44a0  'int (unsigned long long)' 
> > lvalue Function 0x5556682e4290 'operator""s' 'int (unsigned long long)'
> >   `-IntegerLiteral 0x5556682e4480  'unsigned long long' 1
> > ```
> > 
> > The source location of the `UserDefinedLiteral` points to `^1s`, while the 
> > source location of the inner `DeclRefExpr` points to `1^s` (1 offset 
> > shift). In the token buffer, we only have a single spelled token `1s`, thus 
> > `AST.getTokens().spelledTokenAt` can not find any token that starts at 
> > `1^s` source loc.
> thanks, that makes sense!
> 
> then instead of "suppressing" these, can we use 
> `spelledTokensTouching().front()` (and asserting that it isn't empty?)
Thanks, this is a good idea.

But we have to use the `back()`, for the case `ns::^abc` (we want to point to 
`abc`, not the `::`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147686

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


[PATCH] D148206: [clang] Do not crash after suggesting typo correction to constexpr if condition

2023-04-13 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In some cases non-null non-constant yet valid expression may reach point where
`ConditionResult` is created. For example, typo correction mechanism can return
such expression, so double check before evaluating it.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148206

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/test/SemaCXX/invalid-if-constexpr.cpp


Index: clang/test/SemaCXX/invalid-if-constexpr.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/invalid-if-constexpr.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -std=c++20 %s
+
+namespace GH61885 {
+void similar() { // expected-note {{'similar' declared here}}
+  if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
+}
+void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
+   // expected-note {{'__sync_swap' 
declared here}}
+
+int AA() { return true;} // expected-note {{'AA' declared here}}
+
+void b() { if constexpr (AAA<>) {}} // expected-error {{use of undeclared 
identifier 'AAA'; did you mean 'AA'?}}
+}
+
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -12851,7 +12851,8 @@
 bool IsConstexpr)
 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
   HasKnownValue(IsConstexpr && Condition.get() &&
-!Condition.get()->isValueDependent()),
+!Condition.get()->isValueDependent() &&
+Condition.get()->isIntegerConstantExpr(S.Context)),
   KnownValue(HasKnownValue &&
  !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
 explicit ConditionResult(bool Invalid)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -294,6 +294,8 @@
   not a type concept.
 - Fix crash when a doc comment contains a line splicing.
   (`#62054 `_)
+- Fix crash after suggesting typo correction to constexpr if condition.
+  (`#61885 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/SemaCXX/invalid-if-constexpr.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/invalid-if-constexpr.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -std=c++20 %s
+
+namespace GH61885 {
+void similar() { // expected-note {{'similar' declared here}}
+  if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 'similer'; did you mean 'similar'?}}
+}
+void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
+   // expected-note {{'__sync_swap' declared here}}
+
+int AA() { return true;} // expected-note {{'AA' declared here}}
+
+void b() { if constexpr (AAA<>) {}} // expected-error {{use of undeclared identifier 'AAA'; did you mean 'AA'?}}
+}
+
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -12851,7 +12851,8 @@
 bool IsConstexpr)
 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
   HasKnownValue(IsConstexpr && Condition.get() &&
-!Condition.get()->isValueDependent()),
+!Condition.get()->isValueDependent() &&
+Condition.get()->isIntegerConstantExpr(S.Context)),
   KnownValue(HasKnownValue &&
  !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
 explicit ConditionResult(bool Invalid)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -294,6 +294,8 @@
   not a type concept.
 - Fix crash when a doc comment contains a line splicing.
   (`#62054 `_)
+- Fix crash after suggesting typo correction to constexpr if condition.
+  (`#61885 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
_

[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Jeremy Morse via Phabricator via cfe-commits
jmorse added a comment.

Many thanks for all the feedback,

In D146987#4263139 , @aeubanks wrote:

> I'm seeing
>
>   llc: ../../llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:6214: void 
> llvm::SelectionDAGBuilder::visitIntrinsicCall(const CallInst &, unsigned 
> int): Assertion `AssignmentTrackingEnabled && "expected assignment tracking 
> to be enabled"' failed.   
>  
>
> with this patch on the following IR (just run `llc` on it)
> F27123156: b.ll.txt 

H, that feels like a legitimate IR input where the configuration of 
debug-info / intrinsics is just unexpected -- we probably shouldn't assert in 
that situation but gracefully degrade to interpreting a dbg.assign as a 
dbg.value.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[clang] 1689a5d - [clang] fix an unused variable warning after 9d0b55f0e4ca55d04ee8abfdf021913ea3c30082

2023-04-13 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-04-13T10:03:37Z
New Revision: 1689a5d756f81d615bcfca8de2631b0ccc8a3917

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

LOG: [clang] fix an unused variable warning after 
9d0b55f0e4ca55d04ee8abfdf021913ea3c30082

Added: 


Modified: 
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index b90a18d53966..532fef6df5e3 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -8624,7 +8624,6 @@ TEST_P(ASTImporterOptionSpecificTestBase,
 
   auto X = 0 ? (RPX1){} : (RPY1){};
   )";
-  Decl *ToTU = getToTuDecl("", Lang_CXX11);
   Decl *FromTU = getTuDecl(Code, Lang_CXX11);
 
   auto *FromX =



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


[PATCH] D148207: [mlir][Tensor] Drop SplitPaddingPatterns.

2023-04-13 Thread Nicolas Vasilache via Phabricator via cfe-commits
nicolasvasilache created this revision.
Herald added subscribers: bviyer, hanchung, Moerafaat, bzcheeseman, sdasgup3, 
wenzhicui, wrengr, cota, teijeong, rdzhabarov, tatianashp, msifontes, jurahul, 
Kayjukh, grosul1, Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, 
antiagainst, shauheen, rriddle, mehdi_amini, thopre, bixia.
Herald added a project: All.
nicolasvasilache requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer.
Herald added projects: clang, MLIR.

These old patterns are not in use in either MLIR or downstream projects except 
for one test.
Additionally this is redundant with logic in the tensor.pad tiling 
implementation.

Drop SplitPaddingPatterns to reduce entropy.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148207

Files:
  clang/docs/tools/clang-formatted-files.txt
  mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
  mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
  mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
  mlir/test/Dialect/Tensor/split-padding.mlir
  mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp

Index: mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
===
--- mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
+++ mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
@@ -43,11 +43,6 @@
 
   void runOnOperation() override;
 
-  Option testSplitPaddingPatterns{
-  *this, "test-split-padding-patterns",
-  llvm::cl::desc("Test patterns to split tensor.pad ops"),
-  llvm::cl::init(false)};
-
   Option testFoldConstantExtractSlice{
   *this, "test-fold-constant-extract-slice",
   llvm::cl::desc("Test folding arith.constant and tensor.extract_slice"),
@@ -111,12 +106,6 @@
   (void)applyPatternsAndFoldGreedily(rootOp, std::move(patterns));
 }
 
-static void applySplitPaddingPatterns(Operation *rootOp) {
-  RewritePatternSet patterns(rootOp->getContext());
-  tensor::populateSplitPaddingPatterns(patterns);
-  (void)applyPatternsAndFoldGreedily(rootOp, std::move(patterns));
-}
-
 static void applyFoldConstantExtractSlicePatterns(Operation *rootOp) {
   RewritePatternSet patterns(rootOp->getContext());
   tensor::ControlConstantExtractSliceFusionFn controlFn =
@@ -291,8 +280,6 @@
   Operation *rootOp = getOperation();
   if (testSimplifyPackPatterns)
 applySimplifyPackPatterns(rootOp);
-  if (testSplitPaddingPatterns)
-applySplitPaddingPatterns(rootOp);
   if (testFoldConstantExtractSlice)
 applyFoldConstantExtractSlicePatterns(rootOp);
   if (testFoldConsecutiveInsertExtractSlice)
Index: mlir/test/Dialect/Tensor/split-padding.mlir
===
--- mlir/test/Dialect/Tensor/split-padding.mlir
+++ /dev/null
@@ -1,44 +0,0 @@
-// RUN: mlir-opt -split-input-file -test-tensor-transform-patterns=test-split-padding-patterns %s | FileCheck %s
-
-// CHECK-LABEL: func @pad_all_zero_sizes
-func.func @pad_all_zero_sizes(%input: tensor) -> tensor {
-  %f0 = arith.constant 0.0 : f32
-  %c0 = arith.constant 0 : index
-  %0 = tensor.pad %input low[0, %c0, 0] high[%c0, 0, 0] {
-  ^bb0(%dim0: index, %dim1: index, %dim2: index):
-tensor.yield %f0 : f32
-  } : tensor to tensor
-  return %0 : tensor
-}
-
-// CHECK-NOT: scf.if
-// CHECK: tensor.pad
-
-// -
-
-// CHECK-LABEL: func @pad_non_zero_sizes
-//  CHECK-SAME: (%[[INPUT:.+]]: tensor, %[[LOW0:.+]]: index, %[[HIGH1:.+]]: index)
-func.func @pad_non_zero_sizes(%input: tensor, %low0: index, %high1: index) -> tensor {
-  %f0 = arith.constant 0.0 : f32
-  %0 = tensor.pad %input low[%low0, 0, 0] high[0, %high1, 0] {
-  ^bb0(%dim0: index, %dim1: index, %dim2: index):
-tensor.yield %f0 : f32
-  } : tensor to tensor
-  return %0 : tensor
-}
-
-// CHECK-DAG: %[[F0:.+]] = arith.constant 0.00e+00 : f32
-// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
-// CHECK: %[[EQ0:.+]] = arith.cmpi eq, %[[LOW0]], %[[C0]] : index
-// CHECK: %[[EQ1:.+]] = arith.cmpi eq, %[[HIGH1]], %[[C0]] : index
-// CHECK: %[[AND:.+]] = arith.andi %[[EQ0]], %[[EQ1]] : i1
-// CHECK: %[[IF:.+]] = scf.if %[[AND]] -> (tensor) {
-// CHECK:   scf.yield %[[INPUT]] : tensor
-// CHECK: } else {
-// CHECK:   %[[PAD:.+]] = tensor.pad %[[INPUT]] low[%[[LOW0]], 0, 0] high[0, %[[HIGH1]], 0]  {
-// CHECK:   ^bb0(%{{.+}}: index, %{{.+}}: index, %{{.+}}: index):
-// CHECK: tensor.yield %[[F0]] : f32
-// CHECK:   } : tensor to tensor
-// CHECK:   scf.yield %[[PAD]] : tensor
-// CHECK: }
-// CHECK: return %[[IF]] : tensor
Index: mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
===
--- mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-//===- SplitPaddingPatterns.cpp - Splitting tensor.pad Op -===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICEN

[clang-tools-extra] 40276f7 - [include-fixer] Add the missing variant header to the STL header list.

2023-04-13 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-04-13T12:09:36+02:00
New Revision: 40276f78fd4dabc4368724c161ca918d6145ef75

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

LOG: [include-fixer] Add the missing variant header to the STL header list.

Added: 


Modified: 

clang-tools-extra/clang-include-fixer/find-all-symbols/STLPostfixHeaderMap.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-include-fixer/find-all-symbols/STLPostfixHeaderMap.cpp
 
b/clang-tools-extra/clang-include-fixer/find-all-symbols/STLPostfixHeaderMap.cpp
index 122d2df1f1398..5245243bac081 100644
--- 
a/clang-tools-extra/clang-include-fixer/find-all-symbols/STLPostfixHeaderMap.cpp
+++ 
b/clang-tools-extra/clang-include-fixer/find-all-symbols/STLPostfixHeaderMap.cpp
@@ -267,6 +267,7 @@ const HeaderMapCollector::RegexHeaderMap 
*getSTLPostfixHeaderMap() {
   {"unordered_set$", ""},
   {"utility$", ""},
   {"valarray$", ""},
+  {"variant$", ""},
   {"vector$", ""},
   {"include/complex.h$", ""},
   {"include/ctype.h$", ""},



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


[PATCH] D147875: [clang][Diagnostics] WIP: Show line numbers when printing code snippets

2023-04-13 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 513144.

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

https://reviews.llvm.org/D147875

Files:
  clang/include/clang/Basic/DiagnosticOptions.def
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/TextDiagnostic.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/FixIt/fixit-newline-style.c
  clang/test/FixIt/fixit-unicode-with-utf8-output.c
  clang/test/FixIt/fixit-unicode.c
  clang/test/Lexer/header.cpp
  clang/test/Lexer/string-literal-errors.cpp
  clang/test/Misc/caret-diags-macros.c
  clang/test/Misc/caret-diags-multiline.cpp
  clang/test/Misc/diag-macro-backtrace.c
  clang/test/Misc/message-length.c
  clang/test/Misc/tabstop.c
  clang/test/Misc/unnecessary-elipses.cpp
  clang/test/Misc/unprintable.c
  clang/test/Misc/wrong-encoding.c
  clang/test/Parser/brackets.c
  clang/test/Parser/brackets.cpp
  clang/test/SemaCXX/struct-class-redecl.cpp

Index: clang/test/SemaCXX/struct-class-redecl.cpp
===
--- clang/test/SemaCXX/struct-class-redecl.cpp
+++ clang/test/SemaCXX/struct-class-redecl.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fsyntax-only -Wmismatched-tags -verify %s
-// RUN: not %clang_cc1 -fsyntax-only -Wmismatched-tags %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -fsyntax-only -Wmismatched-tags -fno-diagnostics-show-line-numbers -verify %s
+// RUN: not %clang_cc1 -fsyntax-only -Wmismatched-tags -fno-diagnostics-show-line-numbers %s 2>&1 | FileCheck %s
 class X; // expected-note 2{{here}}
 typedef struct X * X_t; // expected-warning{{previously declared}}
 union X { int x; float y; }; // expected-error{{use of 'X' with tag type that does not match previous declaration}}
Index: clang/test/Parser/brackets.cpp
===
--- clang/test/Parser/brackets.cpp
+++ clang/test/Parser/brackets.cpp
@@ -2,7 +2,7 @@
 // RUN: cp %s %t
 // RUN: not %clang_cc1 -fixit %t -x c++ -DFIXIT
 // RUN: %clang_cc1 -fsyntax-only %t -x c++ -DFIXIT
-// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s -strict-whitespace
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -fno-diagnostics-show-line-numbers %s 2>&1 | FileCheck %s -strict-whitespace
 
 void test1() {
   int a[] = {0,1,1,2,3};
Index: clang/test/Parser/brackets.c
===
--- clang/test/Parser/brackets.c
+++ clang/test/Parser/brackets.c
@@ -2,7 +2,7 @@
 // RUN: cp %s %t
 // RUN: not %clang_cc1 -fixit %t -x c -DFIXIT
 // RUN: %clang_cc1 -fsyntax-only %t -x c -DFIXIT
-// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s -strict-whitespace
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -fno-diagnostics-show-line-numbers %s 2>&1 | FileCheck %s -strict-whitespace
 
 void test1(void) {
   int a[] = {0,1,1,2,3};
Index: clang/test/Misc/wrong-encoding.c
===
--- clang/test/Misc/wrong-encoding.c
+++ clang/test/Misc/wrong-encoding.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wno-unused-value %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -fno-diagnostics-show-line-numbers %s 2>&1 | FileCheck %s
 // REQUIRES: asserts
 
 void foo(void) {
Index: clang/test/Misc/unprintable.c
===
--- clang/test/Misc/unprintable.c
+++ clang/test/Misc/unprintable.c
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 %s -fmessage-length=40 2>&1 | FileCheck -strict-whitespace %s
+// RUN: not %clang_cc1 %s -fmessage-length=40 -fno-diagnostics-show-line-numbers 2>&1 | FileCheck -strict-whitespace %s
 
 int main() {
 int i;
Index: clang/test/Misc/unnecessary-elipses.cpp
===
--- clang/test/Misc/unnecessary-elipses.cpp
+++ clang/test/Misc/unnecessary-elipses.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -fmessage-length=80 %s 2>&1 | FileCheck -strict-whitespace %s
+// RUN: %clang_cc1 -fsyntax-only -fmessage-length=80 -fno-diagnostics-show-line-numbers %s 2>&1 | FileCheck -strict-whitespace %s
 
 int main() {
 "xxx";
Index: clang/test/Misc/tabstop.c
===
--- clang/test/Misc/tabstop.c
+++ clang/test/Misc/tabstop.c
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -ftabstop 3 -fsyntax-only -Wno-error=int-conversion %s 2>&1 | FileCheck -check-prefix=CHECK-3 -strict-whitespace %s
-// RUN: %clang_cc1 -ftabstop 4 -fsyntax-only -Wno-error=int-conversion %s 2>&1 | FileCheck -check-prefix=CHECK-4 -strict-whitespace %s
-// RUN: %clang_cc1 -ftabstop 5 -fsyntax-only -Wno-error=int-conversion %s 2>&1 | FileCheck -check-pref

[clang-tools-extra] 2524000 - [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

2023-04-13 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-04-13T12:17:39+02:00
New Revision: 2524000187fc56a3f818a6562199037a90108eda

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

LOG: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

Be more robust, we shuold not crash  when we cannot find the corresponding 
token from the
tokenbuffer.

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

Added: 


Modified: 
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index e645b1cce6a09..b0e4d8dee5568 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -405,9 +405,14 @@ IncludeCleanerFindings 
computeIncludeCleanerFindings(ParsedAST &AST) {
 // through an #include.
 while (SM.getFileID(Loc) != SM.getMainFileID())
   Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-Providers};
+auto TouchingTokens =
+syntax::spelledTokensTouching(Loc, AST.getTokens());
+assert(!TouchingTokens.empty());
+// Loc points to the start offset of the ref token, here we use the 
last
+// element of the TouchingTokens, e.g. avoid getting the "::" for
+// "ns::^abc".
+MissingIncludeDiagInfo DiagInfo{
+Ref.Target, TouchingTokens.back().range(SM), Providers};
 MissingIncludes.push_back(std::move(DiagInfo));
   });
   std::vector UnusedIncludes =

diff  --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp 
b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index c0c15cd0db8e5..d0b99b7150779 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -413,6 +413,28 @@ TEST(IncludeCleaner, MacroExpandedThroughIncludes) {
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  Annotations MainCode(R"cpp(
+#include "all.h"
+void test() {
+  [[1s]];
+}
+)cpp");
+  TU.Code = MainCode.code();
+  TU.AdditionalFiles["foo.h"] =
+  guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  const auto &MissingIncludes =
+  computeIncludeCleanerFindings(AST).MissingIncludes;
+  EXPECT_THAT(MissingIncludes, testing::SizeIs(1));
+  auto &SM = AST.getSourceManager();
+  EXPECT_EQ(
+  halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)),
+  MainCode.range());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang



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


[PATCH] D147686: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

2023-04-13 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2524000187fc: [clangd] Fix a nullptr-dereference crash in 
computeIncludeCleanerFindings. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147686

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -413,6 +413,28 @@
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  Annotations MainCode(R"cpp(
+#include "all.h"
+void test() {
+  [[1s]];
+}
+)cpp");
+  TU.Code = MainCode.code();
+  TU.AdditionalFiles["foo.h"] =
+  guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  const auto &MissingIncludes =
+  computeIncludeCleanerFindings(AST).MissingIncludes;
+  EXPECT_THAT(MissingIncludes, testing::SizeIs(1));
+  auto &SM = AST.getSourceManager();
+  EXPECT_EQ(
+  halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)),
+  MainCode.range());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -405,9 +405,14 @@
 // through an #include.
 while (SM.getFileID(Loc) != SM.getMainFileID())
   Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-Providers};
+auto TouchingTokens =
+syntax::spelledTokensTouching(Loc, AST.getTokens());
+assert(!TouchingTokens.empty());
+// Loc points to the start offset of the ref token, here we use the 
last
+// element of the TouchingTokens, e.g. avoid getting the "::" for
+// "ns::^abc".
+MissingIncludeDiagInfo DiagInfo{
+Ref.Target, TouchingTokens.back().range(SM), Providers};
 MissingIncludes.push_back(std::move(DiagInfo));
   });
   std::vector UnusedIncludes =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -413,6 +413,28 @@
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  Annotations MainCode(R"cpp(
+#include "all.h"
+void test() {
+  [[1s]];
+}
+)cpp");
+  TU.Code = MainCode.code();
+  TU.AdditionalFiles["foo.h"] =
+  guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  const auto &MissingIncludes =
+  computeIncludeCleanerFindings(AST).MissingIncludes;
+  EXPECT_THAT(MissingIncludes, testing::SizeIs(1));
+  auto &SM = AST.getSourceManager();
+  EXPECT_EQ(
+  halfOpenToRange(SM, MissingIncludes.front().SymRefRange.toCharRange(SM)),
+  MainCode.range());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -405,9 +405,14 @@
 // through an #include.
 while (SM.getFileID(Loc) != SM.getMainFileID())
   Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-Providers};
+auto TouchingTokens =
+syntax::spelledTokensTouching(Loc, AST.getTokens());
+assert(!TouchingTokens.empty());
+// Loc points to the start offset of the ref token, here we use the last
+// element of the TouchingTokens, e.g. avoid getting the "::" for
+// "ns::^abc".
+MissingIncludeDiagInfo DiagInfo{
+Ref.Target, TouchingTokens.back().range(SM), Providers};
 MissingIncludes.push_back(std::move(DiagInfo));
   });
   std::vector UnusedIncludes =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https:

[PATCH] D148211: [clang][tests] Fix Flang driver tests for Windows

2023-04-13 Thread Ádám Kallai via Phabricator via cfe-commits
kaadam created this revision.
kaadam added reviewers: kiranchandramohan, bryanpkc, mstorsjo.
Herald added a reviewer: sscalpone.
Herald added a subscriber: sunshaoce.
Herald added a project: All.
kaadam requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Updated the regular expression in order to match '.exe' suffix,
if these Flang tests are running on Windows.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148211

Files:
  clang/test/Driver/flang/flang.f90
  clang/test/Driver/flang/flang_ucase.F90
  clang/test/Driver/flang/multiple-inputs.f90


Index: clang/test/Driver/flang/multiple-inputs.f90
===
--- clang/test/Driver/flang/multiple-inputs.f90
+++ clang/test/Driver/flang/multiple-inputs.f90
@@ -1,7 +1,7 @@
 ! Check that flang driver can handle multiple inputs at once.
 
 ! RUN: %clang --driver-mode=flang -### -fsyntax-only %S/Inputs/one.f90 
%S/Inputs/two.f90 2>&1 | FileCheck --check-prefixes=CHECK-SYNTAX-ONLY %s
-! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/one.f90"
-! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/two.f90"
Index: clang/test/Driver/flang/flang_ucase.F90
===
--- clang/test/Driver/flang/flang_ucase.F90
+++ clang/test/Driver/flang/flang_ucase.F90
@@ -13,7 +13,7 @@
 ! * (no type specified, resulting in an object file)
 
 ! All invocations should begin with flang -fc1, consume up to here.
-! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! ALL-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 
 ! Check that f90 files are not treated as "previously preprocessed"
 ! ... in --driver-mode=flang.
Index: clang/test/Driver/flang/flang.f90
===
--- clang/test/Driver/flang/flang.f90
+++ clang/test/Driver/flang/flang.f90
@@ -13,7 +13,7 @@
 ! * (no type specified, resulting in an object file)
 
 ! All invocations should begin with flang -fc1, consume up to here.
-! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! ALL-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 
 ! Check that f90 files are not treated as "previously preprocessed"
 ! ... in --driver-mode=flang.


Index: clang/test/Driver/flang/multiple-inputs.f90
===
--- clang/test/Driver/flang/multiple-inputs.f90
+++ clang/test/Driver/flang/multiple-inputs.f90
@@ -1,7 +1,7 @@
 ! Check that flang driver can handle multiple inputs at once.
 
 ! RUN: %clang --driver-mode=flang -### -fsyntax-only %S/Inputs/one.f90 %S/Inputs/two.f90 2>&1 | FileCheck --check-prefixes=CHECK-SYNTAX-ONLY %s
-! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/one.f90"
-! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/two.f90"
Index: clang/test/Driver/flang/flang_ucase.F90
===
--- clang/test/Driver/flang/flang_ucase.F90
+++ clang/test/Driver/flang/flang_ucase.F90
@@ -13,7 +13,7 @@
 ! * (no type specified, resulting in an object file)
 
 ! All invocations should begin with flang -fc1, consume up to here.
-! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! ALL-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 
 ! Check that f90 files are not treated as "previously preprocessed"
 ! ... in --driver-mode=flang.
Index: clang/test/Driver/flang/flang.f90
===
--- clang/test/Driver/flang/flang.f90
+++ clang/test/Driver/flang/flang.f90
@@ -13,7 +13,7 @@
 ! * (no type specified, resulting in an object file)
 
 ! All invocations should begin with flang -fc1, consume up to here.
-! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1"
+! ALL-LABEL: "{{[^"]*}}flang-new{{(.exe)?}}" "-fc1"
 
 ! Check that f90 files are not treated as "previously preprocessed"
 ! ... in --driver-mode=flang.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143974: [clangd] Inactive regions support via dedicated protocol

2023-04-13 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks, the implementation looks good.




Comment at: clang-tools-extra/clangd/ClangdServer.cpp:977
+  return CB(InpAST.takeError());
+// Include inactive regions in semantic highlighting tokens only if the
+// client doesn't support a dedicated protocol for being informed about

nridge wrote:
> hokein wrote:
> > As discussed in the GitHub thread (the experiment of highlighting the 
> > inactive regions as comment is considered as a failure),  we should always 
> > not include the inactive region in the semantic highlighting, this will 
> > also simplify the existing code in semantic highlighting (e.g. 
> > https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/SemanticHighlighting.cpp#L464-L513).
> >  I think we can do it in a separated patch. 
> I think it might make sense to keep this support around for a while, so that 
> users whose clients do not yet support this extension still have //some// 
> indication of which preprocessor branches are inactive.
> 
> However, we could make it optional, since some users (for example those who 
> have to work on large sections of code in inactive preprocessor branches) may 
> prefer to see the client-side colors over having it all highlighted as one 
> color.
Rendering the inactive code as comment is the best we can perform per the 
standard LSP spec, but it provides an suboptimal (possibly confusing) UX 
experience, we have received some user complains about that.

Since we are doing it via an extension, I think we should just remove the old 
one in the next release (17).



Comment at: clang-tools-extra/clangd/Protocol.h:1743
 
+/// Parameters for the inactive regions (server-side) push notification.
+struct InactiveRegionsParams {

nit: mention this is a clangd extension as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143974

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

In D146987#4264491 , @jmorse wrote:

> ...
> H, that feels like a legitimate IR input where the configuration of 
> debug-info / intrinsics is just unexpected -- we probably shouldn't assert in 
> that situation but gracefully degrade to interpreting a dbg.assign as a 
> dbg.value.

That sounds reasonable - fixed in D148212 , 
thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[clang] 2031d7d - [mlir][Tensor] Drop SplitPaddingPatterns.

2023-04-13 Thread Nicolas Vasilache via cfe-commits

Author: Nicolas Vasilache
Date: 2023-04-13T03:38:29-07:00
New Revision: 2031d7d66dc8bf7ce2168edf6eef6ba568c16d4f

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

LOG: [mlir][Tensor] Drop SplitPaddingPatterns.

These old patterns are not in use in either MLIR or downstream projects except 
for one test.
Additionally this is redundant with logic in the tensor.pad tiling 
implementation.

Drop SplitPaddingPatterns to reduce entropy.

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

Added: 


Modified: 
clang/docs/tools/clang-formatted-files.txt
mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp

Removed: 
mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
mlir/test/Dialect/Tensor/split-padding.mlir



diff  --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 4b70e78cb1131..f48921d9f878a 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -8250,7 +8250,6 @@ mlir/lib/Dialect/Tensor/IR/TensorTilingInterfaceImpl.cpp
 mlir/lib/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.cpp
 mlir/lib/Dialect/Tensor/Transforms/Bufferize.cpp
 mlir/lib/Dialect/Tensor/Transforms/PassDetail.h
-mlir/lib/Dialect/Tensor/Transforms/SplitPadding.cpp
 mlir/lib/Dialect/Tensor/Utils/Utils.cpp
 mlir/lib/Dialect/Tosa/IR/TosaOps.cpp
 mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeConv2D.cpp

diff  --git a/mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h 
b/mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
index c0c46e9981dfa..a3b5abf08fd7a 100644
--- a/mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
+++ b/mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
@@ -41,12 +41,6 @@ void populateExpandOpsPatterns(RewritePatternSet &patterns);
 /// ops into `patterns`.
 void populateFoldTensorSubsetOpPatterns(RewritePatternSet &patterns);
 
-/// Populates `patterns` with patterns to wrap a tensor.pad op with an scf.if 
op
-/// to separate the cases where we don't need padding (all pad sizes are
-/// actually zeros) and where we indeed need padding.
-void populateSplitPaddingPatterns(RewritePatternSet &patterns,
-  PatternBenefit baseBenefit = 1);
-
 /// Collects patterns to merge consecutive tensor.insert_slice/extract_slice
 /// into one. These patterns are in in this separate entry point because the
 /// bufferization is sensitive over IR structure, particularly those

diff  --git a/mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt 
b/mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
index 9f6780730dc71..44579546f7ea5 100644
--- a/mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
+++ b/mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
@@ -7,7 +7,6 @@ add_mlir_dialect_library(MLIRTensorTransforms
   FoldTensorSubsetOps.cpp
   MergeConsecutiveInsertExtractSlicePatterns.cpp
   ReshapePatterns.cpp
-  SplitPaddingPatterns.cpp
   SwapExtractSliceWithProducerPatterns.cpp
 
   ADDITIONAL_HEADER_DIRS

diff  --git a/mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp 
b/mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
deleted file mode 100644
index 9536f3233b814..0
--- a/mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-//===- SplitPaddingPatterns.cpp - Splitting tensor.pad Op 
-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file implements patterns to wrap a tensor.pad op with an scf.if op
-/// to separate the cases where we don't need padding (all pad sizes are
-/// actually zeros) and where we indeed need padding.
-//
-//===--===//
-
-#include "mlir/Dialect/Arith/IR/Arith.h"
-#include "mlir/Dialect/SCF/IR/SCF.h"
-#include "mlir/Dialect/Tensor/IR/Tensor.h"
-#include "mlir/Dialect/Tensor/Transforms/Transforms.h"
-#include "mlir/Dialect/Utils/StaticValueUtils.h"
-#include "mlir/IR/PatternMatch.h"
-#include "llvm/Support/Debug.h"
-
-#define DEBUG_TYPE "mlir-tensor-split-padding"
-
-using namespace mlir;
-
-/// Returns true if the the given `attrOrValue` is a constant zero.
-static bool isZero(OpFoldResult attrOrValue) {
-  if (std::optional val = getConstantIntValue(attrOrValue))
-return *val == 0;
-  return false;
-}
-
-/// Gets the given `attrOrValue` as a Value by creating constant ops for
-/// att

[PATCH] D148207: [mlir][Tensor] Drop SplitPaddingPatterns.

2023-04-13 Thread Nicolas Vasilache via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2031d7d66dc8: [mlir][Tensor] Drop SplitPaddingPatterns. 
(authored by nicolasvasilache).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148207

Files:
  clang/docs/tools/clang-formatted-files.txt
  mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h
  mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt
  mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
  mlir/test/Dialect/Tensor/split-padding.mlir
  mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp

Index: mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
===
--- mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
+++ mlir/test/lib/Dialect/Tensor/TestTensorTransforms.cpp
@@ -43,11 +43,6 @@
 
   void runOnOperation() override;
 
-  Option testSplitPaddingPatterns{
-  *this, "test-split-padding-patterns",
-  llvm::cl::desc("Test patterns to split tensor.pad ops"),
-  llvm::cl::init(false)};
-
   Option testFoldConstantExtractSlice{
   *this, "test-fold-constant-extract-slice",
   llvm::cl::desc("Test folding arith.constant and tensor.extract_slice"),
@@ -111,12 +106,6 @@
   (void)applyPatternsAndFoldGreedily(rootOp, std::move(patterns));
 }
 
-static void applySplitPaddingPatterns(Operation *rootOp) {
-  RewritePatternSet patterns(rootOp->getContext());
-  tensor::populateSplitPaddingPatterns(patterns);
-  (void)applyPatternsAndFoldGreedily(rootOp, std::move(patterns));
-}
-
 static void applyFoldConstantExtractSlicePatterns(Operation *rootOp) {
   RewritePatternSet patterns(rootOp->getContext());
   tensor::ControlConstantExtractSliceFusionFn controlFn =
@@ -291,8 +280,6 @@
   Operation *rootOp = getOperation();
   if (testSimplifyPackPatterns)
 applySimplifyPackPatterns(rootOp);
-  if (testSplitPaddingPatterns)
-applySplitPaddingPatterns(rootOp);
   if (testFoldConstantExtractSlice)
 applyFoldConstantExtractSlicePatterns(rootOp);
   if (testFoldConsecutiveInsertExtractSlice)
Index: mlir/test/Dialect/Tensor/split-padding.mlir
===
--- mlir/test/Dialect/Tensor/split-padding.mlir
+++ /dev/null
@@ -1,44 +0,0 @@
-// RUN: mlir-opt -split-input-file -test-tensor-transform-patterns=test-split-padding-patterns %s | FileCheck %s
-
-// CHECK-LABEL: func @pad_all_zero_sizes
-func.func @pad_all_zero_sizes(%input: tensor) -> tensor {
-  %f0 = arith.constant 0.0 : f32
-  %c0 = arith.constant 0 : index
-  %0 = tensor.pad %input low[0, %c0, 0] high[%c0, 0, 0] {
-  ^bb0(%dim0: index, %dim1: index, %dim2: index):
-tensor.yield %f0 : f32
-  } : tensor to tensor
-  return %0 : tensor
-}
-
-// CHECK-NOT: scf.if
-// CHECK: tensor.pad
-
-// -
-
-// CHECK-LABEL: func @pad_non_zero_sizes
-//  CHECK-SAME: (%[[INPUT:.+]]: tensor, %[[LOW0:.+]]: index, %[[HIGH1:.+]]: index)
-func.func @pad_non_zero_sizes(%input: tensor, %low0: index, %high1: index) -> tensor {
-  %f0 = arith.constant 0.0 : f32
-  %0 = tensor.pad %input low[%low0, 0, 0] high[0, %high1, 0] {
-  ^bb0(%dim0: index, %dim1: index, %dim2: index):
-tensor.yield %f0 : f32
-  } : tensor to tensor
-  return %0 : tensor
-}
-
-// CHECK-DAG: %[[F0:.+]] = arith.constant 0.00e+00 : f32
-// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
-// CHECK: %[[EQ0:.+]] = arith.cmpi eq, %[[LOW0]], %[[C0]] : index
-// CHECK: %[[EQ1:.+]] = arith.cmpi eq, %[[HIGH1]], %[[C0]] : index
-// CHECK: %[[AND:.+]] = arith.andi %[[EQ0]], %[[EQ1]] : i1
-// CHECK: %[[IF:.+]] = scf.if %[[AND]] -> (tensor) {
-// CHECK:   scf.yield %[[INPUT]] : tensor
-// CHECK: } else {
-// CHECK:   %[[PAD:.+]] = tensor.pad %[[INPUT]] low[%[[LOW0]], 0, 0] high[0, %[[HIGH1]], 0]  {
-// CHECK:   ^bb0(%{{.+}}: index, %{{.+}}: index, %{{.+}}: index):
-// CHECK: tensor.yield %[[F0]] : f32
-// CHECK:   } : tensor to tensor
-// CHECK:   scf.yield %[[PAD]] : tensor
-// CHECK: }
-// CHECK: return %[[IF]] : tensor
Index: mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
===
--- mlir/lib/Dialect/Tensor/Transforms/SplitPaddingPatterns.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-//===- SplitPaddingPatterns.cpp - Splitting tensor.pad Op -===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file implements patterns to wrap a tensor.pad op with an scf.if op
-/// to separate the cases where we don't need padding (all pad sizes are
-/// actually zeros) and where we indeed need padding.
-//
-//===---

[PATCH] D148158: [include-cleaner] Handle incomplete template specializations

2023-04-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/include-cleaner/lib/WalkAST.cpp:85
 // This is the underlying decl used by TemplateSpecializationType, can be
 // null when type is dependent if so fallback to primary template.
 CXXRecordDecl *TD = TST->getAsCXXRecordDecl();

update comment - dependent or not resolved to a pattern yet?



Comment at: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp:163
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete templates don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(

There's no incomplete template here (did you mean `template  struct Foo;`?)

If it's enough that the template is never instantiated then maybe it's still 
clearer not to provide a definition (and tweak the comment slightly?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148158

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


[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
usaxena95 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148213

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Tweak.cpp

Index: clang-tools-extra/clangd/refactor/Tweak.cpp
===
--- clang-tools-extra/clangd/refactor/Tweak.cpp
+++ clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -104,8 +104,9 @@
 Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
 tooling::Replacements Replacements) {
   Edit Ed(SM.getBufferData(FID), std::move(Replacements));
-  if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
-return std::make_pair(*FilePath, std::move(Ed));
+  if (const auto FERef = SM.getFileEntryRefForID(FID))
+if (auto FilePath = getCanonicalPath(*FERef, SM))
+  return std::make_pair(*FilePath, std::move(Ed));
   return error("Failed to get absolute path for edited file: {0}",
SM.getFileEntryRefForID(FID)->getName());
 }
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -46,10 +46,10 @@
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
-  const auto *F = SM.getFileEntryForID(FID);
+  const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
 return false; // Skip invalid files.
-  auto AbsPath = getCanonicalPath(F, SM);
+  auto AbsPath = getCanonicalPath(*F, SM);
   if (!AbsPath)
 return false; // Skip files without absolute path.
   std::lock_guard Lock(FilesMu);
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -205,11 +205,11 @@
 
   // Returns a canonical URI for the file \p FE.
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef &FE) {
 auto R = CacheFEToURI.try_emplace(FE);
 if (R.second) {
   auto CanonPath = getCanonicalPath(FE, SM);
-  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE->getName());
+  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
 }
 return *R.first->second;
   }
@@ -218,7 +218,7 @@
   // If the file is in the FileManager, use that to canonicalize the path.
   // We attempt to make the path absolute in any case.
   const std::string &toURI(llvm::StringRef Path) {
-if (auto File = SM.getFileManager().getFile(Path))
+if (auto File = SM.getFileManager().getFileRef(Path))
   return toURI(*File);
 return toURIInternal(Path);
   }
@@ -373,7 +373,7 @@
   }
 
   llvm::StringRef getIncludeHeaderUncached(FileID FID) {
-const FileEntry *FE = SM.getFileEntryForID(FID);
+const auto FE = SM.getFileEntryRefForID(FID);
 if (!FE || FE->getName().empty())
   return "";
 llvm::StringRef Filename = FE->getName();
@@ -392,13 +392,15 @@
 // Framework headers are spelled as , not
 // "path/FrameworkName.framework/Headers/Foo.h".
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(&FE->getFileEntry(),
+ /*WantExternal*/ false))
   if (!HFI->Framework.empty())
-if (auto Spelling =
-getFrameworkHeaderIncludeSpelling(FE, HFI->Framework, HS))
+if (auto Spelling = getFrameworkHeaderIncludeSpelling(
+&FE->getFileEntry(), HFI->Framework, HS))
   return *Spelling;
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(&FE->getFileEntry(),
+PP->getSourceManager(),
 PP->getHeaderSearchInfo())) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
@@ -409,7 +411,7 @@
   return "";
 }
 // Standard case: just insert the file itself.
-return 

[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 513165.
usaxena95 added a comment.

More refactorings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Tweak.cpp

Index: clang-tools-extra/clangd/refactor/Tweak.cpp
===
--- clang-tools-extra/clangd/refactor/Tweak.cpp
+++ clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -104,8 +104,9 @@
 Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
 tooling::Replacements Replacements) {
   Edit Ed(SM.getBufferData(FID), std::move(Replacements));
-  if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
-return std::make_pair(*FilePath, std::move(Ed));
+  if (const auto FE = SM.getFileEntryRefForID(FID))
+if (auto FilePath = getCanonicalPath(*FE, SM))
+  return std::make_pair(*FilePath, std::move(Ed));
   return error("Failed to get absolute path for edited file: {0}",
SM.getFileEntryRefForID(FID)->getName());
 }
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -46,10 +46,10 @@
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
-  const auto *F = SM.getFileEntryForID(FID);
+  const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
 return false; // Skip invalid files.
-  auto AbsPath = getCanonicalPath(F, SM);
+  auto AbsPath = getCanonicalPath(*F, SM);
   if (!AbsPath)
 return false; // Skip files without absolute path.
   std::lock_guard Lock(FilesMu);
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -205,11 +205,11 @@
 
   // Returns a canonical URI for the file \p FE.
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef &FE) {
 auto R = CacheFEToURI.try_emplace(FE);
 if (R.second) {
   auto CanonPath = getCanonicalPath(FE, SM);
-  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE->getName());
+  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
 }
 return *R.first->second;
   }
@@ -218,7 +218,7 @@
   // If the file is in the FileManager, use that to canonicalize the path.
   // We attempt to make the path absolute in any case.
   const std::string &toURI(llvm::StringRef Path) {
-if (auto File = SM.getFileManager().getFile(Path))
+if (auto File = SM.getFileManager().getFileRef(Path))
   return toURI(*File);
 return toURIInternal(Path);
   }
@@ -373,7 +373,7 @@
   }
 
   llvm::StringRef getIncludeHeaderUncached(FileID FID) {
-const FileEntry *FE = SM.getFileEntryForID(FID);
+const auto FE = SM.getFileEntryRefForID(FID);
 if (!FE || FE->getName().empty())
   return "";
 llvm::StringRef Filename = FE->getName();
@@ -392,13 +392,15 @@
 // Framework headers are spelled as , not
 // "path/FrameworkName.framework/Headers/Foo.h".
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(&FE->getFileEntry(),
+ /*WantExternal*/ false))
   if (!HFI->Framework.empty())
-if (auto Spelling =
-getFrameworkHeaderIncludeSpelling(FE, HFI->Framework, HS))
+if (auto Spelling = getFrameworkHeaderIncludeSpelling(
+&FE->getFileEntry(), HFI->Framework, HS))
   return *Spelling;
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(&FE->getFileEntry(),
+PP->getSourceManager(),
 PP->getHeaderSearchInfo())) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
@@ -409,7 +411,7 @@
   return "";
 }
 // Standard case: just insert the file itself.
-return toURI(FE);
+return toURI(*FE);
   }
 };
 
@@ -417,12 +419,12 @@
 std::optional
 SymbolCollector::g

[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 513168.
usaxena95 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Tweak.cpp

Index: clang-tools-extra/clangd/refactor/Tweak.cpp
===
--- clang-tools-extra/clangd/refactor/Tweak.cpp
+++ clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -104,8 +104,9 @@
 Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
 tooling::Replacements Replacements) {
   Edit Ed(SM.getBufferData(FID), std::move(Replacements));
-  if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
-return std::make_pair(*FilePath, std::move(Ed));
+  if (const auto FE = SM.getFileEntryRefForID(FID))
+if (auto FilePath = getCanonicalPath(*FE, SM))
+  return std::make_pair(*FilePath, std::move(Ed));
   return error("Failed to get absolute path for edited file: {0}",
SM.getFileEntryRefForID(FID)->getName());
 }
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -46,10 +46,10 @@
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
-  const auto *F = SM.getFileEntryForID(FID);
+  const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
 return false; // Skip invalid files.
-  auto AbsPath = getCanonicalPath(F, SM);
+  auto AbsPath = getCanonicalPath(*F, SM);
   if (!AbsPath)
 return false; // Skip files without absolute path.
   std::lock_guard Lock(FilesMu);
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -205,11 +205,11 @@
 
   // Returns a canonical URI for the file \p FE.
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef &FE) {
 auto R = CacheFEToURI.try_emplace(FE);
 if (R.second) {
   auto CanonPath = getCanonicalPath(FE, SM);
-  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE->getName());
+  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
 }
 return *R.first->second;
   }
@@ -218,7 +218,7 @@
   // If the file is in the FileManager, use that to canonicalize the path.
   // We attempt to make the path absolute in any case.
   const std::string &toURI(llvm::StringRef Path) {
-if (auto File = SM.getFileManager().getFile(Path))
+if (auto File = SM.getFileManager().getFileRef(Path))
   return toURI(*File);
 return toURIInternal(Path);
   }
@@ -373,7 +373,7 @@
   }
 
   llvm::StringRef getIncludeHeaderUncached(FileID FID) {
-const FileEntry *FE = SM.getFileEntryForID(FID);
+const auto FE = SM.getFileEntryRefForID(FID);
 if (!FE || FE->getName().empty())
   return "";
 llvm::StringRef Filename = FE->getName();
@@ -392,13 +392,15 @@
 // Framework headers are spelled as , not
 // "path/FrameworkName.framework/Headers/Foo.h".
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(&FE->getFileEntry(),
+ /*WantExternal*/ false))
   if (!HFI->Framework.empty())
-if (auto Spelling =
-getFrameworkHeaderIncludeSpelling(FE, HFI->Framework, HS))
+if (auto Spelling = getFrameworkHeaderIncludeSpelling(
+&FE->getFileEntry(), HFI->Framework, HS))
   return *Spelling;
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(&FE->getFileEntry(),
+PP->getSourceManager(),
 PP->getHeaderSearchInfo())) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
@@ -409,7 +411,7 @@
   return "";
 }
 // Standard case: just insert the file itself.
-return toURI(FE);
+return toURI(*FE);
   }
 };
 
@@ -417,12 +419,12 @@
 std::optional
 SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
   const auto &SM

[PATCH] D148158: [include-cleaner] Handle incomplete template specializations

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

- Update comments & test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148158

Files:
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -144,6 +144,9 @@
   ElementsAre(Decl::CXXRecord));
 
   // Implicit instantiations references most relevant template.
+  EXPECT_THAT(
+  testWalk("template struct $explicit^Foo;", "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(
   testWalk("template struct $explicit^Foo {};", "^Foo x;"),
   ElementsAre(Decl::CXXRecord));
@@ -154,9 +157,15 @@
   ElementsAre(Decl::ClassTemplateSpecialization));
   EXPECT_THAT(testWalk(R"cpp(
 template struct Foo {};
-template struct $explicit^Foo { void x(); };)cpp",
+template struct $explicit^Foo {};)cpp",
"^Foo x;"),
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete instantiations don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(
+template struct $explicit^Foo;
+template struct Foo;)cpp",
+   "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(testWalk(R"cpp(
 template struct $explicit^Foo {};
 template struct Foo;)cpp",
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/Support/Casting.h"
@@ -81,9 +82,10 @@
 if (llvm::isa_and_present(ND))
   return ND;
 // This is the underlying decl used by TemplateSpecializationType, can be
-// null when type is dependent if so fallback to primary template.
+// null when type is dependent or not resolved to a pattern yet.
+// If so, fallback to primary template.
 CXXRecordDecl *TD = TST->getAsCXXRecordDecl();
-if (!TD)
+if (!TD || TD->getTemplateSpecializationKind() == TSK_Undeclared)
   return ND;
 // We ignore explicit instantiations. This might imply marking the wrong
 // declaration as used in specific cases, but seems like the right 
trade-off


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -144,6 +144,9 @@
   ElementsAre(Decl::CXXRecord));
 
   // Implicit instantiations references most relevant template.
+  EXPECT_THAT(
+  testWalk("template struct $explicit^Foo;", "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(
   testWalk("template struct $explicit^Foo {};", "^Foo x;"),
   ElementsAre(Decl::CXXRecord));
@@ -154,9 +157,15 @@
   ElementsAre(Decl::ClassTemplateSpecialization));
   EXPECT_THAT(testWalk(R"cpp(
 template struct Foo {};
-template struct $explicit^Foo { void x(); };)cpp",
+template struct $explicit^Foo {};)cpp",
"^Foo x;"),
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete instantiations don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(
+template struct $explicit^Foo;
+template struct Foo;)cpp",
+   "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(testWalk(R"cpp(
 template struct $explicit^Foo {};
 template struct Foo;)cpp",
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/Support/Casting.h"
@@ -81,9 +82,10 @@
 if (llvm::isa_and_present(ND))
   return ND;
 // This is the underlying decl used by TemplateSpecializationType, can be
-// nul

[PATCH] D148158: [include-cleaner] Handle incomplete template specializations

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp:163
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete templates don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(

sammccall wrote:
> There's no incomplete template here (did you mean `template  Foo;` or `template  struct Foo;`?)
> 
> If it's enough that the template is never instantiated then maybe it's still 
> clearer not to provide a definition (and tweak the comment slightly?)
> If it's enough that the template is never instantiated then maybe it's still 
> clearer not to provide a definition (and tweak the comment slightly?)

right, i meant the instantiation being "incomplete", not the template-decl 
itself. dropping the definition and updating the comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148158

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


[clang-tools-extra] 3d6d2ae - [include-cleaner] Handle incomplete template specializations

2023-04-13 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-04-13T13:34:12+02:00
New Revision: 3d6d2ae6f490f0698e3d4727ae44db34b30ea33e

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

LOG: [include-cleaner] Handle incomplete template specializations

Instantiation pattern is null for incomplete template types and using
specializaiton decl results in not seeing re-declarations.

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp 
b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
index 25afdaa3a75b0..e977bcbb402f7 100644
--- a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/Support/Casting.h"
@@ -81,9 +82,10 @@ class ASTWalker : public RecursiveASTVisitor {
 if (llvm::isa_and_present(ND))
   return ND;
 // This is the underlying decl used by TemplateSpecializationType, can be
-// null when type is dependent if so fallback to primary template.
+// null when type is dependent or not resolved to a pattern yet.
+// If so, fallback to primary template.
 CXXRecordDecl *TD = TST->getAsCXXRecordDecl();
-if (!TD)
+if (!TD || TD->getTemplateSpecializationKind() == TSK_Undeclared)
   return ND;
 // We ignore explicit instantiations. This might imply marking the wrong
 // declaration as used in specific cases, but seems like the right 
trade-off

diff  --git a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
index ad5bb0aba3076..2060ffe3bb56c 100644
--- a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -144,6 +144,9 @@ TEST(WalkAST, ClassTemplates) {
   ElementsAre(Decl::CXXRecord));
 
   // Implicit instantiations references most relevant template.
+  EXPECT_THAT(
+  testWalk("template struct $explicit^Foo;", "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(
   testWalk("template struct $explicit^Foo {};", "^Foo x;"),
   ElementsAre(Decl::CXXRecord));
@@ -154,9 +157,15 @@ TEST(WalkAST, ClassTemplates) {
   ElementsAre(Decl::ClassTemplateSpecialization));
   EXPECT_THAT(testWalk(R"cpp(
 template struct Foo {};
-template struct $explicit^Foo { void x(); };)cpp",
+template struct $explicit^Foo {};)cpp",
"^Foo x;"),
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete instantiations don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(
+template struct $explicit^Foo;
+template struct Foo;)cpp",
+   "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(testWalk(R"cpp(
 template struct $explicit^Foo {};
 template struct Foo;)cpp",



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


[PATCH] D148158: [include-cleaner] Handle incomplete template specializations

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3d6d2ae6f490: [include-cleaner] Handle incomplete template 
specializations (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148158

Files:
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -144,6 +144,9 @@
   ElementsAre(Decl::CXXRecord));
 
   // Implicit instantiations references most relevant template.
+  EXPECT_THAT(
+  testWalk("template struct $explicit^Foo;", "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(
   testWalk("template struct $explicit^Foo {};", "^Foo x;"),
   ElementsAre(Decl::CXXRecord));
@@ -154,9 +157,15 @@
   ElementsAre(Decl::ClassTemplateSpecialization));
   EXPECT_THAT(testWalk(R"cpp(
 template struct Foo {};
-template struct $explicit^Foo { void x(); };)cpp",
+template struct $explicit^Foo {};)cpp",
"^Foo x;"),
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete instantiations don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(
+template struct $explicit^Foo;
+template struct Foo;)cpp",
+   "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(testWalk(R"cpp(
 template struct $explicit^Foo {};
 template struct Foo;)cpp",
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/Support/Casting.h"
@@ -81,9 +82,10 @@
 if (llvm::isa_and_present(ND))
   return ND;
 // This is the underlying decl used by TemplateSpecializationType, can be
-// null when type is dependent if so fallback to primary template.
+// null when type is dependent or not resolved to a pattern yet.
+// If so, fallback to primary template.
 CXXRecordDecl *TD = TST->getAsCXXRecordDecl();
-if (!TD)
+if (!TD || TD->getTemplateSpecializationKind() == TSK_Undeclared)
   return ND;
 // We ignore explicit instantiations. This might imply marking the wrong
 // declaration as used in specific cases, but seems like the right 
trade-off


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -144,6 +144,9 @@
   ElementsAre(Decl::CXXRecord));
 
   // Implicit instantiations references most relevant template.
+  EXPECT_THAT(
+  testWalk("template struct $explicit^Foo;", "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(
   testWalk("template struct $explicit^Foo {};", "^Foo x;"),
   ElementsAre(Decl::CXXRecord));
@@ -154,9 +157,15 @@
   ElementsAre(Decl::ClassTemplateSpecialization));
   EXPECT_THAT(testWalk(R"cpp(
 template struct Foo {};
-template struct $explicit^Foo { void x(); };)cpp",
+template struct $explicit^Foo {};)cpp",
"^Foo x;"),
   ElementsAre(Decl::ClassTemplatePartialSpecialization));
+  // Incomplete instantiations don't have a specific specialization associated.
+  EXPECT_THAT(testWalk(R"cpp(
+template struct $explicit^Foo;
+template struct Foo;)cpp",
+   "^Foo x();"),
+  ElementsAre(Decl::Kind::ClassTemplate));
   EXPECT_THAT(testWalk(R"cpp(
 template struct $explicit^Foo {};
 template struct Foo;)cpp",
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/Support/Casting.h"
@@ -81,9 +82,10 @@
 if (llvm::isa_and_present(ND))
  

[clang] 650d69f - [clang][NFC] Fix comment typo

2023-04-13 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-13T13:42:58+02:00
New Revision: 650d69ffe4d0ff2d2c84b8bf19555a8a9b10aae8

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

LOG: [clang][NFC] Fix comment typo

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 95b5f257c63d4..6dbf7f4ce6f14 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -787,7 +787,7 @@ void TextDiagnostic::emitFilename(StringRef Filename, const 
SourceManager &SM) {
 
 /// Print out the file/line/column information and include trace.
 ///
-/// This method handlen the emission of the diagnostic location information.
+/// This method handles the emission of the diagnostic location information.
 /// This includes extracting as much location information as is present for
 /// the diagnostic and printing it, as well as any include stack or source
 /// ranges necessary.



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


Re: [clang] c1f7636 - [C++20] [Modules] Continue parsing after we found reserved module names

2023-04-13 Thread Aaron Ballman via cfe-commits
On Thu, Apr 13, 2023 at 3:14 AM Chuanqi Xu via cfe-commits
 wrote:
>
>
> Author: Chuanqi Xu
> Date: 2023-04-13T15:14:34+08:00
> New Revision: c1f76363e0db41ab6eb9ebedd687ee098491e9b7
>
> URL: 
> https://github.com/llvm/llvm-project/commit/c1f76363e0db41ab6eb9ebedd687ee098491e9b7
> DIFF: 
> https://github.com/llvm/llvm-project/commit/c1f76363e0db41ab6eb9ebedd687ee098491e9b7.diff
>
> LOG: [C++20] [Modules] Continue parsing after we found reserved module names
>
> Close https://github.com/llvm/llvm-project/issues/62112
>
> In the previous change, we'll stop parsing directly after we found
> reserved module names. But this may be too aggressive. This patch
> changes this. Note that the parsing will still be stopped if the module
> name is `module` or `import`.

Thank you for fixing this up! I think this should be backported to 16.0.2, WDYT?

~Aaron

>
> Added:
> clang/test/Modules/reserved-names-1.cppm
> clang/test/Modules/reserved-names-2.cppm
> clang/test/Modules/reserved-names-3.cppm
> clang/test/Modules/reserved-names-4.cppm
>
> Modified:
> clang/lib/Sema/SemaModule.cpp
>
> Removed:
> clang/test/Modules/reserved-names-1.cpp
> clang/test/Modules/reserved-names-2.cpp
> clang/test/Modules/reserved-names-3.cpp
> clang/test/Modules/reserved-names-4.cpp
>
>
> 
> diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
> index 6c39cc0b44ca4..84a1fd854d804 100644
> --- a/clang/lib/Sema/SemaModule.cpp
> +++ b/clang/lib/Sema/SemaModule.cpp
> @@ -162,7 +162,8 @@ static bool DiagReservedModuleName(Sema &S, const 
> IdentifierInfo *II,
>case Invalid:
>  return S.Diag(Loc, diag::err_invalid_module_name) << II;
>case Reserved:
> -return S.Diag(Loc, diag::warn_reserved_module_name) << II;
> +S.Diag(Loc, diag::warn_reserved_module_name) << II;
> +return false;
>}
>llvm_unreachable("fell off a fully covered switch");
>  }
> @@ -267,10 +268,8 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, 
> SourceLocation ModuleLoc,
>if (!getSourceManager().isInSystemHeader(Path[0].second) &&
>(FirstComponentName == "std" ||
> (FirstComponentName.startswith("std") &&
> -llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit {
> +llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit
>  Diag(Path[0].second, diag::warn_reserved_module_name) << Path[0].first;
> -return nullptr;
> -  }
>
>// Then test all of the components in the path to see if any of them are
>// using another kind of reserved or invalid identifier.
>
> diff  --git a/clang/test/Modules/reserved-names-1.cpp 
> b/clang/test/Modules/reserved-names-1.cpp
> deleted file mode 100644
> index a92c2244f1cb6..0
> --- a/clang/test/Modules/reserved-names-1.cpp
> +++ /dev/null
> @@ -1,46 +0,0 @@
> -// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,loud %s
> -// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected 
> -Wno-reserved-module-identifier %s
> -
> -// expected-note@1 15{{add 'module;' to the start of the file to introduce a 
> global module fragment}}
> -
> -module std;// loud-warning {{'std' is a reserved name for a module}}
> -module _Test;  // loud-warning {{'_Test' is a reserved name for a module}} \
> -  expected-error {{module declaration must occur at the 
> start of the translation unit}}
> -module module; // expected-error {{'module' is an invalid name for a 
> module}} \
> -  expected-error {{module declaration must occur at the 
> start of the translation unit}}
> -module std0;   // loud-warning {{'std0' is a reserved name for a module}} \
> -  expected-error {{module declaration must occur at the 
> start of the translation unit}}
> -
> -export module module; // expected-error {{'module' is an invalid name for a 
> module}} \
> - expected-error {{module declaration must occur at 
> the start of the translation unit}}
> -export module import; // expected-error {{'import' is an invalid name for a 
> module}} \
> - expected-error {{module declaration must occur at 
> the start of the translation unit}}
> -export module _Test;  // loud-warning {{'_Test' is a reserved name for a 
> module}} \
> - expected-error {{module declaration must occur at 
> the start of the translation unit}}
> -export module __test; // loud-warning {{'__test' is a reserved name for a 
> module}} \
> - expected-error {{module declaration must occur at 
> the start of the translation unit}}
> -export module te__st; // loud-warning {{'te__st' is a reserved name for a 
> module}} \
> - expected-error {{module declaration must occur at 
> the start of the translation unit}}
> -export module std;// loud-warning {{'std' is a reserved name for a 
> module}} \
> -

[clang] dfafb7f - [clang][NFC] More range for loops in TextDiagnostic.cpp

2023-04-13 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-13T13:43:57+02:00
New Revision: dfafb7fe5af3e55ff35fb5dbc685a4337af5b29c

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

LOG: [clang][NFC] More range for loops in TextDiagnostic.cpp

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 6dbf7f4ce6f1..08f84d28bb85 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -856,15 +856,14 @@ void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, 
PresumedLoc PLoc,
 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
 bool PrintedRange = false;
 
-for (ArrayRef::const_iterator RI = Ranges.begin(),
- RE = Ranges.end();
- RI != RE; ++RI) {
+for (const auto &R : Ranges) {
   // Ignore invalid ranges.
-  if (!RI->isValid()) continue;
+  if (!R.isValid())
+continue;
 
   auto &SM = Loc.getManager();
-  SourceLocation B = SM.getExpansionLoc(RI->getBegin());
-  CharSourceRange ERange = SM.getExpansionRange(RI->getEnd());
+  SourceLocation B = SM.getExpansionLoc(R.getBegin());
+  CharSourceRange ERange = SM.getExpansionRange(R.getEnd());
   SourceLocation E = ERange.getEnd();
   bool IsTokenRange = ERange.isTokenRange();
 
@@ -1068,51 +1067,51 @@ static std::string buildFixItInsertionLine(FileID FID,
 return FixItInsertionLine;
   unsigned PrevHintEndCol = 0;
 
-  for (ArrayRef::iterator I = Hints.begin(), E = Hints.end();
-   I != E; ++I) {
-if (!I->CodeToInsert.empty()) {
-  // We have an insertion hint. Determine whether the inserted
-  // code contains no newlines and is on the same line as the caret.
-  std::pair HintLocInfo
-= SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
-  if (FID == HintLocInfo.first &&
-  LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
-  StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) 
{
-// Insert the new code into the line just below the code
-// that the user wrote.
-// Note: When modifying this function, be very careful about what is a
-// "column" (printed width, platform-dependent) and what is a
-// "byte offset" (SourceManager "column").
-unsigned HintByteOffset
-  = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
-
-// The hint must start inside the source or right at the end
-assert(HintByteOffset < static_cast(map.bytes())+1);
-unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
-
-// If we inserted a long previous hint, push this one forwards, and add
-// an extra space to show that this is not part of the previous
-// completion. This is sort of the best we can do when two hints appear
-// to overlap.
-//
-// Note that if this hint is located immediately after the previous
-// hint, no space will be added, since the location is more important.
-if (HintCol < PrevHintEndCol)
-  HintCol = PrevHintEndCol + 1;
-
-// This should NOT use HintByteOffset, because the source might have
-// Unicode characters in earlier columns.
-unsigned NewFixItLineSize = FixItInsertionLine.size() +
-  (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
-if (NewFixItLineSize > FixItInsertionLine.size())
-  FixItInsertionLine.resize(NewFixItLineSize, ' ');
-
-std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
-  FixItInsertionLine.end() - I->CodeToInsert.size());
-
-PrevHintEndCol =
-  HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
-  }
+  for (const auto &H : Hints) {
+if (H.CodeToInsert.empty())
+  continue;
+
+// We have an insertion hint. Determine whether the inserted
+// code contains no newlines and is on the same line as the caret.
+std::pair HintLocInfo =
+SM.getDecomposedExpansionLoc(H.RemoveRange.getBegin());
+if (FID == HintLocInfo.first &&
+LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
+StringRef(H.CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
+  // Insert the new code into the line just below the code
+  // that the user wrote.
+  // Note: When modifying this function, be very careful about what is a
+  // "column" (printed width, platform-dependent) and what is a
+  // "byte offset" (SourceManager "column").
+  unsigned HintByteOffset =
+  SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
+
+  // The hint must start in

[clang] 66202d8 - Make 'static assertion failed' diagnostics point to the static assertion expression

2023-04-13 Thread Aaron Ballman via cfe-commits

Author: Jorge Pinto Sousa
Date: 2023-04-13T08:15:13-04:00
New Revision: 66202d83b5d47479ae0f8117aebb523ba7eff82d

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

LOG: Make 'static assertion failed' diagnostics point to the static assertion 
expression

"static assertion failed" pointed to the static_assert token and
then underlined the static assertion expression:

:3:1: error: static assertion failed
static_assert(false);
^ ~
1 error generated.
See Godbolt: https://godbolt.org/z/r38booz59

Now it points to and highlights the assertion expression.

Fixes https://github.com/llvm/llvm-project/issues/61951
Differential Revision: https://reviews.llvm.org/D147745

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/SemaCXX/static-assert.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e08aecfcc881..9abfaf5b2322 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -218,6 +218,9 @@ Improvements to Clang's diagnostics
 - Clang now avoids unnecessary diagnostic warnings for obvious expressions in
   the case of binary operators with logical OR operations.
   (`#57906 `_)
+- Clang's "static assertion failed" diagnostic now points to the static 
assertion
+  expression instead of pointing to the ``static_assert`` token.
+  (`#61951 `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 524f0a07..7fd12319e4d6 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -16820,19 +16820,20 @@ Decl 
*Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   if (InnerCond && isa(InnerCond)) {
 // Drill down into concept specialization expressions to see why they
 // weren't satisfied.
-Diag(StaticAssertLoc, diag::err_static_assert_failed)
-  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
+Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
+<< !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
 ConstraintSatisfaction Satisfaction;
 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
   DiagnoseUnsatisfiedConstraint(Satisfaction);
   } else if (InnerCond && !isa(InnerCond)
&& !isa(InnerCond)) {
-Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
-  << InnerCondDescription << !AssertMessage
-  << Msg.str() << InnerCond->getSourceRange();
+Diag(InnerCond->getBeginLoc(),
+ diag::err_static_assert_requirement_failed)
+<< InnerCondDescription << !AssertMessage << Msg.str()
+<< InnerCond->getSourceRange();
 DiagnoseStaticAssertDetails(InnerCond);
   } else {
-Diag(StaticAssertLoc, diag::err_static_assert_failed)
+Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
 PrintContextStack();
   }

diff  --git a/clang/test/SemaCXX/static-assert.cpp 
b/clang/test/SemaCXX/static-assert.cpp
index ea8037815a20..83fc4bd25628 100644
--- a/clang/test/SemaCXX/static-assert.cpp
+++ b/clang/test/SemaCXX/static-assert.cpp
@@ -287,5 +287,28 @@ namespace Diagnostics {
   static_assert(CHECK_4(a) && A_IS_B, ""); // expected-error {{failed}} \
// expected-note {{evaluates to '4 
== 5'}}
 
+  static_assert(
+false, // expected-error {{static assertion failed}}
+""
+  );
+
+  static_assert(
+true && false, // expected-error {{static assertion failed due to 
requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+true && false, // expected-error {{static assertion failed due to 
requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+(true && // expected-error {{static assertion failed due to requirement 
'(true && false) || false'}}
+false)
+|| false,
+""
+  );
 
 }



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


[PATCH] D147745: Make 'static assertion failed' diagnostics point to the static assertion expression

2023-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG66202d83b5d4: Make 'static assertion failed' 
diagnostics point to the static assertion… (authored by sousajo, committed by 
aaron.ballman).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147745

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/static-assert.cpp


Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -287,5 +287,28 @@
   static_assert(CHECK_4(a) && A_IS_B, ""); // expected-error {{failed}} \
// expected-note {{evaluates to '4 
== 5'}}
 
+  static_assert(
+false, // expected-error {{static assertion failed}}
+""
+  );
+
+  static_assert(
+true && false, // expected-error {{static assertion failed due to 
requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+true && false, // expected-error {{static assertion failed due to 
requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+(true && // expected-error {{static assertion failed due to requirement 
'(true && false) || false'}}
+false)
+|| false,
+""
+  );
 
 }
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -16820,19 +16820,20 @@
   if (InnerCond && isa(InnerCond)) {
 // Drill down into concept specialization expressions to see why they
 // weren't satisfied.
-Diag(StaticAssertLoc, diag::err_static_assert_failed)
-  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
+Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
+<< !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
 ConstraintSatisfaction Satisfaction;
 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
   DiagnoseUnsatisfiedConstraint(Satisfaction);
   } else if (InnerCond && !isa(InnerCond)
&& !isa(InnerCond)) {
-Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
-  << InnerCondDescription << !AssertMessage
-  << Msg.str() << InnerCond->getSourceRange();
+Diag(InnerCond->getBeginLoc(),
+ diag::err_static_assert_requirement_failed)
+<< InnerCondDescription << !AssertMessage << Msg.str()
+<< InnerCond->getSourceRange();
 DiagnoseStaticAssertDetails(InnerCond);
   } else {
-Diag(StaticAssertLoc, diag::err_static_assert_failed)
+Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
 PrintContextStack();
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -218,6 +218,9 @@
 - Clang now avoids unnecessary diagnostic warnings for obvious expressions in
   the case of binary operators with logical OR operations.
   (`#57906 `_)
+- Clang's "static assertion failed" diagnostic now points to the static 
assertion
+  expression instead of pointing to the ``static_assert`` token.
+  (`#61951 `_)
 
 Bug Fixes in This Version
 -


Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -287,5 +287,28 @@
   static_assert(CHECK_4(a) && A_IS_B, ""); // expected-error {{failed}} \
// expected-note {{evaluates to '4 == 5'}}
 
+  static_assert(
+false, // expected-error {{static assertion failed}}
+""
+  );
+
+  static_assert(
+true && false, // expected-error {{static assertion failed due to requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+true && false, // expected-error {{static assertion failed due to requirement 'true && false'}}
+""
+  );
+
+  static_assert(
+// with a comment here
+(true && // expected-error {{static assertion failed due to requirement '(true && false) || false'}}
+false)
+|| false,
+""
+  );
 
 }
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema

[PATCH] D145868: [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-13 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked an inline comment as done.
balazske added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:8627
+  )";
+  Decl *ToTU = getToTuDecl("", Lang_CXX11);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);

bjope wrote:
> With Werror we get:
> 
> ```
> ../../clang/unittests/AST/ASTImporterTest.cpp:8627:9: error: unused variable 
> 'ToTU' [-Werror,-Wunused-variable]
>   Decl *ToTU = getToTuDecl("", Lang_CXX11);
> ^
> 
> ```
Problem was fixed in 1689a5d756f81d615bcfca8de2631b0ccc8a3917.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145868

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


[PATCH] D142907: LangRef: Add "dynamic" option to "denormal-fp-math"

2023-04-13 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

ping


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

https://reviews.llvm.org/D142907

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


[PATCH] D148189: [NFC][Clang] Fix static analyzer tool remark about missing user-defined assignment operator

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

LGTM! It's not strictly needed (the move constructor causes the implicit 
assignment operator to be deleted: 
https://eel.is/c++draft/class.copy.assign#2.sentence-2), but I think it's more 
clear to be explicit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148189

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


[PATCH] D143347: [lldb][DWARF] Infer no_unique_address attribute

2023-04-13 Thread Michael Buch via Phabricator via cfe-commits
Michael137 added inline comments.



Comment at: lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp:2212
 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
-if (record_decl)
+if (record_decl) {
+  bool is_empty = true;

Generally I'm not sure if attaching a `clang::NoUniqueAddressAttr` to every 
empty field is the right approach. That goes slightly against our attempts to 
construct an AST that's faithful to the source to avoid unpredictable behaviour 
(which isn't always possible but for the most part we try). This approach was 
considered in https://reviews.llvm.org/D101237 but concern was raised about it 
affecting ABI, etc., leading to subtle issues down the line.

Based on the the discussion in https://reviews.llvm.org/D101237 it seemed to me 
like the only two viable solutions are:
1. Add a `DW_AT_byte_size` of `0` to the empty field
2. Add a `DW_AT_no_unique_address`

AFAICT Jan tried to implement (1) but never seemed to be able to fully add 
support for this in the ASTImporter/LLDB. Another issue I see with this is that 
sometimes the byte-size of said field is not `0`, depending on the context in 
which the structure is used.

I'm still leaning towards proposing a `DW_AT_no_unique_address`. Which is 
pretty easy to implement and also reason about from LLDB's perspective. 
@dblaikie @aprantl does that sound reasonable to you?



Comment at: lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp:2219
+if (is_empty_field)
+  field->addAttr(clang::NoUniqueAddressAttr::Create(
+  m_ast.getASTContext(), clang::SourceRange()));

Typically the call to `record_decl->fields()` below would worry me, because if 
the decl `!hasLoadedFieldsFromExternalStorage()` then we'd start another 
`ASTImport` process, which could lead to some unpredictable behaviour if we are 
already in the middle of an import. But since 
`CompleteTagDeclarationDefinition` sets 
`setHasLoadedFieldsFromExternalStorage(true)` I *think* we'd be ok. Might 
warrant a comment.



Comment at: lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp:2231
+if (is_empty)
+  record_decl->markEmpty();
+  }

Why do we need to mark the parents empty here again? Wouldn't they have been 
marked in `ParseStructureLikeDIE`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143347

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


[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147073

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


[PATCH] D146329: [Clang] Fix defaulted equality operator so that it does not attempt to compare unnamed bit-fields

2023-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: 
clang/test/CodeGenCXX/defaulted_equality_ignore_unnamed_bitfields.cpp:23
+
+// If it compares the unnamed bitfields it will first compare the named 
bit-field
+// and then branch based on the result of that comparison.

I think these check lines aren't nearly specific enough, i think it should have 
a handful of CHECK lines confirming what we're doing, not just what we're not.


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

https://reviews.llvm.org/D146329

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


[PATCH] D148034: [clang][driver] Disable GP relaxation with RISC-V ShadowCallStack

2023-04-13 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

In D148034#4262991 , @MaskRay wrote:

> In D148034#4260376 , @asb wrote:
>
>> Will `--[no-]relax-gp` make its way into a minor gcc point release or do we 
>> need to wait for the next major release?
>>
>> In terms of this breaking GNU users - isn't it the case that without this 
>> option, they may get silently broken code when using the shadow call stack? 
>> Breaking loudly and early seems preferable, though of course it would be 
>> best if it's easily fixable by e.g. updating to a newer released binutils.
>
> Yes, `-fsanitize=shadow-call-stack` using gp users will get silently broken 
> code if linked with GNU ld, unless GNU ld is specified, or `-Wl,--no-relax` 
> or `-Wl,--no-relax-gp` is specified.
> This is an instance of the guideline proposed in 
> https://github.com/riscv-non-isa/riscv-elf-psabi-doc/pull/371/commits/bb0df41a4f2626fa039173c2a975039905dce99c
>
>> For such platforms, care must be taken to ensure all code (compiler 
>> generated or otherwise) avoids using gp in a way incompatible with the 
>> platform specific purpose, and that global pointer relaxation is disabled in 
>> the toolchain.
>
> Personally I think most `-fsanitize=shadow-call-stack`  users do not use GNU 
> ld, so this incompatibility is actually minor.
>
> `-fsanitize=shadow-call-stack` is already a quite specific configuration. For 
> GNU ld users, I think placing the burden more on user education is fine 
> (sorry, just that we don't have better options).

I just wanted to make sure I'm following your suggestion here. Have you come 
round to the idea of adding `--no-relax-gp` when shadow call stack is enabled 
and letting it error for users of old GNU tools on the basis that there aren't 
better options?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148034

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


[PATCH] D148181: [Demangle] make llvm::demangle take a StringRef; NFC

2023-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

We're C++17 compilation now, so we should be able to use `std::string_view` 
(and I think we're supposed to?).




Comment at: llvm/lib/Demangle/Demangle.cpp:31
   std::string Result;
-  const char *S = MangledName.c_str();
+  std::string Copy = MangledName.str();
+  const char *S = Copy.data();

`std::string` is implicitly constructible from a `std::string_view`, so I think 
on line 37 we can just do: `MangledName[0]` instead of `S[0]`, and just do 
`return MangledName` below, rather than constructing it every time, despite it 
being just destructed in every other branch.

Though, I guess the 'gotcha' here is that despite everything else not modifying 
the `S` here, that we're no longer able to use strlen for the length.   Perhaps 
this change should be more viral, in that the other demangle functions should 
take a `string_view` instead of a `const char *` as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148181

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


[PATCH] D148223: [SiFive] Support C intrinsics for xsfvcp extension.

2023-04-13 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: luke, frasercrmck, luismarques, apazos, 
sameer.abuasal, s.egerton, Jim, jocewei, PkmX, the_o, brucehoult, 
MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, niosHD, sabuasal, 
simoncook, johnrusso, rbar, asb.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, MaskRay.
Herald added a project: clang.

Depends on D147934  and D147935 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148223

Files:
  clang/include/clang/Basic/riscv_vector.td
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-x-rv64.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-x.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-xv-rv64.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-xv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-xvv-rv64.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-xvv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/xsfvcp-xvw.c

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


[PATCH] D147935: [RISCV] Add SiFive extension support

2023-04-13 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat added a comment.

In D147935#4259687 , @craig.topper 
wrote:

> Is there a different patch with the .td for these intrinsics?

Yes, it's in this patch: D148223 




Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:465
   RVV_REQ_FullMultiply = 1 << 1,
+  RVV_REQ_xsfvcp = 1 << 2,
 

asb wrote:
> Nit: It would better match the surrounding capitalisation to call this 
> RVV_REQ_Xsfvcp
Got it! Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147935

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


[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

we've got one more reference to `getCanonicalPath` in 
`clang-tools-extra/clangd/IncludeCleaner.cpp:320`, i guess the best way is just 
calling `getLastRef` on the FileEntry*




Comment at: clang-tools-extra/clangd/SourceCode.cpp:518
 const SourceManager &SourceMgr) {
   if (!F)
 return std::nullopt;

we don't need this check anymore



Comment at: clang-tools-extra/clangd/SourceCode.h:166
 /// possible.
-std::optional getCanonicalPath(const FileEntry *F,
+std::optional getCanonicalPath(const FileEntryRef &F,
 const SourceManager &SourceMgr);

just `FileEntryRef`, it's a cheap value type that provides an immutable view 
into underlying `FileEntry`



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:208
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef &FE) {
 auto R = CacheFEToURI.try_emplace(FE);

again just `FileEntryRef`



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:395
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(&FE->getFileEntry(),
+ /*WantExternal*/ false))

`FileEntryRef` should be implicitly convertable to `FileEntry*` (so just `*FE` 
should be enough?)



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:399
+if (auto Spelling = getFrameworkHeaderIncludeSpelling(
+&FE->getFileEntry(), HFI->Framework, HS))
   return *Spelling;

same as above



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:402
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(&FE->getFileEntry(),
+PP->getSourceManager(),

same as above


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

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


[clang] 25d6123 - [clang][Interp] Make sure we have a variable scope for initializers

2023-04-13 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-13T15:35:30+02:00
New Revision: 25d6123854d16370463ba884e750f303d09e9001

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

LOG: [clang][Interp] Make sure we have a variable scope for initializers

Otherwise, we run into an assertion when trying to use the current
variable scope while creating temporaries for constructor initializers.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 2c53900111d9b..e20b714120e8d 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -102,6 +102,9 @@ bool ByteCodeStmtGen::visitFunc(const FunctionDecl 
*F) {
   return false;
 
 for (const auto *Init : Ctor->inits()) {
+  // Scope needed for the initializers.
+  BlockScope Scope(this);
+
   const Expr *InitExpr = Init->getInit();
   if (const FieldDecl *Member = Init->getMember()) {
 const Record::Field *F = R->getField(Member);

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 39eb65c13342f..745a30bec33bd 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -250,6 +250,78 @@ struct S {
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+namespace InitializerTemporaries {
+  class Bar {
+  private:
+int a;
+
+  public:
+constexpr Bar() : a(10) {}
+constexpr int getA() const { return a; }
+  };
+
+  class Foo {
+  public:
+int a;
+
+constexpr Foo() : a(Bar().getA()) {}
+  };
+  constexpr Foo F;
+  static_assert(F.a == 10, "");
+
+
+  /// Needs constexpr destructors.
+#if __cplusplus >= 202002L
+  /// Does
+  ///Arr[Pos] = Value;
+  ///++Pos;
+  /// in its destructor.
+  class BitSetter {
+  private:
+int *Arr;
+int &Pos;
+int Value;
+
+  public:
+constexpr BitSetter(int *Arr, int &Pos, int Value) :
+  Arr(Arr), Pos(Pos), Value(Value) {}
+
+constexpr int getValue() const { return 0; }
+constexpr ~BitSetter() {
+  Arr[Pos] = Value;
+  ++Pos;
+}
+  };
+
+  class Test {
+int a, b, c;
+  public:
+constexpr Test(int *Arr, int &Pos) :
+  a(BitSetter(Arr, Pos, 1).getValue()),
+  b(BitSetter(Arr, Pos, 2).getValue()),
+  c(BitSetter(Arr, Pos, 3).getValue())
+{}
+  };
+
+
+  constexpr int T(int Index) {
+int Arr[] = {0, 0, 0};
+int Pos = 0;
+
+{
+  auto T = Test(Arr, Pos);
+  // End of scope, should destroy Test.
+}
+
+return Arr[Index];
+  }
+
+  static_assert(T(0) == 1);
+  static_assert(T(1) == 2);
+  static_assert(T(2) == 3);
+#endif
+}
+
 #if __cplusplus >= 201703L
 namespace BaseInit {
   class _A {public: int a;};



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


[PATCH] D147534: [clang][Interp] Make sure we have a variable scope for initializers

2023-04-13 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG25d6123854d1: [clang][Interp] Make sure we have a variable 
scope for initializers (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147534

Files:
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/test/AST/Interp/records.cpp


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -250,6 +250,78 @@
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+namespace InitializerTemporaries {
+  class Bar {
+  private:
+int a;
+
+  public:
+constexpr Bar() : a(10) {}
+constexpr int getA() const { return a; }
+  };
+
+  class Foo {
+  public:
+int a;
+
+constexpr Foo() : a(Bar().getA()) {}
+  };
+  constexpr Foo F;
+  static_assert(F.a == 10, "");
+
+
+  /// Needs constexpr destructors.
+#if __cplusplus >= 202002L
+  /// Does
+  ///Arr[Pos] = Value;
+  ///++Pos;
+  /// in its destructor.
+  class BitSetter {
+  private:
+int *Arr;
+int &Pos;
+int Value;
+
+  public:
+constexpr BitSetter(int *Arr, int &Pos, int Value) :
+  Arr(Arr), Pos(Pos), Value(Value) {}
+
+constexpr int getValue() const { return 0; }
+constexpr ~BitSetter() {
+  Arr[Pos] = Value;
+  ++Pos;
+}
+  };
+
+  class Test {
+int a, b, c;
+  public:
+constexpr Test(int *Arr, int &Pos) :
+  a(BitSetter(Arr, Pos, 1).getValue()),
+  b(BitSetter(Arr, Pos, 2).getValue()),
+  c(BitSetter(Arr, Pos, 3).getValue())
+{}
+  };
+
+
+  constexpr int T(int Index) {
+int Arr[] = {0, 0, 0};
+int Pos = 0;
+
+{
+  auto T = Test(Arr, Pos);
+  // End of scope, should destroy Test.
+}
+
+return Arr[Index];
+  }
+
+  static_assert(T(0) == 1);
+  static_assert(T(1) == 2);
+  static_assert(T(2) == 3);
+#endif
+}
+
 #if __cplusplus >= 201703L
 namespace BaseInit {
   class _A {public: int a;};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -102,6 +102,9 @@
   return false;
 
 for (const auto *Init : Ctor->inits()) {
+  // Scope needed for the initializers.
+  BlockScope Scope(this);
+
   const Expr *InitExpr = Init->getInit();
   if (const FieldDecl *Member = Init->getMember()) {
 const Record::Field *F = R->getField(Member);


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -250,6 +250,78 @@
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+namespace InitializerTemporaries {
+  class Bar {
+  private:
+int a;
+
+  public:
+constexpr Bar() : a(10) {}
+constexpr int getA() const { return a; }
+  };
+
+  class Foo {
+  public:
+int a;
+
+constexpr Foo() : a(Bar().getA()) {}
+  };
+  constexpr Foo F;
+  static_assert(F.a == 10, "");
+
+
+  /// Needs constexpr destructors.
+#if __cplusplus >= 202002L
+  /// Does
+  ///Arr[Pos] = Value;
+  ///++Pos;
+  /// in its destructor.
+  class BitSetter {
+  private:
+int *Arr;
+int &Pos;
+int Value;
+
+  public:
+constexpr BitSetter(int *Arr, int &Pos, int Value) :
+  Arr(Arr), Pos(Pos), Value(Value) {}
+
+constexpr int getValue() const { return 0; }
+constexpr ~BitSetter() {
+  Arr[Pos] = Value;
+  ++Pos;
+}
+  };
+
+  class Test {
+int a, b, c;
+  public:
+constexpr Test(int *Arr, int &Pos) :
+  a(BitSetter(Arr, Pos, 1).getValue()),
+  b(BitSetter(Arr, Pos, 2).getValue()),
+  c(BitSetter(Arr, Pos, 3).getValue())
+{}
+  };
+
+
+  constexpr int T(int Index) {
+int Arr[] = {0, 0, 0};
+int Pos = 0;
+
+{
+  auto T = Test(Arr, Pos);
+  // End of scope, should destroy Test.
+}
+
+return Arr[Index];
+  }
+
+  static_assert(T(0) == 1);
+  static_assert(T(1) == 2);
+  static_assert(T(2) == 3);
+#endif
+}
+
 #if __cplusplus >= 201703L
 namespace BaseInit {
   class _A {public: int a;};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -102,6 +102,9 @@
   return false;
 
 for (const auto *Init : Ctor->inits()) {
+  // Scope needed for the initializers.
+  BlockScope Scope(this);
+
   const Expr *InitExpr = Init->getInit();
   if (const FieldDecl *Member = Init->getMember()) {
 const Record::Field *F = R->getField(Member);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D148200: [clang-format] Correctly indent comment above PP Directive

2023-04-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148200

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


[PATCH] D147176: [clang-format] NFC ensure Style operator== remains sorted for ease of editing

2023-04-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D147176#4263621 , @owenpan wrote:

> @MyDeveloperDay We keep getting "spammed" by [libc++][format] patches. Can 
> you delete the rule in H987 :
>
>   "field": "differential.revision.title",
>   "condition": "contains",
>   "value": "[Format]"
>
> or change "contains" to something equivalent to "starts with"?

I removed this a few days ago, we should be good, I think that review has 
clang-format on it.. one sec let me remove us


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147176

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


[clang] f508d9b - [clang][Interp] Don't create global variables more than once

2023-04-13 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-13T15:41:43+02:00
New Revision: f508d9b1d4fa48e7586b9587a22be23c976297a7

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

LOG: [clang][Interp] Don't create global variables more than once

just because we're being told to evaluate it twice. This sometimes
happens when a variable is evaluated again during codegen.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6ced8ca4d07f..a8e8b2997dde 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1562,7 +1562,11 @@ bool ByteCodeExprGen::visitVarDecl(const 
VarDecl *VD) {
   std::optional VarT = classify(VD->getType());
 
   if (shouldBeGloballyIndexed(VD)) {
-std::optional GlobalIndex = P.getOrCreateGlobal(VD, Init);
+// We've already seen and initialized this global.
+if (P.getGlobal(VD))
+  return true;
+
+std::optional GlobalIndex = P.createGlobal(VD, Init);
 
 if (!GlobalIndex)
   return this->bail(VD);



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


[PATCH] D147535: [clang][Interp] Don't create global variables more than once

2023-04-13 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf508d9b1d4fa: [clang][Interp] Don't create global 
variables more than once (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147535

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp


Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1562,7 +1562,11 @@
   std::optional VarT = classify(VD->getType());
 
   if (shouldBeGloballyIndexed(VD)) {
-std::optional GlobalIndex = P.getOrCreateGlobal(VD, Init);
+// We've already seen and initialized this global.
+if (P.getGlobal(VD))
+  return true;
+
+std::optional GlobalIndex = P.createGlobal(VD, Init);
 
 if (!GlobalIndex)
   return this->bail(VD);


Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1562,7 +1562,11 @@
   std::optional VarT = classify(VD->getType());
 
   if (shouldBeGloballyIndexed(VD)) {
-std::optional GlobalIndex = P.getOrCreateGlobal(VD, Init);
+// We've already seen and initialized this global.
+if (P.getGlobal(VD))
+  return true;
+
+std::optional GlobalIndex = P.createGlobal(VD, Init);
 
 if (!GlobalIndex)
   return this->bail(VD);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144164: [clang][Interp] Handle PtrMemOps

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144164

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


[PATCH] D143334: [clang][Interp] Fix diagnosing uninitialized ctor record arrays

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143334

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


[PATCH] D144457: [clang][Interp] Handle global composite temporaries

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144457

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


[PATCH] D144943: [clang][Interp] Implement bitcasts (WIP)

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

Ping


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

https://reviews.llvm.org/D144943

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


[PATCH] D147176: [clang-format] NFC ensure Style operator== remains sorted for ease of editing

2023-04-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

we should be good now

F27132578: image.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147176

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


[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 513219.
usaxena95 marked 6 inline comments as done.
usaxena95 added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Tweak.cpp

Index: clang-tools-extra/clangd/refactor/Tweak.cpp
===
--- clang-tools-extra/clangd/refactor/Tweak.cpp
+++ clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -104,8 +104,9 @@
 Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
 tooling::Replacements Replacements) {
   Edit Ed(SM.getBufferData(FID), std::move(Replacements));
-  if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
-return std::make_pair(*FilePath, std::move(Ed));
+  if (const auto FE = SM.getFileEntryRefForID(FID))
+if (auto FilePath = getCanonicalPath(*FE, SM))
+  return std::make_pair(*FilePath, std::move(Ed));
   return error("Failed to get absolute path for edited file: {0}",
SM.getFileEntryRefForID(FID)->getName());
 }
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -46,10 +46,10 @@
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
-  const auto *F = SM.getFileEntryForID(FID);
+  const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
 return false; // Skip invalid files.
-  auto AbsPath = getCanonicalPath(F, SM);
+  auto AbsPath = getCanonicalPath(*F, SM);
   if (!AbsPath)
 return false; // Skip files without absolute path.
   std::lock_guard Lock(FilesMu);
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -205,11 +205,11 @@
 
   // Returns a canonical URI for the file \p FE.
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef FE) {
 auto R = CacheFEToURI.try_emplace(FE);
 if (R.second) {
   auto CanonPath = getCanonicalPath(FE, SM);
-  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE->getName());
+  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
 }
 return *R.first->second;
   }
@@ -218,7 +218,7 @@
   // If the file is in the FileManager, use that to canonicalize the path.
   // We attempt to make the path absolute in any case.
   const std::string &toURI(llvm::StringRef Path) {
-if (auto File = SM.getFileManager().getFile(Path))
+if (auto File = SM.getFileManager().getFileRef(Path))
   return toURI(*File);
 return toURIInternal(Path);
   }
@@ -373,7 +373,7 @@
   }
 
   llvm::StringRef getIncludeHeaderUncached(FileID FID) {
-const FileEntry *FE = SM.getFileEntryForID(FID);
+const auto FE = SM.getFileEntryRefForID(FID);
 if (!FE || FE->getName().empty())
   return "";
 llvm::StringRef Filename = FE->getName();
@@ -392,13 +392,13 @@
 // Framework headers are spelled as , not
 // "path/FrameworkName.framework/Headers/Foo.h".
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(*FE, /*WantExternal*/ false))
   if (!HFI->Framework.empty())
 if (auto Spelling =
-getFrameworkHeaderIncludeSpelling(FE, HFI->Framework, HS))
+getFrameworkHeaderIncludeSpelling(*FE, HFI->Framework, HS))
   return *Spelling;
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(*FE, PP->getSourceManager(),
 PP->getHeaderSearchInfo())) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
@@ -409,7 +409,7 @@
   return "";
 }
 // Standard case: just insert the file itself.
-return toURI(FE);
+return toURI(*FE);
   }
 };
 
@@ -417,12 +417,12 @@
 std::optional
 SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
   const auto &SM = ASTCtx->getSourceManager();
-  auto *FE = SM.getFileEntryForID(S

[clang] 4a6a4f8 - [clang][Interp] Add a failing test case

2023-04-13 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-13T15:55:57+02:00
New Revision: 4a6a4f84a7af7212d36aea9c34a1a8b9bb05d733

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

LOG: [clang][Interp] Add a failing test case

Added: 


Modified: 
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 745a30bec33b..a874bf378150 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -451,3 +451,40 @@ namespace ConditionalInit {
   static_assert(getS(true).a == 12, "");
   static_assert(getS(false).a == 13, "");
 };
+/// FIXME: The following tests are broken.
+///   They are using CXXDefaultInitExprs which contain a CXXThisExpr. The This 
pointer
+///   in those refers to the declaration we are currently initializing, *not* 
the
+///   This pointer of the current stack frame. This is something we haven't
+///   implemented in the new interpreter yet.
+namespace DeclRefs {
+  struct A{ int m; const int &f = m; }; // expected-note {{implicit use of 
'this'}}
+
+  constexpr A a{10}; // expected-error {{must be initialized by a constant 
expression}}
+  static_assert(a.m == 10, "");
+  static_assert(a.f == 10, ""); // expected-error {{not an integral constant 
expression}} \
+// expected-note {{read of object outside its 
lifetime}}
+
+  class Foo {
+  public:
+int z = 1337;
+constexpr int a() const {
+  A b{this->z};
+
+  return b.f;
+}
+  };
+  constexpr Foo f;
+  static_assert(f.a() == 1337, "");
+
+
+  struct B {
+A a = A{100};
+  };
+  constexpr B b;
+  /// FIXME: The following two lines don't work because we don't get the
+  ///   pointers on the LHS correct. They make us run into an assertion
+  ///   in CheckEvaluationResult. However, this may just be caused by the
+  ///   problems in the previous examples.
+  //static_assert(b.a.m == 100, "");
+  //static_assert(b.a.f == 100, "");
+}



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


[PATCH] D142630: [clang][Interp] Implement virtual function calls

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142630

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


[PATCH] D125171: [clang-format] Add a new clang-format option AlwaysBreakBeforeFunctionParameters

2023-04-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/Format.cpp:876
Style.AlwaysBreakBeforeMultilineStrings);
+IO.mapOptional("AlwaysBreakBeforeFunctionParameters",
+   Style.AlwaysBreakBeforeFunctionParameters);

This should be Alphabetic should this be before the MultlineStrings option?



Comment at: clang/lib/Format/Format.cpp:1336
   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
+  LLVMStyle.AlwaysBreakBeforeFunctionParameters = false;
   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;

ok, we have this think that the lifetime of an option goes from bool -> enum -> 
struct, sometimes we pick up early that true/false aren't good enough

so here is the think... `AlwaysBreakBeforeFunctionParameters` should this be  
an enum and `BreakBeforeFunctionParameters` but with values

`Leave, Never, Always`

i.e. does `AlwaysBreakBeforeFunctionParameters` = false mean never break? or 
sometimes break.

We don't really want "false" to mean do something..we want it to mean don't do 
anything i.e. Leave







Comment at: clang/unittests/Format/FormatTest.cpp:25437
+  // verify that there is no break by default
+  verifyFormat("int function1(int param1, int param2, int param3);\n"
+   "int function2();\n",

I would say all these function could go to the single format of `verifyFormat`



Comment at: clang/unittests/Format/FormatTest.cpp:25469
+  verifyFormat("void function1() {}\n", // the formatted part
+   "void function1() {}\n", // the original
+   Style);

you can just use the single form of verifyFormat() it will call messUp to 
remove the whitespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125171

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


[PATCH] D145868: [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-13 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:8627
+  )";
+  Decl *ToTU = getToTuDecl("", Lang_CXX11);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);

balazske wrote:
> bjope wrote:
> > With Werror we get:
> > 
> > ```
> > ../../clang/unittests/AST/ASTImporterTest.cpp:8627:9: error: unused 
> > variable 'ToTU' [-Werror,-Wunused-variable]
> >   Decl *ToTU = getToTuDecl("", Lang_CXX11);
> > ^
> > 
> > ```
> Problem was fixed in 1689a5d756f81d615bcfca8de2631b0ccc8a3917.
Great. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145868

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


[PATCH] D147935: [RISCV] Add SiFive extension support

2023-04-13 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat updated this revision to Diff 513223.
4vtomat added a comment.

Resolved Alex's comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147935

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/utils/TableGen/RISCVVEmitter.cpp


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -633,6 +633,7 @@
   RVVRequire RequireExt = StringSwitch(RequiredFeature)
   .Case("RV64", RVV_REQ_RV64)
   .Case("FullMultiply", RVV_REQ_FullMultiply)
+  .Case("Xsfvcp", RVV_REQ_Xsfvcp)
   .Default(RVV_REQ_None);
   assert(RequireExt != RVV_REQ_None && "Unrecognized required feature?");
   SR.RequiredExtensions |= RequireExt;
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -462,8 +462,9 @@
   RVV_REQ_None = 0,
   RVV_REQ_RV64 = 1 << 0,
   RVV_REQ_FullMultiply = 1 << 1,
+  RVV_REQ_Xsfvcp = 1 << 2,
 
-  LLVM_MARK_AS_BITMASK_ENUM(RVV_REQ_FullMultiply)
+  LLVM_MARK_AS_BITMASK_ENUM(RVV_REQ_Xsfvcp)
 };
 
 // Raw RVV intrinsic info, used to expand later.


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -633,6 +633,7 @@
   RVVRequire RequireExt = StringSwitch(RequiredFeature)
   .Case("RV64", RVV_REQ_RV64)
   .Case("FullMultiply", RVV_REQ_FullMultiply)
+  .Case("Xsfvcp", RVV_REQ_Xsfvcp)
   .Default(RVV_REQ_None);
   assert(RequireExt != RVV_REQ_None && "Unrecognized required feature?");
   SR.RequiredExtensions |= RequireExt;
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -462,8 +462,9 @@
   RVV_REQ_None = 0,
   RVV_REQ_RV64 = 1 << 0,
   RVV_REQ_FullMultiply = 1 << 1,
+  RVV_REQ_Xsfvcp = 1 << 2,
 
-  LLVM_MARK_AS_BITMASK_ENUM(RVV_REQ_FullMultiply)
+  LLVM_MARK_AS_BITMASK_ENUM(RVV_REQ_Xsfvcp)
 };
 
 // Raw RVV intrinsic info, used to expand later.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

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


[clang-tools-extra] ed365f4 - [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via cfe-commits

Author: Utkarsh Saxena
Date: 2023-04-13T16:49:30+02:00
New Revision: ed365f464a0a29da08d0a1011603c4cd337c9428

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

LOG: [clangd] Use FileEntryRef for canonicalizing filepaths.

Using FileEntry for retrieving filenames give the name used for the last 
access. FileEntryRef gives the first access name.

Last access name is suspected to change with unrelated changes in clang or the 
underlying filesystem. First access name gives more stability to the name and 
makes it easier to track.

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

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.cpp
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/SourceCode.cpp
clang-tools-extra/clangd/SourceCode.h
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/indexer/IndexerMain.cpp
clang-tools-extra/clangd/refactor/Tweak.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index 12a865fcf9e50..963bf02e21848 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -715,9 +715,9 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
 D.InsideMainFile = isInsideMainFile(PatchLoc, SM);
 D.Range = diagnosticRange(Info, *LangOpts);
 auto FID = SM.getFileID(Info.getLocation());
-if (auto *FE = SM.getFileEntryForID(FID)) {
+if (const auto FE = SM.getFileEntryRefForID(FID)) {
   D.File = FE->getName().str();
-  D.AbsFile = getCanonicalPath(FE, SM);
+  D.AbsFile = getCanonicalPath(*FE, SM);
 }
 D.ID = Info.getID();
 return D;

diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index b0e4d8dee5568..168471a603ea4 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -317,8 +317,8 @@ convertIncludes(const SourceManager &SM,
 std::string spellHeader(ParsedAST &AST, const FileEntry *MainFile,
 include_cleaner::Header Provider) {
   if (Provider.kind() == include_cleaner::Header::Physical) {
-if (auto CanonicalPath =
-getCanonicalPath(Provider.physical(), AST.getSourceManager())) {
+if (auto CanonicalPath = 
getCanonicalPath(Provider.physical()->getLastRef(),
+  AST.getSourceManager())) {
   std::string SpelledHeader =
   llvm::cantFail(URI::includeSpelling(URI::create(*CanonicalPath)));
   if (!SpelledHeader.empty())

diff  --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 044562ec1b59a..831adc3d5fd8d 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -12,6 +12,7 @@
 #include "Protocol.h"
 #include "support/Context.h"
 #include "support/Logger.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -512,12 +513,9 @@ std::vector replacementsToEdits(llvm::StringRef 
Code,
   return Edits;
 }
 
-std::optional getCanonicalPath(const FileEntry *F,
+std::optional getCanonicalPath(const FileEntryRef F,
 const SourceManager &SourceMgr) {
-  if (!F)
-return std::nullopt;
-
-  llvm::SmallString<128> FilePath = F->getName();
+  llvm::SmallString<128> FilePath = F.getName();
   if (!llvm::sys::path::is_absolute(FilePath)) {
 if (auto EC =
 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(

diff  --git a/clang-tools-extra/clangd/SourceCode.h 
b/clang-tools-extra/clangd/SourceCode.h
index 8643fab09656f..8b7c028eb2478 100644
--- a/clang-tools-extra/clangd/SourceCode.h
+++ b/clang-tools-extra/clangd/SourceCode.h
@@ -163,7 +163,7 @@ TextEdit toTextEdit(const FixItHint &FixIt, const 
SourceManager &M,
 /// This function should be used when paths needs to be used outside the
 /// component that generate it, so that paths are normalized as much as
 /// possible.
-std::optional getCanonicalPath(const FileEntry *F,
+std::optional getCanonicalPath(const FileEntryRef F,
 const SourceManager &SourceMgr);
 
 /// Choose the clang-format style we should apply to a certain file.

diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index d4442c11a8ed0..9a1bd7dbd2564 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -208,10 +208,10 @@ getDeclAtPosition(Pars

[PATCH] D148213: [clangd] Use FileEntryRef for canonicalizing filepaths.

2023-04-13 Thread Utkarsh Saxena via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGed365f464a0a: [clangd] Use FileEntryRef for canonicalizing 
filepaths. (authored by usaxena95).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148213

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Tweak.cpp

Index: clang-tools-extra/clangd/refactor/Tweak.cpp
===
--- clang-tools-extra/clangd/refactor/Tweak.cpp
+++ clang-tools-extra/clangd/refactor/Tweak.cpp
@@ -104,8 +104,9 @@
 Tweak::Effect::fileEdit(const SourceManager &SM, FileID FID,
 tooling::Replacements Replacements) {
   Edit Ed(SM.getBufferData(FID), std::move(Replacements));
-  if (auto FilePath = getCanonicalPath(SM.getFileEntryForID(FID), SM))
-return std::make_pair(*FilePath, std::move(Ed));
+  if (const auto FE = SM.getFileEntryRefForID(FID))
+if (auto FilePath = getCanonicalPath(*FE, SM))
+  return std::make_pair(*FilePath, std::move(Ed));
   return error("Failed to get absolute path for edited file: {0}",
SM.getFileEntryRefForID(FID)->getName());
 }
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -46,10 +46,10 @@
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
-  const auto *F = SM.getFileEntryForID(FID);
+  const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
 return false; // Skip invalid files.
-  auto AbsPath = getCanonicalPath(F, SM);
+  auto AbsPath = getCanonicalPath(*F, SM);
   if (!AbsPath)
 return false; // Skip files without absolute path.
   std::lock_guard Lock(FilesMu);
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -205,11 +205,11 @@
 
   // Returns a canonical URI for the file \p FE.
   // We attempt to make the path absolute first.
-  const std::string &toURI(const FileEntry *FE) {
+  const std::string &toURI(const FileEntryRef FE) {
 auto R = CacheFEToURI.try_emplace(FE);
 if (R.second) {
   auto CanonPath = getCanonicalPath(FE, SM);
-  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE->getName());
+  R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
 }
 return *R.first->second;
   }
@@ -218,7 +218,7 @@
   // If the file is in the FileManager, use that to canonicalize the path.
   // We attempt to make the path absolute in any case.
   const std::string &toURI(llvm::StringRef Path) {
-if (auto File = SM.getFileManager().getFile(Path))
+if (auto File = SM.getFileManager().getFileRef(Path))
   return toURI(*File);
 return toURIInternal(Path);
   }
@@ -373,7 +373,7 @@
   }
 
   llvm::StringRef getIncludeHeaderUncached(FileID FID) {
-const FileEntry *FE = SM.getFileEntryForID(FID);
+const auto FE = SM.getFileEntryRefForID(FID);
 if (!FE || FE->getName().empty())
   return "";
 llvm::StringRef Filename = FE->getName();
@@ -392,13 +392,13 @@
 // Framework headers are spelled as , not
 // "path/FrameworkName.framework/Headers/Foo.h".
 auto &HS = PP->getHeaderSearchInfo();
-if (const auto *HFI = HS.getExistingFileInfo(FE, /*WantExternal*/ false))
+if (const auto *HFI = HS.getExistingFileInfo(*FE, /*WantExternal*/ false))
   if (!HFI->Framework.empty())
 if (auto Spelling =
-getFrameworkHeaderIncludeSpelling(FE, HFI->Framework, HS))
+getFrameworkHeaderIncludeSpelling(*FE, HFI->Framework, HS))
   return *Spelling;
 
-if (!tooling::isSelfContainedHeader(FE, PP->getSourceManager(),
+if (!tooling::isSelfContainedHeader(*FE, PP->getSourceManager(),
 PP->getHeaderSearchInfo())) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
@@ -409,7 +409,7 @@
   return "";
 }
 // Standard case: just insert the file itself.
-return toURI(FE);
+return toURI(*FE);
   }
 };
 
@@ -417,12 +417,12 @@
 std::optional
 SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
   const auto &SM = ASTCtx->getSourc

[clang] 0529da5 - [Coverage] Handle invalid end location of an expression/statement.

2023-04-13 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2023-04-13T10:53:02-04:00
New Revision: 0529da5b948cf168f65bec65b0559139f4f5a426

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

LOG: [Coverage] Handle invalid end location of an expression/statement.

Fix a crash when an expression/statement can have valid start location but 
invalid end location in some situations. For example: 
https://github.com/llvm/llvm-project/blob/llvmorg-16.0.1/clang/lib/Sema/SemaExprCXX.cpp#L1536

This confuses `CounterCoverageMappingBuilder` when popping a region from region
stack as if the end location is a macro or include location.

Reviewed By: hans, aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/CodeGen/CoverageMappingGen.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9abfaf5b2322a..b838858c09179 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -297,6 +297,10 @@ Bug Fixes in This Version
   not a type concept.
 - Fix crash when a doc comment contains a line splicing.
   (`#62054 `_)
+- Work around with a clang coverage crash which happens when visiting 
+  expressions/statements with invalid source locations in non-assert builds. 
+  Assert builds may still see assertions triggered from this.
+  (`#62105 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 426ac39b8767e..bac01c7ff67f2 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -602,6 +602,19 @@ struct CounterCoverageMappingBuilder
   MostRecentLocation = *StartLoc;
 }
 
+// If either of these locations is invalid, something elsewhere in the
+// compiler has broken.
+assert((!StartLoc || StartLoc->isValid()) && "Start location is not 
valid");
+assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
+
+// However, we can still recover without crashing.
+// If either location is invalid, set it to std::nullopt to avoid
+// letting users of RegionStack think that region has a valid start/end
+// location.
+if (StartLoc && StartLoc->isInvalid())
+  StartLoc = std::nullopt;
+if (EndLoc && EndLoc->isInvalid())
+  EndLoc = std::nullopt;
 RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
@@ -624,7 +637,8 @@ struct CounterCoverageMappingBuilder
 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
 while (RegionStack.size() > ParentIndex) {
   SourceMappingRegion &Region = RegionStack.back();
-  if (Region.hasStartLoc()) {
+  if (Region.hasStartLoc() &&
+  (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
 SourceLocation StartLoc = Region.getBeginLoc();
 SourceLocation EndLoc = Region.hasEndLoc()
 ? Region.getEndLoc()
@@ -691,7 +705,7 @@ struct CounterCoverageMappingBuilder
 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
 assert(SpellingRegion(SM, Region).isInSourceOrder());
 SourceRegions.push_back(Region);
-}
+  }
   RegionStack.pop_back();
 }
   }



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


[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-04-13 Thread Zequan Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0529da5b948c: [Coverage] Handle invalid end location of an 
expression/statement. (authored by zequanwu).

Changed prior to commit:
  https://reviews.llvm.org/D147073?vs=512971&id=513236#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147073

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/CodeGen/CoverageMappingGen.cpp


Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -602,6 +602,19 @@
   MostRecentLocation = *StartLoc;
 }
 
+// If either of these locations is invalid, something elsewhere in the
+// compiler has broken.
+assert((!StartLoc || StartLoc->isValid()) && "Start location is not 
valid");
+assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
+
+// However, we can still recover without crashing.
+// If either location is invalid, set it to std::nullopt to avoid
+// letting users of RegionStack think that region has a valid start/end
+// location.
+if (StartLoc && StartLoc->isInvalid())
+  StartLoc = std::nullopt;
+if (EndLoc && EndLoc->isInvalid())
+  EndLoc = std::nullopt;
 RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
@@ -624,7 +637,8 @@
 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
 while (RegionStack.size() > ParentIndex) {
   SourceMappingRegion &Region = RegionStack.back();
-  if (Region.hasStartLoc()) {
+  if (Region.hasStartLoc() &&
+  (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
 SourceLocation StartLoc = Region.getBeginLoc();
 SourceLocation EndLoc = Region.hasEndLoc()
 ? Region.getEndLoc()
@@ -691,7 +705,7 @@
 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
 assert(SpellingRegion(SM, Region).isInSourceOrder());
 SourceRegions.push_back(Region);
-}
+  }
   RegionStack.pop_back();
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -297,6 +297,10 @@
   not a type concept.
 - Fix crash when a doc comment contains a line splicing.
   (`#62054 `_)
+- Work around with a clang coverage crash which happens when visiting 
+  expressions/statements with invalid source locations in non-assert builds. 
+  Assert builds may still see assertions triggered from this.
+  (`#62105 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -602,6 +602,19 @@
   MostRecentLocation = *StartLoc;
 }
 
+// If either of these locations is invalid, something elsewhere in the
+// compiler has broken.
+assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid");
+assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
+
+// However, we can still recover without crashing.
+// If either location is invalid, set it to std::nullopt to avoid
+// letting users of RegionStack think that region has a valid start/end
+// location.
+if (StartLoc && StartLoc->isInvalid())
+  StartLoc = std::nullopt;
+if (EndLoc && EndLoc->isInvalid())
+  EndLoc = std::nullopt;
 RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
@@ -624,7 +637,8 @@
 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
 while (RegionStack.size() > ParentIndex) {
   SourceMappingRegion &Region = RegionStack.back();
-  if (Region.hasStartLoc()) {
+  if (Region.hasStartLoc() &&
+  (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
 SourceLocation StartLoc = Region.getBeginLoc();
 SourceLocation EndLoc = Region.hasEndLoc()
 ? Region.getEndLoc()
@@ -691,7 +705,7 @@
 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
 assert(SpellingRegion(SM, Region).isInSourceOrder());
 SourceRegions.push_back(Region);
-}
+  }
   RegionStack.pop_back();
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -297,6 +297,10 @@
   not a type concept.
 - Fix crash when a doc comme

[PATCH] D148206: [clang] Do not crash after suggesting typo correction to constexpr if condition

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



Comment at: clang/include/clang/Sema/Sema.h:12855
+!Condition.get()->isValueDependent() &&
+Condition.get()->isIntegerConstantExpr(S.Context)),
   KnownValue(HasKnownValue &&

Oof, this adds quite a bit of expense to this constructor -- 
`isIntegerConstantExpr()` is implemented by evaluating the constant expression 
and throwing away the computed result... which we then recompute when setting 
`KnownValue` one line later. It'd be better to only do this computation once 
and use the computed value to initialize both members.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148206

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


[PATCH] D146178: [Clang][Sema] Fix comparison of constraint expressions

2023-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:773
+  // ConstrExpr for the inner template will properly adjust the depths.
+  if (isa(ND) && isa(OtherND))
+ForConstraintInstantiation = true;

alexander-shaposhnikov wrote:
> erichkeane wrote:
> > alexander-shaposhnikov wrote:
> > > erichkeane wrote:
> > > > Hmm... this seems really strange to have to do. 
> > > > `ForConstraintInstantiation` shouldn't be used here, the point of that 
> > > > is to make sure we 'keep looking upward' once we hit a spot we normally 
> > > > stop with.  What exactly is the issue that you end up running into 
> > > > here?  Perhaps I can spend some time debugging what we should really be 
> > > > doign.
> > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > workaround (but would be happy to).
> > > This kicks in for the case 
> > > 
> > > ```
> > > template 
> > > concept Constraint = true;
> > > 
> > > 
> > > template
> > > struct Iterator {
> > > template 
> > > friend class Iterator;
> > > void operator*();
> > > };
> > > 
> > > Iterator I2;
> > > ```
> > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > workaround (but would be happy to).
> > > This kicks in for the case 
> > > 
> > > ```
> > > template 
> > > concept Constraint = true;
> > > 
> > > 
> > > template
> > > struct Iterator {
> > > template 
> > > friend class Iterator;
> > > void operator*();
> > > };
> > > 
> > > Iterator I2;
> > > ```
> > 
> > Alright, well, I should have time later in the week to poke at this, 
> > perhaps I can come up with something better?  I DO remember self-friend is 
> > a little wacky, and I spent a bunch of time on it last time.
> Ok, sounds good + maybe Richard will give it another look.
So IMO, `ForConstraintInstantiation` should be 'true' always, and that makes 
those examples pass.  However, I'm now seeing that it causes a failure in the 
concepts-out-of-line-def.cpp file.  

I took the example of `foo3`:

```
   template concept C = true;
   template 
   struct S {
 template  requires C
 void foo3(F3 f); // #1
   };
   template 
   template  requires C
   void S::foo3(F6 f) {} // #3
```

Which, seems to require `ForConstraintInstantiation` to be false to pass.  
However, I don't think this is correct.  This is only working because when 
evaluating the in-line one (#1 above!) its skipping the application of `T1`, 
which is wrong.  

However, I think the problem here is that the `out of line` version (#3) is not 
applying the T4 like it should be. SO, I think the `HandleFunctionTemplateDecl` 
I provided you earlier needs modification.

FIRST, though not related to this, I think we might need to add 
`FunctionTemplateDecl::getInjectedTemplateArgs` to the `Result`, but only 
because that 'sounds right' to me?  IDK what other problem that would cause, 
but it is worth evaluating/saving for later.  It might just not matter, since 
we're treating them as equal at the moment, I don't think injecting them would 
cause anything.

Secondly: I see that the we can get to the `T4` via the 
`FTD->getTemplatedDecl()->getQualifier()->getAsType()->getAs()->template_arguments()`.
  

HOWEVER, the problem that comes with picking THOSE up, is that it ALSO applies 
with a `FunctionTemplateDecl` inside of an out-of-line 
`ClassTemplateSpecializationDecl` (which doesn't NEED the specialization's 
template args).  

SO I think the fix here is something in `HandleFunctionTemplateDecl` to make 
sure we pick up the right list of template arguments.  I haven't figured out 
the magic incantation to make it work unfortunately, perhaps @rsmith has some 
hints?  Else I'll keep poking at it.

BUT, my debugging has shown me that I'm quite convinced the setting 
`ForConstraintInstantiation ` to false is incorrect.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146178

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-13 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

IR that passes the verifier generally shouldn't crash llvm, so an alternative 
would be to make a verifier check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D147256: [DebugInfo] Fix file path separator when targeting windows.

2023-04-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 513252.
zequanwu added a comment.
Herald added a subscriber: MaskRay.

- Move remove_dots to clang driver.
- Revert changes to llc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147256

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/debug-info-slash.c
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -791,7 +791,6 @@
 // Don't emit the filename if we're writing to stdout or to /dev/null.
 PathRef = {};
   } else {
-llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true);
 PathRef = PathStore;
   }
 
Index: clang/test/CodeGen/debug-info-slash.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-slash.c
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-pc-win32  -ffile-reproducible -emit-llvm -S -g 
%s -o - | FileCheck --check-prefix=WIN %s
+// RUN: %clang -target x86_64-linux-gnu  -ffile-reproducible -emit-llvm -S -g 
%s -o - | FileCheck --check-prefix=LINUX %s
+int main() { return 0; }
+
+// WIN:   !DIFile(filename: "{{.*}}\\debug-info-slash.c"
+// LINUX: !DIFile(filename: "{{.*}}/debug-info-slash.c"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -579,6 +579,12 @@
 // Make the path absolute in the debug infos like MSVC does.
 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
   }
+  llvm::sys::path::Style Style =
+  llvm::sys::path::is_absolute(ObjFileNameForDebug)
+  ? llvm::sys::path::Style::native
+  : llvm::sys::path::Style::windows_backslash;
+  llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
+   Style);
   CmdArgs.push_back(
   Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
 }
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -528,6 +528,7 @@
   // Get absolute path name.
   SourceManager &SM = CGM.getContext().getSourceManager();
   auto &CGO = CGM.getCodeGenOpts();
+  const LangOptions &LO = CGM.getLangOpts();
   std::string MainFileName = CGO.MainFileName;
   if (MainFileName.empty())
 MainFileName = "";
@@ -542,9 +543,15 @@
 MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);
-  llvm::sys::path::append(MainFileDirSS, MainFileName);
-  MainFileName =
-  std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
+  llvm::sys::path::Style Style =
+  LO.UseTargetPathSeparator
+  ? (CGM.getTarget().getTriple().isOSWindows()
+ ? llvm::sys::path::Style::windows_backslash
+ : llvm::sys::path::Style::posix)
+  : llvm::sys::path::Style::native;
+  llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
+  MainFileName = std::string(
+  llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
 }
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
@@ -560,7 +567,6 @@
   }
 
   llvm::dwarf::SourceLanguage LangTag;
-  const LangOptions &LO = CGM.getLangOpts();
   if (LO.CPlusPlus) {
 if (LO.ObjC)
   LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -479,9 +479,9 @@
   /// The seed used by the randomize structure layout feature.
   std::string RandstructSeed;
 
-  /// Indicates whether the __FILE__ macro should use the target's
-  /// platform-specific file separator or whether it should use the build
-  /// environment's platform-specific file separator.
+  /// Indicates whether to use target's platform-specific file separator when
+  /// __FILE__ macro is used and when concatenating filename with directory or
+  /// to use build environment environment's platform-specific file separator.
   ///
   /// The plaform-specific path separator is the backslash(\) for Windows and
   /// forward slash (/) elsewhere.


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
==

[PATCH] D148021: [Headers][doc] Add FMA intrinsic descriptions

2023-04-13 Thread Paul Robinson via Phabricator via cfe-commits
probinson added inline comments.



Comment at: clang/lib/Headers/fmaintrin.h:22
+/// Computes a multiply-add of 128-bit vectors of [4 x float].
+///For each element, computes  (__A * __B) + __C .
+///

pengfei wrote:
> We are using a special format to describute the function in a pseudo code to 
> share it with the intrinsic guide, e.g.,
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/avx512fintrin.h#L9604-L9610
> https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_i32logather_pd&ig_expand=4077
> 
> There's no strong requirement to follow it, but it would be better to adopt a 
> uniform format.
Is a FOR loop with computed bit offsets really clearer than "For each element" 
? Is it valuable to repeat information that can be found in the instruction 
reference? 
I can accept answers of "yes" and "yes" because I am not someone who ever deals 
with vector data, but I would be a little surprised by those answers.




Comment at: clang/lib/Headers/fmaintrin.h:26
+///
+/// This intrinsic corresponds to the  VFMADD213PS  instruction.
+///

pengfei wrote:
> It would be odd to user given this is just 1/3 instructions the intrinsic may 
> generate, but I don't have a good idea here.
I listed the 213 version because that's the one that multiplies the first two 
operands, and the intrinsic multiplies the first two operands. So it's the 
instruction that most closely corresponds to the intrinsic.
We don't guarantee that the "corresponding" instruction is what is actually 
generated, in general. I know this point has come up before regarding intrinsic 
descriptions. My thinking is that the "corresponding instruction" gives the 
reader a place to look in the instruction reference manual, so listing only one 
is again okay.


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

https://reviews.llvm.org/D148021

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


[PATCH] D146178: [Clang][Sema] Fix comparison of constraint expressions

2023-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:773
+  // ConstrExpr for the inner template will properly adjust the depths.
+  if (isa(ND) && isa(OtherND))
+ForConstraintInstantiation = true;

erichkeane wrote:
> alexander-shaposhnikov wrote:
> > erichkeane wrote:
> > > alexander-shaposhnikov wrote:
> > > > erichkeane wrote:
> > > > > Hmm... this seems really strange to have to do. 
> > > > > `ForConstraintInstantiation` shouldn't be used here, the point of 
> > > > > that is to make sure we 'keep looking upward' once we hit a spot we 
> > > > > normally stop with.  What exactly is the issue that you end up 
> > > > > running into here?  Perhaps I can spend some time debugging what we 
> > > > > should really be doign.
> > > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > > workaround (but would be happy to).
> > > > This kicks in for the case 
> > > > 
> > > > ```
> > > > template 
> > > > concept Constraint = true;
> > > > 
> > > > 
> > > > template
> > > > struct Iterator {
> > > > template 
> > > > friend class Iterator;
> > > > void operator*();
> > > > };
> > > > 
> > > > Iterator I2;
> > > > ```
> > > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > > workaround (but would be happy to).
> > > > This kicks in for the case 
> > > > 
> > > > ```
> > > > template 
> > > > concept Constraint = true;
> > > > 
> > > > 
> > > > template
> > > > struct Iterator {
> > > > template 
> > > > friend class Iterator;
> > > > void operator*();
> > > > };
> > > > 
> > > > Iterator I2;
> > > > ```
> > > 
> > > Alright, well, I should have time later in the week to poke at this, 
> > > perhaps I can come up with something better?  I DO remember self-friend 
> > > is a little wacky, and I spent a bunch of time on it last time.
> > Ok, sounds good + maybe Richard will give it another look.
> So IMO, `ForConstraintInstantiation` should be 'true' always, and that makes 
> those examples pass.  However, I'm now seeing that it causes a failure in the 
> concepts-out-of-line-def.cpp file.  
> 
> I took the example of `foo3`:
> 
> ```
>template concept C = true;
>template 
>struct S {
>  template  requires C
>  void foo3(F3 f); // #1
>};
>template 
>template  requires C
>void S::foo3(F6 f) {} // #3
> ```
> 
> Which, seems to require `ForConstraintInstantiation` to be false to pass.  
> However, I don't think this is correct.  This is only working because when 
> evaluating the in-line one (#1 above!) its skipping the application of `T1`, 
> which is wrong.  
> 
> However, I think the problem here is that the `out of line` version (#3) is 
> not applying the T4 like it should be. SO, I think the 
> `HandleFunctionTemplateDecl` I provided you earlier needs modification.
> 
> FIRST, though not related to this, I think we might need to add 
> `FunctionTemplateDecl::getInjectedTemplateArgs` to the `Result`, but only 
> because that 'sounds right' to me?  IDK what other problem that would cause, 
> but it is worth evaluating/saving for later.  It might just not matter, since 
> we're treating them as equal at the moment, I don't think injecting them 
> would cause anything.
> 
> Secondly: I see that the we can get to the `T4` via the 
> `FTD->getTemplatedDecl()->getQualifier()->getAsType()->getAs()->template_arguments()`.
>   
> 
> HOWEVER, the problem that comes with picking THOSE up, is that it ALSO 
> applies with a `FunctionTemplateDecl` inside of an out-of-line 
> `ClassTemplateSpecializationDecl` (which doesn't NEED the specialization's 
> template args).  
> 
> SO I think the fix here is something in `HandleFunctionTemplateDecl` to make 
> sure we pick up the right list of template arguments.  I haven't figured out 
> the magic incantation to make it work unfortunately, perhaps @rsmith has some 
> hints?  Else I'll keep poking at it.
> 
> BUT, my debugging has shown me that I'm quite convinced the setting 
> `ForConstraintInstantiation ` to false is incorrect.
I also notice that the work in `HandleRecordDecl` inside of the 
`ForConstraintInstantiation` is a little odd, I don't recall why I put that in 
place, but it DOES result in 5 failed tests if I remove it.  Perhaps we just 
need to be more careful when we substitute in these arguments?  It seems to me 
that putting those arguments in place is perhaps not the right thing to do, 
since they don't have any meaningful values yet?  Perhaps something else for us 
to poke at.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146178

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


[PATCH] D144331: [libc++][format] Implements formatter thread::id.

2023-04-13 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added subscribers: cor3ntin, tahonermann.
tahonermann added a comment.

Adding Corentin for awareness.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144331

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


[PATCH] D146178: [Clang][Sema] Fix comparison of constraint expressions

2023-04-13 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:773
+  // ConstrExpr for the inner template will properly adjust the depths.
+  if (isa(ND) && isa(OtherND))
+ForConstraintInstantiation = true;

erichkeane wrote:
> alexander-shaposhnikov wrote:
> > erichkeane wrote:
> > > alexander-shaposhnikov wrote:
> > > > erichkeane wrote:
> > > > > Hmm... this seems really strange to have to do. 
> > > > > `ForConstraintInstantiation` shouldn't be used here, the point of 
> > > > > that is to make sure we 'keep looking upward' once we hit a spot we 
> > > > > normally stop with.  What exactly is the issue that you end up 
> > > > > running into here?  Perhaps I can spend some time debugging what we 
> > > > > should really be doign.
> > > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > > workaround (but would be happy to).
> > > > This kicks in for the case 
> > > > 
> > > > ```
> > > > template 
> > > > concept Constraint = true;
> > > > 
> > > > 
> > > > template
> > > > struct Iterator {
> > > > template 
> > > > friend class Iterator;
> > > > void operator*();
> > > > };
> > > > 
> > > > Iterator I2;
> > > > ```
> > > > yeah, I agree. I haven't found a proper solution or at least a better 
> > > > workaround (but would be happy to).
> > > > This kicks in for the case 
> > > > 
> > > > ```
> > > > template 
> > > > concept Constraint = true;
> > > > 
> > > > 
> > > > template
> > > > struct Iterator {
> > > > template 
> > > > friend class Iterator;
> > > > void operator*();
> > > > };
> > > > 
> > > > Iterator I2;
> > > > ```
> > > 
> > > Alright, well, I should have time later in the week to poke at this, 
> > > perhaps I can come up with something better?  I DO remember self-friend 
> > > is a little wacky, and I spent a bunch of time on it last time.
> > Ok, sounds good + maybe Richard will give it another look.
> So IMO, `ForConstraintInstantiation` should be 'true' always, and that makes 
> those examples pass.  However, I'm now seeing that it causes a failure in the 
> concepts-out-of-line-def.cpp file.  
> 
> I took the example of `foo3`:
> 
> ```
>template concept C = true;
>template 
>struct S {
>  template  requires C
>  void foo3(F3 f); // #1
>};
>template 
>template  requires C
>void S::foo3(F6 f) {} // #3
> ```
> 
> Which, seems to require `ForConstraintInstantiation` to be false to pass.  
> However, I don't think this is correct.  This is only working because when 
> evaluating the in-line one (#1 above!) its skipping the application of `T1`, 
> which is wrong.  
> 
> However, I think the problem here is that the `out of line` version (#3) is 
> not applying the T4 like it should be. SO, I think the 
> `HandleFunctionTemplateDecl` I provided you earlier needs modification.
> 
> FIRST, though not related to this, I think we might need to add 
> `FunctionTemplateDecl::getInjectedTemplateArgs` to the `Result`, but only 
> because that 'sounds right' to me?  IDK what other problem that would cause, 
> but it is worth evaluating/saving for later.  It might just not matter, since 
> we're treating them as equal at the moment, I don't think injecting them 
> would cause anything.
> 
> Secondly: I see that the we can get to the `T4` via the 
> `FTD->getTemplatedDecl()->getQualifier()->getAsType()->getAs()->template_arguments()`.
>   
> 
> HOWEVER, the problem that comes with picking THOSE up, is that it ALSO 
> applies with a `FunctionTemplateDecl` inside of an out-of-line 
> `ClassTemplateSpecializationDecl` (which doesn't NEED the specialization's 
> template args).  
> 
> SO I think the fix here is something in `HandleFunctionTemplateDecl` to make 
> sure we pick up the right list of template arguments.  I haven't figured out 
> the magic incantation to make it work unfortunately, perhaps @rsmith has some 
> hints?  Else I'll keep poking at it.
> 
> BUT, my debugging has shown me that I'm quite convinced the setting 
> `ForConstraintInstantiation ` to false is incorrect.
p.s. Richard is on vacation.

to quote his comment above (where the story began):

>The right way to fix that and the issue being addressed here is that, rather 
>than adjusting the depths, we ?>should substitute the outer template arguments 
>from the scope specifier (A::) into the constraint before >performing the 
>comparison. (In the special case where none of the outer template parameters 
>are used by the >inner template, that does effectively just adjust the depths 
>of any inner template parameters.)

A. the formal meaning of ForConstraintInstantiation=true/false is unclear, 
@eirchkean - if you happen to understand it - mind expanding the comment a bit 
? (and we can add this to the documentation)

B.  T1 - maybe it should be collected as a retained layer ? 



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D146178/ne

  1   2   >