[PATCH] D119004: [NFC][analyzer] Allow CallDescriptions to be matched with CallExprs

2022-02-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D119004#3299971 , @NoQ wrote:

> The original `lookup()` isn't exactly precise either, it's just slightly more 
> precise as it has better access to path-sensitive information such as current 
> values of function pointers, but this doesn't necessarily help given that 
> these pointers can still be unknown. And when the information is not 
> available the lookup silently fails in both cases.
>
> But I can certainly get behind demotivating callers from calling the new 
> function unless they know what they're doing. Maybe `lookupAsWritten()` to 
> indicate that the function intentionally ignores the runtime state of the 
> program and looks at the syntax only?

I still don't see the benefit of introducing another API.
This is actually a difference between the `CallEvent` and a `CallExpr`, thus it 
has not much to do with the `CallDescription`. For choosing the right 
`matches()` overload inherently depends on knowing about the parameter, on 
which we overload on.
We should have this as a comment for the type `CallEvent`, and I'm okay with 
reminding users even at the `matches(CallExpr)` overload.
I'm still heavily against introducing a new API instead of an overload.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119004

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


[PATCH] D119094: [clang] Don't emit redundant warnings for 'return;'

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Makes sense to me, thanks!




Comment at: clang/lib/Sema/SemaStmt.cpp:4102
+if (FD->isInvalidDecl()) {
+  // Don't redundantly warn about "return;" if the return type is invalid.
+} else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {

The comment in the test helped me understand this case better. I'd find "(The 
intended return type may have been void)" a useful hint here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119094

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


[PATCH] D118104: Make run-clang-tidy.py print the configured checks correctly

2022-02-07 Thread Jesko Appelfeller via Phabricator via cfe-commits
JesApp added a comment.

I'm not so much opposed to writing a test case for the one change I made 
(especially after @salman-javed-nz suggestion) as I am opposed to learning the 
build system. I've tried to set for a few minutes and oh man, that's a lot of 
targets...

So yeah, If someone could merge it like this, I'd be grateful.


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

https://reviews.llvm.org/D118104

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


[clang] 65adf7c - [NFC][Analyzer] Use range based for loop.

2022-02-07 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-02-07T15:45:58+08:00
New Revision: 65adf7c2117ab2b2ff72a8c761164fb2c1b686c0

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

LOG: [NFC][Analyzer] Use range based for loop.

Use range base loop loop to improve code readability.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp 
b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
index b152f9d80ef5b..323c002d0cef6 100644
--- a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -383,14 +383,14 @@ void 
AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
 }
 
 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
-  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
+  for (auto &I : DG) {
 
 // Skip ObjCMethodDecl, wait for the objc container to avoid
 // analyzing twice.
-if (isa(*I))
+if (isa(I))
   continue;
 
-LocalTUDecls.push_back(*I);
+LocalTUDecls.push_back(I);
   }
 }
 
@@ -462,11 +462,9 @@ void AnalysisConsumer::HandleDeclsCallGraph(const unsigned 
LocalTUDeclsSize) {
   SetOfConstDecls Visited;
   SetOfConstDecls VisitedAsTopLevel;
   llvm::ReversePostOrderTraversal RPOT(&CG);
-  for (llvm::ReversePostOrderTraversal::rpo_iterator
- I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
+  for (auto &N : RPOT) {
 NumFunctionTopLevel++;
 
-CallGraphNode *N = *I;
 Decl *D = N->getDecl();
 
 // Skip the abstract root node.



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


[PATCH] D119103: [NFC][Analyzer] Use range based for loop.

2022-02-07 Thread Jun Zhang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG65adf7c2117a: [NFC][Analyzer] Use range based for loop. 
(authored by junaire).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119103

Files:
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp


Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -383,14 +383,14 @@
 }
 
 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
-  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
+  for (auto &I : DG) {
 
 // Skip ObjCMethodDecl, wait for the objc container to avoid
 // analyzing twice.
-if (isa(*I))
+if (isa(I))
   continue;
 
-LocalTUDecls.push_back(*I);
+LocalTUDecls.push_back(I);
   }
 }
 
@@ -462,11 +462,9 @@
   SetOfConstDecls Visited;
   SetOfConstDecls VisitedAsTopLevel;
   llvm::ReversePostOrderTraversal RPOT(&CG);
-  for (llvm::ReversePostOrderTraversal::rpo_iterator
- I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
+  for (auto &N : RPOT) {
 NumFunctionTopLevel++;
 
-CallGraphNode *N = *I;
 Decl *D = N->getDecl();
 
 // Skip the abstract root node.


Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -383,14 +383,14 @@
 }
 
 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
-  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
+  for (auto &I : DG) {
 
 // Skip ObjCMethodDecl, wait for the objc container to avoid
 // analyzing twice.
-if (isa(*I))
+if (isa(I))
   continue;
 
-LocalTUDecls.push_back(*I);
+LocalTUDecls.push_back(I);
   }
 }
 
@@ -462,11 +462,9 @@
   SetOfConstDecls Visited;
   SetOfConstDecls VisitedAsTopLevel;
   llvm::ReversePostOrderTraversal RPOT(&CG);
-  for (llvm::ReversePostOrderTraversal::rpo_iterator
- I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
+  for (auto &N : RPOT) {
 NumFunctionTopLevel++;
 
-CallGraphNode *N = *I;
 Decl *D = N->getDecl();
 
 // Skip the abstract root node.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-02-07 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt:33
   LINK_LIBS
+  clangAnalysis
   clangTidy

njames93 wrote:
> Will this work under clangd as I don't think that links in the clangAnalysis 
> libraries @sammccall?
I did not check if it works and `clangd` does not explicitly link to 
`Analysis`, but only to the checks.
Doesn't the `LINK_LIBS` induce transitive dependency resolution for linking?



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp:102-105
+  // There have been crashes on 'Variable == nullptr', even though the matcher
+  // is not conditional. This comes probably from 'findAll'-matching.
+  if (!Variable || !LocalScope)
+return;

njames93 wrote:
> This sounds like a bug that should be raised with ASTMatchers, if its 
> reproducible.
I found no way to reproduce it (yet).
The crashes occured during verification on big projects and `run-clang-tidy` 
kind of obfuscated where the crash happened.

This is something for the iron out part of the check I think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[clang] 1cee960 - [SYCL] Disallow explicit casts between mismatching address spaces

2022-02-07 Thread Mariya Podchishchaeva via cfe-commits

Author: Mariya Podchishchaeva
Date: 2022-02-07T11:57:30+03:00
New Revision: 1cee9608982a866688434223bee44c878ea489b1

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

LOG: [SYCL] Disallow explicit casts between mismatching address spaces

Reviewed By: bader

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

Added: 


Modified: 
clang/lib/Sema/SemaCast.cpp
clang/test/CodeGenSYCL/address-space-conversions.cpp
clang/test/SemaSYCL/address-space-conversions.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index 7ef1732496c21..e9c1116257d66 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -2545,7 +2545,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, 
ExprResult &SrcExpr,
 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
  QualType DestType, bool CStyle,
  unsigned &msg, CastKind &Kind) {
-  if (!Self.getLangOpts().OpenCL)
+  if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice)
 // FIXME: As compiler doesn't have any information about overlapping addr
 // spaces at the moment we have to be permissive here.
 return TC_NotApplicable;

diff  --git a/clang/test/CodeGenSYCL/address-space-conversions.cpp 
b/clang/test/CodeGenSYCL/address-space-conversions.cpp
index e2fb755a29a6c..4f0484443d191 100644
--- a/clang/test/CodeGenSYCL/address-space-conversions.cpp
+++ b/clang/test/CodeGenSYCL/address-space-conversions.cpp
@@ -35,7 +35,7 @@ void usages() {
   __attribute__((opencl_global_host)) int *GLOBHOST;
 
   // Explicit conversions
-  // From names address spaces to default address space
+  // From named address spaces to default address space
   // CHECK-DAG: [[GLOB_LOAD:%[a-zA-Z0-9]+]] = load i32 addrspace(1)*, i32 
addrspace(1)* addrspace(4)* [[GLOB]].ascast
   // CHECK-DAG: [[GLOB_CAST:%[a-zA-Z0-9]+]] = addrspacecast i32 addrspace(1)* 
[[GLOB_LOAD]] to i32 addrspace(4)*
   // CHECK-DAG: store i32 addrspace(4)* [[GLOB_CAST]], i32 addrspace(4)* 
addrspace(4)* [[NoAS]].ascast

diff  --git a/clang/test/SemaSYCL/address-space-conversions.cpp 
b/clang/test/SemaSYCL/address-space-conversions.cpp
index d2e19b6f901d5..d8758248499de 100644
--- a/clang/test/SemaSYCL/address-space-conversions.cpp
+++ b/clang/test/SemaSYCL/address-space-conversions.cpp
@@ -55,6 +55,9 @@ void usages() {
   baz(NoAS);   // expected-error {{no matching 
function for call to 'baz'}}
   __attribute__((opencl_local)) int *l = NoAS; // expected-error {{cannot 
initialize a variable of type '__local int *' with an lvalue of type 'int *'}}
 
+  // Explicit casts between disjoint address spaces are disallowed
+  GLOB = (__attribute__((opencl_global)) int *)PRIV; // expected-error 
{{C-style cast from '__private int *' to '__global int *' converts between 
mismatching address spaces}}
+
   (void)static_cast(GLOB);
   (void)static_cast(GLOB);
   int *i = GLOB;



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


[PATCH] D118935: [SYCL] Disallow explicit casts between mismatching address spaces

2022-02-07 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1cee9608982a: [SYCL] Disallow explicit casts between 
mismatching address spaces (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118935

Files:
  clang/lib/Sema/SemaCast.cpp
  clang/test/CodeGenSYCL/address-space-conversions.cpp
  clang/test/SemaSYCL/address-space-conversions.cpp


Index: clang/test/SemaSYCL/address-space-conversions.cpp
===
--- clang/test/SemaSYCL/address-space-conversions.cpp
+++ clang/test/SemaSYCL/address-space-conversions.cpp
@@ -55,6 +55,9 @@
   baz(NoAS);   // expected-error {{no matching 
function for call to 'baz'}}
   __attribute__((opencl_local)) int *l = NoAS; // expected-error {{cannot 
initialize a variable of type '__local int *' with an lvalue of type 'int *'}}
 
+  // Explicit casts between disjoint address spaces are disallowed
+  GLOB = (__attribute__((opencl_global)) int *)PRIV; // expected-error 
{{C-style cast from '__private int *' to '__global int *' converts between 
mismatching address spaces}}
+
   (void)static_cast(GLOB);
   (void)static_cast(GLOB);
   int *i = GLOB;
Index: clang/test/CodeGenSYCL/address-space-conversions.cpp
===
--- clang/test/CodeGenSYCL/address-space-conversions.cpp
+++ clang/test/CodeGenSYCL/address-space-conversions.cpp
@@ -35,7 +35,7 @@
   __attribute__((opencl_global_host)) int *GLOBHOST;
 
   // Explicit conversions
-  // From names address spaces to default address space
+  // From named address spaces to default address space
   // CHECK-DAG: [[GLOB_LOAD:%[a-zA-Z0-9]+]] = load i32 addrspace(1)*, i32 
addrspace(1)* addrspace(4)* [[GLOB]].ascast
   // CHECK-DAG: [[GLOB_CAST:%[a-zA-Z0-9]+]] = addrspacecast i32 addrspace(1)* 
[[GLOB_LOAD]] to i32 addrspace(4)*
   // CHECK-DAG: store i32 addrspace(4)* [[GLOB_CAST]], i32 addrspace(4)* 
addrspace(4)* [[NoAS]].ascast
Index: clang/lib/Sema/SemaCast.cpp
===
--- clang/lib/Sema/SemaCast.cpp
+++ clang/lib/Sema/SemaCast.cpp
@@ -2545,7 +2545,7 @@
 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
  QualType DestType, bool CStyle,
  unsigned &msg, CastKind &Kind) {
-  if (!Self.getLangOpts().OpenCL)
+  if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice)
 // FIXME: As compiler doesn't have any information about overlapping addr
 // spaces at the moment we have to be permissive here.
 return TC_NotApplicable;


Index: clang/test/SemaSYCL/address-space-conversions.cpp
===
--- clang/test/SemaSYCL/address-space-conversions.cpp
+++ clang/test/SemaSYCL/address-space-conversions.cpp
@@ -55,6 +55,9 @@
   baz(NoAS);   // expected-error {{no matching function for call to 'baz'}}
   __attribute__((opencl_local)) int *l = NoAS; // expected-error {{cannot initialize a variable of type '__local int *' with an lvalue of type 'int *'}}
 
+  // Explicit casts between disjoint address spaces are disallowed
+  GLOB = (__attribute__((opencl_global)) int *)PRIV; // expected-error {{C-style cast from '__private int *' to '__global int *' converts between mismatching address spaces}}
+
   (void)static_cast(GLOB);
   (void)static_cast(GLOB);
   int *i = GLOB;
Index: clang/test/CodeGenSYCL/address-space-conversions.cpp
===
--- clang/test/CodeGenSYCL/address-space-conversions.cpp
+++ clang/test/CodeGenSYCL/address-space-conversions.cpp
@@ -35,7 +35,7 @@
   __attribute__((opencl_global_host)) int *GLOBHOST;
 
   // Explicit conversions
-  // From names address spaces to default address space
+  // From named address spaces to default address space
   // CHECK-DAG: [[GLOB_LOAD:%[a-zA-Z0-9]+]] = load i32 addrspace(1)*, i32 addrspace(1)* addrspace(4)* [[GLOB]].ascast
   // CHECK-DAG: [[GLOB_CAST:%[a-zA-Z0-9]+]] = addrspacecast i32 addrspace(1)* [[GLOB_LOAD]] to i32 addrspace(4)*
   // CHECK-DAG: store i32 addrspace(4)* [[GLOB_CAST]], i32 addrspace(4)* addrspace(4)* [[NoAS]].ascast
Index: clang/lib/Sema/SemaCast.cpp
===
--- clang/lib/Sema/SemaCast.cpp
+++ clang/lib/Sema/SemaCast.cpp
@@ -2545,7 +2545,7 @@
 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
  QualType DestType, bool CStyle,
  unsigned &msg, CastKind &Kind) {
-  if (!Self.getLangOpts().OpenCL)
+  if (!Self.getLangOpts().OpenCL && !Self.getLangOp

[PATCH] D119071: [Driver][OpenBSD] -r: imply -nostdlib like GCC

2022-02-07 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119071

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


[clang] 1831cbd - [Driver][OpenBSD] -r: imply -nostdlib like GCC

2022-02-07 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2022-02-07T04:07:30-05:00
New Revision: 1831cbd9d4174a93d4017e510ecf0f840af5f7d6

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

LOG: [Driver][OpenBSD] -r: imply -nostdlib like GCC

Similar to D116843 for Gnu.cpp

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/test/Driver/openbsd.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index 96abac57764f7..bcd54bedfa897 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -160,7 +160,8 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 const char *crt0 = nullptr;
 const char *crtbegin = nullptr;
 if (!Args.hasArg(options::OPT_shared)) {
@@ -191,7 +192,8 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
 // Use the static OpenMP runtime with -static-openmp
 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
 !Args.hasArg(options::OPT_static);
@@ -234,7 +236,8 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 CmdArgs.push_back("-lcompiler_rt");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 const char *crtend = nullptr;
 if (!Args.hasArg(options::OPT_shared))
   crtend = "crtend.o";

diff  --git a/clang/test/Driver/openbsd.c b/clang/test/Driver/openbsd.c
index c2ffe2a0397cd..d6d5ae994e67e 100644
--- a/clang/test/Driver/openbsd.c
+++ b/clang/test/Driver/openbsd.c
@@ -40,8 +40,9 @@
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-LD %s
 // RUN: %clang -no-canonical-prefixes -target mips64el-unknown-openbsd %s -### 
2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-LD %s
-// CHECK-LD-R: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-R: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-r" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-R: "-r"
+// CHECK-LD-R-NOT: "-l
+// CHECK-LD-R-NOT: crt{{[^.]+}}.o
 // CHECK-LD-S: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
 // CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-s" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
 // CHECK-LD-T: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"



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


[PATCH] D119071: [Driver][OpenBSD] -r: imply -nostdlib like GCC

2022-02-07 Thread Brad Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1831cbd9d417: [Driver][OpenBSD] -r: imply -nostdlib like GCC 
(authored by brad).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119071

Files:
  clang/lib/Driver/ToolChains/OpenBSD.cpp
  clang/test/Driver/openbsd.c


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -40,8 +40,9 @@
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-LD %s
 // RUN: %clang -no-canonical-prefixes -target mips64el-unknown-openbsd %s -### 
2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-LD %s
-// CHECK-LD-R: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-R: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-r" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-R: "-r"
+// CHECK-LD-R-NOT: "-l
+// CHECK-LD-R-NOT: crt{{[^.]+}}.o
 // CHECK-LD-S: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
 // CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-s" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
 // CHECK-LD-T: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -160,7 +160,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 const char *crt0 = nullptr;
 const char *crtbegin = nullptr;
 if (!Args.hasArg(options::OPT_shared)) {
@@ -191,7 +192,8 @@
   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
 // Use the static OpenMP runtime with -static-openmp
 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
 !Args.hasArg(options::OPT_static);
@@ -234,7 +236,8 @@
 CmdArgs.push_back("-lcompiler_rt");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 const char *crtend = nullptr;
 if (!Args.hasArg(options::OPT_shared))
   crtend = "crtend.o";


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -40,8 +40,9 @@
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-LD %s
 // RUN: %clang -no-canonical-prefixes -target mips64el-unknown-openbsd %s -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-LD %s
-// CHECK-LD-R: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-R: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" "-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-r" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
+// CHECK-LD-R: "-r"
+// CHECK-LD-R-NOT: "-l
+// CHECK-LD-R-NOT: crt{{[^.]+}}.o
 // CHECK-LD-S: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
 // CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" "-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-s" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-LD-T: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -160,7 +160,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 const char *crt0 = nullptr;
 const char *crtbegin = nullptr;
 if (!Args.hasArg(options::OPT_shared)) {
@@ -191,7 +192,8 @@
   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+

[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt:33
   LINK_LIBS
+  clangAnalysis
   clangTidy

JonasToth wrote:
> njames93 wrote:
> > Will this work under clangd as I don't think that links in the 
> > clangAnalysis libraries @sammccall?
> I did not check if it works and `clangd` does not explicitly link to 
> `Analysis`, but only to the checks.
> Doesn't the `LINK_LIBS` induce transitive dependency resolution for linking?
I don't know whether you need to add it everywhere, I suspect transitive is OK.

In any case this isn't a new dependency, Sema depends on Analysis and clangd 
depends on Sema.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp:29
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  return ast_matchers::internal::matchesFirstInPointerRange(
+  InnerMatcher, Node.decl_begin(), Node.decl_end(), Finder, Builder);

This returns an iterator (i.e. a pointer), which is being converted to a 
boolean.

i.e. it's always returning true. I think this is why you're seeing nullptr 
crashes on Variable.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp:29
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  return ast_matchers::internal::matchesFirstInPointerRange(
+  InnerMatcher, Node.decl_begin(), Node.decl_end(), Finder, Builder);

sammccall wrote:
> This returns an iterator (i.e. a pointer), which is being converted to a 
> boolean.
> 
> i.e. it's always returning true. I think this is why you're seeing nullptr 
> crashes on Variable.
this is depending on `::internal` details, which doesn't seem OK.
I think you'd need to find another way to do it, or move this to ASTMatchers 
(in a separate patch).



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp:102-105
+  // There have been crashes on 'Variable == nullptr', even though the matcher
+  // is not conditional. This comes probably from 'findAll'-matching.
+  if (!Variable || !LocalScope)
+return;

JonasToth wrote:
> njames93 wrote:
> > This sounds like a bug that should be raised with ASTMatchers, if its 
> > reproducible.
> I found no way to reproduce it (yet).
> The crashes occured during verification on big projects and `run-clang-tidy` 
> kind of obfuscated where the crash happened.
> 
> This is something for the iron out part of the check I think.
This is a bug in a helper added in this patch, I've added a comment above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Thanks for the patch!

Could you add some tests to 
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp as well?

I wrote a bit about how the tests work on Discord, copying for convenience:

> In SemanticHighlightingTests.cpp, we have code inputs which are annotated 
> with the highlighting kinds (and in some tests, modifiers) that various 
> tokens should get.
> You can build the test suite with `ninja ClangdTests`
> Then you can run an individual test case using a command like 
> `./tools/clang/tools/extra/clangd/unittests/ClangdTests 
> --gtest_filter=SemanticHighlighting.MyTestName`


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

https://reviews.llvm.org/D119077

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


[PATCH] D114533: LLVM IR should allow bitcast between address spaces with the same size.

2022-02-07 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 updated this revision to Diff 406351.
skc7 added a comment.

Rebase


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

https://reviews.llvm.org/D114533

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  llvm/docs/LangRef.rst
  llvm/include/llvm/Analysis/InstSimplifyFolder.h
  llvm/include/llvm/Analysis/TargetFolder.h
  llvm/include/llvm/IR/ConstantFolder.h
  llvm/include/llvm/IR/Constants.h
  llvm/include/llvm/IR/IRBuilder.h
  llvm/include/llvm/IR/IRBuilderFolder.h
  llvm/include/llvm/IR/InstrTypes.h
  llvm/include/llvm/IR/Instructions.h
  llvm/include/llvm/IR/NoFolder.h
  llvm/lib/Analysis/ConstantFolding.cpp
  llvm/lib/Analysis/LoopUnrollAnalyzer.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Constants.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/Coroutines/Coroutines.cpp
  llvm/lib/Transforms/Utils/VNCoercion.cpp
  llvm/test/Transforms/GVN/gvn-eliminate-inttoptr-ptrtoint-for-load.ll
  llvm/test/Transforms/GVN/gvn-eliminate-inttoptr-ptrtoint-for-vector-load.ll
  
llvm/test/Transforms/GVN/gvn-eliminate-inttoptr-ptrtoint-for-vector-ptr-load.ll
  llvm/test/Verifier/bitcast-vector-pointer-as-neg.ll
  llvm/test/Verifier/bitcast-vector-pointer-different-addrspace-illegal.ll
  llvm/test/Verifier/bitcast-vector-pointer-neg.ll
  llvm/test/Verifier/bitcast-vector-pointer-pos.ll
  llvm/test/Verifier/bitcast-vector-pointer-same-addrspace.ll
  llvm/unittests/IR/InstructionsTest.cpp

Index: llvm/unittests/IR/InstructionsTest.cpp
===
--- llvm/unittests/IR/InstructionsTest.cpp
+++ llvm/unittests/IR/InstructionsTest.cpp
@@ -189,6 +189,10 @@
 TEST(InstructionsTest, CastInst) {
   LLVMContext C;
 
+  DataLayout DL("e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-"
+"p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-"
+"v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-ni:7");
+
   Type *Int8Ty = Type::getInt8Ty(C);
   Type *Int16Ty = Type::getInt16Ty(C);
   Type *Int32Ty = Type::getInt32Ty(C);
@@ -217,7 +221,11 @@
   Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1);
   Type *Int64PtrAS1Ty = PointerType::get(Int64Ty, 1);
 
+  Type *Int32PtrAS2Ty = PointerType::get(Int32Ty, 2);
+  Type *Int32PtrAS3Ty = PointerType::get(Int32Ty, 3);
+
   Type *V2Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 2);
+  Type *V2Int32PtrAS2Ty = FixedVectorType::get(Int32PtrAS2Ty, 2);
   Type *V2Int64PtrAS1Ty = FixedVectorType::get(Int64PtrAS1Ty, 2);
   Type *V4Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 4);
   Type *VScaleV4Int32PtrAS1Ty = ScalableVectorType::get(Int32PtrAS1Ty, 4);
@@ -238,50 +246,52 @@
   EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true));
   EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true));
 
