[PATCH] D61627: [clang driver] Allow -fembed-bitcode combined with -mno-red-zone

2019-05-06 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: steven_wu, compnerd, rsmith.
wanders added a project: clang.
Herald added a subscriber: dexonsmith.

The -mno-red-zone (and the option to cancel it out: -mred-zone) were not
allowed to be combined with -fembed-bitcode. However this option has a
direct effect on the generated bitcode as it adds the 'noredzone'
attribute on all functions. This means it is propagated into the
embedded bitcode and it is possible to regenerate the same object from
the embedded bitcode. Therefore there is no reason to forbid it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61627

Files:
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3674,8 +3674,6 @@
 options::OPT_ffixed_x18,
 options::OPT_mglobal_merge,
 options::OPT_mno_global_merge,
-options::OPT_mred_zone,
-options::OPT_mno_red_zone,
 options::OPT_Wa_COMMA,
 options::OPT_Xassembler,
 options::OPT_mllvm,


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3674,8 +3674,6 @@
 options::OPT_ffixed_x18,
 options::OPT_mglobal_merge,
 options::OPT_mno_global_merge,
-options::OPT_mred_zone,
-options::OPT_mno_red_zone,
 options::OPT_Wa_COMMA,
 options::OPT_Xassembler,
 options::OPT_mllvm,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61627: [clang driver] Allow -fembed-bitcode combined with -mno-red-zone

2019-05-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

But running code that has been compiled with `-mno-red-zone` on a platform that 
guarantees that redzones are not stamped on should be fine as far as I can 
understand?

The red zone is that the platform guarantees that it (e.g signal handlers, 
interrupts) will not use some memory outside of current stack pointer, so that 
a program can use that stack memory without adjusting the stackpointer. When 
compiling with `-mno-red-zone` the program will not use that but instead always 
adjust the stack pointer.  So compiling an application with `-mno-red-zone` on 
a platform which allows red-zone usage will just cause some extra stack pointer 
adjustments, but not real ABI problems?On the other hand, compiling with 
`-mred-zone` (default) on a system that does not allow red-zone will risk 
strange corruptions when program has put data on stack without adjusting 
stackpointer and a signal/interrupt arrives.

If my reasoning there happens to be correct I think that `-mno-red-zone` should 
be safe to lift of the blacklist, but `-mred-zone` should be kept on the black 
list (at least if there is/can be such a thing as a platform where 
`-mno-red-zone` is the default)

I think this is similar to `-mno-implicit-float` which _is_ allowed to combined 
with `-fembed-bitcode`. One could easily envision a platform where fpu 
registers are not preserved on signal/interrupts. And then `-mimplicit-float` 
would be broken. However using `-mno-implicit-float` on a platform where the 
they are preserved is fine (except for possible performance loss).

I'm also a bit unsure about exact reasons for putting things in the blacklist. 
I'd also like to remove `-mcmodel=` from the blacklist. So maybe I should start 
a separate thread on cfe-dev on this for a more general discussion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61627



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


[PATCH] D61627: [clang driver] Allow -fembed-bitcode combined with -mno-red-zone

2019-05-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

> Why are you interested in expending this list?

I have a (kernel) that is compiled with `-mno-red-zone` and `-mcmodel=large` 
which I want to compile with `-fembed-bitcode` for a debugging tool that needs 
the bitcode.

But I can carry these patches locally for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61627



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


[PATCH] D61627: [clang driver] Allow -fembed-bitcode combined with -mno-red-zone

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders abandoned this revision.
wanders added a comment.

I might revisit this later. But carrying this patch locally for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61627



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


[PATCH] D68568: [clang-format] Make '.clang-format' variants finding a loop

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: clang-format.
wanders added a project: clang-format.
Herald added a project: clang.

No functional change intended


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68568

Files:
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,34 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
-
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == 
llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on 
Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
   Status = FS->status(ConfigFile.str());
-  FoundConfigFile = Status && (Status->getType() ==
-   llvm::sys::fs::file_type::regular_file);
-}
 
-if (FoundConfigFile) {
-  llvm::ErrorOr> Text =
-  FS->getBufferForFile(ConfigFile.str());
-  if (std::error_code EC = Text.getError())
-return make_string_error(EC.message());
-  if (std::error_code ec =
-  parseConfiguration(Text.get()->getBuffer(), &Style)) {
-if (ec == ParseError::Unsuitable) {
-  if (!UnsuitableConfigFiles.empty())
-UnsuitableConfigFiles.append(", ");
-  UnsuitableConfigFiles.append(ConfigFile);
-  continue;
+  if (Status && (Status->getType() == 
llvm::sys::fs::file_type::regular_file)) {
+llvm::ErrorOr> Text =
+FS->getBufferForFile(ConfigFile.str());
+if (std::error_code EC = Text.getError())
+  return make_string_error(EC.message());
+if (std::error_code ec =
+parseConfiguration(Text.get()->getBuffer(), &Style)) {
+  if (ec == ParseError::Unsuitable) {
+if (!UnsuitableConfigFiles.empty())
+  UnsuitableConfigFiles.append(", ");
+UnsuitableConfigFiles.append(ConfigFile);
+continue;
+  }
+  return make_string_error("Error reading " + ConfigFile + ": " +
+   ec.message());
 }
-return make_string_error("Error reading " + ConfigFile + ": " +
- ec.message());
+LLVM_DEBUG(llvm::dbgs()
+   << "Using configuration file " << ConfigFile << "\n");
+return Style;
   }
-  LLVM_DEBUG(llvm::dbgs()
- << "Using configuration file " << ConfigFile << "\n");
-  return Style;
 }
   }
   if (!UnsuitableConfigFiles.empty())


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,34 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
-
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
   Status = FS->status(ConfigFile.str());
-  FoundConfigFile = Status && (Status->getType() ==
-  

[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: clang-format.
wanders added a project: clang-format.
Herald added a project: clang.

E.g: When formatting foo.cpp it will look for .cpp.clang-format

  

This makes it easy to different formatting for .c/.h files and
.cpp/.hpp files within the same directories.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68569

Files:
  clang/docs/ClangFormat.rst
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2601,6 +2601,11 @@
 return make_string_error(EC.message());
 
   llvm::SmallVector FilesToLookFor;
+
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());
+  }
   FilesToLookFor.push_back(".clang-format");
   FilesToLookFor.push_back("_clang-format");
 
Index: clang/docs/ClangFormat.rst
===
--- clang/docs/ClangFormat.rst
+++ clang/docs/ClangFormat.rst
@@ -82,8 +82,10 @@
 
 When the desired code formatting style is different from the available options,
 the style can be customized using the ``-style="{key: value, ...}"`` option or
-by putting your style configuration in the ``.clang-format`` or 
``_clang-format``
-file in your project's directory and using ``clang-format -style=file``.
+by putting your style configuration a file named ``.{ext}.clang-format`` 
(``{ext}``
+is the file name extension, e.g. ``.cpp.clang-format`` is the formatted file
+is named ``something.cpp``), ``.clang-format`` or ``_clang-format`` in your
+project's directory and using ``clang-format -style=file``.
 
 An easy way to create the ``.clang-format`` file is:
 


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2601,6 +2601,11 @@
 return make_string_error(EC.message());
 
   llvm::SmallVector FilesToLookFor;
+
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());
+  }
   FilesToLookFor.push_back(".clang-format");
   FilesToLookFor.push_back("_clang-format");
 
Index: clang/docs/ClangFormat.rst
===
--- clang/docs/ClangFormat.rst
+++ clang/docs/ClangFormat.rst
@@ -82,8 +82,10 @@
 
 When the desired code formatting style is different from the available options,
 the style can be customized using the ``-style="{key: value, ...}"`` option or
-by putting your style configuration in the ``.clang-format`` or ``_clang-format``
-file in your project's directory and using ``clang-format -style=file``.
+by putting your style configuration a file named ``.{ext}.clang-format`` (``{ext}``
+is the file name extension, e.g. ``.cpp.clang-format`` is the formatted file
+is named ``something.cpp``), ``.clang-format`` or ``_clang-format`` in your
+project's directory and using ``clang-format -style=file``.
 
 An easy way to create the ``.clang-format`` file is:
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

This depends on https://reviews.llvm.org/D68568


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

The "Language" option can not distinguish between C and C++.

We have projects which contains both C and C++ code. Using different style 
(yes..) for C and C++.  Our C++ headers are named hpp.

In our toplevel we have the following symlinks
.c.clang-format -> clang-format/c.clang-format
.h.clang-format -> clang-format/c.clang-format
.cpp.clang-format -> clang-format/cpp.clang-format
.hpp.clang-format -> clang-format/cpp.clang-format

Before this we had a horrible wrapper script that used cd into different 
directories depending on extension, and those directories had different 
.clang-format files, and then had to run clang-format from stdin.

An alternative implementation I did consider was to add some kind of path 
matching in the configuration file doing multiple yaml documents in the 
configuration file. So in my case it would be something like:

  ---
  Language: Cpp
  IndentWidth: 4
  TabWidth: 4
  MoreStuff...
  ---
  PathMatch: [ *.cpp, *.hpp ]
  SpaceBeforeParen: ControlStatements
  ---
  PathMatch [ *.c, *.h ]
  SpaceBeforeParen: Never
  ---


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D84090: [clang-format] Add SpaceAroundBitFieldColon option

2020-07-18 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: MyDeveloperDay, klimek.
wanders added a project: clang-format.
Herald added a project: clang.

  

  This new option allows controlling if there should be spaces around
  the ':' in a bitfield declaration.
  
  Decides if it should be the existing (and therefore default with the
  new option) behavior:
  
unsigned bitfield : 5;   // SpaceAroundBitFieldColon = true
  
  or:
  
unsigned bitfield:5; // SpaceAroundBitFieldColon = false





A bit unsure about naming of the option.   Should there be separate 
Before/After?   I guess some might find `uint x :1` and `uint x: 1` useful.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84090

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2165,6 +2165,13 @@
"  uchar : 8;\n"
"  uchar other;\n"
"};");
+  FormatStyle LLVMWithNoSpaceAroundBitfields = getLLVMStyle();
+  LLVMWithNoSpaceAroundBitfields.SpaceAroundBitFieldColon = false;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass:8;\n"
+   "  unsigned ValueKind:2;\n"
+   "  uchar other;\n"
+   "};", LLVMWithNoSpaceAroundBitfields);
 }
 
 TEST_F(FormatTest, FormatsNamespaces) {
@@ -12156,6 +12163,11 @@
"int   oneTwoThree : 23 = 0;",
Alignment);
 
