[clang-tools-extra] [clangd] Avoid using CompletionItemKind.Text for macro completions from the index (PR #88236)

2024-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Nathan Ridge (HighCommander4)


Changes

This was fixed in https://github.com/clangd/clangd/issues/1484 for Sema 
completions but the fix did not apply to index completions.

Fixes https://github.com/clangd/clangd/issues/2002

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


4 Files Affected:

- (modified) clang-tools-extra/clangd/CodeComplete.cpp (+9-3) 
- (modified) clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp (+5-2) 
- (modified) clang-tools-extra/clangd/unittests/TestIndex.cpp (+6-1) 
- (modified) clang-tools-extra/clangd/unittests/TestIndex.h (+3-1) 


``diff
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 0e5f08cec440ce..38bc2552195ef7 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -89,7 +89,9 @@ const CodeCompleteOptions::CodeCompletionRankingModel
 
 namespace {
 
-CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
+CompletionItemKind
+toCompletionItemKind(index::SymbolKind Kind,
+ const llvm::StringRef *Signature = nullptr) {
   using SK = index::SymbolKind;
   switch (Kind) {
   case SK::Unknown:
@@ -99,7 +101,10 @@ CompletionItemKind toCompletionItemKind(index::SymbolKind 
Kind) {
   case SK::NamespaceAlias:
 return CompletionItemKind::Module;
   case SK::Macro:
-return CompletionItemKind::Text;
+// Use macro signature (if provided) to tell apart function-like and
+// object-like macros.
+return Signature && Signature->contains('(') ? CompletionItemKind::Function
+ : 
CompletionItemKind::Constant;
   case SK::Enum:
 return CompletionItemKind::Enum;
   case SK::Struct:
@@ -379,7 +384,8 @@ struct CodeCompletionBuilder {
   if (Completion.Scope.empty())
 Completion.Scope = std::string(C.IndexResult->Scope);
   if (Completion.Kind == CompletionItemKind::Missing)
-Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
+Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
+   &C.IndexResult->Signature);
   if (Completion.Name.empty())
 Completion.Name = std::string(C.IndexResult->Name);
   if (Completion.FilterText.empty())
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 6d387fec9b3851..abdf239a3dfb19 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -671,7 +671,8 @@ TEST(CompletionTest, Kinds) {
   #define MACRO 10
   int X = ^
   )cpp",
-  {func("indexFunction"), var("indexVariable"), cls("indexClass")});
+  {func("indexFunction"), var("indexVariable"), cls("indexClass"),
+   macro("indexObjMacro"), macro("indexFuncMacro", "(x, y)")});
   EXPECT_THAT(Results.Completions,
   AllOf(has("function", CompletionItemKind::Function),
 has("variable", CompletionItemKind::Variable),
@@ -680,7 +681,9 @@ TEST(CompletionTest, Kinds) {
 has("MACRO", CompletionItemKind::Constant),
 has("indexFunction", CompletionItemKind::Function),
 has("indexVariable", CompletionItemKind::Variable),
-has("indexClass", CompletionItemKind::Class)));
+has("indexClass", CompletionItemKind::Class),
+has("indexObjMacro", CompletionItemKind::Constant),
+has("indexFuncMacro", CompletionItemKind::Function)));
 
   Results = completions("nam^");
   EXPECT_THAT(Results.Completions,
diff --git a/clang-tools-extra/clangd/unittests/TestIndex.cpp 
b/clang-tools-extra/clangd/unittests/TestIndex.cpp
index 278336bdde2ee5..b13a5d32d17524 100644
--- a/clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ b/clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -38,7 +38,7 @@ static std::string replace(llvm::StringRef Haystack, 
llvm::StringRef Needle,
 // Helpers to produce fake index symbols for memIndex() or completions().
 // USRFormat is a regex replacement string for the unqualified part of the USR.
 Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
-   llvm::StringRef USRFormat) {
+   llvm::StringRef USRFormat, llvm::StringRef Signature) {
   Symbol Sym;
   std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
   size_t Pos = QName.rfind("::");
@@ -55,6 +55,7 @@ Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
   Sym.SymInfo.Kind = Kind;
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
   Sym.Origin = SymbolOrigin::Static;
+  Sym.Signature = Signature;
   return Sym;
 }
 
@@ -86,6 +87,10 @@ Symbol conceptSym(llvm::StringRef Name) {
   return sym(Name, index::SymbolKind::Concept, "@CT@\

[clang-tools-extra] [clangd] Avoid using CompletionItemKind.Text for macro completions from the index (PR #88236)

2024-04-09 Thread via cfe-commits

llvmbot wrote:




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

Author: Nathan Ridge (HighCommander4)


Changes

This was fixed in https://github.com/clangd/clangd/issues/1484 for Sema 
completions but the fix did not apply to index completions.

Fixes https://github.com/clangd/clangd/issues/2002

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


4 Files Affected:

- (modified) clang-tools-extra/clangd/CodeComplete.cpp (+9-3) 
- (modified) clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp (+5-2) 
- (modified) clang-tools-extra/clangd/unittests/TestIndex.cpp (+6-1) 
- (modified) clang-tools-extra/clangd/unittests/TestIndex.h (+3-1) 


``diff
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 0e5f08cec440ce..38bc2552195ef7 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -89,7 +89,9 @@ const CodeCompleteOptions::CodeCompletionRankingModel
 
 namespace {
 
-CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
+CompletionItemKind
+toCompletionItemKind(index::SymbolKind Kind,
+ const llvm::StringRef *Signature = nullptr) {
   using SK = index::SymbolKind;
   switch (Kind) {
   case SK::Unknown:
@@ -99,7 +101,10 @@ CompletionItemKind toCompletionItemKind(index::SymbolKind 
Kind) {
   case SK::NamespaceAlias:
 return CompletionItemKind::Module;
   case SK::Macro:
-return CompletionItemKind::Text;
+// Use macro signature (if provided) to tell apart function-like and
+// object-like macros.
+return Signature && Signature->contains('(') ? CompletionItemKind::Function
+ : 
CompletionItemKind::Constant;
   case SK::Enum:
 return CompletionItemKind::Enum;
   case SK::Struct:
@@ -379,7 +384,8 @@ struct CodeCompletionBuilder {
   if (Completion.Scope.empty())
 Completion.Scope = std::string(C.IndexResult->Scope);
   if (Completion.Kind == CompletionItemKind::Missing)
-Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
+Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
+   &C.IndexResult->Signature);
   if (Completion.Name.empty())
 Completion.Name = std::string(C.IndexResult->Name);
   if (Completion.FilterText.empty())
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 6d387fec9b3851..abdf239a3dfb19 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -671,7 +671,8 @@ TEST(CompletionTest, Kinds) {
   #define MACRO 10
   int X = ^
   )cpp",
-  {func("indexFunction"), var("indexVariable"), cls("indexClass")});
+  {func("indexFunction"), var("indexVariable"), cls("indexClass"),
+   macro("indexObjMacro"), macro("indexFuncMacro", "(x, y)")});
   EXPECT_THAT(Results.Completions,
   AllOf(has("function", CompletionItemKind::Function),
 has("variable", CompletionItemKind::Variable),
@@ -680,7 +681,9 @@ TEST(CompletionTest, Kinds) {
 has("MACRO", CompletionItemKind::Constant),
 has("indexFunction", CompletionItemKind::Function),
 has("indexVariable", CompletionItemKind::Variable),
-has("indexClass", CompletionItemKind::Class)));
+has("indexClass", CompletionItemKind::Class),
+has("indexObjMacro", CompletionItemKind::Constant),
+has("indexFuncMacro", CompletionItemKind::Function)));
 
   Results = completions("nam^");
   EXPECT_THAT(Results.Completions,
diff --git a/clang-tools-extra/clangd/unittests/TestIndex.cpp 
b/clang-tools-extra/clangd/unittests/TestIndex.cpp
index 278336bdde2ee5..b13a5d32d17524 100644
--- a/clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ b/clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -38,7 +38,7 @@ static std::string replace(llvm::StringRef Haystack, 
llvm::StringRef Needle,
 // Helpers to produce fake index symbols for memIndex() or completions().
 // USRFormat is a regex replacement string for the unqualified part of the USR.
 Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
-   llvm::StringRef USRFormat) {
+   llvm::StringRef USRFormat, llvm::StringRef Signature) {
   Symbol Sym;
   std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
   size_t Pos = QName.rfind("::");
@@ -55,6 +55,7 @@ Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
   Sym.SymInfo.Kind = Kind;
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
   Sym.Origin = SymbolOrigin::Static;
+  Sym.Signature = Signature;
   return Sym;
 }
 
@@ -86,6 +87,10 @@ Symbol conceptSym(llvm::StringRef Name) {
   return sym(Name, index::SymbolKind::Conc

[clang-tools-extra] [clangd] Avoid using CompletionItemKind.Text for macro completions from the index (PR #88236)

2024-04-09 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/88236

This was fixed in https://github.com/clangd/clangd/issues/1484 for Sema 
completions but the fix did not apply to index completions.

Fixes https://github.com/clangd/clangd/issues/2002

>From 323adbf6501a3482973a8ebb3fa06e4061252321 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Wed, 10 Apr 2024 02:47:23 -0400
Subject: [PATCH] [clangd] Avoid using CompletionItemKind.Text for macro
 completions from the index

This was fixed in https://github.com/clangd/clangd/issues/1484 for Sema
completions but the fix did not apply to index completions.

Fixes https://github.com/clangd/clangd/issues/2002
---
 clang-tools-extra/clangd/CodeComplete.cpp| 12 +---
 .../clangd/unittests/CodeCompleteTests.cpp   |  7 +--
 clang-tools-extra/clangd/unittests/TestIndex.cpp |  7 ++-
 clang-tools-extra/clangd/unittests/TestIndex.h   |  4 +++-
 4 files changed, 23 insertions(+), 7 deletions(-)

diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 0e5f08cec440ce..38bc2552195ef7 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -89,7 +89,9 @@ const CodeCompleteOptions::CodeCompletionRankingModel
 
 namespace {
 
-CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
+CompletionItemKind
+toCompletionItemKind(index::SymbolKind Kind,
+ const llvm::StringRef *Signature = nullptr) {
   using SK = index::SymbolKind;
   switch (Kind) {
   case SK::Unknown:
@@ -99,7 +101,10 @@ CompletionItemKind toCompletionItemKind(index::SymbolKind 
Kind) {
   case SK::NamespaceAlias:
 return CompletionItemKind::Module;
   case SK::Macro:
-return CompletionItemKind::Text;
+// Use macro signature (if provided) to tell apart function-like and
+// object-like macros.
+return Signature && Signature->contains('(') ? CompletionItemKind::Function
+ : 
CompletionItemKind::Constant;
   case SK::Enum:
 return CompletionItemKind::Enum;
   case SK::Struct:
@@ -379,7 +384,8 @@ struct CodeCompletionBuilder {
   if (Completion.Scope.empty())
 Completion.Scope = std::string(C.IndexResult->Scope);
   if (Completion.Kind == CompletionItemKind::Missing)
-Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
+Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
+   &C.IndexResult->Signature);
   if (Completion.Name.empty())
 Completion.Name = std::string(C.IndexResult->Name);
   if (Completion.FilterText.empty())
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 6d387fec9b3851..abdf239a3dfb19 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -671,7 +671,8 @@ TEST(CompletionTest, Kinds) {
   #define MACRO 10
   int X = ^
   )cpp",
-  {func("indexFunction"), var("indexVariable"), cls("indexClass")});
+  {func("indexFunction"), var("indexVariable"), cls("indexClass"),
+   macro("indexObjMacro"), macro("indexFuncMacro", "(x, y)")});
   EXPECT_THAT(Results.Completions,
   AllOf(has("function", CompletionItemKind::Function),
 has("variable", CompletionItemKind::Variable),
@@ -680,7 +681,9 @@ TEST(CompletionTest, Kinds) {
 has("MACRO", CompletionItemKind::Constant),
 has("indexFunction", CompletionItemKind::Function),
 has("indexVariable", CompletionItemKind::Variable),
-has("indexClass", CompletionItemKind::Class)));
+has("indexClass", CompletionItemKind::Class),
+has("indexObjMacro", CompletionItemKind::Constant),
+has("indexFuncMacro", CompletionItemKind::Function)));
 
   Results = completions("nam^");
   EXPECT_THAT(Results.Completions,
diff --git a/clang-tools-extra/clangd/unittests/TestIndex.cpp 
b/clang-tools-extra/clangd/unittests/TestIndex.cpp
index 278336bdde2ee5..b13a5d32d17524 100644
--- a/clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ b/clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -38,7 +38,7 @@ static std::string replace(llvm::StringRef Haystack, 
llvm::StringRef Needle,
 // Helpers to produce fake index symbols for memIndex() or completions().
 // USRFormat is a regex replacement string for the unqualified part of the USR.
 Symbol sym(llvm::StringRef QName, index::SymbolKind Kind,
-   llvm::StringRef USRFormat) {
+   llvm::StringRef USRFormat, llvm::StringRef Signature) {
   Symbol Sym;
   std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
   size_t Pos = QName.rfind("::");
@@ -55

[clang] 299b636 - Revert "Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF format" (#87987)"

2024-04-09 Thread Phoebe Wang via cfe-commits

Author: Phoebe Wang
Date: 2024-04-10T14:40:07+08:00
New Revision: 299b636a8f1c9cb2382f9dce4cdf6ec6330a79c6

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

LOG: Revert "Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF 
format" (#87987)"

This reverts commit 4a93872a4f57d2f205826052150fadc36490445f.

Sorry, there're still buildbot failures.

Added: 


Modified: 
clang/lib/Driver/ToolChains/MSVC.h
clang/test/Driver/gcodeview-command-line.c

Removed: 
clang/test/Misc/win32-elf.c



diff  --git a/clang/lib/Driver/ToolChains/MSVC.h 
b/clang/lib/Driver/ToolChains/MSVC.h
index 3950a8ed38e8b4..48369e030aade2 100644
--- a/clang/lib/Driver/ToolChains/MSVC.h
+++ b/clang/lib/Driver/ToolChains/MSVC.h
@@ -61,8 +61,9 @@ class LLVM_LIBRARY_VISIBILITY MSVCToolChain : public 
ToolChain {
   /// formats, and to DWARF otherwise. Users can use -gcodeview and -gdwarf to
   /// override the default.
   llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const override 
{
-return getTriple().isOSBinFormatCOFF() ? llvm::codegenoptions::DIF_CodeView
-   : llvm::codegenoptions::DIF_DWARF;
+return getTriple().isOSBinFormatMachO()
+   ? llvm::codegenoptions::DIF_DWARF
+   : llvm::codegenoptions::DIF_CodeView;
   }
 
   /// Set the debugger tuning to "default", since we're definitely not tuning

diff  --git a/clang/test/Driver/gcodeview-command-line.c 
b/clang/test/Driver/gcodeview-command-line.c
index 83542fc71aece4..da8708af322480 100644
--- a/clang/test/Driver/gcodeview-command-line.c
+++ b/clang/test/Driver/gcodeview-command-line.c
@@ -1,6 +1,5 @@
 // Note: %s must be preceded by --, otherwise it may be interpreted as a
 // command-line option, e.g. on Mac where %s is commonly under /Users.
-// REQUIRES: 
aarch64-registered-target,arm-registered-target,x86-registered-target
 
 // ON-NOT: "-gno-codview-commandline"
 // OFF: "-gno-codeview-command-line"

diff  --git a/clang/test/Misc/win32-elf.c b/clang/test/Misc/win32-elf.c
deleted file mode 100644
index f75281dc418727..00
--- a/clang/test/Misc/win32-elf.c
+++ /dev/null
@@ -1,5 +0,0 @@
-// Check that basic use of win32-elf targets works.
-// RUN: %clang -fsyntax-only -target x86_64-pc-win32-elf %s
-
-// RUN: %clang -fsyntax-only -target x86_64-pc-win32-elf -g %s -### 2>&1 | 
FileCheck %s -check-prefix=DEBUG-INFO
-// DEBUG-INFO: -dwarf-version={{.*}}



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


[clang] [clang][dataflow] Propagate locations from result objects to initializers. (PR #87320)

2024-04-09 Thread via cfe-commits

martinboehme wrote:

> I know it is not exactly what we need, but I found 
> `Expr::skipRValueSubobjectAdjustments` in the compiler. I think it might be a 
> good idea to take a look just in case there is something we forgot to cover, 
> and maybe in the future we could look for factoring out some common code.

Thanks! I took a look and didn't see anything in there that we would need to 
cover but don't yet.

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


[clang] [clang][c++20] Fix code coverage mapping crash with generalized NTTPs (PR #85837)

2024-04-09 Thread Andrey Ali Khan Bolshakov via cfe-commits

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


[clang] [clang][c++20] Fix code coverage mapping crash with generalized NTTPs (PR #85837)

2024-04-09 Thread Andrey Ali Khan Bolshakov via cfe-commits


@@ -2177,7 +2177,8 @@ struct CounterCoverageMappingBuilder
   }
 
   void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
-Visit(OVE->getSourceExpr());
+if (const Expr *SE = OVE->getSourceExpr())

bolshakov-a wrote:

> If I'm following correctly, you end up visiting the condition twice

No, the "true" branch visitation (`propagateCounts`) is performed only when it 
is the ordinary `ConditionalOperator` 
(https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CoverageMappingGen.cpp#L2018).

Do you think it should be rewritten first? It's just the first case found by me 
where a non-unique OVE has a source expression which is visited. There may be 
more cases.

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


[clang] [clang-tools-extra] [clang analysis] ExprMutationAnalyzer avoid infinite recursion for recursive forwarding reference (PR #87954)

2024-04-09 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/87954

>From 19f66851204547232d586288fba79d8770837350 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 8 Apr 2024 09:20:58 +0800
Subject: [PATCH 1/3] [clang analysis] ExprMutationAnalyzer support recursive
 forwarding reference

Partialy fixes: #60895
---
 .../Analysis/Analyses/ExprMutationAnalyzer.h  | 40 +++
 clang/lib/Analysis/ExprMutationAnalyzer.cpp   | 22 ++
 .../Analysis/ExprMutationAnalyzerTest.cpp | 30 ++
 3 files changed, 77 insertions(+), 15 deletions(-)

diff --git a/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h 
b/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
index 1ceef944fbc34e..af6106fe303afd 100644
--- a/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
+++ b/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
@@ -8,11 +8,10 @@
 #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_EXPRMUTATIONANALYZER_H
 #define LLVM_CLANG_ANALYSIS_ANALYSES_EXPRMUTATIONANALYZER_H
 
-#include 
-
 #include "clang/AST/AST.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "llvm/ADT/DenseMap.h"
+#include 
 
 namespace clang {
 
@@ -22,8 +21,15 @@ class FunctionParmMutationAnalyzer;
 /// a given statement.
 class ExprMutationAnalyzer {
 public:
+  friend class FunctionParmMutationAnalyzer;
+  struct Cache {
+llvm::DenseMap>
+FuncParmAnalyzer;
+  };
+
   ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context)
-  : Stm(Stm), Context(Context) {}
+  : ExprMutationAnalyzer(Stm, Context, nullptr) {}
 
   bool isMutated(const Expr *Exp) { return findMutation(Exp) != nullptr; }
   bool isMutated(const Decl *Dec) { return findMutation(Dec) != nullptr; }
@@ -45,6 +51,19 @@ class ExprMutationAnalyzer {
   using MutationFinder = const Stmt *(ExprMutationAnalyzer::*)(const Expr *);
   using ResultMap = llvm::DenseMap;
 
+  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context, Cache 
*ParentCache)
+  : Stm(Stm), Context(Context) {
+if (ParentCache != nullptr) {
+  CrossAnalysisCache = ParentCache;
+} else {
+  CrossAnalysisCache = std::make_unique();
+}
+  }
+  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context,
+   std::unique_ptr CrossAnalysisCache)
+  : Stm(Stm), Context(Context),
+CrossAnalysisCache(std::move(CrossAnalysisCache)) {}
+
   const Stmt *findMutationMemoized(const Expr *Exp,
llvm::ArrayRef Finders,
ResultMap &MemoizedResults);
@@ -67,11 +86,15 @@ class ExprMutationAnalyzer {
   const Stmt *findReferenceMutation(const Expr *Exp);
   const Stmt *findFunctionArgMutation(const Expr *Exp);
 
+  Cache *getCache() {
+return std::holds_alternative(CrossAnalysisCache)
+   ? std::get(CrossAnalysisCache)
+   : std::get>(CrossAnalysisCache).get();
+  }
+
   const Stmt &Stm;
   ASTContext &Context;
-  llvm::DenseMap>
-  FuncParmAnalyzer;
+  std::variant> CrossAnalysisCache;
   ResultMap Results;
   ResultMap PointeeResults;
 };
@@ -80,7 +103,10 @@ class ExprMutationAnalyzer {
 // params.
 class FunctionParmMutationAnalyzer {
 public:
-  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context);
+  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context)
+  : FunctionParmMutationAnalyzer(Func, Context, nullptr) {}
+  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context,
+   ExprMutationAnalyzer::Cache 
*CrossAnalysisCache);
 
   bool isMutated(const ParmVarDecl *Parm) {
 return findMutation(Parm) != nullptr;
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index bb042760d297a7..dba6f2a3c02112 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -638,9 +638,10 @@ const Stmt 
*ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
   if (!RefType->getPointeeType().getQualifiers() &&
   RefType->getPointeeType()->getAs()) {
 std::unique_ptr &Analyzer =
-FuncParmAnalyzer[Func];
+getCache()->FuncParmAnalyzer[Func];
 if (!Analyzer)
-  Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
+  Analyzer.reset(
+  new FunctionParmMutationAnalyzer(*Func, Context, getCache()));
 if (Analyzer->findMutation(Parm))
   return Exp;
 continue;
@@ -653,13 +654,15 @@ const Stmt 
*ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
 }
 
 FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
-const FunctionDecl &Func, ASTContext &Context)
-: BodyAnalyzer(*Func.getBody(), Context) {
+const FunctionDecl &Func, ASTContext &Context,
+ExprMutationAnalyzer::Cache *CrossAnalysisCache)
+: BodyAnalyzer(*Func.getBody(), Context, Cro

[clang] Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF format" (PR #87987)

2024-04-09 Thread Phoebe Wang via cfe-commits

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


[clang] 4a93872 - Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF format" (#87987)

2024-04-09 Thread via cfe-commits

Author: Phoebe Wang
Date: 2024-04-10T13:58:47+08:00
New Revision: 4a93872a4f57d2f205826052150fadc36490445f

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

LOG: Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF format" 
(#87987)

This relands #87149.

The previous commit exposed failures on some targets. The reason is only
a few targets support COFF ObjectFormatType on Windows:
https://github.com/llvm/llvm-project/blob/main/llvm/lib/TargetParser/Triple.cpp#L835-L842

With #87149, the targets don't support COFF will report "warning:
argument unused during compilation: '-gcodeview-command-line'
[-Wunused-command-line-argument]" in the test gcodeview-command-line.c

This patch limits gcodeview-command-line.c only run on targets support
COFF.

Added: 
clang/test/Misc/win32-elf.c

Modified: 
clang/lib/Driver/ToolChains/MSVC.h
clang/test/Driver/gcodeview-command-line.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/MSVC.h 
b/clang/lib/Driver/ToolChains/MSVC.h
index 48369e030aade2..3950a8ed38e8b4 100644
--- a/clang/lib/Driver/ToolChains/MSVC.h
+++ b/clang/lib/Driver/ToolChains/MSVC.h
@@ -61,9 +61,8 @@ class LLVM_LIBRARY_VISIBILITY MSVCToolChain : public 
ToolChain {
   /// formats, and to DWARF otherwise. Users can use -gcodeview and -gdwarf to
   /// override the default.
   llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const override 
{
-return getTriple().isOSBinFormatMachO()
-   ? llvm::codegenoptions::DIF_DWARF
-   : llvm::codegenoptions::DIF_CodeView;
+return getTriple().isOSBinFormatCOFF() ? llvm::codegenoptions::DIF_CodeView
+   : llvm::codegenoptions::DIF_DWARF;
   }
 
   /// Set the debugger tuning to "default", since we're definitely not tuning

diff  --git a/clang/test/Driver/gcodeview-command-line.c 
b/clang/test/Driver/gcodeview-command-line.c
index da8708af322480..83542fc71aece4 100644
--- a/clang/test/Driver/gcodeview-command-line.c
+++ b/clang/test/Driver/gcodeview-command-line.c
@@ -1,5 +1,6 @@
 // Note: %s must be preceded by --, otherwise it may be interpreted as a
 // command-line option, e.g. on Mac where %s is commonly under /Users.
+// REQUIRES: 
aarch64-registered-target,arm-registered-target,x86-registered-target
 
 // ON-NOT: "-gno-codview-commandline"
 // OFF: "-gno-codeview-command-line"

diff  --git a/clang/test/Misc/win32-elf.c b/clang/test/Misc/win32-elf.c
new file mode 100644
index 00..f75281dc418727
--- /dev/null
+++ b/clang/test/Misc/win32-elf.c
@@ -0,0 +1,5 @@
+// Check that basic use of win32-elf targets works.
+// RUN: %clang -fsyntax-only -target x86_64-pc-win32-elf %s
+
+// RUN: %clang -fsyntax-only -target x86_64-pc-win32-elf -g %s -### 2>&1 | 
FileCheck %s -check-prefix=DEBUG-INFO
+// DEBUG-INFO: -dwarf-version={{.*}}



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


[clang] [clang][Interp] Integral pointers (PR #84159)

2024-04-09 Thread Timm Baeder via cfe-commits

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

>From 3d6a09d1324dbd354668b0341644fb70fe09a47c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 6 Mar 2024 08:36:52 +0100
Subject: [PATCH] [clang][Interp] Integral pointers

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  81 -
 clang/lib/AST/Interp/ByteCodeStmtGen.cpp |   2 +-
 clang/lib/AST/Interp/Descriptor.h|   1 +
 clang/lib/AST/Interp/FunctionPointer.h   |  10 +-
 clang/lib/AST/Interp/Interp.cpp  |   5 +
 clang/lib/AST/Interp/Interp.h|  85 +++--
 clang/lib/AST/Interp/InterpBlock.cpp |   4 +-
 clang/lib/AST/Interp/Opcodes.td  |  12 +
 clang/lib/AST/Interp/Pointer.cpp | 168 +++---
 clang/lib/AST/Interp/Pointer.h   | 383 +--
 clang/lib/AST/Interp/PrimType.h  |   4 +
 clang/test/AST/Interp/c.c|  18 ++
 clang/test/AST/Interp/const-eval.c   | 192 
 clang/test/AST/Interp/functions.cpp  |  15 +
 14 files changed, 798 insertions(+), 182 deletions(-)
 create mode 100644 clang/test/AST/Interp/const-eval.c

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index a1ce6575148325..4e650d49d180bb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -173,10 +173,18 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return this->emitCastFloatingIntegral(*ToT, CE);
   }
 
-  case CK_NullToPointer:
+  case CK_NullToPointer: {
 if (DiscardResult)
   return true;
-return this->emitNull(classifyPrim(CE->getType()), CE);
+
+const Descriptor *Desc = nullptr;
+const QualType PointeeType = CE->getType()->getPointeeType();
+if (!PointeeType.isNull()) {
+  if (std::optional T = classify(PointeeType))
+Desc = P.createDescriptor(SubExpr, *T);
+}
+return this->emitNull(classifyPrim(CE->getType()), Desc, CE);
+  }
 
   case CK_PointerToIntegral: {
 if (DiscardResult)
@@ -199,6 +207,41 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return true;
   }
 
+  case CK_IntegralToPointer: {
+QualType IntType = SubExpr->getType();
+assert(IntType->isIntegralOrEnumerationType());
+if (!this->visit(SubExpr))
+  return false;
+// FIXME: I think the discard is wrong since the int->ptr cast might cause 
a
+// diagnostic.
+PrimType T = classifyPrim(IntType);
+if (DiscardResult)
+  return this->emitPop(T, CE);
+
+QualType PtrType = CE->getType();
+assert(PtrType->isPointerType());
+
+const Descriptor *Desc;
+if (std::optional T = classify(PtrType->getPointeeType()))
+  Desc = P.createDescriptor(SubExpr, *T);
+else if (PtrType->getPointeeType()->isVoidType())
+  Desc = nullptr;
+else
+  Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
+Descriptor::InlineDescMD, true, false,
+/*IsMutable=*/false, nullptr);
+
+if (!this->emitGetIntPtr(T, Desc, CE))
+  return false;
+
+PrimType DestPtrT = classifyPrim(PtrType);
+if (DestPtrT == PT_Ptr)
+  return true;
+
+// In case we're converting the integer to a non-Pointer.
+return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
+  }
+
   case CK_AtomicToNonAtomic:
   case CK_ConstructorConversion:
   case CK_FunctionToPointerDecay:
@@ -207,13 +250,31 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   case CK_UserDefinedConversion:
 return this->delegate(SubExpr);
 
-  case CK_BitCast:
+  case CK_BitCast: {
+// Reject bitcasts to atomic types.
 if (CE->getType()->isAtomicType()) {
   if (!this->discard(SubExpr))
 return false;
   return this->emitInvalidCast(CastKind::Reinterpret, CE);
 }
-return this->delegate(SubExpr);
+
+if (DiscardResult)
+  return this->discard(SubExpr);
+
+std::optional FromT = classify(SubExpr->getType());
+std::optional ToT = classifyPrim(CE->getType());
+if (!FromT || !ToT)
+  return false;
+
+assert(isPtrType(*FromT));
+assert(isPtrType(*ToT));
+if (FromT == ToT)
+  return this->delegate(SubExpr);
+
+if (!this->visit(SubExpr))
+  return false;
+return this->emitDecayPtr(*FromT, *ToT, CE);
+  }
 
   case CK_IntegralToBoolean:
   case CK_IntegralCast: {
@@ -245,7 +306,7 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 if (!this->visit(SubExpr))
   return false;
 
-if (!this->emitNull(PtrT, CE))
+if (!this->emitNull(PtrT, nullptr, CE))
   return false;
 
 return this->emitNE(PtrT, CE);
@@ -455,7 +516,7 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 
   // Pointer arithmetic special case.
   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
-if (T == PT_Ptr || (LT == PT_Ptr && RT == PT_Ptr))
+if (isPtrType(*T) || (isPtr

[clang] [llvm] [InstCombine][CVP][SCCP] Add support for `uitofp nneg` (PR #86154)

2024-04-09 Thread Nikita Popov via cfe-commits

nikic wrote:

Can you please split this into separate patches? Or at least split out the 
InstCombine part of it?

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


[clang] [clang][Interp] Integral pointers (PR #84159)

2024-04-09 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 



@@ -1912,6 +1929,10 @@ inline bool NoRet(InterpState &S, CodePtr OpPC) {
 
 inline bool NarrowPtr(InterpState &S, CodePtr OpPC) {
   const Pointer &Ptr = S.Stk.pop();
+  if (!S.getLangOpts().CPlusPlus) {
+S.Stk.push(Ptr);

tbaederr wrote:

Don't remember why I added that but it's not necessary.

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


[clang] Reland "[Win32][ELF] Make CodeView a DebugInfoFormat only for COFF format" (PR #87987)

2024-04-09 Thread Arthur Eubanks via cfe-commits

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


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


[clang] [Clang][Sema] set declaration invalid earlier to prevent crash in calculating record layout (PR #87173)

2024-04-09 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/87173

>From a0c0feae5bee318bcc253e5497994bfe78f308ee Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Sun, 31 Mar 2024 09:38:05 +0800
Subject: [PATCH] [Clang][Sema] set declaration invalid earlier to prevent
 crash in calculating record layout

---
 clang/docs/ReleaseNotes.rst  | 2 ++
 clang/include/clang/Sema/Scope.h | 6 ++
 clang/lib/Parse/ParseDeclCXX.cpp | 5 +
 clang/lib/Sema/SemaDecl.cpp  | 7 +++
 clang/test/SemaCXX/PR75221.cpp   | 6 ++
 5 files changed, 26 insertions(+)
 create mode 100644 clang/test/SemaCXX/PR75221.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f96cebbde3d825..31a0e5d4d11a12 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -529,6 +529,8 @@ Bug Fixes to C++ Support
 - Clang now correctly tracks type dependence of by-value captures in lambdas 
with an explicit
   object parameter.
   Fixes (#GH70604), (#GH79754), (#GH84163), (#GH84425), (#GH86054), 
(#GH86398), and (#GH86399).
+- Fix a crash caused by defined struct in a type alias template when the 
structure
+  has fields with dependent type. Fixes (#GH75221).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 099c2739e8603a..1752a25111a775 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -156,6 +156,9 @@ class Scope {
 /// This is the scope of an OpenACC Compute Construct, which restricts
 /// jumping into/out of it.
 OpenACCComputeConstructScope = 0x1000,
+
+/// This is a scope of type alias declaration.
+TypeAliasScope = 0x2000,
   };
 
 private:
@@ -580,6 +583,9 @@ class Scope {
   /// if/switch/while/for statement.
   bool isControlScope() const { return getFlags() & Scope::ControlScope; }
 
+  /// Determine whether this scope is a type alias scope.
+  bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 861a25dc5103c1..270d09f8c9580c 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -799,6 +799,11 @@ Parser::DeclGroupPtrTy Parser::ParseUsingDeclaration(
 ProhibitAttributes(PrefixAttrs);
 
 Decl *DeclFromDeclSpec = nullptr;
+Scope *CurScope = getCurScope();
+if (CurScope)
+  CurScope->setFlags(Scope::ScopeFlags::TypeAliasScope |
+ CurScope->getFlags());
+
 Decl *AD = ParseAliasDeclarationAfterDeclarator(
 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c790dab72dd721..afe25e2a1de4ab 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19622,6 +19622,13 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
   // Okay, we successfully defined 'Record'.
   if (Record) {
 bool Completed = false;
+if (S) {
+  Scope *Parent = S->getParent();
+  if (Parent && Parent->isTypeAliasScope() &&
+  Parent->isTemplateParamScope())
+Record->setInvalidDecl();
+}
+
 if (CXXRecord) {
   if (!CXXRecord->isInvalidDecl()) {
 // Set access bits correctly on the directly-declared conversions.
diff --git a/clang/test/SemaCXX/PR75221.cpp b/clang/test/SemaCXX/PR75221.cpp
new file mode 100644
index 00..b342e347c5606a
--- /dev/null
+++ b/clang/test/SemaCXX/PR75221.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -verify -std=c++11 -fsyntax-only %s
+
+template  using foo = struct foo { // expected-error {{'foo' cannot 
be defined in a type alias template}}
+  T size = 0;
+};
+foo a;

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


[clang] [clang] Introduce `SemaSYCL` (PR #88086)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,66 @@
+//===- SemaOpenACC.h 000- Semantic Analysis for SYCL constructs 
---===//

Endilll wrote:

That's... embarrassing.

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


[clang] [clang] Introduce `SemaSYCL` (PR #88086)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,66 @@
+//===- SemaOpenACC.h 000- Semantic Analysis for SYCL constructs 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+/// \file
+/// This file declares semantic analysis for SYCL constructs.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_SEMA_SEMASYCL_H
+#define LLVM_CLANG_SEMA_SEMASYCL_H
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/Type.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Sema/Ownership.h"
+#include "clang/Sema/SemaBase.h"
+#include "llvm/ADT/DenseSet.h"
+
+namespace clang {
+
+class SemaSYCL : public SemaBase {
+public:
+  SemaSYCL(Sema &S);
+
+  /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
+  /// context is "used as device code".
+  ///
+  /// - If CurLexicalContext is a kernel function or it is known that the
+  ///   function will be emitted for the device, emits the diagnostics
+  ///   immediately.
+  /// - If CurLexicalContext is a function and we are compiling
+  ///   for the device, but we don't know that this function will be codegen'ed
+  ///   for devive yet, creates a diagnostic which is emitted if and when we
+  ///   realize that the function will be codegen'ed.
+  ///
+  /// Example usage:
+  ///
+  /// Diagnose __float128 type usage only from SYCL device code if the current
+  /// target doesn't support it
+  /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
+  /// S.getLangOpts().SYCLIsDevice)
+  ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
+  SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,

Endilll wrote:

I did that for all 4 functions in `SemaSYCL`.

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


[clang] [clang] Introduce `SemaSYCL` (PR #88086)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,66 @@
+//===- SemaOpenACC.h 000- Semantic Analysis for SYCL constructs 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+/// \file
+/// This file declares semantic analysis for SYCL constructs.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_SEMA_SEMASYCL_H
+#define LLVM_CLANG_SEMA_SEMASYCL_H
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/Type.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Sema/Ownership.h"
+#include "clang/Sema/SemaBase.h"
+#include "llvm/ADT/DenseSet.h"
+
+namespace clang {
+
+class SemaSYCL : public SemaBase {
+public:
+  SemaSYCL(Sema &S);
+
+  /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
+  /// context is "used as device code".
+  ///
+  /// - If CurLexicalContext is a kernel function or it is known that the
+  ///   function will be emitted for the device, emits the diagnostics
+  ///   immediately.
+  /// - If CurLexicalContext is a function and we are compiling
+  ///   for the device, but we don't know that this function will be codegen'ed
+  ///   for devive yet, creates a diagnostic which is emitted if and when we
+  ///   realize that the function will be codegen'ed.
+  ///
+  /// Example usage:
+  ///
+  /// Diagnose __float128 type usage only from SYCL device code if the current
+  /// target doesn't support it
+  /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
+  /// S.getLangOpts().SYCLIsDevice)
+  ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
+  SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
+ unsigned DiagID);
+
+  void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
+  llvm::DenseSet Visited,
+  ValueDecl *DeclToCheck);
+
+  ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,

Endilll wrote:

Done.

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


[clang] [clang] Introduce `SemaSYCL` (PR #88086)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits

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

>From 9a5c872a8cb7de103841538d251df2f4638a4f5e Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Tue, 9 Apr 2024 06:38:25 +0300
Subject: [PATCH 1/2] [clang] Introduce `SemaSYCL`

---
 clang/include/clang/Sema/Sema.h | 55 +++-
 clang/include/clang/Sema/SemaSYCL.h | 66 +
 clang/lib/Parse/ParseExpr.cpp   |  5 ++-
 clang/lib/Sema/Sema.cpp |  6 ++-
 clang/lib/Sema/SemaExpr.cpp | 22 --
 clang/lib/Sema/SemaSYCL.cpp | 46 +++-
 clang/lib/Sema/TreeTransform.h  |  4 +-
 7 files changed, 119 insertions(+), 85 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaSYCL.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9769d36900664c..e3e255a0dd76f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -184,6 +184,7 @@ class PseudoObjectExpr;
 class QualType;
 class SemaHLSL;
 class SemaOpenACC;
+class SemaSYCL;
 class StandardConversionSequence;
 class Stmt;
 class StringLiteral;
@@ -467,7 +468,6 @@ class Sema final : public SemaBase {
   // 37. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
   // 38. CUDA (SemaCUDA.cpp)
   // 39. OpenMP Directives and Clauses (SemaOpenMP.cpp)
-  // 40. SYCL Constructs (SemaSYCL.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -974,6 +974,11 @@ class Sema final : public SemaBase {
 return *OpenACCPtr;
   }
 
+  SemaSYCL &SYCL() {
+assert(SYCLPtr);
+return *SYCLPtr;
+  }
+
 protected:
   friend class Parser;
   friend class InitializationSequence;
@@ -1006,6 +1011,7 @@ class Sema final : public SemaBase {
 
   std::unique_ptr HLSLPtr;
   std::unique_ptr OpenACCPtr;
+  std::unique_ptr SYCLPtr;
 
   ///@}
 
@@ -5455,15 +5461,6 @@ class Sema final : public SemaBase {
   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
 
-  ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
-   SourceLocation LParen,
-   SourceLocation RParen,
-   TypeSourceInfo *TSI);
-  ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
-   SourceLocation LParen,
-   SourceLocation RParen,
-   ParsedType ParsedTy);
-
   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
 
   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
@@ -14516,44 +14513,6 @@ class Sema final : public SemaBase {
 OpenMPDirectiveKind CancelRegion);
 
   ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
-  /// \name SYCL Constructs
-  /// Implementations are in SemaSYCL.cpp
-  ///@{
-
-public:
-  /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
-  /// context is "used as device code".
-  ///
-  /// - If CurLexicalContext is a kernel function or it is known that the
-  ///   function will be emitted for the device, emits the diagnostics
-  ///   immediately.
-  /// - If CurLexicalContext is a function and we are compiling
-  ///   for the device, but we don't know that this function will be codegen'ed
-  ///   for devive yet, creates a diagnostic which is emitted if and when we
-  ///   realize that the function will be codegen'ed.
-  ///
-  /// Example usage:
-  ///
-  /// Diagnose __float128 type usage only from SYCL device code if the current
-  /// target doesn't support it
-  /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
-  /// S.getLangOpts().SYCLIsDevice)
-  ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
-  SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
- unsigned DiagID);
-
-  void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
-  llvm::DenseSet Visited,
-  ValueDecl *DeclToCheck);
-
-  ///@}
 };
 
 DeductionFailureInfo
diff --git a/clang/include/clang/Sema/SemaSYCL.h 
b/clang/include/clang/Sema/SemaSYCL.h
new file mode 100644
index 00..93fc8c7d99a5e0
--- /dev/null
+++ b/clang/include/clang/Sema/SemaSYCL.h
@@ -0,0 +1,66 @@
+//===- SemaOpenACC.h 000- Semantic Analysis for SYCL constructs 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+/// \file
+/// This file declares sem

[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

2024-04-09 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

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


[clang] [NFC][Clang] Fix static analyzer concern (PR #88179)

2024-04-09 Thread Timm Baeder via cfe-commits

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


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


[clang] [llvm] [InstCombine][CVP][SCCP] Add support for `uitofp nneg` (PR #86154)

2024-04-09 Thread via cfe-commits

goldsteinn wrote:

rebased

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


[clang] [llvm] [InstCombine][CVP][SCCP] Add support for `uitofp nneg` (PR #86154)

2024-04-09 Thread via cfe-commits

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

>From ea9f3393a46f421c3ba96f924f302c5ac4b3e3b0 Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 21 Mar 2024 11:01:21 -0500
Subject: [PATCH 1/4] [InstCombine] Add canonicalization of `sitofp` -> `uitofp
 nneg`

This is essentially the same as #82404 but has the `nneg` flag which
allows the backend to reliably undo the transform.
---
 clang/test/Headers/__clang_hip_math.hip   | 24 +++
 .../InstCombine/InstCombineCasts.cpp  | 18 -
 .../test/Transforms/InstCombine/add-sitofp.ll | 20 +++---
 .../Transforms/InstCombine/binop-itofp.ll | 66 +--
 .../Transforms/InstCombine/clamp-to-minmax.ll | 10 +--
 llvm/test/Transforms/InstCombine/fpcast.ll| 24 +++
 .../Transforms/InstCombine/minmax-fold.ll | 10 +--
 llvm/test/Transforms/InstCombine/minmax-fp.ll |  2 +-
 llvm/test/Transforms/InstCombine/pr27236.ll   |  2 +-
 llvm/test/Transforms/InstCombine/sitofp.ll|  2 +-
 .../LoopVectorize/X86/float-induction-x86.ll  |  6 +-
 .../LoopVectorize/float-induction.ll  | 56 
 12 files changed, 127 insertions(+), 113 deletions(-)

diff --git a/clang/test/Headers/__clang_hip_math.hip 
b/clang/test/Headers/__clang_hip_math.hip
index 37099de74fb8ec..bff1708120604b 100644
--- a/clang/test/Headers/__clang_hip_math.hip
+++ b/clang/test/Headers/__clang_hip_math.hip
@@ -1685,7 +1685,7 @@ extern "C" __device__ double test_j1(double x) {
 // DEFAULT-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// DEFAULT-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
+// DEFAULT-NEXT:[[CONV_I:%.*]] = uitofp nneg i32 [[MUL_I]] to float
 // DEFAULT-NEXT:[[DIV_I:%.*]] = fdiv contract float [[CONV_I]], [[Y]]
 // DEFAULT-NEXT:[[MUL8_I:%.*]] = fmul contract float [[__X1_0_I3]], 
[[DIV_I]]
 // DEFAULT-NEXT:[[SUB_I]] = fsub contract float [[MUL8_I]], [[__X0_0_I2]]
@@ -1718,7 +1718,7 @@ extern "C" __device__ double test_j1(double x) {
 // FINITEONLY-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// FINITEONLY-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
+// FINITEONLY-NEXT:[[CONV_I:%.*]] = uitofp nneg i32 [[MUL_I]] to float
 // FINITEONLY-NEXT:[[DIV_I:%.*]] = fdiv nnan ninf contract float 
[[CONV_I]], [[Y]]
 // FINITEONLY-NEXT:[[MUL8_I:%.*]] = fmul nnan ninf contract float 
[[__X1_0_I3]], [[DIV_I]]
 // FINITEONLY-NEXT:[[SUB_I]] = fsub nnan ninf contract float [[MUL8_I]], 
[[__X0_0_I2]]
@@ -1751,7 +1751,7 @@ extern "C" __device__ double test_j1(double x) {
 // APPROX-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // APPROX-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // APPROX-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// APPROX-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
+// APPROX-NEXT:[[CONV_I:%.*]] = uitofp nneg i32 [[MUL_I]] to float
 // APPROX-NEXT:[[DIV_I:%.*]] = fdiv contract float [[CONV_I]], [[Y]]
 // APPROX-NEXT:[[MUL8_I:%.*]] = fmul contract float [[__X1_0_I3]], 
[[DIV_I]]
 // APPROX-NEXT:[[SUB_I]] = fsub contract float [[MUL8_I]], [[__X0_0_I2]]
@@ -1788,7 +1788,7 @@ extern "C" __device__ float test_jnf(int x, float y) {
 // DEFAULT-NEXT:[[__X1_0_I3:%.*]] = phi double [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[__X0_0_I2:%.*]] = phi double [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// DEFAULT-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to double
+// DEFAULT-NEXT:[[CONV_I:%.*]] = uitofp nneg i32 [[MUL_I]] to double
 // DEFAULT-NEXT:[[DIV_I:%.*]] = fdiv contract double [[CONV_I]], [[Y]]
 // DEFAULT-NEXT:[[MUL8_I:%.*]] = fmul contract double [[__X1_0_I3]], 
[[DIV_I]]
 // DEFAULT-NEXT:[[SUB_I]] = fsub contract double [[MUL8_I]], [[__X0_0_I2]]
@@ -1821,7 +1821,7 @@ extern "C" __device__ float test_jnf(int x, float y) {
 // FINITEONLY-NEXT:[[__X1_0_I3:%.*]] = phi double [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[__X0_0_I2:%.*]] = phi double [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// FINITEONLY-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to double
+//

[clang] [clang] Improve source location in binary type traits diagnostics (PR #88097)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits

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


[clang] 817c832 - [clang] Improve source location in binary type traits diagnostics (#88097)

2024-04-09 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-04-10T08:21:18+04:00
New Revision: 817c832e72f0df3efe1ddd804283c8c89b78639f

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

LOG: [clang] Improve source location in binary type traits diagnostics (#88097)

This patch takes advantage of a recent NFC change that refactored
`EvaluateBinaryTypeTrait()` to accept `TypeSourceInfo` instead of
`QualType` c7db450e5c1a83ea768765dcdedfd50f3358d418.
Before:
```
test2.cpp:105:55: error: variable length arrays are not supported in 
'__is_layout_compatible'
  105 |   static_assert(!__is_layout_compatible(int[n], int[n]));
  |   ^
test2.cpp:125:76: error: incomplete type 'CStructIncomplete' where a complete 
type is required
  125 |   static_assert(__is_layout_compatible(CStructIncomplete, 
CStructIncomplete));
  | 
   ^
``` 
After:
```
test2.cpp:105:41: error: variable length arrays are not supported in 
'__is_layout_compatible'
  105 |   static_assert(!__is_layout_compatible(int[n], int[n]));
  | ^
test2.cpp:125:40: error: incomplete type 'CStructIncomplete' where a complete 
type is required
  125 |   static_assert(__is_layout_compatible(CStructIncomplete, 
CStructIncomplete));
  |^
```

Added: 


Modified: 
clang/lib/Sema/SemaExprCXX.cpp
clang/test/SemaCXX/type-traits.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 80c01b14379c9f..9822477260e592 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5895,7 +5895,8 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, const TypeSourceI
 return false;
 
   if (Self.RequireCompleteType(
-  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
+  Rhs->getTypeLoc().getBeginLoc(), RhsT,
+  diag::err_incomplete_type_used_in_type_trait_expr))
 return false;
 
   return BaseInterface->isSuperClassOf(DerivedInterface);
@@ -5918,8 +5919,9 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, const TypeSourceI
 //   If Base and Derived are class types and are 
diff erent types
 //   (ignoring possible cv-qualifiers) then Derived shall be a
 //   complete type.
-if (Self.RequireCompleteType(KeyLoc, RhsT,
-  diag::err_incomplete_type_used_in_type_trait_expr))
+if (Self.RequireCompleteType(
+Rhs->getTypeLoc().getBeginLoc(), RhsT,
+diag::err_incomplete_type_used_in_type_trait_expr))
   return false;
 
 return cast(rhsRecord->getDecl())
@@ -5971,7 +5973,8 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, const TypeSourceI
   return LhsT->isVoidType();
 
 // A function definition requires a complete, non-abstract return type.
-if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, 
RhsT))
+if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
+Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
   return false;
 
 // Compute the result of add_rvalue_reference.
@@ -6021,12 +6024,14 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, 
TypeTrait BTT, const TypeSourceI
 //   For both, T and U shall be complete types, (possibly cv-qualified)
 //   void, or arrays of unknown bound.
 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
-Self.RequireCompleteType(KeyLoc, LhsT,
-  diag::err_incomplete_type_used_in_type_trait_expr))
+Self.RequireCompleteType(
+Lhs->getTypeLoc().getBeginLoc(), LhsT,
+diag::err_incomplete_type_used_in_type_trait_expr))
   return false;
 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
-Self.RequireCompleteType(KeyLoc, RhsT,
-  diag::err_incomplete_type_used_in_type_trait_expr))
+Self.RequireCompleteType(
+Rhs->getTypeLoc().getBeginLoc(), RhsT,
+diag::err_incomplete_type_used_in_type_trait_expr))
   return false;
 
 // cv void is never assignable.
@@ -6081,12 +6086,17 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, 
TypeTrait BTT, const TypeSourceI
   }
   case BTT_IsLayoutCompatible: {
 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
-  Self.RequireCompleteType(KeyLoc, LhsT, diag::err_incomplete_type);
+  Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
+   diag::err_incomplete_type);
 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
-  Self.RequireCompleteType(KeyL

[clang] [clang] Add tests for some CWG 5xx issues (PR #87909)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang] Add tests for some CWG 5xx issues (PR #87909)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits


@@ -661,6 +680,10 @@ namespace dr553 {
 }
 
 // dr554: na
+
+// dr555: na

Endilll wrote:

I added a proper test for 555. Basically, I copied 466 test, and derived 
reference tests from it. In 466, I derived a test for non-pointer and 
non-reference scalar types.

> Finally, there is no place in the Standard that describes the lookup for 
> pseudo-destructor calls of the form p->T::~T() and r.T::~T(), where p and r 
> are a pointer and reference to scalar, respectively.

As we agreed offline, I'm testing just this sentence from 555, as that's the 
only actionable thing there for us.

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


[clang] [clang] Add tests for some CWG 5xx issues (PR #87909)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits

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

>From 222f444f91d477bbc1ab2657a7f820740031f765 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sun, 7 Apr 2024 10:52:10 +0300
Subject: [PATCH 1/3] [clang] Add tests for some CWG 5xx issues

---
 clang/test/CXX/drs/dr15xx.cpp |  2 +-
 clang/test/CXX/drs/dr19xx.cpp |  2 +-
 clang/test/CXX/drs/dr3xx.cpp  | 12 
 clang/test/CXX/drs/dr5xx.cpp  | 37 +++
 clang/www/cxx_dr_status.html  | 16 +++
 5 files changed, 59 insertions(+), 10 deletions(-)

diff --git a/clang/test/CXX/drs/dr15xx.cpp b/clang/test/CXX/drs/dr15xx.cpp
index 195c0fa610d579..6e3ad41c748fb1 100644
--- a/clang/test/CXX/drs/dr15xx.cpp
+++ b/clang/test/CXX/drs/dr15xx.cpp
@@ -555,7 +555,7 @@ auto DR1579_lambda_invalid = []() -> GenericMoveOnly {
 #endif
 } // end namespace dr1579
 
-namespace dr1584 {
+namespace dr1584 { // dr1584: 7 drafting 2015-05
 #if __cplusplus >= 201103L
   // Deducing function types from cv-qualified types
   template void f(const T *); // #dr1584-f
diff --git a/clang/test/CXX/drs/dr19xx.cpp b/clang/test/CXX/drs/dr19xx.cpp
index 716b1476831ed9..f8c1581f08540e 100644
--- a/clang/test/CXX/drs/dr19xx.cpp
+++ b/clang/test/CXX/drs/dr19xx.cpp
@@ -34,7 +34,7 @@ namespace dr1902 { // dr1902: 3.7
 #endif
 }
 
-namespace dr1903 {
+namespace dr1903 { // dr1903: 2.7
   namespace A {
 struct a {};
 int a;
diff --git a/clang/test/CXX/drs/dr3xx.cpp b/clang/test/CXX/drs/dr3xx.cpp
index 483ebf7a08aadb..6165835e2c183d 100644
--- a/clang/test/CXX/drs/dr3xx.cpp
+++ b/clang/test/CXX/drs/dr3xx.cpp
@@ -1568,6 +1568,18 @@ namespace dr391 { // dr391: 2.8 c++11
 }
 
 // dr392 is in dr392.cpp
+
+namespace dr393 { // dr393: 2.7
+
+template 
+struct S {};
+
+void f1(S);
+void f2(S);
+void g(int(*S::*)[]);
+
+} // namespace dr393
+
 // dr394: na
 
 namespace dr395 { // dr395: 3.0
diff --git a/clang/test/CXX/drs/dr5xx.cpp b/clang/test/CXX/drs/dr5xx.cpp
index 426b368b390ae6..981b9d1afca970 100644
--- a/clang/test/CXX/drs/dr5xx.cpp
+++ b/clang/test/CXX/drs/dr5xx.cpp
@@ -18,6 +18,10 @@ namespace std {
 void *operator new(size_t, std::align_val_t); // 
#dr5xx-global-operator-new-aligned
 #endif
 
+namespace std {
+  struct type_info;
+}
+
 namespace dr500 { // dr500: dup 372
   class D;
   class A {
@@ -265,6 +269,18 @@ namespace dr527 { // dr527: na
   int ax = a.x, bx = b.x, cx = c.x, dx = d.x, ex = E::e->x, fx = F::f->x;
 }
 
+namespace dr528 { // dr528: 2.7
+
+struct S; // #dr528-S
+
+void f() {
+  typeid(S);
+  // expected-error@-1 {{'typeid' of incomplete type 'S'}}
+  //   expected-note@#dr528-S {{forward declaration of 'dr528::S'}}
+}
+
+} // namespace dr528
+
 namespace dr530 { // dr530: yes
   template struct S { enum { N = 1 }; };
   template struct T { enum { N = 1 }; };
@@ -618,6 +634,8 @@ namespace dr548 { // dr548: dup 482
   template void dr548::f();
 }
 
+// dr550: dup 393
+
 namespace dr551 { // dr551: yes c++11
   // FIXME: This obviously should apply in C++98 mode too.
   template void f() {}
@@ -641,6 +659,7 @@ namespace dr552 { // dr552: yes
   X x;
 }
 
+// dr553: 2.7
 struct dr553_class {
   friend void *operator new(size_t, dr553_class);
 };
@@ -661,6 +680,10 @@ namespace dr553 {
 }
 
 // dr554: na
+
+// dr555: na
+// NB: name lookup cases that issue briefly touches are covered in our test 
for CWG466
+
 // dr556: na
 
 namespace dr557 { // dr557: 3.1
@@ -689,6 +712,20 @@ namespace dr558 { // dr558: 2.9
 
 template struct dr559 { typedef int T; dr559::T u; }; // dr559: yes
 
+namespace dr560 { // dr560: 16
+
+template 
+struct Outer {
+  struct Inner {
+Inner* self();
+  };
+};
+template 
+Outer::Inner* Outer::Inner::self() { return this; }
+// cxx98-17-error@-1 {{missing 'typename' prior to dependent type name 
Outer::Inner; implicit 'typename' is a C++20 extension}}
+
+} // namespace dr560
+
 namespace dr561 { // dr561: yes
   template void f(int);
   template void g(T t) {
diff --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index a4c133c13c493f..15318bab81359b 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -2398,7 +2398,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/393.html";>393
 CD4
 Pointer to array of unknown bound in template argument list in 
parameter
-Unknown
+Clang 2.7
   
   
 https://cplusplus.github.io/CWG/issues/394.html";>394
@@ -3208,7 +3208,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/528.html";>528
 NAD
 Why are incomplete class types not allowed with typeid?
-Unknown
+Clang 2.7
   
   
 https://cplusplus.github.io/CWG/issues/529.html";>529
@@ -3342,7 +3342,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/550.html";>550
 dup
 Pointer to array of unknown bound in parameter declarations
-Unknown
+Duplicate of 393
   
   

[clang] [Clang][Sema] Implement approved resolution for CWG2858 (PR #88042)

2024-04-09 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll commented:

This looks much better now, thank you! 
As Corentin suggested earlier, run `clang/www/make_cxx_dr_status` to update the 
DR page, and this should be good to go.

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


[clang] [llvm] [clang][llvm] Remove "implicit-section-name" attribute (PR #87906)

2024-04-09 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

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


[clang] [C99] Claim conformance for _Complex support (PR #88161)

2024-04-09 Thread A. Jiang via cfe-commits

frederick-vs-ja wrote:

> But fails on Windows.

This seems because of that MS UCRT's complex math functions are non-conforming.

I _guess_ they could work if we write the following before including UCRT's 
``.
```C
#define _C_COMPLEX_T
typedef double _Complex _C_double_complex;
typedef float _Complex _C_float_complex;
typedef long double _Complex _C_ldouble_complex;
```

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


[clang] [clang-format] instanceof is a keyword only in Java/JavaScript (PR #88085)

2024-04-09 Thread Owen Pan via cfe-commits

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


[clang] bcf849b - [clang-format] instanceof is a keyword only in Java/JavaScript (#88085)

2024-04-09 Thread via cfe-commits

Author: Owen Pan
Date: 2024-04-09T20:00:03-07:00
New Revision: bcf849b1e5faea405cfbbd4bc848048651055b25

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

LOG: [clang-format] instanceof is a keyword only in Java/JavaScript (#88085)

Fixes #87907.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9abd4282103b7b..628f70417866c3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2354,7 +2354,8 @@ class AnnotatingParser {
 // Line.MightBeFunctionDecl can only be true after the parentheses of a
 // function declaration have been found. In this case, 'Current' is a
 // trailing token of this declaration and thus cannot be a name.
-if (Current.is(Keywords.kw_instanceof)) {
+if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
+Current.is(Keywords.kw_instanceof)) {
   Current.setType(TT_BinaryOperator);
 } else if (isStartOfName(Current) &&
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 251e317c7499cf..c3153cf6b16f07 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1769,6 +1769,10 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsFunctionDeclarationNames) {
   EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_FunctionTypeLParen);
 
+  Tokens = annotate("void instanceof();");
+  ASSERT_EQ(Tokens.size(), 6u);
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName);
+
   Tokens = annotate("int iso_time(time_t);");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName);



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


[clang] [polly] [clang-format] Correctly annotate braces in macros (PR #87953)

2024-04-09 Thread Owen Pan via cfe-commits

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


[clang] 58323de - [clang-format] Correctly annotate braces in macros (#87953)

2024-04-09 Thread via cfe-commits

Author: Owen Pan
Date: 2024-04-09T19:59:36-07:00
New Revision: 58323de2e5ed0fec81ccfe421488d7fb27ecbe38

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

LOG: [clang-format] Correctly annotate braces in macros (#87953)

Also fix unit tests and reformat polly.

Fixes #86550.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp
polly/lib/Analysis/ScopDetectionDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index af57b1420c6ede..c1f7e2874beb24 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -538,16 +538,6 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 if (Style.Language == FormatStyle::LK_Proto) {
   ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
 } else {
-  // Skip NextTok over preprocessor lines, otherwise we may not
-  // properly diagnose the block as a braced intializer
-  // if the comma separator appears after the pp directive.
-  while (NextTok->is(tok::hash)) {
-ScopedMacroState MacroState(*Line, Tokens, NextTok);
-do {
-  NextTok = Tokens->getNextToken();
-} while (NextTok->isNot(tok::eof));
-  }
-
   // Using OriginalColumn to distinguish between ObjC methods and
   // binary operators is a bit hacky.
   bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
@@ -606,6 +596,16 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 NextTok = Tokens->getNextToken();
 ProbablyBracedList = NextTok->isNot(tok::l_square);
   }
+
+  // Cpp macro definition body that is a nonempty braced list or block:
+  if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
+  !FormatTok->Previous && NextTok->is(tok::eof) &&
+  // A statement can end with only `;` (simple statement), a block
+  // closing brace (compound statement), or `:` (label statement).
+  // If PrevTok is a block opening brace, Tok ends an empty block.
+  !PrevTok->isOneOf(tok::semi, BK_Block, tok::colon)) {
+ProbablyBracedList = true;
+  }
 }
 if (ProbablyBracedList) {
   Tok->setBlockKind(BK_BracedInit);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 71450f433cec88..f312a9e21158a9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1865,6 +1865,13 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("MACRO(co_return##something)");
 
   verifyFormat("#define A x:");
+
+  verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
+  "  { \\\n"
+  "#Bar \\\n"
+  "  }");
+  verifyFormat("#define Foo(Bar) {#Bar}", "#define Foo(Bar) \\\n"
+  "  { #Bar }");
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
@@ -11033,7 +11040,7 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
   verifyFormat("some_templated_type");
 
   verifyFormat("#define FOO(typeName, realClass)   
\\\n"
-   "  { #typeName, foo(new foo(#typeName)) }",
+   "  {#typeName, foo(new foo(#typeName))}",
getLLVMStyleWithColumns(60));
 }
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 5ba5e0fbd16f9e..251e317c7499cf 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1933,14 +1933,20 @@ TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
  "#Bar \\\n"
  "  }");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
-  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
-  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit);
+  EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit);
 
   Tokens = annotate("#define Foo(Bar) \\\n"
 "  { #Bar }");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
-  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
-  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[6], BK_BracedInit);
+  EXPECT_BRACE_KIND(Tokens[9], BK_BracedInit);
+
+  Tokens = annotate("#define FOO(typeName, realClass) \\\n"
+"  {#typeName, foo(new foo(#typeName))}");
+  ASSERT

[clang] [X86_64] fix arg pass error in struct. (PR #86902)

2024-04-09 Thread Eli Friedman via cfe-commits

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


[clang] 000f2b5 - [X86_64] fix arg pass error in struct. (#86902)

2024-04-09 Thread via cfe-commits

Author: Longsheng Mou
Date: 2024-04-09T19:57:35-07:00
New Revision: 000f2b51633d181bf4a5919fc38cf964a83f2091

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

LOG: [X86_64] fix arg pass error in struct. (#86902)

```
typedef long long t67 __attribute__((aligned (4)));
struct s67 {
  int a;
  t67 b;
};
void f67(struct s67 x) {
}
```
When classify:
a: Lo = Integer, Hi = NoClass
b: Lo = Integer, Hi = NoClass
struct S: Lo = Integer, Hi = NoClass

```
define dso_local void @f67(i64 %x.coerce) {
```
In this case, only one i64 register is used when the structure parameter
is transferred, which is obviously incorrect.So we need to treat the
split case specially. fix
https://github.com/llvm/llvm-project/issues/85387.

Added: 


Modified: 
clang/lib/CodeGen/Targets/X86.cpp
clang/test/CodeGen/X86/x86_64-arguments.c

Removed: 




diff  --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index c831777699f627..f04db56db3357d 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -2106,8 +2106,11 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
 postMerge(Size, Lo, Hi);
 return;
   }
+
+  bool IsInMemory =
+  Offset % getContext().getTypeAlign(i->getType().getCanonicalType());
   // Note, skip this test for bit-fields, see below.
-  if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
+  if (!BitField && IsInMemory) {
 Lo = Memory;
 postMerge(Size, Lo, Hi);
 return;

diff  --git a/clang/test/CodeGen/X86/x86_64-arguments.c 
b/clang/test/CodeGen/X86/x86_64-arguments.c
index cf5636cfd518b6..82845f0a2b31fd 100644
--- a/clang/test/CodeGen/X86/x86_64-arguments.c
+++ b/clang/test/CodeGen/X86/x86_64-arguments.c
@@ -533,6 +533,24 @@ typedef float t66 __attribute__((__vector_size__(128), 
__aligned__(128)));
 void f66(t66 a0) {
 }
 
+typedef long long t67 __attribute__((aligned (4)));
+struct s67 {
+  int a;
+  t67 b;
+};
+// CHECK-LABEL: define{{.*}} void @f67(ptr noundef byval(%struct.s67) align 8 
%x)
+void f67(struct s67 x) {
+}
+
+typedef double t68 __attribute__((aligned (4)));
+struct s68 {
+  int a;
+  t68 b;
+};
+// CHECK-LABEL: define{{.*}} void @f68(ptr noundef byval(%struct.s68) align 8 
%x)
+void f68(struct s68 x) {
+}
+
 /// The synthesized __va_list_tag does not have file/line fields.
 // CHECK:  = distinct !DICompositeType(tag: DW_TAG_structure_type, name: 
"__va_list_tag",
 // CHECK-NOT:  file:



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


[clang] [X86_64] fix arg pass error in struct. (PR #86902)

2024-04-09 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

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


[clang] [ARM64EC] Add support for parsing __vectorcall (PR #87725)

2024-04-09 Thread Eli Friedman via cfe-commits

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


[clang] 71097e9 - [ARM64EC] Add support for parsing __vectorcall (#87725)

2024-04-09 Thread via cfe-commits

Author: Eli Friedman
Date: 2024-04-09T19:53:56-07:00
New Revision: 71097e927141e278dd92e847e67f636526510a31

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

LOG: [ARM64EC] Add support for parsing __vectorcall (#87725)

MSVC doesn't support generating __vectorcall calls in Arm64EC mode, but
it does treat it as a distinct type. The Microsoft STL depends on this
functionality. (Not sure if this is intentional.) Add support for
parsing the same way as MSVC, and add some checks to ensure we don't try
to actually generate code.

The error handling in CodeGen is ugly, but I can't think of a better way
to do it.

Added: 
clang/test/CodeGenCXX/arm64ec-vectorcall.cpp

Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 1569b5e04b770a..c8d243a8fb7aea 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -1543,10 +1543,13 @@ WindowsARM64TargetInfo::getBuiltinVaListKind() const {
 TargetInfo::CallingConvCheckResult
 WindowsARM64TargetInfo::checkCallingConvention(CallingConv CC) const {
   switch (CC) {
+  case CC_X86VectorCall:
+if (getTriple().isWindowsArm64EC())
+  return CCCR_OK;
+return CCCR_Ignore;
   case CC_X86StdCall:
   case CC_X86ThisCall:
   case CC_X86FastCall:
-  case CC_X86VectorCall:
 return CCCR_Ignore;
   case CC_C:
   case CC_OpenCLKernel:

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index f12765b826935b..3f5463a9a70e9d 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -5591,6 +5591,12 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
  /*AttrOnCallSite=*/true,
  /*IsThunk=*/false);
 
+  if (CallingConv == llvm::CallingConv::X86_VectorCall &&
+  getTarget().getTriple().isWindowsArm64EC()) {
+CGM.Error(Loc, "__vectorcall calling convention is not currently "
+   "supported");
+  }
+
   if (const FunctionDecl *FD = dyn_cast_or_null(CurFuncDecl)) {
 if (FD->hasAttr())
   // All calls within a strictfp function are marked strictfp

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 00b3bfcaa0bc25..75519be8bba052 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2087,6 +2087,14 @@ void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl 
GD,
   llvm::AttributeList PAL;
   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
  /*AttrOnCallSite=*/false, IsThunk);
+  if (CallingConv == llvm::CallingConv::X86_VectorCall &&
+  getTarget().getTriple().isWindowsArm64EC()) {
+SourceLocation Loc;
+if (const Decl *D = GD.getDecl())
+  Loc = D->getLocation();
+
+Error(Loc, "__vectorcall calling convention is not currently supported");
+  }
   F->setAttributes(PAL);
   F->setCallingConv(static_cast(CallingConv));
 }

diff  --git a/clang/test/CodeGenCXX/arm64ec-vectorcall.cpp 
b/clang/test/CodeGenCXX/arm64ec-vectorcall.cpp
new file mode 100644
index 00..73d2d63835917c
--- /dev/null
+++ b/clang/test/CodeGenCXX/arm64ec-vectorcall.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple arm64ec-windows-msvc -emit-llvm -o - %s -verify
+
+// ARM64EC doesn't support generating __vectorcall calls... but __vectorcall
+// function types need to be distinct from __cdecl function types to support
+// compiling the STL. Make sure we only diagnose constructs that actually
+// require generating code.
+void __vectorcall f1();
+void f2(void __vectorcall p()) {}
+void f2(void p()) {}
+void __vectorcall (*f3)();
+void __vectorcall f4(); // expected-error {{__vectorcall}}
+void __vectorcall f5() { // expected-error {{__vectorcall}}
+  f4(); // expected-error{{__vectorcall}}
+}



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


[clang] [Clang][Sema] set declaration invalid earlier to prevent crash in calculating record layout (PR #87173)

2024-04-09 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/87173

>From 26da477eb3633880734c096b13f89cc0d557745b Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Sun, 31 Mar 2024 09:38:05 +0800
Subject: [PATCH] [Clang][Sema] set declaration invalid earlier to prevent
 crash in calculating record layout

---
 clang/docs/ReleaseNotes.rst  | 2 ++
 clang/include/clang/Sema/Scope.h | 6 ++
 clang/lib/Parse/ParseDeclCXX.cpp | 5 +
 clang/lib/Sema/SemaDecl.cpp  | 7 +++
 clang/test/SemaCXX/PR75221.cpp   | 6 ++
 5 files changed, 26 insertions(+)
 create mode 100644 clang/test/SemaCXX/PR75221.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 28e8ddb3c41c3e..1c541af8657dbb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -504,6 +504,8 @@ Bug Fixes to C++ Support
 - Fix crash when inheriting from a cv-qualified type. Fixes:
   (`#35603 `_)
 - Fix a crash when the using enum declaration uses an anonymous enumeration. 
Fixes (#GH86790).
+- Fix a crash caused by defined struct in a type alias template when the 
structure
+  has fields with dependent type. Fixes (#GH75221).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 099c2739e8603a..1752a25111a775 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -156,6 +156,9 @@ class Scope {
 /// This is the scope of an OpenACC Compute Construct, which restricts
 /// jumping into/out of it.
 OpenACCComputeConstructScope = 0x1000,
+
+/// This is a scope of type alias declaration.
+TypeAliasScope = 0x2000,
   };
 
 private:
@@ -580,6 +583,9 @@ class Scope {
   /// if/switch/while/for statement.
   bool isControlScope() const { return getFlags() & Scope::ControlScope; }
 
+  /// Determine whether this scope is a type alias scope.
+  bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 861a25dc5103c1..270d09f8c9580c 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -799,6 +799,11 @@ Parser::DeclGroupPtrTy Parser::ParseUsingDeclaration(
 ProhibitAttributes(PrefixAttrs);
 
 Decl *DeclFromDeclSpec = nullptr;
+Scope *CurScope = getCurScope();
+if (CurScope)
+  CurScope->setFlags(Scope::ScopeFlags::TypeAliasScope |
+ CurScope->getFlags());
+
 Decl *AD = ParseAliasDeclarationAfterDeclarator(
 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c790dab72dd721..afe25e2a1de4ab 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19622,6 +19622,13 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
   // Okay, we successfully defined 'Record'.
   if (Record) {
 bool Completed = false;
+if (S) {
+  Scope *Parent = S->getParent();
+  if (Parent && Parent->isTypeAliasScope() &&
+  Parent->isTemplateParamScope())
+Record->setInvalidDecl();
+}
+
 if (CXXRecord) {
   if (!CXXRecord->isInvalidDecl()) {
 // Set access bits correctly on the directly-declared conversions.
diff --git a/clang/test/SemaCXX/PR75221.cpp b/clang/test/SemaCXX/PR75221.cpp
new file mode 100644
index 00..b342e347c5606a
--- /dev/null
+++ b/clang/test/SemaCXX/PR75221.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -verify -std=c++11 -fsyntax-only %s
+
+template  using foo = struct foo { // expected-error {{'foo' cannot 
be defined in a type alias template}}
+  T size = 0;
+};
+foo a;

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


[clang] 349327f - [ARM64EC] Make intrin.h include arm64intrin.h.

2024-04-09 Thread Eli Friedman via cfe-commits

Author: Eli Friedman
Date: 2024-04-09T19:37:35-07:00
New Revision: 349327f7e73ab7a314ef08c463dd04fcea623150

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

LOG: [ARM64EC] Make intrin.h include arm64intrin.h.

Fixes compiling windows.h using clang's intrin.h.

Added: 


Modified: 
clang/lib/Headers/intrin.h

Removed: 




diff  --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index e890dcd7feeb8d..7eb6dceaabfaeb 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -26,7 +26,7 @@
 #include 
 #endif
 
-#if defined(__aarch64__)
+#if defined(__aarch64__) || defined(__arm64ec__)
 #include 
 #endif
 



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


[clang] [Clang][Sema] Fix crash when 'this' is used in a dependent class scope function template specialization that instantiates to a static member function (PR #87541)

2024-04-09 Thread Jordan Rupprecht via cfe-commits

rupprecht wrote:

This commit appears to regress an example like this:

```c++
template 
struct Foo {
  template 
  int bar(X x) {
return 0;
  }

  template <>
  int bar(int x) {
return bar(5.0);
  }
};

void call() {
  Foo f;
  f.bar(1);
}
```

Used to compile, now results in an error:
```
PR87541.cpp:10:12: error: call to non-static member function without an object 
argument
   10 | return bar(5.0);
  |^~~
PR87541.cpp:16:5: note: in instantiation of function template specialization 
'Foo::bar' requested here
   16 |   f.bar(1);
  | ^
```

Is that intended?

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


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-04-09 Thread Ben Shi via cfe-commits

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


[clang] [Clang][CodeGen] Start migrating away from assuming the Default AS is 0 (PR #88182)

2024-04-09 Thread John McCall via cfe-commits


@@ -2216,7 +2216,7 @@ static llvm::Value *EmitTypeidFromVTable(CodeGenFunction 
&CGF, const Expr *E,
 }
 
 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
-  llvm::Type *PtrTy = llvm::PointerType::getUnqual(getLLVMContext());
+  llvm::Type *PtrTy = Int8PtrTy;

rjmccall wrote:

Should this be `GlobalsInt8PtrTy`?

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


[clang] 36e2577 - clang/test/APINotes/instancetype.m: Clean the cache dir

2024-04-09 Thread NAKAMURA Takumi via cfe-commits

Author: NAKAMURA Takumi
Date: 2024-04-10T10:14:22+09:00
New Revision: 36e25772ddd049c8c742e55fbd2b3c9aaceb7060

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

LOG: clang/test/APINotes/instancetype.m: Clean the cache dir

It has been incompatible since #87761

Added: 


Modified: 
clang/test/APINotes/instancetype.m

Removed: 




diff  --git a/clang/test/APINotes/instancetype.m 
b/clang/test/APINotes/instancetype.m
index 30339e5386f634..e3c13188ae9f78 100644
--- a/clang/test/APINotes/instancetype.m
+++ b/clang/test/APINotes/instancetype.m
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/ModulesCache -fapinotes-modules -fsyntax-only -I 
%S/Inputs/Headers -verify %s
 
 @import InstancetypeModule;



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


[clang] [clang][dataflow] Propagate locations from result objects to initializers. (PR #87320)

2024-04-09 Thread Gábor Horváth via cfe-commits


@@ -6830,50 +6932,6 @@ TEST(TransferTest, LambdaCaptureThis) {
   });
 }
 
-TEST(TransferTest, DifferentReferenceLocInJoin) {

Xazax-hun wrote:

What is the main reason for removing this test?

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


[clang] [clang][modules] Only compute affecting module maps with implicit search (PR #87849)

2024-04-09 Thread Michael Spencer via cfe-commits

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


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


[clang] [flang] [Flang][AMDGPU] Add rocm-path flag (PR #88190)

2024-04-09 Thread Joseph Huber via cfe-commits


@@ -201,3 +201,24 @@
 ! RUN:  -nogpulibc %s 2>&1 \
 ! RUN:   | FileCheck --check-prefix=NO-LIBC-GPU-AMDGPU %s
 ! NO-LIBC-GPU-AMDGPU-NOT: "-lcgpu-amdgpu"
+
+! RUN:   rm -rf %t/Inputs
+
+! RUN:   not %flang -### -v --target=x86_64-unknown-linux-gnu -fopenmp  \
+! RUN:  --offload-arch=gfx900 \
+! RUN:  --rocm-path=%t/Inputs/rocm %s 2>&1 \

jhuber6 wrote:

Even in that case I don't think `%t` is right, should probably just point it to 
some non-existant path off the current directory `%S`.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -2220,40 +2227,47 @@ class ASTReader
 return Sema::AlignPackInfo::getFromRawEncoding(Raw);
   }
 
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Read a source location from raw form and return it in its
   /// originating module file's source location space.
-  SourceLocation ReadUntranslatedSourceLocation(SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
+  std::pair
+  ReadUntranslatedSourceLocation(RawLocEncoding Raw,
+ LocSeq *Seq = nullptr) const {
 return SourceLocationEncoding::decode(Raw, Seq);
   }
 
   /// Read a source location from raw form.
-  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
-SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
-SourceLocation Loc = ReadUntranslatedSourceLocation(Raw, Seq);
-return TranslateSourceLocation(ModuleFile, Loc);
+  SourceLocation ReadRawSourceLocation(ModuleFile &MF, RawLocEncoding Raw,
+   LocSeq *Seq = nullptr) const {
+if (!MF.ModuleOffsetMap.empty())
+  ReadModuleOffsetMap(MF);
+
+auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
+ModuleFile *ModuleFileHomingLoc =

Bigcheese wrote:

`ModuleFileHomingLoc` sounds a bit confusing to me. Would a better name here be 
`OwningModuleFile`?

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -2220,40 +2227,47 @@ class ASTReader
 return Sema::AlignPackInfo::getFromRawEncoding(Raw);
   }
 
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Read a source location from raw form and return it in its
   /// originating module file's source location space.
-  SourceLocation ReadUntranslatedSourceLocation(SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
+  std::pair
+  ReadUntranslatedSourceLocation(RawLocEncoding Raw,
+ LocSeq *Seq = nullptr) const {
 return SourceLocationEncoding::decode(Raw, Seq);
   }
 
   /// Read a source location from raw form.
-  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
-SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
-SourceLocation Loc = ReadUntranslatedSourceLocation(Raw, Seq);
-return TranslateSourceLocation(ModuleFile, Loc);
+  SourceLocation ReadRawSourceLocation(ModuleFile &MF, RawLocEncoding Raw,
+   LocSeq *Seq = nullptr) const {
+if (!MF.ModuleOffsetMap.empty())
+  ReadModuleOffsetMap(MF);
+
+auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
+ModuleFile *ModuleFileHomingLoc =
+ModuleFileIndex ? ImportedModuleFiles[&MF][ModuleFileIndex - 1] : &MF;

Bigcheese wrote:

Should have at least a bounds check assert on the ModuleFileIndex value here.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -2220,40 +2227,47 @@ class ASTReader
 return Sema::AlignPackInfo::getFromRawEncoding(Raw);
   }
 
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Read a source location from raw form and return it in its
   /// originating module file's source location space.
-  SourceLocation ReadUntranslatedSourceLocation(SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
+  std::pair
+  ReadUntranslatedSourceLocation(RawLocEncoding Raw,
+ LocSeq *Seq = nullptr) const {
 return SourceLocationEncoding::decode(Raw, Seq);
   }
 
   /// Read a source location from raw form.
-  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
-SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
-SourceLocation Loc = ReadUntranslatedSourceLocation(Raw, Seq);
-return TranslateSourceLocation(ModuleFile, Loc);
+  SourceLocation ReadRawSourceLocation(ModuleFile &MF, RawLocEncoding Raw,
+   LocSeq *Seq = nullptr) const {
+if (!MF.ModuleOffsetMap.empty())
+  ReadModuleOffsetMap(MF);
+
+auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
+ModuleFile *ModuleFileHomingLoc =
+ModuleFileIndex ? ImportedModuleFiles[&MF][ModuleFileIndex - 1] : &MF;
+return TranslateSourceLocation(*ModuleFileHomingLoc, Loc);
   }
 
   /// Translate a source location from another module file's source
   /// location space into ours.
   SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
  SourceLocation Loc) const {
-if (!ModuleFile.ModuleOffsetMap.empty())
-  ReadModuleOffsetMap(ModuleFile);
-assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
-   ModuleFile.SLocRemap.end() &&
-   "Cannot find offset to remap.");
-SourceLocation::IntTy Remap =
-ModuleFile.SLocRemap.find(Loc.getOffset())->second;
-return Loc.getLocWithOffset(Remap);
+if (Loc.isInvalid())
+  return Loc;
+
+// It implies that the Loc is already translated.
+if (SourceMgr.isLoadedSourceLocation(Loc))
+  return Loc;
+
+return Loc.getLocWithOffset(ModuleFile.SLocEntryBaseOffset - 2);

Bigcheese wrote:

Why the -2 here?

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -149,14 +157,44 @@ class SourceLocationSequence::State {
   operator SourceLocationSequence *() { return &Seq; }
 };
 
-inline uint64_t SourceLocationEncoding::encode(SourceLocation Loc,
-   SourceLocationSequence *Seq) {
-  return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+inline SourceLocationEncoding::RawLocEncoding
+SourceLocationEncoding::encode(SourceLocation Loc, UIntTy BaseOffset,
+   unsigned BaseModuleFileIndex,
+   SourceLocationSequence *Seq) {
+  // If the source location is a local source location, we can try to optimize
+  // the similar sequences to only record the differences.
+  if (!BaseOffset)
+return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+
+  if (Loc.isInvalid())
+return 0;
+  
+  // Otherwise, the higher bits are used to store the module file index,
+  // so it is meaningless to optimize the source locations into small
+  // integers. Let's try to always use the raw encodings.
+  assert(Loc.getOffset() >= BaseOffset);
+  Loc = Loc.getLocWithOffset(-BaseOffset);
+  RawLocEncoding Encoded = encodeRaw(Loc.getRawEncoding());
+  assert(Encoded < ((RawLocEncoding)1 << 32));
+
+  assert(BaseModuleFileIndex < ((RawLocEncoding)1 << 32));
+  Encoded |= (RawLocEncoding)BaseModuleFileIndex << 32;

Bigcheese wrote:

Were you going to change this to only reserve 16 bits for module index?

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -4078,8 +4065,8 @@ void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
   return;

Bigcheese wrote:

There's no more SourceLocation remap so I believe this error message is wrong 
now.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits


@@ -149,14 +157,44 @@ class SourceLocationSequence::State {
   operator SourceLocationSequence *() { return &Seq; }
 };
 
-inline uint64_t SourceLocationEncoding::encode(SourceLocation Loc,
-   SourceLocationSequence *Seq) {
-  return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+inline SourceLocationEncoding::RawLocEncoding
+SourceLocationEncoding::encode(SourceLocation Loc, UIntTy BaseOffset,
+   unsigned BaseModuleFileIndex,
+   SourceLocationSequence *Seq) {
+  // If the source location is a local source location, we can try to optimize
+  // the similar sequences to only record the differences.
+  if (!BaseOffset)
+return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+
+  if (Loc.isInvalid())
+return 0;
+  
+  // Otherwise, the higher bits are used to store the module file index,
+  // so it is meaningless to optimize the source locations into small
+  // integers. Let's try to always use the raw encodings.
+  assert(Loc.getOffset() >= BaseOffset);
+  Loc = Loc.getLocWithOffset(-BaseOffset);
+  RawLocEncoding Encoded = encodeRaw(Loc.getRawEncoding());
+  assert(Encoded < ((RawLocEncoding)1 << 32));
+
+  assert(BaseModuleFileIndex < ((RawLocEncoding)1 << 32));
+  Encoded |= (RawLocEncoding)BaseModuleFileIndex << 32;
+  return Encoded;
 }
-inline SourceLocation
-SourceLocationEncoding::decode(uint64_t Encoded, SourceLocationSequence *Seq) {
-  return Seq ? Seq->decode(Encoded)
- : SourceLocation::getFromRawEncoding(decodeRaw(Encoded));
+inline std::pair
+SourceLocationEncoding::decode(RawLocEncoding Encoded,
+   SourceLocationSequence *Seq) {
+  unsigned ModuleFileIndex = Encoded >> 32;
+
+  if (!ModuleFileIndex)
+return {Seq ? Seq->decode(Encoded)
+ : SourceLocation::getFromRawEncoding(decodeRaw(Encoded)),
+ModuleFileIndex};
+
+  Encoded &= ((RawLocEncoding)1 << 33) - 1;

Bigcheese wrote:

We have `maskTrailingOnes(32)` which is a bit clearer than raw 
bit math.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese commented:

I have a few minor comments on the patch. I want to do some additional perf 
testing on module scanning perf because I'm a bit concerned about the cost of 
`ASTWriter::getRawSourceLocationEncoding`.

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

2024-04-09 Thread Jun Wang via cfe-commits

jwanggit86 wrote:

@jayfoad Do you have any more comments?

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Kees Cook via cfe-commits

kees wrote:

This now passes my behavioral testing suite for wrapping; yay! (The earlier 
version didn't cover truncate, so this is very nice now.)

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


[clang] [clang-cl] [Driver] Fix clang-cl driver supported colon options (PR #88216)

2024-04-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-driver

@llvm/pr-subscribers-clang

Author: Max Winkler (MaxEW707)


Changes

Tested locally against msvc 1939.
MSVC supports the colon form of various options that take a path even though 
that isn't documented for all options on MSDN.
I added the colon form for all supported msvc options that clang-cl does not 
intentionally ignore due to being unsupported.

I also fixed the existing colon options by ensure we use `JoinedOrSeparate`. 
`/F[x]` argument must used within the same command line argument. However, 
`/F[x]:` arguments are allowed to span a command line argument. The following 
is valid `/F[x]: path` which is 2 separate command line arguments.
You can see this documented here, 
https://learn.microsoft.com/en-us/cpp/build/reference/fo-object-file-name?view=msvc-170,
 where it says `/Fo:[ ]"pathname"`.
This behaviour works for all colon options that take a path and I tested it 
locally against msvc 1939 for all the option changes in this PR.

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


3 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+4-2) 
- (modified) clang/test/Driver/cl-outputs.c (+4) 
- (modified) clang/test/Driver/cl-pch.cpp (+6) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f745e573eb2686..bc7041c7830984 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8331,14 +8331,15 @@ def _SLASH_FI : CLJoinedOrSeparate<"FI">,
 def _SLASH_Fe : CLJoined<"Fe">,
   HelpText<"Set output executable file name">,
   MetaVarName<"">;
-def _SLASH_Fe_COLON : CLJoined<"Fe:">, Alias<_SLASH_Fe>;
+def _SLASH_Fe_COLON : CLJoinedOrSeparate<"Fe:">, Alias<_SLASH_Fe>;
 def _SLASH_Fi : CLCompileJoined<"Fi">,
   HelpText<"Set preprocess output file name (with /P)">,
   MetaVarName<"">;
+def _SLASH_Fi_COLON : CLJoinedOrSeparate<"Fi:">, Alias<_SLASH_Fi>;
 def _SLASH_Fo : CLCompileJoined<"Fo">,
   HelpText<"Set output object file (with /c)">,
   MetaVarName<"">;
-def _SLASH_Fo_COLON : CLCompileJoined<"Fo:">, Alias<_SLASH_Fo>;
+def _SLASH_Fo_COLON : CLCompileJoinedOrSeparate<"Fo:">, Alias<_SLASH_Fo>;
 def _SLASH_guard : CLJoined<"guard:">,
   HelpText<"Enable Control Flow Guard with /guard:cf, or only the table with 
/guard:cf,nochecks. "
"Enable EH Continuation Guard with /guard:ehcont">;
@@ -8433,6 +8434,7 @@ def _SLASH_Zc_dllexportInlines_ : 
CLFlag<"Zc:dllexportInlines-">,
   HelpText<"Do not dllexport/dllimport inline member functions of 
dllexport/import classes">;
 def _SLASH_Fp : CLJoined<"Fp">,
   HelpText<"Set pch file name (with /Yc and /Yu)">, MetaVarName<"">;
+def _SLASH_Fp_COLON : CLJoinedOrSeparate<"Fp:">, Alias<_SLASH_Fp>;
 
 def _SLASH_Gd : CLFlag<"Gd">,
   HelpText<"Set __cdecl as a default calling convention">;
diff --git a/clang/test/Driver/cl-outputs.c b/clang/test/Driver/cl-outputs.c
index 4d58f0fb548b57..4298657ac49f5c 100644
--- a/clang/test/Driver/cl-outputs.c
+++ b/clang/test/Driver/cl-outputs.c
@@ -118,6 +118,7 @@
 
 // RUN: %clang_cl /Fefoo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT %s
 // RUN: %clang_cl /Fe:foo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT 
%s
+// RUN: %clang_cl /Fe: foo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT 
%s
 // FeEXT: "-out:foo.ext"
 
 // RUN: %clang_cl /LD /Fefoo.ext -### -- %s 2>&1 | FileCheck 
-check-prefix=FeEXTDLL %s
@@ -270,6 +271,8 @@
 // P: "-o" "cl-outputs.i"
 
 // RUN: %clang_cl /P /Fifoo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
+// RUN: %clang_cl /P /Fi:foo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
+// RUN: %clang_cl /P /Fi: foo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
 // Fi1: "-E"
 // Fi1: "-o" "foo.i"
 
@@ -302,6 +305,7 @@
 // RELATIVE_OBJPATH1: "-object-file-name=a.obj"
 
 // RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fo:a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH1_COLON %s
+// RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fo: a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH1_COLON %s
 // RELATIVE_OBJPATH1_COLON: "-object-file-name=a.obj"
 
 // RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fofoo/a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH2 %s
diff --git a/clang/test/Driver/cl-pch.cpp b/clang/test/Driver/cl-pch.cpp
index d09b177eb617de..cc4fc435a61c20 100644
--- a/clang/test/Driver/cl-pch.cpp
+++ b/clang/test/Driver/cl-pch.cpp
@@ -99,6 +99,12 @@
 // /Yu /Fpout.pch => out.pch is filename
 // RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fpout.pch /c -### -- %s 
2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-YUFP1 %s
+// /Yu /Fp:out.pch => out.pch is filename
+// RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fp:out.pch /c -### -- %s 
2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-YUFP1 %s
+// /Yu /Fp: out.pch => out.pch is filename
+// RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fp: out.pch /c -### -- %s 
2>

[clang] [clang-cl] [Driver] Fix clang-cl driver supported colon options (PR #88216)

2024-04-09 Thread Max Winkler via cfe-commits

MaxEW707 wrote:

CC @rnk 

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


[clang] [clang-cl] [Driver] Fix clang-cl driver supported colon options (PR #88216)

2024-04-09 Thread Max Winkler via cfe-commits

https://github.com/MaxEW707 created 
https://github.com/llvm/llvm-project/pull/88216

Tested locally against msvc 1939.
MSVC supports the colon form of various options that take a path even though 
that isn't documented for all options on MSDN.
I added the colon form for all supported msvc options that clang-cl does not 
intentionally ignore due to being unsupported.

I also fixed the existing colon options by ensure we use `JoinedOrSeparate`. 
`/F[x]` argument must used within the same command line argument. However, 
`/F[x]:` arguments are allowed to span a command line argument. The following 
is valid `/F[x]: path` which is 2 separate command line arguments.
You can see this documented here, 
https://learn.microsoft.com/en-us/cpp/build/reference/fo-object-file-name?view=msvc-170,
 where it says `/Fo:[ ]"pathname"`.
This behaviour works for all colon options that take a path and I tested it 
locally against msvc 1939 for all the option changes in this PR.

>From 22c37dbc2d9b18f5ea18b525c37f4ba5771365f6 Mon Sep 17 00:00:00 2001
From: MaxEW707 
Date: Tue, 9 Apr 2024 19:27:44 -0400
Subject: [PATCH] Fix clang-cl driver supported colon options

---
 clang/include/clang/Driver/Options.td | 6 --
 clang/test/Driver/cl-outputs.c| 4 
 clang/test/Driver/cl-pch.cpp  | 6 ++
 3 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f745e573eb2686..bc7041c7830984 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8331,14 +8331,15 @@ def _SLASH_FI : CLJoinedOrSeparate<"FI">,
 def _SLASH_Fe : CLJoined<"Fe">,
   HelpText<"Set output executable file name">,
   MetaVarName<"">;
-def _SLASH_Fe_COLON : CLJoined<"Fe:">, Alias<_SLASH_Fe>;
+def _SLASH_Fe_COLON : CLJoinedOrSeparate<"Fe:">, Alias<_SLASH_Fe>;
 def _SLASH_Fi : CLCompileJoined<"Fi">,
   HelpText<"Set preprocess output file name (with /P)">,
   MetaVarName<"">;
+def _SLASH_Fi_COLON : CLJoinedOrSeparate<"Fi:">, Alias<_SLASH_Fi>;
 def _SLASH_Fo : CLCompileJoined<"Fo">,
   HelpText<"Set output object file (with /c)">,
   MetaVarName<"">;
-def _SLASH_Fo_COLON : CLCompileJoined<"Fo:">, Alias<_SLASH_Fo>;
+def _SLASH_Fo_COLON : CLCompileJoinedOrSeparate<"Fo:">, Alias<_SLASH_Fo>;
 def _SLASH_guard : CLJoined<"guard:">,
   HelpText<"Enable Control Flow Guard with /guard:cf, or only the table with 
/guard:cf,nochecks. "
"Enable EH Continuation Guard with /guard:ehcont">;
@@ -8433,6 +8434,7 @@ def _SLASH_Zc_dllexportInlines_ : 
CLFlag<"Zc:dllexportInlines-">,
   HelpText<"Do not dllexport/dllimport inline member functions of 
dllexport/import classes">;
 def _SLASH_Fp : CLJoined<"Fp">,
   HelpText<"Set pch file name (with /Yc and /Yu)">, MetaVarName<"">;
+def _SLASH_Fp_COLON : CLJoinedOrSeparate<"Fp:">, Alias<_SLASH_Fp>;
 
 def _SLASH_Gd : CLFlag<"Gd">,
   HelpText<"Set __cdecl as a default calling convention">;
diff --git a/clang/test/Driver/cl-outputs.c b/clang/test/Driver/cl-outputs.c
index 4d58f0fb548b57..4298657ac49f5c 100644
--- a/clang/test/Driver/cl-outputs.c
+++ b/clang/test/Driver/cl-outputs.c
@@ -118,6 +118,7 @@
 
 // RUN: %clang_cl /Fefoo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT %s
 // RUN: %clang_cl /Fe:foo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT 
%s
+// RUN: %clang_cl /Fe: foo.ext -### -- %s 2>&1 | FileCheck -check-prefix=FeEXT 
%s
 // FeEXT: "-out:foo.ext"
 
 // RUN: %clang_cl /LD /Fefoo.ext -### -- %s 2>&1 | FileCheck 
-check-prefix=FeEXTDLL %s
@@ -270,6 +271,8 @@
 // P: "-o" "cl-outputs.i"
 
 // RUN: %clang_cl /P /Fifoo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
+// RUN: %clang_cl /P /Fi:foo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
+// RUN: %clang_cl /P /Fi: foo -### -- %s 2>&1 | FileCheck -check-prefix=Fi1 %s
 // Fi1: "-E"
 // Fi1: "-o" "foo.i"
 
@@ -302,6 +305,7 @@
 // RELATIVE_OBJPATH1: "-object-file-name=a.obj"
 
 // RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fo:a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH1_COLON %s
+// RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fo: a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH1_COLON %s
 // RELATIVE_OBJPATH1_COLON: "-object-file-name=a.obj"
 
 // RUN: %clang_cl -fdebug-compilation-dir=. /Z7 /Fofoo/a.obj -### -- %s 2>&1 | 
FileCheck -check-prefix=RELATIVE_OBJPATH2 %s
diff --git a/clang/test/Driver/cl-pch.cpp b/clang/test/Driver/cl-pch.cpp
index d09b177eb617de..cc4fc435a61c20 100644
--- a/clang/test/Driver/cl-pch.cpp
+++ b/clang/test/Driver/cl-pch.cpp
@@ -99,6 +99,12 @@
 // /Yu /Fpout.pch => out.pch is filename
 // RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fpout.pch /c -### -- %s 
2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-YUFP1 %s
+// /Yu /Fp:out.pch => out.pch is filename
+// RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fp:out.pch /c -### -- %s 
2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-YUFP1 %s
+// /Yu /Fp: out.pch => out.pch is f

[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits

jansvoboda11 wrote:

I left a couple of initial comments. With the 64-bit `SourceLocation` aspect of 
this change solved and with just 2% size increase, I think this approach makes 
sense. Could you share the rest of the "no transitive change" patches, or at 
least their outline? I'm curious what else goes into making that work.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -696,7 +696,7 @@ class ASTReader
   /// Mapping from global submodule IDs to the module file in which the
   /// submodule resides along with the offset that should be added to the
   /// global submodule ID to produce a local ID.
-  GlobalSubmoduleMapType GlobalSubmoduleMap;
+  mutable GlobalSubmoduleMapType GlobalSubmoduleMap;

jansvoboda11 wrote:

Is `mutable` necessary here?

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


[clang] [clang][CodeGen][OpenMP] Fix casting of atomic update of ptr types (PR #88215)

2024-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Mike Rice (mikerice1969)


Changes

In 4d5e834c5b7f0d90a6d543e182df602f6bc8, casts were removed for pointers 
but one case was missed. Add missing check.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGAtomic.cpp (+5-1) 
- (modified) clang/test/OpenMP/atomic_update_codegen.cpp (+11) 


``diff
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index d35ce0409d7232..07452b18a85ea4 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -1806,7 +1806,11 @@ void AtomicInfo::EmitAtomicUpdateOp(
  /*NumReservedValues=*/2);
   PHI->addIncoming(OldVal, CurBB);
   Address NewAtomicAddr = CreateTempAlloca();
-  Address NewAtomicIntAddr = castToAtomicIntPointer(NewAtomicAddr);
+  Address NewAtomicIntAddr =
+  shouldCastToInt(NewAtomicAddr.getElementType(), /*CmpXchg=*/true)
+  ? castToAtomicIntPointer(NewAtomicAddr)
+  : NewAtomicAddr;
+
   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
   requiresMemSetZero(getAtomicAddress().getElementType())) {
 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
diff --git a/clang/test/OpenMP/atomic_update_codegen.cpp 
b/clang/test/OpenMP/atomic_update_codegen.cpp
index ce0765118922a1..fe745590a9f919 100644
--- a/clang/test/OpenMP/atomic_update_codegen.cpp
+++ b/clang/test/OpenMP/atomic_update_codegen.cpp
@@ -27,6 +27,7 @@ long double ldv, ldx;
 _Complex int civ, cix;
 _Complex float cfv, cfx;
 _Complex double cdv, cdx;
+char *cpx;
 
 typedef int int4 __attribute__((__vector_size__(16)));
 int4 int4x;
@@ -851,6 +852,16 @@ int main(void) {
 // CHECK: call{{.*}} @__kmpc_flush(
 #pragma omp atomic seq_cst
   rix = dv / rix;
+
+// CHECK: [[LD_CPX:%.+]] = load atomic ptr, ptr @cpx monotonic
+// CHECK: br label %[[CONT:.+]]
+// CHECK: [[CONT]]
+// CHECK: [[PHI:%.+]] = phi ptr
+// CHECK: [[RES:%.+]] = cmpxchg ptr @cpx,
+// CHECK: br i1 %{{.+}}, label %[[EXIT:.+]], label %[[CONT]]
+  #pragma omp atomic update
+  cpx += 1;
+
   return 0;
 }
 

``




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


[clang] [clang][CodeGen][OpenMP] Fix casting of atomic update of ptr types (PR #88215)

2024-04-09 Thread Mike Rice via cfe-commits

mikerice1969 wrote:

See: https://godbolt.org/z/av7axb9as

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


[clang] [clang][CodeGen][OpenMP] Fix casting of atomic update of ptr types (PR #88215)

2024-04-09 Thread Mike Rice via cfe-commits

https://github.com/mikerice1969 created 
https://github.com/llvm/llvm-project/pull/88215

In 4d5e834c5b7f0d90a6d543e182df602f6bc8, casts were removed for pointers 
but one case was missed. Add missing check.

>From b1eaa2f5b13db4d63390a0358ad0f9b13cbe927f Mon Sep 17 00:00:00 2001
From: Mike Rice 
Date: Tue, 9 Apr 2024 16:11:30 -0700
Subject: [PATCH] [clang][CodeGen][OpenMP] Fix casting of atomic update of ptr
 types

In 4d5e834c5b7f0d90a6d543e182df602f6bc8, casts were removed for
pointers but one case was missed. Add missing check.
---
 clang/lib/CodeGen/CGAtomic.cpp  |  6 +-
 clang/test/OpenMP/atomic_update_codegen.cpp | 11 +++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index d35ce0409d7232..07452b18a85ea4 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -1806,7 +1806,11 @@ void AtomicInfo::EmitAtomicUpdateOp(
  /*NumReservedValues=*/2);
   PHI->addIncoming(OldVal, CurBB);
   Address NewAtomicAddr = CreateTempAlloca();
-  Address NewAtomicIntAddr = castToAtomicIntPointer(NewAtomicAddr);
+  Address NewAtomicIntAddr =
+  shouldCastToInt(NewAtomicAddr.getElementType(), /*CmpXchg=*/true)
+  ? castToAtomicIntPointer(NewAtomicAddr)
+  : NewAtomicAddr;
+
   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
   requiresMemSetZero(getAtomicAddress().getElementType())) {
 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
diff --git a/clang/test/OpenMP/atomic_update_codegen.cpp 
b/clang/test/OpenMP/atomic_update_codegen.cpp
index ce0765118922a1..fe745590a9f919 100644
--- a/clang/test/OpenMP/atomic_update_codegen.cpp
+++ b/clang/test/OpenMP/atomic_update_codegen.cpp
@@ -27,6 +27,7 @@ long double ldv, ldx;
 _Complex int civ, cix;
 _Complex float cfv, cfx;
 _Complex double cdv, cdx;
+char *cpx;
 
 typedef int int4 __attribute__((__vector_size__(16)));
 int4 int4x;
@@ -851,6 +852,16 @@ int main(void) {
 // CHECK: call{{.*}} @__kmpc_flush(
 #pragma omp atomic seq_cst
   rix = dv / rix;
+
+// CHECK: [[LD_CPX:%.+]] = load atomic ptr, ptr @cpx monotonic
+// CHECK: br label %[[CONT:.+]]
+// CHECK: [[CONT]]
+// CHECK: [[PHI:%.+]] = phi ptr
+// CHECK: [[RES:%.+]] = cmpxchg ptr @cpx,
+// CHECK: br i1 %{{.+}}, label %[[EXIT:.+]], label %[[CONT]]
+  #pragma omp atomic update
+  cpx += 1;
+
   return 0;
 }
 

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -2220,40 +2227,47 @@ class ASTReader
 return Sema::AlignPackInfo::getFromRawEncoding(Raw);
   }
 
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Read a source location from raw form and return it in its
   /// originating module file's source location space.
-  SourceLocation ReadUntranslatedSourceLocation(SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
+  std::pair
+  ReadUntranslatedSourceLocation(RawLocEncoding Raw,
+ LocSeq *Seq = nullptr) const {
 return SourceLocationEncoding::decode(Raw, Seq);
   }
 
   /// Read a source location from raw form.
-  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
-SourceLocation::UIntTy Raw,
-LocSeq *Seq = nullptr) const {
-SourceLocation Loc = ReadUntranslatedSourceLocation(Raw, Seq);
-return TranslateSourceLocation(ModuleFile, Loc);
+  SourceLocation ReadRawSourceLocation(ModuleFile &MF, RawLocEncoding Raw,

jansvoboda11 wrote:

Can we undo the rename? This is named after the return type (what the client 
expects) not after the argument (the raw location). Also, `ASTReader` will 
never read a non-"raw" source location.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -5574,10 +5577,34 @@ void ASTWriter::AddFileID(FileID FID, RecordDataImpl 
&Record) {
   Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
 }
 
+SourceLocationEncoding::RawLocEncoding
+ASTWriter::getRawSourceLocationEncoding(SourceLocation Loc, LocSeq *Seq) {
+  unsigned BaseOffset = 0;
+  unsigned ModuleFileIndex = 0;
+
+  // See SourceLocationEncoding.h for the encoding details.
+  if (Context->getSourceManager().isLoadedSourceLocation(Loc) &&
+  Loc.isValid()) {
+assert(getChain());
+auto SLocMapI = getChain()->GlobalSLocOffsetMap.find(
+SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
+assert(SLocMapI != getChain()->GlobalSLocOffsetMap.end() &&
+   "Corrupted global sloc offset map");
+ModuleFile *F = SLocMapI->second;
+BaseOffset = F->SLocEntryBaseOffset - 2;
+// 0 means the location is not loaded. So we need to add 1 to the index to
+// make it clear.
+ModuleFileIndex = F->Index + 1;
+assert(&getChain()->getModuleManager()[F->Index] == F);

jansvoboda11 wrote:

This seems a bit tautological.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -942,6 +942,12 @@ class ASTReader
   /// Sema tracks these to emit deferred diags.
   llvm::SmallSetVector DeclsToCheckForDeferredDiags;
 
+  /// The module files imported by different module files. Indirectly imported
+  /// module files are included too. The information comes from
+  /// ReadModuleOffsetMap(ModuleFile&).
+  mutable llvm::DenseMap>
+  ImportedModuleFiles;

jansvoboda11 wrote:

Why does this live in `ASTReader`? If we moved it to `ModuleFile`, we could 
remove `mutable` and the map lookups.

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -149,14 +157,44 @@ class SourceLocationSequence::State {
   operator SourceLocationSequence *() { return &Seq; }
 };
 
-inline uint64_t SourceLocationEncoding::encode(SourceLocation Loc,
-   SourceLocationSequence *Seq) {
-  return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+inline SourceLocationEncoding::RawLocEncoding
+SourceLocationEncoding::encode(SourceLocation Loc, UIntTy BaseOffset,
+   unsigned BaseModuleFileIndex,
+   SourceLocationSequence *Seq) {
+  // If the source location is a local source location, we can try to optimize
+  // the similar sequences to only record the differences.
+  if (!BaseOffset)
+return Seq ? Seq->encode(Loc) : encodeRaw(Loc.getRawEncoding());
+
+  if (Loc.isInvalid())
+return 0;
+  
+  // Otherwise, the higher bits are used to store the module file index,
+  // so it is meaningless to optimize the source locations into small
+  // integers. Let's try to always use the raw encodings.
+  assert(Loc.getOffset() >= BaseOffset);
+  Loc = Loc.getLocWithOffset(-BaseOffset);
+  RawLocEncoding Encoded = encodeRaw(Loc.getRawEncoding());
+  assert(Encoded < ((RawLocEncoding)1 << 32));

jansvoboda11 wrote:

My compiler says:
```
warning: result of comparison of constant 4294967296 with expression of type 
'unsigned int' is always true [-Wtautological-constant-out-of-range-compare]
```

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


[clang] [clang-tools-extra] [clang][modules] Do not resolve `HeaderFileInfo` externally in `ASTWriter` (PR #87848)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -409,7 +409,7 @@ class SymbolCollector::HeaderFileURICache {
 // 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))

jansvoboda11 wrote:

Might be, I'm not sure. CC @DavidGoldman

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


[clang] [Clang][CodeGen] Start migrating away from assuming the Default AS is 0 (PR #88182)

2024-04-09 Thread Alex Voicu via cfe-commits


@@ -4551,6 +4554,7 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
 
   llvm::Function *F =
   llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
+ getDataLayout().getProgramAddressSpace(),

AlexVlx wrote:

Whoops, that's a mistake, apologies. Fixed.

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


[clang] [Clang][CodeGen] Start migrating away from assuming the Default AS is 0 (PR #88182)

2024-04-09 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/88182

>From 426e74cabb003eb5dc83adf347a5800d49bc87b7 Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Mon, 18 Mar 2024 11:49:12 +
Subject: [PATCH 1/7] Start migrating away from the embedded assumption that
 the default AS **must** be 0.

---
 clang/lib/CodeGen/CGExprCXX.cpp  |  2 +-
 clang/lib/CodeGen/CodeGenModule.cpp  | 10 ++
 clang/lib/CodeGen/CodeGenTypeCache.h |  2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp
index 2adbef6d55122c..b9c920a81d79c9 100644
--- a/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/clang/lib/CodeGen/CGExprCXX.cpp
@@ -,7 +,7 @@ static llvm::Value *EmitTypeidFromVTable(CodeGenFunction 
&CGF, const Expr *E,
 }
 
 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
-  llvm::Type *PtrTy = llvm::PointerType::getUnqual(getLLVMContext());
+  llvm::Type *PtrTy = Int8PtrTy;
   LangAS GlobAS = CGM.GetGlobalVarAddressSpace(nullptr);
 
   auto MaybeASCast = [=](auto &&TypeInfo) {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8ceecff28cbc63..7dd14d32aa2d03 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -364,7 +364,8 @@ CodeGenModule::CodeGenModule(ASTContext &C,
   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
   IntPtrTy = llvm::IntegerType::get(LLVMContext,
 C.getTargetInfo().getMaxPointerWidth());
-  Int8PtrTy = llvm::PointerType::get(LLVMContext, 0);
+  Int8PtrTy = llvm::PointerType::get(
+  LLVMContext, C.getTargetInfo().getTargetAddressSpace(LangAS::Default));
   const llvm::DataLayout &DL = M.getDataLayout();
   AllocaInt8PtrTy =
   llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
@@ -4512,9 +4513,10 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
 IsIncompleteFunction = true;
   }
 
-  llvm::Function *F =
-  llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
- Entry ? StringRef() : MangledName, &getModule());
+  llvm::Function *F = llvm::Function::Create(
+  FTy, llvm::Function::ExternalLinkage,
+  getDataLayout().getProgramAddressSpace(),
+  Entry ? StringRef() : MangledName, &getModule());
 
   // Store the declaration associated with this function so it is potentially
   // updated by further declarations or definitions and emitted at the end.
diff --git a/clang/lib/CodeGen/CodeGenTypeCache.h 
b/clang/lib/CodeGen/CodeGenTypeCache.h
index 083d69214fb3c2..e273ebe3b060f2 100644
--- a/clang/lib/CodeGen/CodeGenTypeCache.h
+++ b/clang/lib/CodeGen/CodeGenTypeCache.h
@@ -51,7 +51,7 @@ struct CodeGenTypeCache {
 llvm::IntegerType *PtrDiffTy;
   };
 
-  /// void*, void** in address space 0
+  /// void*, void** in the target's default address space (often 0)
   union {
 llvm::PointerType *UnqualPtrTy;
 llvm::PointerType *VoidPtrTy;

>From 74ae6f52a5f84f8fc92135df3ff93a4a89b914ed Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Mon, 25 Mar 2024 10:55:22 +0200
Subject: [PATCH 2/7] Make querying the Global AS more robust, add 1 new test
 (WiP).

---
 clang/lib/CodeGen/CodeGenModule.cpp   | 10 ---
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |  4 ++-
 ...x11-with-nonzero-default-address-space.cpp | 29 +++
 3 files changed, 38 insertions(+), 5 deletions(-)
 create mode 100644 
clang/test/CodeGenCXX/typeid-cxx11-with-nonzero-default-address-space.cpp

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 63d54f9b1c0b60..39ccd40bf1adbb 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -371,8 +371,8 @@ CodeGenModule::CodeGenModule(ASTContext &C,
   const llvm::DataLayout &DL = M.getDataLayout();
   AllocaInt8PtrTy =
   llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
-  GlobalsInt8PtrTy =
-  llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
+  GlobalsInt8PtrTy = llvm::PointerType::get(
+  LLVMContext, C.getTargetAddressSpace(GetGlobalVarAddressSpace(nullptr)));
   ConstGlobalsPtrTy = llvm::PointerType::get(
   LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
@@ -5018,7 +5018,9 @@ llvm::GlobalVariable 
*CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
 
   // Create a new variable.
   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
-Linkage, nullptr, Name);
+Linkage, nullptr, Name, nullptr,
+llvm::GlobalValue::NotThreadLocal,
+GlobalsInt8PtrTy->getAddressSpace());
 
   if (OldGV) {
 // Replace occurrences of the old variable if needed.
@@ -5133,7 +5135,7 @@ La

[clang] [Clang][CodeGen] Start migrating away from assuming the Default AS is 0 (PR #88182)

2024-04-09 Thread Alex Voicu via cfe-commits

AlexVlx wrote:

> > I'm not quite sure how to parse this comment, could you explain what you 
> > have in mind here? The problem is precisely that the FE assumes 0 is fine / 
> > picks it by default, which ends up into dangerzones when e.g. a target 
> > happened to use 0 to point to private (stack). I feel as if I'm missing the 
> > core of your comment though, so apologies in advance.
> 
> I'm just saying that I don't think it makes any sense to add a concept of a 
> default AS to LLVM. The "default" AS is a frontend-level concept about how to 
> interpret source-level types , not an LLVM-level concept. LLVM would only 
> need a default AS if it were inventing a memory allocation/operation from 
> whole cloth, which is generally not something LLVM should be doing except in 
> local memory; the only legitimate counter-example I can think of would be 
> something like materializing a constant into constant global memory, in which 
> case LLVM needs to assign the new constant an AS.

Thinking about this a bit more, is it not the case that today, we do have a _de 
facto_ default AS in LLVM, if only by virtue of the fact that an unqualified 
ptr ends up as a ptr to AS 0; unqualified ptrs are used all over the place / 
the FE is pretty liberal in their employ? So, it's possible that a large part 
of this pain is that we say stuff like the below:
```cpp
/// void*, void** in address space 0
 union {
llvm::PointerType *UnqualPtrTy;
```

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


[clang] [Modules] No transitive source location change (PR #86912)

2024-04-09 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese commented:

I think the general approach makes sense. I'll take a closer look at the 
specific changes.

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

https://github.com/JustinStitt updated 
https://github.com/llvm/llvm-project/pull/86618

>From 10ee32826fc2acb6bd993c88bdb7142360b6f263 Mon Sep 17 00:00:00 2001
From: Justin Stitt 
Date: Tue, 5 Mar 2024 03:14:49 +
Subject: [PATCH 1/4] implement wraps attribute

Signed-off-by: Justin Stitt 
---
 clang/docs/ReleaseNotes.rst   |  9 +++
 clang/include/clang/AST/Expr.h|  3 +
 clang/include/clang/Basic/Attr.td |  6 ++
 clang/include/clang/Basic/AttrDocs.td | 66 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +
 clang/include/clang/Sema/Sema.h   |  4 ++
 clang/lib/AST/Expr.cpp| 19 ++
 clang/lib/AST/ExprConstant.cpp|  6 +-
 clang/lib/AST/TypePrinter.cpp |  3 +
 clang/lib/CodeGen/CGExprScalar.cpp| 40 +--
 clang/lib/Sema/SemaDeclAttr.cpp   | 12 +++-
 clang/lib/Sema/SemaType.cpp   | 15 +
 clang/test/CodeGen/integer-overflow.c | 56 
 clang/test/CodeGen/unsigned-overflow.c| 63 +++---
 clang/test/Sema/attr-wraps.c  |  9 +++
 15 files changed, 298 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/Sema/attr-wraps.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f96cebbde3d825..cb02af7e948989 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -282,6 +282,15 @@ Attribute Changes in Clang
   This allows the ``_Nullable`` and ``_Nonnull`` family of type attributes to
   apply to this class.
 
+- Introduced ``__attribute((wraps))__`` which can be added to type or variable
+  declarations. Using an attributed type or variable in an arithmetic
+  expression will define the overflow behavior for that expression as having
+  two's complement wrap-around. These expressions cannot trigger integer
+  overflow warnings or sanitizer warnings. They also cannot be optimized away
+  by some eager UB optimizations.
+
+  This attribute is ignored in C++.
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 2bfefeabc348be..68cd7d7c0fac3b 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4077,6 +4077,9 @@ class BinaryOperator : public Expr {
   static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
 return HasFPFeatures * sizeof(FPOptionsOverride);
   }
+
+  /// Do one of the subexpressions have the wraps attribute?
+  bool oneOfWraps(const ASTContext &Ctx) const;
 };
 
 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dc87a8c6f022dc..06e41fcee206c4 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4506,3 +4506,9 @@ def CodeAlign: StmtAttr {
 static constexpr int MaximumAlignment = 4096;
   }];
 }
+
+def Wraps : DeclOrTypeAttr {
+  let Spellings = [Clang<"wraps">, CXX11<"", "wraps", 202403>];
+  let Subjects = SubjectList<[Var, TypedefName, Field]>;
+  let Documentation = [WrapsDocs];
+}
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 0ca4ea377fc36a..a2adb923e3c47c 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8044,3 +8044,69 @@ requirement:
   }
   }];
 }
+
+def WrapsDocs : Documentation {
+  let Category = DocCatField;
+  let Content = [{
+This attribute can be used with type or variable declarations to denote that
+arithmetic containing these marked components have defined overflow behavior.
+Specifically, the behavior is defined as being consistent with two's complement
+wrap-around. For the purposes of sanitizers or warnings that concern themselves
+with the definedness of integer arithmetic, they will cease to instrument or
+warn about arithmetic that directly involves a "wrapping" component.
+
+For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
+will not warn about suspicious overflowing arithmetic -- assuming correct usage
+of the wraps attribute.
+
+This example shows some basic usage of ``__attribute__((wraps))`` on a type
+definition when building with ``-fsanitize=signed-integer-overflow``
+
+.. code-block:: c
+  typedef int __attribute__((wraps)) wrapping_int;
+
+  void foo() {
+wrapping_int a = INT_MAX;
+++a; // no sanitizer warning
+  }
+
+  int main() { foo(); }
+
+In the following example, we use ``__attribute__((wraps))`` on a variable to
+disable overflow instrumentation for arithmetic expressions it appears in. We
+do so with a popular overflow-checking pattern which we might not want to trip
+sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
+
+.. code-block:: c
+  void foo(int off

[clang] [clang-tools-extra] [clang][modules] Do not resolve `HeaderFileInfo` externally in `ASTWriter` (PR #87848)

2024-04-09 Thread Ben Langmuir via cfe-commits


@@ -409,7 +409,7 @@ class SymbolCollector::HeaderFileURICache {
 // 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))

benlangmuir wrote:

Could this code be performance sensitive?

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


[clang] [clang-tools-extra] [clang][modules] Do not resolve `HeaderFileInfo` externally in `ASTWriter` (PR #87848)

2024-04-09 Thread Jan Svoboda via cfe-commits


@@ -409,7 +409,7 @@ class SymbolCollector::HeaderFileURICache {
 // 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))

jansvoboda11 wrote:

I think that would be closer to the original semantics, but my feeling is that 
it's not correct. This `FileEntry` corresponds to a `FileID` containing the 
`SourceLocation` of a `NamedDecl` which (I think) might've been deserialized 
from a PCM file. So I think including external `HeaderFileInfo` here is the 
right thing to do.

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


[clang] [llvm] demangle function names in trace files (PR #87626)

2024-04-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-driver

@llvm/pr-subscribers-clang

Author: Trass3r (Trass3r)


Changes

This improves consistency in the trace files as other entries are demangled too.

@jamieschmeiser @An-DJ

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


4 Files Affected:

- (modified) clang/test/Driver/ftime-trace-sections.py (+13-2) 
- (modified) llvm/lib/IR/LegacyPassManager.cpp (+3-1) 
- (modified) llvm/lib/Passes/CMakeLists.txt (+1) 
- (modified) llvm/lib/Passes/StandardInstrumentations.cpp (+5-4) 


``diff
diff --git a/clang/test/Driver/ftime-trace-sections.py 
b/clang/test/Driver/ftime-trace-sections.py
old mode 100644
new mode 100755
index 02afa4ac54eb7b..eeb3aa24131a39
--- a/clang/test/Driver/ftime-trace-sections.py
+++ b/clang/test/Driver/ftime-trace-sections.py
@@ -19,9 +19,12 @@ def is_before(range1, range2):
 
 log_contents = json.loads(sys.stdin.read())
 events = log_contents["traceEvents"]
-codegens = [event for event in events if event["name"] == "CodeGen Function"]
+
+instants  = [event for event in events if event["name"] == 
"InstantiateFunction"]
+codegens  = [event for event in events if event["name"] == "CodeGen Function"]
+opts  = [event for event in events if event["name"] == "OptFunction"]
 frontends = [event for event in events if event["name"] == "Frontend"]
-backends = [event for event in events if event["name"] == "Backend"]
+backends  = [event for event in events if event["name"] == "Backend"]
 
 beginning_of_time = log_contents["beginningOfTime"] / 100
 seconds_since_epoch = time.time()
@@ -48,3 +51,11 @@ def is_before(range1, range2):
 ]
 ):
 sys.exit("Not all Frontend section are before all Backend sections!")
+
+# Check that entries for foo exist and are in a demangled form.
+if not any(e for e in instants if "foo" in e["args"]["detail"]):
+sys.exit("Missing Instantiate entry for foo!")
+if not any(e for e in codegens if "foo" in e["args"]["detail"]):
+sys.exit("Missing CodeGen entry for foo!")
+if not any(e for e in opts if "foo" in e["args"]["detail"]):
+sys.exit("Missing Optimize entry for foo!")
diff --git a/llvm/lib/IR/LegacyPassManager.cpp 
b/llvm/lib/IR/LegacyPassManager.cpp
index 953f21ce740590..9e3578954418ad 100644
--- a/llvm/lib/IR/LegacyPassManager.cpp
+++ b/llvm/lib/IR/LegacyPassManager.cpp
@@ -12,6 +12,7 @@
 
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LLVMContext.h"
@@ -1421,7 +1422,8 @@ bool FPPassManager::runOnFunction(Function &F) {
 
   // Store name outside of loop to avoid redundant calls.
   const StringRef Name = F.getName();
-  llvm::TimeTraceScope FunctionScope("OptFunction", Name);
+  llvm::TimeTraceScope FunctionScope(
+  "OptFunction", [&F]() { return demangle(F.getName().str()); });
 
   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
 FunctionPass *FP = getContainedPass(Index);
diff --git a/llvm/lib/Passes/CMakeLists.txt b/llvm/lib/Passes/CMakeLists.txt
index 6425f4934b2103..b5224327d79216 100644
--- a/llvm/lib/Passes/CMakeLists.txt
+++ b/llvm/lib/Passes/CMakeLists.txt
@@ -21,6 +21,7 @@ add_llvm_component_library(LLVMPasses
   CodeGen
   Core
   Coroutines
+  Demangle
   HipStdPar
   IPO
   InstCombine
diff --git a/llvm/lib/Passes/StandardInstrumentations.cpp 
b/llvm/lib/Passes/StandardInstrumentations.cpp
index 697988b3fc7c0b..0faf865cd013c8 100644
--- a/llvm/lib/Passes/StandardInstrumentations.cpp
+++ b/llvm/lib/Passes/StandardInstrumentations.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Analysis/LazyCallGraph.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Module.h"
@@ -215,12 +216,12 @@ void printIR(raw_ostream &OS, const Loop *L) {
   printLoop(const_cast(*L), OS);
 }
 
-std::string getIRName(Any IR) {
+std::string getIRName(Any IR, bool demangled = false) {
   if (unwrapIR(IR))
 return "[module]";
 
   if (const auto *F = unwrapIR(IR))
-return F->getName().str();
+return demangled ? demangle(F->getName()) : F->getName().str();
 
   if (const auto *C = unwrapIR(IR))
 return C->getName();
@@ -229,7 +230,7 @@ std::string getIRName(Any IR) {
 return L->getName().str();
 
   if (const auto *MF = unwrapIR(IR))
-return MF->getName().str();
+return demangled ? demangle(MF->getName()) : MF->getName().str();
 
   llvm_unreachable("Unknown wrapped IR type");
 }
@@ -1495,7 +1496,7 @@ void TimeProfilingPassesHandler::registerCallbacks(
 }
 
 void TimeProfilingPassesHandler::runBeforePass(StringRef PassID, Any IR) {
-  timeTraceProfilerBegin(PassID, getIRName(IR));
+  timeTraceProfilerBegin(PassID, getIRName(IR, true));
 }
 
 void TimeProfilingPassesHandler::runAfterPass() { timeTraceProfilerEnd(); }

``




ht

[clang] [llvm] demangle function names in trace files (PR #87626)

2024-04-09 Thread via cfe-commits

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


[clang] [clang-tools-extra] [clang][modules] Do not resolve `HeaderFileInfo` externally in `ASTWriter` (PR #87848)

2024-04-09 Thread Ben Langmuir via cfe-commits


@@ -409,7 +409,7 @@ class SymbolCollector::HeaderFileURICache {
 // 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))

benlangmuir wrote:

Shouldn't this be `getExistingLocalFileInfo` since it was previously 
`/*WantExternal*/ false`?

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

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


[clang] [InstallAPI] Handle zippered frameworks (PR #88205)

2024-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes

A zippered framework is a single framework that can be loaded in both macOS and 
macatalyst processes. Broadly to InstallAPI, it means the same interface can 
represent two separate platforms.

A dylib's symbol table does not distinguish between macOS/macCatalyst.
  `InstallAPI` provides the ability for the tbd file to distinct
symbols between them.
The verifier handles this special logic by tracking all unavailable and 
obsoleted APIs in this context and checking against those when determining 
dylib symbols with no matching declaration.

* If there exists an available decl for either platform, do not warn.
* If there is no available decl, emit a diagnostic and print the source 
location for both decls.

---

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


8 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticInstallAPIKinds.td (+4) 
- (modified) clang/include/clang/InstallAPI/DylibVerifier.h (+29-3) 
- (modified) clang/lib/InstallAPI/DylibVerifier.cpp (+87-11) 
- (added) clang/test/InstallAPI/Inputs/MacOSX13.0.sdk/SDKSettings.json (+19) 
- (added) clang/test/InstallAPI/diagnostics-zippered.test (+765) 
- (modified) clang/test/InstallAPI/driver-invalid-options.test (+7) 
- (modified) clang/tools/clang-installapi/Options.cpp (+50-2) 
- (modified) clang/tools/clang-installapi/Options.h (+3) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 0a477da7186b09..396bff0146a373 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -20,6 +20,10 @@ def warn_no_such_excluded_header_file : Warning<"no such 
excluded %select{public
 def warn_glob_did_not_match: Warning<"glob '%0' did not match any header 
file">, InGroup;
 def err_no_such_umbrella_header_file : Error<"%select{public|private|project}1 
umbrella header file not found in input: '%0'">;
 def err_cannot_find_reexport : Error<"cannot find re-exported 
%select{framework|library}0: '%1'">;
+def err_no_matching_target : Error<"no matching target found for target 
variant '%0'">;
+def err_unsupported_vendor : Error<"vendor '%0' is not supported: '%1'">;
+def err_unsupported_environment : Error<"environment '%0' is not supported: 
'%1'">;
+def err_unsupported_os : Error<"os '%0' is not supported: '%1'">;
 } // end of command line category.
 
 let CategoryName = "Verification" in {
diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index a3df25f10de4b1..31de212fc423a5 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -28,6 +28,16 @@ enum class VerificationMode {
 using LibAttrs = llvm::StringMap;
 using ReexportedInterfaces = llvm::SmallVector;
 
+// Pointers to information about a zippered declaration used for
+// querying and reporting violations against different
+// declarations that all map to the same symbol.
+struct ZipperedDeclSource {
+  const FrontendAttrs *FA;
+  clang::SourceManager *SrcMgr;
+  Target T;
+};
+using ZipperedDeclSources = std::vector;
+
 /// Service responsible to tracking state of verification across the
 /// lifetime of InstallAPI.
 /// As declarations are collected during AST traversal, they are
@@ -68,10 +78,10 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   DylibVerifier() = default;
 
   DylibVerifier(llvm::MachO::Records &&Dylib, ReexportedInterfaces &&Reexports,
-DiagnosticsEngine *Diag, VerificationMode Mode, bool Demangle,
-StringRef DSYMPath)
+DiagnosticsEngine *Diag, VerificationMode Mode, bool Zippered,
+bool Demangle, StringRef DSYMPath)
   : Dylib(std::move(Dylib)), Reexports(std::move(Reexports)), Mode(Mode),
-Demangle(Demangle), DSYMPath(DSYMPath),
+Zippered(Zippered), Demangle(Demangle), DSYMPath(DSYMPath),
 Exports(std::make_unique()), Ctx(VerifierContext{Diag}) {}
 
   Result verify(GlobalRecord *R, const FrontendAttrs *FA);
@@ -118,6 +128,15 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   /// symbols should be omitted from the text-api file.
   bool shouldIgnoreReexport(const Record *R, SymbolContext &SymCtx) const;
 
+  // Ignore and omit unavailable symbols in zippered libraries.
+  bool shouldIgnoreZipperedAvailability(const Record *R, SymbolContext 
&SymCtx);
+
+  // Check if an internal declaration in zippered library has an
+  // external declaration for a different platform. This results
+  // in the symbol being in a "seperate" platform slice.
+  bool shouldIgnoreInternalZipperedSymbol(const Record *R,
+  const SymbolContext &SymCtx) const;
+
   /// Compare the visibility declarations to t

[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

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


[clang] [InstallAPI] Handle zippered frameworks (PR #88205)

2024-04-09 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/88205

A zippered framework is a single framework that can be loaded in both macOS and 
macatalyst processes. Broadly to InstallAPI, it means the same interface can 
represent two separate platforms.

A dylib's symbol table does not distinguish between macOS/macCatalyst.
  `InstallAPI` provides the ability for the tbd file to distinct
symbols between them.
The verifier handles this special logic by tracking all unavailable and 
obsoleted APIs in this context and checking against those when determining 
dylib symbols with no matching declaration.

* If there exists an available decl for either platform, do not warn.
* If there is no available decl, emit a diagnostic and print the source 
location for both decls.

>From cf8e63e06d8ed8ee626aab4fdf5ec499ed476b51 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Tue, 9 Apr 2024 14:14:10 -0700
Subject: [PATCH] [InstallAPI] Handle zippered frameworks

A zippered framework is a single framework that can be loaded in both macOS and
macatalyst processes. Broadly to InstallAPI, it means the same interface can
represent two seperate platforms.

A dylib's symbol table does not distinct between macOS/macCatalyst.
  `InstallAPI` provides ability for the tbd file to distinct
symbols between them.
The verifier handles this special logic by tracking all unavailable and
obsoleted APIs in this context and check against those when determining
dylib symbols with no matching declaration.

* If there exists an available decl for either platform, do not warn.
* If there is no available decl, emit an diagnostic and print the source
  location for both decls.
---
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |   4 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  32 +-
 clang/lib/InstallAPI/DylibVerifier.cpp|  98 ++-
 .../Inputs/MacOSX13.0.sdk/SDKSettings.json|  19 +
 .../test/InstallAPI/diagnostics-zippered.test | 765 ++
 .../InstallAPI/driver-invalid-options.test|   7 +
 clang/tools/clang-installapi/Options.cpp  |  52 +-
 clang/tools/clang-installapi/Options.h|   3 +
 8 files changed, 964 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/InstallAPI/Inputs/MacOSX13.0.sdk/SDKSettings.json
 create mode 100644 clang/test/InstallAPI/diagnostics-zippered.test

diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 0a477da7186b09..396bff0146a373 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -20,6 +20,10 @@ def warn_no_such_excluded_header_file : Warning<"no such 
excluded %select{public
 def warn_glob_did_not_match: Warning<"glob '%0' did not match any header 
file">, InGroup;
 def err_no_such_umbrella_header_file : Error<"%select{public|private|project}1 
umbrella header file not found in input: '%0'">;
 def err_cannot_find_reexport : Error<"cannot find re-exported 
%select{framework|library}0: '%1'">;
+def err_no_matching_target : Error<"no matching target found for target 
variant '%0'">;
+def err_unsupported_vendor : Error<"vendor '%0' is not supported: '%1'">;
+def err_unsupported_environment : Error<"environment '%0' is not supported: 
'%1'">;
+def err_unsupported_os : Error<"os '%0' is not supported: '%1'">;
 } // end of command line category.
 
 let CategoryName = "Verification" in {
diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index a3df25f10de4b1..31de212fc423a5 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -28,6 +28,16 @@ enum class VerificationMode {
 using LibAttrs = llvm::StringMap;
 using ReexportedInterfaces = llvm::SmallVector;
 
+// Pointers to information about a zippered declaration used for
+// querying and reporting violations against different
+// declarations that all map to the same symbol.
+struct ZipperedDeclSource {
+  const FrontendAttrs *FA;
+  clang::SourceManager *SrcMgr;
+  Target T;
+};
+using ZipperedDeclSources = std::vector;
+
 /// Service responsible to tracking state of verification across the
 /// lifetime of InstallAPI.
 /// As declarations are collected during AST traversal, they are
@@ -68,10 +78,10 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   DylibVerifier() = default;
 
   DylibVerifier(llvm::MachO::Records &&Dylib, ReexportedInterfaces &&Reexports,
-DiagnosticsEngine *Diag, VerificationMode Mode, bool Demangle,
-StringRef DSYMPath)
+DiagnosticsEngine *Diag, VerificationMode Mode, bool Zippered,
+bool Demangle, StringRef DSYMPath)
   : Dylib(std::move(Dylib)), Reexports(std::move(Reexports)), Mode(Mode),
-Demangle(Demangle), DSYMPath(DSYMPath),
+Zippered(Zippered), Demangle(Demangle), DSYMPath(DSYMPath),
 Exp

[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

JustinStitt wrote:

Hi, I've made some changes and am looking for some more review on this PR:

* This attribute no longer supports C++ as there are other solutions for that 
language [1] that allow for the same fine-grained wrapping control without 
changing syntax patterns.
* Add bypass for implicit-(un)signed-integer-truncation sanitizers
* Rebased onto eec41d2f8d81b546d7b97648cca6b2d656104bd3

[1]: https://godbolt.org/z/7qPve6cWq (simple example)

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

https://github.com/JustinStitt updated 
https://github.com/llvm/llvm-project/pull/86618

>From 10ee32826fc2acb6bd993c88bdb7142360b6f263 Mon Sep 17 00:00:00 2001
From: Justin Stitt 
Date: Tue, 5 Mar 2024 03:14:49 +
Subject: [PATCH 1/3] implement wraps attribute

Signed-off-by: Justin Stitt 
---
 clang/docs/ReleaseNotes.rst   |  9 +++
 clang/include/clang/AST/Expr.h|  3 +
 clang/include/clang/Basic/Attr.td |  6 ++
 clang/include/clang/Basic/AttrDocs.td | 66 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +
 clang/include/clang/Sema/Sema.h   |  4 ++
 clang/lib/AST/Expr.cpp| 19 ++
 clang/lib/AST/ExprConstant.cpp|  6 +-
 clang/lib/AST/TypePrinter.cpp |  3 +
 clang/lib/CodeGen/CGExprScalar.cpp| 40 +--
 clang/lib/Sema/SemaDeclAttr.cpp   | 12 +++-
 clang/lib/Sema/SemaType.cpp   | 15 +
 clang/test/CodeGen/integer-overflow.c | 56 
 clang/test/CodeGen/unsigned-overflow.c| 63 +++---
 clang/test/Sema/attr-wraps.c  |  9 +++
 15 files changed, 298 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/Sema/attr-wraps.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f96cebbde3d825..cb02af7e948989 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -282,6 +282,15 @@ Attribute Changes in Clang
   This allows the ``_Nullable`` and ``_Nonnull`` family of type attributes to
   apply to this class.
 
+- Introduced ``__attribute((wraps))__`` which can be added to type or variable
+  declarations. Using an attributed type or variable in an arithmetic
+  expression will define the overflow behavior for that expression as having
+  two's complement wrap-around. These expressions cannot trigger integer
+  overflow warnings or sanitizer warnings. They also cannot be optimized away
+  by some eager UB optimizations.
+
+  This attribute is ignored in C++.
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 2bfefeabc348be..68cd7d7c0fac3b 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4077,6 +4077,9 @@ class BinaryOperator : public Expr {
   static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
 return HasFPFeatures * sizeof(FPOptionsOverride);
   }
+
+  /// Do one of the subexpressions have the wraps attribute?
+  bool oneOfWraps(const ASTContext &Ctx) const;
 };
 
 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dc87a8c6f022dc..06e41fcee206c4 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4506,3 +4506,9 @@ def CodeAlign: StmtAttr {
 static constexpr int MaximumAlignment = 4096;
   }];
 }
+
+def Wraps : DeclOrTypeAttr {
+  let Spellings = [Clang<"wraps">, CXX11<"", "wraps", 202403>];
+  let Subjects = SubjectList<[Var, TypedefName, Field]>;
+  let Documentation = [WrapsDocs];
+}
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 0ca4ea377fc36a..a2adb923e3c47c 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8044,3 +8044,69 @@ requirement:
   }
   }];
 }
+
+def WrapsDocs : Documentation {
+  let Category = DocCatField;
+  let Content = [{
+This attribute can be used with type or variable declarations to denote that
+arithmetic containing these marked components have defined overflow behavior.
+Specifically, the behavior is defined as being consistent with two's complement
+wrap-around. For the purposes of sanitizers or warnings that concern themselves
+with the definedness of integer arithmetic, they will cease to instrument or
+warn about arithmetic that directly involves a "wrapping" component.
+
+For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
+will not warn about suspicious overflowing arithmetic -- assuming correct usage
+of the wraps attribute.
+
+This example shows some basic usage of ``__attribute__((wraps))`` on a type
+definition when building with ``-fsanitize=signed-integer-overflow``
+
+.. code-block:: c
+  typedef int __attribute__((wraps)) wrapping_int;
+
+  void foo() {
+wrapping_int a = INT_MAX;
+++a; // no sanitizer warning
+  }
+
+  int main() { foo(); }
+
+In the following example, we use ``__attribute__((wraps))`` on a variable to
+disable overflow instrumentation for arithmetic expressions it appears in. We
+do so with a popular overflow-checking pattern which we might not want to trip
+sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
+
+.. code-block:: c
+  void foo(int off

[clang] [InstallAPI] Tie lifetime of FE objects to DylibVerifier (PR #88189)

2024-04-09 Thread Cyndy Ishida via cfe-commits

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


[clang] f04452d - [InstallAPI] Tie lifetime of FE objects to DylibVerifier (#88189)

2024-04-09 Thread via cfe-commits

Author: Cyndy Ishida
Date: 2024-04-09T15:13:55-07:00
New Revision: f04452de1986e4e01296a80231efb212d6c84c42

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

LOG: [InstallAPI] Tie lifetime of FE objects to DylibVerifier (#88189)

A few verification checks need to happen until all AST's have been
traversed, specifically for zippered framework checking. To keep source
location until that time valid, hold onto to references of
FrontendRecords + SourceManager.

Added: 


Modified: 
clang/include/clang/InstallAPI/DylibVerifier.h
clang/include/clang/InstallAPI/Frontend.h
clang/include/clang/InstallAPI/FrontendRecords.h
clang/lib/InstallAPI/DylibVerifier.cpp
clang/lib/InstallAPI/Frontend.cpp
clang/tools/clang-installapi/ClangInstallAPI.cpp

Removed: 




diff  --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index 07dbd3bf5f2b10..a3df25f10de4b1 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_INSTALLAPI_DYLIBVERIFIER_H
 
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/InstallAPI/MachO.h"
 
 namespace clang {
@@ -99,11 +100,7 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   Result getState() const { return Ctx.FrontendState; }
 
   /// Set 
diff erent source managers to the same diagnostics engine.
-  void setSourceManager(SourceManager &SourceMgr) const {
-if (!Ctx.Diag)
-  return;
-Ctx.Diag->setSourceManager(&SourceMgr);
-  }
+  void setSourceManager(IntrusiveRefCntPtr SourceMgr);
 
 private:
   /// Determine whether to compare declaration to symbol in binary.
@@ -190,6 +187,9 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
 
   // Track DWARF provided source location for dylibs.
   DWARFContext *DWARFCtx = nullptr;
+
+  // Source manager for each unique compiler instance.
+  llvm::SmallVector, 12> SourceManagers;
 };
 
 } // namespace installapi

diff  --git a/clang/include/clang/InstallAPI/Frontend.h 
b/clang/include/clang/InstallAPI/Frontend.h
index 5cccd891c58093..bc4e77de2b7256 100644
--- a/clang/include/clang/InstallAPI/Frontend.h
+++ b/clang/include/clang/InstallAPI/Frontend.h
@@ -36,7 +36,7 @@ class InstallAPIAction : public ASTFrontendAction {
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef InFile) override {
 Ctx.Diags->getClient()->BeginSourceFile(CI.getLangOpts());
-Ctx.Verifier->setSourceManager(CI.getSourceManager());
+Ctx.Verifier->setSourceManager(CI.getSourceManagerPtr());
 return std::make_unique(
 CI.getASTContext(), Ctx, CI.getSourceManager(), CI.getPreprocessor());
   }

diff  --git a/clang/include/clang/InstallAPI/FrontendRecords.h 
b/clang/include/clang/InstallAPI/FrontendRecords.h
index 59271e81e230c2..ef82398addd7ac 100644
--- a/clang/include/clang/InstallAPI/FrontendRecords.h
+++ b/clang/include/clang/InstallAPI/FrontendRecords.h
@@ -21,6 +21,7 @@ namespace installapi {
 struct FrontendAttrs {
   const AvailabilityInfo Avail;
   const Decl *D;
+  const SourceLocation Loc;
   const HeaderType Access;
 };
 

diff  --git a/clang/lib/InstallAPI/DylibVerifier.cpp 
b/clang/lib/InstallAPI/DylibVerifier.cpp
index 2387ee0e78ad56..4fa2d4e9292c72 100644
--- a/clang/lib/InstallAPI/DylibVerifier.cpp
+++ b/clang/lib/InstallAPI/DylibVerifier.cpp
@@ -214,16 +214,16 @@ bool DylibVerifier::compareObjCInterfaceSymbols(const 
Record *R,
  StringRef SymName, bool PrintAsWarning = false) {
 if (SymLinkage == RecordLinkage::Unknown)
   Ctx.emitDiag([&]() {
-Ctx.Diag->Report(SymCtx.FA->D->getLocation(),
- PrintAsWarning ? diag::warn_library_missing_symbol
-: diag::err_library_missing_symbol)
+Ctx.Diag->Report(SymCtx.FA->Loc, PrintAsWarning
+ ? 
diag::warn_library_missing_symbol
+ : 
diag::err_library_missing_symbol)
 << SymName;
   });
 else
   Ctx.emitDiag([&]() {
-Ctx.Diag->Report(SymCtx.FA->D->getLocation(),
- PrintAsWarning ? diag::warn_library_hidden_symbol
-: diag::err_library_hidden_symbol)
+Ctx.Diag->Report(SymCtx.FA->Loc, PrintAsWarning
+ ? diag::warn_library_hidden_symbol
+ : diag::err_library_hidden_symbol)
 << SymName;
   });
   };
@@ -270,16 +270,14 @@ DylibVerifier::Result 
DylibVerifier::compareVisibility(const Record *R,
  

[clang] ANDROID: x86_64: Set default max-page-size to 16kB (PR #87413)

2024-04-09 Thread via cfe-commits

pirama-arumuga-nainar wrote:

Can you add a test similar to #70251?

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


[clang] Fix quadratic slowdown in AST matcher parent map generation (PR #87824)

2024-04-09 Thread via cfe-commits

higher-performance wrote:

Added a release note as well; feel free to edit it if needed (or let me know if 
I should change anything)!

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


[clang] Fix quadratic slowdown in AST matcher parent map generation (PR #87824)

2024-04-09 Thread via cfe-commits

https://github.com/higher-performance updated 
https://github.com/llvm/llvm-project/pull/87824

>From 78f18445804fdb1cdf7810f56d3ae3c6e55f8da7 Mon Sep 17 00:00:00 2001
From: higher-performance
 <113926381+higher-performa...@users.noreply.github.com>
Date: Fri, 5 Apr 2024 15:36:05 -0400
Subject: [PATCH] Fix quadratic slowdown in AST matcher parent map generation

Avoids the need to linearly re-scan all seen parent nodes to check for 
duplicates, which previously caused a slowdown for ancestry checks in Clang AST 
matchers.

Fixes https://github.com/llvm/llvm-project/issues/86881.
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/AST/ParentMapContext.cpp | 25 ++---
 2 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 28e8ddb3c41c3e..cd9e0b54d55fde 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -622,6 +622,9 @@ Fixed Point Support in Clang
 AST Matchers
 
 
+- Fixes a long-standing performance issue in parent map generation for
+  ancestry-based matchers such as ``hasParent`` and ``hasAncestor``, making
+  them significantly faster.
 - ``isInStdNamespace`` now supports Decl declared with ``extern "C++"``.
 - Add ``isExplicitObjectMemberFunction``.
 - Fixed ``forEachArgumentWithParam`` and ``forEachArgumentWithParamType`` to
diff --git a/clang/lib/AST/ParentMapContext.cpp 
b/clang/lib/AST/ParentMapContext.cpp
index 21cfd5b1de6e9d..9723c0cfa83bbe 100644
--- a/clang/lib/AST/ParentMapContext.cpp
+++ b/clang/lib/AST/ParentMapContext.cpp
@@ -61,7 +61,26 @@ class ParentMapContext::ParentMap {
   template  friend struct ::MatchParents;
 
   /// Contains parents of a node.
-  using ParentVector = llvm::SmallVector;
+  class ParentVector {
+  public:
+ParentVector() = default;
+explicit ParentVector(size_t N, const DynTypedNode &Value) {
+  Items.reserve(N);
+  for (; N > 0; --N)
+push_back(Value);
+}
+bool contains(const DynTypedNode &Value) {
+  return Seen.contains(Value);
+}
+void push_back(const DynTypedNode &Value) {
+  if (!Value.getMemoizationData() || Seen.insert(Value).second)
+Items.push_back(Value);
+}
+llvm::ArrayRef view() const { return Items; }
+  private:
+llvm::SmallVector Items;
+llvm::SmallDenseSet Seen;
+  };
 
   /// Maps from a node to its parents. This is used for nodes that have
   /// pointer identity only, which are more common and we can save space by
@@ -99,7 +118,7 @@ class ParentMapContext::ParentMap {
   return llvm::ArrayRef();
 }
 if (const auto *V = I->second.template dyn_cast()) {
-  return llvm::ArrayRef(*V);
+  return V->view();
 }
 return getSingleDynTypedNodeFromParentMap(I->second);
   }
@@ -252,7 +271,7 @@ class ParentMapContext::ParentMap {
   const auto *S = It->second.dyn_cast();
   if (!S) {
 if (auto *Vec = It->second.dyn_cast())
-  return llvm::ArrayRef(*Vec);
+  return Vec->view();
 return getSingleDynTypedNodeFromParentMap(It->second);
   }
   const auto *P = dyn_cast(S);

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


[clang] [Clang] Add wraps attribute (for granular integer overflow handling) (PR #86618)

2024-04-09 Thread Justin Stitt via cfe-commits

https://github.com/JustinStitt updated 
https://github.com/llvm/llvm-project/pull/86618

>From 0fa8f07c722f9d7f80a90824f961ae6e9c5bdef7 Mon Sep 17 00:00:00 2001
From: Justin Stitt 
Date: Tue, 5 Mar 2024 03:14:49 +
Subject: [PATCH 1/4] implement wraps attribute

Signed-off-by: Justin Stitt 
---
 clang/docs/ReleaseNotes.rst   |  7 ++
 clang/include/clang/AST/Expr.h|  3 +
 clang/include/clang/Basic/Attr.td |  6 ++
 clang/include/clang/Basic/AttrDocs.td | 66 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +
 clang/include/clang/Sema/Sema.h   |  4 ++
 clang/lib/AST/Expr.cpp| 19 ++
 clang/lib/AST/ExprConstant.cpp|  6 +-
 clang/lib/AST/TypePrinter.cpp |  3 +
 clang/lib/CodeGen/CGExprScalar.cpp| 40 +--
 clang/lib/Sema/SemaDeclAttr.cpp   | 12 +++-
 clang/lib/Sema/SemaType.cpp   | 15 +
 clang/test/CodeGen/integer-overflow.c | 56 
 clang/test/CodeGen/unsigned-overflow.c| 63 +++---
 clang/test/Sema/attr-wraps.c  |  9 +++
 15 files changed, 296 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/Sema/attr-wraps.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fbe2fec6ca065..20bb9815830592 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -248,6 +248,13 @@ Attribute Changes in Clang
   added a new extension query ``__has_extension(swiftcc)`` corresponding to the
   ``__attribute__((swiftcc))`` attribute.
 
+- Introduced ``__attribute((wraps))`` or ``[[wraps]]`` which can be added to
+  type or variable declarations. Using an attributed type or variable in an
+  arithmetic expression will define the overflow behavior for that expression
+  as having two's complement wrap-around. These expressions cannot trigger
+  integer overflow warnings or sanitizer warnings. They also cannot be
+  optimized away by some eager UB optimizations.
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 6e153ebe024b42..934146e8a182bc 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4084,6 +4084,9 @@ class BinaryOperator : public Expr {
   static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
 return HasFPFeatures * sizeof(FPOptionsOverride);
   }
+
+  /// Do one of the subexpressions have the wraps attribute?
+  bool oneOfWraps(const ASTContext &Ctx) const;
 };
 
 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e03e55612645b..0ea7755791d82e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4496,3 +4496,9 @@ def CodeAlign: StmtAttr {
 static constexpr int MaximumAlignment = 4096;
   }];
 }
+
+def Wraps : DeclOrTypeAttr {
+  let Spellings = [Clang<"wraps">, CXX11<"", "wraps", 202403>];
+  let Subjects = SubjectList<[Var, TypedefName, Field]>;
+  let Documentation = [WrapsDocs];
+}
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 9de14f608fd114..af662702edcffa 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8005,3 +8005,69 @@ requirement:
   }
   }];
 }
+
+def WrapsDocs : Documentation {
+  let Category = DocCatField;
+  let Content = [{
+This attribute can be used with type or variable declarations to denote that
+arithmetic containing these marked components have defined overflow behavior.
+Specifically, the behavior is defined as being consistent with two's complement
+wrap-around. For the purposes of sanitizers or warnings that concern themselves
+with the definedness of integer arithmetic, they will cease to instrument or
+warn about arithmetic that directly involves a "wrapping" component.
+
+For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
+will not warn about suspicious overflowing arithmetic -- assuming correct usage
+of the wraps attribute.
+
+This example shows some basic usage of ``__attribute__((wraps))`` on a type
+definition when building with ``-fsanitize=signed-integer-overflow``
+
+.. code-block:: c
+  typedef int __attribute__((wraps)) wrapping_int;
+
+  void foo() {
+wrapping_int a = INT_MAX;
+++a; // no sanitizer warning
+  }
+
+  int main() { foo(); }
+
+In the following example, we use ``__attribute__((wraps))`` on a variable to
+disable overflow instrumentation for arithmetic expressions it appears in. We
+do so with a popular overflow-checking pattern which we might not want to trip
+sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
+
+.. code-block:: c
+  void foo(int offset)

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

2024-04-09 Thread via cfe-commits

mydeveloperday wrote:

I wish we'd made this removal an option rather than just removing it, what we 
are seeing is reasonably formatted json or xml being streamed out is now poorly 
written

```c++
osjson << "{\n"
   <<"  \"name\": \"value\",\n"
   <<"  \"key\": \"abc\", \n"
   <<" }";
```

now becomes

```c++
osjson << "{\n" <<"  \"name\": \"value\",\n <<"  \"key\": \"abc\",\n  << "}";
```

While i understand its correct for column width its not as nicer.

These rules about breaking between << were part of the original author rules 
for now to best try and format c++ and I sort of feel we should at least honour 
it via an option.

I also feel that this will create a large amount of complaints about us 
changing defaults.
 

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


[clang] Fix coverage when /fo is used (PR #88201)

2024-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (pdagobert)


Changes

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

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


1 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+4) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 766a9b91e3c0ad..44d18acd25a589 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -802,6 +802,10 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, 
Compilation &C,
 } else if (Arg *FinalOutput =
C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
   CoverageFilename = FinalOutput->getValue();
+  StringRef V = FinalOutput->getValue();
+  if (llvm::sys::path::is_separator(V.back())) {
+CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
+  }
 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
   CoverageFilename = FinalOutput->getValue();
 } else {

``




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


[clang] Fix coverage when /fo is used (PR #88201)

2024-04-09 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] Fix coverage when /fo is used (PR #88201)

2024-04-09 Thread via cfe-commits

https://github.com/pdagobert created 
https://github.com/llvm/llvm-project/pull/88201

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

>From 6db0e01e198de9e5ee4055f9433150818c429c10 Mon Sep 17 00:00:00 2001
From: pdagobert 
Date: Tue, 9 Apr 2024 23:10:58 +0200
Subject: [PATCH] Fix coverage when /fo is used

---
 clang/lib/Driver/ToolChains/Clang.cpp | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 766a9b91e3c0ad..44d18acd25a589 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -802,6 +802,10 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, 
Compilation &C,
 } else if (Arg *FinalOutput =
C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
   CoverageFilename = FinalOutput->getValue();
+  StringRef V = FinalOutput->getValue();
+  if (llvm::sys::path::is_separator(V.back())) {
+CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
+  }
 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
   CoverageFilename = FinalOutput->getValue();
 } else {

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


[clang] [InstallAPI] Tie lifetime of FE objects to DylibVerifier (PR #88189)

2024-04-09 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/88189

>From a7894f987b80f1916195c3ab15da5c33ab69ab00 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Tue, 9 Apr 2024 13:04:18 -0700
Subject: [PATCH] [InstallAPI] Tie lifetime of FE objects to DylibVerifier

A few verification checks need to happen until all AST's have been
traversed, specifically for zippered framework checking.
To keep source location until that time valid, hold onto to
references of FrontendRecords + SourceManager.
---
 .../include/clang/InstallAPI/DylibVerifier.h  | 10 ++--
 clang/include/clang/InstallAPI/Frontend.h |  2 +-
 .../clang/InstallAPI/FrontendRecords.h|  1 +
 clang/lib/InstallAPI/DylibVerifier.cpp| 47 +--
 clang/lib/InstallAPI/Frontend.cpp | 15 +++---
 .../clang-installapi/ClangInstallAPI.cpp  |  2 +
 6 files changed, 40 insertions(+), 37 deletions(-)

diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index 07dbd3bf5f2b10..a3df25f10de4b1 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_INSTALLAPI_DYLIBVERIFIER_H
 
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/InstallAPI/MachO.h"
 
 namespace clang {
@@ -99,11 +100,7 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
   Result getState() const { return Ctx.FrontendState; }
 
   /// Set different source managers to the same diagnostics engine.
-  void setSourceManager(SourceManager &SourceMgr) const {
-if (!Ctx.Diag)
-  return;
-Ctx.Diag->setSourceManager(&SourceMgr);
-  }
+  void setSourceManager(IntrusiveRefCntPtr SourceMgr);
 
 private:
   /// Determine whether to compare declaration to symbol in binary.
@@ -190,6 +187,9 @@ class DylibVerifier : llvm::MachO::RecordVisitor {
 
   // Track DWARF provided source location for dylibs.
   DWARFContext *DWARFCtx = nullptr;
+
+  // Source manager for each unique compiler instance.
+  llvm::SmallVector, 12> SourceManagers;
 };
 
 } // namespace installapi
diff --git a/clang/include/clang/InstallAPI/Frontend.h 
b/clang/include/clang/InstallAPI/Frontend.h
index 5cccd891c58093..bc4e77de2b7256 100644
--- a/clang/include/clang/InstallAPI/Frontend.h
+++ b/clang/include/clang/InstallAPI/Frontend.h
@@ -36,7 +36,7 @@ class InstallAPIAction : public ASTFrontendAction {
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef InFile) override {
 Ctx.Diags->getClient()->BeginSourceFile(CI.getLangOpts());
-Ctx.Verifier->setSourceManager(CI.getSourceManager());
+Ctx.Verifier->setSourceManager(CI.getSourceManagerPtr());
 return std::make_unique(
 CI.getASTContext(), Ctx, CI.getSourceManager(), CI.getPreprocessor());
   }
diff --git a/clang/include/clang/InstallAPI/FrontendRecords.h 
b/clang/include/clang/InstallAPI/FrontendRecords.h
index 59271e81e230c2..ef82398addd7ac 100644
--- a/clang/include/clang/InstallAPI/FrontendRecords.h
+++ b/clang/include/clang/InstallAPI/FrontendRecords.h
@@ -21,6 +21,7 @@ namespace installapi {
 struct FrontendAttrs {
   const AvailabilityInfo Avail;
   const Decl *D;
+  const SourceLocation Loc;
   const HeaderType Access;
 };
 
diff --git a/clang/lib/InstallAPI/DylibVerifier.cpp 
b/clang/lib/InstallAPI/DylibVerifier.cpp
index 2387ee0e78ad56..4fa2d4e9292c72 100644
--- a/clang/lib/InstallAPI/DylibVerifier.cpp
+++ b/clang/lib/InstallAPI/DylibVerifier.cpp
@@ -214,16 +214,16 @@ bool DylibVerifier::compareObjCInterfaceSymbols(const 
Record *R,
  StringRef SymName, bool PrintAsWarning = false) {
 if (SymLinkage == RecordLinkage::Unknown)
   Ctx.emitDiag([&]() {
-Ctx.Diag->Report(SymCtx.FA->D->getLocation(),
- PrintAsWarning ? diag::warn_library_missing_symbol
-: diag::err_library_missing_symbol)
+Ctx.Diag->Report(SymCtx.FA->Loc, PrintAsWarning
+ ? 
diag::warn_library_missing_symbol
+ : 
diag::err_library_missing_symbol)
 << SymName;
   });
 else
   Ctx.emitDiag([&]() {
-Ctx.Diag->Report(SymCtx.FA->D->getLocation(),
- PrintAsWarning ? diag::warn_library_hidden_symbol
-: diag::err_library_hidden_symbol)
+Ctx.Diag->Report(SymCtx.FA->Loc, PrintAsWarning
+ ? diag::warn_library_hidden_symbol
+ : diag::err_library_hidden_symbol)
 << SymName;
   });
   };
@@ -270,16 +270,14 @@ DylibVerifier::Result 
DylibVerifier::compareVisibility(const Record *R,
   if (R->isExported()) {
 if (!DR) {
   Ctx.emitDiag([&]() {
-Ctx.Diag->

  1   2   3   4   >