-  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy));
-  EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty));
-  EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy));
-  EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty));
-  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty));
-
-  // Check address space casts are rejected since we don't know the sizes here
-  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty));
-  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy));
-  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty));
-  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy));
-  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty));
+  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty, DL));
+
+  // Check validity of casts here
+  EXPECT_TRUE(CastInst::isBitCastable(Int32PtrAS2Ty, Int32PtrAS3Ty, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrAS2Ty, DL));
+  EXPECT_TRUE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty, DL));
+  EXPECT_TRUE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy, DL));
+  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty, DL));
+  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy, DL));
+  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty, DL));
+  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrAS2Ty, DL));
   EXPECT_EQ(CastInst::AddrSpaceCast, CastInst::getCastOpcode(v2ptr32, true,
  V2Int32PtrAS1Ty,
  true));
 
   // Test mismatched number of elements for pointers
-  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int64PtrAS1Ty));
-  EXPECT_FALSE(CastInst::isBitCastable(V4Int64P

[PATCH] D104044: [clang-format] Fix the issue that empty lines being removed at the beginning of namespace

2022-02-07 Thread Yan via Phabricator via cfe-commits
pem added a comment.

I am looking forward for this // EmptyLineInsertion// feature.

In D104044#2813515 , @MyDeveloperDay 
wrote:

> Do we need a set options for when we want to insert/retain/add a newline 
> after various constructs? frankly I've been mulling over the concept of 
> adding a
>
>   NewLinesBetweenFunctions: 1
>
> I personally don't like code written like this as I find it hard to read, I'd 
> like to be able to mandate a single line between functions
>
>   void foo()
>   {
>   ...
>   }
>   void bar()
>   {
>   ...
>   }
>   void foobar()
>   {
>   ...
>   }
>
> I prefer when its written as:
>
>   void foo()
>   {
>   ...
>   }
>   
>   void bar()
>   {
>   ...
>   }
>   
>   void foobar()
>   {
>   ...
>   }
>
> Maybe we even need a more generalised mechanism that would allow alot of 
> flexibility letting people control their own specific style.
>
>   EmptyLineInsertionStyle: Custom
> AfterNameSpaceOpeningBrace: 1
> BeforeNameSpaceClosingBrace: 1
> BetweenFunctions: 2
> AfterClassOpeningBrace: 1
> BeforeClassClosingBrace: 1
> AfterAccessModifier : 1
> BeforeAccessModifier: 1




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104044

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

I haven't looked at the patch in detail, but one high level question: have you 
considered the possibility of adding these highlightings during the 
findExplicitReferences 

 phase, rather than in `CollectExtraHighlightings`? (I haven't thought through 
whether that would work, just wondering if you have. The reason this is worth 
asking is that if we can get `findExplicitReferences` to handle overloaded 
operator calls, other clangd features that use `findExplicitReferences` would 
benefit from knowing about such calls as well.)




Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:662
 
-// FIXME ...here it would make sense though.
+// Already handled by VisitCXXOperatorCallExpr.
 if (isa(E))

This FIXME was specifically about highlighting mutable reference arguments for 
overloaded operator calls, so it remains unfixed. (I realize that wasn't super 
clear.)


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

https://reviews.llvm.org/D119077

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


[PATCH] D113874: [clang] Propagate requires-clause from constructor template to implicit deduction guide

2022-02-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added reviewers: kadircet, sammccall.
nridge added a comment.

Adding some potential reviewers.

I'm open to testing this some way other than through clangd, but note that, 
while the issue is not in AST serialization code, it only trips an assertion 
after a serialization round-trip.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113874

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


[PATCH] D117500: [clang] Mention MS on-demand TLS initialization in release notes

2022-02-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans closed this revision.
hans added a comment.

Oh, right. And since the change landed before the branch, this should go on the 
14.x release branch. Landed here: 
https://github.com/llvm/llvm-project/commit/20ea9e379984f240d7135843baae6999abf3bf2b


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117500

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


[PATCH] D119116: [clangd] Pull AST printer helpers to Clang

2022-02-07 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added projects: clang, clang-tools-extra.

This will be needed for pulling out the stdlib header handlers from clangd into
Clang.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119116

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp

Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -5191,3 +5191,31 @@
 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   return new (C, ID) ExportDecl(nullptr, SourceLocation());
 }
+
+//===--===//
+// Helpers
+//===--===//
+
+std::string clang::printQualifiedName(const NamedDecl &ND) {
+  std::string QName;
+  llvm::raw_string_ostream OS(QName);
+  clang::PrintingPolicy Policy(ND.getASTContext().getLangOpts());
+  // Note that inline namespaces are treated as transparent scopes. This
+  // reflects the way they're most commonly used for lookup. Ideally we'd
+  // include them, but at query time it's hard to find all the inline
+  // namespaces to query: the preamble doesn't have a dedicated list.
+  Policy.SuppressUnwrittenScope = true;
+  ND.printQualifiedName(OS, Policy);
+  OS.flush();
+  assert(!StringRef(QName).startswith("::"));
+  return QName;
+}
+
+/// Returns the first enclosing namespace scope starting from \p DC.
+std::string printNamespaceScope(const DeclContext &DC) {
+  for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
+if (const auto *NS = dyn_cast(Ctx))
+  if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
+return clang::printQualifiedName(*NS) + "::";
+  return "";
+}
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -4659,6 +4659,13 @@
   return "$ompvariant";
 }
 
+/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes
+/// like inline namespaces.
+std::string printQualifiedName(const NamedDecl &ND);
+
+/// Returns the first enclosing namespace scope starting from \p DC.
+std::string printNamespaceScope(const DeclContext &DC);
+
 } // namespace clang
 
 #endif // LLVM_CLANG_AST_DECL_H
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -42,13 +42,6 @@
 /// this function.
 SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM);
 
-/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes
-/// like inline namespaces.
-std::string printQualifiedName(const NamedDecl &ND);
-
-/// Returns the first enclosing namespace scope starting from \p DC.
-std::string printNamespaceScope(const DeclContext &DC);
-
 /// Returns the name of the namespace inside the 'using namespace' directive, as
 /// written in the code. E.g., passing 'using namespace ::std' will result in
 /// '::std'.
Index: clang-tools-extra/clangd/AST.cpp
===
--- clang-tools-extra/clangd/AST.cpp
+++ clang-tools-extra/clangd/AST.cpp
@@ -171,21 +171,6 @@
   return SM.getExpansionLoc(L);
 }
 
-std::string printQualifiedName(const NamedDecl &ND) {
-  std::string QName;
-  llvm::raw_string_ostream OS(QName);
-  PrintingPolicy Policy(ND.getASTContext().getLangOpts());
-  // Note that inline namespaces are treated as transparent scopes. This
-  // reflects the way they're most commonly used for lookup. Ideally we'd
-  // include them, but at query time it's hard to find all the inline
-  // namespaces to query: the preamble doesn't have a dedicated list.
-  Policy.SuppressUnwrittenScope = true;
-  ND.printQualifiedName(OS, Policy);
-  OS.flush();
-  assert(!StringRef(QName).startswith("::"));
-  return QName;
-}
-
 static bool isAnonymous(const DeclarationName &N) {
   return N.isIdentifier() && !N.getAsIdentifierInfo();
 }
@@ -280,14 +265,6 @@
   return TemplateArgs;
 }
 
-std::string printNamespaceScope(const DeclContext &DC) {
-  for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
-if (const auto *NS = dyn_cast(Ctx))
-  if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
-return printQualifiedName(*NS) + "::";
-  return "";
-}
-
 static llvm::StringRef
 getNameOrErrForObjCInterface(const ObjCInterfaceDecl *ID) {
   return ID ? ID->getName() : "<>";
___
cfe-commits mailing list
cfe-commits@lists.llvm

[PATCH] D118976: clangd: Set a diagnostic on a code action resulting from a tweak

2022-02-07 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler updated this revision to Diff 406359.
ckandeler added a comment.

Fixed Lint complaints


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118976

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp


Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -986,8 +986,8 @@
 
   // Now enumerate the semantic code actions.
   auto ConsumeActions =
-  [Reply = std::move(Reply), File, Selection = Params.range,
-   FixIts = std::move(FixIts), this](
+  [Diags = Params.context.diagnostics, Reply = std::move(Reply), File,
+   Selection = Params.range, FixIts = std::move(FixIts), this](
   llvm::Expected> Tweaks) mutable {
 if (!Tweaks)
   return Reply(Tweaks.takeError());
@@ -1003,13 +1003,17 @@
 for (auto &Action : Actions) {
   if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
 if (OnlyFix) {
-  OnlyFix->isPreferred = false;
+  OnlyFix = nullptr;
   break;
 }
-Action.isPreferred = true;
 OnlyFix = &Action;
   }
 }
+if (OnlyFix) {
+  OnlyFix->isPreferred = true;
+  if (Diags.size() == 1 && Diags.front().range == Selection)
+OnlyFix->diagnostics = {Diags.front()};
+}
 
 if (SupportsCodeAction)
   return Reply(llvm::json::Array(Actions));


Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -986,8 +986,8 @@
 
   // Now enumerate the semantic code actions.
   auto ConsumeActions =
-  [Reply = std::move(Reply), File, Selection = Params.range,
-   FixIts = std::move(FixIts), this](
+  [Diags = Params.context.diagnostics, Reply = std::move(Reply), File,
+   Selection = Params.range, FixIts = std::move(FixIts), this](
   llvm::Expected> Tweaks) mutable {
 if (!Tweaks)
   return Reply(Tweaks.takeError());
@@ -1003,13 +1003,17 @@
 for (auto &Action : Actions) {
   if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
 if (OnlyFix) {
-  OnlyFix->isPreferred = false;
+  OnlyFix = nullptr;
   break;
 }
-Action.isPreferred = true;
 OnlyFix = &Action;
   }
 }
+if (OnlyFix) {
+  OnlyFix->isPreferred = true;
+  if (Diags.size() == 1 && Diags.front().range == Selection)
+OnlyFix->diagnostics = {Diags.front()};
+}
 
 if (SupportsCodeAction)
   return Reply(llvm::json::Array(Actions));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119117: [clang-format] Fix formatting of the array form of delete.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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

There was an inconsistency in formatting of delete expressions.

Before:

  delete (void*)a;
  delete[](void*) a;

After this patch:

  delete (void*)a;
  delete[] (void*)a;


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119117

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -91,6 +91,28 @@
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_RecordLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsNewAndDelete) {
+  auto Tokens = annotate("delete (void *)p;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] /*comment*/ (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[/*comment*/] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete/*comment*/[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9725,6 +9725,7 @@
"new (aa(aaa))\n"
"typename ();");
   verifyFormat("delete[] h->p;");
+  verifyFormat("delete[] (void *)p;");
 
   verifyFormat("void operator delete(void *foo) ATTRIB;");
   verifyFormat("void operator new(void *foo) ATTRIB;");
@@ -20009,15 +20010,13 @@
 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
getLLVMStyleWithColumns(35));
-  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
-   getLLVMStyleWithColumns(31));
+  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", getLLVMStyleWithColumns(31));
   verifyFormat("// Однажды в студёную зимнюю пору...",
getLLVMStyleWithColumns(36));
   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
   verifyFormat("/* Однажды в студёную зимнюю пору... */",
getLLVMStyleWithColumns(39));
-  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
-   getLLVMStyleWithColumns(35));
+  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", getLLVMStyleWithColumns(35));
 }
 
 TEST_F(FormatTest, SplitsUTF8Strings) {
@@ -20037,21 +20036,20 @@
 "\"пору,\"",
 format("\"Однажды, в студёную зимнюю пору,\"",
getLLVMStyleWithColumns(13)));
+  EXPECT_EQ("\"一 二 三 \"\n"
+"\"四 五六 \"\n"
+"\"七 八 九 \"\n"
+"\"十\"",
+format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
   EXPECT_EQ(
-  "\"一 二 三 \"\n"
-  "\"四 五六 \"\n"
-  "\"七 八 九 \"\n"
-  "\"十\"",
-  format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
-  EXPECT_EQ("\"一\t\"\n"
-"\"二 \t\"\n"
-"\"三 四 \"\n"
-"\"五\t\"\n"
-"\"六 \t\"\n"
-"\"七 \"\n"
-"\"八九十\tqq\"",
-format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
-   getLLVMStyleWithColumns(11)));
+  "\"一\t\"\n"
+  "\"二 \t\"\n"
+  "\"三 四 \"\n"
+  "\"五\t\"\n"
+  "\"六 \t\"\n"
+  "\"七 \"\n"
+  "\"八九十\tqq\"",
+  format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", getLLVMStyleWithColumns(11)));
 
   // UTF8 character in an escape sequence.
   EXPECT_EQ("\"aa\"\n"
@@ -20096,16 +20094,16 @@
 format("/* Гляжу, поднимается медленно в гору\n"
" * Лошадка, везущая хворосту воз. */",
getLLVMStyleWithColumns(13)));
-  EXPECT_EQ(
-  "/* 一二三\n

[PATCH] D119008: Add Cortex-X1C to Clang LLVM 14 release notes

2022-02-07 Thread Amilendra Kodithuwakku via Phabricator via cfe-commits
amilendra added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119008

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


[PATCH] D119117: [clang-format] Fix formatting of the array form of delete.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 406363.
curdeius added a comment.

Revert unrelated changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119117

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -91,6 +91,28 @@
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_RecordLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsNewAndDelete) {
+  auto Tokens = annotate("delete (void *)p;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] /*comment*/ (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[/*comment*/] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete/*comment*/[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9725,6 +9725,7 @@
"new 
(aa(aaa))\n"
"typename ();");
   verifyFormat("delete[] h->p;");
+  verifyFormat("delete[] (void *)p;");
 
   verifyFormat("void operator delete(void *foo) ATTRIB;");
   verifyFormat("void operator new(void *foo) ATTRIB;");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1883,6 +1883,25 @@
 LeftOfParens = LeftOfParens->MatchingParen->Previous;
   }
 
+  if (LeftOfParens->is(tok::r_square)) {
+//   delete[] (void *)ptr;
+auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
+  if (Tok->isNot(tok::r_square))
+return nullptr;
+
+  Tok = Tok->getPreviousNonComment();
+  if (!Tok || Tok->isNot(tok::l_square))
+return nullptr;
+
+  Tok = Tok->getPreviousNonComment();
+  if (!Tok || Tok->isNot(tok::kw_delete))
+return nullptr;
+  return Tok;
+};
+if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
+  LeftOfParens = MaybeDelete;
+  }
+
   // The Condition directly below this one will see the operator arguments
   // as a (void *foo) cast.
   //   void operator delete(void *foo) ATTRIB;
@@ -3227,7 +3246,10 @@
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
-  if (Left.isOneOf(tok::kw_new, tok::kw_delete))
+  if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
+  (Left.is(tok::r_square) && Left.MatchingParen &&
+   Left.MatchingParen->Previous &&
+   Left.MatchingParen->Previous->is(tok::kw_delete)))
 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
spaceRequiredBeforeParens(Right);
 }


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -91,6 +91,28 @@
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_RecordLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsNewAndDelete) {
+  auto Tokens = annotate("delete (void *)p;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] /*comment*/ (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[/*comment*/] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete/*comment*/[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+}
+
 } /

[PATCH] D119116: [clangd] Pull AST printer helpers to Clang

2022-02-07 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 406367.
kbobyrev added a comment.

Fix the build


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119116

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp

Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -5191,3 +5191,31 @@
 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   return new (C, ID) ExportDecl(nullptr, SourceLocation());
 }
+
+//===--===//
+// Helpers
+//===--===//
+
+std::string clang::printQualifiedName(const NamedDecl &ND) {
+  std::string QName;
+  llvm::raw_string_ostream OS(QName);
+  clang::PrintingPolicy Policy(ND.getASTContext().getLangOpts());
+  // Note that inline namespaces are treated as transparent scopes. This
+  // reflects the way they're most commonly used for lookup. Ideally we'd
+  // include them, but at query time it's hard to find all the inline
+  // namespaces to query: the preamble doesn't have a dedicated list.
+  Policy.SuppressUnwrittenScope = true;
+  ND.printQualifiedName(OS, Policy);
+  OS.flush();
+  assert(!StringRef(QName).startswith("::"));
+  return QName;
+}
+
+/// Returns the first enclosing namespace scope starting from \p DC.
+std::string clang::printNamespaceScope(const DeclContext &DC) {
+  for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
+if (const auto *NS = dyn_cast(Ctx))
+  if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
+return clang::printQualifiedName(*NS) + "::";
+  return "";
+}
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -4659,6 +4659,13 @@
   return "$ompvariant";
 }
 
+/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes
+/// like inline namespaces.
+std::string printQualifiedName(const NamedDecl &ND);
+
+/// Returns the first enclosing namespace scope starting from \p DC.
+std::string printNamespaceScope(const DeclContext &DC);
+
 } // namespace clang
 
 #endif // LLVM_CLANG_AST_DECL_H
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -42,13 +42,6 @@
 /// this function.
 SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM);
 
-/// Returns the qualified name of ND. The scope doesn't contain unwritten scopes
-/// like inline namespaces.
-std::string printQualifiedName(const NamedDecl &ND);
-
-/// Returns the first enclosing namespace scope starting from \p DC.
-std::string printNamespaceScope(const DeclContext &DC);
-
 /// Returns the name of the namespace inside the 'using namespace' directive, as
 /// written in the code. E.g., passing 'using namespace ::std' will result in
 /// '::std'.
Index: clang-tools-extra/clangd/AST.cpp
===
--- clang-tools-extra/clangd/AST.cpp
+++ clang-tools-extra/clangd/AST.cpp
@@ -171,21 +171,6 @@
   return SM.getExpansionLoc(L);
 }
 
-std::string printQualifiedName(const NamedDecl &ND) {
-  std::string QName;
-  llvm::raw_string_ostream OS(QName);
-  PrintingPolicy Policy(ND.getASTContext().getLangOpts());
-  // Note that inline namespaces are treated as transparent scopes. This
-  // reflects the way they're most commonly used for lookup. Ideally we'd
-  // include them, but at query time it's hard to find all the inline
-  // namespaces to query: the preamble doesn't have a dedicated list.
-  Policy.SuppressUnwrittenScope = true;
-  ND.printQualifiedName(OS, Policy);
-  OS.flush();
-  assert(!StringRef(QName).startswith("::"));
-  return QName;
-}
-
 static bool isAnonymous(const DeclarationName &N) {
   return N.isIdentifier() && !N.getAsIdentifierInfo();
 }
@@ -280,14 +265,6 @@
   return TemplateArgs;
 }
 