+  Alignment.SpaceAroundBitFieldColon = false;
+  verifyFormat("int const a  :5;\n"
+   "int   oneTwoThree:23;",
+   Alignment);
+
   // Known limitations: ':' is only recognized as a bitfield colon when
   // followed by a number.
   /*
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3251,6 +3251,8 @@
   if (Right.is(TT_RangeBasedForLoopColon) &&
   !Style.SpaceBeforeRangeBasedForLoopColon)
 return false;
+  if (Left.is(TT_BitFieldColon))
+return Style.SpaceAroundBitFieldColon;
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
@@ -3267,6 +3269,8 @@
   return false;
 if (Right.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_BitFieldColon))
+  return Style.SpaceAroundBitFieldColon;
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -593,6 +593,8 @@
 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
 IO.mapOptional("SpaceBeforeSquareBrackets",
Style.SpaceBeforeSquareBrackets);
+IO.mapOptional("SpaceAroundBitFieldColon",
+   Style.SpaceAroundBitFieldColon);
 IO.mapOptional("Standard", Style.Standard);
 IO.mapOptional("StatementMacros", Style.StatementMacros);
 IO.mapOptional("TabWidth", Style.TabWidth);
@@ -918,6 +920,7 @@
   LLVMStyle.SpaceBeforeAssignmentOperators = true;
   LLVMStyle.SpaceBeforeCpp11BracedList = false;
   LLVMStyle.SpaceBeforeSquareBrackets = false;
+  LLVMStyle.SpaceAroundBitFieldColon = true;
   LLVMStyle.SpacesInAngles = false;
   LLVMStyle.SpacesInConditionalStatement = false;
 
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -2228,6 +2228,13 @@
   /// \endcode
   bool SpaceBeforeSquareBrackets;
 
+  /// If ``false``, space will be removed around ``:`` in bitfield 
declarations.
+  /// \code
+  ///true:  false:
+  ///unsigned bf : 3;  vs.  unsigned bf:3;
+  /// \endcode
+  bool SpaceAroundBitFieldColon;
+
   /// Supported language standards for parsing and formatting C++ constructs.
   /// \code
   ///Latest:vector>
@@ -2404,6 +2411,7 @@
SpacesInParentheses == R.SpacesInParentheses &&
SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
+   SpaceAroundBitFieldColon == R.SpaceAroundBitFieldColon &&
Standard == R.Standard && TabWidth == R.TabWidth &&
StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;


Index: clang/unittests/Format/FormatTest.cpp
==

[PATCH] D84103: [clang-format] Make sure rst documentation matches comments

2020-07-18 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: MyDeveloperDay, JakeMerdichAMD.
wanders added a project: clang-format.
Herald added a project: clang.

  clang/docs/tools/dump_format_style.py is used to read the comments
  from clang/include/clang/Format/Format.h and update the contents of
  clang/docs/ClangFormatStyleOptions.rst
  
  Recent changes made these out of date. This commit syncs them by
  folding the improved wording back to the comments and then
  regenerating the rst file.

https://github.com/wanders/llvm-project/commit/148dd6d805a3429fef4973a5fb0a217b2ffeda32


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84103

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -1425,15 +1425,20 @@
   /// For example: TESTSUITE
   std::vector NamespaceMacros;
 
-  /// A vector of macros which are whitespace-sensitive and shouldn't be
-  /// touched.
+  /// A vector of macros which are whitespace-sensitive and should not
+  /// be touched.
   ///
   /// These are expected to be macros of the form:
   /// \code
   ///   STRINGIZE(...)
   /// \endcode
   ///
-  /// For example: STRINGIZE
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
+  /// \endcode
+  ///
+  /// For example: BOOST_PP_STRINGIZE
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2694,8 +2694,11 @@
 Use tabs whenever we need to fill whitespace that spans at least from
 one tab stop to the next one.
 
+
+
 **WhitespaceSensitiveMacros** (``std::vector``)
-  A vector of macros which are whitespace-sensitive and should not be touched.
+  A vector of macros which are whitespace-sensitive and should not
+  be touched.
 
   These are expected to be macros of the form:
 
@@ -2709,9 +2712,7 @@
 
 WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
 
-  For example: BOOST_PP_STRINGIZE.
-
-
+  For example: BOOST_PP_STRINGIZE
 
 .. END_FORMAT_STYLE_OPTIONS
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -1425,15 +1425,20 @@
   /// For example: TESTSUITE
   std::vector NamespaceMacros;
 
-  /// A vector of macros which are whitespace-sensitive and shouldn't be
-  /// touched.
+  /// A vector of macros which are whitespace-sensitive and should not
+  /// be touched.
   ///
   /// These are expected to be macros of the form:
   /// \code
   ///   STRINGIZE(...)
   /// \endcode
   ///
-  /// For example: STRINGIZE
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
+  /// \endcode
+  ///
+  /// For example: BOOST_PP_STRINGIZE
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2694,8 +2694,11 @@
 Use tabs whenever we need to fill whitespace that spans at least from
 one tab stop to the next one.
 
+
+
 **WhitespaceSensitiveMacros** (``std::vector``)
-  A vector of macros which are whitespace-sensitive and should not be touched.
+  A vector of macros which are whitespace-sensitive and should not
+  be touched.
 
   These are expected to be macros of the form:
 
@@ -2709,9 +2712,7 @@
 
 WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
 
-  For example: BOOST_PP_STRINGIZE.
-
-
+  For example: BOOST_PP_STRINGIZE
 
 .. END_FORMAT_STYLE_OPTIONS
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84103: [clang-format] Make sure rst documentation matches comments

2020-07-18 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6d7ec54170f9: [clang-format] Make sure rst documentation 
matches comments (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84103

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -1425,15 +1425,20 @@
   /// For example: TESTSUITE
   std::vector NamespaceMacros;
 
-  /// A vector of macros which are whitespace-sensitive and shouldn't be
-  /// touched.
+  /// A vector of macros which are whitespace-sensitive and should not
+  /// be touched.
   ///
   /// These are expected to be macros of the form:
   /// \code
   ///   STRINGIZE(...)
   /// \endcode
   ///
-  /// For example: STRINGIZE
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
+  /// \endcode
+  ///
+  /// For example: BOOST_PP_STRINGIZE
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2694,8 +2694,11 @@
 Use tabs whenever we need to fill whitespace that spans at least from
 one tab stop to the next one.
 
+
+
 **WhitespaceSensitiveMacros** (``std::vector``)
-  A vector of macros which are whitespace-sensitive and should not be touched.
+  A vector of macros which are whitespace-sensitive and should not
+  be touched.
 
   These are expected to be macros of the form:
 
@@ -2709,9 +2712,7 @@
 
 WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
 
-  For example: BOOST_PP_STRINGIZE.
-
-
+  For example: BOOST_PP_STRINGIZE
 
 .. END_FORMAT_STYLE_OPTIONS
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -1425,15 +1425,20 @@
   /// For example: TESTSUITE
   std::vector NamespaceMacros;
 
-  /// A vector of macros which are whitespace-sensitive and shouldn't be
-  /// touched.
+  /// A vector of macros which are whitespace-sensitive and should not
+  /// be touched.
   ///
   /// These are expected to be macros of the form:
   /// \code
   ///   STRINGIZE(...)
   /// \endcode
   ///
-  /// For example: STRINGIZE
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
+  /// \endcode
+  ///
+  /// For example: BOOST_PP_STRINGIZE
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2694,8 +2694,11 @@
 Use tabs whenever we need to fill whitespace that spans at least from
 one tab stop to the next one.
 
+
+
 **WhitespaceSensitiveMacros** (``std::vector``)
-  A vector of macros which are whitespace-sensitive and should not be touched.
+  A vector of macros which are whitespace-sensitive and should not
+  be touched.
 
   These are expected to be macros of the form:
 
@@ -2709,9 +2712,7 @@
 
 WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
 
-  For example: BOOST_PP_STRINGIZE.
-
-
+  For example: BOOST_PP_STRINGIZE
 
 .. END_FORMAT_STYLE_OPTIONS
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84090: [clang-format] Add SpaceAroundBitFieldColon option

2020-07-18 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 279010.
wanders added a comment.

- Regenerated rst
- Fixed clang format errors
- Added release note
- Added bool parsing test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84090

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2165,6 +2165,14 @@
"  uchar : 8;\n"
"  uchar other;\n"
"};");
+  FormatStyle LLVMWithNoSpaceAroundBitfields = getLLVMStyle();
+  LLVMWithNoSpaceAroundBitfields.SpaceAroundBitFieldColon = false;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass:8;\n"
+   "  unsigned ValueKind:2;\n"
+   "  uchar other;\n"
+   "};",
+   LLVMWithNoSpaceAroundBitfields);
 }
 
 TEST_F(FormatTest, FormatsNamespaces) {
@@ -12156,6 +12164,11 @@
"int   oneTwoThree : 23 = 0;",
Alignment);
 
+  Alignment.SpaceAroundBitFieldColon = false;
+  verifyFormat("int const a  :5;\n"
+   "int   oneTwoThree:23;",
+   Alignment);
+
   // Known limitations: ':' is only recognized as a bitfield colon when
   // followed by a number.
   /*
@@ -13685,6 +13698,7 @@
   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
+  CHECK_PARSE_BOOL(SpaceAroundBitFieldColon);
   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3251,6 +3251,8 @@
   if (Right.is(TT_RangeBasedForLoopColon) &&
   !Style.SpaceBeforeRangeBasedForLoopColon)
 return false;
+  if (Left.is(TT_BitFieldColon))
+return Style.SpaceAroundBitFieldColon;
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
@@ -3267,6 +3269,8 @@
   return false;
 if (Right.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_BitFieldColon))
+  return Style.SpaceAroundBitFieldColon;
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -593,6 +593,7 @@
 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
 IO.mapOptional("SpaceBeforeSquareBrackets",
Style.SpaceBeforeSquareBrackets);
+IO.mapOptional("SpaceAroundBitFieldColon", Style.SpaceAroundBitFieldColon);
 IO.mapOptional("Standard", Style.Standard);
 IO.mapOptional("StatementMacros", Style.StatementMacros);
 IO.mapOptional("TabWidth", Style.TabWidth);
@@ -918,6 +919,7 @@
   LLVMStyle.SpaceBeforeAssignmentOperators = true;
   LLVMStyle.SpaceBeforeCpp11BracedList = false;
   LLVMStyle.SpaceBeforeSquareBrackets = false;
+  LLVMStyle.SpaceAroundBitFieldColon = true;
   LLVMStyle.SpacesInAngles = false;
   LLVMStyle.SpacesInConditionalStatement = false;
 
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -2233,6 +2233,13 @@
   /// \endcode
   bool SpaceBeforeSquareBrackets;
 
+  /// If ``true``, space will be inserted around ``:`` in bitfield declarations.
+  /// \code
+  ///true:  false:
+  ///unsigned bf : 3;  vs.  unsigned bf:3;
+  /// \endcode
+  bool SpaceAroundBitFieldColon;
+
   /// Supported language standards for parsing and formatting C++ constructs.
   /// \code
   ///Latest:vector>
@@ -2409,6 +2416,7 @@
SpacesInParentheses == R.SpacesInParentheses &&
SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
+   SpaceAroundBitFieldColon == R.SpaceAroundBitFieldColon &&
Standard == R.Standard && TabWidth == R.TabWidth &&
StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;
Index: clang/docs/ReleaseNotes.rst
===

[PATCH] D84090: [clang-format] Add SpaceAroundBitFieldColon option

2020-07-18 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders marked an inline comment as done.
wanders added a comment.

In D84090#2160411 , @curdeius wrote:

> The changes look good to me in general. I share your doubt though about 
> whether a bool flag is sufficient here. We've seen in the past a few times 
> that at some time a false/true flag is not enough. I'd rather go for a 
> Before/After/Both/None flag (or similar, naming probably should be coherent 
> with other flags). But I'm not really aware of the projects/coding styles 
> that use bit fields. Maybe a small research on this would be good to confirm 
> or infirm a necessity of higher complexity.


Did some basic research in repos I happened to have.

Here I call the different styles:  "Neither" - no spaces around colon. "Both" 
space on both sides. "Left" space on left side only. "Right" space on right 
side only. ("Right" is of course subject to AlignConsecutiveBitField, so if 
alignment requires there to be spaces there will be space).

In summary - in the projects I looked at - the uses doesn't seem to be very 
consistent, can even use different styles within same struct. Most projects 
mixes "Both" and "Neither".  "Right" doesn't really seem to be used - it seems 
to be typos when it is.  "Left" is used in some cases when there are aligment 
for consecutive lines. (keep in mind that there almost always is consecutive 
lines,  a single bitfield in a struct seldom makes any sense)..

There was one case in musl that really made me smile.  `include/arpa/nameser.h` 
struct HEADER has different bitfield members depending on endianness,  for big 
endian it uses "Right" and little endian it uses "Left".  ( 
https://git.musl-libc.org/cgit/musl/tree/include/arpa/nameser.h#n324 )

My guess is that no project's coding style document really specifies this 
detail (except implicitly for projects where the style is defined as "whatever 
clang-format says").

But I think the conclusion is that it probably should be more that true/false.  
Pondering about doing it in steps, so first just `BitFieldColonSpacing` with 
values `Both` and `Neither` (i.e same functionality as in current patch) and 
then add `Before` as an additional option.

- qemu
  - mixing "Both" and "Neither"

- emacs
  - mixing "Both" and "Neither"

- git
  - mixing "Both" and "Neither"

- linux kernel
  - mixing "Both" and "Neither"
  - (also has a bunch of "unsigned x:1, y:2, z:3", which is interesting and 
seems to be missing tests for clang-format)
  - Has consecutive aligned variants

- gnupg
  - mixing "Both" and "Neither"
  - but mostly "Neither"
  - Also has one "Right": `agent/agent.h:int raw_value: 1;`

- lwip
  - Mostly "Left" combined with aligned consecutive
  - Some "Both"

- intel-pcm
  - "Both"

- syslog-ng
  - "Neither"

- busybox
  - "Left" combined with aligned consecutive

- glibc
  - mixing "Both" and "Neither"

- gcc
  - mixing "Both" and "Neither"  (mostly "Both")


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84090



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


[PATCH] D84090: [clang-format] Add BitFieldColonSpacing option

2020-07-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 279237.
wanders retitled this revision from "[clang-format] Add 
SpaceAroundBitFieldColon option" to "[clang-format] Add BitFieldColonSpacing 
option".
wanders edited the summary of this revision.
wanders added a comment.

Renamed option to "BitFieldColonSpacing" and made it an enum of: "Both", 
"None," "Before", "After"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84090

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2165,6 +2165,34 @@
"  uchar : 8;\n"
"  uchar other;\n"
"};");
+  FormatStyle Style = getLLVMStyle();
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass:8;\n"
+   "  unsigned ValueKind:2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  verifyFormat("struct A {\n"
+   "  int a:1,\n"
+   "  b:2;\n"
+   "};",
+	   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass :8;\n"
+   "  unsigned ValueKind :2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass: 8;\n"
+   "  unsigned ValueKind: 2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+
 }
 
 TEST_F(FormatTest, FormatsNamespaces) {
@@ -12156,6 +12184,21 @@
"int   oneTwoThree : 23 = 0;",
Alignment);
 
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("int const a  :5;\n"
+   "int   oneTwoThree:23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("int const a   :5;\n"
+   "int   oneTwoThree :23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("int const a  : 5;\n"
+   "int   oneTwoThree: 23;",
+   Alignment);
+
   // Known limitations: ':' is only recognized as a bitfield colon when
   // followed by a number.
   /*
@@ -14004,6 +14047,16 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
+  FormatStyle::BFCS_Both);
+  CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
+  FormatStyle::BFCS_None);
+  CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
+  FormatStyle::BFCS_Before);
+  CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
+  FormatStyle::BFCS_After);
+
   // FIXME: This is required because parsing a configuration simply overwrites
   // the first N elements of the list instead of resetting it.
   Style.ForEachMacros.clear();
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3251,6 +3251,8 @@
   if (Right.is(TT_RangeBasedForLoopColon) &&
   !Style.SpaceBeforeRangeBasedForLoopColon)
 return false;
+  if (Left.is(TT_BitFieldColon))
+return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
@@ -3267,6 +3269,8 @@
   return false;
 if (Right.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_BitFieldColon))
+  return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -366,6 +366,15 @@
   }
 };
 
+template <> struct ScalarEnumerationTraits {
+  static void enumeration(IO &IO, FormatStyle::BitFieldColonSpacingStyle &Value) {
+ 

[PATCH] D84090: [clang-format] Add BitFieldColonSpacing option

2020-07-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 279279.

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

https://reviews.llvm.org/D84090

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2165,6 +2165,33 @@
"  uchar : 8;\n"
"  uchar other;\n"
"};");
+  FormatStyle Style = getLLVMStyle();
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass:8;\n"
+   "  unsigned ValueKind:2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  verifyFormat("struct A {\n"
+   "  int a:1,\n"
+   "  b:2;\n"
+   "};",
+   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass :8;\n"
+   "  unsigned ValueKind :2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass: 8;\n"
+   "  unsigned ValueKind: 2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsNamespaces) {
@@ -12156,6 +12183,21 @@
"int   oneTwoThree : 23 = 0;",
Alignment);
 
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("int const a  :5;\n"
+   "int   oneTwoThree:23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("int const a   :5;\n"
+   "int   oneTwoThree :23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("int const a  : 5;\n"
+   "int   oneTwoThree: 23;",
+   Alignment);
+
   // Known limitations: ':' is only recognized as a bitfield colon when
   // followed by a number.
   /*
@@ -14004,6 +14046,16 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
+  FormatStyle::BFCS_Both);
+  CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
+  FormatStyle::BFCS_None);
+  CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
+  FormatStyle::BFCS_Before);
+  CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
+  FormatStyle::BFCS_After);
+
   // FIXME: This is required because parsing a configuration simply overwrites
   // the first N elements of the list instead of resetting it.
   Style.ForEachMacros.clear();
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3251,6 +3251,9 @@
   if (Right.is(TT_RangeBasedForLoopColon) &&
   !Style.SpaceBeforeRangeBasedForLoopColon)
 return false;
+  if (Left.is(TT_BitFieldColon))
+return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+   Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
@@ -3267,6 +3270,9 @@
   return false;
 if (Right.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_BitFieldColon))
+  return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+ Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -366,6 +366,17 @@
   }
 };
 
+template <>
+struct ScalarEnumerationTraits {
+  static void enumeration(IO &IO,
+  FormatStyle::BitFieldColonSpacingStyle &Value) {
+IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
+IO.enumCase(Value, "None", FormatStyle::BFCS_None);
+IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
+IO.enumCase(Value, "After", FormatStyle::BFCS_After);
+  }
+};
+
 template <> struct MappingTraits {
   static void ma

[PATCH] D84090: [clang-format] Add BitFieldColonSpacing option

2020-07-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D84090#2162389 , @MyDeveloperDay 
wrote:

> 2. then I can do `git clang-format`, this will fix up any files in the diff 
> that need formatting (you'll need to git add them again if they have)


(I use https://github.com/kimgr/git-format )  just need to remember to run 
it...  But created a "prepare-patch" script now so as long as I remember to run 
that.

> 
> 
> 3. I then check the documentation builds with `/usr/bin/sphinx-build -n 
> ./docs ./html`  (if the review contains rst files)

Great tip! Thanks

> 
> 
> 4. then I do  `git diff --cached -U99 > patch_to_submitt.diff`
> 5. I check the patch to ensure I'm not changing the mode of the files with 
> `grep -A0 -B2 "new mode" patch_to_submitt.diff`
> 6. and this is the patch_tosubmitt.diff I upload to the review
> 
>   These steps try to reduce the number of review fails I get based on 
> clang-format issues (all of this is scripted so making a patch is repeatable, 
> quick and easy and all based off whats in my staged area)

Thanks for assistance and review. And sorry about the extra noise.


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

https://reviews.llvm.org/D84090



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


[PATCH] D84090: [clang-format] Add BitFieldColonSpacing option

2020-07-20 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG52ab7aa0ba5a: [clang-format] Add BitFieldColonSpacing option 
(authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84090

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2165,6 +2165,33 @@
"  uchar : 8;\n"
"  uchar other;\n"
"};");
+  FormatStyle Style = getLLVMStyle();
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass:8;\n"
+   "  unsigned ValueKind:2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  verifyFormat("struct A {\n"
+   "  int a:1,\n"
+   "  b:2;\n"
+   "};",
+   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass :8;\n"
+   "  unsigned ValueKind :2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("struct Bitfields {\n"
+   "  unsigned sClass: 8;\n"
+   "  unsigned ValueKind: 2;\n"
+   "  uchar other;\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsNamespaces) {
@@ -12156,6 +12183,21 @@
"int   oneTwoThree : 23 = 0;",
Alignment);
 
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  verifyFormat("int const a  :5;\n"
+   "int   oneTwoThree:23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
+  verifyFormat("int const a   :5;\n"
+   "int   oneTwoThree :23;",
+   Alignment);
+
+  Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
+  verifyFormat("int const a  : 5;\n"
+   "int   oneTwoThree: 23;",
+   Alignment);
+
   // Known limitations: ':' is only recognized as a bitfield colon when
   // followed by a number.
   /*
@@ -14004,6 +14046,16 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
+  CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
+  FormatStyle::BFCS_Both);
+  CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
+  FormatStyle::BFCS_None);
+  CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
+  FormatStyle::BFCS_Before);
+  CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
+  FormatStyle::BFCS_After);
+
   // FIXME: This is required because parsing a configuration simply overwrites
   // the first N elements of the list instead of resetting it.
   Style.ForEachMacros.clear();
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3251,6 +3251,9 @@
   if (Right.is(TT_RangeBasedForLoopColon) &&
   !Style.SpaceBeforeRangeBasedForLoopColon)
 return false;
+  if (Left.is(TT_BitFieldColon))
+return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+   Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
@@ -3267,6 +3270,9 @@
   return false;
 if (Right.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_BitFieldColon))
+  return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
+ Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -366,6 +366,17 @@
   }
 };
 
+template <>
+struct ScalarEnumerationTraits {
+  static void enumeration(IO &IO,
+  FormatStyle::BitFieldColonSpacingStyle &Value) {
+IO.enumCase(Value, "Both", FormatStyle:

[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2020-05-08 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders abandoned this revision.
wanders added a comment.

In D68569#2019895 , @MyDeveloperDay 
wrote:

> Can we abandon this review now we have the style=file:?


Yes, lets abandon this.




Comment at: clang/lib/Format/Format.cpp:2606
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());

MyDeveloperDay wrote:
> if Extension is a std::string useif (!Extension.empty())
It is a StringRef  (`StringRef llvm::sys::path::extension(StringRef path)`)  
but that also has `empty()`, thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D125974: [clang] Limit bitcode option ignorelist to Darwin

2022-05-19 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:4760-4762
 // reject options that shouldn't be supported in bitcode
 // also reject kernel/kext
 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {

This comment and variable name are not as accurate any longer.  Maybe moving it 
inside `if (RawTriple.isOSDarwin())` makes it clearer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125974

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


[PATCH] D125961: [clang-format] Don't break lines after pragma region

2022-05-19 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

There are other pragmas which include colon. How do they fare?

Example https://docs.microsoft.com/en-us/cpp/preprocessor/warning?view=msvc-170

  #pragma warning( disable : 4507 34; once : 4385; error : 164 )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125961

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


[PATCH] D125974: [clang] Limit bitcode option ignorelist to Darwin

2022-05-24 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

This looks sensible to me. But I'm not an expert in the area (and still not 
100% clear on the purpose of the ignorelist) so can't really say if the added 
comments captures the intent accurately.




Comment at: clang/test/Driver/embed-bitcode-elf.c:1
+// RUN: %clang -c -target aarch64-linux-android21 %s -fembed-bitcode -o %t.o \
+// RUN: -ffunction-sections -fdata-sections -fstack-protector-strong

Should this test have a `// REQUIRES: aarch64-registered-target`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125974

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


[PATCH] D101139: Create install targets for scan-build-py.

2021-05-13 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D101139#2743346 , @aabbaabb wrote:

> Renamed lib to libexec and add custom rules to copy files to build output.

That rename was a bit too fast I think.
I would expect the libraries (libear & libscanbuild) to be in lib/.
The internal wrappers analyze-c++,analyze-cc,intercept-c++,intercept-cc to be 
installed in libexec.
And finally analyze-build, intercept-build, scan-build which are the commands 
user can execute to be installed in bin/

(I have picked up this patch in our internal toolchain as it gives us a way to 
generate compilation databases out of the box. It works fine here)


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

https://reviews.llvm.org/D101139

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


[PATCH] D101139: Create install targets for scan-build-py.

2021-06-09 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

I think this looks good. I can't vouch for the cmake changes.

However there seems like diff is based on something that already has moved 
parts into libexec. It doesn't apply cleanly here - and buildkite seems to 
complain too. Make sure you have the complete diff.


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

https://reviews.llvm.org/D101139

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


[PATCH] D126974: [scan-build-py] Fix exception on shutdown with sarif-html output format

2022-06-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 435999.
wanders added a comment.

Updated patch with full context.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126974

Files:
  clang/tools/scan-build-py/lib/libscanbuild/analyze.py


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126974: [scan-build-py] Fix exception on shutdown with sarif-html output format

2022-06-10 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGff4abe755279: [scan-build-py] Fix exception on shutdown with 
sarif-html output format (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126974

Files:
  clang/tools/scan-build-py/lib/libscanbuild/analyze.py


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127201: [clang] Add tests for statement expression in initializers

2022-06-13 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

One week gentle ping.
+ added reviewers from the https://reviews.llvm.org/D111400 patch that fixed 
the bug these tests covers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127201

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


[PATCH] D127201: [clang] Add tests for statement expression in initializers

2022-06-13 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D127201#3578077 , @aaron.ballman 
wrote:

> Thanks for adding some more test coverage! Would it be worth mentioning the 
> miscompile fix in the release notes more explicitly?

Yes, might be a good idea, in particualar as some cases which were accepted 
(but miscompiled) now gives compilation errors.

Will add something to release notes.




Comment at: clang/test/CodeGen/stmtexpr-init.c:1
+// RUN: %clang_cc1 -O -std=gnu11 %s -emit-llvm -o - | FileCheck %s
+

erichkeane wrote:
> why the -std=gnu11 here?  I would assume our default would be enough?  Also, 
> why the opt-flag?  That likely is unnecessary/will cause 'bad things' to 
> happen.  Clang tests typically don't use the opt flags.
> why the -std=gnu11 here?  I would assume our default would be enough?  Also, 
> why the opt-flag?  That likely is unnecessary/will cause 'bad things' to 
> happen.  Clang tests typically don't use the opt flags.

Right, gnu11 shouldn't be needed.

The -O flag was there as that made the optimizer remove some of the dynamic 
initialization things making it easier to see the pattern to match on. But I 
see now that the checks I ended up doing matches just fine without it.

So will drop these. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127201

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


[PATCH] D127201: [clang] Add tests for statement expression in initializers

2022-06-13 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 436561.
wanders added a subscriber: kimgr.
wanders added a comment.

Updated diff with:

- Release note
- Cleaned up command line options in  RUN commands
- Fixed type mimatch pointed out by @kimgr (out of band)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127201

Files:
  clang/docs/ReleaseNotes.rst
  clang/test/CodeGen/stmtexpr-init.c
  clang/test/Sema/stmtexpr-init.c


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+static int *z[1] = {({ static int _x = 70; &_x; })}; // expected-error 
{{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error 
{{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; \
+  &_a;   \
+})
+
+struct outer {
+  const struct sized_array *a;
+};
+
+void T2(void) {
+  // CHECK-DAG: internal constant { i32, [2 x i32] } { i32 2, [2 x i32] [i32 
50, i32 60] }
+  const struct sized_array *A = ARRAY_PTR(50, 60);
+
+  // CHECK-DAG: internal constant { i32, [3 x i32] } { i32 3, [3 x i32] [i32 
10, i32 20, i32 30] }
+  struct outer X = {ARRAY_PTR(10, 20, 30)};
+
+  escape(A);
+  escape(&X);
+}
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -170,6 +170,11 @@
   fixes `Issue 48230 `_.
 - Fixed memory leak due to ``VarTemplateSpecializationDecl`` using
   ``TemplateArgumentListInfo`` instead of ``ASTTemplateArgumentListInfo``.
+- An initializer for a static variable declaration, which is nested
+  inside a statement expression in an aggregate initializer, is now
+  emitted as a dynamic initializer. Previously the variable would
+  incorrectly be zero-initialized. In contexts where a dynamic
+  initializer is not allowed this is now diagnosed as an error.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+static int *z[1] = {({ static int _x = 70; &_x; })}; // expected-error {{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error {{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; \
+  &_a;   \
+})
+
+struct outer {
+  const struct sized_array *a;
+};
+
+void T2(void) {
+  // CHECK-DAG: internal constant { i32, [2 x i32] } { i32 2, [2 x i32] [i32 50, i32 60] }
+  const struct sized_arr

[PATCH] D127201: [clang] Add tests for statement expression in initializers

2022-06-14 Thread Anders Waldenborg 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 rG657e954939c8: [clang] Add tests for statement expression in 
initializers (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127201

Files:
  clang/docs/ReleaseNotes.rst
  clang/test/CodeGen/stmtexpr-init.c
  clang/test/Sema/stmtexpr-init.c


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+static int *z[1] = {({ static int _x = 70; &_x; })}; // expected-error 
{{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error 
{{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; \
+  &_a;   \
+})
+
+struct outer {
+  const struct sized_array *a;
+};
+
+void T2(void) {
+  // CHECK-DAG: internal constant { i32, [2 x i32] } { i32 2, [2 x i32] [i32 
50, i32 60] }
+  const struct sized_array *A = ARRAY_PTR(50, 60);
+
+  // CHECK-DAG: internal constant { i32, [3 x i32] } { i32 3, [3 x i32] [i32 
10, i32 20, i32 30] }
+  struct outer X = {ARRAY_PTR(10, 20, 30)};
+
+  escape(A);
+  escape(&X);
+}
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -170,6 +170,11 @@
   fixes `Issue 48230 `_.
 - Fixed memory leak due to ``VarTemplateSpecializationDecl`` using
   ``TemplateArgumentListInfo`` instead of ``ASTTemplateArgumentListInfo``.
+- An initializer for a static variable declaration, which is nested
+  inside a statement expression in an aggregate initializer, is now
+  emitted as a dynamic initializer. Previously the variable would
+  incorrectly be zero-initialized. In contexts where a dynamic
+  initializer is not allowed this is now diagnosed as an error.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+static int *z[1] = {({ static int _x = 70; &_x; })}; // expected-error {{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error {{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; \
+  &_a;   \
+})
+
+struct outer {
+  const struct sized_array *a;
+};
+
+void T2(void) {
+  // CHECK-DAG: internal constant { i32, [2 x i32] } { i32 2, [2 x i32] [i32 50, i32 60] }
+  const struct sized_array *A

[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-05-24 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: lattner, jyknight, rsmith.
wanders added a project: clang.
Herald added a reviewer: aaron.ballman.
Herald added a project: All.
wanders requested review of this revision.
Herald added a subscriber: cfe-commits.

A variable with `weak` attribute signifies that it can be replaced with
a "strong" symbol link time. Therefore it must not emitted with
"weak_odr" linkage, as that allows the backend to use its value in
optimizations.

The frontend already considers weak const variables as
non-constant (note_constexpr_var_init_weak diagnostic) so this change
makes frontend and backend consistent.

This commit reverses the

  f49573d1 weak globals that are const should get weak_odr linkage.

commit from 2009-08-05 which introduced this behavior. Unfortunately
that commit doesn't provide any details on why the change was made.

This was discussed in
https://discourse.llvm.org/t/weak-attribute-semantics-on-const-variables/62311


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126324

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/global-init.c
  clang/test/CodeGen/weak_constant.c

Index: clang/test/CodeGen/weak_constant.c
===
--- clang/test/CodeGen/weak_constant.c
+++ clang/test/CodeGen/weak_constant.c
@@ -1,13 +1,31 @@
 // RUN: %clang_cc1 -w -emit-llvm %s -O1 -o - | FileCheck %s
-// Check for bug compatibility with gcc.
+// This used to "check for bug compatibility with gcc".
+// Now it checks that that the "weak" declaration makes the value
+// fully interposable whereas a "selectany" one is handled as constant
+// and propagated.
 
+// CHECK: @x = weak constant i32 123
 const int x __attribute((weak)) = 123;
 
+// CHECK: @y = weak_odr constant i32 234
+const int y __attribute((selectany)) = 234;
+
 int* f(void) {
   return &x;
 }
 
 int g(void) {
-  // CHECK: ret i32 123
+  // CHECK: load i32, ptr @x
+  // CHECK-NOT: ret i32 123
   return *f();
 }
+
+int* k(void) {
+  return &y;
+}
+
+int l(void) {
+  // CHECK-NOT: load i32, ptr @y
+  // CHECK: ret i32 234
+  return *k();
+}
Index: clang/test/CodeGen/global-init.c
===
--- clang/test/CodeGen/global-init.c
+++ clang/test/CodeGen/global-init.c
@@ -9,14 +9,22 @@
 
 // This should get normal weak linkage.
 int c __attribute__((weak))= 0;
-// CHECK: @c = weak{{.*}} global i32 0
+// CHECK: @c = weak global i32 0
 
 
-// Since this is marked const, it should get weak_odr linkage, since all
-// definitions have to be the same.
-// CHECK: @d = weak_odr constant i32 0
+// Even though is marked const, it should get still get "weak"
+// linkage, not "weak_odr" as the weak attribute makes it possible
+// that there is a strong definition that changes the value linktime,
+// so the value must not be considered constant.
+// CHECK: @d = weak constant i32 0
 const int d __attribute__((weak))= 0;
 
+// However, "selectany" is similar to "weak", but isn't interposable
+// by a strong definition, and should appear as weak_odr.
+// CHECK: @e = weak_odr constant i32 17
+const int e __attribute__((selectany)) = 17;
+
+
 // PR6168 "too many undefs"
 struct ManyFields {
   int a;
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4893,12 +4893,8 @@
   if (Linkage == GVA_Internal)
 return llvm::Function::InternalLinkage;
 
-  if (D->hasAttr()) {
-if (IsConstantVariable)
-  return llvm::GlobalVariable::WeakODRLinkage;
-else
-  return llvm::GlobalVariable::WeakAnyLinkage;
-  }
+  if (D->hasAttr())
+return llvm::GlobalVariable::WeakAnyLinkage;
 
   if (const auto *FD = D->getAsFunction())
 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@
 The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
   }];
 }
+
+def WeakDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+
+In supported output formats the ``weak`` attribute can be used to
+specify that a variable or function should be emitted as a symbol with
+``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
+external symbol) `linkage
+`_.
+
+If there is a non-weak definition of the symbol the linker will select
+that over the weak. They must have same type and alignment (variables
+must also have the same size), but may have a different value.
+
+If there are multiple weak definitions of same symbol, but no n

[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-05-25 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 431933.
wanders added a comment.

Diff updated to be git-clang-format clean and to (hopefully) accommodate for 
differences in test output on w64.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/global-init.c
  clang/test/CodeGen/weak_constant.c

Index: clang/test/CodeGen/weak_constant.c
===
--- clang/test/CodeGen/weak_constant.c
+++ clang/test/CodeGen/weak_constant.c
@@ -1,13 +1,31 @@
 // RUN: %clang_cc1 -w -emit-llvm %s -O1 -o - | FileCheck %s
-// Check for bug compatibility with gcc.
+// This used to "check for bug compatibility with gcc".
+// Now it checks that that the "weak" declaration makes the value
+// fully interposable whereas a "selectany" one is handled as constant
+// and propagated.
 
+// CHECK: @x = weak {{.*}}constant i32 123
 const int x __attribute((weak)) = 123;
 
+// CHECK: @y = weak_odr {{.*}}constant i32 234
+const int y __attribute((selectany)) = 234;
+
 int* f(void) {
   return &x;
 }
 
 int g(void) {
-  // CHECK: ret i32 123
+  // CHECK: load i32, ptr @x
+  // CHECK-NOT: ret i32 123
   return *f();
 }
+
+int *k(void) {
+  return &y;
+}
+
+int l(void) {
+  // CHECK-NOT: load i32, ptr @y
+  // CHECK: ret i32 234
+  return *k();
+}
Index: clang/test/CodeGen/global-init.c
===
--- clang/test/CodeGen/global-init.c
+++ clang/test/CodeGen/global-init.c
@@ -9,14 +9,20 @@
 
 // This should get normal weak linkage.
 int c __attribute__((weak))= 0;
-// CHECK: @c = weak{{.*}} global i32 0
+// CHECK: @c = weak global i32 0
 
-
-// Since this is marked const, it should get weak_odr linkage, since all
-// definitions have to be the same.
-// CHECK: @d = weak_odr constant i32 0
+// Even though is marked const, it should get still get "weak"
+// linkage, not "weak_odr" as the weak attribute makes it possible
+// that there is a strong definition that changes the value linktime,
+// so the value must not be considered constant.
+// CHECK: @d = weak constant i32 0
 const int d __attribute__((weak))= 0;
 
+// However, "selectany" is similar to "weak", but isn't interposable
+// by a strong definition, and should appear as weak_odr.
+// CHECK: @e = weak_odr constant i32 17
+const int e __attribute__((selectany)) = 17;
+
 // PR6168 "too many undefs"
 struct ManyFields {
   int a;
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4893,12 +4893,8 @@
   if (Linkage == GVA_Internal)
 return llvm::Function::InternalLinkage;
 
-  if (D->hasAttr()) {
-if (IsConstantVariable)
-  return llvm::GlobalVariable::WeakODRLinkage;
-else
-  return llvm::GlobalVariable::WeakAnyLinkage;
-  }
+  if (D->hasAttr())
+return llvm::GlobalVariable::WeakAnyLinkage;
 
   if (const auto *FD = D->getAsFunction())
 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@
 The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
   }];
 }
+
+def WeakDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+
+In supported output formats the ``weak`` attribute can be used to
+specify that a variable or function should be emitted as a symbol with
+``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
+external symbol) `linkage
+`_.
+
+If there is a non-weak definition of the symbol the linker will select
+that over the weak. They must have same type and alignment (variables
+must also have the same size), but may have a different value.
+
+If there are multiple weak definitions of same symbol, but no non-weak
+definition, they should have same type, size, alignment and value, the
+linker will select one of them (see also selectany_ attribute).
+
+If the ``weak`` attribute is applied to a ``const`` qualified variable
+definition that variable is no longer consider a compiletime constant
+as its value can change during linking (or dynamic linking). This
+means that it can e.g no longer be part of an initializer expression.
+
+.. code-block:: c
+
+  const int ANSWER __attribute__ ((weak)) = 42;
+
+  /* This function may be replaced link-time */
+  __attribute__ ((weak)) void debug_log(const char *msg)
+  {
+  fprintf(stderr, "DEBUG: %s\n", msg);
+  }
+
+  int main(int argc, const char **argv)
+  {
+  debug_

[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-05-25 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D126324#3536785 , @aaron.ballman 
wrote:

> The changes so far look sensible, but I think we should add some more tests 
> for a few situations. 1) Using a const weak symbol as a valid initializer 
> should be diagnosed (with a warning? with an error?) so users are alerted to 
> the behavioral quirks. 2) Using a const weak symbol in a constant expression 
> context should probably be an error, right? e.g.,

