[clang] a29f8db - [C++20][Modules][8/8] Amend module visibility rules for partitions.

2022-03-01 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-03-01T08:29:05Z
New Revision: a29f8dbb7f3e816344a7be75996eea3ab5a0b5a3

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

LOG: [C++20][Modules][8/8] Amend module visibility rules for partitions.

Implementation partitions bring two extra cases where we have
visibility of module-private data.

1) When we import a module implementation partition.
2) When a partition implementation imports the primary module intertace.

We maintain a record of direct imports into the current module since
partition decls from direct imports (but not trasitive ones) are visible.

The rules on decl-reachability are much more relaxed (with the standard
giving permission for an implementation to load dependent modules and for
the decls there to be reachable, but not visible).

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

Added: 


Modified: 
clang/lib/Sema/SemaLookup.cpp
clang/test/Modules/cxx20-10-1-ex2.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 13320497c4b4b..65f5112afee3e 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -1687,8 +1687,8 @@ bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl 
*D) {
   Module *DeclModule = SemaRef.getOwningModule(D);
   assert(DeclModule && "hidden decl has no owning module");
 
-  // If the owning module is visible, the decl is visible.
   if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
+// If the owning module is visible, the decl is visible.
 return true;
 
   // Determine whether a decl context is a file context for the purpose of
@@ -1762,6 +1762,22 @@ bool Sema::isModuleVisible(const Module *M, bool 
ModulePrivate) {
   if (ModulePrivate) {
 if (isInCurrentModule(M, getLangOpts()))
   return true;
+else if (M->Kind == Module::ModuleKind::ModulePartitionImplementation &&
+ isModuleDirectlyImported(M))
+  // Unless a partition implementation is directly imported it is not
+  // counted as visible for lookup, although the contained decls might
+  // still be reachable.  It's a partition, so it must be part of the
+  // current module to be a valid import.
+  return true;
+else if (getLangOpts().CPlusPlusModules && !ModuleScopes.empty() &&
+ ModuleScopes[0].Module->Kind ==
+ Module::ModuleKind::ModulePartitionImplementation &&
+ ModuleScopes[0].Module->getPrimaryModuleInterfaceName() ==
+ M->Name &&
+ isModuleDirectlyImported(M))
+  // We are building a module implementation partition and the TU imports
+  // the primary module interface unit.
+  return true;
   } else {
 if (VisibleModules.isVisible(M))
   return true;

diff  --git a/clang/test/Modules/cxx20-10-1-ex2.cpp 
b/clang/test/Modules/cxx20-10-1-ex2.cpp
index 66323fc9d6460..6b47fb0f41eec 100644
--- a/clang/test/Modules/cxx20-10-1-ex2.cpp
+++ b/clang/test/Modules/cxx20-10-1-ex2.cpp
@@ -12,9 +12,8 @@
 // RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu3.cpp \
 // RUN:   -o %t/B_X1.pcm -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
-//   -fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
+// RUN:-fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
 
 // RUN: %clang_cc1 -std=c++20 -emit-obj %t/std10-1-ex2-tu5.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu5.o
@@ -22,9 +21,8 @@
 // RUN: %clang_cc1 -std=c++20 -S %t/std10-1-ex2-tu6.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu6.s -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
-//   -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
+// RUN: -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
 
 //--- std10-1-ex2-tu1.cpp
 module B:Y;



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


[PATCH] D118599: [C++20][Modules][8/8] Amend module visibility rules for partitions.

2022-03-01 Thread Iain Sandoe via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
iains marked an inline comment as done.
Closed by commit rGa29f8dbb7f3e: [C++20][Modules][8/8] Amend module visibility 
rules for partitions. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118599

Files:
  clang/lib/Sema/SemaLookup.cpp
  clang/test/Modules/cxx20-10-1-ex2.cpp


Index: clang/test/Modules/cxx20-10-1-ex2.cpp
===
--- clang/test/Modules/cxx20-10-1-ex2.cpp
+++ clang/test/Modules/cxx20-10-1-ex2.cpp
@@ -12,9 +12,8 @@
 // RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu3.cpp \
 // RUN:   -o %t/B_X1.pcm -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
-//   -fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
+// RUN:-fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
 
 // RUN: %clang_cc1 -std=c++20 -emit-obj %t/std10-1-ex2-tu5.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu5.o
@@ -22,9 +21,8 @@
 // RUN: %clang_cc1 -std=c++20 -S %t/std10-1-ex2-tu6.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu6.s -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
-//   -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
+// RUN: -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
 
 //--- std10-1-ex2-tu1.cpp
 module B:Y;
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -1687,8 +1687,8 @@
   Module *DeclModule = SemaRef.getOwningModule(D);
   assert(DeclModule && "hidden decl has no owning module");
 
-  // If the owning module is visible, the decl is visible.
   if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
+// If the owning module is visible, the decl is visible.
 return true;
 
   // Determine whether a decl context is a file context for the purpose of
@@ -1762,6 +1762,22 @@
   if (ModulePrivate) {
 if (isInCurrentModule(M, getLangOpts()))
   return true;
+else if (M->Kind == Module::ModuleKind::ModulePartitionImplementation &&
+ isModuleDirectlyImported(M))
+  // Unless a partition implementation is directly imported it is not
+  // counted as visible for lookup, although the contained decls might
+  // still be reachable.  It's a partition, so it must be part of the
+  // current module to be a valid import.
+  return true;
+else if (getLangOpts().CPlusPlusModules && !ModuleScopes.empty() &&
+ ModuleScopes[0].Module->Kind ==
+ Module::ModuleKind::ModulePartitionImplementation &&
+ ModuleScopes[0].Module->getPrimaryModuleInterfaceName() ==
+ M->Name &&
+ isModuleDirectlyImported(M))
+  // We are building a module implementation partition and the TU imports
+  // the primary module interface unit.
+  return true;
   } else {
 if (VisibleModules.isVisible(M))
   return true;


Index: clang/test/Modules/cxx20-10-1-ex2.cpp
===
--- clang/test/Modules/cxx20-10-1-ex2.cpp
+++ clang/test/Modules/cxx20-10-1-ex2.cpp
@@ -12,9 +12,8 @@
 // RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu3.cpp \
 // RUN:   -o %t/B_X1.pcm -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
-//   -fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu4.cpp \
+// RUN:-fmodule-file=%t/B.pcm  -o %t/B_X2.pcm
 
 // RUN: %clang_cc1 -std=c++20 -emit-obj %t/std10-1-ex2-tu5.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu5.o
@@ -22,9 +21,8 @@
 // RUN: %clang_cc1 -std=c++20 -S %t/std10-1-ex2-tu6.cpp \
 // RUN:  -fmodule-file=%t/B.pcm  -o %t/b_tu6.s -verify
 
-// Not expected to work yet.
-//  %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
-//   -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/std10-1-ex2-tu7.cpp \
+// RUN: -fmodule-file=%t/B_X2.pcm  -o %t/B_X3.pcm -verify
 
 //--- std10-1-ex2-tu1.cpp
 module B:Y;
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -1687,8 +1687,8 @@
   Module *DeclModule = SemaRef.getOwningModule(D);
   assert(DeclModule && "hidden decl has no owning module");
 
-  // If the owning module is visible, the decl is visible.
   if (SemaRef.isModuleVisible(DeclModule, D->

[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-03-01 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 411996.
ChuanqiXu added a comment.

Add test in CodeGen.


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

https://reviews.llvm.org/D120397

Files:
  clang/lib/AST/Decl.cpp
  clang/test/CodeGenCXX/inconsistent-export-template.cpp
  clang/test/Modules/inconsist-export-template.cpp


Index: clang/test/Modules/inconsist-export-template.cpp
===
--- /dev/null
+++ clang/test/Modules/inconsist-export-template.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+// expected-no-diagnostics
+export module m;
+export template 
+void f() {
+}
+
+template <>
+void f() {
+}
+
+template 
+void f1() {
+}
+
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+}
+
+export template 
+class C {
+};
+
+template <>
+class C {
+public:
+  void M(){};
+};
+
+void Use(C &p) { p.M(); }
Index: clang/test/CodeGenCXX/inconsistent-export-template.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/inconsistent-export-template.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -std=c++20 %s -S -emit-llvm -triple %itanium_abi_triple 
-disable-llvm-passes -o - | FileCheck %s
+
+export module m;
+export template 
+void f() {
+}
+
+// CHECK: void @_Z1fIiEvv
+template <>
+void f() {
+}
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -391,11 +391,18 @@
   bool considerVisibility =
 shouldConsiderTemplateVisibility(fn, specInfo);
 
-  // Merge information from the template parameters.
   FunctionTemplateDecl *temp = specInfo->getTemplate();
-  LinkageInfo tempLV =
-getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
-  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
+
+  // Merge information from the template declaration.
+  LinkageInfo tempLV = getLVForDecl(temp, computation);
+  // The linkage of the specialization should be consistent with the
+  // template declaration.
+  LV.setLinkage(tempLV.getLinkage());
+
+  // Merge information from the template parameters.
+  LinkageInfo paramsLV =
+  getLVForTemplateParameterList(temp->getTemplateParameters(), 
computation);
+  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
 
   // Merge information from the template arguments.
   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;


Index: clang/test/Modules/inconsist-export-template.cpp
===
--- /dev/null
+++ clang/test/Modules/inconsist-export-template.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+// expected-no-diagnostics
+export module m;
+export template 
+void f() {
+}
+
+template <>
+void f() {
+}
+
+template 
+void f1() {
+}
+
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+}
+
+export template 
+class C {
+};
+
+template <>
+class C {
+public:
+  void M(){};
+};
+
+void Use(C &p) { p.M(); }
Index: clang/test/CodeGenCXX/inconsistent-export-template.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/inconsistent-export-template.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -std=c++20 %s -S -emit-llvm -triple %itanium_abi_triple -disable-llvm-passes -o - | FileCheck %s
+
+export module m;
+export template 
+void f() {
+}
+
+// CHECK: void @_Z1fIiEvv
+template <>
+void f() {
+}
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -391,11 +391,18 @@
   bool considerVisibility =
 shouldConsiderTemplateVisibility(fn, specInfo);
 
-  // Merge information from the template parameters.
   FunctionTemplateDecl *temp = specInfo->getTemplate();
-  LinkageInfo tempLV =
-getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
-  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
+
+  // Merge information from the template declaration.
+  LinkageInfo tempLV = getLVForDecl(temp, computation);
+  // The linkage of the specialization should be consistent with the
+  // template declaration.
+  LV.setLinkage(tempLV.getLinkage());
+
+  // Merge information from the template parameters.
+  LinkageInfo paramsLV =
+  getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
+  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
 
   // Merge information from the template arguments.
   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/

[PATCH] D120331: [clang-tidy][run-clang-tidy.py] Add --config-file= option

2022-03-01 Thread Shreyas via Phabricator via cfe-commits
SAtacker added a comment.

@JonasToth Could you please review it?




Comment at: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py:236
   'each source file in its parent directories.')
+  parser.add_argument('-config-file', default=None,
+  help='Specify the path of .clang-tidy or custom config'

JonasToth wrote:
> please ensure that those option exclude each other. right now it could be 
> used with both options which is a contradiction for `clang-tidy`
Do you mean mutual exclusion? From the docs: 
https://docs.python.org/3/library/argparse.html#mutual-exclusion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120331

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


[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-03-01 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/CodeGenCXX/inconsistent-export-template.cpp:8
+
+// CHECK: void @_Z1fIiEvv
+template <>

The mangled name should contain module name if D118352 is ready.



Comment at: clang/test/Modules/inconsist-export-template.cpp:1-2
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+// expected-no-diagnostics
+export module m;

urnathan wrote:
> dblaikie wrote:
> > This test doesn't appear to test anything - it verifies that this file 
> > produces no diagnostics, but not that it has any other/particular behavior.
> > 
> > Should this be testing codegen to verify that the correct linkage was used 
> > on the resulting IR functions?
> > 
> > Are there other ways of observing the particular language-level linkage of 
> > the entities to confirm it's as expected?
> yes, this should be a codegen test 
> (clang/test/CodeGenCXX/Modules/cxx20-$something.cpp?
The compiler would crash at the test before the patch landed. So I send the 
patch here to show that the test wouldn't cause the compiler crash.



Comment at: clang/test/Modules/inconsist-export-template.cpp:19-23
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+

urnathan wrote:
> I don't think we should be testing for ill-formed code here.  We want to 
> verify that explicit instantiations, explicit specializations and implicit 
> instantiations all get the expected linkage -- both external linkage on 
> exported entities, module linkage on non-exported module-purview entities.
I think it could add an `expected-error` once we complete the check in compiler 
so I added the FIXME here.


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

https://reviews.llvm.org/D120397

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


[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-03-01 Thread Iain Sandoe via Phabricator via cfe-commits
iains added inline comments.



Comment at: clang/test/Modules/inconsist-export-template.cpp:19-23
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+

ChuanqiXu wrote:
> urnathan wrote:
> > I don't think we should be testing for ill-formed code here.  We want to 
> > verify that explicit instantiations, explicit specializations and implicit 
> > instantiations all get the expected linkage -- both external linkage on 
> > exported entities, module linkage on non-exported module-purview entities.
> I think it could add an `expected-error` once we complete the check in 
> compiler so I added the FIXME here.
would it be possible to find a suitable place in the source for the FIXME?
I would be concerned that it could get forgotten in the test-case.


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

https://reviews.llvm.org/D120397

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


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-01 Thread Diana Picus via Phabricator via cfe-commits
rovka added a comment.

This passes on Windows on Arm if you add a forward declaration for  `class 
PassInstrumentation` here 
.
 This is necessary because otherwise clang picks up the PassInstrumentation 
from MLIR instead of the PassInstrumentation defined lower in the file.

For reference, this is the error I was seeing before:

  
C:\Work\diana.picus\llvm-project\llvm\include\llvm/IR/PassInstrumentation.h(145,16):
 warning: unqualified friend declaration referring to type outside of the 
nearest enclosing namespace is a Microsoft extension; add a nested name 
specifier [-Wmicrosoft-unqualified-friend]
friend class PassInstrumentation;
 ^
 ::mlir::
  
C:\Work\diana.picus\llvm-project\llvm\include\llvm/IR/PassInstrumentation.h(292,33):
 error: 'AnalysesClearedCallbacks' is a private member of 
'llvm::PassInstrumentationCallbacks'
for (auto &C : Callbacks->AnalysesClearedCallbacks)
  ^
  
C:\Work\diana.picus\llvm-project\llvm\include\llvm/IR/PassInstrumentation.h(173,7):
 note: declared private here
AnalysesClearedCallbacks;


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

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


[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-03-01 Thread Iain Sandoe via Phabricator via cfe-commits
iains added inline comments.



Comment at: clang/test/Modules/inconsist-export-template.cpp:19-23
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+

iains wrote:
> ChuanqiXu wrote:
> > urnathan wrote:
> > > I don't think we should be testing for ill-formed code here.  We want to 
> > > verify that explicit instantiations, explicit specializations and 
> > > implicit instantiations all get the expected linkage -- both external 
> > > linkage on exported entities, module linkage on non-exported 
> > > module-purview entities.
> > I think it could add an `expected-error` once we complete the check in 
> > compiler so I added the FIXME here.
> would it be possible to find a suitable place in the source for the FIXME?
> I would be concerned that it could get forgotten in the test-case.
or maybe just file a PR for accepts invalid code?


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

https://reviews.llvm.org/D120397

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


[PATCH] D105408: [clang-format] Pass a TextDiagnosticPrinter when we can not create tempory file.

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

This is no longer needed, please abanson


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105408

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


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-01 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 412008.
awarzynski added a comment.
Herald added subscribers: llvm-commits, dexonsmith.
Herald added a project: LLVM.

Add a forward declaration for `class PassInstrumentation` (thank you @rovka!)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

Files:
  clang/include/clang/Driver/Options.td
  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/ExecuteCompilerInvocation.cpp
  flang/lib/Optimizer/Support/FIRContext.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/code-gen-aarch64.f90
  flang/test/Driver/code-gen-x86.f90
  flang/test/Driver/code-gen.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-asm-aarch64.f90
  flang/test/Driver/emit-asm-x86.f90
  flang/test/Driver/syntax-only.f90
  flang/test/Fir/target-rewrite-triple.fir
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/FrontendActionTest.cpp
  llvm/include/llvm/IR/PassInstrumentation.h

Index: llvm/include/llvm/IR/PassInstrumentation.h
===
--- llvm/include/llvm/IR/PassInstrumentation.h
+++ llvm/include/llvm/IR/PassInstrumentation.h
@@ -60,6 +60,9 @@
 
 class PreservedAnalyses;
 class StringRef;
+// This forward declaration is required to avoid clashes with a similarly named
+// class in other sub-projects (e.g. MLIR).
+class PassInstrumentation;
 
 /// This class manages callbacks registration, as well as provides a way for
 /// PassInstrumentation to pass control to the registered callbacks.
Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -11,6 +11,7 @@
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/FrontendTool/Utils.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/raw_ostream.h"
 
 #include "gtest/gtest.h"
@@ -188,4 +189,35 @@
   EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
   .contains("define void @_QQmain()"));
 }
+
+TEST_F(FrontendActionTest, EmitAsm) {
+  // 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 = EmitAssembly;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Initialise LLVM backend
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
+  // 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("_QQmain"));
+}
 } // namespace
Index: flang/unittests/Frontend/CMakeLists.txt
===
--- flang/unittests/Frontend/CMakeLists.txt
+++ flang/unittests/Frontend/CMakeLists.txt
@@ -1,3 +1,7 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+)
+
 add_flang_unittest(FlangFrontendTests
   CompilerInstanceTest.cpp
   FrontendActionTest.cpp
Index: flang/tools/flang-driver/fc1_main.cpp
===
--- flang/tools/flang-driver/fc1_main.cpp
+++ flang/tools/flang-driver/fc1_main.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
+#include "llvm/Support/TargetSelect.h"
 
 #include 
 
@@ -48,6 +49,11 @@
   bool success =
   CompilerInvocation::CreateFromArgs(flang->invocation(), argv, diags);
 
+  // Initialize targets first, so that --version shows registered targets.
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
   diagsBuffer->FlushDiagnostics(flang->diagnostics());
 
   if (!success)
Index: flang/test/lit.site.cfg.py.in
===
--- flang/test/lit.site.cfg.py.in
+++ flang/test/lit.site.cfg.py.in
@@ -18,6 +18,7 @@
 config.flang_standalone_build = @FLAN

[PATCH] D120111: [AArch64] Default HBC/MOPS features in clang

2022-03-01 Thread Son Tuan Vu via Phabricator via cfe-commits
tyb0807 updated this revision to Diff 412010.
tyb0807 added a comment.

Taking into account remarks from @tmatheson, I'm reverting my latest changes
consisting in caching architecture feature into a variable, which makes the
`getAArch64ArchFeaturesFrom*` interfaces more complicated.

I'd propose we move forward with this patch, and the performance issue raised by
@nickdesaulniers will be addressed properly in a separate one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120111

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/test/Driver/aarch64-hbc.c
  clang/test/Driver/aarch64-mops.c
  clang/test/Preprocessor/aarch64-target-features.c

Index: clang/test/Preprocessor/aarch64-target-features.c
===
--- clang/test/Preprocessor/aarch64-target-features.c
+++ clang/test/Preprocessor/aarch64-target-features.c
@@ -524,14 +524,18 @@
 // CHECK-LSE: __ARM_FEATURE_ATOMICS 1
 
 // == Check Armv8.8-A/Armv9.3-A memcpy and memset acceleration instructions (MOPS)
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.7-a  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.7-a+mops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a+mops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.2-a  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.2-a+mops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.3-a  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
-// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.3-a+mops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.7-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.7-a+mops-x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a+nomops  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a+nomops+mops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a+mops-x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv8.8-a+mops+nomops -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.2-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.2-a+mops-x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.3-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.3-a+nomops  -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NOMOPS %s
+// RUN: %clang -target aarch64-arm-none-eabi -march=armv9.3-a+mops-x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-MOPS   %s
 // CHECK-MOPS: __ARM_FEATURE_MOPS 1
 // CHECK-NOMOPS-NOT: __ARM_FEATURE_MOPS 1
 
Index: clang/test/Driver/aarch64-mops.c
===
--- clang/test/Driver/aarch64-mops.c
+++ clang/test/Driver/aarch64-mops.c
@@ -1,6 +1,12 @@
 // Test that target feature mops is implemented and available correctly
-// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+mops %s 2>&1 | FileCheck %s
-// CHECK: "-target-feature" "+mops"
-
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.7-a+mops   %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a%s 2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+mops   %s 2>&1 | FileCheck %s
 // RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+nomops %s 2>&1 | FileCheck %s --check-prefix=NO_MOPS
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.2-a+mops   %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.3-a%s 2>&1 | FileCheck %s
+// RUN

[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-03-01 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/Modules/inconsist-export-template.cpp:19-23
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+

iains wrote:
> iains wrote:
> > ChuanqiXu wrote:
> > > urnathan wrote:
> > > > I don't think we should be testing for ill-formed code here.  We want 
> > > > to verify that explicit instantiations, explicit specializations and 
> > > > implicit instantiations all get the expected linkage -- both external 
> > > > linkage on exported entities, module linkage on non-exported 
> > > > module-purview entities.
> > > I think it could add an `expected-error` once we complete the check in 
> > > compiler so I added the FIXME here.
> > would it be possible to find a suitable place in the source for the FIXME?
> > I would be concerned that it could get forgotten in the test-case.
> or maybe just file a PR for accepts invalid code?
I would like to send an issue after the patch to remind me not forgetting it. 
The issue is needed after the patch since it would crash too. I prefer to 
remain the FIXME here so that it would look like a pre-commit test case, which 
should be good.


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

https://reviews.llvm.org/D120397

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


[PATCH] D120305: [Driver] Default CLANG_DEFAULT_PIE_ON_LINUX to ON

2022-03-01 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

I've been looking into the compile-time regressions.

The large regression on sqlite3 is due to differences in inlining behavior. The 
inlining cost model is slightly different for PIC builds, because GEPs that are 
based on a global and have a variable offset are no longer considered free. In 
the sqlite3 case this leads to different inlining decisions, which ultimately 
lead to the large compile-time regression. I don't think there is anything 
immediately actionable here, it's just bad luck that the different cost 
modeling happens to push us across an arbitrary threshold.

I've also looked at many smaller regressions (around ~5% on individual files), 
where the common factor is that we spend a lot more time in RAGreedy (e.g. from 
2% of total compile-time up to 6%). Most of the additional cost is in the 
calculation of region splitting costs. Something is clearly very wrong here, 
because a single RAGreedy::trySplit() call shouldn't take 3M instructions to 
execute.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120305

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

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

You should copy the `mempcpy14`, `mempcpy15` test cases into a separate file, 
and cut the `top`; while disabling this `alpha.unix.cstring.UninitializedRead` 
checker in the existing test file(s) and explicitly enable in the new separated 
file.
This way it wouldn't interfere with the existing test cases, since it would 
halt the analyzer (emits a sink node).
After that, you could land it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120499: [NVPTX] Fix nvvm.match.sync*.i64 intrinsics return type (i64 -> i32)

2022-03-01 Thread Kristina Bessonova 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 rG57aaab3b17f0: [NVPTX] Fix nvvm.match.sync*.i64 intrinsics 
return type (i64 -> i32) (authored by krisb).

Changed prior to commit:
  https://reviews.llvm.org/D120499?vs=411416&id=412018#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120499

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/test/CodeGen/builtins-nvptx-ptx60.cu
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/test/CodeGen/NVPTX/match.ll

Index: llvm/test/CodeGen/NVPTX/match.ll
===
--- llvm/test/CodeGen/NVPTX/match.ll
+++ llvm/test/CodeGen/NVPTX/match.ll
@@ -1,7 +1,7 @@
 ; RUN: llc < %s -march=nvptx64 -mcpu=sm_70 -mattr=+ptx60 | FileCheck %s
 
 declare i32 @llvm.nvvm.match.any.sync.i32(i32, i32)
-declare i64 @llvm.nvvm.match.any.sync.i64(i32, i64)
+declare i32 @llvm.nvvm.match.any.sync.i64(i32, i64)
 
 ; CHECK-LABEL: .func{{.*}}match.any.sync.i32
 define i32 @match.any.sync.i32(i32 %mask, i32 %value) {
@@ -23,26 +23,26 @@
 }
 
 ; CHECK-LABEL: .func{{.*}}match.any.sync.i64
-define i64 @match.any.sync.i64(i32 %mask, i64 %value) {
+define i32 @match.any.sync.i64(i32 %mask, i64 %value) {
   ; CHECK: ld.param.u32 	[[MASK:%r[0-9]+]], [match.any.sync.i64_param_0];
   ; CHECK: ld.param.u64 	[[VALUE:%rd[0-9]+]], [match.any.sync.i64_param_1];
 
-  ; CHECK:  match.any.sync.b64  [[V0:%rd[0-9]+]], [[VALUE]], [[MASK]];
-  %v0 = call i64 @llvm.nvvm.match.any.sync.i64(i32 %mask, i64 %value)
-  ; CHECK:  match.any.sync.b64  [[V1:%rd[0-9]+]], [[VALUE]], 1;
-  %v1 = call i64 @llvm.nvvm.match.any.sync.i64(i32 1, i64 %value)
-  ; CHECK:  match.any.sync.b64  [[V2:%rd[0-9]+]], 2, [[MASK]];
-  %v2 = call i64 @llvm.nvvm.match.any.sync.i64(i32 %mask, i64 2)
-  ; CHECK:  match.any.sync.b64  [[V3:%rd[0-9]+]], 4, 3;
-  %v3 = call i64 @llvm.nvvm.match.any.sync.i64(i32 3, i64 4)
-  %sum1 = add i64 %v0, %v1
-  %sum2 = add i64 %v2, %v3
-  %sum3 = add i64 %sum1, %sum2
-  ret i64 %sum3;
+  ; CHECK:  match.any.sync.b64  [[V0:%r[0-9]+]], [[VALUE]], [[MASK]];
+  %v0 = call i32 @llvm.nvvm.match.any.sync.i64(i32 %mask, i64 %value)
+  ; CHECK:  match.any.sync.b64  [[V1:%r[0-9]+]], [[VALUE]], 1;
+  %v1 = call i32 @llvm.nvvm.match.any.sync.i64(i32 1, i64 %value)
+  ; CHECK:  match.any.sync.b64  [[V2:%r[0-9]+]], 2, [[MASK]];
+  %v2 = call i32 @llvm.nvvm.match.any.sync.i64(i32 %mask, i64 2)
+  ; CHECK:  match.any.sync.b64  [[V3:%r[0-9]+]], 4, 3;
+  %v3 = call i32 @llvm.nvvm.match.any.sync.i64(i32 3, i64 4)
+  %sum1 = add i32 %v0, %v1
+  %sum2 = add i32 %v2, %v3
+  %sum3 = add i32 %sum1, %sum2
+  ret i32 %sum3;
 }
 
 declare {i32, i1} @llvm.nvvm.match.all.sync.i32p(i32, i32)
-declare {i64, i1} @llvm.nvvm.match.all.sync.i64p(i32, i64)
+declare {i32, i1} @llvm.nvvm.match.all.sync.i64p(i32, i64)
 
 ; CHECK-LABEL: .func{{.*}}match.all.sync.i32p(
 define {i32,i1} @match.all.sync.i32p(i32 %mask, i32 %value) {
@@ -81,37 +81,37 @@
 }
 
 ; CHECK-LABEL: .func{{.*}}match.all.sync.i64p(
-define {i64,i1} @match.all.sync.i64p(i32 %mask, i64 %value) {
+define {i32,i1} @match.all.sync.i64p(i32 %mask, i64 %value) {
   ; CHECK: ld.param.u32 	[[MASK:%r[0-9]+]], [match.all.sync.i64p_param_0];
   ; CHECK: ld.param.u64 	[[VALUE:%rd[0-9]+]], [match.all.sync.i64p_param_1];
 
-  ; CHECK:  match.all.sync.b64 {{%rd[0-9]+\|%p[0-9]+}}, [[VALUE]], [[MASK]];
-  %r1 = call {i64, i1} @llvm.nvvm.match.all.sync.i64p(i32 %mask, i64 %value)
-  %v1 = extractvalue {i64, i1} %r1, 0
-  %p1 = extractvalue {i64, i1} %r1, 1
-
-  ; CHECK:  match.all.sync.b64 {{%rd[0-9]+\|%p[0-9]+}}, 1, [[MASK]];
-  %r2 = call {i64, i1} @llvm.nvvm.match.all.sync.i64p(i32 %mask, i64 1)
-  %v2 = extractvalue {i64, i1} %r2, 0
-  %p2 = extractvalue {i64, i1} %r2, 1
-
-  ; CHECK:  match.all.sync.b64 {{%rd[0-9]+\|%p[0-9]+}}, [[VALUE]], 2;
-  %r3 = call {i64, i1} @llvm.nvvm.match.all.sync.i64p(i32 2, i64 %value)
-  %v3 = extractvalue {i64, i1} %r3, 0
-  %p3 = extractvalue {i64, i1} %r3, 1
-
-  ; CHECK:  match.all.sync.b64 {{%rd[0-9]+\|%p[0-9]+}}, 4, 3;
-  %r4 = call {i64, i1} @llvm.nvvm.match.all.sync.i64p(i32 3, i64 4)
-  %v4 = extractvalue {i64, i1} %r4, 0
-  %p4 = extractvalue {i64, i1} %r4, 1
-
-  %vsum1 = add i64 %v1, %v2
-  %vsum2 = add i64 %v3, %v4
-  %vsum3 = add i64 %vsum1, %vsum2
+  ; CHECK:  match.all.sync.b64 {{%r[0-9]+\|%p[0-9]+}}, [[VALUE]], [[MASK]];
+  %r1 = call {i32, i1} @llvm.nvvm.match.all.sync.i64p(i32 %mask, i64 %value)
+  %v1 = extractvalue {i32, i1} %r1, 0
+  %p1 = extractvalue {i32, i1} %r1, 1
+
+  ; CHECK:  match.all.sync.b64 {{%r[0-9]+\|%p[0-9]+}}, 1, [[MASK]];
+  %r2 = call {i32, i1} @llvm.nvvm.match.all.sync.i64p(i32 %mask, i64 1)
+  %v2 = extractvalue {i32, i1} %r2, 0
+  %p2 = extractvalue {i32, i1} %r2, 1
+
+  ; CHECK:  match.all.s

[clang] 57aaab3 - [NVPTX] Fix nvvm.match.sync*.i64 intrinsics return type (i64 -> i32)

2022-03-01 Thread Kristina Bessonova via cfe-commits

Author: Kristina Bessonova
Date: 2022-03-01T12:26:16+02:00
New Revision: 57aaab3b17f02a0904b823278035afe555f6f99a

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

LOG: [NVPTX] Fix nvvm.match.sync*.i64 intrinsics return type (i64 -> i32)

NVVM IR specification defines them with i32 return type:

  declare i32 @llvm.nvvm.match.any.sync.i64(i32 %membermask, i64 %value)
  declare {i32, i1} @llvm.nvvm.match.all.sync.i64(i32 %membermask, i64 %value)
  ...
  The i32 return value is a 32-bit mask where bit position in mask corresponds
  to thread’s laneid.

as well as PTX ISA:

  9.7.12.8. Parallel Synchronization and Communication Instructions: match.sync

  match.any.sync.type  d, a, membermask;
  match.all.sync.type  d[|p], a, membermask;
  ...
  Destination d is a 32-bit mask where bit position in mask corresponds
  to thread’s laneid.

Additionally, ptxas doesn't accept intructions, produced by NVPTX backend.
After this patch, it compiles with no issues.

Reviewed By: tra

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsNVPTX.def
clang/lib/Headers/__clang_cuda_intrinsics.h
clang/test/CodeGen/builtins-nvptx-ptx60.cu
llvm/include/llvm/IR/IntrinsicsNVVM.td
llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
llvm/test/CodeGen/NVPTX/match.ll

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index 6b94dd8573008..1279d83f1f61f 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -473,11 +473,11 @@ TARGET_BUILTIN(__nvvm_vote_uni_sync, "bUib", "", PTX60)
 TARGET_BUILTIN(__nvvm_vote_ballot_sync, "UiUib", "", PTX60)
 
 // Match
-TARGET_BUILTIN(__nvvm_match_any_sync_i32, "UiUiUi", "", PTX60)
-TARGET_BUILTIN(__nvvm_match_any_sync_i64, "WiUiWi", "", PTX60)
+TARGET_BUILTIN(__nvvm_match_any_sync_i32, "UiUiUi", "", AND(SM_70,PTX60))
+TARGET_BUILTIN(__nvvm_match_any_sync_i64, "UiUiWi", "", AND(SM_70,PTX60))
 // These return a pair {value, predicate}, which requires custom lowering.
-TARGET_BUILTIN(__nvvm_match_all_sync_i32p, "UiUiUii*", "", PTX60)
-TARGET_BUILTIN(__nvvm_match_all_sync_i64p, "WiUiWii*", "", PTX60)
+TARGET_BUILTIN(__nvvm_match_all_sync_i32p, "UiUiUii*", "", AND(SM_70,PTX60))
+TARGET_BUILTIN(__nvvm_match_all_sync_i64p, "UiUiWii*", "", AND(SM_70,PTX60))
 
 // Redux
 TARGET_BUILTIN(__nvvm_redux_sync_add, "iii", "", AND(SM_80,PTX70))

diff  --git a/clang/lib/Headers/__clang_cuda_intrinsics.h 
b/clang/lib/Headers/__clang_cuda_intrinsics.h
index e0875bbcbf4ae..eee2930ece85a 100644
--- a/clang/lib/Headers/__clang_cuda_intrinsics.h
+++ b/clang/lib/Headers/__clang_cuda_intrinsics.h
@@ -234,7 +234,7 @@ inline __device__ unsigned int __match32_any_sync(unsigned 
int mask,
   return __nvvm_match_any_sync_i32(mask, value);
 }
 
-inline __device__ unsigned long long
+inline __device__ unsigned int
 __match64_any_sync(unsigned int mask, unsigned long long value) {
   return __nvvm_match_any_sync_i64(mask, value);
 }
@@ -244,7 +244,7 @@ __match32_all_sync(unsigned int mask, unsigned int value, 
int *pred) {
   return __nvvm_match_all_sync_i32p(mask, value, pred);
 }
 
-inline __device__ unsigned long long
+inline __device__ unsigned int
 __match64_all_sync(unsigned int mask, unsigned long long value, int *pred) {
   return __nvvm_match_all_sync_i64p(mask, value, pred);
 }

diff  --git a/clang/test/CodeGen/builtins-nvptx-ptx60.cu 
b/clang/test/CodeGen/builtins-nvptx-ptx60.cu
index 36d17e629eb82..afbe0a45b091b 100644
--- a/clang/test/CodeGen/builtins-nvptx-ptx60.cu
+++ b/clang/test/CodeGen/builtins-nvptx-ptx60.cu
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple nvptx64-unknown-unknown -target-cpu sm_60 \
+// RUN: %clang_cc1 -triple nvptx64-unknown-unknown -target-cpu sm_70 \
 // RUN:-fcuda-is-device -target-feature +ptx60 \
 // RUN:-S -emit-llvm -o - -x cuda %s \
 // RUN:   | FileCheck -check-prefix=CHECK %s
@@ -10,7 +10,7 @@
 // RUN:-fcuda-is-device -target-feature +ptx70 \
 // RUN:-S -emit-llvm -o - -x cuda %s \
 // RUN:   | FileCheck -check-prefix=CHECK %s
-// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_60 \
+// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_70 \
 // RUN:   -fcuda-is-device -S -o /dev/null -x cuda -verify %s
 
 #define __device__ __attribute__((device))
@@ -89,16 +89,16 @@ __device__ void nvvm_sync(unsigned mask, int i, float f, 
int a, int b,
   //
 
   // CHECK: call i32 @llvm.nvvm.match.any.sync.i32(i32
-  // expected-error@+1 {{'__nvvm_match_any_sync_i32' needs target feature 
ptx60}}
+  // expected-error-re@+1 {{'__nvvm_match_any_sync_i32' needs target feature 
(sm_70{{.*}}),(ptx60{{.*}})}}
   __nvvm_match_

[PATCH] D118370: [clang-tidy] bugprone-signal-handler: Message improvement and code refactoring.

2022-03-01 Thread Whisperity via Phabricator via cfe-commits
whisperity added a reviewer: whisperity.
whisperity added a comment.
Herald added a subscriber: rnkovacs.

This generally looks good, and thank you! I have a few minor comments (mostly 
presentation and documentation).




Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:72-73
 
 /// Given a call graph node of a function and another one that is called from
 /// this function, get a CallExpr of the corresponding function call.
 /// It is unspecified which call is found if multiple calls exist, but the 
order

(Nit: There are a lot of indirections in the documentation that did not help 
understanding what is happening here.)



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:159-160
Itr != ItrE; ++Itr) {
 const auto *CallF = dyn_cast((*Itr)->getDecl());
-if (CallF && !isFunctionAsyncSafe(CallF)) {
-  assert(Itr.getPathLength() >= 2);
-  reportBug(CallF, findCallExpr(Itr.getPath(Itr.getPathLength() - 2), 
*Itr),
-/*DirectHandler=*/false);
-  reportHandlerCommon(Itr, SignalCall, HandlerDecl, HandlerExpr);
+if (CallF) {
+  unsigned int PathL = Itr.getPathLength();





Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:165-171
+  if (checkFunction(CallF, CallOrRef))
+reportHandlerChain(Itr, HandlerExpr);
 }
   }
 }
 
+bool SignalHandlerCheck::checkFunction(const FunctionDecl *FD,

What does the return value of `checkFunction` signal to the user, and the `if`?



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:188
+  if (!FD->hasBody()) {
+diag(CallOrRef->getBeginLoc(), "cannot verify if external function %0 is "
+   "asynchronous-safe; "





Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:239
 // 
https://wiki.sei.cmu.edu/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers
-llvm::StringSet<> SignalHandlerCheck::MinimalConformingFunctions{
+const llvm::StringSet<> SignalHandlerCheck::MinimalConformingFunctions{
 "signal", "abort", "_Exit", "quick_exit"};

whisperity wrote:
> Perchance this could work with `constexpr`? Although I'm not sure how widely 
> supported that is, given that we're pegged at C++14 still.
Otherwise, **if** these are truly const and we are reasonably sure they can be 
instantiated on any meaningful system without crashing, then these could be a 
TU-`static`. It's still iffy, but that technique is used in many places already.



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:239-240
 // 
https://wiki.sei.cmu.edu/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers
-llvm::StringSet<> SignalHandlerCheck::MinimalConformingFunctions{
+const llvm::StringSet<> SignalHandlerCheck::MinimalConformingFunctions{
 "signal", "abort", "_Exit", "quick_exit"};
 

Perchance this could work with `constexpr`? Although I'm not sure how widely 
supported that is, given that we're pegged at C++14 still.



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h:48-49
   bool isSystemCallAsyncSafe(const FunctionDecl *FD) const;
-  void reportBug(const FunctionDecl *CalledFunction, const Expr *CallOrRef,
- bool DirectHandler);
-  void reportHandlerCommon(llvm::df_iterator Itr,
-   const CallExpr *SignalCall,
-   const FunctionDecl *HandlerDecl,
-   const Expr *HandlerRef);
+  /// Add bug report notes to show the call chain of functions from a signal
+  /// handler to an actual called function (from it).
+  /// @param Itr Position during a call graph depth-first iteration. It 
contains

First, we usually call these "diagnostics" in Tidy and not "bug report notes", 
which to me seems like CSA terminology. Second... It's not clear to me what 
`(from it)` is referring to. //"[...] show call chain from a signal handler to 
a [... specific? provided? expected? ...] function"// sounds alright to me.



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h:54
+  /// @param HandlerRef Reference to the signal handler function where it is
+  /// registered (considered as first part of the call chain).
+  void reportHandlerChain(const llvm::df_iterator &Itr,





Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h:46-49
   llvm::StringSet<> &ConformingFunctions;
 
   static llvm::StringSet<> MinimalConformingFunctions;
   static llvm::StringSet<> POSIXConformingFunctions;

njames93 wrote:
> While you're refactoring, those static StringSets really belong in the 
> implementation

[PATCH] D120499: [NVPTX] Fix nvvm.match.sync*.i64 intrinsics return type (i64 -> i32)

2022-03-01 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb added a comment.

@tra thank you for looking at this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120499

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


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-01 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:509
+  TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+

rovka wrote:
> Shouldn't this be a diagnostic? People could be trying to compile a random IR 
> file with a triple that's not registered.
Good point! However, I'm struggling to trigger this assert ATM and I don't want 
to issue a diagnostic if I can't test it.  This will change once `flang-new` 
can consume LLVM IR files (soon). In the meantime, let me add a `TODO`. 
Hopefully we won't forget to elevate this to a proper diagnostic when the time 
is right :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

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


[clang-tools-extra] 9485091 - [NFC][clang-tidy][docs] Remove mention of backported fix of `readability-suspicious-call-argument` from `ReleaseNotes`

2022-03-01 Thread via cfe-commits

Author: Whisperity
Date: 2022-03-01T12:06:59+01:00
New Revision: 94850918274c20c15c6071dc52314df51ed2a357

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

LOG: [NFC][clang-tidy][docs] Remove mention of backported fix of 
`readability-suspicious-call-argument` from `ReleaseNotes`

Commit 416e689ecda66616da855c82f7ec652657730c6a introduced a fix to
`readability-suspicious-call-argument` which added an entry to the
Release Notes, but the same change was backported to **14.0** in commit
e89602b7b2ec12f20f2618cefb864c2b22d0048a.

Hence, this change is not a new thing of the to-be 15.0 release.

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3227fb5ce576a..103f337bb5cd1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,10 +112,6 @@ Changes in existing checks
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is 
referenced by an lvalue
 
-- Fixed a crash in :doc:`readability-suspicious-call-argument
-  ` related to passing
-  arguments that refer to program elements without a trivial identifier.
-
 Removed checks
 ^^
 



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


[PATCH] D120710: [clang-format] QualifierOrder does not reorder template arguments

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: HazardyKnusperkeks, curdeius.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

https://github.com/llvm/llvm-project/issues/53981

Reorder the qualifiers inside the template argument. This should handle the 
simple cases of

  
  

But only by relaxing that single letter capital variables are not possible 
macros

Fixes: #53981


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120710

Files:
  clang/lib/Format/QualifierAlignmentFixer.cpp
  clang/unittests/Format/QualifierFixerTest.cpp


Index: clang/unittests/Format/QualifierFixerTest.cpp
===
--- clang/unittests/Format/QualifierFixerTest.cpp
+++ clang/unittests/Format/QualifierFixerTest.cpp
@@ -895,5 +895,36 @@
Style);
 }
 
+TEST_F(QualifierFixerTest, TemplatesRight) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"type", "const"};
+
+  verifyFormat("template \n"
+   "  requires Concept\n"
+   "void f();",
+   "template \n"
+   "  requires Concept\n"
+   "void f();",
+   Style);
+  verifyFormat("TemplateType t;", "TemplateType t;", Style);
+}
+
+TEST_F(QualifierFixerTest, TemplatesLeft) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"const", "type"};
+
+  verifyFormat("template  t;", "template  t;", Style);
+  verifyFormat("template \n"
+   "  requires Concept\n"
+   "void f();",
+   "template \n"
+   "  requires Concept\n"
+   "void f();",
+   Style);
+  verifyFormat("TemplateType t;", "TemplateType t;", Style);
+}
+
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/QualifierAlignmentFixer.cpp
===
--- clang/lib/Format/QualifierAlignmentFixer.cpp
+++ clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -223,6 +223,12 @@
   if (LastQual && Qual != LastQual) {
 rotateTokens(SourceMgr, Fixes, Tok, LastQual, /*Left=*/false);
 Tok = LastQual;
+  } else if (Tok->startsSequence(QualifierType, tok::identifier,
+ TT_TemplateCloser)) {
+FormatToken *Closer = Tok->Next->Next;
+rotateTokens(SourceMgr, Fixes, Tok, Tok->Next, /*Left=*/false);
+Tok = Closer;
+return Tok;
   } else if (Tok->startsSequence(QualifierType, tok::identifier,
  TT_TemplateOpener)) {
 // Read from the TemplateOpener to
@@ -307,6 +313,11 @@
 rotateTokens(SourceMgr, Fixes, Tok, Tok->Next, /*Left=*/true);
 Tok = Tok->Next;
   }
+} else if (Tok->startsSequence(tok::identifier, QualifierType,
+   TT_TemplateCloser)) {
+  FormatToken *Closer = Tok->Next->Next;
+  rotateTokens(SourceMgr, Fixes, Tok, Tok->Next, /*Left=*/true);
+  Tok = Closer;
 }
   }
   if (Tok->is(TT_TemplateOpener) && Tok->Next &&
@@ -329,8 +340,12 @@
 Next = Next->getNextNonComment();
   assert(Next->MatchingParen && "Missing template closer");
   Next = Next->MatchingParen;
+
+  // If the template closer is closing the requires clause
+  // then stop and go back to the TemplateOpenener and do whatever is
+  // inside the <>
   if (Next->ClosesRequiresClause)
-return Next;
+return Next->MatchingParen;
   Next = Next->Next;
 
   // Move to the end of any template class members e.g.
@@ -460,8 +475,12 @@
 return false;
   if (!Tok->is(tok::identifier))
 return false;
-  if (Tok->TokenText.upper() == Tok->TokenText.str())
+  if (Tok->TokenText.upper() == Tok->TokenText.str()) {
+// T,K,U,V likely could be template arguments
+if (Tok->TokenText.size() == 1)
+  return false;
 return true;
+  }
   return false;
 }
 


Index: clang/unittests/Format/QualifierFixerTest.cpp
===
--- clang/unittests/Format/QualifierFixerTest.cpp
+++ clang/unittests/Format/QualifierFixerTest.cpp
@@ -895,5 +895,36 @@
Style);
 }
 
+TEST_F(QualifierFixerTest, TemplatesRight) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"type", "const"};
+
+  verifyFormat("template \n"
+   "  requires Concept\n"
+   "void f();",
+   "template \n"
+   "  requires Concept\n"
+   "void f();",
+   Style);
+  verifyFormat("TemplateType t;", "TemplateType t;", Style);
+}
+
+TEST_F(QualifierFixerTest, TemplatesLeft) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"const"

[PATCH] D120555: [clang-tidy] Fix `readability-suspicious-call-argument` crash for arguments without name-like identifier

2022-03-01 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In D120555#3345707 , @njames93 wrote:

> If you backport, the release notes change on trunk should then be reverted.

Release Notes entry of current development tree reverted in 
rG94850918274c20c15c6071dc52314df51ed2a357 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120555

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, xazax.hun, gribozavr2.
Herald added subscribers: tschuett, steakhal, rnkovacs, mgorny.
sgatev requested review of this revision.
Herald added a project: clang.

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120711

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -68,7 +69,7 @@
   ControlFlowContext::build(nullptr, Body, &AST->getASTContext()));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx);
 
   return runDataflowAnalysis(CFCtx, Analysis, Env);
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -23,6 +23,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
@@ -104,7 +105,7 @@
   if (!CFCtx)
 return CFCtx.takeError();
 
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -0,0 +1,69 @@
+//===- unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.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/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+
+class EnvironmentTest : public ::testing::Test {
+  DataflowAnalysisContext Context;
+
+protected:
+  EnvironmentTest()
+  : Context(std::make_unique()), Env(Context) {}
+
+  Environment Env;
+};
+
+TEST_F(EnvironmentTest, MakeAndReturnsSameExprGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XAndX = Env.makeAnd(X, X);
+  EXPECT_EQ(&XAndX, &X);
+}
+
+TEST_F(EnvironmentTest, MakeOrReturnsSameExprGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XOrX = Env.makeOr(X, X);
+  EXPECT_EQ(&XOrX, &X);
+}
+
+TEST_F(EnvironmentTest, MakeImplicationReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeImplication(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, MakeIffReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeIff(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, FlowCondition) {
+  EXPECT_TRUE(Env.flowConditionImplies(Env.getBoolLiteralValue(true)));
+  EXPECT_FALSE(Env.flowCondit

[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 412034.
sgatev added a comment.

Minor changes to comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -68,7 +69,7 @@
   ControlFlowContext::build(nullptr, Body, &AST->getASTContext()));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx);
 
   return runDataflowAnalysis(CFCtx, Analysis, Env);
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -23,6 +23,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
@@ -104,7 +105,7 @@
   if (!CFCtx)
 return CFCtx.takeError();
 
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -0,0 +1,69 @@
+//===- unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.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/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+
+class EnvironmentTest : public ::testing::Test {
+  DataflowAnalysisContext Context;
+
+protected:
+  EnvironmentTest()
+  : Context(std::make_unique()), Env(Context) {}
+
+  Environment Env;
+};
+
+TEST_F(EnvironmentTest, MakeAndReturnsSameExprGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XAndX = Env.makeAnd(X, X);
+  EXPECT_EQ(&XAndX, &X);
+}
+
+TEST_F(EnvironmentTest, MakeOrReturnsSameExprGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XOrX = Env.makeOr(X, X);
+  EXPECT_EQ(&XOrX, &X);
+}
+
+TEST_F(EnvironmentTest, MakeImplicationReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeImplication(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, MakeIffReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeIff(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, FlowCondition) {
+  EXPECT_TRUE(Env.flowConditionImplies(Env.getBoolLiteralValue(true)));
+  EXPECT_FALSE(Env.flowConditionImplies(Env.getBoolLiteralValue(false)));
+
+  auto &X = Env.makeAtomicBoolValue();
+  EXPECT_FALSE(Env.flowConditionImplies(X));
+
+  Env.addToFlowCondition(X);
+  EXPECT_TRUE(Env.flowConditionIm

[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk created this revision.
kwk added a reviewer: FederAndInk.
kwk requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If there was this enum definition before:

  struct FormatStyle {
//...
  
/// Different styles for aligning after open brackets.
enum WhateverStyle : unsigned char {
  /// Foo
  WS_Bar = 5
};
  };

We would output the following in
`clang/docs/ClangFormatStyleOptions.rst`
when running `cd ~/llvm-project/clang/docs/tools &&
./dump_format_style.py`:

  * ``WS_Bar = 5`` (in configuration: ``Bar = 5``)
Foo.

With this patch, we change it to something that looks more like what we
are accustomed to:

  * ``WS_Bar`` (in configuration: ``Bar``)
Foo.

This is a theoretical change because we don't have format style enums
that currently explicitly select a value. But while I was doing some
research on how to extend the `FormatStyle` I noticed this behavior and
thought it would make a small change.

You can experiment with and without this change by simply running 
`dump_format_style.py` while setting `AIAS_Left` to `AIAS_Left = 0`
in `clang/include/clang/Format/Format.h`. Without this change in
`Format.h` you shouldn't see any change being made to
`clang/docs/ClangFormatStyleOptions.rst`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120712

Files:
  clang/docs/tools/dump_format_style.py


Index: clang/docs/tools/dump_format_style.py
===
--- clang/docs/tools/dump_format_style.py
+++ clang/docs/tools/dump_format_style.py
@@ -159,10 +159,20 @@
 self.comment = comment
 self.config = config
 
+  @property
+  def clean_name(self) -> str:
+# In case the enum value has an explicit value (e.g. enum foo {bar = 42};)
+# we remove everything after the equal sign and just use "bar". 
+return self.name.split("=", 1)[0].strip()
+
+  @property
+  def clean_config(self) -> str:
+return re.sub('.*_', '', self.config).split("=", 1)[0].strip()
+
   def __str__(self):
 return '* ``%s`` (in configuration: ``%s``)\n%s' % (
-self.name,
-re.sub('.*_', '', self.config),
+self.clean_name,
+self.clean_config,
 doxygen2rst(indent(self.comment, 2)))
 
 


Index: clang/docs/tools/dump_format_style.py
===
--- clang/docs/tools/dump_format_style.py
+++ clang/docs/tools/dump_format_style.py
@@ -159,10 +159,20 @@
 self.comment = comment
 self.config = config
 
+  @property
+  def clean_name(self) -> str:
+# In case the enum value has an explicit value (e.g. enum foo {bar = 42};)
+# we remove everything after the equal sign and just use "bar". 
+return self.name.split("=", 1)[0].strip()
+
+  @property
+  def clean_config(self) -> str:
+return re.sub('.*_', '', self.config).split("=", 1)[0].strip()
+
   def __str__(self):
 return '* ``%s`` (in configuration: ``%s``)\n%s' % (
-self.name,
-re.sub('.*_', '', self.config),
+self.clean_name,
+self.clean_config,
 doxygen2rst(indent(self.comment, 2)))
 
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118996: [clang-tidy] Support C++14 in bugprone-signal-handler.

2022-03-01 Thread Whisperity via Phabricator via cfe-commits
whisperity added a reviewer: whisperity.
whisperity added inline comments.



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:142-149
   Finder->addMatcher(
   callExpr(callee(SignalFunction), hasArgument(1, HandlerExpr))
   .bind("register_call"),
   this);
+  Finder->addMatcher(
+  callExpr(callee(SignalFunction), hasArgument(1, HandlerLambda))
+  .bind("register_call"),

LegalizeAdulthood wrote:
> Is there any utility/performance to be gained by combining these into a 
> single matcher?
> e.g.
> ```
> callExpr(callee(SignalFunction), anyOf(hasArgument(1, HandlerExpr), 
> hasArgument(1, HandlerLambda)))
> ```
> (not sure if that is syntactically valid, but you get my point)
Or perhaps

```
callExpr(callee(SignalFunction), hasArgument(1, expr(anyOf(HandlerExpr, 
HandlerLambda;
```



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:247
 
+  if (!getLangOpts().CPlusPlus17 && getLangOpts().CPlusPlus)
+return checkFunctionCPP14(FD, CallOrRef, ChainReporter);

balazske wrote:
> LegalizeAdulthood wrote:
> > How can the first expression here ever be false when
> > we rejected C++17 in the `isLanguageVersionSupported`
> > override?
> I was thinking for the case when this check supports C++17 too. The change 
> can be added later, this makes current code more readable.
(True. I think @LegalizeAdulthood's comment can be marked as Done.)



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:41
 
+bool isInGlobalNamespace(const FunctionDecl *FD) {
+  const DeclContext *DC = FD->getDeclContext();

Is this feature not available in (some parent class of) `FunctionDecl`?



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:46
+  assert(DC && "Function should have a declaration context.");
+  return DC->isTranslationUnit();
+}

(Perhaps a >= C++20 fixme that this query here //might// not handle modules 
well?)



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:94
 
+SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) {
+  ParentMapContext &PM = Ctx.getParentMapContext();

Okay, this is interesting... Why is `Ctx` not `const`? Unless 
**`get`**`Something()` is changing things (which is non-intuitive then...), as 
far as I can tell, you're only reading from `Ctx`.



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:96
+  ParentMapContext &PM = Ctx.getParentMapContext();
+  DynTypedNode P = DynTypedNode::create(*S);
+  while (P.getSourceRange().getBegin().isInvalid()) {

Are these objects cleaned up properly in their destructor (same question for 
`DynTypeNodeList`)?



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:97
+  DynTypedNode P = DynTypedNode::create(*S);
+  while (P.getSourceRange().getBegin().isInvalid()) {
+DynTypedNodeList PL = PM.getParents(P);

`SourceRange` itself should have a sentinel query. Why is only the beginning of 
it interesting?



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:99-101
+if (PL.size() != 1)
+  return {};
+P = PL[0];

`size != 1` could still mean `size == 0` in which case taking an element seems 
dangerous. Is triggering such UB possible here?



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:153
+diag(HandlerLambda->getBeginLoc(),
+ "lambda function is not allowed as signal handler (until C++17)")
+<< HandlerLambda->getSourceRange();

I am trying to find some source for this claim but so far hit a blank. 😦 Could 
you please elaborate where this information comes from? Most notably, [[ 
https://en.cppreference.com/w/cpp/utility/program/signal | std::signal on 
CppReference ]] makes no mention of this, which would be the first place I 
would expect most people to look at.

Maybe this claim is derived from the rule that signal handlers **MUST** have C 
linkage? (If so, is there a warning against people setting C++-linkage 
functions as signal handlers in this check in general?)



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:162
   const auto *HandlerExpr = 
Result.Nodes.getNodeAs("handler_expr");
+
   assert(SignalCall && HandlerDecl && HandlerExpr &&

(Nit: maybe it is better without this newline, to visibly demarcate the "local 
state init "block"" of the function.)



Comment at: clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp:178-179
+// Check the handler function.
+// The warning is placed to the signal handler registration.
+// No need to display a call chain and no need for more checks.
+(void

[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-01 Thread Diana Picus via Phabricator via cfe-commits
rovka added a comment.

I don't have any other comments, I'll let Eric take it from here :)




Comment at: flang/lib/Frontend/FrontendActions.cpp:509
+  TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+

awarzynski wrote:
> rovka wrote:
> > Shouldn't this be a diagnostic? People could be trying to compile a random 
> > IR file with a triple that's not registered.
> Good point! However, I'm struggling to trigger this assert ATM and I don't 
> want to issue a diagnostic if I can't test it.  This will change once 
> `flang-new` can consume LLVM IR files (soon). In the meantime, let me add a 
> `TODO`. Hopefully we won't forget to elevate this to a proper diagnostic when 
> the time is right :)
TODO is fine for now, thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

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


[PATCH] D120713: [clangd] Make dexp command line options sticky

2022-03-01 Thread Yevgeny Rouban via Phabricator via cfe-commits
yrouban created this revision.
yrouban added reviewers: jhenderson, lattner, jpienaar, mehdi_amini.
yrouban added a project: clang.
Herald added subscribers: usaxena95, kadircet, arphaman.
yrouban requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Preparing for the cl::opt reset fix proposed on D115433 
 this patch fixes the dexp tool to preserve 
its three command line options (IndexLocation, ExecCommand, ProjectRoot) from 
reset that is done before parsing query options.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120713

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp


Index: clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
===
--- clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
+++ clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
@@ -413,6 +413,12 @@
   using namespace clang::clangd;
 
   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
+
+  // Protect IndexLocation, ExecCommand and ProjectRoot from being reset.
+  IndexLocation.setValue(IndexLocation, true /* initial */);
+  ExecCommand.setValue(ExecCommand, true /* initial */);
+  ProjectRoot.setValue(ProjectRoot, true /* initial */);
+
   llvm::cl::ResetCommandLineParser(); // We reuse it for REPL commands.
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 


Index: clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
===
--- clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
+++ clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
@@ -413,6 +413,12 @@
   using namespace clang::clangd;
 
   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
+
+  // Protect IndexLocation, ExecCommand and ProjectRoot from being reset.
+  IndexLocation.setValue(IndexLocation, true /* initial */);
+  ExecCommand.setValue(ExecCommand, true /* initial */);
+  ProjectRoot.setValue(ProjectRoot, true /* initial */);
+
   llvm::cl::ResetCommandLineParser(); // We reuse it for REPL commands.
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120111: [AArch64] Default HBC/MOPS features in clang

2022-03-01 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson accepted this revision.
tmatheson added a comment.
This revision is now accepted and ready to land.

LGTM, please give @nickdesaulniers some time to respond though. I do agree that 
iterating over the features repeatedly is less than ideal, but also that this 
patch is probably not the place to try to fix it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120111

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


[PATCH] D120710: [clang-format] QualifierOrder does not reorder template arguments

2022-03-01 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks for fixing this!




Comment at: clang/lib/Format/QualifierAlignmentFixer.cpp:344-346
+  // If the template closer is closing the requires clause
+  // then stop and go back to the TemplateOpenener and do whatever is
+  // inside the <>




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120710

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


[clang] 3cdc1c1 - [Clang] Add `-funstable` flag to enable unstable and experimental features

2022-03-01 Thread Egor Zhdan via cfe-commits

Author: Egor Zhdan
Date: 2022-03-01T12:35:20Z
New Revision: 3cdc1c155b40897a17d7fd61092d2f6fd21fb7ef

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

LOG: [Clang] Add `-funstable` flag to enable unstable and experimental features

This new flag enables `__has_feature(cxx_unstable)` that would replace libc++ 
macros for individual unstable/experimental features, e.g. 
`_LIBCPP_HAS_NO_INCOMPLETE_RANGES` or `_LIBCPP_HAS_NO_INCOMPLETE_FORMAT`.

This would make it easier and more convenient to opt-in into all libc++ 
unstable features at once.

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

Added: 
clang/test/Driver/unstable-flag.cpp
clang/test/Lexer/has_feature_cxx_unstable.cpp

Modified: 
clang/include/clang/Basic/Features.def
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 6ca0e646b8650..522ae5951499b 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -173,6 +173,7 @@ FEATURE(cxx_thread_local,
 FEATURE(cxx_trailing_return, LangOpts.CPlusPlus11)
 FEATURE(cxx_unicode_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_unrestricted_unions, LangOpts.CPlusPlus11)
+FEATURE(cxx_unstable, LangOpts.Unstable)
 FEATURE(cxx_user_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_variadic_templates, LangOpts.CPlusPlus11)
 // C++14 features

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 6d98850a2bea9..3745740d3d29c 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -150,6 +150,7 @@ LANGOPT(GNUAsm, 1, 1, "GNU-style inline 
assembly")
 LANGOPT(Coroutines, 1, 0, "C++20 coroutines")
 LANGOPT(DllExportInlines  , 1, 1, "dllexported classes dllexport inline 
methods")
 LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template 
template arguments")
+LANGOPT(Unstable  , 1, 0, "Enable unstable and experimental features")
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 60e90f3f2237a..24e2069711be5 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1160,6 +1160,11 @@ defm coroutines_ts : BoolFOption<"coroutines-ts",
   PosFlag,
   NegFlag>;
 
+defm unstable : BoolFOption<"unstable",
+  LangOpts<"Unstable">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
+
 def fembed_offload_object_EQ : Joined<["-"], "fembed-offload-object=">,
   Group, Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Embed Offloading device-side binary into host object file as a 
section.">,

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 341e108ed65da..14f33a0ae66e9 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5764,6 +5764,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back(A->getValue());
   }
 
+  if (Args.hasArg(options::OPT_funstable)) {
+CmdArgs.push_back("-funstable");
+if (!Args.hasArg(options::OPT_fno_coroutines_ts))
+  CmdArgs.push_back("-fcoroutines-ts");
+CmdArgs.push_back("-fmodules-ts");
+  }
+
   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
 

diff  --git a/clang/test/Driver/unstable-flag.cpp 
b/clang/test/Driver/unstable-flag.cpp
new file mode 100644
index 0..7e241facf76e5
--- /dev/null
+++ b/clang/test/Driver/unstable-flag.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang -funstable -### %s 2>&1 | FileCheck %s
+
+// CHECK: -funstable
+// CHECK: -fcoroutines-ts
+// CHECK: -fmodules-ts

diff  --git a/clang/test/Lexer/has_feature_cxx_unstable.cpp 
b/clang/test/Lexer/has_feature_cxx_unstable.cpp
new file mode 100644
index 0..c4ce45a93075d
--- /dev/null
+++ b/clang/test/Lexer/has_feature_cxx_unstable.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -funstable -E %s -o - | FileCheck 
--check-prefix=CHECK-UNSTABLE %s
+// RUN: %clang_cc1 -E %s -o - | FileCheck --check-prefix=CHECK-NO-UNSTABLE %s
+
+#if __has_feature(cxx_unstable)
+int has_cxx_unstable();
+#else
+int has_no_cxx_unstable();
+#endif
+// CHECK-UNSTABLE: int has_cxx_unstable();
+// CHECK-NO-UNSTABLE: int has_no_cxx_unstable();



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


[PATCH] D120160: [Clang] Add `-funstable` flag to enable unstable and experimental features

2022-03-01 Thread Egor Zhdan 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 rG3cdc1c155b40: [Clang] Add `-funstable` flag to enable 
unstable and experimental features (authored by egorzhdan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120160

Files:
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/unstable-flag.cpp
  clang/test/Lexer/has_feature_cxx_unstable.cpp


Index: clang/test/Lexer/has_feature_cxx_unstable.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_cxx_unstable.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -funstable -E %s -o - | FileCheck 
--check-prefix=CHECK-UNSTABLE %s
+// RUN: %clang_cc1 -E %s -o - | FileCheck --check-prefix=CHECK-NO-UNSTABLE %s
+
+#if __has_feature(cxx_unstable)
+int has_cxx_unstable();
+#else
+int has_no_cxx_unstable();
+#endif
+// CHECK-UNSTABLE: int has_cxx_unstable();
+// CHECK-NO-UNSTABLE: int has_no_cxx_unstable();
Index: clang/test/Driver/unstable-flag.cpp
===
--- /dev/null
+++ clang/test/Driver/unstable-flag.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang -funstable -### %s 2>&1 | FileCheck %s
+
+// CHECK: -funstable
+// CHECK: -fcoroutines-ts
+// CHECK: -fmodules-ts
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5764,6 +5764,13 @@
 CmdArgs.push_back(A->getValue());
   }
 
+  if (Args.hasArg(options::OPT_funstable)) {
+CmdArgs.push_back("-funstable");
+if (!Args.hasArg(options::OPT_fno_coroutines_ts))
+  CmdArgs.push_back("-fcoroutines-ts");
+CmdArgs.push_back("-fmodules-ts");
+  }
+
   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1160,6 +1160,11 @@
   PosFlag,
   NegFlag>;
 
+defm unstable : BoolFOption<"unstable",
+  LangOpts<"Unstable">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
+
 def fembed_offload_object_EQ : Joined<["-"], "fembed-offload-object=">,
   Group, Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Embed Offloading device-side binary into host object file as a 
section.">,
Index: clang/include/clang/Basic/LangOptions.def
===
--- clang/include/clang/Basic/LangOptions.def
+++ clang/include/clang/Basic/LangOptions.def
@@ -150,6 +150,7 @@
 LANGOPT(Coroutines, 1, 0, "C++20 coroutines")
 LANGOPT(DllExportInlines  , 1, 1, "dllexported classes dllexport inline 
methods")
 LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template 
template arguments")
+LANGOPT(Unstable  , 1, 0, "Enable unstable and experimental features")
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -173,6 +173,7 @@
 FEATURE(cxx_trailing_return, LangOpts.CPlusPlus11)
 FEATURE(cxx_unicode_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_unrestricted_unions, LangOpts.CPlusPlus11)
+FEATURE(cxx_unstable, LangOpts.Unstable)
 FEATURE(cxx_user_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_variadic_templates, LangOpts.CPlusPlus11)
 // C++14 features


Index: clang/test/Lexer/has_feature_cxx_unstable.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_cxx_unstable.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -funstable -E %s -o - | FileCheck --check-prefix=CHECK-UNSTABLE %s
+// RUN: %clang_cc1 -E %s -o - | FileCheck --check-prefix=CHECK-NO-UNSTABLE %s
+
+#if __has_feature(cxx_unstable)
+int has_cxx_unstable();
+#else
+int has_no_cxx_unstable();
+#endif
+// CHECK-UNSTABLE: int has_cxx_unstable();
+// CHECK-NO-UNSTABLE: int has_no_cxx_unstable();
Index: clang/test/Driver/unstable-flag.cpp
===
--- /dev/null
+++ clang/test/Driver/unstable-flag.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang -funstable -### %s 2>&1 | FileCheck %s
+
+// CHECK: -funstable
+// CHECK: -fcoroutines-ts
+// CHECK: -fmodules-ts
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib

[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I'm not quite sure how I feel about adding functionality that doesn't actually 
do anything.




Comment at: clang/docs/tools/dump_format_style.py:174-175
 return '* ``%s`` (in configuration: ``%s``)\n%s' % (
-self.name,
-re.sub('.*_', '', self.config),
+self.clean_name,
+self.clean_config,
 doxygen2rst(indent(self.comment, 2)))

Feels like there is repetition here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D116439: [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

2022-03-01 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 412056.

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

https://reviews.llvm.org/D116439

Files:
  clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
@@ -271,3 +271,17 @@
 
 int **const * n_multiple_ptr();
 int *const & n_pointer_ref();
+
+class PVBase {
+public:
+  virtual const int getC() = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: virtual int getC() = 0;
+};
+
+class PVDerive : public PVBase {
+public:
+  const int getC() { return 1; }
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: int getC() { return 1; }
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,6 +112,10 @@
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is 
referenced by an lvalue
 
+- Fixed a crash in :doc:`readability-const-return-type
+  ` when a pure virtual 
function
+  overrided has a const return type. Removed the fix for a virtual function.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -97,7 +97,9 @@
   // Find all function definitions for which the return types are `const`
   // qualified.
   Finder->addMatcher(
-  functionDecl(returns(isConstQualified()), isDefinition()).bind("func"),
+  functionDecl(returns(isConstQualified()),
+   anyOf(isDefinition(), cxxMethodDecl(isPure(
+  .bind("func"),
   this);
 }
 
@@ -115,6 +117,12 @@
 << Def->getReturnType();
 if (CR.ConstRange.isValid())
   Diagnostic << CR.ConstRange;
+
+// Do not propose fixes for virtual function.
+const auto *Method = dyn_cast(Def);
+if (Method && Method->isVirtual())
+  return;
+
 for (auto &Hint : CR.Hints)
   Diagnostic << Hint;
   }


Index: clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
@@ -271,3 +271,17 @@
 
 int **const * n_multiple_ptr();
 int *const & n_pointer_ref();
+
+class PVBase {
+public:
+  virtual const int getC() = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-qualified at the top level, which may reduce code readability without improving const correctness
+  // CHECK-NOT-FIXES: virtual int getC() = 0;
+};
+
+class PVDerive : public PVBase {
+public:
+  const int getC() { return 1; }
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-qualified at the top level, which may reduce code readability without improving const correctness
+  // CHECK-NOT-FIXES: int getC() { return 1; }
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,6 +112,10 @@
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is referenced by an lvalue
 
+- Fixed a crash in :doc:`readability-const-return-type
+  ` when a pure virtual function
+  overrided has a const return type. Removed the fix for a virtual function.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -97,7 +97,9 @@
   // Find all function definitions for which the return types are `const`
   // qualified.
   Finder->addMatcher(
-  functionDecl(returns(isConstQualified()), isDefinition()).bind("func"),
+  functionDecl(returns(isConstQualified()),
+

[PATCH] D120369: [analyzer] Add more propagations to Taint analysis

2022-03-01 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 412057.
gamesh411 marked 17 inline comments as done.
gamesh411 added a comment.
Herald added a subscriber: manas.

- remove vscanf and co.
- use debug.ExprInspection for test cases
- fix semantic issues for modeled functions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120369

Files:
  clang/docs/analyzer/checkers.rst
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/test/Analysis/taint-generic.c

Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -1,20 +1,26 @@
-// RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast -verify %s \
+// RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast \
+// RUN:   -Wno-incompatible-library-redeclaration -verify %s \
 // RUN:   -analyzer-checker=alpha.security.taint \
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=alpha.security.ArrayBoundV2 \
+// RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config \
 // RUN: alpha.security.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config.yaml
 
-// RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast -verify %s \
+// RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast \
+// RUN:   -Wno-incompatible-library-redeclaration -verify %s \
 // RUN:   -DFILE_IS_STRUCT \
 // RUN:   -analyzer-checker=alpha.security.taint \
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=alpha.security.ArrayBoundV2 \
+// RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config \
 // RUN: alpha.security.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config.yaml
 
-// RUN: not %clang_analyze_cc1 -Wno-pointer-to-int-cast -verify %s \
+// RUN: not %clang_analyze_cc1 -Wno-pointer-to-int-cast \
+// RUN:   -Wno-incompatible-library-redeclaration -verify %s \
 // RUN:   -analyzer-checker=alpha.security.taint \
+// RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config \
 // RUN: alpha.security.taint.TaintPropagation:Config=justguessit \
 // RUN:   2>&1 | FileCheck %s -check-prefix=CHECK-INVALID-FILE
@@ -24,8 +30,10 @@
 // CHECK-INVALID-FILE-SAME:that expects a valid filename instead of
 // CHECK-INVALID-FILE-SAME:'justguessit'
 
-// RUN: not %clang_analyze_cc1 -verify %s \
+// RUN: not %clang_analyze_cc1 -Wno-incompatible-library-redeclaration \
+// RUN:   -verify %s \
 // RUN:   -analyzer-checker=alpha.security.taint \
+// RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config \
 // RUN: alpha.security.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config-ill-formed.yaml \
 // RUN:   2>&1 | FileCheck -DMSG=%errc_EINVAL %s -check-prefix=CHECK-ILL-FORMED
@@ -34,8 +42,10 @@
 // CHECK-ILL-FORMED-SAME:'alpha.security.taint.TaintPropagation:Config',
 // CHECK-ILL-FORMED-SAME:that expects a valid yaml file: [[MSG]]
 
-// RUN: not %clang_analyze_cc1 -verify %s \
+// RUN: not %clang_analyze_cc1 -Wno-incompatible-library-redeclaration \
+// RUN:   -verify %s \
 // RUN:   -analyzer-checker=alpha.security.taint \
+// RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config \
 // RUN: alpha.security.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config-invalid-arg.yaml \
 // RUN:   2>&1 | FileCheck %s -check-prefix=CHECK-INVALID-ARG
@@ -45,6 +55,10 @@
 // CHECK-INVALID-ARG-SAME:that expects an argument number for propagation
 // CHECK-INVALID-ARG-SAME:rules greater or equal to -1
 
+void clang_analyzer_isTainted_char(char);
+void clang_analyzer_isTainted_charp(char*);
+void clang_analyzer_isTainted_int(int);
+
 int scanf(const char *restrict format, ...);
 char *gets(char *str);
 int getchar(void);
@@ -58,10 +72,15 @@
 
 #define bool _Bool
 
+#define NULL (void*)0
+
+FILE *fopen(const char *name, const char *mode);
+
 int fscanf(FILE *restrict stream, const char *restrict format, ...);
 int sprintf(char *str, const char *format, ...);
 void setproctitle(const char *fmt, ...);
 typedef __typeof(sizeof(int)) size_t;
+typedef int ssize_t;
 
 // Define string functions. Use builtin for some of them. They all default to
 // the processing in the taint checker.
@@ -352,6 +371,510 @@
   return 1 / x; // expected-warning {{Division by a tainted value, possibly zero}}
 }
 
+int fscanf_s(FILE *stream, const char *format, ...);
+void testFscanf_s(const char *fname, int *d) {
+  FILE *f = fopen(fname, "r");
+  fscanf_s(f, "%d", d);
+  clang_analyzer_isTainted_int(*d); // expected-warning {{YES}}
+}
+
+int fread(void *buffer, size_t size, size_t count, FILE *stream);
+void testFread(const char *fname, int *buffer, size_t size, size_t count) {
+  FILE *f = fopen(fname, "r");
+  size_t read = fread(buffer, size,

[PATCH] D120369: [analyzer] Add more propagations to Taint analysis

2022-03-01 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:2361
 Default propagations defined by ``GenericTaintChecker``:
-``atoi``, ``atol``, ``atoll``, ``fgetc``, ``fgetln``, ``fgets``, ``fscanf``, 
``sscanf``, ``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, 
``pread``, ``read``, ``strchr``, ``strrchr``, ``tolower``, ``toupper``
+``atoi``, ``atol``, ``atoll``, ``basename``, ``dirname``, ``fgetc``, 
``fgetln``, ``fgets``, ``fnmatch``, ``fread``, ``fscanf``, ``fscanf_s``, 
``index``, ``inflate``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``, 
``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``, 
``isspace``, ``isupper``, ``isxdigit``, ``memchr``, ``memrchr``, ``sscanf``, 
``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, ``memcmp``, 
``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``, 
``qsort_r``, ``rawmemchr``, ``read``, ``readv``, ``recv``, ``recvfrom``, 
``rindex``, ``strcasestr``, ``strchr``, ``strchrnul``,  ``strcasecmp``, 
``strcmp``, ``strcspn``, ``strlen``, ``strncasecmp``, ``strncmp``, ``strndup``, 
``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``, ``strstr``, 
``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``, ``toupper``, 
``ttyname``, ``ttyname_r``, ``vfscanf``, ``vfscanf``, ``wctomb``, ``wcwidth``
 

steakhal wrote:
> I cannot see the corresponding propagation rule.
> That being said, it would be handy to mention that this is for `zlib` 
> decompression and this should be probably a taint source anyway.
> 
> `vfscanf` occurs two times.
> 
> `vscanf` is not mentioned here; and there are probably a couple others like 
> this.
Removed `vscanf` and `vfscanf` as modeling their taint is not straightforward 
and should be done in another checker.
The problem with those is that they do not use variadic arguments, but an 
abstraction of those implemented by the type `va_list`, which is used to 
support invocations, where the number of arguments is determined at runtime.
In addition to modeling individual v-variants we will also have to handle the 
creation of `va_list` objects, and `va_start` function calls and try to reason 
about which parameters will be tainted.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:561
+  {{"vscanf"}, TR::Prop({{0}}, {{}, 1})},
+  {{"vfscanf"}, TR::Prop({{0}}, {{}, 2})},
+

steakhal wrote:
> This function has exactly 3 arguments.
> I'm also puzzled how tainting `va_list` will work out. That should be modeled 
> separately IMO.
> This comment applies to all of the similar `va_list` accepting functions, 
> such as `vscanf`, `vfscanf`, and possibly others.
> 
> That being said, I think `vscanf` is more like `scanf`, so it should be 
> modeled as a taint source instead of a propagator.
removed



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:575
+  {{"fread"}, TR::Prop({{3}}, {{0, ReturnValueIndex}})},
+  {{"readv"}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
+  {{"recv"}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},

steakhal wrote:
> I'm on board with marking read operations as props/sources.
> Let's look at the declaration: `ssize_t readv(int fd, const struct iovec 
> *iov, int iovcnt);`
> I'm not sure how could the pointee of `iov` be modified by this call, as its 
> `const`.
> Additionally, I doubt the effectiveness of the rule, since I don't think it 
> would be too likely to have a path leading to a taint sink with an `iov` 
> pointer. That being said, let it be, but don't expect much from this rule :D
On second thought, this seems pointless indeed, removed.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:582-583
+
+  {{"dirname"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
+  {{"basename"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
+  {{"fnmatch"}, TR::Prop({{0}}, {{ReturnValueIndex}})},

steakhal wrote:
> These should be sorted, isn't it?
swapped, thx



Comment at: clang/test/Analysis/taint-generic.c:399-400
+struct iovec {
+  void *iov_base; /* Starting address */
+  size_t iov_len; /* Number of bytes to transfer */
+};

steakhal wrote:
> Please use single-line comments.
> It makes debugging test files easier in some cases.
removed



Comment at: clang/test/Analysis/taint-generic.c:408
+  size_t read = readv(fd, iov, iovcnt);
+  // FIXME: should be able to assert that iov is also tainted
+  return 1 / read; // expected-warning {{Division by a tainted value, possibly 
zero}}

steakhal wrote:
> `clang_analyzer_isTainted(*iov)`
test case removed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120369

___
cfe-commits mailin

[PATCH] D116439: [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

2022-03-01 Thread gehry 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 rGba54ebeb5eba: [clang-tidy] Fix 
`readability-const-return-type` for pure virtual function. (authored by Sockke).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116439

Files:
  clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
@@ -271,3 +271,17 @@
 
 int **const * n_multiple_ptr();
 int *const & n_pointer_ref();
+
+class PVBase {
+public:
+  virtual const int getC() = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: virtual int getC() = 0;
+};
+
+class PVDerive : public PVBase {
+public:
+  const int getC() { return 1; }
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: int getC() { return 1; }
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,6 +112,10 @@
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is 
referenced by an lvalue
 
+- Fixed a crash in :doc:`readability-const-return-type
+  ` when a pure virtual 
function
+  overrided has a const return type. Removed the fix for a virtual function.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -97,7 +97,9 @@
   // Find all function definitions for which the return types are `const`
   // qualified.
   Finder->addMatcher(
-  functionDecl(returns(isConstQualified()), isDefinition()).bind("func"),
+  functionDecl(returns(isConstQualified()),
+   anyOf(isDefinition(), cxxMethodDecl(isPure(
+  .bind("func"),
   this);
 }
 
@@ -115,6 +117,12 @@
 << Def->getReturnType();
 if (CR.ConstRange.isValid())
   Diagnostic << CR.ConstRange;
+
+// Do not propose fixes for virtual function.
+const auto *Method = dyn_cast(Def);
+if (Method && Method->isVirtual())
+  return;
+
 for (auto &Hint : CR.Hints)
   Diagnostic << Hint;
   }


Index: clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
@@ -271,3 +271,17 @@
 
 int **const * n_multiple_ptr();
 int *const & n_pointer_ref();
+
+class PVBase {
+public:
+  virtual const int getC() = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-qualified at the top level, which may reduce code readability without improving const correctness
+  // CHECK-NOT-FIXES: virtual int getC() = 0;
+};
+
+class PVDerive : public PVBase {
+public:
+  const int getC() { return 1; }
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-qualified at the top level, which may reduce code readability without improving const correctness
+  // CHECK-NOT-FIXES: int getC() { return 1; }
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,6 +112,10 @@
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is referenced by an lvalue
 
+- Fixed a crash in :doc:`readability-const-return-type
+  ` when a pure virtual function
+  overrided has a const return type. Removed the fix for a virtual function.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -97,7 +97,9

[clang-tools-extra] ba54ebe - [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

2022-03-01 Thread via cfe-commits

Author: Sockke
Date: 2022-03-01T20:55:28+08:00
New Revision: ba54ebeb5eba0f63de8ce2d73a85e9bf508008f6

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

LOG: [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

It cannot match a `pure virtual function`. This patch fixes this behavior.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
index 1647cb1f4c940..814d3f266c5c3 100644
--- a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -97,7 +97,9 @@ void ConstReturnTypeCheck::registerMatchers(MatchFinder 
*Finder) {
   // Find all function definitions for which the return types are `const`
   // qualified.
   Finder->addMatcher(
-  functionDecl(returns(isConstQualified()), isDefinition()).bind("func"),
+  functionDecl(returns(isConstQualified()),
+   anyOf(isDefinition(), cxxMethodDecl(isPure(
+  .bind("func"),
   this);
 }
 
@@ -115,6 +117,12 @@ void ConstReturnTypeCheck::check(const 
MatchFinder::MatchResult &Result) {
 << Def->getReturnType();
 if (CR.ConstRange.isValid())
   Diagnostic << CR.ConstRange;
+
+// Do not propose fixes for virtual function.
+const auto *Method = dyn_cast(Def);
+if (Method && Method->isVirtual())
+  return;
+
 for (auto &Hint : CR.Hints)
   Diagnostic << Hint;
   }

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 103f337bb5cd1..551e36dea0937 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,6 +112,10 @@ Changes in existing checks
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is 
referenced by an lvalue
 
+- Fixed a crash in :doc:`readability-const-return-type
+  ` when a pure virtual 
function
+  overrided has a const return type. Removed the fix for a virtual function.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
index f801b18a98b87..70da965275650 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-const-return-type.cpp
@@ -271,3 +271,17 @@ const int n14();
 
 int **const * n_multiple_ptr();
 int *const & n_pointer_ref();
+
+class PVBase {
+public:
+  virtual const int getC() = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: virtual int getC() = 0;
+};
+
+class PVDerive : public PVBase {
+public:
+  const int getC() { return 1; }
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 
'const'-qualified at the top level, which may reduce code readability without 
improving const correctness
+  // CHECK-NOT-FIXES: int getC() { return 1; }
+};



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


[PATCH] D120369: [analyzer] Add more propagations to Taint analysis

2022-03-01 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a reviewer: NoQ.
steakhal added a comment.
This revision is now accepted and ready to land.

Looks good to me. Check the docs if they are still in sync.
Also, postpone this for two days to let others block this if they have 
objections.
Other than that, land it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120369

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


[PATCH] D114413: [OpenMPIRBuilder] Implement static-chunked workshare-loop schedules.

2022-03-01 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added inline comments.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:1505
+  /// valid in the condition block (i.e., defined in the preheader) and is
+  /// interpreted as an unsigned integer.
+  void setTripCount(Value *TripCount);

peixin wrote:
> Nit: integer -> 64-bit integer?
not necessarily, we do not require a specific integer size. For instance, 
`__kmpc_for_static_init_4u` takes a 32-bit integer. It is up to the applyXYZ 
function to zext/trunc it when necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114413

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


[PATCH] D120720: [clang][AVR] Implement standard calling convention for AVR and AVRTiny

2022-03-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 created this revision.
benshi001 added reviewers: aykevl, dylanmckay.
Herald added a subscriber: Jim.
benshi001 requested review of this revision.
Herald added subscribers: cfe-commits, jacquesguan.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120720

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/lib/Basic/Targets/AVR.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/avr/argument.c

Index: clang/test/CodeGen/avr/argument.c
===
--- /dev/null
+++ clang/test/CodeGen/avr/argument.c
@@ -0,0 +1,60 @@
+// RUN: %clang_cc1 -triple avr -target-cpu atmega328 -emit-llvm %s -o - \
+// RUN: | FileCheck %s --check-prefix AVR
+// RUN: %clang_cc1 -triple avr -target-cpu attiny40 -emit-llvm %s -o - \
+// RUN: | FileCheck %s --check-prefix TINY
+
+// NOTE: All arguments are passed in memory for functions with variable arguments.
+// AVR:  define {{.*}} i8 @foo0(i8 {{.*}}, i8 {{.*}}, ...)
+// TINY: define {{.*}} i8 @foo0(i8 {{.*}}, i8 {{.*}}, ...)
+// AVR-NOT:  define {{.*}} i8 @foo0(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}}, ...)
+// TINY-NOT: define {{.*}} i8 @foo0(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}}, ...)
+char foo0(char a, char b, ...) {
+  return a + b;
+}
+
+// NOTE: All arguments are passed via registers.
+// AVR:  define {{.*}} i8 @foo1(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} i8 @foo1(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}})
+char foo1(char a, char b) {
+  return a + b;
+}
+
+// NOTE: The char type argument is passed via registers on both avr and avrtiny.
+// AVR:  define {{.*}} @foo2({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} @foo2({{.*}}, i8 {{.*}} signext {{.*}})
+struct s07 {
+  char arr[7];
+};
+struct s06 {
+  char arr[6];
+};
+struct s07 foo2(struct s06 s6, char a) {
+  struct s07 s7;
+  s7.arr[a] = s6.arr[a];
+  return s7;
+}
+
+// NOTE: The char type argument is passed via registers on avr but via stack on avrtiny.
+// AVR:  define {{.*}} @foo3({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} @foo3({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} @foo3({{.*}}, i8 {{.*}})
+struct s09 {
+  char arr[9];
+};
+struct s09 foo3(struct s06 s6, char a) {
+  struct s09 s9;
+  s9.arr[a] = s6.arr[a];
+  return s9;
+}
+
+// NOTE: The char type argument is passed via stack on both avr and avrtiny.
+// AVR:  define {{.*}} @foo4({{.*}}, i8 {{.*}})
+// TINY: define {{.*}} @foo4({{.*}}, i8 {{.*}})
+// AVR-NOT:  define {{.*}} @foo4({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} @foo4({{.*}}, i8 {{.*}} signext {{.*}})
+struct s17 {
+  char arr[17];
+};
+char foo4(struct s17 s, char c) {
+  return s.arr[c];
+}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -19,9 +19,9 @@
 #include "CodeGenFunction.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/RecordLayout.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/DiagnosticFrontend.h"
-#include "clang/Basic/Builtins.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/CodeGen/SwiftCallingConv.h"
 #include "llvm/ADT/SmallBitVector.h"
@@ -33,6 +33,7 @@
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsS390.h"
 #include "llvm/IR/Type.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include  // std::sort
 
@@ -8272,32 +8273,83 @@
 
 namespace {
 class AVRABIInfo : public DefaultABIInfo {
+private:
+  // The total amount of registers can be used to pass parameters. It is 18 on
+  // AVR, or 8 on AVRTiny.
+  mutable unsigned ParamRegs;
+
 public:
-  AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
+  AVRABIInfo(CodeGenTypes &CGT, unsigned N)
+  : DefaultABIInfo(CGT), ParamRegs(N) {}
 
   ABIArgInfo classifyReturnType(QualType Ty) const {
-// A return struct with size less than or equal to 8 bytes is returned
-// directly via registers R18-R25.
-if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
+if (isAggregateTypeForABI(Ty)) {
+  // A return struct with size less than or equal to 8 bytes is returned
+  // directly via registers R18-R25.
+  if (getContext().getTypeSize(Ty) <= 64)
+return ABIArgInfo::getDirect();
+  // A return struct with size larger than 8 bytes is returned via a stack
+  // slot, along with a pointer to it as the function's implicit argument.
+  ParamRegs -= 2;
+  return getNaturalAlignIndirect(Ty);
+}
+// Otherwise we follow the default way which is compatible.
+return DefaultABIInfo::classifyReturnType(Ty);
+  }
+
+  ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const {
+unsigned TySize = getContext().getTypeSize(Ty);
+
+// An 

[PATCH] D120697: [clang-offload-bundler] HIP and OpenMP comaptibility for linking heterogeneous archive library

2022-03-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl 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/D120697/new/

https://reviews.llvm.org/D120697

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


[PATCH] D117887: [NVPTX] Expose float tys min, max, abs, neg as builtins

2022-03-01 Thread Jakub Chlanda via Phabricator via cfe-commits
jchlanda marked an inline comment as done.
jchlanda added a comment.

@tra thank you for landing the patches, it seems that the clang part (builtin 
declarations and tests) have been dropped, only `llvm` dir changes made it 
through. Is there any way I could fix it (same goes for the other two patches 
in this stack)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117887

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


[PATCH] D120723: [pseudo] Fix an out-of-bound error in LRTable::find.

2022-03-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
hokein requested review of this revision.
Herald added a project: clang.

The linear scan should not escape the TargetedStates range.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120723

Files:
  clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
  clang/test/Syntax/lr-build-basic.test


Index: clang/test/Syntax/lr-build-basic.test
===
--- clang/test/Syntax/lr-build-basic.test
+++ clang/test/Syntax/lr-build-basic.test
@@ -1,24 +1,29 @@
 _ := expr
-expr := IDENTIFIER
+expr := id
+id := IDENTIFIER
 
 # RUN: clang-pseudo -grammar %s -print-graph | FileCheck %s 
--check-prefix=GRAPH
 #  GRAPH: States:
 # GRPAH-NEXT: State 0
 # GRPAH-NEXT: _ :=  • expr
-# GRPAH-NEXT: expr :=  • IDENTIFIER
+# GRPAH-NEXT: expr :=  • id
+# GRPAH-NEXT: id :=  • IDENTIFIER
 # GRPAH-NEXT: State 1
 # GRPAH-NEXT: _ := expr • 
 # GRPAH-NEXT: State 2
-# GRPAH-NEXT: expr := IDENTIFIER • 
-# GRPAH-NEXT: 0 ->[expr] 1
-# GRPAH-NEXT: 0 ->[IDENTIFIER] 2
+# GRPAH-NEXT: expr := id • 
+# GRPAH-NEXT: State 3
+# GRPAH-NEXT: id := IDENTIFIER • 
 
 # RUN: clang-pseudo -grammar %s -print-table | FileCheck %s 
--check-prefix=TABLE
 #  TABLE: LRTable:
 # TABLE-NEXT: State 0
-# TABLE-NEXT: 'IDENTIFIER': shift state 2
+# TABLE-NEXT: 'IDENTIFIER': shift state 3
 # TABLE-NEXT: 'expr': go to state 1
+# TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
 # TABLE-NEXT: 'EOF': accept
 # TABLE-NEXT: State 2
-# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
+# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
+# TABLE-NEXT: State 3
+# TABLE-NEXT: 'EOF': reduce by rule 2 'id := IDENTIFIER'
Index: clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
===
--- clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -110,14 +110,15 @@
 
   assert(llvm::is_sorted(TargetedStates) &&
  "subrange of the StateIdx should be sorted!");
-  const LRTable::StateID *It = llvm::partition_point(
+  const LRTable::StateID *Start = llvm::partition_point(
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
+  if (Start == TargetedStates.end())
 return {};
-  size_t Start = It - States.data(), End = Start;
-  while (End < States.size() && States[End] == Src)
+  const LRTable::StateID *End = Start;
+  while (End != TargetedStates.end() && *End == Src)
 ++End;
-  return llvm::makeArrayRef(&Actions[Start], End - Start);
+  return llvm::makeArrayRef(&Actions[Start - States.data()],
+/*length=*/End - Start);
 }
 
 } // namespace pseudo


Index: clang/test/Syntax/lr-build-basic.test
===
--- clang/test/Syntax/lr-build-basic.test
+++ clang/test/Syntax/lr-build-basic.test
@@ -1,24 +1,29 @@
 _ := expr
-expr := IDENTIFIER
+expr := id
+id := IDENTIFIER
 
 # RUN: clang-pseudo -grammar %s -print-graph | FileCheck %s --check-prefix=GRAPH
 #  GRAPH: States:
 # GRPAH-NEXT: State 0
 # GRPAH-NEXT: _ :=  • expr
-# GRPAH-NEXT: expr :=  • IDENTIFIER
+# GRPAH-NEXT: expr :=  • id
+# GRPAH-NEXT: id :=  • IDENTIFIER
 # GRPAH-NEXT: State 1
 # GRPAH-NEXT: _ := expr • 
 # GRPAH-NEXT: State 2
-# GRPAH-NEXT: expr := IDENTIFIER • 
-# GRPAH-NEXT: 0 ->[expr] 1
-# GRPAH-NEXT: 0 ->[IDENTIFIER] 2
+# GRPAH-NEXT: expr := id • 
+# GRPAH-NEXT: State 3
+# GRPAH-NEXT: id := IDENTIFIER • 
 
 # RUN: clang-pseudo -grammar %s -print-table | FileCheck %s --check-prefix=TABLE
 #  TABLE: LRTable:
 # TABLE-NEXT: State 0
-# TABLE-NEXT: 'IDENTIFIER': shift state 2
+# TABLE-NEXT: 'IDENTIFIER': shift state 3
 # TABLE-NEXT: 'expr': go to state 1
+# TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
 # TABLE-NEXT: 'EOF': accept
 # TABLE-NEXT: State 2
-# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
+# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
+# TABLE-NEXT: State 3
+# TABLE-NEXT: 'EOF': reduce by rule 2 'id := IDENTIFIER'
Index: clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
===
--- clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -110,14 +110,15 @@
 
   assert(llvm::is_sorted(TargetedStates) &&
  "subrange of the StateIdx should be sorted!");
-  const LRTable::StateID *It = llvm::partition_point(
+  const LRTable::StateID *Start = llvm::partition_point(
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
+  if (Start == TargetedStates.end())
 return {};
-  size_t Start = It - States.data(), End = Start;
-  while (End < States.size() && States[End] == Src)
+  const LRTable::StateID *En

[PATCH] D120723: [pseudo] Fix an out-of-bound error in LRTable::find.

2022-03-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp:115
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
+  if (Start == TargetedStates.end())
 return {};

I think this check is no longer needed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120723

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


[PATCH] D120724: [pseudo] Add a print-grammar option in the tool

2022-03-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
hokein requested review of this revision.
Herald added a project: clang.

This is helpful for debugging purposes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120724

Files:
  clang/tools/clang-pseudo/ClangPseudo.cpp


Index: clang/tools/clang-pseudo/ClangPseudo.cpp
===
--- clang/tools/clang-pseudo/ClangPseudo.cpp
+++ clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -24,6 +24,7 @@
 
 static opt
 Grammar("grammar", desc("Parse and check a BNF grammar file."), init(""));
+static opt PrintGrammar("print-grammar", desc("Print the grammar."));
 static opt PrintGraph("print-graph",
 desc("Print the LR graph for the grammar"));
 static opt PrintTable("print-table",
@@ -60,6 +61,8 @@
 }
 llvm::outs() << llvm::formatv("grammar file {0} is parsed successfully\n",
   Grammar);
+if (PrintGrammar)
+  llvm::outs() << G->dump();
 if (PrintGraph)
   llvm::outs() << 
clang::syntax::pseudo::LRGraph::buildLR0(*G).dumpForTests(
   *G);


Index: clang/tools/clang-pseudo/ClangPseudo.cpp
===
--- clang/tools/clang-pseudo/ClangPseudo.cpp
+++ clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -24,6 +24,7 @@
 
 static opt
 Grammar("grammar", desc("Parse and check a BNF grammar file."), init(""));
+static opt PrintGrammar("print-grammar", desc("Print the grammar."));
 static opt PrintGraph("print-graph",
 desc("Print the LR graph for the grammar"));
 static opt PrintTable("print-table",
@@ -60,6 +61,8 @@
 }
 llvm::outs() << llvm::formatv("grammar file {0} is parsed successfully\n",
   Grammar);
+if (PrintGrammar)
+  llvm::outs() << G->dump();
 if (PrintGraph)
   llvm::outs() << clang::syntax::pseudo::LRGraph::buildLR0(*G).dumpForTests(
   *G);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120159: [Clang] Implement __builtin_source_location.

2022-03-01 Thread James Y Knight via Phabricator via cfe-commits
jyknight updated this revision to Diff 412087.
jyknight marked an inline comment as done.
jyknight added a comment.

Fix and test __impl lookup within the definition of std::source_location.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120159

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/DeclNodes.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprClassification.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CodeGenCXX/builtin-source-location.cpp
  clang/test/SemaCXX/source_location.cpp
  clang/test/SemaCXX/source_location_err.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -6466,6 +6466,7 @@
   case Decl::Binding:
   case Decl::MSProperty:
   case Decl::MSGuid:
+  case Decl::UnnamedGlobalConstant:
   case Decl::TemplateParamObject:
   case Decl::IndirectField:
   case Decl::ObjCIvar:
Index: clang/test/SemaCXX/source_location_err.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/source_location_err.cpp
@@ -0,0 +1,105 @@
+// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify -DTEST=1 %s
+// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify -DTEST=2 %s
+// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify -DTEST=3 %s
+// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify -DTEST=4 %s
+// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify -DTEST=5 %s
+
+#if TEST == 1
+auto test1a = __builtin_source_location(); // expected-error {{'std::source_location::__impl' was not found}}
+
+namespace std {
+inline namespace NS {
+  struct source_location;
+}
+}
+
+auto test1b = __builtin_source_location(); // expected-error {{'std::source_location::__impl' was not found}}
+
+namespace std {
+inline namespace NS {
+  struct source_location {
+struct __impl;
+  };
+}
+}
+auto test1c = __builtin_source_location(); // expected-error {{'std::source_location::__impl' was not found}}
+
+#elif TEST == 2
+auto test2a = __builtin_source_location(); // expected-error {{'std::source_location::__impl' was not found}}
+
+namespace std {
+inline namespace NS {
+struct source_location {
+  struct __impl { int x; };
+};
+}
+}
+auto test2b = __builtin_source_location(); // expected-error {{'std::source_location::__impl' must be standard-layout and have only two 'const char *' fields '_M_file_name' and '_M_function_name', and two integral fields '_M_line' and '_M_column'}}
+
+#elif TEST == 3
+namespace std {
+struct source_location {
+  struct __impl {
+int other_member;
+char _M_line;
+const char *_M_file_name;
+char _M_column;
+const char *_M_function_name;
+  };
+};
+}
+auto test3 = __builtin_source_location(); // expected-error {{'std::source_location::__impl' must be standard-layout and have only two 'const char *' fields '_M_file_name' and '_M_function_name', and two integral fields '_M_line' and '_M_column'}}
+
+#elif TEST == 4
+namespace std {
+struct source_location {
+  struct parent {};
+  struct __impl : public parent {
+char _M_line;
+const char *_M_file_name;
+char _M_column;
+const char *_M_function_name;
+  };
+};
+}
+auto test4 = __builtin_source_location(); // expected-error {{'std::source_location::__impl' must be standard-layout and have only two 'const char *' fields '_M_file_name' and '_M_function_name', and two integral fields '_M_line' and '_M_column'}}
+
+
+#elif TEST == 5
+namespace std {
+struct source_location {
+  struct __impl {
+signed char _M_line; // odd integral type to choose, but ok!
+const char *_M_file_name;
+signed char _M_column;
+const char *_M_function_name;
+static int other_member; // static members are OK
+  };
+  using BuiltinT = decltype(__builtin_sou

[clang] 8f4ea36 - [clang] Improve laziness of resolving module map headers.

2022-03-01 Thread Adam Czachorowski via cfe-commits

Author: Adam Czachorowski
Date: 2022-03-01T15:56:23+01:00
New Revision: 8f4ea36bfe4caf7d08f9778ee2a347b78f02bc0f

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

LOG: [clang] Improve laziness of resolving module map headers.

clang has support for lazy headers in module maps - if size and/or
modtime and provided in the cppmap file, headers are only resolved when
an include directive for a file with that size/modtime is encoutered.

Before this change, the lazy resolution was all-or-nothing per module.
That means as soon as even one file in that module potentially matched
an include, all lazy files in that module were resolved. With this
change, only files with matching size/modtime will be resolved.

The goal is to avoid unnecessary stat() calls on non-included files,
which is especially valuable on networked file systems, with higher
latency.

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

Added: 


Modified: 
clang/include/clang/Lex/ModuleMap.h
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Lex/ModuleMap.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/ModuleMap.h 
b/clang/include/clang/Lex/ModuleMap.h
index 26169ae9cee95..538dcc7c4bec1 100644
--- a/clang/include/clang/Lex/ModuleMap.h
+++ b/clang/include/clang/Lex/ModuleMap.h
@@ -456,8 +456,11 @@ class ModuleMap {
   /// is effectively internal, but is exposed so HeaderSearch can call it.
   void resolveHeaderDirectives(const FileEntry *File) const;
 
-  /// Resolve all lazy header directives for the specified module.
-  void resolveHeaderDirectives(Module *Mod) const;
+  /// Resolve lazy header directives for the specified module. If File is
+  /// provided, only headers with same size and modtime are resolved. If File
+  /// is not set, all headers are resolved.
+  void resolveHeaderDirectives(Module *Mod,
+   llvm::Optional File) const;
 
   /// Reports errors if a module must not include a specific file.
   ///

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index c5b9e80356db4..b8f92381613a3 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -331,7 +331,7 @@ static std::error_code collectModuleHeaderIncludes(
 return std::error_code();
 
   // Resolve all lazy header directives to header files.
-  ModMap.resolveHeaderDirectives(Module);
+  ModMap.resolveHeaderDirectives(Module, /*File=*/llvm::None);
 
   // If any headers are missing, we can't build this module. In most cases,
   // diagnostics for this should have already been produced; we only get here

diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 0b136aeb580fe..824b2bb192909 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -482,7 +482,7 @@ void ModuleMap::diagnoseHeaderInclusion(Module 
*RequestingModule,
 
   if (RequestingModule) {
 resolveUses(RequestingModule, /*Complain=*/false);
-resolveHeaderDirectives(RequestingModule);
+resolveHeaderDirectives(RequestingModule, /*File=*/llvm::None);
   }
 
   bool Excluded = false;
@@ -1191,25 +1191,35 @@ void ModuleMap::resolveHeaderDirectives(const FileEntry 
*File) const {
   auto BySize = LazyHeadersBySize.find(File->getSize());
   if (BySize != LazyHeadersBySize.end()) {
 for (auto *M : BySize->second)
-  resolveHeaderDirectives(M);
+  resolveHeaderDirectives(M, File);
 LazyHeadersBySize.erase(BySize);
   }
 
   auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
   if (ByModTime != LazyHeadersByModTime.end()) {
 for (auto *M : ByModTime->second)
-  resolveHeaderDirectives(M);
+  resolveHeaderDirectives(M, File);
 LazyHeadersByModTime.erase(ByModTime);
   }
 }
 
-void ModuleMap::resolveHeaderDirectives(Module *Mod) const {
+void ModuleMap::resolveHeaderDirectives(
+Module *Mod, llvm::Optional File) const {
   bool NeedsFramework = false;
-  for (auto &Header : Mod->UnresolvedHeaders)
-// This operation is logically const; we're just changing how we represent
-// the header information for this file.
-const_cast(this)->resolveHeader(Mod, Header, NeedsFramework);
-  Mod->UnresolvedHeaders.clear();
+  SmallVector NewHeaders;
+  const auto Size = File ? File.getValue()->getSize() : 0;
+  const auto ModTime = File ? File.getValue()->getModificationTime() : 0;
+
+  for (auto &Header : Mod->UnresolvedHeaders) {
+if (File && ((Header.ModTime && Header.ModTime != ModTime) ||
+ (Header.Size && Header.Size != Size)))
+  NewHeaders.push_back(Header);
+else
+  // This operation is logically const; we're just changing how we 
represent
+  // the header information for

[PATCH] D120569: [clang] Improve laziness of resolving module map headers.

2022-03-01 Thread Adam Czachorowski 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 rG8f4ea36bfe4c: [clang] Improve laziness of resolving module 
map headers. (authored by adamcz).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120569

Files:
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1879,7 +1879,7 @@
   // headers list when emitting resolved headers in the first loop below.
   // FIXME: It'd be preferable to avoid doing this if we were given
   // sufficient stat information in the module map.
-  HS.getModuleMap().resolveHeaderDirectives(M);
+  HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/llvm::None);
 
   // If the file didn't exist, we can still create a module if we were given
   // enough information in the module map.
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -482,7 +482,7 @@
 
   if (RequestingModule) {
 resolveUses(RequestingModule, /*Complain=*/false);
-resolveHeaderDirectives(RequestingModule);
+resolveHeaderDirectives(RequestingModule, /*File=*/llvm::None);
   }
 
   bool Excluded = false;
@@ -1191,25 +1191,35 @@
   auto BySize = LazyHeadersBySize.find(File->getSize());
   if (BySize != LazyHeadersBySize.end()) {
 for (auto *M : BySize->second)
-  resolveHeaderDirectives(M);
+  resolveHeaderDirectives(M, File);
 LazyHeadersBySize.erase(BySize);
   }
 
   auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
   if (ByModTime != LazyHeadersByModTime.end()) {
 for (auto *M : ByModTime->second)
-  resolveHeaderDirectives(M);
+  resolveHeaderDirectives(M, File);
 LazyHeadersByModTime.erase(ByModTime);
   }
 }
 
-void ModuleMap::resolveHeaderDirectives(Module *Mod) const {
+void ModuleMap::resolveHeaderDirectives(
+Module *Mod, llvm::Optional File) const {
   bool NeedsFramework = false;
-  for (auto &Header : Mod->UnresolvedHeaders)
-// This operation is logically const; we're just changing how we represent
-// the header information for this file.
-const_cast(this)->resolveHeader(Mod, Header, NeedsFramework);
-  Mod->UnresolvedHeaders.clear();
+  SmallVector NewHeaders;
+  const auto Size = File ? File.getValue()->getSize() : 0;
+  const auto ModTime = File ? File.getValue()->getModificationTime() : 0;
+
+  for (auto &Header : Mod->UnresolvedHeaders) {
+if (File && ((Header.ModTime && Header.ModTime != ModTime) ||
+ (Header.Size && Header.Size != Size)))
+  NewHeaders.push_back(Header);
+else
+  // This operation is logically const; we're just changing how we represent
+  // the header information for this file.
+  const_cast(this)->resolveHeader(Mod, Header, NeedsFramework);
+  }
+  Mod->UnresolvedHeaders.swap(NewHeaders);
 }
 
 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -331,7 +331,7 @@
 return std::error_code();
 
   // Resolve all lazy header directives to header files.
-  ModMap.resolveHeaderDirectives(Module);
+  ModMap.resolveHeaderDirectives(Module, /*File=*/llvm::None);
 
   // If any headers are missing, we can't build this module. In most cases,
   // diagnostics for this should have already been produced; we only get here
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -456,8 +456,11 @@
   /// is effectively internal, but is exposed so HeaderSearch can call it.
   void resolveHeaderDirectives(const FileEntry *File) const;
 
-  /// Resolve all lazy header directives for the specified module.
-  void resolveHeaderDirectives(Module *Mod) const;
+  /// Resolve lazy header directives for the specified module. If File is
+  /// provided, only headers with same size and modtime are resolved. If File
+  /// is not set, all headers are resolved.
+  void resolveHeaderDirectives(Module *Mod,
+   llvm::Optional File) const;
 
   /// Reports errors if a module must not include a specific file.
   ///
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120727: [libc++] Overhaul how we select the ABI library

2022-03-01 Thread Louis Dionne via Phabricator via cfe-commits
ldionne created this revision.
Herald added a subscriber: arichardson.
ldionne requested review of this revision.
Herald added projects: clang, libc++.
Herald added subscribers: libcxx-commits, cfe-commits.
Herald added a reviewer: libc++.

This patch overhauls how we pick up the ABI library. Instead of setting
ad-hoc flags, it creates interface targets that can be linked against by
the rest of the build, which is easier to follow and extend to support
new ABI libraries. It also adds a new ABI library called "system-libcxxabi",
which represents linking against a LLVM libc++abi already installed on the
system, and solves existing issues when trying to build against a system
libc++abi outside of the now-unsupported standalone build.

This is intended to be a NFC change, however there are some additional
simplifications and improvements we can make in the future that would
require a slight behavior change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120727

Files:
  clang/cmake/caches/CrossWinToARMLinux.cmake
  libcxx/CMakeLists.txt
  libcxx/cmake/Modules/HandleLibCXXABI.cmake
  libcxx/docs/BuildingLibcxx.rst
  libcxx/include/CMakeLists.txt
  libcxx/lib/abi/CMakeLists.txt
  libcxx/src/CMakeLists.txt
  libcxx/test/CMakeLists.txt
  libcxx/test/configs/legacy.cfg.in
  libcxx/utils/libcxx/test/config.py

Index: libcxx/utils/libcxx/test/config.py
===
--- libcxx/utils/libcxx/test/config.py
+++ libcxx/utils/libcxx/test/config.py
@@ -390,7 +390,7 @@
 self.cxx.link_flags += ['-lstdc++']
 elif cxx_abi == 'libsupc++':
 self.cxx.link_flags += ['-lsupc++']
-elif cxx_abi == 'libcxxabi':
+elif cxx_abi == 'libcxxabi' or 'system-libcxxabi':
 # If the C++ library requires explicitly linking to libc++abi, or
 # if we're testing libc++abi itself (the test configs are shared),
 # then link it.
@@ -417,7 +417,7 @@
 # The compiler normally links in oldnames.lib too, but we've
 # specified -nostdlib above, so we need to specify it manually.
 self.cxx.link_flags += ['-loldnames']
-elif cxx_abi == 'none' or cxx_abi == 'default':
+elif cxx_abi == 'none':
 if self.target_info.is_windows():
 debug_suffix = 'd' if self.debug_build else ''
 self.cxx.link_flags += ['-lmsvcrt%s' % debug_suffix]
Index: libcxx/test/configs/legacy.cfg.in
===
--- libcxx/test/configs/legacy.cfg.in
+++ libcxx/test/configs/legacy.cfg.in
@@ -14,7 +14,7 @@
 config.cxx_library_root = "@LIBCXX_LIBRARY_DIR@"
 config.abi_library_root = "@LIBCXX_CXX_ABI_LIBRARY_PATH@"
 config.enable_shared= @LIBCXX_LINK_TESTS_WITH_SHARED_LIBCXX@
-config.cxx_abi  = "@LIBCXX_CXX_ABI_LIBNAME@"
+config.cxx_abi  = "@LIBCXX_CXXABI_FOR_TESTS@"
 config.configuration_variant= "@LIBCXX_LIT_VARIANT@"
 config.host_triple  = "@LLVM_HOST_TRIPLE@"
 config.sysroot  = "@CMAKE_SYSROOT@"
Index: libcxx/test/CMakeLists.txt
===
--- libcxx/test/CMakeLists.txt
+++ libcxx/test/CMakeLists.txt
@@ -17,7 +17,9 @@
 # The tests shouldn't link to any ABI library when it has been linked into
 # libc++ statically or via a linker script.
 if (LIBCXX_ENABLE_STATIC_ABI_LIBRARY OR LIBCXX_ENABLE_ABI_LINKER_SCRIPT)
-  set(LIBCXX_CXX_ABI_LIBNAME "none")
+  set(LIBCXX_CXXABI_FOR_TESTS "none")
+else()
+  set(LIBCXX_CXXABI_FOR_TESTS "${LIBCXX_CXX_ABI}")
 endif()
 
 # The tests shouldn't link to libunwind if we have a linker script which
Index: libcxx/src/CMakeLists.txt
===
--- libcxx/src/CMakeLists.txt
+++ libcxx/src/CMakeLists.txt
@@ -155,11 +155,6 @@
   set(exclude_from_all EXCLUDE_FROM_ALL)
 endif()
 
-# If LIBCXX_CXX_ABI_LIBRARY_PATH is defined we want to add it to the search path.
-add_link_flags_if(LIBCXX_CXX_ABI_LIBRARY_PATH
-  "${CMAKE_LIBRARY_PATH_FLAG}${LIBCXX_CXX_ABI_LIBRARY_PATH}")
-
-
 if (LIBCXX_GENERATE_COVERAGE AND NOT LIBCXX_COVERAGE_LIBRARY)
   find_compiler_rt_library(profile LIBCXX_COVERAGE_LIBRARY)
 endif()
@@ -196,10 +191,6 @@
 endif()
 
 function(cxx_set_common_defines name)
-  if(LIBCXX_CXX_ABI_HEADER_TARGET)
-add_dependencies(${name} ${LIBCXX_CXX_ABI_HEADER_TARGET})
-  endif()
-
   if (LIBCXX_ENABLE_PARALLEL_ALGORITHMS)
 target_link_libraries(${name} PUBLIC pstl::ParallelSTL)
   endif()
@@ -240,19 +231,18 @@
   # Link against libc++abi
   if (LIBCXX_STATICALLY_LINK_ABI_IN_SHARED_LIBRARY)
 if (APPLE)
-  target_link_libraries(cxx_shared PRIVATE "-Wl,-force_load" "${LIBCXX_CXX_STATIC_ABI_LIBRARY}")
+  target_link_libraries(cxx_shared PRIVATE "-Wl,-force_load" "$")
 else()
-  target_link_libraries(cxx_shared PRIVATE "-Wl,--whol

[PATCH] D119949: [Clang-tidy] Check the existence of ElaboratedType's qualifiers

2022-03-01 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood accepted this revision.
LegalizeAdulthood added a comment.
This revision is now accepted and ready to land.

Fix one nit and ship




Comment at: 
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp:74
+  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  BaseExpr->getType()->isTypedefNameType() ? false : true;
+

Simplify to `!BaseExpr->getType()->isTypedefNameType();`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119949

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


[PATCH] D120132: [HIP] Fix HIP include path

2022-03-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D120132#3350020 , @tra wrote:

> In D120132#3349936 , @yaxunl wrote:
>
>> Users may use clang driver to compile HIP program and C++ program with one 
>> clang driver invocation, e.g.
>>
>>   clang --offload-arch=gfx906 a.hip b.cpp
>>
>> Clang driver will create job actions for a.hip and b.cpp separately. The job 
>> actions for a.hip have HIP offload kind. The job actions for b.cpp have 
>> 'none' offload kind.
>>
>> Only job actions having HIP offload kind should have HIP include paths, 
>> otherwise, even if clang driver is used for compiling one single C++ 
>> program, it will add HIP include path.
>
> Are you saying that clang driver would pick HIP toolchain for the C++ 
> compilation? It does not make sense. It that were the case we would be 
> risking picking up C++ toolchain for the HIP compilation, too and that would 
> obviously not work at all.
>
> AFAICT, clang certainly does not add CUDA include paths to C++ compilations 
> passed to the top-level invocation. I believe this should work for HIP, too. 
> Search for cuda-11.5 below:
>
>   # bin/clang++ --cuda-path=$HOME/local/cuda-11.5.0 -### -c a.cu b.cc
>   
>   clang version 15.0.0
>   Target: x86_64-unknown-linux-gnu
>   Thread model: posix
>   InstalledDir: /usr/local/home/tra/work/llvm/build/release+assert+zapcc/bin
>"/usr/local/home/tra/work/llvm/build/release+assert+zapcc/bin/clang-15" 
> "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" 
> "x86_64-unknown-linux-gnu" "-S" "-disable-free" "-clear-ast-before-backend" 
> "-main-file-name" "a.cu" "-mrelocation-model" "static" "-mframe-pointer=all" 
> "-fno-rounding-math" "-fno-verbose-asm" "-no-integrated-as" "-aux-target-cpu" 
> "x86-64" "-fcuda-is-device" "-mllvm" "-enable-memcpyopt-without-libcalls" 
> "-mlink-builtin-bitcode" 
> "/usr/local/home/tra/local/cuda-11.5.0/nvvm/libdevice/libdevice.10.bc" 
> "-target-feature" "+ptx75" "-target-sdk-version=11.5" "-target-cpu" "sm_35" 
> "-mllvm" "-treat-scalable-fixed-error-as-warning" "-debugger-tuning=gdb" 
> "-fno-dwarf-directory-asm" "-resource-dir" 
> "/usr/local/home/tra/work/llvm/build/release+assert+zapcc/lib/clang/15.0.0" 
> "-internal-isystem" 
> "/usr/local/home/tra/work/llvm/build/release+assert+zapcc/lib/clang/15.0.0/include/cuda_wrappers"
>  "-include" "__clang_cuda_runtime_wrapper.h" "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11" 
> "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11"
>  "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/backward" 
> "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11" 
> "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11"
>  "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/backward" 
> "-internal-isystem" 
> "/usr/local/home/tra/work/llvm/build/release+assert+zapcc/lib/clang/15.0.0/include"
>  "-internal-isystem" "/usr/local/include" "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" 
> "-internal-externc-isystem" "/usr/include/x86_64-linux-gnu" 
> "-internal-externc-isystem" "/include" "-internal-externc-isystem" 
> "/usr/include" "-internal-isystem" 
> "/usr/local/home/tra/local/cuda-11.5.0/include" "-internal-isystem" 
> "/usr/local/home/tra/work/llvm/build/release+assert+zapcc/lib/clang/15.0.0/include"
>  "-internal-isystem" "/usr/local/include" "-internal-isystem" 
> "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" 
> "-internal-externc-isystem" "/usr/include/x86_64-linux-gnu" 
> "-internal-externc-isystem" "/include" "-internal-externc-isystem" 
> "/usr/include" "-fdeprecated-macro" "-fno-autolink" 
> "-fdebug-compilation-dir=/usr/local/home/tra/work/llvm/build/release+assert+zapcc"
>  "-ferror-limit" "19" "-fgnuc-version=4.2.1" "-fcxx-exceptions" 
> "-fexceptions" "-fcolor-diagnostics" "-cuid=fce3a17633fb941f" 
> "-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o" "/tmp/a-8486d3/a-sm_35.s" "-x" "cuda" 
> "a.cu"
>"/usr/local/home/tra/local/cuda-11.5.0/bin/ptxas" "-m64" "-O0" 
> "--gpu-name" "sm_35" "--output-file" "/tmp/a-7c357d/a-sm_35.o" 
> "/tmp/a-8486d3/a-sm_35.s"
>"/usr/local/home/tra/local/cuda-11.5.0/bin/fatbinary" "-64" "--create" 
> "/tmp/a-c46038.fatbin" "--image=profile=sm_35,file=/tmp/a-7c357d/a-sm_35.o" 
> "--image=profile=compute_35,file=/tmp/a-8486d3/a-sm_35.s"
>"/usr/local/home/tra/work/llvm/build/release+assert+zapcc/bin/clang-15" 
> "-cc1" "-triple" "x86_64-unknown-linux-gnu" "-target-sdk-version=11.5" 
> "-aux-triple" "nvptx64-nvidia-cuda" "-emit-obj" "-mrelax-all" 
> "--mrelax-relocations" "-disable-free" "-clear-ast-before-backend" 
> "-main-file-name" "a.cu" "-mrelocation-model" "static" "-mframe-pointer=all" 
> "-fmath-errno" "-ffp-contract=on" "-fno-roundin

[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk added a comment.

In D120712#3351014 , @MyDeveloperDay 
wrote:

> I'm not quite sure how I feel about adding functionality that doesn't 
> actually do anything.

I hear you. My reasoning was that I'm going to introduce an explicit enum value 
sometime soon and when I have that value and this patch in one together with 
the added logic it would be harder to review. Whereas with my upcoming changes 
I'm simply updating the `clang/docs/ClangFormatStyleOptions.rst` by 
regenerating it with this script and you can just approve it. Essentially I 
want to make the review process as easy as it could be.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D120729: Promote addInstantiatedParametersToScope to a private Sema function

2022-03-01 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added a reviewer: aaron.ballman.
erichkeane requested review of this revision.

This is used a few places in SemaTeplateInstantiateDecl, but is going
to be useful in SemaConcept.cpp as well. This patch switches it to be
a private function in Sema.


https://reviews.llvm.org/D120729

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4377,10 +4377,10 @@
 /// Introduce the instantiated function parameters into the local
 /// instantiation scope, and set the parameter names to those used
 /// in the template.
-static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
- const FunctionDecl *PatternDecl,
- LocalInstantiationScope &Scope,
-   const MultiLevelTemplateArgumentList &TemplateArgs) {
+bool Sema::addInstantiatedParametersToScope(
+FunctionDecl *Function, const FunctionDecl *PatternDecl,
+LocalInstantiationScope &Scope,
+const MultiLevelTemplateArgumentList &TemplateArgs) {
   unsigned FParamIdx = 0;
   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
@@ -4396,9 +4396,9 @@
   // it's instantiation-dependent.
   // FIXME: Updating the type to work around this is at best fragile.
   if (!PatternDecl->getType()->isDependentType()) {
-QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
- FunctionParam->getLocation(),
- FunctionParam->getDeclName());
+QualType T = SubstType(PatternParam->getType(), TemplateArgs,
+   FunctionParam->getLocation(),
+   FunctionParam->getDeclName());
 if (T.isNull())
   return true;
 FunctionParam->setType(T);
@@ -4411,8 +4411,8 @@
 
 // Expand the parameter pack.
 Scope.MakeInstantiatedLocalArgPack(PatternParam);
-Optional NumArgumentsInExpansion
-  = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
+Optional NumArgumentsInExpansion =
+getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
 if (NumArgumentsInExpansion) {
   QualType PatternType =
   PatternParam->getType()->castAs()->getPattern();
@@ -4420,10 +4420,10 @@
 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
 FunctionParam->setDeclName(PatternParam->getDeclName());
 if (!PatternDecl->getType()->isDependentType()) {
-  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
-  QualType T = S.SubstType(PatternType, TemplateArgs,
-   FunctionParam->getLocation(),
-   FunctionParam->getDeclName());
+  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
+  QualType T =
+  SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
+FunctionParam->getDeclName());
   if (T.isNull())
 return true;
   FunctionParam->setType(T);
@@ -4487,8 +4487,7 @@
 
 FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
 /*ForDefinition*/ false);
-if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
- TemplateArgs))
+if (addInstantiatedParametersToScope(FD, Pattern, Local, TemplateArgs))
   return true;
 
 runWithSufficientStackSpace(CallLoc, [&] {
@@ -4561,8 +4560,7 @@
   // we don't store enough information to map back to the friend declaration in
   // the template.
   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
-  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
-   TemplateArgs)) {
+  if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
 UpdateExceptionSpec(Decl, EST_None);
 return;
   }
@@ -4603,8 +4601,7 @@
 MultiLevelTemplateArgumentList MLTAL(
 *Decl->getTemplateSpecializationArgs());
 if (addInstantiatedParametersToScope(
-*this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
-Scope, MLTAL))
+Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(), Scope, MLTAL))
   return true;
   }
   Qualifiers ThisQuals;
@@ -5050,7 +5047,7 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
-if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
+if (addInstantiatedParametersToScope(Function, PatternDecl

[PATCH] D115031: [AST] Print NTTP args as string-literals when possible

2022-03-01 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.

Aside from a testing nit, this LGTM!




Comment at: clang/include/clang/Basic/CharInfo.h:199-200
+return "\\t";
+  case '\v':
+return "\\v";
+  }

lichray wrote:
> aaron.ballman wrote:
> > lichray wrote:
> > > aaron.ballman wrote:
> > > > We're also missing `\?` right?
> > > `?` does not seem to need `"escaping?"`
> > It's the only simple escape sequence we're not handling here: 
> > http://eel.is/c++draft/lex.literal#nt:simple-escape-sequence-char
> > 
> > (You need to escape `?` thanks to trigraphs. Consider a string literal like 
> > `"This does what now??!"`.)
> > It's the only simple escape sequence we're not handling here: 
> > http://eel.is/c++draft/lex.literal#nt:simple-escape-sequence-char
> > 
> > (You need to escape `?` thanks to trigraphs. Consider a string literal like 
> > `"This does what now??!"`.)
> 
> Hmm, I think we're safe here
> ```
> ~/devel/llvm-project> ./build/bin/clang++ -fsyntax-only -std=c++14 c.cc
> c.cc:1:50: warning: trigraph converted to '|' character [-Wtrigraphs]
> void foo() { char const s[] = "This does what now??!"; }
>  ^
> 1 warning generated.
> ~/devel/llvm-project> ./build/bin/clang++ -fsyntax-only -std=c++20 c.cc
> c.cc:1:50: warning: trigraph ignored [-Wtrigraphs]
> void foo() { char const s[] = "This does what now??!"; }
>  ^
> 1 warning generated.
> ```
> For these reasons,
> 1. I don't want users to copy diagnosis messages, paste them into a program, 
> and get something different. This has been prevented by the warnings.
> 2. We support trigraph up to C++14, way behind the version (C++20) we can use 
> string literals in NTTP. So it should be mostly fine.
> 3. In C++14 we can use the characters in NTTP, but that one has a different 
> diagnosis:
> 
> ```
> template  class ASCII {};
> 
> void Foo(ASCII<'?'>);
> void Foo(ASCII<'??!'>);
> void test_pascal() {
>   ASCII<'!'> a;
>   Foo(a);
> }
> ```
> 
> ```
> c.cc:4:17: warning: trigraph converted to '|' character [-Wtrigraphs]
> void Foo(ASCII<'??!'>);
> ^
> c.cc:7:3: error: no matching function for call to 'Foo'
>   Foo(a);
>   ^~~
> c.cc:3:6: note: candidate function not viable: no known conversion from 
> 'ASCII<'!' aka 33>' to 'ASCII<'?' aka 63>' for 1st argument
> void Foo(ASCII<'?'>);
>  ^
> c.cc:4:6: note: candidate function not viable: no known conversion from 
> 'ASCII<'!' aka 33>' to 'ASCII<'|' aka 124>' for 1st argument
> void Foo(ASCII<'??!'>);
>  ^
> 1 warning and 1 error generated.
> ```
> Looks nice to me even if we don't escape.
Okay, that sounds reasonable to me, thank you for checking! Can you add a 
trigraph test case so that it's clear we purposefully don't escape the `\?` 
(with some comment to that effect)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115031

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


[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk added inline comments.



Comment at: clang/docs/tools/dump_format_style.py:174-175
 return '* ``%s`` (in configuration: ``%s``)\n%s' % (
-self.name,
-re.sub('.*_', '', self.config),
+self.clean_name,
+self.clean_config,
 doxygen2rst(indent(self.comment, 2)))

MyDeveloperDay wrote:
> Feels like there is repetition here
Are you suggesting to introduce a function `name_only` that looks like this?

```lang=python
def name_only(s: str) -> str:
  return s.split("=", 1)[0].strip()
```

If so, should this be a member function of `EnumValue` or where would you see 
it?

I'm not fond of introducing this function TBH because the name suggest it to be 
very generically usable when in fact it does just a simple thing. If you pass 
`foo and bar` to it you get `foo and bar` but that's not a usable name of any 
kind, right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[clang-tools-extra] ac616fb - [Clang-tidy] Check the existence of ElaboratedType's qualifiers

2022-03-01 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-03-01T23:52:44+08:00
New Revision: ac616fbb05b8c0e8f85144d54d5295d2d663c5b7

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

LOG: [Clang-tidy] Check the existence of ElaboratedType's qualifiers

The ElaboratedType can have no qualifiers, so we should check it before
use.

Fix #issue53874(https://github.com/llvm/llvm-project/issues/53874)

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
index f2c1b0f5ec49b..0f73b1320de5a 100644
--- 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -19,14 +19,15 @@ namespace readability {
 
 static unsigned getNameSpecifierNestingLevel(const QualType &QType) {
   if (const ElaboratedType *ElType = QType->getAs()) {
-const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier();
-unsigned NameSpecifierNestingLevel = 1;
-do {
-  NameSpecifierNestingLevel++;
-  NestedSpecifiers = NestedSpecifiers->getPrefix();
-} while (NestedSpecifiers);
-
-return NameSpecifierNestingLevel;
+if (const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier()) {
+  unsigned NameSpecifierNestingLevel = 1;
+  do {
+NameSpecifierNestingLevel++;
+NestedSpecifiers = NestedSpecifiers->getPrefix();
+  } while (NestedSpecifiers);
+
+  return NameSpecifierNestingLevel;
+}
   }
   return 0;
 }
@@ -68,6 +69,10 @@ void StaticAccessedThroughInstanceCheck::check(
   PrintingPolicy PrintingPolicyWithSupressedTag(AstContext->getLangOpts());
   PrintingPolicyWithSupressedTag.SuppressTagKeyword = true;
   PrintingPolicyWithSupressedTag.SuppressUnwrittenScope = true;
+
+  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  !BaseExpr->getType()->isTypedefNameType();
+
   std::string BaseTypeName =
   BaseType.getAsString(PrintingPolicyWithSupressedTag);
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
index cd8d198c3d47d..debf3b9222164 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
@@ -198,6 +198,28 @@ void static_through_instance() {
   h<4>();
 }
 
+struct SP {
+  static int I;
+} P;
+
+void usep() {
+  P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  SP::I;{{$}}
+}
+
+namespace NSP {
+struct SP {
+  static int I;
+} P;
+} // namespace NSP
+
+void usensp() {
+  NSP::P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  NSP::SP::I;{{$}}
+}
+
 // Overloaded member access operator
 struct Q {
   static int K;
@@ -237,9 +259,9 @@ void use_anonymous() {
 
 namespace Outer {
   inline namespace Inline {
-struct S {
-  static int I;
-};
+  struct S {
+static int I;
+  };
   }
 }
 



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


[PATCH] D119949: [Clang-tidy] Check the existence of ElaboratedType's qualifiers

2022-03-01 Thread Jun Zhang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGac616fbb05b8: [Clang-tidy] Check the existence of 
ElaboratedType's qualifiers (authored by junaire).

Changed prior to commit:
  https://reviews.llvm.org/D119949?vs=409511&id=412111#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119949

Files:
  
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
@@ -198,6 +198,28 @@
   h<4>();
 }
 
+struct SP {
+  static int I;
+} P;
+
+void usep() {
+  P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  SP::I;{{$}}
+}
+
+namespace NSP {
+struct SP {
+  static int I;
+} P;
+} // namespace NSP
+
+void usensp() {
+  NSP::P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  NSP::SP::I;{{$}}
+}
+
 // Overloaded member access operator
 struct Q {
   static int K;
@@ -237,9 +259,9 @@
 
 namespace Outer {
   inline namespace Inline {
-struct S {
-  static int I;
-};
+  struct S {
+static int I;
+  };
   }
 }
 
Index: 
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
===
--- 
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ 
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -19,14 +19,15 @@
 
 static unsigned getNameSpecifierNestingLevel(const QualType &QType) {
   if (const ElaboratedType *ElType = QType->getAs()) {
-const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier();
-unsigned NameSpecifierNestingLevel = 1;
-do {
-  NameSpecifierNestingLevel++;
-  NestedSpecifiers = NestedSpecifiers->getPrefix();
-} while (NestedSpecifiers);
-
-return NameSpecifierNestingLevel;
+if (const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier()) {
+  unsigned NameSpecifierNestingLevel = 1;
+  do {
+NameSpecifierNestingLevel++;
+NestedSpecifiers = NestedSpecifiers->getPrefix();
+  } while (NestedSpecifiers);
+
+  return NameSpecifierNestingLevel;
+}
   }
   return 0;
 }
@@ -68,6 +69,10 @@
   PrintingPolicy PrintingPolicyWithSupressedTag(AstContext->getLangOpts());
   PrintingPolicyWithSupressedTag.SuppressTagKeyword = true;
   PrintingPolicyWithSupressedTag.SuppressUnwrittenScope = true;
+
+  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  !BaseExpr->getType()->isTypedefNameType();
+
   std::string BaseTypeName =
   BaseType.getAsString(PrintingPolicyWithSupressedTag);
 


Index: clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
@@ -198,6 +198,28 @@
   h<4>();
 }
 
+struct SP {
+  static int I;
+} P;
+
+void usep() {
+  P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  SP::I;{{$}}
+}
+
+namespace NSP {
+struct SP {
+  static int I;
+} P;
+} // namespace NSP
+
+void usensp() {
+  NSP::P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  NSP::SP::I;{{$}}
+}
+
 // Overloaded member access operator
 struct Q {
   static int K;
@@ -237,9 +259,9 @@
 
 namespace Outer {
   inline namespace Inline {
-struct S {
-  static int I;
-};
+  struct S {
+static int I;
+  };
   }
 }
 
Index: clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -19,14 +19,15 @@
 
 static unsigned getNameSpecifierNestingLevel(const QualType &QType) {
   if (const ElaboratedType *ElType = QType->getAs()) {
-const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier();
-unsigned NameSpecifierNestingLevel = 1;
-do {
-  NameSpecifierNestingLevel++;
-  NestedSpecifiers = NestedSpecifiers->getPrefix();
-} while (NestedSpecifiers);
-
-return NameSpecifierNestingLevel;
+if (const NestedNameSpecifier *NestedSpecifiers = ElType->ge

[PATCH] D120646: [clang][scan-build] Change mode of installation for scan-build.1

2022-03-01 Thread Manas Gupta via Phabricator via cfe-commits
manas updated this revision to Diff 412112.
manas added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120646

Files:
  clang/tools/scan-build/CMakeLists.txt


Index: clang/tools/scan-build/CMakeLists.txt
===
--- clang/tools/scan-build/CMakeLists.txt
+++ clang/tools/scan-build/CMakeLists.txt
@@ -74,7 +74,7 @@
  "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
 list(APPEND Depends 
"${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}")
-install(PROGRAMS man/${ManPage}
+install(FILES man/${ManPage}
 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
 COMPONENT scan-build)
   endforeach()


Index: clang/tools/scan-build/CMakeLists.txt
===
--- clang/tools/scan-build/CMakeLists.txt
+++ clang/tools/scan-build/CMakeLists.txt
@@ -74,7 +74,7 @@
  "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
 list(APPEND Depends "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}")
-install(PROGRAMS man/${ManPage}
+install(FILES man/${ManPage}
 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
 COMPONENT scan-build)
   endforeach()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120646: [clang][scan-build] Change mode of installation for scan-build.1

2022-03-01 Thread Manas Gupta via Phabricator via cfe-commits
manas added a comment.

I rebased to see if it satisfies the buildbot.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120646

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


[PATCH] D119876: [nfc][codegen] Move RegisterBank[Info].h under CodeGen

2022-03-01 Thread Mircea Trofin via Phabricator via cfe-commits
mtrofin added a comment.

As this is a follow-up of a refactoring, I assume I can just land it (short of 
file header comments, there was nothing really this patch did more 
intelligently)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119876

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


[clang] 32ac21d - [NFC][analyzer] Allow CallDescriptions to be matched with CallExprs

2022-03-01 Thread Kristóf Umann via cfe-commits

Author: Kristóf Umann
Date: 2022-03-01T17:13:04+01:00
New Revision: 32ac21d04909da0d50d3b24100d5d9ab30b29a95

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

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

Since CallDescriptions can only be matched against CallEvents that are created
during symbolic execution, it was not possible to use it in syntactic-only
contexts. For example, even though InnerPointerChecker can check with its set of
CallDescriptions whether a function call is interested during analysis, its
unable to check without hassle whether a non-analyzer piece of code also calls
such a function.

The patch adds the ability to use CallDescriptions in syntactic contexts as
well. While we already have that in Signature, we still want to leverage the
ability to use dynamic information when we have it (function pointers, for
example). This could be done with Signature as well (StdLibraryFunctionsChecker
does it), but it makes it even less of a drop-in replacement.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp
clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index cd972b7837d00..e552b833b6f25 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -108,13 +108,56 @@ class CallDescription {
 return CD1.matches(Call);
   }
 
-  /// \copydoc clang::ento::matchesAny(const CallEvent &, const 
CallDescription &)
+  /// \copydoc clang::ento::CallDescription::matchesAny(const CallEvent &, 
const CallDescription &)
   template 
   friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1,
  const Ts &...CDs) {
 return CD1.matches(Call) || matchesAny(Call, CDs...);
   }
   /// @}
+
+  /// @name Matching CallDescriptions against a CallExpr
+  /// @{
+
+  /// Returns true if the CallExpr is a call to a function that matches the
+  /// CallDescription.
+  ///
+  /// When available, always prefer matching with a CallEvent! This function
+  /// exists only when that is not available, for example, when _only_
+  /// syntactic check is done on a piece of code.
+  ///
+  /// Also, StdLibraryFunctionsChecker::Signature is likely a better candicade
+  /// for syntactic only matching if you are writing a new checker. This is
+  /// handy if a CallDescriptionMap is already there.
+  ///
+  /// The function is imprecise because CallEvent may know path sensitive
+  /// information, such as the precise argument count (see comments for
+  /// CallEvent::getNumArgs), the called function if it was called through a
+  /// function pointer, and other information not available syntactically.
+  bool matchesAsWritten(const CallExpr &CE) const;
+
+  /// Returns true whether the CallExpr matches on any of the CallDescriptions
+  /// supplied.
+  ///
+  /// \note This function is not intended to be used to match Obj-C method
+  /// calls.
+  friend bool matchesAnyAsWritten(const CallExpr &CE,
+  const CallDescription &CD1) {
+return CD1.matchesAsWritten(CE);
+  }
+
+  /// \copydoc clang::ento::CallDescription::matchesAnyAsWritten(const 
CallExpr &, const CallDescription &)
+  template 
+  friend bool matchesAnyAsWritten(const CallExpr &CE,
+  const CallDescription &CD1,
+  const Ts &...CDs) {
+return CD1.matchesAsWritten(CE) || matchesAnyAsWritten(CE, CDs...);
+  }
+  /// @}
+
+private:
+  bool matchesImpl(const FunctionDecl *Callee, size_t ArgCount,
+   size_t ParamCount) const;
 };
 
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
@@ -156,6 +199,28 @@ template  class CallDescriptionMap {
 
 return nullptr;
   }
+
+  /// When available, always prefer lookup with a CallEvent! This function
+  /// exists only when that is not available, for example, when _only_
+  /// syntactic check is done on a piece of code.
+  ///
+  /// Also, StdLibraryFunctionsChecker::Signature is likely a better candicade
+  /// for syntactic only matching if you are writing a new checker. This is
+  /// handy if a CallDescriptionMap is already there.
+  ///
+  /// The function is imprecise because CallEvent may know path sensitive
+  /// information, such as the precise argument count (see comments for
+  /// CallEvent::getNumArgs), the called function if it

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

2022-03-01 Thread Kristóf Umann 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 rG32ac21d04909: [NFC][analyzer] Allow CallDescriptions to be 
matched with CallExprs (authored by Szelethus).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119004

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp
  clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp

Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -6,11 +6,18 @@
 //
 //===--===//
 
+#include "CheckerRegistration.h"
 #include "Reusables.h"
 
 #include "clang/AST/ExprCXX.h"
+#include "clang/Analysis/PathDiagnostic.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
+#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
 #include 
@@ -543,6 +550,77 @@
   }
 }
 
+//===--===//
+// Testing through a checker interface.
+//
+// Above, the static analyzer isn't run properly, only the bare minimum to
+// create CallEvents. This causes CallEvents through function pointers to not
+// refer to the pointee function, but this works fine if we run
+// AnalysisASTConsumer.
+//===--===//
+
+class CallDescChecker
+: public Checker> {
+  CallDescriptionSet Set = {{"bar", 0}};
+
+public:
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
+if (Set.contains(Call)) {
+  C.getBugReporter().EmitBasicReport(
+  Call.getDecl(), this, "CallEvent match", categories::LogicError,
+  "CallEvent match",
+  PathDiagnosticLocation{Call.getDecl(), C.getSourceManager()});
+}
+  }
+
+  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
+if (Set.containsAsWritten(*CE)) {
+  C.getBugReporter().EmitBasicReport(
+  CE->getCalleeDecl(), this, "CallExpr match", categories::LogicError,
+  "CallExpr match",
+  PathDiagnosticLocation{CE->getCalleeDecl(), C.getSourceManager()});
+}
+  }
+};
+
+void addCallDescChecker(AnalysisASTConsumer &AnalysisConsumer,
+AnalyzerOptions &AnOpts) {
+  AnOpts.CheckersAndPackages = {{"test.CallDescChecker", true}};
+  AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) {
+Registry.addChecker("test.CallDescChecker", "Description",
+ "");
+  });
+}
+
+TEST(CallDescription, CheckCallExprMatching) {
+  // Imprecise matching shouldn't catch the call to bar, because its obscured
+  // by a function pointer.
+  constexpr StringRef FnPtrCode = R"code(
+void bar();
+void foo() {
+  void (*fnptr)() = bar;
+  fnptr();
+})code";
+  std::string Diags;
+  EXPECT_TRUE(runCheckerOnCode(FnPtrCode.str(), Diags,
+   /*OnlyEmitWarnings*/ true));
+  EXPECT_EQ("test.CallDescChecker: CallEvent match\n", Diags);
+
+  // This should be caught properly by imprecise matching, as the call is done
+  // purely through syntactic means.
+  constexpr StringRef Code = R"code(
+void bar();
+void foo() {
+  bar();
+})code";
+  Diags.clear();
+  EXPECT_TRUE(runCheckerOnCode(Code.str(), Diags,
+   /*OnlyEmitWarnings*/ true));
+  EXPECT_EQ("test.CallDescChecker: CallEvent match\n"
+"test.CallDescChecker: CallExpr match\n",
+Diags);
+}
+
 } // namespace
 } // namespace ento
 } // namespace clang
Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -13,6 +13,7 @@
 //===--===//
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/AST/Decl.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -61,15 +62,32 @@
   if (!FD)
 return false;
 
+  

[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-01 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp:377
+  if (Access == AccessKind::read) {
+if (StInBound->getSVal(ER).isUndef()) {
+  emitUninitializedReadBug(C, StInBound, Buffer.Expression);

You should make this check optional, only if the 'checker' was enabled.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120729: [NFC] Promote addInstantiatedParametersToScope to a private Sema function

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

LGTM!


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

https://reviews.llvm.org/D120729

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


[clang] c601377 - [NFC]Promote addInstantiatedParametersToScope to a private Sema function

2022-03-01 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-03-01T08:31:51-08:00
New Revision: c601377b23767ede02fe5bbe880c05d420b53250

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

LOG: [NFC]Promote addInstantiatedParametersToScope to a private Sema function

This is used a few places in SemaTeplateInstantiateDecl, but is going
to be useful in SemaConcept.cpp as well. This patch switches it to be
a private function in Sema.

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 0840f3a6cdb71..d905db93ccfff 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6935,6 +6935,14 @@ class Sema final {
   llvm::ContextualFoldingSet
   SatisfactionCache;
 
+  /// Introduce the instantiated function parameters into the local
+  /// instantiation scope, and set the parameter names to those used
+  /// in the template.
+  bool addInstantiatedParametersToScope(
+  FunctionDecl *Function, const FunctionDecl *PatternDecl,
+  LocalInstantiationScope &Scope,
+  const MultiLevelTemplateArgumentList &TemplateArgs);
+
 public:
   const NormalizedConstraint *
   getNormalizedAssociatedConstraints(

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 237886c906a5b..49fe11d3fa6df 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4377,10 +4377,10 @@ 
TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
 /// Introduce the instantiated function parameters into the local
 /// instantiation scope, and set the parameter names to those used
 /// in the template.
-static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
- const FunctionDecl *PatternDecl,
- LocalInstantiationScope &Scope,
-   const MultiLevelTemplateArgumentList &TemplateArgs) 
{
+bool Sema::addInstantiatedParametersToScope(
+FunctionDecl *Function, const FunctionDecl *PatternDecl,
+LocalInstantiationScope &Scope,
+const MultiLevelTemplateArgumentList &TemplateArgs) {
   unsigned FParamIdx = 0;
   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
@@ -4396,9 +4396,9 @@ static bool addInstantiatedParametersToScope(Sema &S, 
FunctionDecl *Function,
   // it's instantiation-dependent.
   // FIXME: Updating the type to work around this is at best fragile.
   if (!PatternDecl->getType()->isDependentType()) {
-QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
- FunctionParam->getLocation(),
- FunctionParam->getDeclName());
+QualType T = SubstType(PatternParam->getType(), TemplateArgs,
+   FunctionParam->getLocation(),
+   FunctionParam->getDeclName());
 if (T.isNull())
   return true;
 FunctionParam->setType(T);
@@ -4411,8 +4411,8 @@ static bool addInstantiatedParametersToScope(Sema &S, 
FunctionDecl *Function,
 
 // Expand the parameter pack.
 Scope.MakeInstantiatedLocalArgPack(PatternParam);
-Optional NumArgumentsInExpansion
-  = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
+Optional NumArgumentsInExpansion =
+getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
 if (NumArgumentsInExpansion) {
   QualType PatternType =
   PatternParam->getType()->castAs()->getPattern();
@@ -4420,10 +4420,10 @@ static bool addInstantiatedParametersToScope(Sema &S, 
FunctionDecl *Function,
 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
 FunctionParam->setDeclName(PatternParam->getDeclName());
 if (!PatternDecl->getType()->isDependentType()) {
-  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
-  QualType T = S.SubstType(PatternType, TemplateArgs,
-   FunctionParam->getLocation(),
-   FunctionParam->getDeclName());
+  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
+  QualType T =
+  SubstType(PatternType, TemplateArgs, 
FunctionParam->getLocation(),
+FunctionParam->getDeclName());
   if (T.isNull())
 return true;
   FunctionParam->setType(T);
@@ -4487,8 +4487,7 @@ bool Sema::Instan

[PATCH] D120729: [NFC] Promote addInstantiatedParametersToScope to a private Sema function

2022-03-01 Thread Erich Keane via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc601377b2376: [NFC]Promote addInstantiatedParametersToScope 
to a private Sema function (authored by erichkeane).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120729

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4377,10 +4377,10 @@
 /// Introduce the instantiated function parameters into the local
 /// instantiation scope, and set the parameter names to those used
 /// in the template.
-static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
- const FunctionDecl *PatternDecl,
- LocalInstantiationScope &Scope,
-   const MultiLevelTemplateArgumentList &TemplateArgs) {
+bool Sema::addInstantiatedParametersToScope(
+FunctionDecl *Function, const FunctionDecl *PatternDecl,
+LocalInstantiationScope &Scope,
+const MultiLevelTemplateArgumentList &TemplateArgs) {
   unsigned FParamIdx = 0;
   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
@@ -4396,9 +4396,9 @@
   // it's instantiation-dependent.
   // FIXME: Updating the type to work around this is at best fragile.
   if (!PatternDecl->getType()->isDependentType()) {
-QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
- FunctionParam->getLocation(),
- FunctionParam->getDeclName());
+QualType T = SubstType(PatternParam->getType(), TemplateArgs,
+   FunctionParam->getLocation(),
+   FunctionParam->getDeclName());
 if (T.isNull())
   return true;
 FunctionParam->setType(T);
@@ -4411,8 +4411,8 @@
 
 // Expand the parameter pack.
 Scope.MakeInstantiatedLocalArgPack(PatternParam);
-Optional NumArgumentsInExpansion
-  = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
+Optional NumArgumentsInExpansion =
+getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
 if (NumArgumentsInExpansion) {
   QualType PatternType =
   PatternParam->getType()->castAs()->getPattern();
@@ -4420,10 +4420,10 @@
 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
 FunctionParam->setDeclName(PatternParam->getDeclName());
 if (!PatternDecl->getType()->isDependentType()) {
-  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
-  QualType T = S.SubstType(PatternType, TemplateArgs,
-   FunctionParam->getLocation(),
-   FunctionParam->getDeclName());
+  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
+  QualType T =
+  SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
+FunctionParam->getDeclName());
   if (T.isNull())
 return true;
   FunctionParam->setType(T);
@@ -4487,8 +4487,7 @@
 
 FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
 /*ForDefinition*/ false);
-if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
- TemplateArgs))
+if (addInstantiatedParametersToScope(FD, Pattern, Local, TemplateArgs))
   return true;
 
 runWithSufficientStackSpace(CallLoc, [&] {
@@ -4561,8 +4560,7 @@
   // we don't store enough information to map back to the friend declaration in
   // the template.
   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
-  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
-   TemplateArgs)) {
+  if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
 UpdateExceptionSpec(Decl, EST_None);
 return;
   }
@@ -4603,8 +4601,7 @@
 MultiLevelTemplateArgumentList MLTAL(
 *Decl->getTemplateSpecializationArgs());
 if (addInstantiatedParametersToScope(
-*this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
-Scope, MLTAL))
+Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(), Scope, MLTAL))
   return true;
   }
   Qualifiers ThisQuals;
@@ -5050,7 +5047,7 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
-if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
+if (addI

[PATCH] D120404: [NFC][Lexer] Remove getLangOpts function from Lexer

2022-03-01 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 updated this revision to Diff 412120.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

Files:
  clang/include/clang/Lex/Lexer.h
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/ModuleMap.cpp


Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1615,7 +1615,7 @@
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
 unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+Lexer::getSpelling(LToken, Start, SourceMgr, Map.LangOpts);
 uint64_t Value;
 if (StringRef(Start, Length).getAsInteger(0, Value)) {
   Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -1194,11 +1194,11 @@
 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
 /// return the result character.  Finally, emit a warning about trigraph use
 /// whether trigraphs are enabled or not.
-static char DecodeTrigraphChar(const char *CP, Lexer *L) {
+static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
   char Res = GetTrigraphCharForLetter(*CP);
   if (!Res || !L) return Res;
 
-  if (!L->getLangOpts().Trigraphs) {
+  if (!Trigraphs) {
 if (!L->isLexingRawMode())
   L->Diag(CP-2, diag::trigraph_ignored);
 return 0;
@@ -1372,7 +1372,8 @@
   if (Ptr[0] == '?' && Ptr[1] == '?') {
 // If this is actually a legal trigraph (not something like "??x"), emit
 // a trigraph warning.  If so, and if trigraphs are enabled, return it.
-if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
+if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
+LangOpts.Trigraphs)) {
   // Remember that this token needs to be cleaned.
   if (Tok) Tok->setFlag(Token::NeedsCleaning);
 
@@ -2543,8 +2544,8 @@
 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
 /// character (either \\n or \\r) is part of an escaped newline sequence.  
Issue
 /// a diagnostic if so.  We know that the newline is inside of a block comment.
-static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
-  Lexer *L) {
+static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
+  bool Trigraphs) {
   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
 
   // Position of the first trigraph in the ending sequence.
@@ -2595,7 +2596,7 @@
   if (TrigraphPos) {
 // If no trigraphs are enabled, warn that we ignored this trigraph and
 // ignore this * character.
-if (!L->getLangOpts().Trigraphs) {
+if (!Trigraphs) {
   if (!L->isLexingRawMode())
 L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
   return false;
@@ -2725,7 +2726,8 @@
 break;
 
   if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
-if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
+if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
+  LangOpts.Trigraphs)) {
   // We found the final */, though it had an escaped newline between 
the
   // * and /.  We're done!
   break;
Index: clang/include/clang/Lex/Lexer.h
===
--- clang/include/clang/Lex/Lexer.h
+++ clang/include/clang/Lex/Lexer.h
@@ -183,10 +183,6 @@
SourceLocation ExpansionLocEnd,
unsigned TokLen, Preprocessor &PP);
 
-  /// getLangOpts - Return the language features currently enabled.
-  /// NOTE: this lexer modifies features as a file is parsed!
-  const LangOptions &getLangOpts() const { return LangOpts; }
-
   /// getFileLoc - Return the File Location for the file we are lexing out of.
   /// The physical location encodes the location where the characters come 
from,
   /// the virtual location encodes where we should *claim* the characters came


Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1615,7 +1615,7 @@
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
 unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+Lexer::getSpelling(LToken, Start, SourceMgr, Map.LangOpts);
 uint64_t Value;
 if (StringRef(Start, Length).getAsInteger(0, Value)) {
   Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
Index

[PATCH] D120404: [NFC][Lexer] Remove getLangOpts function from Lexer

2022-03-01 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Rebased to https://reviews.llvm.org/D120334 and simplified by removing 
non-static Lexer::getSpelling function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

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


[PATCH] D120498: [AST] Test RecursiveASTVisitor's current traversal of templates.

2022-03-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thought about this some more, and talked to @hokein offline.

I want to make sure there's consensus on "desired behavior" before documenting 
it, to avoid too much confusion.
https://discourse.llvm.org/t/template-representation-in-ast-and-rav-with-explicit-instantiations/60606




Comment at: clang/unittests/Tooling/RecursiveASTVisitorTests/Templates.cpp:283
+  VisitClassTemplateSpecializationDecl
+  VisitFieldDecl
+TraverseClassTemplateSpecializationDecl

nridge wrote:
> Is this a FIXME (body is traversed is an instantiation declaration)?
Possibly - it seems like a body shouldn't even exist, right? But maybe the 
instantiation is performed anyway if the definition is visible, I don't really 
know the semantics.

If it does exist, traversing it seems wrong: this is almost certainly a 
double-traversal of the body if there's also an instantiation definition for 
the same decl.

I'll look into it...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120498

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:41
+  ///
+  ///  `Slvr` must not be null.
+  DataflowAnalysisContext(std::unique_ptr Slvr)

I think `S` would be easier to read. 



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:244-245
+  /// order, will return the same result. If the given boolean values represent
+  /// the
+  // same value, the result will be the value itself.
+  BoolValue &makeAnd(BoolValue &LHS, BoolValue &RHS) {





Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:253-254
+  /// order, will return the same result. If the given boolean values represent
+  /// the
+  // same value, the result will be the value itself.
+  BoolValue &makeOr(BoolValue &LHS, BoolValue &RHS) {





Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:34
+
+  auto Res = ConjunctionVals.try_emplace(
+  {&LHS, &RHS},

Why not use `try_emplace` earlier, to save of one of the lookups?



Comment at: 
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp:28-31
+TEST_F(DataflowAnalysisContextTest,
+   GetOrCreateConjunctionValueReturnsSameExprOnSubsequentCalls) {
+  auto &X = Context.createAtomicBoolValue();
+  auto &Y = Context.createAtomicBoolValue();

maybe add another one which simply tests that two calls to 
`createAtomicBoolValue` return distinct values (or even just distinct pointers?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

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


[PATCH] D119816: [SanitizerBounds] Add support for NoSanitizeBounds function

2022-03-01 Thread Tong Zhang via Phabricator via cfe-commits
ztong0001 added a comment.

Hi Marco,
@melver, Could you please help me landing it? I don't have write permission to 
the repo.
Please use Tong Zhang
Thanks,

Tong


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119816

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


[PATCH] D119876: [nfc][codegen] Move RegisterBank[Info].h under CodeGen

2022-03-01 Thread Min-Yih Hsu via Phabricator via cfe-commits
myhsu accepted this revision.
myhsu added a comment.
This revision is now accepted and ready to land.

since D119053  was accepted, I don't see any 
reason why this patch shouldn't be :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119876

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


[PATCH] D119876: [nfc][codegen] Move RegisterBank[Info].h under CodeGen

2022-03-01 Thread Min-Yih Hsu via Phabricator via cfe-commits
myhsu added inline comments.



Comment at: llvm/lib/Target/ARM/ARMTargetMachine.cpp:43
 #include "llvm/Pass.h"
+#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/CodeGen.h"

Hmm...did you use clang-format-diff.py? I wonder why this was changed (although 
it's a legit one)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119876

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


[PATCH] D120132: [HIP] Fix HIP include path

2022-03-01 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D120132#3351391 , @yaxunl wrote:

> 



> If any input file is HIP program, clang driver will use HIP offload kind for 
> all inputs. This behavior is similar as cuda-clang.

I do not think this is the case as illustrated by the example above. CUDA paths 
are only added to CUDA compilation. C++ compilation of `b.cc` does not have any 
of them.

> Therefore if any input file is HIP program, HIP include path is added for 
> each input file compilation. I think this is acceptable.

I disagree. HIP-specific include path should apply to HIP-specific cc1 
compilation only.

> However, when there is only C++ input file, clang driver should not add HIP 
> or CUDA include path.

Agreed. AFAICT this is the case for CUDA.

> The current patch breaks that. That's why I think it needs change.

I agree. Hence my suggestion to add the path via toolchain-specific 
`AddClangSystemIncludeArgs`.


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

https://reviews.llvm.org/D120132

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


[PATCH] D119816: [SanitizerBounds] Add support for NoSanitizeBounds function

2022-03-01 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D119816#3349076 , @ztong0001 wrote:

> Hi Marco,
> @melver, Could you please help me landing it? I don't have write permission 
> to the repo.
> Please use Tong Zhang

Sure. I had already applied the patch locally to test, but then got distracted. 
Doing it now.

Thanks for your work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119816

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


[clang] 17ce89f - [SanitizerBounds] Add support for NoSanitizeBounds function

2022-03-01 Thread Marco Elver via cfe-commits

Author: Tong Zhang
Date: 2022-03-01T18:47:02+01:00
New Revision: 17ce89fa8016758be2ec879c5560e506cad4c362

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

LOG: [SanitizerBounds] Add support for NoSanitizeBounds function

Currently adding attribute no_sanitize("bounds") isn't disabling
-fsanitize=local-bounds (also enabled in -fsanitize=bounds). The Clang
frontend handles fsanitize=array-bounds which can already be disabled by
no_sanitize("bounds"). However, instrumentation added by the
BoundsChecking pass in the middle-end cannot be disabled by the
attribute.

The fix is very similar to D102772 that added the ability to selectively
disable sanitizer pass on certain functions.

In this patch, if no_sanitize("bounds") is provided, an additional
function attribute (NoSanitizeBounds) is attached to IR to let the
BoundsChecking pass know we want to disable local-bounds checking. In
order to support this feature, the IR is extended (similar to D102772)
to make Clang able to preserve the information and let BoundsChecking
pass know bounds checking is disabled for certain function.

Reviewed By: melver

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

Added: 
llvm/test/Instrumentation/BoundsChecking/nosanitize-bounds.ll

Modified: 
clang/lib/CodeGen/CodeGenFunction.cpp
clang/test/CodeGen/bounds-checking.c
clang/test/CodeGen/sanitize-coverage.c
llvm/bindings/go/llvm/ir_test.go
llvm/docs/BitCodeFormat.rst
llvm/docs/LangRef.rst
llvm/include/llvm/AsmParser/LLToken.h
llvm/include/llvm/Bitcode/LLVMBitCodes.h
llvm/include/llvm/IR/Attributes.td
llvm/lib/AsmParser/LLLexer.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
llvm/lib/Transforms/Utils/CodeExtractor.cpp
llvm/test/Bitcode/attributes.ll
llvm/test/Bitcode/compatibility.ll
llvm/utils/emacs/llvm-mode.el
llvm/utils/llvm.grm
llvm/utils/vim/syntax/llvm.vim
llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 9c3e5d5460014..c1f3a3014a192 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -740,6 +740,7 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   } while (false);
 
   if (D) {
+const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
 bool NoSanitizeCoverage = false;
 
 for (auto Attr : D->specific_attrs()) {
@@ -760,6 +761,9 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
 NoSanitizeCoverage = true;
 }
 
+if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
+  Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
+
 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
   Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
   }

diff  --git a/clang/test/CodeGen/bounds-checking.c 
b/clang/test/CodeGen/bounds-checking.c
index ba8c18934388c..25b767c7fa0d9 100644
--- a/clang/test/CodeGen/bounds-checking.c
+++ b/clang/test/CodeGen/bounds-checking.c
@@ -49,3 +49,12 @@ int f5(union U *u, int i) {
   return u->c[i];
   // CHECK: }
 }
+
+__attribute__((no_sanitize("bounds")))
+int f6(int i) {
+   int b[64];
+   // CHECK-NOT: call void @llvm.trap()
+   // CHECK-NOT: trap:
+   // CHECK-NOT: cont:
+   return b[i];
+}

diff  --git a/clang/test/CodeGen/sanitize-coverage.c 
b/clang/test/CodeGen/sanitize-coverage.c
index 6fd0adcb4a880..984076fed0ce4 100644
--- a/clang/test/CodeGen/sanitize-coverage.c
+++ b/clang/test/CodeGen/sanitize-coverage.c
@@ -53,6 +53,7 @@ void test_no_sanitize_combined(int n) {
   // ASAN-NOT: call void @__asan_report_store
   // MSAN-NOT: call void @__msan_warning
   // BOUNDS-NOT: call void @__ubsan_handle_out_of_bounds
+  // BOUNDS-NOT: call void @llvm.trap()
   // TSAN-NOT: call void @__tsan_func_entry
   // UBSAN-NOT: call void @__ubsan_handle
   if (n)
@@ -72,6 +73,7 @@ void test_no_sanitize_separate(int n) {
   // ASAN-NOT: call void @__asan_report_store
   // MSAN-NOT: call void @__msan_warning
   // BOUNDS-NOT: call void @__ubsan_handle_out_of_bounds
+  // BOUNDS-NOT: call void @llvm.trap()
   // TSAN-NOT: call void @__tsan_func_entry
   // UBSAN-NOT: call void @__ubsan_handle
   if (n)

diff  --git a/llvm/bindings/go/llvm/ir_test.go 
b/llvm/bindings/go/llvm/ir_test.go
index 61b482f2ef9a2..1aeb6e69bafb2 100644
--- a/llvm/bindings/go/llvm/ir_test.go
+++ b/llvm/bindings/go/llvm/ir_test.go
@@ -69,6 +69,7 @@ func TestAttributes(t *testing.T) {
"noredzone",
"noreturn",
"nounwind",
+   "nosanitize_

[PATCH] D119816: [SanitizerBounds] Add support for NoSanitizeBounds function

2022-03-01 Thread Marco Elver 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 rG17ce89fa8016: [SanitizerBounds] Add support for 
NoSanitizeBounds function (authored by ztong0001, committed by melver).

Changed prior to commit:
  https://reviews.llvm.org/D119816?vs=411457&id=412141#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119816

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGen/bounds-checking.c
  clang/test/CodeGen/sanitize-coverage.c
  llvm/bindings/go/llvm/ir_test.go
  llvm/docs/BitCodeFormat.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/AsmParser/LLToken.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp
  llvm/test/Bitcode/attributes.ll
  llvm/test/Bitcode/compatibility.ll
  llvm/test/Instrumentation/BoundsChecking/nosanitize-bounds.ll
  llvm/utils/emacs/llvm-mode.el
  llvm/utils/llvm.grm
  llvm/utils/vim/syntax/llvm.vim
  llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml

Index: llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
===
--- llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
+++ llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
@@ -238,6 +238,7 @@
 \\bnosync\\b|\
 \\bnoundef\\b|\
 \\bnounwind\\b|\
+\\bnosanitize_bounds\\b|\
 \\bnosanitize_coverage\\b|\
 \\bnull_pointer_is_valid\\b|\
 \\boptforfuzzing\\b|\
Index: llvm/utils/vim/syntax/llvm.vim
===
--- llvm/utils/vim/syntax/llvm.vim
+++ llvm/utils/vim/syntax/llvm.vim
@@ -139,6 +139,7 @@
   \ nosync
   \ noundef
   \ nounwind
+  \ nosanitize_bounds
   \ nosanitize_coverage
   \ null_pointer_is_valid
   \ optforfuzzing
Index: llvm/utils/llvm.grm
===
--- llvm/utils/llvm.grm
+++ llvm/utils/llvm.grm
@@ -176,6 +176,7 @@
  | sanitize_thread
  | sanitize_memory
  | mustprogress
+ | nosanitize_bounds
  | nosanitize_coverage
  ;
 
Index: llvm/utils/emacs/llvm-mode.el
===
--- llvm/utils/emacs/llvm-mode.el
+++ llvm/utils/emacs/llvm-mode.el
@@ -25,7 +25,7 @@
'("alwaysinline" "argmemonly" "allocsize" "builtin" "cold" "convergent" "dereferenceable" "dereferenceable_or_null" "hot" "inaccessiblememonly"
  "inaccessiblemem_or_argmemonly" "inalloca" "inlinehint" "jumptable" "minsize" "mustprogress" "naked" "nobuiltin" "nonnull"
  "nocallback" "nocf_check" "noduplicate" "nofree" "noimplicitfloat" "noinline" "nomerge" "nonlazybind" "noprofile" "noredzone" "noreturn"
- "norecurse" "nosync" "noundef" "nounwind" "nosanitize_coverage" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
+ "norecurse" "nosync" "noundef" "nounwind" "nosanitize_bounds" "nosanitize_coverage" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
  "shadowcallstack" "speculatable" "speculative_load_hardening" "ssp" "sspreq" "sspstrong" "safestack" "sanitize_address" "sanitize_hwaddress" "sanitize_memtag"
  "sanitize_thread" "sanitize_memory" "strictfp" "swifterror" "uwtable" "vscale_range" "willreturn" "writeonly" "immarg") 'symbols) . font-lock-constant-face)
;; Variables
Index: llvm/test/Instrumentation/BoundsChecking/nosanitize-bounds.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/BoundsChecking/nosanitize-bounds.ll
@@ -0,0 +1,17 @@
+; RUN: opt < %s -passes=bounds-checking -S | FileCheck %s
+target datalayout = "e-p:64:64:64-p1:16:16:16-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
+
+; CHECK: @foo
+define i32 @foo(i32 %i) nosanitize_bounds {
+entry:
+  %i.addr = alloca i32, align 4
+  %b = alloca [64 x i32], align 16
+  store i32 %i, i32* %i.addr, align 4
+  %0 = load i32, i32* %i.addr, align 4
+  %idxprom = sext i32 %0 to i64
+  %arrayidx = getelementptr inbounds [64 x i32], [64 x i32]* %b, i64 0, i64 %idxprom
+  %1 = load i32, i32* %arrayidx, align 4
+  ret i32 %1
+; CHECK-NOT: call void @llvm.trap()
+}
+
Index: llvm/test/Bitcode/compatibility.ll
===
--- llvm/test/Bitcode/compatibility.ll
+++ llvm/test/Bitcode/compatibility.ll
@@ -1510,7 +1510,7 @@
   ; CHECK: select <2 x i1

[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

> My reasoning was that I'm going to introduce an explicit enum value

Any reason why?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:41
+  ///
+  ///  `Slvr` must not be null.
+  DataflowAnalysisContext(std::unique_ptr Slvr)

ymandel wrote:
> I think `S` would be easier to read. 
Initially, I was wondering if we want to make the solver optional to 
potentially speed up analyses that do not need this capability. But I realized, 
we could just pass in a dummy no-op solver in those cases so this should be ok.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:247
+  BoolValue &makeAnd(BoolValue &LHS, BoolValue &RHS) {
+return &LHS == &RHS ? LHS : DACtx->getOrCreateConjunctionValue(LHS, RHS);
+  }

Should we move this check to `DataflowAnalysisContext` to protect against cases 
where users inadvertently try to call the its methods directly instead of using 
the `Environment`? 



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:30
+
+  It = ConjunctionVals.find({&RHS, &LHS});
+  if (It != ConjunctionVals.end())

Alternatively, we could canonicalize `BoolValue`s, e.g. always having the 
operand with the smaller address on the left. This could help us doing one less 
lookup (at the cost of a pointer comparison and sometimes a swap).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-03-01 Thread Felix Berger via Phabricator via cfe-commits
flx added a comment.

I'm still seeing build failures. Could you resolve them?


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

https://reviews.llvm.org/D116593

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


[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/docs/tools/dump_format_style.py:174-175
 return '* ``%s`` (in configuration: ``%s``)\n%s' % (
-self.name,
-re.sub('.*_', '', self.config),
+self.clean_name,
+self.clean_config,
 doxygen2rst(indent(self.comment, 2)))

kwk wrote:
> MyDeveloperDay wrote:
> > Feels like there is repetition here
> Are you suggesting to introduce a function `name_only` that looks like this?
> 
> ```lang=python
> def name_only(s: str) -> str:
>   return s.split("=", 1)[0].strip()
> ```
> 
> If so, should this be a member function of `EnumValue` or where would you see 
> it?
> 
> I'm not fond of introducing this function TBH because the name suggest it to 
> be very generically usable when in fact it does just a simple thing. If you 
> pass `foo and bar` to it you get `foo and bar` but that's not a usable name 
> of any kind, right?
yes I was suggesting adding a function, feel free to suggest a better name.

However all this said, I don't understand the need, you say your going to 
introduce explicit values to the enum, but why? I'm not a massive fan of that 
either, normally it means someone wants to abuse the enum by using the values 
and that IMHO can means people start doing things like taking values away from 
each other and/or doing a range loop from one value to another, and this 
becomes very unstable when enum values are added in between.

But please enlighten us as to what use the values will have I'm keen to learn.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk added a comment.

In D120712#3351889 , @MyDeveloperDay 
wrote:

>> My reasoning was that I'm going to introduce an explicit enum value
>
> Any reason why?

Yes, I but where's the fun if I told you now ;) . Just kidding. I don't want to 
go into the details but I plan on supporting a shared value between all 
enumerations. That's all I can say for now before I have my PoC ready to be 
presented for further discussion. But even if this future patch will never 
land, this very patch doesn't hurt, does it? Like I said, I tried to split my 
work into more easily consumable patches but I guess you're not convinced.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D120398: [format] follow up: Use unsigned char as the base of all enums in FormatStyle

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Before this lands can we have a discussion about what clarity this gives us?, 
because I think it makes the code more unreadable, but surely we are saving 
just 7x(3 bytes) (the difference between and int and a unsigned char for 7 
enums)

Is saving 21 bytes valuable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120398

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


[PATCH] D120132: [HIP] Fix HIP include path

2022-03-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D120132#3351853 , @tra wrote:

> In D120132#3351391 , @yaxunl wrote:
>
>> 
>
>
>
>> If any input file is HIP program, clang driver will use HIP offload kind for 
>> all inputs. This behavior is similar as cuda-clang.
>
> I do not think this is the case as illustrated by the example above. CUDA 
> paths are only added to CUDA compilation. C++ compilation of `b.cc` does not 
> have any of them.

I noticed that with "-c" HIP/CUDA include path is not used for C++ program. 
However without "-c" HIP/CUDA include path is used for C++ program. Probably 
this is a bug.

>> Therefore if any input file is HIP program, HIP include path is added for 
>> each input file compilation. I think this is acceptable.
>
> I disagree. HIP-specific include path should apply to HIP-specific cc1 
> compilation only.
>
>> However, when there is only C++ input file, clang driver should not add HIP 
>> or CUDA include path.
>
> Agreed. AFAICT this is the case for CUDA.
>
>> The current patch breaks that. That's why I think it needs change.
>
> I agree. Hence my suggestion to add the path via a toolchain-specific 
> `AddClangSystemIncludeArgs`.

In the current patch, AddClangSystemIncludeArgs is modified to add HIP include 
path. However, there is no good way to know if the current job action is HIP or 
C++ program.

The signature of AddClangSystemIncludeArgs is

  void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const ;

In the case of two input files `a.hip` and `b.cpp`, DriverArgs contain both 
`a.hip` and `b.cpp`. Clang does not know if the call of 
AddClangSystemIncludeArgs is for `a.hip` or `b.cpp`. The current patch adds HIP 
include path for both HIP and C++ programs.

To fix this issue, we either need to add a JobAction argument to 
AddClangSystemIncludeArgs to let clang know the current call of 
AddClangSystemIncludeArgs is for HIP program or C++ program, or we need to add 
HIP include path in a location where the current JobAction is known.


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

https://reviews.llvm.org/D120132

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


[PATCH] D120398: [format] follow up: Use unsigned char as the base of all enums in FormatStyle

2022-03-01 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

In D120398#3351998 , @MyDeveloperDay 
wrote:

> Before this lands can we have a discussion about what clarity this gives us?, 
> because I think it makes the code more unreadable, but surely we are saving 
> just 7x(3 bytes) (the difference between and int and a unsigned char for 7 
> enums)
>
> Is saving 21 bytes valuable?

Peanut gallery says: I think giving every enum a concrete underlying type is a 
//good// practice, so I don't think this makes anything less readable. (That 
is, I'd even favor adding `: int` to each of these enums, over the status quo 
where the type is merely implied — we've seen that people can be unsure of the 
exact behavior.)
I can imagine that someone might object that hard-coding one byte for each enum 
might one day cause problems if we want more than 256 possible settings for any 
given enum, but that's not likely, is it?
Re space savings, OP says that they're saving 21 bytes //per object// and that 
they have "lots" of objects in their particular use-case, even if clang-format 
itself doesn't.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120398

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


[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added subscribers: HazardyKnusperkeks, owenpan, curdeius.
MyDeveloperDay added a comment.

Does it need to be so "cloak and dagger"?  ;-)

We always welcome patches, but please think about logging the idea in github 
issues (and assigning it to yourself), and use the good will of the regular 
contributors to give you some feedback/advice (you never know we might know a 
thing or too)

I'd like to see this review in the context of what you are proposing. I know it 
doesn't do any actual harm on its own, but its doesn't actually do anything, as 
such its technical debt right? we have to maintain and support it when it goes 
wrong (it will unlikely go wrong, but it could I guess).

My suggestion is to hold off this patch until you have something that needs it 
then submit the reviews at the same time and mark with a dependency.  
(@curdeius, @HazardyKnusperkeks, @owenpan  am I being fair?)

Please also consider being more open about what you intend to work on, you 
never know we could save you time and effort. Plus remember you'll want one of 
us to review the changes so its good to build good relationships with the key 
contributors and get their input.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[PATCH] D117887: [NVPTX] Expose float tys min, max, abs, neg as builtins

2022-03-01 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D117887#3351257 , @jchlanda wrote:

> @tra thank you for landing the patches, it seems that the clang part (builtin 
> declarations and tests) have been dropped, only `llvm` dir changes made it 
> through. Is there any way I could fix it (same goes for the other two patches 
> in this stack)?

Somehow `arc export | git apply` didn't pick clang changes when I was 
transferring the patch from the phabricator. I'll re-fetch the patches and will 
land the missing pieces shortly.

I'm not sure how the you've submitted the patch to phabricator. In general, it 
works best when the patch is supplied as a gic commit diff, with the author 
metadata, etc. 
Or via `arc diff`. See for the details. 
https://llvm.org/docs/Phabricator.html#phabricator-reviews


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117887

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


[PATCH] D118525: [modules] Merge ObjC interface ivars with anonymous types.

2022-03-01 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

The modules side of this looks good to me, and logically changing the lexical 
decl context in an interface to be that interface makes a lot of sense, but I 
agree with @rjmccall that it's hard to predict what the consequences of that 
change might be. Can you also test this against some body of real-world code?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118525

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 412160.
sgatev marked 8 inline comments as done.
sgatev added a comment.

Address reviewers' comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -68,7 +69,7 @@
   ControlFlowContext::build(nullptr, Body, &AST->getASTContext()));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx);
 
   return runDataflowAnalysis(CFCtx, Analysis, Env);
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -23,6 +23,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
@@ -104,7 +105,7 @@
   if (!CFCtx)
 return CFCtx.takeError();
 
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -0,0 +1,57 @@
+//===- unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.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/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+
+class EnvironmentTest : public ::testing::Test {
+  DataflowAnalysisContext Context;
+
+protected:
+  EnvironmentTest()
+  : Context(std::make_unique()), Env(Context) {}
+
+  Environment Env;
+};
+
+TEST_F(EnvironmentTest, MakeImplicationReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeImplication(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, MakeIffReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeIff(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, FlowCondition) {
+  EXPECT_TRUE(Env.flowConditionImplies(Env.getBoolLiteralValue(true)));
+  EXPECT_FALSE(Env.flowConditionImplies(Env.getBoolLiteralValue(false)));
+
+  auto &X = Env.makeAtomicBoolValue();
+  EXPECT_FALSE(Env.flowConditionImplies(X));
+
+  Env.addToFlowCondition(X);
+  EXPECT_TRUE(Env.flowConditionImplies(X));
+
+  auto &NotX = Env.makeNot(X);
+  EXPECT_FALSE(Env.flowConditionImplies(NotX));
+}
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- /dev/null
+++ clang/unittests/

[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:41
+  ///
+  ///  `Slvr` must not be null.
+  DataflowAnalysisContext(std::unique_ptr Slvr)

xazax.hun wrote:
> ymandel wrote:
> > I think `S` would be easier to read. 
> Initially, I was wondering if we want to make the solver optional to 
> potentially speed up analyses that do not need this capability. But I 
> realized, we could just pass in a dummy no-op solver in those cases so this 
> should be ok.
Agreed.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:247
+  BoolValue &makeAnd(BoolValue &LHS, BoolValue &RHS) {
+return &LHS == &RHS ? LHS : DACtx->getOrCreateConjunctionValue(LHS, RHS);
+  }

xazax.hun wrote:
> Should we move this check to `DataflowAnalysisContext` to protect against 
> cases where users inadvertently try to call the its methods directly instead 
> of using the `Environment`? 
Done, but kept the implication and bi-conditional helpers in `Environment` as 
I'm not sure if we'll need them in `DataflowAnalysisContext` at this point.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:30
+
+  It = ConjunctionVals.find({&RHS, &LHS});
+  if (It != ConjunctionVals.end())

xazax.hun wrote:
> Alternatively, we could canonicalize `BoolValue`s, e.g. always having the 
> operand with the smaller address on the left. This could help us doing one 
> less lookup (at the cost of a pointer comparison and sometimes a swap).
Agreed. I updated the implementation.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:34
+
+  auto Res = ConjunctionVals.try_emplace(
+  {&LHS, &RHS},

ymandel wrote:
> Why not use `try_emplace` earlier, to save of one of the lookups?
Makes sense. I updated the implementation.



Comment at: 
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp:28-31
+TEST_F(DataflowAnalysisContextTest,
+   GetOrCreateConjunctionValueReturnsSameExprOnSubsequentCalls) {
+  auto &X = Context.createAtomicBoolValue();
+  auto &Y = Context.createAtomicBoolValue();

ymandel wrote:
> maybe add another one which simply tests that two calls to 
> `createAtomicBoolValue` return distinct values (or even just distinct 
> pointers?)
Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

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


[PATCH] D119876: [nfc][codegen] Move RegisterBank[Info].h under CodeGen

2022-03-01 Thread Mircea Trofin via Phabricator via cfe-commits
mtrofin marked an inline comment as done.
mtrofin added inline comments.



Comment at: llvm/lib/Target/ARM/ARMTargetMachine.cpp:43
 #include "llvm/Pass.h"
+#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/CodeGen.h"

myhsu wrote:
> Hmm...did you use clang-format-diff.py? I wonder why this was changed 
> (although it's a legit one)
did git clang-format, and since that had to re-sort the includes due to my 
change, it affected incorrectly placed lines. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119876

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


[PATCH] D120437: [HWASAN] erase lifetime intrinsics if tag is outside.

2022-03-01 Thread Florian Mayer via Phabricator via cfe-commits
fmayer added inline comments.



Comment at: clang/test/CodeGen/lifetime-sanitizer.c:9
+// RUN: %clang -target aarch64-linux-gnu -S -emit-llvm -o /dev/null -O0 \
+// RUN: -fsanitize=hwaddress -mllvm -print-before=hwasan %s 2>&1 | \
 // RUN: FileCheck %s -check-prefix=LIFETIME

eugenis wrote:
> You can use -Xclang -disable-llvm-passes instead.
Isn't what is currently there closer to what we actually want to test: that the 
hwasan pass has access to lifetimes?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120437

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


[PATCH] D120398: [format] follow up: Use unsigned char as the base of all enums in FormatStyle

2022-03-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In my own area I gave FormatStyle a copy constructor and made it private, it 
hardly caused any issues, this isn't something that we tend copy about very 
much, we tend copy construct it only when we do getLLVMStyle() to make another 
style say like google style sure we'll do that a handful of times but I very 
much doubt it would make an impact.. can we measure?

I have no problems adding the base class if that's the LLVM coding style 
recommendation, otherwise I don't see it gives us anything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120398

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 412162.
sgatev added a comment.

Address reviewers' comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -68,7 +69,7 @@
   ControlFlowContext::build(nullptr, Body, &AST->getASTContext()));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx);
 
   return runDataflowAnalysis(CFCtx, Analysis, Env);
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -23,6 +23,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
@@ -104,7 +105,7 @@
   if (!CFCtx)
 return CFCtx.takeError();
 
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -0,0 +1,57 @@
+//===- unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.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/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+
+class EnvironmentTest : public ::testing::Test {
+  DataflowAnalysisContext Context;
+
+protected:
+  EnvironmentTest()
+  : Context(std::make_unique()), Env(Context) {}
+
+  Environment Env;
+};
+
+TEST_F(EnvironmentTest, MakeImplicationReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeImplication(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, MakeIffReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeIff(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, FlowCondition) {
+  EXPECT_TRUE(Env.flowConditionImplies(Env.getBoolLiteralValue(true)));
+  EXPECT_FALSE(Env.flowConditionImplies(Env.getBoolLiteralValue(false)));
+
+  auto &X = Env.makeAtomicBoolValue();
+  EXPECT_FALSE(Env.flowConditionImplies(X));
+
+  Env.addToFlowCondition(X);
+  EXPECT_TRUE(Env.flowConditionImplies(X));
+
+  auto &NotX = Env.makeNot(X);
+  EXPECT_FALSE(Env.flowConditionImplies(NotX));
+}
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisCo

[PATCH] D120437: [HWASAN] erase lifetime intrinsics if tag is outside.

2022-03-01 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added inline comments.



Comment at: clang/test/CodeGen/lifetime-sanitizer.c:9
+// RUN: %clang -target aarch64-linux-gnu -S -emit-llvm -o /dev/null -O0 \
+// RUN: -fsanitize=hwaddress -mllvm -print-before=hwasan %s 2>&1 | \
 // RUN: FileCheck %s -check-prefix=LIFETIME

fmayer wrote:
> eugenis wrote:
> > You can use -Xclang -disable-llvm-passes instead.
> Isn't what is currently there closer to what we actually want to test: that 
> the hwasan pass has access to lifetimes?
I don't have a strong opinion on this, but it is common to exclude llvm passes 
from clang tests because that makes them brittle. Integration tests generally 
belong in compiler-rt, but there are some in clang, too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120437

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


[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-01 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:43
+
+  auto Res = ConjunctionVals.try_emplace(
+  std::move(Key),

As far as I understand, we need to do the double lookup (`find` and later 
`try_emplace`) because we do not want to allocate + take ownership when we hit 
the cache.  An alternative is to first do `try_emplace` with a `nullptr` and 
overwrite the value if the emplace was successful. But I guess that also can be 
confusing, so it is up to you which one would you prefer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

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


[clang] 7a6d692 - [NVPTX] Expose float tys min, max, abs, neg as builtins

2022-03-01 Thread Artem Belevich via cfe-commits

Author: Jakub Chlanda
Date: 2022-03-01T11:07:11-08:00
New Revision: 7a6d692b3b11e80fd19e7c9b65e1e6f70035c676

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

LOG: [NVPTX] Expose float tys min, max, abs, neg as builtins

Adds support for the following builtins:

abs, neg:
- .bf16,
- .bf16x2
min, max
- {.ftz}{.NaN}{.xorsign.abs}.f16
- {.ftz}{.NaN}{.xorsign.abs}.f16x2
- {.NaN}{.xorsign.abs}.bf16
- {.NaN}{.xorsign.abs}.bf16x2
- {.ftz}{.NaN}{.xorsign.abs}.f32

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

Added: 
clang/test/CodeGen/builtins-nvptx-native-half-type.c

Modified: 
clang/include/clang/Basic/BuiltinsNVPTX.def
clang/test/CodeGen/builtins-nvptx.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index 1279d83f1f61f..43874a9aa19b3 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -107,13 +107,89 @@ BUILTIN(__nvvm_prmt, "UiUiUiUi", "")
 
 // Min Max
 
-BUILTIN(__nvvm_fmax_ftz_f, "fff",  "")
-BUILTIN(__nvvm_fmax_f, "fff",  "")
-BUILTIN(__nvvm_fmin_ftz_f, "fff",  "")
-BUILTIN(__nvvm_fmin_f, "fff",  "")
+TARGET_BUILTIN(__nvvm_fmin_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_ftz_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_nan_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_nan_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_xorsign_abs_f16, "hhh", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_ftz_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_nan_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_xorsign_abs_f16x2, "V2hV2hV2h", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_xorsign_abs_f16x2, "V2hV2hV2h", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_nan_xorsign_abs_f16x2, "V2hV2hV2h", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_xorsign_abs_f16x2, "V2hV2hV2h", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_bf16, "UsUsUs", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_nan_bf16, "UsUsUs", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_xorsign_abs_bf16, "UsUsUs", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_nan_xorsign_abs_bf16, "UsUsUs", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_bf16x2, "ZUiZUiZUi", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_nan_bf16x2, "ZUiZUiZUi", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_xorsign_abs_bf16x2, "ZUiZUiZUi", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_nan_xorsign_abs_bf16x2, "ZUiZUiZUi", "",
+   AND(SM_86, PTX72))
+BUILTIN(__nvvm_fmin_f, "fff", "")
+BUILTIN(__nvvm_fmin_ftz_f, "fff", "")
+TARGET_BUILTIN(__nvvm_fmin_nan_f, "fff", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_f, "fff", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmin_xorsign_abs_f, "fff", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_xorsign_abs_f, "fff", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_nan_xorsign_abs_f, "fff", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmin_ftz_nan_xorsign_abs_f, "fff", "", AND(SM_86, PTX72))
+BUILTIN(__nvvm_fmin_d, "ddd", "")
 
+TARGET_BUILTIN(__nvvm_fmax_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_ftz_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_nan_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_ftz_nan_f16, "hhh", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmax_ftz_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmax_nan_xorsign_abs_f16, "hhh", "", AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmax_ftz_nan_xorsign_abs_f16, "hhh", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmax_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_ftz_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_nan_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_ftz_nan_f16x2, "V2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fmax_xorsign_abs_f16x2, "V2hV2hV2h", "",
+   AND(SM_86, PTX72))
+TARGET_BUILTIN(__nvvm_fmax_ftz_xorsign_abs_f16x2, "V2hV2hV2h", "",
+ 

[clang] a895182 - [NVPTX] Add more FMA intriniscs/builtins

2022-03-01 Thread Artem Belevich via cfe-commits

Author: Jakub Chlanda
Date: 2022-03-01T11:07:11-08:00
New Revision: a8951823024b38c455e839d40656ad533b4aa8ff

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

LOG: [NVPTX] Add more FMA intriniscs/builtins

This patch adds builtins/intrinsics for the following variants of FMA:

NOTE: follow-up commit with the missing clang-side changes.

- f16, f16x2
  - rn
  - rn_ftz
  - rn_sat
  - rn_ftz_sat
  - rn_relu
  - rn_ftz_relu
- bf16, bf16x2
  - rn
  - rn_relu

ptxas (Cuda compilation tools, release 11.0, V11.0.194) is happy with the 
generated assembly.

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsNVPTX.def
clang/test/CodeGen/builtins-nvptx-native-half-type.c
clang/test/CodeGen/builtins-nvptx.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index 43874a9aa19b..a058925a6a5f 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -17,6 +17,7 @@
 #   define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) BUILTIN(ID, TYPE, ATTRS)
 #endif
 
+#pragma push_macro("SM_53")
 #pragma push_macro("SM_70")
 #pragma push_macro("SM_72")
 #pragma push_macro("SM_75")
@@ -30,7 +31,9 @@
 
 #pragma push_macro("SM_60")
 #define SM_60 "sm_60|sm_61|sm_62|" SM_70
+#define SM_53 "sm_53|" SM_60
 
+#pragma push_macro("PTX42")
 #pragma push_macro("PTX60")
 #pragma push_macro("PTX61")
 #pragma push_macro("PTX63")
@@ -53,6 +56,7 @@
 #define PTX63 "ptx63|" PTX64
 #define PTX61 "ptx61|" PTX63
 #define PTX60 "ptx60|" PTX61
+#define PTX42 "ptx42|" PTX60
 
 #pragma push_macro("AND")
 #define AND(a, b) "(" a "),(" b ")"
@@ -293,6 +297,22 @@ BUILTIN(__nvvm_cos_approx_f, "ff", "")
 
 // Fma
 
+TARGET_BUILTIN(__nvvm_fma_rn_f16, "", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_f16, "", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_sat_f16, "", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_sat_f16, "", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_relu_f16, "", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_relu_f16, "", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_f16x2, "V2hV2hV2hV2h", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_f16x2, "V2hV2hV2hV2h", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_sat_f16x2, "V2hV2hV2hV2h", "", AND(SM_53, PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_sat_f16x2, "V2hV2hV2hV2h", "", AND(SM_53, 
PTX42))
+TARGET_BUILTIN(__nvvm_fma_rn_relu_f16x2, "V2hV2hV2hV2h", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_ftz_relu_f16x2, "V2hV2hV2hV2h", "", AND(SM_80, 
PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_bf16, "UsUsUsUs", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_relu_bf16, "UsUsUsUs", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_bf16x2, "ZUiZUiZUiZUi", "", AND(SM_80, PTX70))
+TARGET_BUILTIN(__nvvm_fma_rn_relu_bf16x2, "ZUiZUiZUiZUi", "", AND(SM_80, 
PTX70))
 BUILTIN(__nvvm_fma_rn_ftz_f, "", "")
 BUILTIN(__nvvm_fma_rn_f, "", "")
 BUILTIN(__nvvm_fma_rz_ftz_f, "", "")
@@ -913,12 +933,14 @@ TARGET_BUILTIN(__nvvm_neg_bf16x2, "ZUiZUi", "", 
AND(SM_80,PTX70))
 #undef BUILTIN
 #undef TARGET_BUILTIN
 #pragma pop_macro("AND")
+#pragma pop_macro("SM_53")
 #pragma pop_macro("SM_60")
 #pragma pop_macro("SM_70")
 #pragma pop_macro("SM_72")
 #pragma pop_macro("SM_75")
 #pragma pop_macro("SM_80")
 #pragma pop_macro("SM_86")
+#pragma pop_macro("PTX42")
 #pragma pop_macro("PTX60")
 #pragma pop_macro("PTX61")
 #pragma pop_macro("PTX63")

diff  --git a/clang/test/CodeGen/builtins-nvptx-native-half-type.c 
b/clang/test/CodeGen/builtins-nvptx-native-half-type.c
index 4440b274f670..c232c4de5640 100644
--- a/clang/test/CodeGen/builtins-nvptx-native-half-type.c
+++ b/clang/test/CodeGen/builtins-nvptx-native-half-type.c
@@ -20,6 +20,16 @@
 // RUN:   -fnative-half-type -S -emit-llvm -o - -x cuda %s \
 // RUN:   | FileCheck -check-prefix=CHECK -check-prefix=CHECK_PTX72_SM86 %s
 
+// RUN: %clang_cc1 -ffp-contract=off -triple nvptx-unknown-unknown -target-cpu 
\
+// RUN:   sm_53 -target-feature +ptx42 -fcuda-is-device -fnative-half-type -S \
+// RUN:   -emit-llvm -o - -x cuda %s \
+// RUN:   | FileCheck -check-prefix=CHECK -check-prefix=CHECK_PTX42_SM53 %s
+
+// RUN: %clang_cc1 -ffp-contract=off -triple nvptx64-unknown-unknown \
+// RUN:   -target-cpu sm_53 -target-feature +ptx42 -fcuda-is-device \
+// RUN:   -fnative-half-type -S -emit-llvm -o - -x cuda %s \
+// RUN:   | FileCheck -check-prefix=CHECK -check-prefix=CHECK_PTX42_SM53 %s
+
 #define __device__ __attribute__((device))
 
 // CHECK-LABEL: nvvm_min_max_sm80
@@ -62,6 +72,52 @@ __device__ void nvvm_min_max_sm80() {
   // CHECK: ret void
 }
 
+// CHECK-LABEL:

[clang] 510fd28 - [NVPTX] Add ex2.approx.f16/f16x2 support

2022-03-01 Thread Artem Belevich via cfe-commits

Author: Nicolas Miller
Date: 2022-03-01T11:07:11-08:00
New Revision: 510fd283fda2d7c5118ae1b451a1f2365cfc3f27

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

LOG: [NVPTX] Add ex2.approx.f16/f16x2 support

NOTE: this is a follow-up commit with the missing clang-side changes.

This patch adds builtins and intrinsics for the f16 and f16x2 variants of the 
ex2
instruction.

These two variants were added in PTX7.0, and are supported by sm_75 and above.

Note that this isn't wired with the exp2 llvm intrinsic because the ex2
instruction is only available in its approx variant.

Running ptxas on the assembly generated by the test f16-ex2.ll works as
expected.

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsNVPTX.def
clang/test/CodeGen/builtins-nvptx-native-half-type.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index a058925a6a5f6..04bed16c9958e 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -282,6 +282,8 @@ BUILTIN(__nvvm_saturate_d, "dd", "")
 BUILTIN(__nvvm_ex2_approx_ftz_f, "ff", "")
 BUILTIN(__nvvm_ex2_approx_f, "ff", "")
 BUILTIN(__nvvm_ex2_approx_d, "dd", "")
+TARGET_BUILTIN(__nvvm_ex2_approx_f16, "hh", "", AND(SM_75, PTX70))
+TARGET_BUILTIN(__nvvm_ex2_approx_f16x2, "V2hV2h", "", AND(SM_75, PTX70))
 
 BUILTIN(__nvvm_lg2_approx_ftz_f, "ff", "")
 BUILTIN(__nvvm_lg2_approx_f, "ff", "")

diff  --git a/clang/test/CodeGen/builtins-nvptx-native-half-type.c 
b/clang/test/CodeGen/builtins-nvptx-native-half-type.c
index c232c4de5640a..95021f274cd0f 100644
--- a/clang/test/CodeGen/builtins-nvptx-native-half-type.c
+++ b/clang/test/CodeGen/builtins-nvptx-native-half-type.c
@@ -1,4 +1,9 @@
 // REQUIRES: nvptx-registered-target
+//
+// RUN: %clang_cc1 -ffp-contract=off -triple nvptx-unknown-unknown -target-cpu 
\
+// RUN:   sm_75 -target-feature +ptx70 -fcuda-is-device -fnative-half-type -S \
+// RUN:   -emit-llvm -o - -x cuda %s \
+// RUN:   | FileCheck -check-prefix=CHECK -check-prefix=CHECK_PTX70_SM75 %s
 
 // RUN: %clang_cc1 -ffp-contract=off -triple nvptx-unknown-unknown -target-cpu 
\
 // RUN:   sm_80 -target-feature +ptx70 -fcuda-is-device -fnative-half-type -S \
@@ -32,6 +37,16 @@
 
 #define __device__ __attribute__((device))
 
+__device__ void nvvm_ex2_sm75() {
+#if __CUDA_ARCH__ >= 750
+  // CHECK_PTX70_SM75: call half @llvm.nvvm.ex2.approx.f16
+  __nvvm_ex2_approx_f16(0.1f16);
+  // CHECK_PTX70_SM75: call <2 x half> @llvm.nvvm.ex2.approx.f16x2
+  __nvvm_ex2_approx_f16x2({0.1f16, 0.7f16});
+#endif
+  // CHECK: ret void
+}
+
 // CHECK-LABEL: nvvm_min_max_sm80
 __device__ void nvvm_min_max_sm80() {
 #if __CUDA_ARCH__ >= 800



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


  1   2   >