-std::string printNamespaceScope(const DeclContext &DC) {
-  for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
-if (const auto *NS = dyn_cast(Ctx))
-  if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
-return printQualifiedName(*NS) + "::";
-  return "";
-}
-
 static llvm::StringRef
 getNameOrErrForObjCInterface(const ObjCInterfaceDecl *ID) {
   return ID ? ID->getName() : "<>";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119011: [clang] Cache OpenCL types

2022-02-07 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119011

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


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/include/flang/Frontend/FrontendActions.h:150
+//===--===//
+class CodeGenAction : public FrontendAction {
+

schweitz wrote:
> This appears in a header file. Should there be doxygen comments?
Good point, I'll add something here.



Comment at: flang/include/flang/Frontend/FrontendActions.h:160
+  std::unique_ptr mlirModule_;
+  std::unique_ptr mlirCtx_;
+  /// }

schweitz wrote:
> The LLVM coding conventions do not require trailing undescores.
Good point, I'll change this. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118985

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


[clang] c15782b - [OpenCL] opencl-c.h: make attribute order consistent; NFC

2022-02-07 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2022-02-07T10:54:55Z
New Revision: c15782bcf5c900fc43fd545c9572f77ef92c5f5e

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

LOG: [OpenCL] opencl-c.h: make attribute order consistent; NFC

For most builtins, `__purefn` always comes after `__ovld`, but the
read_image functions did not follow this pattern.

Added: 


Modified: 
clang/lib/Headers/opencl-c.h

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 059a2ec2371bd..6e5733249ee4c 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -15427,123 +15427,123 @@ half16 __ovld __cnfn shuffle2(half16 x, half16 y, 
ushort16 mask);
  * in the description above are undefined.
  */
 
-float4 __purefn __ovld read_imagef(read_only image2d_t image, sampler_t 
sampler, int2 coord);
-float4 __purefn __ovld read_imagef(read_only image2d_t image, sampler_t 
sampler, float2 coord);
+float4 __ovld __purefn read_imagef(read_only image2d_t image, sampler_t 
sampler, int2 coord);
+float4 __ovld __purefn read_imagef(read_only image2d_t image, sampler_t 
sampler, float2 coord);
 
-int4 __purefn __ovld read_imagei(read_only image2d_t image, sampler_t sampler, 
int2 coord);
-int4 __purefn __ovld read_imagei(read_only image2d_t image, sampler_t sampler, 
float2 coord);
-uint4 __purefn __ovld read_imageui(read_only image2d_t image, sampler_t 
sampler, int2 coord);
-uint4 __purefn __ovld read_imageui(read_only image2d_t image, sampler_t 
sampler, float2 coord);
+int4 __ovld __purefn read_imagei(read_only image2d_t image, sampler_t sampler, 
int2 coord);
+int4 __ovld __purefn read_imagei(read_only image2d_t image, sampler_t sampler, 
float2 coord);
+uint4 __ovld __purefn read_imageui(read_only image2d_t image, sampler_t 
sampler, int2 coord);
+uint4 __ovld __purefn read_imageui(read_only image2d_t image, sampler_t 
sampler, float2 coord);
 
-float4 __purefn __ovld read_imagef(read_only image3d_t image, sampler_t 
sampler, int4 coord);
-float4 __purefn __ovld read_imagef(read_only image3d_t image, sampler_t 
sampler, float4 coord);
+float4 __ovld __purefn read_imagef(read_only image3d_t image, sampler_t 
sampler, int4 coord);
+float4 __ovld __purefn read_imagef(read_only image3d_t image, sampler_t 
sampler, float4 coord);
 
-int4 __purefn __ovld read_imagei(read_only image3d_t image, sampler_t sampler, 
int4 coord);
-int4 __purefn __ovld read_imagei(read_only image3d_t image, sampler_t sampler, 
float4 coord);
-uint4 __purefn __ovld read_imageui(read_only image3d_t image, sampler_t 
sampler, int4 coord);
-uint4 __purefn __ovld read_imageui(read_only image3d_t image, sampler_t 
sampler, float4 coord);
+int4 __ovld __purefn read_imagei(read_only image3d_t image, sampler_t sampler, 
int4 coord);
+int4 __ovld __purefn read_imagei(read_only image3d_t image, sampler_t sampler, 
float4 coord);
+uint4 __ovld __purefn read_imageui(read_only image3d_t image, sampler_t 
sampler, int4 coord);
+uint4 __ovld __purefn read_imageui(read_only image3d_t image, sampler_t 
sampler, float4 coord);
 
 #if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_1_2)
-float4 __purefn __ovld read_imagef(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
-float4 __purefn __ovld read_imagef(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
+float4 __ovld __purefn read_imagef(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
+float4 __ovld __purefn read_imagef(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
 
-int4 __purefn __ovld read_imagei(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
-int4 __purefn __ovld read_imagei(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
-uint4 __purefn __ovld read_imageui(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
-uint4 __purefn __ovld read_imageui(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
+int4 __ovld __purefn read_imagei(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
+int4 __ovld __purefn read_imagei(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
+uint4 __ovld __purefn read_imageui(read_only image2d_array_t image_array, 
sampler_t sampler, int4 coord);
+uint4 __ovld __purefn read_imageui(read_only image2d_array_t image_array, 
sampler_t sampler, float4 coord);
 #endif // defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_1_2)
 
-float4 __purefn __ovld read_imagef(read_only image1d_t image, sampler_t 
sampler, int coord);
-float4 __purefn __ovld read_imagef(read_only image1d_t image, sampler_t 
sampler, float coord);
+float4 __ovld __purefn read_imagef(read_on

[PATCH] D114439: [Annotation] Allow parameter pack expansions and initializer lists in annotate attribute

2022-02-07 Thread Steffen Larsen via Phabricator via cfe-commits
steffenlarsen updated this revision to Diff 406373.
steffenlarsen added a comment.

Added a check to prevent duplicate "empty" constructors, i.e. if there are only 
optional arguments such as a single variadic argument.


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

https://reviews.llvm.org/D114439

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/annotate.c
  clang/test/SemaCXX/attr-annotate.cpp
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -202,9 +202,9 @@
 bool Fake;
 
   public:
-Argument(const Record &Arg, StringRef Attr)
-: lowerName(std::string(Arg.getValueAsString("Name"))),
-  upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
+Argument(StringRef Arg, StringRef Attr)
+: lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
+  isOpt(false), Fake(false) {
   if (!lowerName.empty()) {
 lowerName[0] = std::tolower(lowerName[0]);
 upperName[0] = std::toupper(upperName[0]);
@@ -215,6 +215,8 @@
   if (lowerName == "interface")
 lowerName = "interface_";
 }
+Argument(const Record &Arg, StringRef Attr)
+: Argument(Arg.getValueAsString("Name"), Attr) {}
 virtual ~Argument() = default;
 
 StringRef getLowerName() const { return lowerName; }
@@ -666,6 +668,11 @@
   ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
   RangeName(std::string(getLowerName())) {}
 
+VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
+: Argument(Arg, Attr), Type(std::move(T)),
+  ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
+  RangeName(std::string(getLowerName())) {}
+
 const std::string &getType() const { return Type; }
 const std::string &getArgName() const { return ArgName; }
 const std::string &getArgSizeName() const { return ArgSizeName; }
@@ -688,6 +695,18 @@
  << "); }\n";
 }
 
+void writeSetter(raw_ostream &OS) const {
+  OS << "  void set" << getUpperName() << "(ASTContext &Ctx, ";
+  writeCtorParameters(OS);
+  OS << ") {\n";
+  OS << "" << ArgSizeName << " = " << getUpperName() << "Size;\n";
+  OS << "" << ArgName << " = new (Ctx, 16) " << getType() << "["
+ << ArgSizeName << "];\n";
+  OS << "  ";
+  writeCtorBody(OS);
+  OS << "  }\n";
+}
+
 void writeCloneArgs(raw_ostream &OS) const override {
   OS << ArgName << ", " << ArgSizeName;
 }
@@ -1169,6 +1188,9 @@
   : VariadicArgument(Arg, Attr, "Expr *")
 {}
 
+VariadicExprArgument(StringRef ArgName, StringRef Attr)
+: VariadicArgument(ArgName, Attr, "Expr *") {}
+
 void writeASTVisitorTraversal(raw_ostream &OS) const override {
   OS << "  {\n";
   OS << "" << getType() << " *I = A->" << getLowerName()
@@ -2138,6 +2160,11 @@
   }
 }
 
+static bool isTypeArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ Arg->getSuperClasses().back().first->getName() == "TypeArgument";
+}
+
 /// Emits the first-argument-is-type property for attributes.
 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
@@ -2149,7 +2176,7 @@
 if (Args.empty())
   continue;
 
-if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
+if (!isTypeArgument(Args[0]))
   continue;
 
 // All these spellings take a single type argument.
@@ -2179,7 +2206,7 @@
   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
 }
 
-static bool isIdentifierArgument(Record *Arg) {
+static bool isIdentifierArgument(const Record *Arg) {
   return !Arg->getSuperClasses().empty() &&
 llvm::StringSwitch(Arg->getSuperClasses().back().first->getName())
 .Case("IdentifierArgument", true)
@@ -2188,7 +2215,7 @@
 .Default(false);
 }
 
-static bool isVariadicIdentifierArgument(Record *Arg) {
+static bool isVariadicIdentifierArgument(const Record *Arg) {
   return !Arg->getSuperClasses().empty() &&
  llvm::StringSwitch(
  Arg->getSuperClasses().back().first->getName())
@@ -2197,6 +2224,14 @@
  .Default(false);
 }
 
+static bool isVariadicExprArgument(const Record *Arg) {
+  return !Arg

[PATCH] D119124: Removing unnecessary condition

2022-02-07 Thread harish via Phabricator via cfe-commits
harishch4 created this revision.
harishch4 added a reviewer: llvm-commits.
harishch4 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fix to https://github.com/llvm/llvm-project/issues/53545


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119124

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -715,8 +715,6 @@
Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts,
llvm::outs()));
-if (!CompletionConsumer)
-  return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -715,8 +715,6 @@
Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts,
llvm::outs()));
-if (!CompletionConsumer)
-  return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406377.
awarzynski added a comment.

Removed trailing "_" from member variable names, added a comment, updated CMake 
dependencies (needed after https://reviews.llvm.org/D118966)

@schweitz, thank you for reviewing! If there are no new comments, I'll merge 
this today/tomorrow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The the `-emit-fir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActio

[PATCH] D116160: [AArch64] ACLE feature macro for Armv8.8-A MOPS

2022-02-07 Thread Son Tuan Vu via Phabricator via cfe-commits
tyb0807 abandoned this revision.
tyb0807 added a comment.

This is superseded by https://reviews.llvm.org/D118199. Comments have been 
addressed in the new patch. I should have commandeered this patch instead (did 
not know about this, sorry...).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116160

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


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406380.
awarzynski added a comment.

Rebase, remove trailing "_" from member variable names


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! The the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,80 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();
+  fir::KindMapping kindMap(mlirCtx.get(),
+  ll

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

This has been extracted from `fir-dev`. Original PR: 
https://github.com/flang-compiler/f18-llvm-project/pull/1113


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

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


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Diana Picus via Phabricator via cfe-commits
rovka added inline comments.



Comment at: flang/include/flang/Frontend/FrontendOptions.h:37
 
+  /// Emit a .llvm file
+  EmitLLVM,

Shouldn't this be .ll?



Comment at: flang/lib/Frontend/FrontendActions.cpp:421
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule_, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

Nit: Should we assert that mlirModule exists?
Also, why doesn't it already have a triple and a kind mapping?



Comment at: flang/lib/Frontend/FrontendActions.cpp:464
+  if (ci.IsOutputStreamNull()) {
+// Lower from the LLVM dialect to LLVM IR
+os = ci.CreateDefaultOutputFile(

This looks like an obsolete comment.



Comment at: flang/test/Driver/emit-llvm.f90:1
+! The the `-emit-llvm` option
+




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

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


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added a comment.

Few Nits/questions.




Comment at: flang/lib/Frontend/FrontendActions.cpp:69
+
+  // Create a LoweringBridge
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

Nit: Can we remove the three autos below?



Comment at: flang/lib/Frontend/FrontendActions.cpp:419
+
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(

Nit: Should we test the existence of such a file?



Comment at: flang/lib/Frontend/FrontendActions.cpp:420
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "mlir")};

Nit: can we remove auto?



Comment at: flang/test/Driver/emit-mlir.f90:1
+! The the `-emit-fir` option
+

Nit: The the



Comment at: flang/test/Driver/syntax-only.f90:16
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-

Nit: Do you have another test for `fsyntax-only`?



Comment at: flang/test/Driver/syntax-only.f90:23
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 

Do we currently run the stages before codegen and then issue this error?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118985

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


[PATCH] D113874: [clang] Propagate requires-clause from constructor template to implicit deduction guide

2022-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

As for testing strategy, after this change the AST should look different. You 
can probably modify `clang/test/SemaTemplate/deduction-guide.cpp` to check for 
existence of requires clauses in the implicitly generated function templates 
for guides.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113874

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


[clang-tools-extra] c63522e - [clang-tidy] Add new check 'shared-ptr-array-mismatch'.

2022-02-07 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2022-02-07T12:57:58+01:00
New Revision: c63522e6ba7782c335043893ae7cbd37eca24fe5

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

LOG: [clang-tidy] Add new check 'shared-ptr-array-mismatch'.

Reviewed By: LegalizeAdulthood

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

Added: 
clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.h

clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone-shared-ptr-array-mismatch.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 82a807eaa1714..7b1a2c14ed3c1 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -42,6 +42,7 @@
 #include "PosixReturnCheck.h"
 #include "RedundantBranchConditionCheck.h"
 #include "ReservedIdentifierCheck.h"
+#include "SharedPtrArrayMismatchCheck.h"
 #include "SignalHandlerCheck.h"
 #include "SignedCharMisuseCheck.h"
 #include "SizeofContainerCheck.h"
@@ -143,6 +144,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-posix-return");
 CheckFactories.registerCheck(
 "bugprone-reserved-identifier");
+CheckFactories.registerCheck(
+"bugprone-shared-ptr-array-mismatch");
 
CheckFactories.registerCheck("bugprone-signal-handler");
 CheckFactories.registerCheck(
 "bugprone-signed-char-misuse");

diff  --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index d1dbaec8358ad..b33072ddf01b8 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -37,6 +37,8 @@ add_clang_library(clangTidyBugproneModule
   PosixReturnCheck.cpp
   RedundantBranchConditionCheck.cpp
   ReservedIdentifierCheck.cpp
+  SharedPtrArrayMismatchCheck.cpp
+  SmartPtrArrayMismatchCheck.cpp
   SignalHandlerCheck.cpp
   SignedCharMisuseCheck.cpp
   SizeofContainerCheck.cpp

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.cpp
new file mode 100644
index 0..b628ebd4ae784
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.cpp
@@ -0,0 +1,31 @@
+//===--- SharedPtrArrayMismatchCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SharedPtrArrayMismatchCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+SharedPtrArrayMismatchCheck::SharedPtrArrayMismatchCheck(
+StringRef Name, ClangTidyContext *Context)
+: SmartPtrArrayMismatchCheck(Name, Context, "shared") {}
+
+SharedPtrArrayMismatchCheck::SmartPtrClassMatcher
+SharedPtrArrayMismatchCheck::getSmartPointerClassMatcher() const {
+  return classTemplateSpecializationDecl(
+  hasName("::std::shared_ptr"), templateArgumentCountIs(1),
+  hasTemplateArgument(
+  0, templateArgument(refersToType(qualType().bind(PointerTypeN);
+}
+
+} // namespace bugprone
+} // namespace tidy
+} // namespace clang

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
new file mode 100644
index 0..f628e02962d27
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
@@ -0,0 +1,38 @@
+//===--- SharedPtrArrayMismatchCheck.h - clang-tidy -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BU

[PATCH] D117306: [clang-tidy] Add new check 'shared-ptr-array-mismatch'.

2022-02-07 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc63522e6ba77: [clang-tidy] Add new check 
'shared-ptr-array-mismatch'. (authored by balazske).

Changed prior to commit:
  https://reviews.llvm.org/D117306?vs=405971&id=406385#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117306

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
  clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-shared-ptr-array-mismatch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-shared-ptr-array-mismatch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-shared-ptr-array-mismatch.cpp
@@ -0,0 +1,95 @@
+// RUN: %check_clang_tidy %s bugprone-shared-ptr-array-mismatch %t
+
+namespace std {
+
+template 
+struct shared_ptr {
+  template 
+  explicit shared_ptr(Y *) {}
+  template 
+  shared_ptr(Y *, Deleter) {}
+};
+
+} // namespace std
+
+struct A {};
+
+void f1() {
+  std::shared_ptr P1{new int};
+  std::shared_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P2{new int[10]};
+  // clang-format off
+  std::shared_ptr<  int  > P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr<  int[]  > P3{new int[10]};
+  // clang-format on
+  std::shared_ptr P4(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P4(new int[10]);
+  new std::shared_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  std::shared_ptr P5(new int[10]);
+  std::shared_ptr P6(new int[10], [](const int *Ptr) {});
+}
+
+void f2() {
+  std::shared_ptr P1(new A);
+  std::shared_ptr P2(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P2(new A[10]);
+  std::shared_ptr P3(new A[10]);
+}
+
+void f3() {
+  std::shared_ptr P1{new int}, P2{new int[10]}, P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  // CHECK-MESSAGES: :[[@LINE-2]]:57: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+}
+
+struct S {
+  std::shared_ptr P1;
+  std::shared_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  std::shared_ptr P3{new int}, P4{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  S() : P1{new int[10]} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+};
+
+void f_parm(std::shared_ptr);
+
+void f4() {
+  f_parm(std::shared_ptr{new int[10]});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+}
+
+std::shared_ptr f_ret() {
+  return std::shared_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+}
+
+template 
+void f_tmpl() {
+  std::shared_ptr P1{new T[10]};
+}
+
+void f5() {
+  f_tmpl();
+}
+
+#define CHAR_PTR_TYPE std::shared_ptr
+#define CHAR_PTR_VAR(X) \
+  X { new char[10] }
+#define CHAR_PTR_INIT(X, Y) \
+  std::shared_ptr X { Y }
+
+void f6() {
+  CHAR_PTR_TYPE P1{new char[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
+  std::shared_ptr CHAR_PTR_VAR(P2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: shared pointer to non-array is initialized with array [bugprone-sha

[PATCH] D118471: [clang][Lexer] Make raw and normal lexer behave the same for line comments

2022-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang/unittests/Lex/LexerTest.cpp:654
+  while (!L.LexFromRawLexer(T)) {
+ASSERT_TRUE(!ToksView.empty());
+EXPECT_EQ(T.getKind(), ToksView.front().getKind());

probinson wrote:
> @kadircet  @sammccall  It turns out this while loop is zero-trip; the test 
> assertions in the body are never executed.  Replace it with `assert(false);` 
> and the test doesn't crash.
> 
> That means `ToksView` is empty from the start.  This is probably not what you 
> wanted?
> 
> In other words, the test does not exercise the patch.  This is pretty 
> serious.  It needs to be fixed or reverted.
thanks! the discrepancy was actually having tokens in one but not the other, 
hence tests were failing initially but after the fix the tests passed (by 
making both lexing modes return none) so it skipped my attention. sending out a 
fix now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118471

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


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:69
+
+  // Create a LoweringBridge
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

kiranchandramohan wrote:
> Nit: Can we remove the three autos below?
Sure!



Comment at: flang/lib/Frontend/FrontendActions.cpp:419
+
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(

kiranchandramohan wrote:
> Nit: Should we test the existence of such a file?
We do :) Sort of!

To me, "existence" is a low level concept. Files are handled through e.g. 
`llvm::raw_fd_ostream` (and occasionally other streams) and IMO all low level 
details should be dealt with there (and indeed are). `flang-new` should only 
verify that `os` is not a `nullptr`. If the file does not exist, `os` will be a 
`nullptr` and that's checked further down. If the file does exist, then 
everything is fine and we can move to the next step. 



Comment at: flang/lib/Frontend/FrontendActions.cpp:420
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "mlir")};

kiranchandramohan wrote:
> Nit: can we remove auto?
Sure!



Comment at: flang/test/Driver/emit-mlir.f90:1
+! The the `-emit-fir` option
+

kiranchandramohan wrote:
> Nit: The the
Thanks :) Also, should be `-emit-mlir` instead of  `-emit-fir`.



Comment at: flang/test/Driver/syntax-only.f90:16
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-

kiranchandramohan wrote:
> Nit: Do you have another test for `fsyntax-only`?
No, but there are many tests that use it: 
https://github.com/llvm/llvm-project/blob/main/flang/test/Semantics/call17.f90



Comment at: flang/test/Driver/syntax-only.f90:23
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 

kiranchandramohan wrote:
> Do we currently run the stages before codegen and then issue this error?
Yes, but this error is here only temporarily. I will be removing it shortly 
(once `-emit-obj` is implemented).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118985

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


[PATCH] D119130: [clangd] NFC: Move stdlibg headers handling to Clang

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

The moved *.inc files are generated, the generator needs to be moved (and 
updated?) too I think.

Is having clangd continue to include the .inc files textually intended to stay 
that way, or is it a FIXME?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119130

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


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406398.
awarzynski added a comment.

Remove `auto`, update comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The `-emit-mlir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -11,7 +11,12 @@
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/Frontend/PreprocessorOptions.h"
+#include "flang/Lower/Bridge.h"
 #include "flang

[PATCH] D119130: [clangd] NFC: Move stdlibg headers handling to Clang

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This looks sensible to me, but as I wrote this code we should maybe get a 
second look (@kadircet?) that it makes sense to lift to clang::tooling.

Some positive experience: we've used it successfully in an internal clang-tidy 
check.




Comment at: clang-tools-extra/clangd/unittests/HeadersTests.cpp:412
 
-TEST(StdlibTest, All) {
-  auto VectorH = stdlib::Header::named("");
-  EXPECT_TRUE(VectorH);
-  EXPECT_EQ(llvm::to_string(*VectorH), "");
-  EXPECT_FALSE(stdlib::Header::named("HeadersTests.cpp"));
-
-  auto Vector = stdlib::Symbol::named("std::", "vector");
-  EXPECT_TRUE(Vector);
-  EXPECT_EQ(llvm::to_string(*Vector), "std::vector");
-  EXPECT_FALSE(stdlib::Symbol::named("std::", "dongle"));
-  EXPECT_FALSE(stdlib::Symbol::named("clang::", "ASTContext"));
-
-  EXPECT_EQ(Vector->header(), *VectorH);
-  EXPECT_THAT(Vector->headers(), ElementsAre(*VectorH));
-}
-
 TEST(StdlibTest, Recognizer) {
   auto TU = TestTU::withCode(R"cpp(

Recognizer test also needs to be moved



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:1
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/Optional.h"

This needs a copyright header and a file comment



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:7
+namespace clang {
+namespace stdlib {
+

namespace tooling { namespace stdlib {



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:13
+// Lightweight class, in fact just an index into a table.
+class Header {
+public:

what's the design around C vs C++?

e.g. are `std::printf` and `::printf` distinct symbols, are C `printf` and C++ 
`::printf` distinct symbols, similarly for headers.

(Fine if only C++ is implemented here, but the interface should probably say 
one way or the other)

In clangd we had a handle on all the callers, but here we have to worry about 
acquiring callers that e.g. can't easily provide language information.



Comment at: clang/lib/Tooling/Inclusions/StandardLibrary.cpp:110
+return namespaceSymbols(Parent);
+return NamespaceSymbols->lookup((D->getName() + "::").str());
+  }();

if D is `std::chrono` I think it just returns "chrono"?

(we should probably have a Recognizer test for this, sorry I left it out...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119130

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


[PATCH] D119130: [clangd] NFC: Move stdlibg headers handling to Clang

2022-02-07 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 406401.
kbobyrev added a comment.

Move include-mapping generators to clang and re-generate the files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119130

Files:
  clang-tools-extra/clangd/CSymbolMap.inc
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/StdSymbolMap.inc
  clang-tools-extra/clangd/include-mapping/cppreference_parser.py
  clang-tools-extra/clangd/include-mapping/gen_std.py
  clang-tools-extra/clangd/include-mapping/test.py
  clang-tools-extra/clangd/index/CanonicalIncludes.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang/include/clang/Tooling/Inclusions/CSymbolMap.inc
  clang/include/clang/Tooling/Inclusions/StandardLibrary.h
  clang/include/clang/Tooling/Inclusions/StdSymbolMap.inc
  clang/lib/Tooling/Inclusions/CMakeLists.txt
  clang/lib/Tooling/Inclusions/StandardLibrary.cpp
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py
  clang/tools/include-mapping/test.py
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StandardLibraryTest.cpp

Index: clang/unittests/Tooling/StandardLibraryTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -0,0 +1,39 @@
+//===- unittest/Tooling/StandardLibrary.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/StandardLibrary.h"
+#include "llvm/Support/ScopedPrinter.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using ::testing::ElementsAre;
+
+namespace clang {
+namespace tooling {
+namespace {
+
+TEST(StdlibTest, All) {
+  auto VectorH = stdlib::Header::named("");
+  EXPECT_TRUE(VectorH);
+  EXPECT_EQ(llvm::to_string(*VectorH), "");
+  EXPECT_FALSE(stdlib::Header::named("HeadersTests.cpp"));
+
+  auto Vector = stdlib::Symbol::named("std::", "vector");
+  EXPECT_TRUE(Vector);
+  EXPECT_EQ(llvm::to_string(*Vector), "std::vector");
+  EXPECT_FALSE(stdlib::Symbol::named("std::", "dongle"));
+  EXPECT_FALSE(stdlib::Symbol::named("clang::", "ASTContext"));
+
+  EXPECT_EQ(Vector->header(), *VectorH);
+  EXPECT_THAT(Vector->headers(), ElementsAre(*VectorH));
+}
+
+} // namespace
+} // namespace tooling
+} // namespace clang
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -17,6 +17,7 @@
   ExecutionTest.cpp
   FixItTest.cpp
   HeaderIncludesTest.cpp
+  StandardLibraryTest.cpp
   LexicallyOrderedRecursiveASTVisitorTest.cpp
   LookupTest.cpp
   QualTypeNamesTest.cpp
Index: clang-tools-extra/clangd/include-mapping/test.py
===
--- /dev/null
+++ clang-tools-extra/clangd/include-mapping/test.py
@@ -1,155 +0,0 @@
-#!/usr/bin/env python
-#===- test.py -  -*- python -*--===#
-#
-# 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
-#
-#======#
-
-from cppreference_parser import _ParseSymbolPage, _ParseIndexPage
-
-import unittest
-
-class TestStdGen(unittest.TestCase):
-
-  def testParseIndexPage(self):
-html = """
- abs() (int) 
- abs<>() (std::complex) 
- acos() 
- acosh() (since C++11) 
- as_bytes<>() (since C++20) 
- """
-
-actual = _ParseIndexPage(html)
-expected = [
-  ("abs", "abs.html", True),
-  ("abs", "complex/abs.html", True),
-  ("acos", "acos.html", False),
-  ("acosh", "acosh.html", False),
-  ("as_bytes", "as_bytes.html", False),
-]
-self.assertEqual(len(actual), len(expected))
-for i in range(0, len(actual)):
-  self.assertEqual(expected[i][0], actual[i][0])
-  self.assertTrue(actual[i][1].endswith(expected[i][1]))
-  self.assertEqual(expected[i][2], actual[i][2])
-
-
-  def testParseSymbolPage_SingleHeader(self):
-# Defined in header 
-html = """
- 
-  
-   Defined in header 
-   
-  
-  
-  
-  
-void foo()
-this is matched
-  
-
-"""
-self.assertEqual(_ParseSymbolPage(html, 'foo'), set(['']))
-
-
-  def testParseSymbolPage_MulHeaders(self):
-#  Defined in header 
-#  Defined in header 
-#  Defined in header 
-html = """
-
-  
- Defined in header 
- 
- 
-
-  
-  
-void bar()
-this me

[PATCH] D118976: clangd: Set a diagnostic on a code action resulting from a tweak

2022-02-07 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler added a comment.

It'd be great if you could merge this, as I don't have the necessary privileges.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118976

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


[clang] f597870 - [clang][Lexer] Fix tests after ff77071a4d67

2022-02-07 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-02-07T14:06:32+01:00
New Revision: f59787084e09aeb787cb3be3103b2419ccd14163

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

LOG: [clang][Lexer] Fix tests after ff77071a4d67

Added: 


Modified: 
clang/unittests/Lex/LexerTest.cpp

Removed: 




diff  --git a/clang/unittests/Lex/LexerTest.cpp 
b/clang/unittests/Lex/LexerTest.cpp
index df22e775314a9..f534de1ca813a 100644
--- a/clang/unittests/Lex/LexerTest.cpp
+++ b/clang/unittests/Lex/LexerTest.cpp
@@ -639,6 +639,7 @@ TEST_F(LexerTest, RawAndNormalLexSameForLineComments) {
   const llvm::StringLiteral Source = R"cpp(
   // First line comment.
   //* Second line comment which is ambigious.
+  ; // Have a non-comment token to make sure something is lexed.
   )cpp";
   LangOpts.LineComment = false;
   auto Toks = Lex(Source);
@@ -650,6 +651,7 @@ TEST_F(LexerTest, RawAndNormalLexSameForLineComments) {
 
   auto ToksView = llvm::makeArrayRef(Toks);
   clang::Token T;
+  EXPECT_FALSE(ToksView.empty());
   while (!L.LexFromRawLexer(T)) {
 ASSERT_TRUE(!ToksView.empty());
 EXPECT_EQ(T.getKind(), ToksView.front().getKind());



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


[PATCH] D118044: [ARM] Undeprecate complex IT blocks

2022-02-07 Thread Dave Green via Phabricator via cfe-commits
dmgreen accepted this revision.
dmgreen added a comment.
This revision is now accepted and ready to land.

Thanks for the updates. LGTM.




Comment at: llvm/test/CodeGen/ARM/ifcvt-branch-weight.ll:21
 
-; CHECK: bb.2.bb2:
+; CHECK: bb.1.bb:
 ; CHECK: successors: %bb.4(0x4000), %bb.3(0x4000)

I think this should still be bb.2.bb2


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118044

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


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko updated this revision to Diff 406411.
ivanmurashko added a comment.

There are some changes:

- unit test for HeaderIncludes was added
- lit test for clangd was removed
- Solution uses std::list instead of copying by value


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

Files:
  clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
  clang/unittests/Tooling/HeaderIncludesTest.cpp


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,7 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,7 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko added inline comments.



Comment at: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h:100
   // and "x" will be treated as the same header when deleting #includes.
   llvm::StringMap> ExistingIncludes;
 

sammccall wrote:
> An alternative would be to use a std::forward_list here.
> 
> This guarantees pointer stability, it's an extra allocation but seems 
> unlikely to matter.
> 
> It would be more robust if the data structure changes (e.g. becomes large, or 
> is mutated after creation) but probably none of this will ever happen.
> 
> Up to you.
I changed my solution accordingly this suggestion. 
Small note: The `std::list` seems to be more suitable here as soon as the last 
element of the structure is used at the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

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


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks, looks good!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

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


[PATCH] D119130: [clangd] NFC: Move stdlibg headers handling to Clang

2022-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Regarding the include mapping generator, I think it would've been better if we 
had some sort of list directly from libc++ (as this is now being part of clang 
rather than just clangd), but having the current symbol mapping available for 
other tools too is definitely a useful improvement and implementation details 
can change later on.
I think we should have some "more public" documentation available around the 
limitations of current generator though, so that people are not surprised and 
aware of the caveats (like symbols might be missing, or in case of ambiguity 
they might be dropped, etc). Not sure where that belongs though, maybe header 
of the `.inc` file, or if we want it to be only used through the recognizer 
interface, maybe we can make the `inc` file "private" and document it there.

As for stdlib symbol/header/recognizer, I've got a couple questions around the 
functionality we are exposing:

- (briefly mentioned above) should we just make raw symbol mappings an 
implementation detail of stdlib recognizer and have applications depend on it?
- do we want headers/symbols to be created outside of the recognizer?




Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:15
+public:
+  static llvm::Optional named(llvm::StringRef Name);
+

can you clarify if `Name` can have quotes/angles ?



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:37
+  static llvm::Optional named(llvm::StringRef Scope,
+  llvm::StringRef Name);
+

should scope have trailing `::` ?



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:46
+  Header header() const;
+  // Some symbols may be provided my multiple headers.
+  llvm::SmallVector headers() const;

s/my/by



Comment at: clang/include/clang/Tooling/Inclusions/StandardLibrary.h:66
+  Recognizer();
+  llvm::Optional operator()(const Decl *D);
+

what about macros?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119130

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


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h:101
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  llvm::StringMap> ExistingIncludes;
 

May be worth a comment here that std::list is used for pointer stability, since 
it looks a little odd at first glance.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

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


[PATCH] D119124: Removing unnecessary condition

2022-02-07 Thread harish via Phabricator via cfe-commits
harishch4 updated this revision to Diff 406412.

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

https://reviews.llvm.org/D119124

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -715,6 +715,7 @@
Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts,
llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -715,6 +715,7 @@
Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts,
llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118924: [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 406413.
curdeius added a comment.

Add tests, update in loop.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118924

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,22 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstOnLine = [](const FormatToken &Tok) {
+  return Tok.HasUnescapedNewline || Tok.IsFirst;
+};
+
+if (PreviousWasComment) {
+  // Consider preprocessor directives preceded by block comments as first 
on
+  // line.
+  FirstNonCommentOnLine |= IsFirstOnLine(*FormatTok);
+} else {
+  FirstNonCommentOnLine = IsFirstOnLine(*FormatTok);
+}
+
+PreviousWasComment = FormatTok->Tok.is(tok::comment);
+
 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
-   (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
+   FirstNonCommentOnLine) {
   distributeComments(Comments, FormatTok);
   Comments.clear();
   // If there is an unfinished unwrapped line, we flush the preprocessor
@@ -3585,6 +3601,14 @@
 Line->Level += PPBranchLevel;
   flushComments(isOnNewLine(*FormatTok));
   parsePPDirective();
+  PreviousWasComment = FormatTok->Tok.is(tok::comment);
+  if (PreviousWasComment) {
+// Consider preprocessor directives preceded by block comments as first
+// on line.
+FirstNonCommentOnLine |= IsFirstOnLine(*FormatTok);
+  } else {
+FirstNonCommentOnLine = IsFirstOnLine(*FormatTok);
+  }
 }
 
 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,22 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstOnLine = [](const FormatToken &Tok) {
+  return Tok.HasUnescapedNewline || Tok.IsFirst;
+};
+
+if (PreviousWasComment) {
+  // Consider preprocessor directives preceded by block comments as first on
+  // line.
+  FirstNonCommentOnLine |= IsFirstOnLine(*FormatTok);
+} else {
+  FirstNonComme

[PATCH] D118924: [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 406415.
curdeius marked 2 inline comments as done.
curdeius added a comment.

Don't use `|=`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118924

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,23 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstOnLine = [](const FormatToken &Tok) {
+  return Tok.HasUnescapedNewline || Tok.IsFirst;
+};
+
+if (PreviousWasComment) {
+  // Consider preprocessor directives preceded by block comments as first 
on
+  // line.
+  FirstNonCommentOnLine =
+  FirstNonCommentOnLine || IsFirstOnLine(*FormatTok);
+} else {
+  FirstNonCommentOnLine = IsFirstOnLine(*FormatTok);
+}
+
+PreviousWasComment = FormatTok->Tok.is(tok::comment);
+
 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
-   (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
+   FirstNonCommentOnLine) {
   distributeComments(Comments, FormatTok);
   Comments.clear();
   // If there is an unfinished unwrapped line, we flush the preprocessor
@@ -3585,6 +3602,14 @@
 Line->Level += PPBranchLevel;
   flushComments(isOnNewLine(*FormatTok));
   parsePPDirective();
+  PreviousWasComment = FormatTok->Tok.is(tok::comment);
+  if (PreviousWasComment) {
+// Consider preprocessor directives preceded by block comments as first
+// on line.
+FirstNonCommentOnLine |= IsFirstOnLine(*FormatTok);
+  } else {
+FirstNonCommentOnLine = IsFirstOnLine(*FormatTok);
+  }
 }
 
 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,23 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstOnLine = [](const FormatToken &Tok) {
+  return Tok.HasUnescapedNewline || Tok.IsFirst;
+};
+
+if (PreviousWasComment) {
+  // Consider preprocessor directives preceded by block comments as first on
+  // line.
+  FirstNonCommentOnLi

[PATCH] D114439: [Annotation] Allow parameter pack expansions and initializer lists in annotate attribute

2022-02-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Sema/ParsedAttr.h:52-57
+  /// The number of non-fake arguments specified in the attribute definition.
+  unsigned NumArgMembers : 4;
   /// True if the parsing does not match the semantic content.
   unsigned HasCustomParsing : 1;
+  // True if this attribute accepts expression parameter pack expansions.
+  unsigned AcceptsExprPack : 1;

Er, this means the bit packed part of the structure can no longer fit in a 
32-bit allocation unit (we went from needing 30 bits to needing 35 bits). 
That's unfortunate. I don't see any other bits to reasonably steal from.

I took a look to see whether I thought this would have a significant 
performance impact. We definitely keep arrays of these things around and walk 
over the array, so I expect some performance loss from this change. But it 
seems like the sort of thing likely to fall out in the noise rather than be on 
the hot path, so I think this is fine. However, if we see a noticeable 
performance regression, we should keep this change in mind to see if there's 
something more we can do to keep us within a 32-bit allocation unit.



Comment at: clang/include/clang/Sema/ParsedAttr.h:113
   }
+  // Check if argument at index I is an expression argument
+  virtual bool isExprArg(size_t N) const { return false; }

I don't think this API is needed. `isArgExpr()` already exists on the interface 
and I'm not certain how this differs. (If this API is needed, we need a far 
better name for it because I'd have no idea how to distinguish `isExprArg()` 
and `isArgExpr()`.)



Comment at: clang/include/clang/Sema/Sema.h:4383-4385
+  bool checkStringLiteralExpr(const AttributeCommonInfo &CI, const Expr *E,
+  StringRef &Str,
+  SourceLocation *ArgLocation = nullptr);

This name makes it sound like far more general of an API than it is. This 
function is specific to checking string literal arguments for an attribute. But 
then why does `checkStringLiteralArgumentAttr()` not suffice? It does the same 
thing, but with more bells and whistles.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:4185
   StringRef Str;
-  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
+  if (!checkStringLiteralExpr(CI, AllArgs[0], Str))
 return;

This is a slight loss of functionality. We used to recommend identifiers be 
converted to string literals under the old interface. I don't think this 
refactoring is necessary any longer, right?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:4179-4182
+  if (AllArgs.size() < 1) {
+Diag(CI.getLoc(), diag::err_attribute_too_few_arguments) << CI << 1;
+return;
+  }

steffenlarsen wrote:
> aaron.ballman wrote:
> > Please double-check that the call to `checkCommonAttributeFeatures()` from 
> > `ProcessDeclAttribute()` doesn't already handle this for you. If it does, 
> > then I think this can be replaced with `assert(!AllArgs.empty() && 
> > "expected at least one argument");`
> It does go through `checkCommonAttributeFeatures` but (as of the recent 
> changes) it will skip size-checks if arguments are delayed as a pack 
> expansion could potentially populate the seemingly missing expressions after 
> template instantiation for some attribute.
> For annotate we could also have a pack as the only expression, which would 
> then evaluate to an empty list of expressions. Since this path is also taken 
> by `instantiateDependentAnnotationAttr` if there are delayed args. In reality 
> it is only really needed after template instantiations, given as you said 
> `checkCommonAttributeFeatures` will do the checking in the other case, but I 
> personally think it is cleaner to have it here. If you disagree I will move 
> it into `instantiateDependentAnnotationAttr` instead and add the assert.
Ah, I think what caught me off-guard is that I was expecting 
`checkCommonAttributeFeatures()` to be called again from template instantiation 
time. Then there are less (possibly even no more) dependent arguments, so it 
can do more automated checking. However, I see that `Sema::InstantiateAttrs()` 
is crying out for refactoring to make that more useful, so it's outside the 
scope of this patch (what you're doing here is fine). Thanks!



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:4203
+  if (AllArgs.size() && AllArgs[0]->isValueDependent()) {
+auto *Attr = AnnotateAttr::CreateWithDelayedArgs(
+S.getASTContext(), AllArgs.data(), AllArgs.size(), AL);

steffenlarsen wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > aaron.ballman wrote:
> > > > erichkeane wrote:
> > > > > I would like @aaron.ballman to comment on this, but I think we 
> > > > > probably want this case to be covered in the top of `HandleDeclAttr`, 
> > > > > which would mean 

[clang-tools-extra] 29fc5e0 - [clang-tidy] Fixed a compile warning (NFC).

2022-02-07 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2022-02-07T14:56:27+01:00
New Revision: 29fc5e0245cb360387cb8daac52c13dbc390fafd

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

LOG: [clang-tidy] Fixed a compile warning (NFC).

Fixed a "override" related warning in SharedPtrArrayMismatchCheck.h.
Related to differential revision: https://reviews.llvm.org/D117306

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
index f628e02962d2..bb549c5a2c69 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/SharedPtrArrayMismatchCheck.h
@@ -28,7 +28,7 @@ class SharedPtrArrayMismatchCheck : public 
SmartPtrArrayMismatchCheck {
   SharedPtrArrayMismatchCheck(StringRef Name, ClangTidyContext *Context);
 
 protected:
-  virtual SmartPtrClassMatcher getSmartPointerClassMatcher() const;
+  virtual SmartPtrClassMatcher getSmartPointerClassMatcher() const override;
 };
 
 } // namespace bugprone



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


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko updated this revision to Diff 406420.
ivanmurashko edited the summary of this revision.
ivanmurashko added a comment.

Comment about std::list was added


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

Files:
  clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
  clang/unittests/Tooling/HeaderIncludesTest.cpp


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,9 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  // std::list is used for pointers stability that are referenced by
+  // IncludesByPriority
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,9 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  // std::list is used for pointers stability that are referenced by
+  // IncludesByPriority
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118755: [clangd] Crash in __memcmp_avx2_movbe

2022-02-07 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko updated this revision to Diff 406421.
ivanmurashko added a comment.

comment update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118755

Files:
  clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
  clang/unittests/Tooling/HeaderIncludesTest.cpp


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,8 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  // std::list is used for pointers stability (see IncludesByPriority)
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when


Index: clang/unittests/Tooling/HeaderIncludesTest.cpp
===
--- clang/unittests/Tooling/HeaderIncludesTest.cpp
+++ clang/unittests/Tooling/HeaderIncludesTest.cpp
@@ -51,6 +51,15 @@
   EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
 }
 
+TEST_F(HeaderIncludesTest, RepeatedIncludes) {
+  std::string Code;
+  for (int i = 0; i < 100; ++i) {
+Code += "#include \"a.h\"\n";
+  }
+  std::string Expected = Code + "#include \"a2.h\"\n";
+  EXPECT_EQ(Expected, insert(Code, "\"a2.h\""));
+}
+
 TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
   std::string Code = "#ifndef A_H\n"
  "#define A_H\n"
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -14,6 +14,7 @@
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include 
 #include 
 
 namespace clang {
@@ -97,7 +98,8 @@
   // Map from include name (quotation trimmed) to a list of existing includes
   // (in case there are more than one) with the name in the current file. 
   // and "x" will be treated as the same header when deleting #includes.
-  llvm::StringMap> ExistingIncludes;
+  // std::list is used for pointers stability (see IncludesByPriority)
+  llvm::StringMap> ExistingIncludes;
 
   /// Map from priorities of #include categories to all #includes in the same
   /// category. This is used to find #includes of the same category when
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119067: [clang-format] Fix DefinitionBlockSeparator extra empty lines

2022-02-07 Thread ksyx via Phabricator via cfe-commits
ksyx marked an inline comment as done.
ksyx added inline comments.



Comment at: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp:305
   "  int r = j / k;\n"
+  "  if (struct S = getS()) {\n"
+  "// if condition\n"

curdeius wrote:
> curdeius wrote:
> > I'd rather see this added in another function e.g. bar3, because otherwise 
> > you don't test what was tested before.
> When I wrote this comment I thought that bar3 didn't exist... But well, I 
> think I'll create a patch to clean up these tests a bit anyway.
Thank you very much for this!


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

https://reviews.llvm.org/D119067

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


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:421
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule_, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

rovka wrote:
> Nit: Should we assert that mlirModule exists?
> Also, why doesn't it already have a triple and a kind mapping?
> Nit: Should we assert that mlirModule exists?

We could do, yes. However, `mlirModule` is created in 
`CodeGenAction::BeginSourceFileAction`. If that method fails, the driver should 
stop immediately. So perhaps that would be a better for place for an assert?

On a related note, `mlirModule` is obtained via [[ 
https://github.com/llvm/llvm-project/blob/79b3fe80707b2eb9a38c1517a829fb58062fb687/flang/include/flang/Lower/Bridge.h#L67
 | LoweringBridge::getModule ]]. But if the corresponding module is `nullptr` 
than that getter should probably assert. See https://reviews.llvm.org/D119133.

>  Also, why doesn't it already have a triple and a kind mapping?
Good catch, this is not needed yet. I didn't notice this when going over `tco`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

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


[PATCH] D118350: [Clang][Sema][AIX][PowerPC] Emit byval alignment warning only when struct member is passed to a function

2022-02-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:5212-5215
+  const Expr *AArg = Arg->IgnoreParens();
+  if (const auto *ICE = dyn_cast(AArg)) {
+AArg = ICE->getSubExpr();
+if (const auto *ME = dyn_cast(AArg)) {

I don't see a need for `AArg`, so I'd sink it into the uses instead.



Comment at: clang/lib/Sema/SemaChecking.cpp:5220-5221
+  Context.toCharUnitsFromBits(AA->getAlignment(Context));
+  if (Alignment.getQuantity() >= 16)
+Diag(Loc, diag::warn_not_xl_compatible) << FD;
+}

I think it'd probably be helpful to tell the user which alignment was 
calculated (it may not be obvious from the context because the alignment could 
be hidden behind a macro or something).



Comment at: clang/lib/Sema/SemaChecking.cpp:5341-5342
+if (Context.getTargetInfo().getTriple().isOSAIX() && Arg &&
+(FDecl->hasLinkage()) &&
+!(FDecl->getFormalLinkage() == InternalLinkage))
+  checkAIXMemberAlignment((Arg->getExprLoc()), FDecl,





Comment at: clang/test/Sema/aix-attr-align.c:34-35
+  baz(s.a); // no-warning
+  baz(s.b); // expected-warning {{requesting an alignment of 16 bytes or 
greater for struct members is not binary compatible with IBM XL C/C++ for AIX 
16.1.0 and older}}
+  baz(s.c); // expected-warning {{requesting an alignment of 16 bytes or 
greater for struct members is not binary compatible with IBM XL C/C++ for AIX 
16.1.0 and older}}
+

This diagnostic is a bit odd to me. It says there's a request for alignment, 
but there's no such request on this line. So it's not clear how the user is 
supposed to react to the diagnostic. While the current code makes it somewhat 
obvious because there's only one field in the expression, imagine code like 
`quux(s.a, s.b);` where it's less clear as to which field causes the diagnostic 
from looking at the call site.

Personally, I found the old diagnostics to be more clear as to what the issue 
is. I think we should put the warning on the declaration involving the 
alignment request, and we should add a note to the call site where the 
diagnostic is generated from (or vice versa). WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118350

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-07 Thread Iannis de Zwart via Phabricator via cfe-commits
iannisdezwart updated this revision to Diff 406422.
iannisdezwart added a comment.

Two changes:

1. Added tests for overloaded operators into SemanticHighlightingTests.
2. Fixed the way tokens are expanded. Previously `operator<<` would be split 
into two highlighting tokens: `operator` and `<<`. Now it's all one 
highlighting token. The same is true for all other compound operator keyword 
statements.


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

https://reviews.llvm.org/D119077

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -109,7 +109,7 @@
 $Class[[AS]] $LocalVariable_decl[[AA]];
 $Primitive_deduced_defaultLibrary[[auto]] $LocalVariable_decl[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
 auto $LocalVariable_decl[[FN]] = [ $LocalVariable[[AA]]](int $Parameter_decl[[A]]) -> void {};
-$LocalVariable[[FN]](12312);
+$LocalVariable[[FN]]$Method_readonly[[(]]12312$Method_readonly[[)]];
   }
 )cpp",
   R"cpp(
@@ -138,7 +138,7 @@
   struct $Class_decl[[B]] {
 $Class_decl[[B]]();
 ~$Class[[B]](); // FIXME: inconsistent with constructor
-void operator<<($Class[[B]]);
+void $Method_decl[[operator<<]]($Class[[B]]);
 $Class[[AAA]] $Field_decl[[AA]];
   };
   $Class[[B]]::$Class_decl[[B]]() {}
@@ -289,10 +289,10 @@
   struct $Class_decl[[B]] {};
   struct $Class_decl[[A]] {
 $Class[[B]] $Field_decl[[BB]];
-$Class[[A]] &operator=($Class[[A]] &&$Parameter_decl[[O]]);
+$Class[[A]] &$Method_decl[[operator=]]($Class[[A]] &&$Parameter_decl[[O]]);
   };
 
-  $Class[[A]] &$Class[[A]]::operator=($Class[[A]] &&$Parameter_decl[[O]]) = default;
+  $Class[[A]] &$Class[[A]]::$Method_decl[[operator=]]($Class[[A]] &&$Parameter_decl[[O]]) = default;
 )cpp",
   R"cpp(
   enum $Enum_decl[[En]] {
@@ -777,7 +777,7 @@
 void $Function_decl[[foo]]() {
   int $LocalVariable_decl[[a]], $LocalVariable_decl[[b]];
   [ $LocalVariable_decl[[c]] = $LocalVariable[[a]],
-$LocalVariable_decl[[d]]($LocalVariable[[b]]) ]() {}();
+$LocalVariable_decl[[d]]($LocalVariable[[b]]) ]() {}$Method_readonly[[(]]$Method_readonly[[)]];
 }
   )cpp",
   // Enum base specifier
@@ -790,6 +790,34 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
+  // Overloaded operators
+  R"cpp(
+struct $Class_decl[[Foo]] {
+  bool $Method_decl[[operator()]]() { return true; }
+  void $Method_decl[[operator<<]](int $Parameter_decl[[K]]) {}
+  operator bool() {} // FIXME: consider how this should be highlighted.
+};
+
+namespace $Namespace_decl[[namesp]] {
+  void $Function_decl[[operator--]]($Class[[Foo]] $Parameter_decl[[F]])
+  {}
+};
+
+auto $Variable_decl[[a]] =
+  &$Namespace[[namesp]]::$Function[[operator--]];
+
+void $Function_decl[[operator++]]($Class[[Foo]] &$Parameter_decl[[F]])
+{}
+
+int $Function_decl[[main]]() {
+  $Class[[Foo]] $LocalVariable_decl[[foo]];
+  $LocalVariable[[foo]].$Method[[operator()]]();
+  $LocalVariable[[foo]].$Method[[operator<<]](1);
+
+  $Function[[operator++]]($LocalVariable_usedAsMutableReference[[foo]]);
+  $Function[[operator delete[]]]($Function[[operator new[]]](1));
+}
+  )cpp",
   };
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclarationName.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
@@ -26,6 +27,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
@@ -449,8 +451,9 @@
   }
 
   const HeuristicResolver *getResolver() const { return Resolver; }
+  const SourceManager &getSourceMgr() const { return SourceMgr; }
+  const syntax::TokenBuffer &getTB() const { return TB; }
 
-pr

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406425.
awarzynski marked 2 inline comments as done.
awarzynski added a comment.

Update comments + add an `assert`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! Test the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,81 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule, "native");
+  auto &defKinds = ci.i

[clang] d7ddad4 - Reformat CastExpr unittest suite; NFC

2022-02-07 Thread Aaron Ballman via cfe-commits

Author: Kim Gräsman
Date: 2022-02-07T09:21:41-05:00
New Revision: d7ddad408f5b64df39a39f4af3a631275961b975

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

LOG: Reformat CastExpr unittest suite; NFC

In preparation for adding new tests. No functional change.

Added: 


Modified: 
clang/unittests/Tooling/CastExprTest.cpp

Removed: 




diff  --git a/clang/unittests/Tooling/CastExprTest.cpp 
b/clang/unittests/Tooling/CastExprTest.cpp
index cda963a6a897..a07eff36afb0 100644
--- a/clang/unittests/Tooling/CastExprTest.cpp
+++ b/clang/unittests/Tooling/CastExprTest.cpp
@@ -23,15 +23,15 @@ struct CastExprVisitor : TestVisitor {
 };
 
 TEST(CastExprTest, GetSubExprAsWrittenThroughMaterializedTemporary) {
-CastExprVisitor Visitor;
-Visitor.OnExplicitCast = [](ExplicitCastExpr *Expr) {
-  auto Sub = Expr->getSubExprAsWritten();
-  EXPECT_TRUE(isa(Sub))
+  CastExprVisitor Visitor;
+  Visitor.OnExplicitCast = [](ExplicitCastExpr *Expr) {
+auto Sub = Expr->getSubExprAsWritten();
+EXPECT_TRUE(isa(Sub))
 << "Expected DeclRefExpr, but saw " << Sub->getStmtClassName();
-};
-Visitor.runOver("struct S1 {};\n"
-"struct S2 { operator S1(); };\n"
-"S1 f(S2 s) { return static_cast(s); }\n");
+  };
+  Visitor.runOver("struct S1 {};\n"
+  "struct S2 { operator S1(); };\n"
+  "S1 f(S2 s) { return static_cast(s); }\n");
 }
 
 // Verify that getSubExprAsWritten looks through a ConstantExpr in a scenario
@@ -43,15 +43,15 @@ TEST(CastExprTest, 
GetSubExprAsWrittenThroughMaterializedTemporary) {
 // `-CXXConstructExpr 'S' 'void (int)'
 //   `-IntegerLiteral 'int' 0
 TEST(CastExprTest, GetSubExprAsWrittenThroughConstantExpr) {
-CastExprVisitor Visitor;
-Visitor.OnExplicitCast = [](ExplicitCastExpr *Expr) {
-  auto *Sub = Expr->getSubExprAsWritten();
-  EXPECT_TRUE(isa(Sub))
+  CastExprVisitor Visitor;
+  Visitor.OnExplicitCast = [](ExplicitCastExpr *Expr) {
+auto *Sub = Expr->getSubExprAsWritten();
+EXPECT_TRUE(isa(Sub))
 << "Expected IntegerLiteral, but saw " << Sub->getStmtClassName();
-};
-Visitor.runOver("struct S { consteval S(int) {} };\n"
-"S f() { return S(0); }\n",
-CastExprVisitor::Lang_CXX2a);
+  };
+  Visitor.runOver("struct S { consteval S(int) {} };\n"
+  "S f() { return S(0); }\n",
+  CastExprVisitor::Lang_CXX2a);
 }
 
-}
+} // namespace



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


[PATCH] D118924: [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:3609
+// on line.
+FirstNonCommentOnLine |= IsFirstOnLine(*FormatTok);
+  } else {

There it is again. ;)

The if is the same as above, isn't it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118924

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


[clang] a70549a - [clang-format] Fix DefSeparator empty line issues

2022-02-07 Thread via cfe-commits

Author: ksyx
Date: 2022-02-07T14:23:21Z
New Revision: a70549ae43dfa551f3eacdfa7a7f2c0df073be8e

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

LOG: [clang-format] Fix DefSeparator empty line issues

- Add or remove empty lines surrounding union blocks.
- Fixes https://github.com/llvm/llvm-project/issues/53229, in which
  keywords like class and struct in a line ending with left brace or
  whose next line is left brace only, will be falsely recognized as
  definition line, causing extra empty lines inserted surrounding blocks
  with no need to be formatted.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D119067

Added: 


Modified: 
clang/lib/Format/DefinitionBlockSeparator.cpp
clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/DefinitionBlockSeparator.cpp 
b/clang/lib/Format/DefinitionBlockSeparator.cpp
index b7fca864efc6..b7b1123773ce 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -35,19 +35,31 @@ void DefinitionBlockSeparator::separateBlocks(
   const bool IsNeverStyle =
   Style.SeparateDefinitionBlocks == FormatStyle::SDS_Never;
   const AdditionalKeywords &ExtraKeywords = Tokens.getKeywords();
-  auto LikelyDefinition = [this, ExtraKeywords](const AnnotatedLine *Line,
-bool ExcludeEnum = false) {
+  auto GetBracketLevelChange = [](const FormatToken *Tok) {
+if (Tok->isOneOf(tok::l_brace, tok::l_paren, tok::l_square))
+  return 1;
+if (Tok->isOneOf(tok::r_brace, tok::r_paren, tok::r_square))
+  return -1;
+return 0;
+  };
+  auto LikelyDefinition = [&](const AnnotatedLine *Line,
+  bool ExcludeEnum = false) {
 if ((Line->MightBeFunctionDecl && Line->mightBeFunctionDefinition()) ||
 Line->startsWithNamespace())
   return true;
-FormatToken *CurrentToken = Line->First;
-while (CurrentToken) {
-  if (CurrentToken->isOneOf(tok::kw_class, tok::kw_struct) ||
-  (Style.isJavaScript() && 
CurrentToken->is(ExtraKeywords.kw_function)))
-return true;
-  if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
-return true;
-  CurrentToken = CurrentToken->Next;
+int BracketLevel = 0;
+for (const FormatToken *CurrentToken = Line->First; CurrentToken;
+ CurrentToken = CurrentToken->Next) {
+  if (BracketLevel == 0) {
+if ((CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
+   tok::kw_union) ||
+ (Style.isJavaScript() &&
+  CurrentToken->is(ExtraKeywords.kw_function
+  return true;
+if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
+  return true;
+  }
+  BracketLevel += GetBracketLevelChange(CurrentToken);
 }
 return false;
   };
@@ -102,14 +114,17 @@ void DefinitionBlockSeparator::separateBlocks(
  IsPPConditional(OpeningLineIndex - 1);
 };
 const auto HasEnumOnLine = [&]() {
-  FormatToken *CurrentToken = CurrentLine->First;
   bool FoundEnumKeyword = false;
-  while (CurrentToken) {
-if (CurrentToken->is(tok::kw_enum))
-  FoundEnumKeyword = true;
-else if (FoundEnumKeyword && CurrentToken->is(tok::l_brace))
-  return true;
-CurrentToken = CurrentToken->Next;
+  int BracketLevel = 0;
+  for (const FormatToken *CurrentToken = CurrentLine->First; CurrentToken;
+   CurrentToken = CurrentToken->Next) {
+if (BracketLevel == 0) {
+  if (CurrentToken->is(tok::kw_enum))
+FoundEnumKeyword = true;
+  else if (FoundEnumKeyword && CurrentToken->is(tok::l_brace))
+return true;
+}
+BracketLevel += GetBracketLevelChange(CurrentToken);
   }
   return FoundEnumKeyword && I + 1 < Lines.size() &&
  Lines[I + 1]->First->is(tok::l_brace);

diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 4cbae0f55b03..582b62e445df 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -109,6 +109,15 @@ TEST_F(DefinitionBlockSeparatorTest, Basic) {
"};",
Style);
 
+  verifyFormat("union foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "union bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
   verifyFormat("class foo {\n"
"  int i, j;\n"
"};\n"
@@ -311,6 +320,9 @@ TEST_

[PATCH] D117390: [AST] Reformat CastExpr unittest suite

2022-02-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

In D117390#3290715 , @kimgr wrote:

> @aaron.ballman Thanks! Please use Kim Gräsman and kim.grasman at gmail.com.

You're welcome. I've pushed on your behalf in 
d7ddad408f5b64df39a39f4af3a631275961b975 
. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117390

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


[PATCH] D119067: [clang-format] Fix DefinitionBlockSeparator extra empty lines

2022-02-07 Thread ksyx via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa70549ae43df: [clang-format] Fix DefSeparator empty line 
issues (authored by ksyx).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119067

Files:
  clang/lib/Format/DefinitionBlockSeparator.cpp
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -109,6 +109,15 @@
"};",
Style);
 
+  verifyFormat("union foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "union bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
   verifyFormat("class foo {\n"
"  int i, j;\n"
"};\n"
@@ -311,6 +320,9 @@
   "int bar3(int j, int k, const enum Bar b) {\n"
   "  // A comment\n"
   "  int r = j % k;\n"
+  "  if (struct S = getS()) {\n"
+  "// if condition\n"
+  "  }\n"
   "  return r;\n"
   "}\n";
   std::string Postfix = "\n"
@@ -364,6 +376,9 @@
 "int bar3(int j, int k, const enum Bar b) {\n"
 "  // A comment\n"
 "  int r = j % k;\n"
+"  if (struct S = getS()) {\n"
+"// if condition\n"
+"  }\n"
 "  return r;\n"
 "}\n"
 "} // namespace";
@@ -425,6 +440,10 @@
"{\n"
"  // A comment\n"
"  int r = j % k;\n"
+   "  if (struct S = getS())\n"
+   "  {\n"
+   "// if condition\n"
+   "  }\n"
"  return r;\n"
"}\n"
"} // namespace NS",
@@ -473,6 +492,9 @@
 "int bar3(int j, int k, const enum Bar b) {\n"
 "  // A comment\n"
 "  int r = j % k;\n"
+"  if (struct S = getS()) {\n"
+"// if condition\n"
+"  }\n"
 "  return r;\n"
 "}\n"
 "} // namespace";
Index: clang/lib/Format/DefinitionBlockSeparator.cpp
===
--- clang/lib/Format/DefinitionBlockSeparator.cpp
+++ clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -35,19 +35,31 @@
   const bool IsNeverStyle =
   Style.SeparateDefinitionBlocks == FormatStyle::SDS_Never;
   const AdditionalKeywords &ExtraKeywords = Tokens.getKeywords();
-  auto LikelyDefinition = [this, ExtraKeywords](const AnnotatedLine *Line,
-bool ExcludeEnum = false) {
+  auto GetBracketLevelChange = [](const FormatToken *Tok) {
+if (Tok->isOneOf(tok::l_brace, tok::l_paren, tok::l_square))
+  return 1;
+if (Tok->isOneOf(tok::r_brace, tok::r_paren, tok::r_square))
+  return -1;
+return 0;
+  };
+  auto LikelyDefinition = [&](const AnnotatedLine *Line,
+  bool ExcludeEnum = false) {
 if ((Line->MightBeFunctionDecl && Line->mightBeFunctionDefinition()) ||
 Line->startsWithNamespace())
   return true;
-FormatToken *CurrentToken = Line->First;
-while (CurrentToken) {
-  if (CurrentToken->isOneOf(tok::kw_class, tok::kw_struct) ||
-  (Style.isJavaScript() && CurrentToken->is(ExtraKeywords.kw_function)))
-return true;
-  if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
-return true;
-  CurrentToken = CurrentToken->Next;
+int BracketLevel = 0;
+for (const FormatToken *CurrentToken = Line->First; CurrentToken;
+ CurrentToken = CurrentToken->Next) {
+  if (BracketLevel == 0) {
+if ((CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
+   tok::kw_union) ||
+ (Style.isJavaScript() &&
+  CurrentToken->is(ExtraKeywords.kw_function
+  return true;
+if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
+  return true;
+  }
+  BracketLevel += GetBracketLevelChange(CurrentToken);
 }
 return false;
   };
@@ -102,14 +114,17 @@
  IsPPConditional(OpeningLineIndex - 1);
 };
 const auto HasEnumOnLine = [&]() {
-  FormatToken *CurrentToken = CurrentLine->First;
   bool FoundEnumKeyword = false;
-  while (CurrentToken) {
-if (CurrentToken->is(tok::kw_enum))

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406428.
awarzynski added a comment.

Remove the calls to `setTargetTriple` and `setKindMapping`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! Test the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,76 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  mlir::PassManager pm(mlirCtx.get(), mlir::OpPassManager::Nesting::Implicit);
+
+  pm.add

[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-07 Thread Iannis de Zwart via Phabricator via cfe-commits
iannisdezwart accepted this revision.
iannisdezwart added a comment.
This revision is now accepted and ready to land.

In D119077#3300271 , @nridge wrote:

> I haven't looked at the patch in detail, but one high level question: have 
> you considered the possibility of adding these highlightings during the 
> findExplicitReferences 
> 
>  phase, rather than in `CollectExtraHighlightings`? (I haven't thought 
> through whether that would work, just wondering if you have. The reason this 
> is worth asking is that if we can get `findExplicitReferences` to handle 
> overloaded operator calls, other clangd features that use 
> `findExplicitReferences` would benefit from knowing about such calls as well.)

I have in fact looked at the possibility of adding the code into 
`findExplicitReferences`, but I figured it would be more suitable to add it 
into `CollectExtraHighlightings`, because it is easier to distinguish 
declarations from references. In `findExplicitReferences` the declaration will 
be traversed multiple times, so it would be a pain to check if it had already 
been traversed. I found it was relatively easy to write code that would work in 
`CollectExtraHighlightings`, and I also don't know for sure if it's even 
possible to handle all cases in `findExplicitReferences`.


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

https://reviews.llvm.org/D119077

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


[PATCH] D118605: [OpenCL] Add support of language builtins for OpenCL C 3.0

2022-02-07 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov updated this revision to Diff 406434.
azabaznov added a comment.

Check only against specific language option, remove unused LanguageIDs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118605

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/Builtins.h
  clang/lib/Basic/Builtins.cpp
  clang/test/CodeGenOpenCL/cl20-device-side-enqueue.cl
  clang/test/CodeGenOpenCL/pipe_types.cl
  clang/test/CodeGenOpenCL/to_addr_builtin.cl
  clang/test/SemaOpenCL/cl20-device-side-enqueue.cl
  clang/test/SemaOpenCL/clang-builtin-version.cl
  clang/test/SemaOpenCL/to_addr_builtin.cl

Index: clang/test/SemaOpenCL/to_addr_builtin.cl
===
--- clang/test/SemaOpenCL/to_addr_builtin.cl
+++ clang/test/SemaOpenCL/to_addr_builtin.cl
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -verify -fsyntax-only %s
 // RUN: %clang_cc1 -Wconversion -verify -fsyntax-only -cl-std=CL2.0 %s
+// RUN: %clang_cc1 -Wconversion -verify -fsyntax-only -cl-std=CL3.0 -cl-ext=-all %s
+// RUN: %clang_cc1 -Wconversion -verify -fsyntax-only -cl-std=CL3.0 %s
 
 void test(void) {
   global int *glob;
@@ -11,7 +13,7 @@
   const_int_ty *con_typedef;
 
   glob = to_global(glob, loc);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-error@-2{{implicit declaration of function 'to_global' is invalid in OpenCL}}
   // expected-warning@-3{{incompatible integer to pointer conversion assigning to '__global int *__private' from 'int'}}
 #else
@@ -20,28 +22,28 @@
 
   int x;
   glob = to_global(x);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-warning@-2{{incompatible integer to pointer conversion assigning to '__global int *__private' from 'int'}}
 #else
   // expected-error@-4{{invalid argument x to function: 'to_global', expecting a generic pointer argument}}
 #endif
 
   glob = to_global(con);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-warning@-2{{incompatible integer to pointer conversion assigning to '__global int *__private' from 'int'}}
 #else
   // expected-error@-4{{invalid argument con to function: 'to_global', expecting a generic pointer argument}}
 #endif
 
   glob = to_global(con_typedef);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-warning@-2{{incompatible integer to pointer conversion assigning to '__global int *__private' from 'int'}}
 #else
   // expected-error@-4{{invalid argument con_typedef to function: 'to_global', expecting a generic pointer argument}}
 #endif
 
   loc = to_global(glob);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-warning@-2{{incompatible integer to pointer conversion assigning to '__local int *__private' from 'int'}}
 #else
   // expected-error@-4{{assigning '__global int *' to '__local int *__private' changes address space of pointer}}
@@ -49,7 +51,7 @@
 #endif
 
   loc = to_private(glob);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-error@-2{{implicit declaration of function 'to_private' is invalid in OpenCL}}
   // expected-warning@-3{{incompatible integer to pointer conversion assigning to '__local int *__private' from 'int'}}
 #else
@@ -58,17 +60,17 @@
 #endif
 
   loc = to_local(glob);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-error@-2{{implicit declaration of function 'to_local' is invalid in OpenCL}}
   // expected-warning@-3{{incompatible integer to pointer conversion assigning to '__local int *__private' from 'int'}}
   // expected-note@-4{{did you mean 'to_global'}}
-  // expected-note@13{{'to_global' declared here}}
+  // expected-note@15{{'to_global' declared here}}
 #else
   // expected-warning@-7{{passing non-generic address space pointer to to_local may cause dynamic conversion affecting performance}}
 #endif
 
   priv = to_global(glob);
-#if __OPENCL_C_VERSION__ < CL_VERSION_2_0
+#if (__OPENCL_C_VERSION__ < CL_VERSION_2_0) || (__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && !defined(__opencl_c_generic_address_space))
   // expected-warni

[PATCH] D118605: [OpenCL] Add support of language builtins for OpenCL C 3.0

2022-02-07 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov marked 4 inline comments as done.
azabaznov added inline comments.



Comment at: clang/lib/Basic/Builtins.cpp:79
+  bool OclBlocksUnsupported =
+  (LangOpts.getOpenCLCompatibleVersion() < 200 || !LangOpts.Blocks) &&
+  (BuiltinInfo.Langs & OCL_BLOCKS);

This check is needed as //-cl-std=CL1.2// can be used together with 
//-fblocks//. But in 3.0 block support requires //__opencl_c_device_enqueue// 
feature.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118605

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


[PATCH] D118924: [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 406437.
curdeius marked an inline comment as done.
curdeius added a comment.

Clean up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118924

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,26 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
+  const FormatToken &Tok,
+  bool PreviousWasComment) {
+  auto IsFirstOnLine = [](const FormatToken &Tok) {
+return Tok.HasUnescapedNewline || Tok.IsFirst;
+  };
+
+  // Consider preprocessor directives preceded by block comments as first
+  // on line.
+  if (PreviousWasComment)
+return FirstNonCommentOnLine || IsFirstOnLine(Tok);
+  return IsFirstOnLine(Tok);
+};
+
+FirstNonCommentOnLine = IsFirstNonCommentOnLine(
+FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
+PreviousWasComment = FormatTok->Tok.is(tok::comment);
+
 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
-   (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
+   FirstNonCommentOnLine) {
   distributeComments(Comments, FormatTok);
   Comments.clear();
   // If there is an unfinished unwrapped line, we flush the preprocessor
@@ -3585,6 +3605,9 @@
 Line->Level += PPBranchLevel;
   flushComments(isOnNewLine(*FormatTok));
   parsePPDirective();
+  PreviousWasComment = FormatTok->Tok.is(tok::comment);
+  FirstNonCommentOnLine = IsFirstNonCommentOnLine(
+  FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
 }
 
 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3549,6 +3549,8 @@
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3565,8 +3567,26 @@
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
+  const FormatToken &Tok,
+  bool PreviousWasComm

[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-02-07 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
cor3ntin requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

Implement P2036R3.

Captured variables by copy (explicitely or not), are deduced
correctly at the point we know whether the lambda is mutable,
and ill-formed before that.

Up until now, the entire lambda declaration up to the start
of the body would be parsed in the parent scope, such that capture
would not be available to look up.

The scoping is changed to have an outer lambda scope, followed
by the lambda prototype and body.

The lambda scope is necessary because there may be a template
scope between the start of the lambda (to which we want to attach
the captured variable) and the prototype scope.

We also need to introduce a declaration context to attach
the captured variable to (and several parts of clang assume captures
are handled from the call operator context), before we know
the type of the call operator.

The order of operations is as follow:

- Parse the init capture in the lambda's parent scope

- Introduce a lambda scope

- Create the lambda class and call operator

- Add the init captures to the call operator context and the lambda

scope. But the variables are not capured yet (because we don't know their type).
Instead, explicit  captures are stored in a temporary map
that conserves the order of capture
(for the purpose of having a stable order in the ast dumps).

- A flag is set on LambdaScopeInfo to indicate that we have not yet

injected the captures.

- The parameters are parsed (in the parent context, as lambda

mangling recurses in the parent context, we couldn't mangle a lambda
that is attached to the context of a lambda whose type is not yet known).

- The lambda qualifiers are parsed, at this point We

can switch (for the second time) inside the lambda context,
unset the flag indicating that we have not parsed the lambda qualifiers,
record the lambda is mutable and capture the explicit variables.

- We can parse the resrt of the lambda type, transform the lambda

and call operator's types and also transform the call operator to
a template function decl where necessary.

At this point, both captures and parameters can be injected
in the body's scope.

When trying to capture an implicit variable, if
we are before the qualifiers of a lambda,
we need to remember that the variables are still in the parent's
context (rather than in the call operator's).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119136

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1348,7 +1348,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3";>P2036R3
-  No
+  Clang 15
 
 
   Multidimensional subscript operator
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,134 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [&x = y](
+ decltype([&]

[PATCH] D118924: [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

@HazardyKnusperkeks, sorry for that. Should be better now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118924

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


[PATCH] D118104: Make run-clang-tidy.py print the configured checks correctly

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

In D118104#3297315 , 
@LegalizeAdulthood wrote:

> In D118104#3296467 , 
> @salman-javed-nz wrote:
>
>> Anyway, I don't want what was a drive-by comment by me baloon into a lot of 
>> extra work for the author, so I will not push for it, unless others really 
>> want it.
>
> I think it's reasonable to accept this change and have the tests added as a 
> follow-up change.

Normally I'd be opposed to this, but given the testing difficulties with this 
tool are not new and this patch doesn't make them substantially worse, I think 
it's fine to land as-is and address testing in a follow-up.


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

https://reviews.llvm.org/D118104

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


[PATCH] D117569: Constexpr not supported with __declspec(dllimport).

2022-02-07 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 406443.

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

https://reviews.llvm.org/D117569

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/CodeGenCXX/PR19955.cpp
  clang/test/CodeGenCXX/dllimport.cpp
  clang/test/SemaCXX/PR19955.cpp
  clang/test/SemaCXX/dllimport-constexpr.cpp

Index: clang/test/SemaCXX/dllimport-constexpr.cpp
===
--- clang/test/SemaCXX/dllimport-constexpr.cpp
+++ clang/test/SemaCXX/dllimport-constexpr.cpp
@@ -40,7 +40,6 @@
 // constexpr initialization doesn't work for dllimport things.
 // expected-error@+1{{must be initialized by a constant expression}}
 constexpr void (*constexpr_import_func)() = &imported_func;
-// expected-error@+1{{must be initialized by a constant expression}}
 constexpr int *constexpr_import_int = &imported_int;
 // expected-error@+1{{must be initialized by a constant expression}}
 constexpr void (Foo::*constexpr_memptr)() = &Foo::imported_method;
@@ -60,3 +59,14 @@
   // expected-note@+1 {{requested here}}
   StaticConstexpr::g_fp();
 }
+
+void foo() {
+  extern int __declspec(dllimport) dll_import_int;
+  constexpr int &dll_import_constexpr_ref = dll_import_int;
+}
+
+extern int __declspec(dllimport) dll_import_int;
+constexpr int &dll_import_constexpr_ref = dll_import_int;
+int goo() {
+  return dll_import_constexpr_ref;
+}
Index: clang/test/SemaCXX/PR19955.cpp
===
--- clang/test/SemaCXX/PR19955.cpp
+++ clang/test/SemaCXX/PR19955.cpp
@@ -2,7 +2,7 @@
 // RUN: %clang_cc1 -triple i686-mingw32 -verify -std=c++11 %s
 
 extern int __attribute__((dllimport)) var;
-constexpr int *varp = &var; // expected-error {{must be initialized by a constant expression}}
+constexpr int *varp = &var;
 
 extern __attribute__((dllimport)) void fun();
 constexpr void (*funp)(void) = &fun; // expected-error {{must be initialized by a constant expression}}
Index: clang/test/CodeGenCXX/dllimport.cpp
===
--- clang/test/CodeGenCXX/dllimport.cpp
+++ clang/test/CodeGenCXX/dllimport.cpp
@@ -98,8 +98,8 @@
 USE(inlineStaticLocalsFunc);
 
 // The address of a dllimport global cannot be used in constant initialization.
-// M32-DAG: @"?arr@?1??initializationFunc@@YAPAHXZ@4QBQAHB" = internal global [1 x i32*] zeroinitializer
-// GNU-DAG: @_ZZ18initializationFuncvE3arr = internal global [1 x i32*] zeroinitializer
+// M32-DAG: @"?arr@?1??initializationFunc@@YAPAHXZ@4QBQAHB" = internal constant [1 x i32*] [i32* @"?ExternGlobalDecl@@3HA"]
+// GNU-DAG: @_ZZ18initializationFuncvE3arr = internal constant [1 x i32*] [i32* @ExternGlobalDecl]
 int *initializationFunc() {
   static int *const arr[] = {&ExternGlobalDecl};
   return arr[0];
Index: clang/test/CodeGenCXX/PR19955.cpp
===
--- clang/test/CodeGenCXX/PR19955.cpp
+++ clang/test/CodeGenCXX/PR19955.cpp
@@ -6,20 +6,16 @@
 
 extern int *varp;
 int *varp = &var;
-// CHECK-DAG: @"?varp@@3PAHA" = dso_local global i32* null
-// X64-DAG: @"?varp@@3PEAHEA" = dso_local global i32* null
+// CHECK-DAG: @"?var@@3HA" = external dllimport global i32
+// CHECK-DAG: @"?varp@@3PAHA" = dso_local global i32* @"?var@@3HA"
+// X64-DAG: @"?var@@3HA" = external dllimport global i32, align 4
+// X64-DAG: @"?varp@@3PEAHEA" = dso_local global i32* @"?var@@3HA"
 
 extern void (*funp)();
 void (*funp)() = &fun;
 // CHECK-DAG: @"?funp@@3P6AXXZA" = dso_local global void ()* null
 // X64-DAG: @"?funp@@3P6AXXZEA" = dso_local global void ()* null
 
-// CHECK-LABEL: @"??__Evarp@@YAXXZ"
-// CHECK-DAG: store i32* @"?var@@3HA", i32** @"?varp@@3PAHA"
-
-// X64-LABEL: @"??__Evarp@@YAXXZ"
-// X64-DAG: store i32* @"?var@@3HA", i32** @"?varp@@3PEAHEA"
-
 // CHECK-LABEL: @"??__Efunp@@YAXXZ"()
 // CHECK-DAG: store void ()* @"?fun@@YAXXZ", void ()** @"?funp@@3P6AXXZA"
 
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2211,9 +2211,13 @@
 // FIXME: Diagnostic!
 return false;
 
-  // A dllimport variable never acts like a constant, unless we're
-  // evaluating a value for use only in name mangling.
-  if (!isForManglingOnly(Kind) && Var->hasAttr())
+  // A dllimport variable in C99, or a dllexport variable in C++ never acts
+  // like a constant, unless we're evaluating a value for use only in name
+  // mangling.
+  if (Info.getLangOpts().C99 && !isForManglingOnly(Kind) &&
+  Var->hasAttr() ||
+  Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
+  Var->hasAttr())
 // FIXME: Diagnostic!
 return false;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commit

[PATCH] D118880: [analyzer] Improve NoOwnershipChangeVisitor's understanding of deallocators

2022-02-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I like it.
nits here and there;




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h:102
 
+  /// Returns true if the CallEvent is a call to a function that matches
+  /// the CallDescription.

CallExpr



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:750
   SymbolRef Sym;
+  const MallocChecker *Checker;
   using OwnerSet = llvm::SmallPtrSet;

What about having a const reference, or a const pointer to const?



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:802
 
+  bool isFreeingCallImprecise(const CallExpr &Call) const {
+if (Checker->FreeingMemFnMap.lookupImprecise(Call) ||

You should probably add an example of when is it imprecise and an explanation 
of why we have this function.



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:807
+
+if (const auto *Func = dyn_cast(Call.getCalleeDecl()))
+  return MallocChecker::isFreeingOwnershipAttrCall(Func);





Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:818-819
   return false;
-// TODO: Operator delete is hardly the only deallocator -- Can we reuse
+// TODO: Operator delete is hardly the only deallocatr -- Can we reuse
 // isFreeingCall() or something thats already here?
+auto Matches = match(findAll(stmt(anyOf(cxxDeleteExpr().bind("delete"),

I guess, this gets fixed by this patch.



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:820-831
+auto Matches = match(findAll(stmt(anyOf(cxxDeleteExpr().bind("delete"),
+callExpr().bind("call",
+ *FD->getBody(), ACtx);
+for (BoundNodes Match : Matches) {
+  if (Match.getNodeAs("delete")) {
+return true;
+  }

Without braces, it would be slightly more compact & readable IMO.



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:832
+}
 // TODO: Ownership my change with an attempt to store the allocated memory.
+return false;

Could you clarify what this wants to denote? I'm just curious.



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:1104
+
+  if (const auto *Func = dyn_cast(Call.getDecl()))
+return isFreeingOwnershipAttrCall(Func);





Comment at: clang/test/Analysis/NewDeleteLeaks.cpp:152
+  // like to deallocate anything.
+  bar();
+}

I guess we would not have the warning if `bar` would accept the pointer `P`, 
since that way it would escape.
Am I correct?


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

https://reviews.llvm.org/D118880

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


[PATCH] D113319: [clang-format] Improve require and concept handling

2022-02-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks updated this revision to Diff 406444.
HazardyKnusperkeks added a comment.

Small fix in the test. For this change it is not relevant, but for the next one.


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

https://reviews.llvm.org/D113319

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -14,6 +14,14 @@
 
 namespace clang {
 namespace format {
+
+// Not really the equality, but everything we need.
+static bool operator==(const FormatToken &LHS,
+   const FormatToken &RHS) noexcept {
+  return LHS.Tok.getKind() == RHS.Tok.getKind() &&
+ LHS.getType() == RHS.getType();
+}
+
 namespace {
 
 class TokenAnnotatorTest : public ::testing::Test {
@@ -97,6 +105,261 @@
   EXPECT_TOKEN(Tokens[4], tok::l_brace, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsRequiresClausesAndConcepts) {
+  auto Tokens = annotate("template \n"
+ "concept C = (Foo && Bar) && (Bar && Baz);");
+
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[16], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("template \n"
+"concept C = requires(T t) {\n"
+"  { t.foo() };\n"
+"} && Bar && Baz;");
+  ASSERT_EQ(Tokens.size(), 35u) << Tokens;
+  EXPECT_TOKEN(Tokens[23], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[28], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("template\n"
+"requires C1 && (C21 || C22 && C2e) && C3\n"
+"struct Foo;");
+  ASSERT_EQ(Tokens.size(), 36u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::identifier, TT_Unknown);
+  EXPECT_EQ(Tokens[6]->FakeLParens.size(), 1u);
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[16], tok::pipepipe, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[21], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[27], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[31], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[31]->FakeRParens, 1u);
+  EXPECT_TRUE(Tokens[31]->ClosesRequiresClause);
+
+  Tokens =
+  annotate("template\n"
+   "requires (C1 && (C21 || C22 && C2e) && C3)\n"
+   "struct Foo;");
+  ASSERT_EQ(Tokens.size(), 38u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::identifier, TT_Unknown);
+  EXPECT_EQ(Tokens[7]->FakeLParens.size(), 1u);
+  EXPECT_TOKEN(Tokens[11], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[17], tok::pipepipe, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[22], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[28], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[32], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[32]->FakeRParens, 1u);
+  EXPECT_TOKEN(Tokens[33], tok::r_paren, TT_Unknown);
+  EXPECT_TRUE(Tokens[33]->ClosesRequiresClause);
+}
+
+TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
+  auto NumberOfAdditionalRequiresClauseTokens = 5u;
+  auto NumberOfTokensBeforeRequires = 5u;
+
+  auto BaseTokens = annotate("template\n"
+ "T Pi = 3.14;");
+  auto ConstrainedTokens = annotate("template\n"
+"  requires Foo\n"
+"T Pi = 3.14;");
+
+  auto NumberOfBaseTokens = 11u;
+
+  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
+  ASSERT_EQ(ConstrainedTokens.size(),
+NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
+  << ConstrainedTokens;
+
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
+if (I < NumberOfTokensBeforeRequires)
+  EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
+else
+  EXPECT_EQ(*BaseTokens[I],
+*ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
+  << I;
+
+  BaseTokens = annotate("template\n"
+"struct Bar;");
+  ConstrainedTokens = annotate("template\n"
+   "  requires Foo\n"
+   "struct Bar;");
+  NumberOfBaseTokens = 9u;
+
+  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
+  ASSERT_EQ(ConstrainedTokens.size(),
+NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
+  << Con

[PATCH] D119138: [clang-format] Further improve support for requires expressions

2022-02-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: MyDeveloperDay, curdeius, owenpan.
HazardyKnusperkeks added a project: clang-format.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Detect requires expressions in more unusable contexts. This is far from
perfect, but currently we have no good metric to decide between a
requires expression and a trailing requires clause.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119138

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -119,6 +119,9 @@
 "  { t.foo() };\n"
 "} && Bar && Baz;");
   ASSERT_EQ(Tokens.size(), 35u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[9], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[23], tok::ampamp, TT_BinaryOperator);
   EXPECT_TOKEN(Tokens[28], tok::ampamp, TT_BinaryOperator);
 
@@ -126,6 +129,7 @@
 "requires C1 && (C21 || C22 && C2e) && C3\n"
 "struct Foo;");
   ASSERT_EQ(Tokens.size(), 36u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[6], tok::identifier, TT_Unknown);
   EXPECT_EQ(Tokens[6]->FakeLParens.size(), 1u);
   EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_BinaryOperator);
@@ -141,6 +145,7 @@
"requires (C1 && (C21 || C22 && C2e) && C3)\n"
"struct Foo;");
   ASSERT_EQ(Tokens.size(), 38u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[7], tok::identifier, TT_Unknown);
   EXPECT_EQ(Tokens[7]->FakeLParens.size(), 1u);
   EXPECT_TOKEN(Tokens[11], tok::ampamp, TT_BinaryOperator);
@@ -151,6 +156,72 @@
   EXPECT_EQ(Tokens[32]->FakeRParens, 1u);
   EXPECT_TOKEN(Tokens[33], tok::r_paren, TT_Unknown);
   EXPECT_TRUE(Tokens[33]->ClosesRequiresClause);
+
+  Tokens = annotate("template \n"
+"void foo(T) noexcept requires Bar;");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[11], tok::kw_requires, TT_RequiresClause);
+
+  Tokens = annotate("template \n"
+"struct S {\n"
+"  void foo() const requires Bar;\n"
+"  void bar() const & requires Baz;\n"
+"  void bar() && requires Baz2;\n"
+"  void baz() const & noexcept requires Baz;\n"
+"  void baz() && noexcept requires Baz2;\n"
+"};\n"
+"\n"
+"void S::bar() const & requires Baz { }");
+  ASSERT_EQ(Tokens.size(), 85u) << Tokens;
+  EXPECT_TOKEN(Tokens[13], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[25], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[36], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[49], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[61], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[77], tok::kw_requires, TT_RequiresClause);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {
+  auto Tokens = annotate("bool b = requires(int i) { i + 5; };");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_RequiresExpressionLBrace);
+
+  Tokens = annotate("if (requires(int i) { i + 5; }) return;");
+  ASSERT_EQ(Tokens.size(), 17u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[3], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[7], tok::l_brace, TT_RequiresExpressionLBrace);
+
+  Tokens = annotate("if (func() && requires(int i) { i + 5; }) return;");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[7], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[11], tok::l_brace, TT_RequiresExpressionLBrace);
+
+  Tokens = annotate("template \n"
+"concept C = requires(T T) {\n"
+"  requires Bar && Foo;\n"
+"};");
+  ASSERT_EQ(Tokens.size(), 28u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[9], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
+  EXPECT_TOKEN(Tokens[14], tok

[PATCH] D116597: [analyzer] Don't track function calls as control dependencies

2022-02-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Looks great!
Thanks for your hard work on this topic @Szelethus.




Comment at: clang/lib/Analysis/CFG.cpp:5908-5909
 
+void CFG::dump(bool ShowColors) const { dump(LangOptions{}, ShowColors); }
+
 /// print - A simple pretty printer of a CFG that outputs to an ostream.

How are these `dump()` changes related?



Comment at: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1968
+static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N) {
+
   Ex = Ex->IgnoreParenCasts();

extra blank line



Comment at: clang/test/Analysis/track-control-dependency-conditions.cpp:1006
+  x = nullptr;  // expected-note {{Null pointer value stored to 
'x'}}
+  if (auto e = couldFail()) // expected-note {{Taking true branch}}
+*x = 5; // expected-warning {{Dereference of null pointer 
(loaded from variable 'x') [core.NullDereference]}}

Please also have a `c++17` init if statement.



Comment at: clang/test/Analysis/track-control-dependency-conditions.cpp:1036
+  x = nullptr;// expected-note {{Null pointer value stored to 'x'}}
+  if (!alwaysFalse()) // expected-note {{Taking true branch}}
+*x = 5;   // expected-warning {{Dereference of null pointer 
(loaded from variable 'x') [core.NullDereference]}}

What if this expression is enclosed by a logical operator such as `&&`?


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

https://reviews.llvm.org/D116597

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


[PATCH] D113369: [clang-format] Extend SpaceBeforeParens for requires

2022-02-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks updated this revision to Diff 406450.
HazardyKnusperkeks marked 4 inline comments as done.
HazardyKnusperkeks added a reviewer: curdeius.
HazardyKnusperkeks removed a subscriber: curdeius.
HazardyKnusperkeks added a comment.
This revision is now accepted and ready to land.

- Rebased
- Updated
- Tests changed


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

https://reviews.llvm.org/D113369

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14912,6 +14912,88 @@
   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
+
+  auto SpaceAfterRequires = getLLVMStyle();
+  SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_FALSE(SpaceAfterRequires.SpaceBeforeParensOptions
+   .AfterRequiresKeywordInRequiresClause);
+  EXPECT_FALSE(SpaceAfterRequires.SpaceBeforeParensOptions
+   .AfterRequiresKeywordInRequiresExpression);
+  verifyFormat("void f(auto x)\n"
+   "  requires requires(int i) { x + i; }\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("void f(auto x)\n"
+   "  requires(requires(int i) { x + i; })\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("if (requires(int i) { x + i; })\n"
+   "  return;",
+   SpaceAfterRequires);
+  verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
+  verifyFormat("template \n"
+   "  requires(Foo)\n"
+   "class Bar;",
+   SpaceAfterRequires);
+
+  SpaceAfterRequires.SpaceBeforeParensOptions
+  .AfterRequiresKeywordInRequiresClause = true;
+  verifyFormat("void f(auto x)\n"
+   "  requires requires(int i) { x + i; }\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("void f(auto x)\n"
+   "  requires (requires(int i) { x + i; })\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("if (requires(int i) { x + i; })\n"
+   "  return;",
+   SpaceAfterRequires);
+  verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
+  verifyFormat("template \n"
+   "  requires (Foo)\n"
+   "class Bar;",
+   SpaceAfterRequires);
+
+  SpaceAfterRequires.SpaceBeforeParensOptions
+  .AfterRequiresKeywordInRequiresClause = false;
+  SpaceAfterRequires.SpaceBeforeParensOptions
+  .AfterRequiresKeywordInRequiresExpression = true;
+  verifyFormat("void f(auto x)\n"
+   "  requires requires (int i) { x + i; }\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("void f(auto x)\n"
+   "  requires(requires (int i) { x + i; })\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("if (requires (int i) { x + i; })\n"
+   "  return;",
+   SpaceAfterRequires);
+  verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
+  verifyFormat("template \n"
+   "  requires(Foo)\n"
+   "class Bar;",
+   SpaceAfterRequires);
+
+  SpaceAfterRequires.SpaceBeforeParensOptions
+  .AfterRequiresKeywordInRequiresClause = true;
+  verifyFormat("void f(auto x)\n"
+   "  requires requires (int i) { x + i; }\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("void f(auto x)\n"
+   "  requires (requires (int i) { x + i; })\n"
+   "{}",
+   SpaceAfterRequires);
+  verifyFormat("if (requires (int i) { x + i; })\n"
+   "  return;",
+   SpaceAfterRequires);
+  verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
+  verifyFormat("template \n"
+   "  requires (Foo)\n"
+   "class Bar;",
+   SpaceAfterRequires);
 }
 
 TEST_F(FormatTest, SpaceAfterLogicalNot) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3211,8 +3211,14 @@
   if (Right.is(tok::l_paren)) {
 if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
   return spaceRequiredBeforeParens(Right);
-if (Left.is(tok::kw_requires))
-  return spaceRequiredBeforeParens(Right);
+if (Left.isOneOf(TT_RequiresClause, TT_RequiresClauseInARequiresExpression))
+  return Style.SpaceBeforePare

[PATCH] D113369: [clang-format] Extend SpaceBeforeParens for requires

2022-02-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks requested review of this revision.
HazardyKnusperkeks added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3756
+  * ``bool AfterRequiresClause`` If ``true``, put space between requires 
keyword in a requires clause and
+opening parentheses, if is are one.
+

Quuxplusone wrote:
> HazardyKnusperkeks wrote:
> > Quuxplusone wrote:
> > > HazardyKnusperkeks wrote:
> > > > curdeius wrote:
> > > > > You meant "if there is one", right?
> > > > Yeah
> > > IMO these options should be named `InRequiresClause` and 
> > > `InRequiresExpression`: that's where the space is going. The space 
> > > doesn't go //after// the requires-clause. The space doesn't go //after// 
> > > the requires-expression.
> > > It occurs to me that the name of this option could be analogous to the 
> > > name of the option that controls `[]() {}` versus `[] () {}`... except 
> > > that it looks like there is no such option (and I'm happy about that). :) 
> > > Also, the name of that option would probably just be `AfterCaptureList`, 
> > > which doesn't help us in this case.
> > I get your point, but the space does not go anywhere in the 
> > clause/expression, so `AfterRequiresForClauses`?
> (I'd avoid the word `For`, because of keyword `for`.)
> A //requires-expression// is the whole expression, `requires + param-list + 
> body`: https://eel.is/c++draft/expr.prim.req#nt:requires-expression
> A //requires-clause// is the whole clause, `requires + logical-or-expr`: 
> https://eel.is/c++draft/temp.pre#nt:requires-clause
> Does that resolve your concern about the word `In`?
My concern is: `In` may refer to anywhere in the clause, but we are talking 
about one very specific point per clause. (Analogues for expression.)

The current version is very explicit, and I don't have a problem with such a 
long name.



Comment at: clang/include/clang/Format/Format.h:3371
+/// If ``true``, put space between requires keyword in a requires clause 
and
+/// opening parentheses, if there is one.
+/// \code

Quuxplusone wrote:
> Here and line 3380, and possibly elsewhere: `s/parentheses/parenthesis/`
Non native here, but I think one could argue both were okay. I just copied what 
the other options state.


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

https://reviews.llvm.org/D113369

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-07 Thread Iannis de Zwart via Phabricator via cfe-commits
iannisdezwart updated this revision to Diff 406452.
iannisdezwart added a comment.

Fixed formatting & reverted a deleted FIXME comment.


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

https://reviews.llvm.org/D119077

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -109,7 +109,7 @@
 $Class[[AS]] $LocalVariable_decl[[AA]];
 $Primitive_deduced_defaultLibrary[[auto]] $LocalVariable_decl[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
 auto $LocalVariable_decl[[FN]] = [ $LocalVariable[[AA]]](int $Parameter_decl[[A]]) -> void {};
-$LocalVariable[[FN]](12312);
+$LocalVariable[[FN]]$Method_readonly[[(]]12312$Method_readonly[[)]];
   }
 )cpp",
   R"cpp(
@@ -138,7 +138,7 @@
   struct $Class_decl[[B]] {
 $Class_decl[[B]]();
 ~$Class[[B]](); // FIXME: inconsistent with constructor
-void operator<<($Class[[B]]);
+void $Method_decl[[operator<<]]($Class[[B]]);
 $Class[[AAA]] $Field_decl[[AA]];
   };
   $Class[[B]]::$Class_decl[[B]]() {}
@@ -289,10 +289,10 @@
   struct $Class_decl[[B]] {};
   struct $Class_decl[[A]] {
 $Class[[B]] $Field_decl[[BB]];
-$Class[[A]] &operator=($Class[[A]] &&$Parameter_decl[[O]]);
+$Class[[A]] &$Method_decl[[operator=]]($Class[[A]] &&$Parameter_decl[[O]]);
   };
 
-  $Class[[A]] &$Class[[A]]::operator=($Class[[A]] &&$Parameter_decl[[O]]) = default;
+  $Class[[A]] &$Class[[A]]::$Method_decl[[operator=]]($Class[[A]] &&$Parameter_decl[[O]]) = default;
 )cpp",
   R"cpp(
   enum $Enum_decl[[En]] {
@@ -777,7 +777,7 @@
 void $Function_decl[[foo]]() {
   int $LocalVariable_decl[[a]], $LocalVariable_decl[[b]];
   [ $LocalVariable_decl[[c]] = $LocalVariable[[a]],
-$LocalVariable_decl[[d]]($LocalVariable[[b]]) ]() {}();
+$LocalVariable_decl[[d]]($LocalVariable[[b]]) ]() {}$Method_readonly[[(]]$Method_readonly[[)]];
 }
   )cpp",
   // Enum base specifier
@@ -790,6 +790,34 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
+  // Overloaded operators
+  R"cpp(
+struct $Class_decl[[Foo]] {
+  bool $Method_decl[[operator()]]() { return true; }
+  void $Method_decl[[operator<<]](int $Parameter_decl[[K]]) {}
+  operator bool() {} // FIXME: consider how this should be highlighted.
+};
+
+namespace $Namespace_decl[[namesp]] {
+  void $Function_decl[[operator--]]($Class[[Foo]] $Parameter_decl[[F]])
+  {}
+};
+
+auto $Variable_decl[[a]] =
+  &$Namespace[[namesp]]::$Function[[operator--]];
+
+void $Function_decl[[operator++]]($Class[[Foo]] &$Parameter_decl[[F]])
+{}
+
+int $Function_decl[[main]]() {
+  $Class[[Foo]] $LocalVariable_decl[[foo]];
+  $LocalVariable[[foo]].$Method[[operator()]]();
+  $LocalVariable[[foo]].$Method[[operator<<]](1);
+
+  $Function[[operator++]]($LocalVariable_usedAsMutableReference[[foo]]);
+  $Function[[operator delete[]]]($Function[[operator new[]]](1));
+}
+  )cpp",
   };
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclarationName.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
@@ -26,6 +27,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
@@ -449,8 +451,9 @@
   }
 
   const HeuristicResolver *getResolver() const { return Resolver; }
+  const SourceManager &getSourceMgr() const { return SourceMgr; }
+  const syntax::TokenBuffer &getTB() const { return TB; }
 
-private:
   llvm::Optional getRangeForSourceLocation(SourceLocation Loc) {
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
@@ -463,6 +466,7 @@
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }
 
+private:
 

[PATCH] D113369: [clang-format] Extend SpaceBeforeParens for requires

2022-02-07 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/include/clang/Format/Format.h:3371
+/// If ``true``, put space between requires keyword in a requires clause 
and
+/// opening parentheses, if there is one.
+/// \code

HazardyKnusperkeks wrote:
> Quuxplusone wrote:
> > Here and line 3380, and possibly elsewhere: `s/parentheses/parenthesis/`
> Non native here, but I think one could argue both were okay. I just copied 
> what the other options state.
It's definitely not grammatical to talk about "opening parentheses, if there is 
one". But if this is just copying pre-existing wording, then OK, no objection 
to someone handling the grammar in a followup PR.


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

https://reviews.llvm.org/D113369

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


[PATCH] D118044: [ARM] Undeprecate complex IT blocks

2022-02-07 Thread Mark Murray via Phabricator via cfe-commits
MarkMurrayARM marked 2 inline comments as done.
MarkMurrayARM added inline comments.



Comment at: llvm/test/CodeGen/ARM/ifcvt-branch-weight.ll:21
 
-; CHECK: bb.2.bb2:
+; CHECK: bb.1.bb:
 ; CHECK: successors: %bb.4(0x4000), %bb.3(0x4000)

dmgreen wrote:
> I think this should still be bb.2.bb2
If I do that the test fails. It's definitely like this in the generated code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118044

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


[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-02-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp:102-105
+  // There have been crashes on 'Variable == nullptr', even though the matcher
+  // is not conditional. This comes probably from 'findAll'-matching.
+  if (!Variable || !LocalScope)
+return;

sammccall wrote:
> JonasToth wrote:
> > njames93 wrote:
> > > This sounds like a bug that should be raised with ASTMatchers, if its 
> > > reproducible.
> > I found no way to reproduce it (yet).
> > The crashes occured during verification on big projects and 
> > `run-clang-tidy` kind of obfuscated where the crash happened.
> > 
> > This is something for the iron out part of the check I think.
> This is a bug in a helper added in this patch, I've added a comment above.
Ahh, hopefully once D118520 lands it should be easier to track down these bugs 
and create reproducers


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D119144: [tests][Driver] Pass an empty sysroot for `DEFAULT_SYSROOT` builds

2022-02-07 Thread Carlo Cabrera via Phabricator via cfe-commits
carlocab created this revision.
carlocab added a reviewer: abidh.
carlocab added a project: clang.
Herald added a subscriber: ki.stfu.
carlocab requested review of this revision.
Herald added a subscriber: cfe-commits.

The `baremetal-sysroot` test fails when the toolchain is configured with
`DEFAULT_SYSROOT`. So, to emulate not having passed one at all, let's
pass an empty sysroot instead.

This simply follows D79694 , D66834 
, and D51972 
. D51972  in 
particular was
meant to address a failing test for behaviour when `--sysroot` is not
passed and `DEFAULT_SYSROOT` is set.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119144

Files:
  clang/test/Driver/baremetal-sysroot.cpp


Index: clang/test/Driver/baremetal-sysroot.cpp
===
--- clang/test/Driver/baremetal-sysroot.cpp
+++ clang/test/Driver/baremetal-sysroot.cpp
@@ -10,7 +10,7 @@
 // RUN: ln -s %clang %T/baremetal_default_sysroot/bin/clang
 
 // RUN: %T/baremetal_default_sysroot/bin/clang -no-canonical-prefixes %s -### 
-o %t.o 2>&1 \
-// RUN: -target armv6m-none-eabi \
+// RUN: -target armv6m-none-eabi --sysroot= \
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-C %s
 // CHECK-V6M-C: "{{.*}}clang{{.*}}" "-cc1" "-triple" 
"thumbv6m-none-unknown-eabi"
 // CHECK-V6M-C-SAME: "-internal-isystem" 
"{{.*}}/baremetal_default_sysroot{{[/\\]+}}bin{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}armv6m-none-eabi{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"


Index: clang/test/Driver/baremetal-sysroot.cpp
===
--- clang/test/Driver/baremetal-sysroot.cpp
+++ clang/test/Driver/baremetal-sysroot.cpp
@@ -10,7 +10,7 @@
 // RUN: ln -s %clang %T/baremetal_default_sysroot/bin/clang
 
 // RUN: %T/baremetal_default_sysroot/bin/clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
-// RUN: -target armv6m-none-eabi \
+// RUN: -target armv6m-none-eabi --sysroot= \
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-C %s
 // CHECK-V6M-C: "{{.*}}clang{{.*}}" "-cc1" "-triple" "thumbv6m-none-unknown-eabi"
 // CHECK-V6M-C-SAME: "-internal-isystem" "{{.*}}/baremetal_default_sysroot{{[/\\]+}}bin{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}armv6m-none-eabi{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118876: [HIPSPV] Fix literals are mapped to Generic address space

2022-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

It has been cherry-picked to 14.x by 02d5b112 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118876

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


[PATCH] D117795: [AArch64] Add some missing strict FP vector lowering

2022-02-07 Thread Dave Green via Phabricator via cfe-commits
dmgreen accepted this revision.
dmgreen added a comment.
This revision is now accepted and ready to land.

Thanks for the changes. LGTM


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

https://reviews.llvm.org/D117795

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


[clang] cdc0573 - [MatrixBuilder] Remove unnecessary IRBuilder template (NFC)

2022-02-07 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2022-02-07T16:42:38+01:00
New Revision: cdc0573f753e639ed78f2a3645179ac2d2718fd0

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

LOG: [MatrixBuilder] Remove unnecessary IRBuilder template (NFC)

IRBuilderBase exists specifically to avoid the need for this.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprScalar.cpp
llvm/include/llvm/IR/MatrixBuilder.h
llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a3905e0ea4105..9ed19af901b08 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3231,14 +3231,14 @@ RValue CodeGenFunction::EmitBuiltinExpr(const 
GlobalDecl GD, unsigned BuiltinID,
   case Builtin::BI__builtin_matrix_transpose: {
 auto *MatrixTy = E->getArg(0)->getType()->castAs();
 Value *MatValue = EmitScalarExpr(E->getArg(0));
-MatrixBuilder MB(Builder);
+MatrixBuilder MB(Builder);
 Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
  MatrixTy->getNumColumns());
 return RValue::get(Result);
   }
 
   case Builtin::BI__builtin_matrix_column_major_load: {
-MatrixBuilder MB(Builder);
+MatrixBuilder MB(Builder);
 // Emit everything that isn't dependent on the first parameter type
 Value *Stride = EmitScalarExpr(E->getArg(3));
 const auto *ResultTy = E->getType()->getAs();
@@ -3257,7 +3257,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   }
 
   case Builtin::BI__builtin_matrix_column_major_store: {
-MatrixBuilder MB(Builder);
+MatrixBuilder MB(Builder);
 Value *Matrix = EmitScalarExpr(E->getArg(0));
 Address Dst = EmitPointerWithAlignment(E->getArg(1));
 Value *Stride = EmitScalarExpr(E->getArg(2));

diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index bb5d18b748947..4565f4343aa34 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1932,7 +1932,7 @@ RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, 
SourceLocation Loc) {
 llvm::Value *Idx = LV.getMatrixIdx();
 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
   const auto *const MatTy = LV.getType()->castAs();
-  llvm::MatrixBuilder MB(Builder);
+  llvm::MatrixBuilder MB(Builder);
   MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
 }
 llvm::LoadInst *Load =
@@ -2078,7 +2078,7 @@ void CodeGenFunction::EmitStoreThroughLValue(RValue Src, 
LValue Dst,
   llvm::Value *Idx = Dst.getMatrixIdx();
   if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
 const auto *const MatTy = Dst.getType()->castAs();
-llvm::MatrixBuilder MB(Builder);
+llvm::MatrixBuilder MB(Builder);
 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
   }
   llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 4e8933fffe03b..705e50b58324a 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -731,7 +731,7 @@ class ScalarExprEmitter
 }
 
 if (Ops.Ty->isConstantMatrixType()) {
-  llvm::MatrixBuilder MB(Builder);
+  llvm::MatrixBuilder MB(Builder);
   // We need to check the types of the operands of the operator to get the
   // correct matrix dimensions.
   auto *BO = cast(Ops.E);
@@ -1795,7 +1795,7 @@ Value 
*ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
 
   const auto *MatrixTy = E->getBase()->getType()->castAs();
   unsigned NumRows = MatrixTy->getNumRows();
-  llvm::MatrixBuilder MB(Builder);
+  llvm::MatrixBuilder MB(Builder);
   Value *Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows);
   if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
 MB.CreateIndexAssumption(Idx, MatrixTy->getNumElementsFlattened());
@@ -3263,7 +3263,7 @@ Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
   }
 
   if (Ops.Ty->isConstantMatrixType()) {
-llvm::MatrixBuilder MB(Builder);
+llvm::MatrixBuilder MB(Builder);
 // We need to check the types of the operands of the operator to get the
 // correct matrix dimensions.
 auto *BO = cast(Ops.E);
@@ -3657,7 +3657,7 @@ Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
   }
 
   if (op.Ty->isConstantMatrixType()) {
-llvm::MatrixBuilder MB(Builder);
+llvm::MatrixBuilder MB(Builder);
 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
 return MB.CreateAdd(op.LHS, op.RHS);
   }
@@ -3807,7 +3807,7 @@ Value *Scalar

[PATCH] D118690: [analyzer] Prevent misuses of -analyze-function

2022-02-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 406463.
steakhal added a comment.

- pin target triple to (possibly) resolve the build bot failure
- add obj-c test case


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

https://reviews.llvm.org/D118690

Files:
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  clang/test/Analysis/analyze-function-guide.cpp
  clang/test/Analysis/analyze-function-guide.m

Index: clang/test/Analysis/analyze-function-guide.m
===
--- /dev/null
+++ clang/test/Analysis/analyze-function-guide.m
@@ -0,0 +1,26 @@
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='-[MyClass messageWithFoo:bar:]' \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-MATCH --allow-empty
+//
+// Expected empty standard output.
+// CHECK-MATCH-NOT: Every top-level function was skipped.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='missing_fn' \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-MISSING
+//
+// CHECK-MISSING: Every top-level function was skipped.
+// CHECK-MISSING: Pass the -analyzer-display-progress for tracking which functions are analyzed.
+
+@interface MyClass
+- (int)messageWithFoo:(int)foo bar:(int)bar;
+@end
+
+@implementation MyClass
+- (int)messageWithFoo:(int)foo bar:(int)bar {
+  return foo + bar;
+}
+@end
Index: clang/test/Analysis/analyze-function-guide.cpp
===
--- /dev/null
+++ clang/test/Analysis/analyze-function-guide.cpp
@@ -0,0 +1,81 @@
+int fizzbuzz(int x, bool y) {
+  return x + y;
+}
+
+// C++ but not uses parentheses in the '-analyze-function' option.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='missing_fn' -x c++ \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-CXX
+//
+// CHECK-CXX:  Every top-level function was skipped.
+// CHECK-CXX-NEXT: Pass the -analyzer-display-progress for tracking which functions are analyzed.
+// CHECK-CXX-NEXT: For analyzing C++ code you need to pass the function parameter list: -analyze-function="foobar(int, _Bool)"
+
+// C but uses parentheses in the '-analyze-function' option.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='missing_fn()' -x c -Dbool=_Bool \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-C
+//
+// CHECK-C:  Every top-level function was skipped.
+// CHECK-C-NEXT: Pass the -analyzer-display-progress for tracking which functions are analyzed.
+// CHECK-C-NEXT: For analyzing C code you shouldn't pass the function parameter list, only the name of the function: -analyze-function=foobar
+
+// The user passed the '-analyzer-display-progress' option, we don't need to advocate it.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function=missing_fn \
+// RUN:   -analyzer-display-progress -x c -Dbool=_Bool \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-DONT-ADVOCATE-DISPLAY-PROGRESS
+//
+// CHECK-DONT-ADVOCATE-DISPLAY-PROGRESS: Every top-level function was skipped.
+// CHECK-DONT-ADVOCATE-DISPLAY-PROGRESS-NOT: Pass the -analyzer-display-progress
+
+// The user passed the '-analyze-function' option but that doesn't mach to any declaration.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='missing_fn()' -x c++ \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-ADVOCATE-DISPLAY-PROGRESS
+//
+// CHECK-ADVOCATE-DISPLAY-PROGRESS:  Every top-level function was skipped.
+// CHECK-ADVOCATE-DISPLAY-PROGRESS-NEXT: Pass the -analyzer-display-progress for tracking which functions are analyzed.
+// CHECK-ADVOCATE-DISPLAY-PROGRESS-NOT:  For analyzing
+
+// The user passed the '-analyze-function' option and that matches on a
+// declaration in C++ mode.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='fizzbuzz(int, _Bool)' -x c++ \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-EMPTY --allow-empty
+//
+// Expected empty standard output.
+// CHECK-EMPTY-NOT: Every top-level function was skipped.
+
+// The user passed the '-analyze-function' option and that matches on a
+// declaration in C mode.
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:   -analyze-function='fizzbuzz' -x c -Dbool=_Bool \
+// RUN:   -triple x86_64-pc-linux-gnu 2>&1 %s \
+// RUN: | FileCheck %s -check-prefix=CHECK-EMPTY2 --allow-empty
+//
+// Expected empty standard output.
+// CHECK-EMPTY2-NOT: Every top-level function was skipped.
+
+// Same as the previous but syntax mode only.
+// FIXME: This should have empty standard output.
+//
+// RUN:

[clang] 807e2f1 - Revert "Remove -Wweak-template-vtables"

2022-02-07 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2022-02-07T16:52:23+01:00
New Revision: 807e2f12fab52c6abf3e89c02eec0f585b3b8f22

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

LOG: Revert "Remove -Wweak-template-vtables"

Turns out there's still some code referencing this. No harm in keeping it in a
bit longer.

> as it was planned for removal in clang 15 and we're now past the branch point
>
> See https://github.com/llvm/llvm-project/issues/19107
>
> Differential revision: https://reviews.llvm.org/D118762

This reverts commit 564f9be11c9cb8d131f48df07538fab7a19b41a7.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/test/SemaCXX/warn-weak-vtables.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e96d8dc2e38e6..8704b4f79cd88 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -67,9 +67,6 @@ Modified Compiler Flags
 Removed Compiler Flags
 -
 
-- -Wweak-template-vtables, which was deprecated in the previous release and no
-  longer had any effect, has been removed.
-
 New Pragmas in Clang
 
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 7f73b9b285e37..f9bfd343ac8d1 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1651,6 +1651,9 @@ def warn_weak_vtable : Warning<
   "%0 has no out-of-line virtual method definitions; its vtable will be "
   "emitted in every translation unit">,
   InGroup>, DefaultIgnore;
+def warn_weak_template_vtable : Warning<
+  "this warning is no longer in use and will be removed in the next release">,
+  InGroup>, DefaultIgnore;
 
 def ext_using_undefined_std : ExtWarn<
   "using directive refers to implicitly-defined namespace 'std'">;

diff  --git a/clang/test/SemaCXX/warn-weak-vtables.cpp 
b/clang/test/SemaCXX/warn-weak-vtables.cpp
index 9355af50310d4..083209fa5e315 100644
--- a/clang/test/SemaCXX/warn-weak-vtables.cpp
+++ b/clang/test/SemaCXX/warn-weak-vtables.cpp
@@ -3,6 +3,9 @@
 // Check that this warning is disabled on MS ABI targets which don't have key
 // functions.
 // RUN: %clang_cc1 %s -fsyntax-only -triple %ms_abi_triple -Werror 
-Wweak-vtables
+//
+// -Wweak-template-vtables is deprecated but we still parse it.
+// RUN: %clang_cc1 %s -fsyntax-only -Werror -Wweak-template-vtables
 
 struct A { // expected-warning {{'A' has no out-of-line virtual method 
definitions; its vtable will be emitted in every translation unit}}
   virtual void f() { } 



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


[PATCH] D114439: [Annotation] Allow parameter pack expansions and initializer lists in annotate attribute

2022-02-07 Thread Steffen Larsen via Phabricator via cfe-commits
steffenlarsen updated this revision to Diff 406468.
steffenlarsen added a comment.

Recent changes:

- Replaces `isExprArg` with `isArgMemberExprHolder` which returns true if the 
"argument member" can hold one or more expressions.
- Renames `checkStringLiteralExpr` to `checkASCIIStringLiteralExpr` to better 
convey the intended semantics.
- Reverts changes to `HandleAnnotateAttr` and removes `HandleAnnotationAttr`, 
moving final-args checks of expressions into 
`instantiateDependentAnnotationAttr`.
- Removes nonsensical comment.


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

https://reviews.llvm.org/D114439

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/annotate.c
  clang/test/SemaCXX/attr-annotate.cpp
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -202,9 +202,9 @@
 bool Fake;
 
   public:
-Argument(const Record &Arg, StringRef Attr)
-: lowerName(std::string(Arg.getValueAsString("Name"))),
-  upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
+Argument(StringRef Arg, StringRef Attr)
+: lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
+  isOpt(false), Fake(false) {
   if (!lowerName.empty()) {
 lowerName[0] = std::tolower(lowerName[0]);
 upperName[0] = std::toupper(upperName[0]);
@@ -215,6 +215,8 @@
   if (lowerName == "interface")
 lowerName = "interface_";
 }
+Argument(const Record &Arg, StringRef Attr)
+: Argument(Arg.getValueAsString("Name"), Attr) {}
 virtual ~Argument() = default;
 
 StringRef getLowerName() const { return lowerName; }
@@ -666,6 +668,11 @@
   ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
   RangeName(std::string(getLowerName())) {}
 
+VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
+: Argument(Arg, Attr), Type(std::move(T)),
+  ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
+  RangeName(std::string(getLowerName())) {}
+
 const std::string &getType() const { return Type; }
 const std::string &getArgName() const { return ArgName; }
 const std::string &getArgSizeName() const { return ArgSizeName; }
@@ -688,6 +695,18 @@
  << "); }\n";
 }
 
+void writeSetter(raw_ostream &OS) const {
+  OS << "  void set" << getUpperName() << "(ASTContext &Ctx, ";
+  writeCtorParameters(OS);
+  OS << ") {\n";
+  OS << "" << ArgSizeName << " = " << getUpperName() << "Size;\n";
+  OS << "" << ArgName << " = new (Ctx, 16) " << getType() << "["
+ << ArgSizeName << "];\n";
+  OS << "  ";
+  writeCtorBody(OS);
+  OS << "  }\n";
+}
+
 void writeCloneArgs(raw_ostream &OS) const override {
   OS << ArgName << ", " << ArgSizeName;
 }
@@ -1169,6 +1188,9 @@
   : VariadicArgument(Arg, Attr, "Expr *")
 {}
 
+VariadicExprArgument(StringRef ArgName, StringRef Attr)
+: VariadicArgument(ArgName, Attr, "Expr *") {}
+
 void writeASTVisitorTraversal(raw_ostream &OS) const override {
   OS << "  {\n";
   OS << "" << getType() << " *I = A->" << getLowerName()
@@ -2138,6 +2160,11 @@
   }
 }
 
+static bool isTypeArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ Arg->getSuperClasses().back().first->getName() == "TypeArgument";
+}
+
 /// Emits the first-argument-is-type property for attributes.
 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
@@ -2149,7 +2176,7 @@
 if (Args.empty())
   continue;
 
-if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
+if (!isTypeArgument(Args[0]))
   continue;
 
 // All these spellings take a single type argument.
@@ -2179,7 +2206,7 @@
   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
 }
 
-static bool isIdentifierArgument(Record *Arg) {
+static bool isIdentifierArgument(const Record *Arg) {
   return !Arg->getSuperClasses().empty() &&
 llvm::StringSwitch(Arg->getSuperClasses().back().first->getName())
 .Case("IdentifierArgument", true)
@@ -2188,7 +2215,7 @@
 .Default(false);
 }
 
-static bool isVariadicIdentifierArgument(Record *Arg) {
+static bool i

[PATCH] D117391: [AST] Ignore implicit nodes in CastExpr::getConversionFunction

2022-02-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D117391#3299483 , @kimgr wrote:

> I have now convinced myself that including `FullExpr` in 
> `skipImplicitTemporary` gives an improvement in `consteval` diagnostics. But 
> I'm still not sure why. Motivating example, derived from cxx2a-consteval.cpp:
>
>   struct A {
> int *p = new int(42);
> consteval A ret_a() const {
> return A{};
> }
>   };
>   
>   consteval const A &to_lvalue_ref(const A &&a) {
> return a;
>   }
>   
>   void test() {
> constexpr A a{nullptr};
>   
> // error: call to consteval function 'A::ret_a' is not a constant 
> expression
> // { (void)a.ret_a(); }
>   
> // error: call to consteval function 'to_lvalue_ref' is not a constant 
> expression
> // { (void)to_lvalue_ref(A{}); }
>   
> // error: call to consteval function 'to_lvalue_ref' is not a constant 
> expression
> // but should probably also raise
> // error: call to consteval function 'A::ret_a' is not a constant 
> expression
> { (void)to_lvalue_ref(a.ret_a()); }
>   }
>
> It's interesting to experiment with these one by one

Agreed. This stuff is about as clear as mud given that the rules change in 
every version of C++ and no two compilers implement the same constant 
expression evaluation rules at this point.

> - `A::ret_a` returns a new A, whose constructor does heap allocation; no 
> consteval possible

Agreed, though there are cases where it could be possible: 
http://eel.is/c++draft/expr.const#5.19.

> - `to_lvalue_ref` attempts to return a reference to a temporary; no consteval 
> possible

Hmm, is that still the case? http://eel.is/c++draft/expr.const#4.7

> Composing the two as in the last example, it seems to me, should print both 
> diagnostics. Mainline Clang doesn't, but changing `skipImplicitTemporary` to 
> also skip `FullExpr`s does (also allowing removal of all `IgnoreImplicit` 
> from `getSubExprAsWritten` and `getConversionFunction`).
>
> It seems intuitively right to me. I'm just a little peeved that I can't 
> figure out the connection between the diagnostic emission and 
> `skipImplicitTemporary`.

Assuming that the `to_lvalue_ref(A{})` case should diagnose, then yes, I agree, 
I think the `ret_a()` portion should as well.




Comment at: clang/lib/AST/Expr.cpp:1946-1947
   for (const CastExpr *E = this; E; E = dyn_cast(SubExpr)) {
 SubExpr = skipImplicitTemporary(E->getSubExpr());
+SubExpr = SubExpr->IgnoreImplicit();
 

kimgr wrote:
> davrec wrote:
> > aaron.ballman wrote:
> > > `IgnoreImplicit()` calls `IgnoreImplicitSingleStep()` eventually, and 
> > > that call does the same work as `skipImplicitTemporary()`, so I think the 
> > > end result here should be the same.
> > As I look at this a second time, I just realized...calling IgnoreImplicit 
> > here mean that the loop only ever runs one iteration, since IgnoreImplicit 
> > presumably skips over ImplicitCastExprs.  While I liked how Kim did 
> > revision initially because it seemed to handle the constructor conversions 
> > similarly to their handling of getSubExprAsWritten() above, now I think 
> > something different is needed here.
> > 
> > Proposed alternative:
> > Right now skipIimplicitTemporary does what IgnoreImplicit does *except* 
> > skip over a) ImplicitCastExprs and b) FullExprs (= ConstantExprs or 
> > ExprWithCleanups).
> > 
> > Kim has identified that we need to skip over at least ConstantExprs at 
> > least in this case (i.e. the most conservative possible fix would be to 
> > skip over ConstantExprs just before the cast in line 1950).
> > 
> > But perhaps the better solution, to forestall future bugs, is to skip over 
> > FullExprs in skipImplicitTemporary, so that it skips over everything 
> > IgnoreImplicit does except ImplicitCastExprs.  (And, some documentation 
> > should be added to `skipImplicitTemporary` to that effect, to aid future 
> > maintenance.)
> > 
> > I can't see offhand how the other uses of skipImplicitTemporary would be 
> > negatively affected by additionally skipping over FullExprs.
> > 
> > Aaron what do you think?  Kim can you verify this alternative would also 
> > solve the problem without breaking any tests?
> > 
> @aaron.ballman Just removing the `skipImplicitTemporary` line is probably not 
> going to work, since that's the first time `SubExpr` is assigned a 
> Aaron what do you think? Kim can you verify this alternative would also solve 
> the problem without breaking any tests?

I think that's a good idea to explore. I hadn't spotted the `FullExpr` 
difference when I was looking at it before.



Comment at: clang/lib/AST/Expr.cpp:1949-1950
 
 if (E->getCastKind() == CK_ConstructorConversion)
   return cast(SubExpr)->getConstructor();
 

kimgr wrote:
> kimgr wrote:
> > davrec wrote:
> > > I think the errors prove we should fall back to the most conservative 
> > > possible fix: rem

[clang] c45a99f - [MatrixBuilder] Require explicit element type in CreateColumnMajorLoad()

2022-02-07 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2022-02-07T16:57:33+01:00
New Revision: c45a99f36b6e87440765572bd38cbd515c60173a

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

LOG: [MatrixBuilder] Require explicit element type in CreateColumnMajorLoad()

This makes the method compatible with opaque pointers.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
llvm/include/llvm/IR/MatrixBuilder.h
mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 9ed19af901b0..7ec9994aea41 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3250,8 +3250,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
 E->getArg(0)->getExprLoc(), FD, 0);
 Value *Result = MB.CreateColumnMajorLoad(
-Src.getPointer(), Align(Src.getAlignment().getQuantity()), Stride,
-IsVolatile, ResultTy->getNumRows(), ResultTy->getNumColumns(),
+Src.getElementType(), Src.getPointer(),
+Align(Src.getAlignment().getQuantity()), Stride, IsVolatile,
+ResultTy->getNumRows(), ResultTy->getNumColumns(),
 "matrix");
 return RValue::get(Result);
   }

diff  --git a/llvm/include/llvm/IR/MatrixBuilder.h 
b/llvm/include/llvm/IR/MatrixBuilder.h
index cbecc6eab4f5..c2f5c4eab8fa 100644
--- a/llvm/include/llvm/IR/MatrixBuilder.h
+++ b/llvm/include/llvm/IR/MatrixBuilder.h
@@ -58,18 +58,14 @@ class MatrixBuilder {
   MatrixBuilder(IRBuilderBase &Builder) : B(Builder) {}
 
   /// Create a column major, strided matrix load.
+  /// \p EltTy   - Matrix element type
   /// \p DataPtr - Start address of the matrix read
   /// \p Rows- Number of rows in matrix (must be a constant)
   /// \p Columns - Number of columns in matrix (must be a constant)
   /// \p Stride  - Space between columns
-  CallInst *CreateColumnMajorLoad(Value *DataPtr, Align Alignment,
+  CallInst *CreateColumnMajorLoad(Type *EltTy, Value *DataPtr, Align Alignment,
   Value *Stride, bool IsVolatile, unsigned 
Rows,
   unsigned Columns, const Twine &Name = "") {
-
-// Deal with the pointer
-PointerType *PtrTy = cast(DataPtr->getType());
-Type *EltTy = PtrTy->getPointerElementType();
-
 auto *RetType = FixedVectorType::get(EltTy, Rows * Columns);
 
 Value *Ops[] = {DataPtr, Stride, B.getInt1(IsVolatile), B.getInt32(Rows),

diff  --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td 
b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index 164493720fe4..78b3af47ae19 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -1614,10 +1614,10 @@ def LLVM_MatrixColumnMajorLoadOp : 
LLVM_Op<"intr.matrix.column.major.load"> {
 llvm::MatrixBuilder mb(builder);
 const llvm::DataLayout &dl =
   builder.GetInsertBlock()->getModule()->getDataLayout();
-llvm::Align align = dl.getABITypeAlign(
-  $data->getType()->getPointerElementType());
+llvm::Type *ElemTy = $data->getType()->getPointerElementType();
+llvm::Align align = dl.getABITypeAlign(ElemTy);
 $res = mb.CreateColumnMajorLoad(
-  $data, align, $stride, $isVolatile, $rows,
+  ElemTy, $data, align, $stride, $isVolatile, $rows,
   $columns);
   }];
   let assemblyFormat = "$data `,` `<` `stride` `=` $stride `>` attr-dict"



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


[PATCH] D119094: [clang] Don't emit redundant warnings for 'return;'

2022-02-07 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone planned changes to this revision.
Quuxplusone added a comment.

Unfortunately some existing tests fail: 
https://reviews.llvm.org/harbormaster/unit/view/2282838/
I haven't yet figured out why consteval functions are considered to have 
`FD->isInvalidDecl()`. There's also an Objective-C failure that I assume 
indicates sometimes (when this is a //method// not a //function//) we have no 
`FD` at all. I'd need to solve both of these problems (the former being the 
difficult one) before I can make progress here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119094

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


[PATCH] D119138: [clang-format] Further improve support for requires expressions

2022-02-07 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Some nits.




Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1541-1542
+case tok::kw_requires: {
+  bool Return = parseRequires();
+  if (Return)
+return;





Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2791
+/// \pre The current token has to be the requires keyword.
+/// \returns If it parsed a clause.
+bool clang::format::UnwrappedLineParser::parseRequires() {





Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2818
+default:
+  // Is most definitly an expression.
+  return true;





Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2826
+if (!LastParenContent) {
+  // No Token is invalid code, just do whatever you want.
+  return true;





Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2854
+  if (LastParenContent->isSimpleTypeSpecifier()) {
+// Definetly function delcaration.
+return false;





Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2862
+if (!BeforeLastParenContent) {
+  // No Token is invalid code, just do whatever you want.
+  return true;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119138

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


[PATCH] D114439: [Annotation] Allow parameter pack expansions and initializer lists in annotate attribute

2022-02-07 Thread Steffen Larsen via Phabricator via cfe-commits
steffenlarsen added inline comments.



Comment at: clang/include/clang/Sema/ParsedAttr.h:113
   }
+  // Check if argument at index I is an expression argument
+  virtual bool isExprArg(size_t N) const { return false; }

aaron.ballman wrote:
> I don't think this API is needed. `isArgExpr()` already exists on the 
> interface and I'm not certain how this differs. (If this API is needed, we 
> need a far better name for it because I'd have no idea how to distinguish 
> `isExprArg()` and `isArgExpr()`.)
There is an important distinction between the two, specifically that 
`isArgExpr` checks if the parsed argument at the index is an expression, while 
`isExprArg` checks if the specified argument in the attribute is an 
"ExprArgument", i.e. one checks post-parsing the other reflects on the 
attribute's definition.

That said, I agree that with that naming there's little distinction between the 
two. I have therefore removed `isExprArg` and replaced it with 
`isArgMemberExprHolder` which is true if the "argument member" (referring to 
the argument defined in Attr.td) is able to hold an expression (i.e. it is 
either a `ExprArgument` or a `VaridicExprArgument`.) Functionally there is 
little change to it, as the only place we use the check is after checking if 
the expression is variadic, but it fit better with the actual intent of the 
check.



Comment at: clang/include/clang/Sema/Sema.h:4383-4385
+  bool checkStringLiteralExpr(const AttributeCommonInfo &CI, const Expr *E,
+  StringRef &Str,
+  SourceLocation *ArgLocation = nullptr);

aaron.ballman wrote:
> This name makes it sound like far more general of an API than it is. This 
> function is specific to checking string literal arguments for an attribute. 
> But then why does `checkStringLiteralArgumentAttr()` not suffice? It does the 
> same thing, but with more bells and whistles.
The problem is that `checkStringLiteralArgumentAttr()` requires the arguments 
to be extracted from the parsed attribute, which we do not have after template 
instantiation, so the split was for generality. However, as you mentioned in 
another comment, the generality is not that needed anymore so 
`handleAnnotateAttr` has been reverted to the old version.

That said, this is still needed for doing post-initalization check if arguments 
have been delayed, so I have renamed it to `checkASCIIStringLiteralExpr` which 
hopefully conveys the intent a little better?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:4185
   StringRef Str;
-  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
+  if (!checkStringLiteralExpr(CI, AllArgs[0], Str))
 return;

aaron.ballman wrote:
> This is a slight loss of functionality. We used to recommend identifiers be 
> converted to string literals under the old interface. I don't think this 
> refactoring is necessary any longer, right?
You're absolutely right. There is actually no reason for this refactoring 
anymore, except for maybe some minor common code between this and delayed 
argument instantiation, but it is so little now that if we want to keep the 
hint (which I agree we should) then there's little reason not to revert the 
changes to `handleAnnotateAttr`. So that's what I've done! Similarly, 
`handleAnnotateAttr` is no longer needed so it has been removed and the excess 
logic has been moved to `instantiateDependentAnnotationAttr`. Thanks for 
pointing this out!



Comment at: clang/utils/TableGen/ClangAttrEmitter.cpp:2312
+
+// All these spellings take are parsed unevaluated.
+forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {

aaron.ballman wrote:
> The comment doesn't seem grammatical and may need some expounding.
I don't think a comment makes much sense here anyway, so I've removed it. This 
seems like fairly common practice for these kind of functions. If you disagree 
I can reintroduce it and expand on it.


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

https://reviews.llvm.org/D114439

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


  1   2   3   >