I do think we have already diagnose/fail on all the relevant cases here. And 
have tests for them, like

  extern const int weak_int __attribute__((weak));
  const int weak_int = 42;
  int weak_int_test = weak_int; // expected-error {{not a compile-time 
constant}}

in clang/test/Sema/const-eval.c

But I'll have another look to make sure we have proper coverage.

> Also, this definitely could use a release note so users know about the 
> behavioral change.

Happy to write one, but not sure what it should say.
The "only" change in behavior is that frontend no longer tells backend it is 
allowed to optimize based on initializer value. Frontend behavior is intended 
to be kept exactly the same (it already is restrictive enough).

> Do you have any ideas on how much code this change is expected to break? (Is 
> it sufficient enough that we want to have an explicit deprecation period of 
> the existing behavior before we switch to the new behavior?)

I don't really know much code out there would be affected. As mentioned in the 
discourse thread 
https://discourse.llvm.org/t/weak-attribute-semantics-on-const-variables/62311/7
 I did some grepping in open source projects I could find. This was biased 
towards looking at C code.
I could see two different uses of const+weak:

1. For defining a constant in a header file (which makes that symbol end up in 
many object files, making it weak avoids multiple definition link errors)
2. To define some default configuration/identificationstring which is 
overridden by a strong symbol

There might of course be other uses of weak that I'm not aware of or could find.

But these two cases I want to think are fine with the proposed change:

For 1. we wouldn't alter behavior of code just speed due to optimization being 
prevented. (I think these uses want to use "selectany" attribute instead)

For 2. this change should actually fix a bug where functions in the same 
translation unit that provided the default was using the default rather than 
overridden value.

Here are some examples I found:
In u-boot they do this 
https://source.denx.de/u-boot/u-boot/-/blob/master/common/hwconfig.c#L71 and I 
think (havn't verified) clang/llvm would optimize the `strlen(cpu_hwconfig)` on 
line 103 to `0`. So here I believe this code currently has incorrect behavior 
when compiled with clang.

Arduino for esp does this constant in header 
https://github.com/esp8266/Arduino/blob/master/variants/generic/common.h#L79 so 
that would cause an extra load of the value from memory for everyone blinking 
the LED using the old deprecaded name for that pin.

Here is a c++ example 
https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/Allocator.cpp#L11
 which I think it might not allow overriding the variable with a strong 
definition as intended when compiling with clang.

The case that motivated me to look into this is like:

  const char VERSION[] __attribute__ ((weak))= "devel";
  
  int is_devel_version(void) {
  return !strcmp (VERSION, "devel");
  }

and when "VERSION" gets "weak_odr" linkage "is_devel_version" gets optimized to 
"return 1".  Even if VERSION gets replaced with a strong value later in link 
phase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

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


[PATCH] D126578: [clang] Add tests for (const) weak variables

2022-05-27 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This adds tests checking the behavior of const variables declared with
weak attribute.

Both checking that they can not be used in places where a constant
expression is required and that a dynamic initializer is emitted when
used as an initializer expression.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126578

Files:
  clang/test/CodeGenCXX/weak-init.cpp
  clang/test/SemaCXX/weak-init.cpp


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__ ((weak)) = 10; // expected-note {{declared 
here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is 
not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak 
variable 'W1' is not considered constant because it may be different at 
runtime}}
+
+
+extern const int W2 __attribute__ ((weak)) = 20;
+
+int S2[W2];  // expected-error {{variable length array declaration not allowed 
at file scope}}
+
+
+extern const int W3 __attribute__ ((weak)) = 30; // expected-note {{declared 
here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be 
initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' 
is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__ ((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__ ((weak)) = 10; // expected-note {{declared here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak variable 'W1' is not considered constant because it may be different at runtime}}
+
+
+extern const int W2 __attribute__ ((weak)) = 20;
+
+int S2[W2];  // expected-error {{variable length array declaration not allowed at file scope}}
+
+
+extern const int W3 __attribute__ ((weak)) = 30; // expected-note {{declared here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__ ((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-05-27 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 432669.
wanders added a comment.

Diff updated with release note + updated text in documentation as per 
jyknight's suggestion.

Tests for existing behavior added in separate patch: 
https://reviews.llvm.org/D126578


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/global-init.c
  clang/test/CodeGen/weak_constant.c

Index: clang/test/CodeGen/weak_constant.c
===
--- clang/test/CodeGen/weak_constant.c
+++ clang/test/CodeGen/weak_constant.c
@@ -1,13 +1,31 @@
 // RUN: %clang_cc1 -w -emit-llvm %s -O1 -o - | FileCheck %s
-// Check for bug compatibility with gcc.
+// This used to "check for bug compatibility with gcc".
+// Now it checks that that the "weak" declaration makes the value
+// fully interposable whereas a "selectany" one is handled as constant
+// and propagated.
 
+// CHECK: @x = weak {{.*}}constant i32 123
 const int x __attribute((weak)) = 123;
 
+// CHECK: @y = weak_odr {{.*}}constant i32 234
+const int y __attribute((selectany)) = 234;
+
 int* f(void) {
   return &x;
 }
 
 int g(void) {
-  // CHECK: ret i32 123
+  // CHECK: load i32, ptr @x
+  // CHECK-NOT: ret i32 123
   return *f();
 }
+
+int *k(void) {
+  return &y;
+}
+
+int l(void) {
+  // CHECK-NOT: load i32, ptr @y
+  // CHECK: ret i32 234
+  return *k();
+}
Index: clang/test/CodeGen/global-init.c
===
--- clang/test/CodeGen/global-init.c
+++ clang/test/CodeGen/global-init.c
@@ -9,14 +9,20 @@
 
 // This should get normal weak linkage.
 int c __attribute__((weak))= 0;
-// CHECK: @c = weak{{.*}} global i32 0
+// CHECK: @c = weak global i32 0
 
-
-// Since this is marked const, it should get weak_odr linkage, since all
-// definitions have to be the same.
-// CHECK: @d = weak_odr constant i32 0
+// Even though is marked const, it should get still get "weak"
+// linkage, not "weak_odr" as the weak attribute makes it possible
+// that there is a strong definition that changes the value linktime,
+// so the value must not be considered constant.
+// CHECK: @d = weak constant i32 0
 const int d __attribute__((weak))= 0;
 
+// However, "selectany" is similar to "weak", but isn't interposable
+// by a strong definition, and should appear as weak_odr.
+// CHECK: @e = weak_odr constant i32 17
+const int e __attribute__((selectany)) = 17;
+
 // PR6168 "too many undefs"
 struct ManyFields {
   int a;
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4899,12 +4899,8 @@
   if (Linkage == GVA_Internal)
 return llvm::Function::InternalLinkage;
 
-  if (D->hasAttr()) {
-if (IsConstantVariable)
-  return llvm::GlobalVariable::WeakODRLinkage;
-else
-  return llvm::GlobalVariable::WeakAnyLinkage;
-  }
+  if (D->hasAttr())
+return llvm::GlobalVariable::WeakAnyLinkage;
 
   if (const auto *FD = D->getAsFunction())
 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@
 The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
   }];
 }
+
+def WeakDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+
+In supported output formats the ``weak`` attribute can be used to
+specify that a variable or function should be emitted as a symbol with
+``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
+external symbol) `linkage
+`_.
+
+If there is a non-weak definition of the symbol the linker will select
+that over the weak. They must have same type and alignment (variables
+must also have the same size), but may have a different value.
+
+If there are multiple weak definitions of same symbol, but no non-weak
+definition, they should have same type, size, alignment and value, the
+linker will select one of them (see also selectany_ attribute).
+
+If the ``weak`` attribute is applied to a ``const`` qualified variable
+definition that variable is no longer consider a compiletime constant
+as its value can change during linking (or dynamic linking). This
+means that it can e.g no longer be part of an initializer expression.
+
+.. code-block:: c
+
+  const int ANSWER __attribute__ ((weak)) = 42;
+
+  /* This function may be replaced link-time */
+  __attribute__ ((weak)) void debug_log(const char *msg)
+  {
+  fpri

[PATCH] D126578: [clang] Add tests for (const) weak variables

2022-05-28 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 432742.
wanders added a comment.

Added explicit triple to hopefully make it pass on win.
Made the new files clang-format clean.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126578

Files:
  clang/test/CodeGenCXX/weak-init.cpp
  clang/test/SemaCXX/weak-init.cpp


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__((weak)) = 10; // expected-note {{declared 
here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is 
not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak 
variable 'W1' is not considered constant because it may be different at 
runtime}}
+
+extern const int W2 __attribute__((weak)) = 20;
+
+int S2[W2]; // expected-error {{variable length array declaration not allowed 
at file scope}}
+
+extern const int W3 __attribute__((weak)) = 30; // expected-note {{declared 
here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be 
initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' 
is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck 
%s
+
+extern const int W __attribute__((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__((weak)) = 10; // expected-note {{declared here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak variable 'W1' is not considered constant because it may be different at runtime}}
+
+extern const int W2 __attribute__((weak)) = 20;
+
+int S2[W2]; // expected-error {{variable length array declaration not allowed at file scope}}
+
+extern const int W3 __attribute__((weak)) = 30; // expected-note {{declared here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126578: [clang] Add tests for (const) weak variables

2022-05-28 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D126578#3543994 , @aaron.ballman 
wrote:

> Thanks for looking to improve our test coverage here! However, precommit CI 
> looks to be failing:

Thanks for notifying me.  It should be green now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126578

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


[PATCH] D126578: [clang] Add tests for (const) weak variables

2022-06-01 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG86f9cf88cb06: [clang] Add tests for (const) weak variables 
(authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126578

Files:
  clang/test/CodeGenCXX/weak-init.cpp
  clang/test/SemaCXX/weak-init.cpp


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__((weak)) = 10; // expected-note {{declared 
here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is 
not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak 
variable 'W1' is not considered constant because it may be different at 
runtime}}
+
+extern const int W2 __attribute__((weak)) = 20;
+
+int S2[W2]; // expected-error {{variable length array declaration not allowed 
at file scope}}
+
+extern const int W3 __attribute__((weak)) = 30; // expected-note {{declared 
here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be 
initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' 
is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck 
%s
+
+extern const int W __attribute__((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__((weak)) = 10; // expected-note {{declared here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak variable 'W1' is not considered constant because it may be different at runtime}}
+
+extern const int W2 __attribute__((weak)) = 20;
+
+int S2[W2]; // expected-error {{variable length array declaration not allowed at file scope}}
+
+extern const int W3 __attribute__((weak)) = 30; // expected-note {{declared here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126804: [scan-build-py] Change scripts to explicitly require python3

2022-06-01 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: phosek, sylvestre.ledru.
Herald added a subscriber: whisperity.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The "#!" line in all scan-build-py scripts were using just bare
"/usr/bin/python" which according to PEP-0394 can be either python3,
python2 or not exist at all.

E.g in latest debian and ubuntu releases "/usr/bin/python" does not
exist at all by default and user must install python-is-python2 or
python-is-python3 packages to get the bare version less "python"
command.

Until recently (70b06fe8a186 
 
"scan-build-py: Force the opening in utf-8"
changed "libscanbuild") these scripts worked in both python2 and
python3, but now they (rightfully) are python3 only, and broke on
systems where the "python" command means python2.

By changing the "#!" to be "python3" it is not only explicit that the
scripts require python3 it also works on systems where "python" command
is python2 or nonexistent.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126804

Files:
  clang/tools/scan-build-py/bin/analyze-build
  clang/tools/scan-build-py/bin/intercept-build
  clang/tools/scan-build-py/bin/scan-build
  clang/tools/scan-build-py/libexec/analyze-c++
  clang/tools/scan-build-py/libexec/analyze-cc
  clang/tools/scan-build-py/libexec/intercept-c++
  clang/tools/scan-build-py/libexec/intercept-cc


Index: clang/tools/scan-build-py/libexec/intercept-cc
===
--- clang/tools/scan-build-py/libexec/intercept-cc
+++ clang/tools/scan-build-py/libexec/intercept-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/intercept-c++
===
--- clang/tools/scan-build-py/libexec/intercept-c++
+++ clang/tools/scan-build-py/libexec/intercept-c++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/analyze-cc
===
--- clang/tools/scan-build-py/libexec/analyze-cc
+++ clang/tools/scan-build-py/libexec/analyze-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/analyze-c++
===
--- clang/tools/scan-build-py/libexec/analyze-c++
+++ clang/tools/scan-build-py/libexec/analyze-c++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/scan-build
===
--- clang/tools/scan-build-py/bin/scan-build
+++ clang/tools/scan-build-py/bin/scan-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/intercept-build
===
--- clang/tools/scan-build-py/bin/intercept-build
+++ clang/tools/scan-build-py/bin/intercept-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/analyze-build
===
--- clang/tools/scan-build-py/bin/analyze-build
+++ clang/tools/scan-build-py/bin/analyze-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.


Index: clang/tools/scan-build-py/libexec/intercept-cc
===
--- clang/tools/scan-build-py/libexec/intercept-cc
+++ clang/tools/scan-build-py/libexec/intercept-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8

[PATCH] D126804: [scan-build-py] Change scripts to explicitly require python3

2022-06-02 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4c1e487c4138: scan-build-py: Change scripts to explicitly 
require python3 (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126804

Files:
  clang/tools/scan-build-py/bin/analyze-build
  clang/tools/scan-build-py/bin/intercept-build
  clang/tools/scan-build-py/bin/scan-build
  clang/tools/scan-build-py/libexec/analyze-c++
  clang/tools/scan-build-py/libexec/analyze-cc
  clang/tools/scan-build-py/libexec/intercept-c++
  clang/tools/scan-build-py/libexec/intercept-cc


Index: clang/tools/scan-build-py/libexec/intercept-cc
===
--- clang/tools/scan-build-py/libexec/intercept-cc
+++ clang/tools/scan-build-py/libexec/intercept-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/intercept-c++
===
--- clang/tools/scan-build-py/libexec/intercept-c++
+++ clang/tools/scan-build-py/libexec/intercept-c++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/analyze-cc
===
--- clang/tools/scan-build-py/libexec/analyze-cc
+++ clang/tools/scan-build-py/libexec/analyze-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/analyze-c++
===
--- clang/tools/scan-build-py/libexec/analyze-c++
+++ clang/tools/scan-build-py/libexec/analyze-c++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/scan-build
===
--- clang/tools/scan-build-py/bin/scan-build
+++ clang/tools/scan-build-py/bin/scan-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/intercept-build
===
--- clang/tools/scan-build-py/bin/intercept-build
+++ clang/tools/scan-build-py/bin/intercept-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/bin/analyze-build
===
--- clang/tools/scan-build-py/bin/analyze-build
+++ clang/tools/scan-build-py/bin/analyze-build
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.


Index: clang/tools/scan-build-py/libexec/intercept-cc
===
--- clang/tools/scan-build-py/libexec/intercept-cc
+++ clang/tools/scan-build-py/libexec/intercept-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/intercept-c++
===
--- clang/tools/scan-build-py/libexec/intercept-c++
+++ clang/tools/scan-build-py/libexec/intercept-c++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 # See https://llvm.org/LICENSE.txt for license information.
Index: clang/tools/scan-build-py/libexec/analyze-cc
===
--- clang/tools/scan-build-py/libexec/analyze-cc
+++ clang/tools/scan-build-py/libexec/analyze-cc
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env

[PATCH] D126974: [scan-build-py] Fix exception on shutdown with sarif-html output format

2022-06-03 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: phosek, isthismyaccount.
Herald added a subscriber: whisperity.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When running scan-build-py's analyze-build script with output format set
to sarif & html it wants to print a message on how to look at the
defects mentioning the directory name twice.

But the path argument was only given once to the logging function,
causing "TypeError: not enough arguments for format string" exception.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126974

Files:
  clang/tools/scan-build-py/lib/libscanbuild/analyze.py


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)


Index: clang/tools/scan-build-py/lib/libscanbuild/analyze.py
===
--- clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@
 try:
 yield name
 finally:
+args = (name,)
 if os.listdir(name):
 if output_format not in ['sarif', 'sarif-html']: # FIXME:
 # 'scan-view' currently does not support sarif format.
@@ -364,6 +365,7 @@
 elif output_format == 'sarif-html':
 msg = "Run 'scan-view %s' to examine bug reports or see " \
 "merged sarif results at %s/results-merged.sarif."
+args = (name, name)
 else:
 msg = "View merged sarif results at %s/results-merged.sarif."
 keep = True
@@ -372,7 +374,7 @@
 msg = "Report directory '%s' contains no report, but kept."
 else:
 msg = "Removing directory '%s' because it contains no report."
-logging.warning(msg, name)
+logging.warning(msg, *args)
 
 if not keep:
 os.rmdir(name)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-06-03 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
wanders marked 2 inline comments as done.
Closed by commit rGdd2362a8bab3: [clang] Allow const variables with weak 
attribute to be overridden (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/global-init.c
  clang/test/CodeGen/weak_constant.c

Index: clang/test/CodeGen/weak_constant.c
===
--- clang/test/CodeGen/weak_constant.c
+++ clang/test/CodeGen/weak_constant.c
@@ -1,13 +1,31 @@
 // RUN: %clang_cc1 -w -emit-llvm %s -O1 -o - | FileCheck %s
-// Check for bug compatibility with gcc.
+// This used to "check for bug compatibility with gcc".
+// Now it checks that that the "weak" declaration makes the value
+// fully interposable whereas a "selectany" one is handled as constant
+// and propagated.
 
+// CHECK: @x = weak {{.*}}constant i32 123
 const int x __attribute((weak)) = 123;
 
+// CHECK: @y = weak_odr {{.*}}constant i32 234
+const int y __attribute((selectany)) = 234;
+
 int* f(void) {
   return &x;
 }
 
 int g(void) {
-  // CHECK: ret i32 123
+  // CHECK: load i32, ptr @x
+  // CHECK-NOT: ret i32 123
   return *f();
 }
+
+int *k(void) {
+  return &y;
+}
+
+int l(void) {
+  // CHECK-NOT: load i32, ptr @y
+  // CHECK: ret i32 234
+  return *k();
+}
Index: clang/test/CodeGen/global-init.c
===
--- clang/test/CodeGen/global-init.c
+++ clang/test/CodeGen/global-init.c
@@ -9,14 +9,20 @@
 
 // This should get normal weak linkage.
 int c __attribute__((weak))= 0;
-// CHECK: @c = weak{{.*}} global i32 0
+// CHECK: @c = weak global i32 0
 
-
-// Since this is marked const, it should get weak_odr linkage, since all
-// definitions have to be the same.
-// CHECK: @d = weak_odr constant i32 0
+// Even though is marked const, it should get still get "weak"
+// linkage, not "weak_odr" as the weak attribute makes it possible
+// that there is a strong definition that changes the value linktime,
+// so the value must not be considered constant.
+// CHECK: @d = weak constant i32 0
 const int d __attribute__((weak))= 0;
 
+// However, "selectany" is similar to "weak", but isn't interposable
+// by a strong definition, and should appear as weak_odr.
+// CHECK: @e = weak_odr constant i32 17
+const int e __attribute__((selectany)) = 17;
+
 // PR6168 "too many undefs"
 struct ManyFields {
   int a;
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4899,12 +4899,8 @@
   if (Linkage == GVA_Internal)
 return llvm::Function::InternalLinkage;
 
-  if (D->hasAttr()) {
-if (IsConstantVariable)
-  return llvm::GlobalVariable::WeakODRLinkage;
-else
-  return llvm::GlobalVariable::WeakAnyLinkage;
-  }
+  if (D->hasAttr())
+return llvm::GlobalVariable::WeakAnyLinkage;
 
   if (const auto *FD = D->getAsFunction())
 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@
 The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
   }];
 }
+
+def WeakDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+
+In supported output formats the ``weak`` attribute can be used to
+specify that a variable or function should be emitted as a symbol with
+``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
+external symbol) `linkage
+`_.
+
+If there is a non-weak definition of the symbol the linker will select
+that over the weak. They must have same type and alignment (variables
+must also have the same size), but may have a different value.
+
+If there are multiple weak definitions of same symbol, but no non-weak
+definition, they should have same type, size, alignment and value, the
+linker will select one of them (see also selectany_ attribute).
+
+If the ``weak`` attribute is applied to a ``const`` qualified variable
+definition that variable is no longer consider a compiletime constant
+as its value can change during linking (or dynamic linking). This
+means that it can e.g no longer be part of an initializer expression.
+
+.. code-block:: c
+
+  const int ANSWER __attribute__ ((weak)) = 42;
+
+  /* This function may be replaced link-time */
+  __attribute__ ((weak)) void debug_log(const char *msg)
+  {
+  fprintf(stderr, "DE

[PATCH] D127201: [clang] Add tests for statement expression in initializers

2022-06-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added reviewers: cor3ntin, rsmith.
wanders added a project: clang.
Herald added a project: All.
wanders requested review of this revision.
Herald added a subscriber: cfe-commits.

The commit 683e83c5 


  [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr

fixed a code generation bug when using (C-extension) statement
expressions inside initializer expressions.

Before that commit a nested static initializer inside the statement
expression would not be emitted, causing it to be zero initialized.

It is a bit surprising (at least to me) that a commit implementing a new
C++ feature would fix this code generation bug. Zooming in it is the
change done in ExprConstant.cpp that helps. That changes so that
"ESR_Failed" is returned in more cases, causing the expression to not be
deemed constant. This fixes the code generation as instead the compiler
has to resort to generating a dynamic initializer.

That commit also meant that some statement expressions (in particular
the ones using static variables) that previously were accepted now are
errors due to not being constant (matching GCC behavior).

Given how a seemingly unrelated change caused this behavior to change,
it is probably a good thing to add at least some rudimentary tests for
these kind expressions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D127201

Files:
  clang/test/CodeGen/stmtexpr-init.c
  clang/test/Sema/stmtexpr-init.c


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -std=gnu11 %s
+
+static int z[1] = {({ static int _x = 70; &_x; })}; // expected-error 
{{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error 
{{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -O -std=gnu11 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; \
+  &_a;   \
+})
+
+struct outer {
+  const struct sized_array *a;
+};
+
+void T2(void) {
+  // CHECK-DAG: internal constant { i32, [2 x i32] } { i32 2, [2 x i32] [i32 
50, i32 60] }
+  const struct sized_array *A = ARRAY_PTR(50, 60);
+
+  // CHECK-DAG: internal constant { i32, [3 x i32] } { i32 3, [3 x i32] [i32 
10, i32 20, i32 30] }
+  struct outer X = {ARRAY_PTR(10, 20, 30)};
+
+  escape(A);
+  escape(&X);
+}


Index: clang/test/Sema/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/Sema/stmtexpr-init.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -std=gnu11 %s
+
+static int z[1] = {({ static int _x = 70; &_x; })}; // expected-error {{statement expression not allowed at file scope}}
+
+void T1(void) {
+  int *x[1] = {({ static int _x = 10; &_x; })}; // expected-no-error
+
+  /* Before commit
+ 683e83c5 [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
+ (i.e in clang-14 and earlier)
+ this was silently accepted, but generated incorrect code.
+  */
+  static int *y[1] = {({ static int _x = 20; &_x; })}; // expected-error {{initializer element is not a compile-time constant}}
+}
Index: clang/test/CodeGen/stmtexpr-init.c
===
--- /dev/null
+++ clang/test/CodeGen/stmtexpr-init.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -O -std=gnu11 %s -emit-llvm -o - | FileCheck %s
+
+void escape(const void *);
+
+// CHECK-DAG: internal global i8 99
+
+void T1(void) {
+  const char *x[1] = {({static char _x = 99; &_x; })};
+  escape(x);
+}
+
+struct sized_array {
+  int count;
+  int entries[];
+};
+
+#define N_ARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
+
+#define ARRAY_PTR(...) ({\
+  static const struct sized_array _a = {N_ARGS(__VA_ARGS__), {__VA_ARGS__}}; 

[PATCH] D126974: [scan-build-py] Fix exception on shutdown with sarif-html output format

2022-06-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

Gentle 1-week ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126974

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


[PATCH] D68568: [clang-format] Make '.clang-format' variants finding a loop

2019-11-06 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D68568#1735741 , @MyDeveloperDay 
wrote:

> Do you need help landing this?


Sorry that I havn't gotten back to this.

I started looking into the "PathMatch" idea I floated in D68569 
 ([clang-format] Also look for 
.{ext}.clang-format file). That would mean something entirely different than 
the patch in D68596 , making this refactor 
less needed.

But I can still land it if you think it still relavant on its own.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68568



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


[PATCH] D68568: [clang-format] Make '.clang-format' variants finding a loop

2019-11-07 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG86825dbe3306: [clang-format] Make '.clang-format' 
variants finding a loop (NFC) (authored by wanders).

Changed prior to commit:
  https://reviews.llvm.org/D68568?vs=223488&id=228187#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68568

Files:
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,35 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
-
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == 
llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on 
Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
   Status = FS->status(ConfigFile.str());
-  FoundConfigFile = Status && (Status->getType() ==
-   llvm::sys::fs::file_type::regular_file);
-}
 
-if (FoundConfigFile) {
-  llvm::ErrorOr> Text =
-  FS->getBufferForFile(ConfigFile.str());
-  if (std::error_code EC = Text.getError())
-return make_string_error(EC.message());
-  if (std::error_code ec =
-  parseConfiguration(Text.get()->getBuffer(), &Style)) {
-if (ec == ParseError::Unsuitable) {
-  if (!UnsuitableConfigFiles.empty())
-UnsuitableConfigFiles.append(", ");
-  UnsuitableConfigFiles.append(ConfigFile);
-  continue;
+  if (Status &&
+  (Status->getType() == llvm::sys::fs::file_type::regular_file)) {
+llvm::ErrorOr> Text =
+FS->getBufferForFile(ConfigFile.str());
+if (std::error_code EC = Text.getError())
+  return make_string_error(EC.message());
+if (std::error_code ec =
+parseConfiguration(Text.get()->getBuffer(), &Style)) {
+  if (ec == ParseError::Unsuitable) {
+if (!UnsuitableConfigFiles.empty())
+  UnsuitableConfigFiles.append(", ");
+UnsuitableConfigFiles.append(ConfigFile);
+continue;
+  }
+  return make_string_error("Error reading " + ConfigFile + ": " +
+   ec.message());
 }
-return make_string_error("Error reading " + ConfigFile + ": " +
- ec.message());
+LLVM_DEBUG(llvm::dbgs()
+   << "Using configuration file " << ConfigFile << "\n");
+return Style;
   }
-  LLVM_DEBUG(llvm::dbgs()
- << "Using configuration file " << ConfigFile << "\n");
-  return Style;
 }
   }
   if (!UnsuitableConfigFiles.empty())


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,35 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
-
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm:

[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-01 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added inline comments.



Comment at: clang/lib/Basic/Attributes.cpp:46
+  for (auto &AttrPlugin : getAttributePluginInstances()) {
+for (auto &S : AttrPlugin->Spellings)
+  if (S.Syntax == Syntax && S.NormalizedFullName == Name)

erichkeane wrote:
> I think this should be a property of the AttributePlugin type, where you send 
> it the Syntax/Name and it checks to see if it is provided. 
Do you think I should do something like this? 

(refactor based on mainline)

```
diff --git a/clang/include/clang/Sema/ParsedAttr.h 
b/clang/include/clang/Sema/ParsedAttr.h
index f060564e6719..635580ac599b 100644
--- a/clang/include/clang/Sema/ParsedAttr.h
+++ b/clang/include/clang/Sema/ParsedAttr.h
@@ -98,6 +98,13 @@ protected:
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute can be spelled like this. Only used for plugin 
attributes
+  virtual bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) 
{
+return llvm::any_of(Spellings, [&] (const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {
diff --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index c1e39acb14ec..b53132d73d79 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -135,8 +135,7 @@ const ParsedAttrInfo &ParsedAttrInfo::get(const 
AttributeCommonInfo &A) {
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : *PluginAttrInstances)
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
+if (Ptr->handlesSpelling(SyntaxUsed, FullName))
 return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
```

Maybe not `virtual` as allowing plugins to handle attributes not in their 
Spellings array maybe is too flexible?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

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


[PATCH] D144402: [clang] Move ParsedAttrInfo from Sema to Basic (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 504041.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144402

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp

Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -26,8 +26,6 @@
 
 using namespace clang;
 
-LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
-
 IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,
  IdentifierInfo *Ident) {
   IdentifierLoc *Result = new (Ctx) IdentifierLoc;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- /dev/null
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -0,0 +1,18 @@
+//===- ParsedAttrInfo.cpp - Registry for attribute plugins --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file contains the Registry of attributes added by plugins which
+// derive the ParsedAttrInfo class.
+//
+//===--===//
+
+#include "clang/Basic/ParsedAttrInfo.h"
+
+using namespace clang;
+
+LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
Index: clang/lib/Basic/CMakeLists.txt
===
--- clang/lib/Basic/CMakeLists.txt
+++ clang/lib/Basic/CMakeLists.txt
@@ -61,6 +61,7 @@
   OpenCLOptions.cpp
   OpenMPKinds.cpp
   OperatorPrecedence.cpp
+  ParsedAttrInfo.cpp
   ProfileList.cpp
   NoSanitizeList.cpp
   SanitizerSpecialCaseList.cpp
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -17,12 +17,12 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Allocator.h"
-#include "llvm/Support/Registry.h"
 #include "llvm/Support/VersionTuple.h"
 #include 
 #include 
@@ -36,124 +36,10 @@
 class Expr;
 class IdentifierInfo;
 class LangOptions;
-class ParsedAttr;
 class Sema;
 class Stmt;
 class TargetInfo;
 
-struct ParsedAttrInfo {
-  /// Corresponds to the Kind enum.
-  unsigned AttrKind : 16;
-  /// The number of required arguments of this attribute.
-  unsigned NumArgs : 4;
-  /// The number of optional arguments of this attributes.
-  unsigned OptArgs : 4;
-  /// The number of non-fake arguments specified in the attribute definition.
-  unsigned NumArgMembers : 4;
-  /// True if the parsing does not match the semantic content.
-  unsigned HasCustomParsing : 1;
-  // True if this attribute accepts expression parameter pack expansions.
-  unsigned AcceptsExprPack : 1;
-  /// True if this attribute is only available for certain targets.
-  unsigned IsTargetSpecific : 1;
-  /// True if this attribute applies to types.
-  unsigned IsType : 1;
-  /// True if this attribute applies to statements.
-  unsigned IsStmt : 1;
-  /// True if this attribute has any spellings that are known to gcc.
-  unsigned IsKnownToGCC : 1;
-  /// True if this attribute is supported by #pragma clang attribute.
-  unsigned IsSupportedByPragmaAttribute : 1;
-  /// The syntaxes supported by this attribute and how they're spelled.
-  struct Spelling {
-AttributeCommonInfo::Syntax Syntax;
-const char *NormalizedFullName;
-  };
-  ArrayRef Spellings;
-  // The names of the known arguments of this attribute.
-  ArrayRef ArgNames;
-
-protected:
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind =
-   AttributeCommonInfo::NoSemaHandlerAttribute)
-  : AttrKind(AttrKind), NumArgs(0), OptArgs(0), NumArgMembers(0),
-HasCustomParsing(0), AcceptsExprPack(0), IsTargetSpecific(0), IsType(0),
-IsStmt(0), IsKnownToGCC(0), IsSupportedByPragmaAttribute(0) {}
-
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind, unsigned NumArgs,
-   unsigned OptArgs, unsigned NumArgMembers,
-   unsigned HasCustomParsing, unsigned AcceptsExprPack,
-   unsigned IsTargetSpecific, unsigned IsType,
-   unsigned IsStmt, unsigned IsKnownToGCC,
-  

[PATCH] D144403: [clang] Extract attribute plugin instantiation to function (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders edited the summary of this revision.
wanders updated this revision to Diff 504042.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144403

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -12,7 +12,21 @@
 
//===--===//
 
 #include "clang/Basic/ParsedAttrInfo.h"
+#include "llvm/Support/ManagedStatic.h"
+#include 
+#include 
 
 using namespace clang;
 
 LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
+
+const std::list> &
+clang::getAttributePluginInstances() {
+  static llvm::ManagedStatic>>
+  PluginAttrInstances;
+  if (PluginAttrInstances->empty())
+for (auto It : ParsedAttrInfoRegistry::entries())
+  PluginAttrInstances->emplace_back(It.instantiate());
+
+  return *PluginAttrInstances;
+}
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -20,6 +20,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/Registry.h"
 #include 
+#include 
 
 namespace clang {
 
@@ -137,6 +138,8 @@
 
 typedef llvm::Registry ParsedAttrInfoRegistry;
 
+const std::list> 
&getAttributePluginInstances();
+
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_PARSEDATTRINFO_H


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -12,7 +12,21 @@
 //===--===//
 
 #include "clang/Basic/ParsedAttrInfo.h"
+#include "llvm/Support/ManagedStatic.h"
+#include 
+#include 
 
 using namespace clang;
 
 LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
+
+const std::list> &
+clang::getAttributePluginInstances() {
+  st

[PATCH] D145769: [clang] Extract ParsedAttrInfo::hasSpelling method (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This intends to simplify this checking when it is done in more places.

No functional change intended.

Depends on D144403 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145769

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) {
+return llvm::any_of(Spellings, [&] (const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) {
+return llvm::any_of(Spellings, [&] (const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144404: [clang] Extract function for generated part of clang::hasAttribute (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders edited the summary of this revision.
wanders updated this revision to Diff 504044.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144404

Files:
  clang/lib/Basic/Attributes.cpp


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo 
*Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) 
{
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo *Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) {
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders edited the summary of this revision.
wanders updated this revision to Diff 504045.
wanders marked an inline comment as not done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

Files:
  clang/docs/ReleaseNotes.rst
  clang/examples/Attribute/Attribute.cpp
  clang/lib/Basic/Attributes.cpp
  clang/test/Frontend/plugin-attribute-pp.cpp

Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,36 @@
+// RUN: split-file %s %t
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.cpp | FileCheck %t/has_attr.cpp
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.c | FileCheck %t/has_attr.c
+// REQUIRES: plugins, examples
+
+
+//--- has_attr.cpp
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_cpp_attribute (example)
+// CHECK: YES - It did cpp-exist
+YES - It did cpp-exist
+#endif
+
+#if __has_attribute (doesnt_exist)
+// CHECK-NOT: NO - There is no such attribute
+NO - There is no such attribute
+#endif
+
+
+//--- has_attr.c
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_c_attribute (example)
+// CHECK: YES - It did c-exist
+YES - It did c-exist
+#endif
+
+#if __has_attribute (doesnt_exist)
+// CHECK-NOT: NO - There is no such attribute
+NO - There is no such attribute
+#endif
Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -2,6 +2,7 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 using namespace clang;
 
 static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
@@ -40,6 +41,11 @@
   if (res)
 return res;
 
+  // Check if any plugin provides this attribute.
+  for (auto &Ptr : getAttributePluginInstances())
+if (Ptr->hasSpelling(Syntax, Name))
+  return 1;
+
   return 0;
 }
 
Index: clang/examples/Attribute/Attribute.cpp
===
--- clang/examples/Attribute/Attribute.cpp
+++ clang/examples/Attribute/Attribute.cpp
@@ -9,6 +9,8 @@
 // Example clang plugin which adds an an annotation to file-scope declarations
 // with the 'example' attribute.
 //
+// This plugin is used by clang/test/Frontend/plugin-attribute tests.
+//
 //===--===//
 
 #include "clang/AST/ASTContext.h"
@@ -27,9 +29,10 @@
 // number of arguments. This just illustrates how many arguments a
 // `ParsedAttrInfo` can hold, we will not use that much in this example.
 OptArgs = 15;
-// GNU-style __attribute__(("example")) and C++-style [[example]] and
+// GNU-style __attribute__(("example")) and C++/C2x-style [[example]] and
 // [[plugin::example]] supported.
 static constexpr Spelling S[] = {{ParsedAttr::AS_GNU, "example"},
+ {ParsedAttr::AS_C2x, "example"},
  {ParsedAttr::AS_CXX11, "example"},
  {ParsedAttr::AS_CXX11, "plugin::example"}};
 Spellings = S;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -146,6 +146,8 @@
   uses the optional USR value when indexing Clang's AST. This value is expected
   to be generated by an external compiler when generating C++ bindings during
   the compilation of the foreign language sources (e.g. Swift).
+- The ``__has_attribute``, ``__has_c_attribute`` and ``__has_cpp_attribute``
+  preprocessor operators now return 1 also for attributes defined by plugins.
 
 Improvements to Clang's diagnostics
 ---
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders marked 2 inline comments as done.
wanders added a comment.

@erichkeane 
Patch stack now updated to include a method extraction of hasSpelling, and 
releasenote added.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

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


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D144405#4184726 , @erichkeane 
wrote:

> Looks like this doesn't compile pre-commit, though no idea if that is a 
> patch-stack issue.  Other than test, patch looks fine.

Yeah, when uploading the new commit the stack was disorganized. So the build 
probably started before I got around organizing the stack in correct order.

So hopefully clears up when I fix the test  (clang-format and const thing)




Comment at: clang/test/Frontend/plugin-attribute-pp.cpp:1
+// RUN: split-file %s %t
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.cpp | 
FileCheck %t/has_attr.cpp

erichkeane wrote:
> This split-file thing is weird, don't do that.  create 2 tests instead, OR 
> Just use -x c and -x c++ to change languages (you can use a separate macro to 
> get __has_c and __has_cpp_attribute right).
Right. That should be simpler. Will fix.

(it ended up this way because I first added a split to the existing 
`plugin-attribute.cpp` test with splits)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

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


[PATCH] D144402: [clang] Move ParsedAttrInfo from Sema to Basic (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D144402#4184749 , @erichkeane 
wrote:

> I want to wait for @aaron.ballman to answer, but i think this is generally 
> OK.  Note the motivation is the ability to check this from 
> __has_cpp_attribute/__has_c_attribute/etc.

I did discuss this with @aaron.ballman in his office hours 13th Feb, so he 
should be aware of context.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144402

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


[PATCH] D144404: [clang] Extract function for generated part of clang::hasAttribute (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 504151.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144404

Files:
  clang/lib/Basic/Attributes.cpp


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo 
*Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) 
{
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo *Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) {
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 504152.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

Files:
  clang/docs/ReleaseNotes.rst
  clang/examples/Attribute/Attribute.cpp
  clang/lib/Basic/Attributes.cpp
  clang/test/Frontend/plugin-attribute-pp.cpp


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s | FileCheck %s
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s -x c | 
FileCheck %s
+// REQUIRES: plugins, examples
+
+#ifdef __cplusplus
+# define HAS_ATTR(a) __has_cpp_attribute (a)
+#else
+# define HAS_ATTR(a) __has_c_attribute (a)
+#endif
+
+#if __has_attribute(example)
+// CHECK: has_attribute(example) was true
+has_attribute(example) was true
+#endif
+#if HAS_ATTR(example)
+// CHECK: has_$LANG_attribute(example) was true
+has_$LANG_attribute(example) was true
+#endif
+
+#if __has_attribute(doesnt_exist)
+// CHECK-NOT: has_attribute(doesnt_exist) unexpectedly was true
+has_attribute(doesnt_exist) unexpectedly was true
+#endif
+
+#if HAS_ATTR(doesnt_exist)
+// CHECK-NOT: has_$LANG_attribute(doesnt_exist) unexpectedly was true
+has_$LANG_attribute(doesnt_exist) unexpectedly was true
+#endif
Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -2,6 +2,7 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 using namespace clang;
 
 static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
@@ -40,6 +41,11 @@
   if (res)
 return res;
 
+  // Check if any plugin provides this attribute.
+  for (auto &Ptr : getAttributePluginInstances())
+if (Ptr->hasSpelling(Syntax, Name))
+  return 1;
+
   return 0;
 }
 
Index: clang/examples/Attribute/Attribute.cpp
===
--- clang/examples/Attribute/Attribute.cpp
+++ clang/examples/Attribute/Attribute.cpp
@@ -9,6 +9,8 @@
 // Example clang plugin which adds an an annotation to file-scope declarations
 // with the 'example' attribute.
 //
+// This plugin is used by clang/test/Frontend/plugin-attribute tests.
+//
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
@@ -27,9 +29,10 @@
 // number of arguments. This just illustrates how many arguments a
 // `ParsedAttrInfo` can hold, we will not use that much in this example.
 OptArgs = 15;
-// GNU-style __attribute__(("example")) and C++-style [[example]] and
+// GNU-style __attribute__(("example")) and C++/C2x-style [[example]] and
 // [[plugin::example]] supported.
 static constexpr Spelling S[] = {{ParsedAttr::AS_GNU, "example"},
+ {ParsedAttr::AS_C2x, "example"},
  {ParsedAttr::AS_CXX11, "example"},
  {ParsedAttr::AS_CXX11, 
"plugin::example"}};
 Spellings = S;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -146,6 +146,8 @@
   uses the optional USR value when indexing Clang's AST. This value is expected
   to be generated by an external compiler when generating C++ bindings during
   the compilation of the foreign language sources (e.g. Swift).
+- The ``__has_attribute``, ``__has_c_attribute`` and ``__has_cpp_attribute``
+  preprocessor operators now return 1 also for attributes defined by plugins.
 
 Improvements to Clang's diagnostics
 ---


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s | FileCheck %s
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s -x c | FileCheck %s
+// REQUIRES: plugins, examples
+
+#ifdef __cplusplus
+# define HAS_ATTR(a) __has_cpp_attribute (a)
+#else
+# define HAS_ATTR(a) __has_c_attribute (a)
+#endif
+
+#if __has_attribute(example)
+// CHECK: has_attribute(example) was true
+has_attribute(example) was true
+#endif
+#if HAS_ATTR(example)
+// CHECK: has_$LANG_attribute(example) was true
+has_$LANG_attribute(example) was true
+#endif
+
+#if __has_attribute(doesnt_exist)
+// CHECK-NOT: has_attribute(doesnt_exist) unexpectedly was true
+has_attribute(doesnt_exist) unexpectedly was true
+#endif
+
+#if HAS_ATTR(doesnt_exist)
+// CHECK-NOT: has_$LANG_attribute(does

[PATCH] D145769: [clang] Extract ParsedAttrInfo::hasSpelling method (NFC)

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders edited the summary of this revision.
wanders updated this revision to Diff 504150.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145769

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) const {
+return llvm::any_of(Spellings, [&](const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) const {
+return llvm::any_of(Spellings, [&](const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-10 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

In D144405#4184964 , @erichkeane 
wrote:

> So here's a potential idea for future development:  It isn't 
> uncommon/untypical for an attribute to want to return something other than 
> '1', for 'version' (usually an integral value representing a date).  The 
> standard attributes all do this.  It might be worth looking into some 
> infrastructure to do that.

Adding this to my list of things to look into. Thanks.

I see that D144403  in the stack is not 
accepted, is there anything I need to fix that I have missed?

My current plan after this is to look into making it possible to attach custom 
attributes to the AST nodes, and in the end use plugin-defined attributes in 
ASTMatchers.

So I'll probably be poking around in that area anyway.

My imaginary API for that is something like:

  /* find all calls to functions with my-attribute from functions without 
my-attribute
  Finder->addMatcher(callExpr(
callee(
   functionDecl(
hasAttr(MyAttribute)
)
   )
hasAncestor(
functionDecl(
 
unless(hasAttr(MyAttribute))
 
).bind("containing-function")
)
).bind("call"), this);

where "MyAttribute" is the plugin defined attribute.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

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


[PATCH] D144402: [clang] Move ParsedAttrInfo from Sema to Basic (NFC)

2023-03-13 Thread Anders Waldenborg 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 rG383cfeee09d1: [clang] Move ParsedAttrInfo from Sema to Basic 
(NFC) (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144402

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp

Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -26,8 +26,6 @@
 
 using namespace clang;
 
-LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
-
 IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,
  IdentifierInfo *Ident) {
   IdentifierLoc *Result = new (Ctx) IdentifierLoc;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- /dev/null
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -0,0 +1,18 @@
+//===- ParsedAttrInfo.cpp - Registry for attribute plugins --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file contains the Registry of attributes added by plugins which
+// derive the ParsedAttrInfo class.
+//
+//===--===//
+
+#include "clang/Basic/ParsedAttrInfo.h"
+
+using namespace clang;
+
+LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
Index: clang/lib/Basic/CMakeLists.txt
===
--- clang/lib/Basic/CMakeLists.txt
+++ clang/lib/Basic/CMakeLists.txt
@@ -61,6 +61,7 @@
   OpenCLOptions.cpp
   OpenMPKinds.cpp
   OperatorPrecedence.cpp
+  ParsedAttrInfo.cpp
   ProfileList.cpp
   NoSanitizeList.cpp
   SanitizerSpecialCaseList.cpp
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -17,12 +17,12 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Allocator.h"
-#include "llvm/Support/Registry.h"
 #include "llvm/Support/VersionTuple.h"
 #include 
 #include 
@@ -36,124 +36,10 @@
 class Expr;
 class IdentifierInfo;
 class LangOptions;
-class ParsedAttr;
 class Sema;
 class Stmt;
 class TargetInfo;
 
-struct ParsedAttrInfo {
-  /// Corresponds to the Kind enum.
-  unsigned AttrKind : 16;
-  /// The number of required arguments of this attribute.
-  unsigned NumArgs : 4;
-  /// The number of optional arguments of this attributes.
-  unsigned OptArgs : 4;
-  /// The number of non-fake arguments specified in the attribute definition.
-  unsigned NumArgMembers : 4;
-  /// True if the parsing does not match the semantic content.
-  unsigned HasCustomParsing : 1;
-  // True if this attribute accepts expression parameter pack expansions.
-  unsigned AcceptsExprPack : 1;
-  /// True if this attribute is only available for certain targets.
-  unsigned IsTargetSpecific : 1;
-  /// True if this attribute applies to types.
-  unsigned IsType : 1;
-  /// True if this attribute applies to statements.
-  unsigned IsStmt : 1;
-  /// True if this attribute has any spellings that are known to gcc.
-  unsigned IsKnownToGCC : 1;
-  /// True if this attribute is supported by #pragma clang attribute.
-  unsigned IsSupportedByPragmaAttribute : 1;
-  /// The syntaxes supported by this attribute and how they're spelled.
-  struct Spelling {
-AttributeCommonInfo::Syntax Syntax;
-const char *NormalizedFullName;
-  };
-  ArrayRef Spellings;
-  // The names of the known arguments of this attribute.
-  ArrayRef ArgNames;
-
-protected:
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind =
-   AttributeCommonInfo::NoSemaHandlerAttribute)
-  : AttrKind(AttrKind), NumArgs(0), OptArgs(0), NumArgMembers(0),
-HasCustomParsing(0), AcceptsExprPack(0), IsTargetSpecific(0), IsType(0),
-IsStmt(0), IsKnownToGCC(0), IsSupportedByPragmaAttribute(0) {}
-
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind, unsigned NumArgs,
-   unsigned OptArgs, unsigned NumArgMembers,
-   unsigned HasCustomParsing,

[PATCH] D145769: [clang] Extract ParsedAttrInfo::hasSpelling method (NFC)

2023-03-13 Thread Anders Waldenborg 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 rG446f78092ffa: [clang] Extract ParsedAttrInfo::hasSpelling 
method (NFC) (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145769

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) const {
+return llvm::any_of(Spellings, [&](const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
   for (auto &Ptr : getAttributePluginInstances())
-for (auto &S : Ptr->Spellings)
-  if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
-return *Ptr;
+if (Ptr->hasSpelling(SyntaxUsed, FullName))
+  return *Ptr;
 
   // If we failed to find a match then return a default ParsedAttrInfo.
   static const ParsedAttrInfo DefaultParsedAttrInfo(
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@
 public:
   virtual ~ParsedAttrInfo() = default;
 
+  /// Check if this attribute has specified spelling.
+  bool hasSpelling(AttributeCommonInfo::Syntax Syntax, StringRef Name) const {
+return llvm::any_of(Spellings, [&](const Spelling &S) {
+  return (S.Syntax == Syntax && S.NormalizedFullName == Name);
+});
+  }
+
   /// Check if this attribute appertains to D, and issue a diagnostic if not.
   virtual bool diagAppertainsToDecl(Sema &S, const ParsedAttr &Attr,
 const Decl *D) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144403: [clang] Extract attribute plugin instantiation to function (NFC)

2023-03-13 Thread Anders Waldenborg 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 rGf5f1813defb5: [clang] Extract attribute plugin instantiation 
to function (NFC) (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144403

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -12,7 +12,21 @@
 
//===--===//
 
 #include "clang/Basic/ParsedAttrInfo.h"
+#include "llvm/Support/ManagedStatic.h"
+#include 
+#include 
 
 using namespace clang;
 
 LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
+
+const std::list> &
+clang::getAttributePluginInstances() {
+  static llvm::ManagedStatic>>
+  PluginAttrInstances;
+  if (PluginAttrInstances->empty())
+for (auto It : ParsedAttrInfoRegistry::entries())
+  PluginAttrInstances->emplace_back(It.instantiate());
+
+  return *PluginAttrInstances;
+}
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -20,6 +20,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/Registry.h"
 #include 
+#include 
 
 namespace clang {
 
@@ -137,6 +138,8 @@
 
 typedef llvm::Registry ParsedAttrInfoRegistry;
 
+const std::list> 
&getAttributePluginInstances();
+
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_PARSEDATTRINFO_H


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -12,7 +12,21 @@
 //===--===//
 
 #include "clang/Basic/ParsedAttrInfo.h"
+#include "llvm/Support/ManagedStatic.h"
+#inclu

[PATCH] D144404: [clang] Extract function for generated part of clang::hasAttribute (NFC)

2023-03-13 Thread Anders Waldenborg 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 rG8629343a8b6c: [clang] Extract function for generated part of 
clang::hasAttribute (NFC) (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144404

Files:
  clang/lib/Basic/Attributes.cpp


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo 
*Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) 
{
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo *Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) {
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-13 Thread Anders Waldenborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1285a495d588: [clang][pp] Handle attributes defined by 
plugin in __has_attribute (authored by wanders).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144405

Files:
  clang/docs/ReleaseNotes.rst
  clang/examples/Attribute/Attribute.cpp
  clang/lib/Basic/Attributes.cpp
  clang/test/Frontend/plugin-attribute-pp.cpp


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s | FileCheck %s
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s -x c | 
FileCheck %s
+// REQUIRES: plugins, examples
+
+#ifdef __cplusplus
+# define HAS_ATTR(a) __has_cpp_attribute (a)
+#else
+# define HAS_ATTR(a) __has_c_attribute (a)
+#endif
+
+#if __has_attribute(example)
+// CHECK: has_attribute(example) was true
+has_attribute(example) was true
+#endif
+#if HAS_ATTR(example)
+// CHECK: has_$LANG_attribute(example) was true
+has_$LANG_attribute(example) was true
+#endif
+
+#if __has_attribute(doesnt_exist)
+// CHECK-NOT: has_attribute(doesnt_exist) unexpectedly was true
+has_attribute(doesnt_exist) unexpectedly was true
+#endif
+
+#if HAS_ATTR(doesnt_exist)
+// CHECK-NOT: has_$LANG_attribute(doesnt_exist) unexpectedly was true
+has_$LANG_attribute(doesnt_exist) unexpectedly was true
+#endif
Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -2,6 +2,7 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 using namespace clang;
 
 static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
@@ -40,6 +41,11 @@
   if (res)
 return res;
 
+  // Check if any plugin provides this attribute.
+  for (auto &Ptr : getAttributePluginInstances())
+if (Ptr->hasSpelling(Syntax, Name))
+  return 1;
+
   return 0;
 }
 
Index: clang/examples/Attribute/Attribute.cpp
===
--- clang/examples/Attribute/Attribute.cpp
+++ clang/examples/Attribute/Attribute.cpp
@@ -9,6 +9,8 @@
 // Example clang plugin which adds an an annotation to file-scope declarations
 // with the 'example' attribute.
 //
+// This plugin is used by clang/test/Frontend/plugin-attribute tests.
+//
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
@@ -27,9 +29,10 @@
 // number of arguments. This just illustrates how many arguments a
 // `ParsedAttrInfo` can hold, we will not use that much in this example.
 OptArgs = 15;
-// GNU-style __attribute__(("example")) and C++-style [[example]] and
+// GNU-style __attribute__(("example")) and C++/C2x-style [[example]] and
 // [[plugin::example]] supported.
 static constexpr Spelling S[] = {{ParsedAttr::AS_GNU, "example"},
+ {ParsedAttr::AS_C2x, "example"},
  {ParsedAttr::AS_CXX11, "example"},
  {ParsedAttr::AS_CXX11, 
"plugin::example"}};
 Spellings = S;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -147,6 +147,8 @@
   uses the optional USR value when indexing Clang's AST. This value is expected
   to be generated by an external compiler when generating C++ bindings during
   the compilation of the foreign language sources (e.g. Swift).
+- The ``__has_attribute``, ``__has_c_attribute`` and ``__has_cpp_attribute``
+  preprocessor operators now return 1 also for attributes defined by plugins.
 
 Improvements to Clang's diagnostics
 ---


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s | FileCheck %s
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %s -x c | FileCheck %s
+// REQUIRES: plugins, examples
+
+#ifdef __cplusplus
+# define HAS_ATTR(a) __has_cpp_attribute (a)
+#else
+# define HAS_ATTR(a) __has_c_attribute (a)
+#endif
+
+#if __has_attribute(example)
+// CHECK: has_attribute(example) was true
+has_attribute(example) was true
+#endif
+#if HAS_ATTR(example)
+// CHECK: has_$LANG_attribute(example) was true
+has_$LANG_attribute(example) was true
+#endif
+
+#if __has_attribute(doesnt_exist)
+// CHECK-NOT: has_attribute(doesnt_exist

[PATCH] D144402: [clang] Move ParsedAttrInfo from Sema to Basic (NFC) r=aaron.ballman

2023-02-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This moves the ParsedAttrInfo class and the registry for attribute
plugin to be part of Basic module instead of Sema module.

This will allow it to be accessed from preprocessor later on.

No functional change intended.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144402

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp

Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -26,8 +26,6 @@
 
 using namespace clang;
 
-LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
-
 IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,
  IdentifierInfo *Ident) {
   IdentifierLoc *Result = new (Ctx) IdentifierLoc;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- /dev/null
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -0,0 +1,18 @@
+//===- ParsedAttrInfo.cpp - Registry for attribute plugins --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file contains the Registry of attributes added by plugins which
+// derive the ParsedAttrInfo class.
+//
+//===--===//
+
+#include "clang/Basic/ParsedAttrInfo.h"
+
+using namespace clang;
+
+LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
Index: clang/lib/Basic/CMakeLists.txt
===
--- clang/lib/Basic/CMakeLists.txt
+++ clang/lib/Basic/CMakeLists.txt
@@ -61,6 +61,7 @@
   OpenCLOptions.cpp
   OpenMPKinds.cpp
   OperatorPrecedence.cpp
+  ParsedAttrInfo.cpp
   ProfileList.cpp
   NoSanitizeList.cpp
   SanitizerSpecialCaseList.cpp
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -17,12 +17,12 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Allocator.h"
-#include "llvm/Support/Registry.h"
 #include "llvm/Support/VersionTuple.h"
 #include 
 #include 
@@ -36,124 +36,10 @@
 class Expr;
 class IdentifierInfo;
 class LangOptions;
-class ParsedAttr;
 class Sema;
 class Stmt;
 class TargetInfo;
 
-struct ParsedAttrInfo {
-  /// Corresponds to the Kind enum.
-  unsigned AttrKind : 16;
-  /// The number of required arguments of this attribute.
-  unsigned NumArgs : 4;
-  /// The number of optional arguments of this attributes.
-  unsigned OptArgs : 4;
-  /// The number of non-fake arguments specified in the attribute definition.
-  unsigned NumArgMembers : 4;
-  /// True if the parsing does not match the semantic content.
-  unsigned HasCustomParsing : 1;
-  // True if this attribute accepts expression parameter pack expansions.
-  unsigned AcceptsExprPack : 1;
-  /// True if this attribute is only available for certain targets.
-  unsigned IsTargetSpecific : 1;
-  /// True if this attribute applies to types.
-  unsigned IsType : 1;
-  /// True if this attribute applies to statements.
-  unsigned IsStmt : 1;
-  /// True if this attribute has any spellings that are known to gcc.
-  unsigned IsKnownToGCC : 1;
-  /// True if this attribute is supported by #pragma clang attribute.
-  unsigned IsSupportedByPragmaAttribute : 1;
-  /// The syntaxes supported by this attribute and how they're spelled.
-  struct Spelling {
-AttributeCommonInfo::Syntax Syntax;
-const char *NormalizedFullName;
-  };
-  ArrayRef Spellings;
-  // The names of the known arguments of this attribute.
-  ArrayRef ArgNames;
-
-protected:
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind =
-   AttributeCommonInfo::NoSemaHandlerAttribute)
-  : AttrKind(AttrKind), NumArgs(0), OptArgs(0), NumArgMembers(0),
-HasCustomParsing(0), AcceptsExprPack(0), IsTargetSpecific(0), IsType(0),
-IsStmt(0), IsKnownToGCC(0), IsSupportedByPragmaAttribute(0) {}
-
-  constexpr ParsedAttrInfo(AttributeCommonInfo::Kind AttrKind, unsigned Num

[PATCH] D144403: [clang] Extract attribute plugin instantiation to function (NFC) r=aaron.ballman

2023-02-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This moves the code to instantiate the attribute plugins to the same
place where the plugin registry is defined so they live together and the
user of the plugins doesn't have the burden of instantiating the
plugins.

No functional change intended.

Depends on D144402 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144403

Files:
  clang/include/clang/Basic/ParsedAttrInfo.h
  clang/lib/Basic/ParsedAttrInfo.cpp
  clang/lib/Sema/ParsedAttr.cpp


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttrInfo.cpp
@@ -12,7 +12,21 @@
 
//===--===//
 
 #include "clang/Basic/ParsedAttrInfo.h"
+#include "llvm/Support/ManagedStatic.h"
+#include 
+#include 
 
 using namespace clang;
 
 LLVM_INSTANTIATE_REGISTRY(ParsedAttrInfoRegistry)
+
+const std::list> &
+clang::getAttributePluginInstances() {
+  static llvm::ManagedStatic>>
+  PluginAttrInstances;
+  if (PluginAttrInstances->empty())
+for (auto It : ParsedAttrInfoRegistry::entries())
+  PluginAttrInstances->emplace_back(It.instantiate());
+
+  return *PluginAttrInstances;
+}
Index: clang/include/clang/Basic/ParsedAttrInfo.h
===
--- clang/include/clang/Basic/ParsedAttrInfo.h
+++ clang/include/clang/Basic/ParsedAttrInfo.h
@@ -20,6 +20,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/Registry.h"
 #include 
+#include 
 
 namespace clang {
 
@@ -137,6 +138,8 @@
 
 typedef llvm::Registry ParsedAttrInfoRegistry;
 
+const std::list> 
&getAttributePluginInstances();
+
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_PARSEDATTRINFO_H


Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/ManagedStatic.h"
 #include 
 #include 
 #include 
@@ -118,13 +117,7 @@
   if (A.getParsedKind() == AttributeCommonInfo::IgnoredAttribute)
 return IgnoredParsedAttrInfo;
 
-  // Otherwise this may be an attribute defined by a plugin. First instantiate
-  // all plugin attributes if we haven't already done so.
-  static llvm::ManagedStatic>>
-  PluginAttrInstances;
-  if (PluginAttrInstances->empty())
-for (auto It : ParsedAttrInfoRegistry::entries())
-  PluginAttrInstances->emplace_back(It.instantiate());
+  // Otherwise this may be an attribute defined by a plugin.
 
   // Search for a ParsedAttrInfo whose name and syntax match.
   std::string FullName = A.getNormalizedFullName();
@@ -132,7 +125,7 @@
   if (SyntaxUsed == AttributeCommonInfo::AS_ContextSensitiveKeyword)
 SyntaxUsed = AttributeCommonInfo::AS_Keyword;
 
-  for (auto &Ptr : *PluginAttrInstances)
+  for (auto &Ptr : getAttributePluginInstances())
 for (auto &S : Ptr->Spellings)
   if (S.Syntax == SyntaxUsed && S.NormalizedFullName == FullName)
 return *Ptr;
Index: clang/lib/Basic/ParsedAttrInfo.cpp
===
--- clang/lib/Basic/ParsedAttrInfo.cpp
+++ clang/lib/Basic/ParsedAttr

[PATCH] D144404: [clang] Extract function for generated part of clang::hasAttribute (NFC) r=aaron.ballman

2023-02-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This makes it easier to add additional handling when the
tablegen-generated code does not find a match.

No functional change intended.

Depends on D144403 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144404

Files:
  clang/lib/Basic/Attributes.cpp


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo 
*Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) 
{
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }


Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -4,6 +4,15 @@
 #include "clang/Basic/IdentifierTable.h"
 using namespace clang;
 
+static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
+StringRef ScopeName, const TargetInfo &Target,
+const LangOptions &LangOpts) {
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
+  return 0;
+}
+
 int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 const IdentifierInfo *Scope, const IdentifierInfo *Attr,
 const TargetInfo &Target, const LangOptions &LangOpts) {
@@ -27,7 +36,9 @@
   ScopeName == "omp")
 return (Name == "directive" || Name == "sequence") ? 1 : 0;
 
-#include "clang/Basic/AttrHasAttributeImpl.inc"
+  int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
+  if (res)
+return res;
 
   return 0;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144405: [clang][pp] Handle attributes defined by plugin in __has_attribute r=aaron.ballman

2023-02-20 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When using attributes by plugins (both in clang and clang-tidy) the
preprocessor functions `__has_attribute`, `__has_c_attribute`,
`__has_cpp_attribute` still returned 0.

That problem is fixed by having the "hasAttribute" function also check
if any of the plugins provide that attribute.

This also adds C2x spelling to the example plugin for attributes so that
`__has_c_attribute` can be tested.

Depends on D144404 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144405

Files:
  clang/examples/Attribute/Attribute.cpp
  clang/lib/Basic/Attributes.cpp
  clang/test/Frontend/plugin-attribute-pp.cpp


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,36 @@
+// RUN: split-file %s %t
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.cpp | 
FileCheck %t/has_attr.cpp
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.c | 
FileCheck %t/has_attr.c
+// REQUIRES: plugins, examples
+
+
+//--- has_attr.cpp
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_cpp_attribute (example)
+// CHECK: YES - It did cpp-exist
+YES - It did cpp-exist
+#endif
+
+#if __has_attribute (doesnt_exist)
+// CHECK-NOT: NO - There is no such attribute
+NO - There is no such attribute
+#endif
+
+
+//--- has_attr.c
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_c_attribute (example)
+// CHECK: YES - It did c-exist
+YES - It did c-exist
+#endif
+
+#if __has_attribute (doesnt_exist)
+// CHECK-NOT: NO - There is no such attribute
+NO - There is no such attribute
+#endif
Index: clang/lib/Basic/Attributes.cpp
===
--- clang/lib/Basic/Attributes.cpp
+++ clang/lib/Basic/Attributes.cpp
@@ -2,6 +2,7 @@
 #include "clang/Basic/AttrSubjectMatchRules.h"
 #include "clang/Basic/AttributeCommonInfo.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/ParsedAttrInfo.h"
 using namespace clang;
 
 static int hasAttributeImpl(AttributeCommonInfo::Syntax Syntax, StringRef Name,
@@ -40,6 +41,13 @@
   if (res)
 return res;
 
+  // Check if any plugin provides this attribute.
+  for (auto &AttrPlugin : getAttributePluginInstances()) {
+for (auto &S : AttrPlugin->Spellings)
+  if (S.Syntax == Syntax && S.NormalizedFullName == Name)
+return 1;
+  }
+
   return 0;
 }
 
Index: clang/examples/Attribute/Attribute.cpp
===
--- clang/examples/Attribute/Attribute.cpp
+++ clang/examples/Attribute/Attribute.cpp
@@ -9,6 +9,8 @@
 // Example clang plugin which adds an an annotation to file-scope declarations
 // with the 'example' attribute.
 //
+// This plugin is used by clang/test/Frontend/plugin-attribute tests.
+//
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
@@ -27,9 +29,10 @@
 // number of arguments. This just illustrates how many arguments a
 // `ParsedAttrInfo` can hold, we will not use that much in this example.
 OptArgs = 15;
-// GNU-style __attribute__(("example")) and C++-style [[example]] and
+// GNU-style __attribute__(("example")) and C++/C2x-style [[example]] and
 // [[plugin::example]] supported.
 static constexpr Spelling S[] = {{ParsedAttr::AS_GNU, "example"},
+ {ParsedAttr::AS_C2x, "example"},
  {ParsedAttr::AS_CXX11, "example"},
  {ParsedAttr::AS_CXX11, 
"plugin::example"}};
 Spellings = S;


Index: clang/test/Frontend/plugin-attribute-pp.cpp
===
--- /dev/null
+++ clang/test/Frontend/plugin-attribute-pp.cpp
@@ -0,0 +1,36 @@
+// RUN: split-file %s %t
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.cpp | FileCheck %t/has_attr.cpp
+// RUN: %clang -fplugin=%llvmshlibdir/Attribute%pluginext -E %t/has_attr.c | FileCheck %t/has_attr.c
+// REQUIRES: plugins, examples
+
+
+//--- has_attr.cpp
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_cpp_attribute (example)
+// CHECK: YES - It did cpp-exist
+YES - It did cpp-exist
+#endif
+
+#if __has_attribute (doesnt_exist)
+// CHECK-NOT: NO - There is no such attribute
+NO - There is no such attribute
+#endif
+
+
+//--- has_attr.c
+#if __has_attribute (example)
+// CHECK: YES - It did exist
+YES - It did exist
+#endif
+#if __has_c_attri

[PATCH] D101139: Create install targets for scan-build-py.

2021-05-03 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added inline comments.



Comment at: clang/tools/scan-build-py/CMakeLists.txt:8
+ "bin/intercept-cc"
+ "bin/scan-build")
+

This overwrites the "bin/scan-build" that was installed from the scan-build (no 
-py) subdirectory.

So with this  "scan-build" will suddenly mean the python variant instead of the 
per variant. That might be fine (?), but can't be a good idea to have that done 
by first installing the perl scan-build and then overwriting it with the python 
scan-build.  Also the man-page that the perl variant installs is not 
overwritten so "man scan-build" will show manual page for the perl variant.


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

https://reviews.llvm.org/D101139

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