[clang] 6d7ec54 - [clang-format] Make sure rst documentation matches comments

2020-07-18 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2020-07-18T18:02:14+02:00
New Revision: 6d7ec54170f9ef68710f484299caa1a6dd42ff48

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

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

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.

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index e84676760c30..6647b117ac59 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2694,8 +2694,11 @@ the configuration (without a prefix: ``Auto``).
 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 @@ the configuration (without a prefix: ``Auto``).
 
 WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
 
-  For example: BOOST_PP_STRINGIZE.
-
-
+  For example: BOOST_PP_STRINGIZE
 
 .. END_FORMAT_STYLE_OPTIONS
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3549ec9eee0e..7201c11f1158 100755
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1425,15 +1425,20 @@ struct FormatStyle {
   /// 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;



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


[Differential] D84090: Test revision5 (ignore)

2020-07-20 Thread Anders Waldenborg 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).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D84090?vs=278987&id=279025#toc

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

[clang] 52ab7aa - [clang-format] Add BitFieldColonSpacing option

2020-07-20 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2020-07-20T20:55:51+02:00
New Revision: 52ab7aa0ba5a3c7a0b2fe1b48519f1d4dc52cacf

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

LOG: [clang-format] Add BitFieldColonSpacing option

This new option allows controlling if there should be spaces around
the ':' in a bitfield declaration.

BitFieldColonSpacing accepts four different values:

  // "Both" - default
  unsigned bitfield : 5
  unsigned bf2  : 5  // AlignConsecutiveBitFields=true

  // "None"
  unsigned bitfield:5
  unsigned bf2 :5

  // "Before"
  unsigned bitfield :5
  unsigned bf2  :5

  // "After"
  unsigned bitfield: 5
  unsigned bf2 : 5

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

Added: 


Modified: 
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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6647b117ac59..c35718b51248 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -794,6 +794,43 @@ the configuration (without a prefix: ``Auto``).
int ,
int aaa) {}
 
+**BitFieldColonSpacing** (``BitFieldColonSpacingStyle``)
+  The BitFieldColonSpacingStyle to use for bitfields.
+
+  Possible values:
+
+  * ``BFCS_Both`` (in configuration: ``Both``)
+Add one space on each side of the ``:``
+
+.. code-block:: c++
+
+  unsigned bf : 2;
+
+  * ``BFCS_None`` (in configuration: ``None``)
+Add no space around the ``:`` (except when needed for
+``AlignConsecutiveBitFields``).
+
+.. code-block:: c++
+
+  unsigned bf:2;
+
+  * ``BFCS_Before`` (in configuration: ``Before``)
+Add space before the ``:`` only
+
+.. code-block:: c++
+
+  unsigned bf :2;
+
+  * ``BFCS_After`` (in configuration: ``After``)
+Add space after the ``:`` only (space may be added before if
+needed for ``AlignConsecutiveBitFields``).
+
+.. code-block:: c++
+
+  unsigned bf: 2;
+
+
+
 **BraceWrapping** (``BraceWrappingFlags``)
   Control of individual brace wrapping cases.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 10ead604239c..21689c5c5d85 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -149,7 +149,33 @@ AST Matchers
 clang-format
 
 
-- ...
+- Option ``BitFieldColonSpacing`` has been added that decides how
+  space should be added around identifier, colon and bit-width in
+  bitfield definitions.
+
+  .. code-block:: c++
+
+// Both (default)
+struct F {
+  unsigned dscp : 6;
+  unsigned ecn  : 2; // AlignConsecutiveBitFields=true
+};
+// None
+struct F {
+  unsigned dscp:6;
+  unsigned ecn :2;
+};
+// Before
+struct F {
+  unsigned dscp :6;
+  unsigned ecn  :2;
+};
+// After
+struct F {
+  unsigned dscp: 6;
+  unsigned ecn : 2;
+};
+
 
 libclang
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
old mode 100755
new mode 100644
index 7201c11f1158..269eab971a2c
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2233,6 +2233,34 @@ struct FormatStyle {
   /// \endcode
   bool SpaceBeforeSquareBrackets;
 
+  /// Styles for adding spacing around ``:`` in bitfield definitions.
+  enum BitFieldColonSpacingStyle {
+/// Add one space on each side of the ``:``
+/// \code
+///   unsigned bf : 2;
+/// \endcode
+BFCS_Both,
+/// Add no space around the ``:`` (except when needed for
+/// ``AlignConsecutiveBitFields``).
+/// \code
+///   unsigned bf:2;
+/// \endcode
+BFCS_None,
+/// Add space before the ``:`` only
+/// \code
+///   unsigned bf :2;
+/// \endcode
+BFCS_Before,
+/// Add space after the ``:`` only (space may be added before if
+/// needed for ``AlignConsecutiveBitFields``).
+/// \code
+///   unsigned bf: 2;
+/// \endcode
+BFCS_After
+  };
+  /// The BitFieldColonSpacingStyle to use for bitfields.
+  BitFieldColonSpacingStyle BitFieldColonSpacing;
+
   /// Supported language standards for parsing and formatting C++ constructs.
   /// \code
   ///Latest:vector>
@@ -2409,6 +2437,7 @@ struct FormatStyle {
SpacesInParentheses == R.SpacesInParentheses &&
SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
+   BitFieldColo

[clang] ff4abe7 - [scan-build-py] Fix exception on shutdown with sarif-html output format

2022-06-10 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2022-06-10T23:21:09+02:00
New Revision: ff4abe755279a3a47cc416ef80dbc900d9a98a19

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

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

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.

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

Added: 


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

Removed: 




diff  --git a/clang/tools/scan-build-py/lib/libscanbuild/analyze.py 
b/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
index 08802de81cc5..2633139fd523 100644
--- a/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
+++ b/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
@@ -357,6 +357,7 @@ def report_directory(hint, keep, output_format):
 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 @@ def report_directory(hint, keep, output_format):
 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 @@ def report_directory(hint, keep, output_format):
 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


[clang] 657e954 - [clang] Add tests for statement expression in initializers

2022-06-14 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2022-06-14T23:16:41+02:00
New Revision: 657e954939c8a7d33c40291ef3214333a1e2ca5b

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

LOG: [clang] Add tests for statement expression in initializers

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.

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

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

Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8766adb27a09a..7d84933b43bca 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -170,6 +170,11 @@ Bug Fixes
   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
 ^^^

diff  --git a/clang/test/CodeGen/stmtexpr-init.c 
b/clang/test/CodeGen/stmtexpr-init.c
new file mode 100644
index 0..e2db75518e9a4
--- /dev/null
+++ b/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);
+}

diff  --git a/clang/test/Sema/stmtexpr-init.c b/clang/test/Sema/stmtexpr-init.c
new file mode 100644
index 0..73c87e0d4b726
--- /dev/null
+++ b/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}}
+}



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


[clang] 86f9cf8 - [clang] Add tests for (const) weak variables

2022-06-01 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2022-06-01T20:18:54+02:00
New Revision: 86f9cf88cb06d36e37ef8de006b2a0b651c9b7e9

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

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

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.

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

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

Modified: 


Removed: 




diff  --git a/clang/test/CodeGenCXX/weak-init.cpp 
b/clang/test/CodeGenCXX/weak-init.cpp
new file mode 100644
index 0..634021f38f854
--- /dev/null
+++ b/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;

diff  --git a/clang/test/SemaCXX/weak-init.cpp 
b/clang/test/SemaCXX/weak-init.cpp
new file mode 100644
index 0..c040330bb274a
--- /dev/null
+++ b/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 
diff erent 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 
diff erent at runtime}}



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


[clang] 4c1e487 - scan-build-py: Change scripts to explicitly require python3

2022-06-02 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2022-06-02T20:08:21+02:00
New Revision: 4c1e487c413810655757ea19d0cf3d4f5c40898e

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

LOG: scan-build-py: Change scripts to explicitly require python3

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.

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

Added: 


Modified: 
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

Removed: 




diff  --git a/clang/tools/scan-build-py/bin/analyze-build 
b/clang/tools/scan-build-py/bin/analyze-build
index b3f61429906c4..636b5aa4dd36d 100755
--- a/clang/tools/scan-build-py/bin/analyze-build
+++ b/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.

diff  --git a/clang/tools/scan-build-py/bin/intercept-build 
b/clang/tools/scan-build-py/bin/intercept-build
index 9ecde39984434..dcd0473ef5489 100755
--- a/clang/tools/scan-build-py/bin/intercept-build
+++ b/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.

diff  --git a/clang/tools/scan-build-py/bin/scan-build 
b/clang/tools/scan-build-py/bin/scan-build
index a341751d993a2..3e5a5ade304c2 100755
--- a/clang/tools/scan-build-py/bin/scan-build
+++ b/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.

diff  --git a/clang/tools/scan-build-py/libexec/analyze-c++ 
b/clang/tools/scan-build-py/libexec/analyze-c++
index a280b2fb4ddaf..5c72dfff4a896 100755
--- a/clang/tools/scan-build-py/libexec/analyze-c++
+++ b/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.

diff  --git a/clang/tools/scan-build-py/libexec/analyze-cc 
b/clang/tools/scan-build-py/libexec/analyze-cc
index 36bbcd93f9871..fbdbde8f5b2e6 100755
--- a/clang/tools/scan-build-py/libexec/analyze-cc
+++ b/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.

diff  --git a/clang/tools/scan-build-py/libexec/intercept-c++ 
b/clang/tools/scan-build-py/libexec/intercept-c++
index 9e541a180d6b4..b8c8e923ec76e 100755
--- a/clang/tools/scan-build-py/libexec/intercept-c++
+++ b/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.

diff  --git a/clang/tools/scan-build-py/libexec/intercept-cc 
b/clang/tools/scan-build-py/libexec/intercept-cc
index 9e541a180d6b4..b8c8e923ec76e 100755
--- a/clang/tools/scan-build-py/libexec/intercept-cc
+++ b/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 LL

[clang] dd2362a - [clang] Allow const variables with weak attribute to be overridden

2022-06-03 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2022-06-03T23:44:15+02:00
New Revision: dd2362a8bab312dffc42bfcb30ad1340840ef581

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

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

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

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

Added: 


Modified: 
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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bcd7ec1b9316..c37773840147 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -336,6 +336,9 @@ Attribute Changes in Clang
   builtins (corresponding to the specific names listed in the attribute) in the
   body of the function the attribute is on.
 
+- When the ``weak`` attribute is applied to a const qualified variable clang 
no longer
+  tells the backend it is allowed to optimize based on initializer value.
+
 Windows Support
 ---
 

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 464432350127..fe6295f3069c 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2959,7 +2959,7 @@ def WarnUnusedResult : InheritableAttr {
 def Weak : InheritableAttr {
   let Spellings = [GCC<"weak">];
   let Subjects = SubjectList<[Var, Function, CXXRecord]>;
-  let Documentation = [Undocumented];
+  let Documentation = [WeakDocs];
   let SimpleHandler = 1;
 }
 

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index aedf11a70753..872eb8a26673 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@ is only supported in compute shaders.
 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 
diff erent 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_log ("Starting up...");
+
+  /* This may print something else than "6 * 7 = 42",
+ if there is a non-weak definition of "ANSWER" in
+an object linked in */
+  printf("6 * 7 = %d\n", ANSWER);
+
+  return 0;
+   }
+
+If an external declaration is marked weak and that symbol does not
+exist during linking (possibly dynamic) the address of the symbol will
+evaluate to NULL.
+
+.. code-block:: c
+
+  void may_not_exist(void) __attribute__ ((weak));
+
+  int main(int argc, const char **argv)
+  {
+  if (may_not_exist) {
+  may_not_exist();
+  } else {
+  printf("Function did not exist\n");
+  }

[clang] [NFC] Minimize header includes (PR #66339)

2023-09-14 Thread Anders Waldenborg via cfe-commits

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

LGTM.

Assuming that clang/examples/Attribute/ still compiles fine  (it should be part 
of clang/test/Frontend/ tests)

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


[clang] 86825db - [clang-format] Make '.clang-format' variants finding a loop (NFC)

2019-11-07 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2019-11-07T10:00:04+01:00
New Revision: 86825dbe3306d296094432feb4a7af7d385d6b1d

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

LOG: [clang-format] Make '.clang-format' variants finding a loop (NFC)

This simplifies logic making it trivial to add searching for other
files later.

Differential revision: https://reviews.llvm.org/D68568

Added: 


Modified: 
clang/lib/Format/Format.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index cd44c0be85f0..50a687730932 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@ llvm::Expected getStyle(StringRef 
StyleName, StringRef FileName,
   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 @@ llvm::Expected getStyle(StringRef 
StyleName, StringRef FileName,
   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())



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


[clang] 383cfee - [clang] Move ParsedAttrInfo from Sema to Basic (NFC)

2023-03-13 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2023-03-13T16:47:51+01:00
New Revision: 383cfeee09d1f345d08f396f2b7295b36830c88e

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

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

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.

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

Added: 
clang/include/clang/Basic/ParsedAttrInfo.h
clang/lib/Basic/ParsedAttrInfo.cpp

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

Removed: 




diff  --git a/clang/include/clang/Basic/ParsedAttrInfo.h 
b/clang/include/clang/Basic/ParsedAttrInfo.h
new file mode 100644
index 0..3dc022aa4db3e
--- /dev/null
+++ b/clang/include/clang/Basic/ParsedAttrInfo.h
@@ -0,0 +1,142 @@
+//===- ParsedAttrInfo.h - Info needed to parse an attribute -*- 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 defines the ParsedAttrInfo class, which dictates how to
+// parse an attribute. This class is the one that plugins derive to
+// define a new attribute.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_BASIC_PARSEDATTRINFO_H
+#define LLVM_CLANG_BASIC_PARSEDATTRINFO_H
+
+#include "clang/Basic/AttrSubjectMatchRules.h"
+#include "clang/Basic/AttributeCommonInfo.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/Registry.h"
+#include 
+
+namespace clang {
+
+class Decl;
+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,
+   unsigned IsSupportedByPragmaAttribute,
+   ArrayRef Spellings,
+   ArrayRef ArgNames)
+  : AttrKind(AttrKind), NumArgs(NumArgs), OptArgs(OptArgs),
+NumArgMembers(NumArgMembers), HasCustomParsing(HasCustomParsing),
+AcceptsExprPack(AcceptsExprPack), IsTargetSpecific(IsTargetSpecific),
+IsType(IsType), IsStmt(IsStmt), IsKnownToGCC(IsKnownToGCC),
+IsSupportedByPragmaAttribute(IsSupportedByPragmaAttribute),
+Spellings(Spellings), ArgNames(ArgNames) {}
+
+public:
+  virtual ~ParsedAttrInfo() = default;
+
+  /// Check if this attribute appertains to D, and issue a diagnostic if 

[clang] f5f1813 - [clang] Extract attribute plugin instantiation to function (NFC)

2023-03-13 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2023-03-13T16:47:51+01:00
New Revision: f5f1813defb5810223de8f916380808a8ed34584

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

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

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.

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

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/ParsedAttrInfo.h 
b/clang/include/clang/Basic/ParsedAttrInfo.h
index 3dc022aa4db3..788c960b01bf 100644
--- a/clang/include/clang/Basic/ParsedAttrInfo.h
+++ b/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 @@ struct ParsedAttrInfo {
 
 typedef llvm::Registry ParsedAttrInfoRegistry;
 
+const std::list> 
&getAttributePluginInstances();
+
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_PARSEDATTRINFO_H

diff  --git a/clang/lib/Basic/ParsedAttrInfo.cpp 
b/clang/lib/Basic/ParsedAttrInfo.cpp
index 497e05483585..7757f30da511 100644
--- a/clang/lib/Basic/ParsedAttrInfo.cpp
+++ b/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;
+}

diff  --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index 67254e1aaf23..50191d45b100 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/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 @@ const ParsedAttrInfo &ParsedAttrInfo::get(const 
AttributeCommonInfo &A) {
   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 @@ const ParsedAttrInfo &ParsedAttrInfo::get(const 
AttributeCommonInfo &A) {
   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;



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


[clang] 8629343 - [clang] Extract function for generated part of clang::hasAttribute (NFC)

2023-03-13 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2023-03-13T16:47:51+01:00
New Revision: 8629343a8b6c26f15f02de2fdd8db440eba71937

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

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

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

No functional change intended.

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

Added: 


Modified: 
clang/lib/Basic/Attributes.cpp

Removed: 




diff  --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index a961e68f4ac1..5c168ec67da1 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/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 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
   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


[clang] 1285a49 - [clang][pp] Handle attributes defined by plugin in __has_attribute

2023-03-13 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2023-03-13T16:47:51+01:00
New Revision: 1285a495d5886b99f8d193c90b258a56f89c8937

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

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

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.

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

Added: 
clang/test/Frontend/plugin-attribute-pp.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/examples/Attribute/Attribute.cpp
clang/lib/Basic/Attributes.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 47fee3ef6b248..440fd04274777 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -147,6 +147,8 @@ Attribute Changes in Clang
   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
 ---

diff  --git a/clang/examples/Attribute/Attribute.cpp 
b/clang/examples/Attribute/Attribute.cpp
index 159b09e4b154d..24b95dde4e559 100644
--- a/clang/examples/Attribute/Attribute.cpp
+++ b/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 @@ struct ExampleAttrInfo : public ParsedAttrInfo {
 // 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;

diff  --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 5c168ec67da11..da339d5b1bab6 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/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 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
   if (res)
 return res;
 
+  // Check if any plugin provides this attribute.
+  for (auto &Ptr : getAttributePluginInstances())
+if (Ptr->hasSpelling(Syntax, Name))
+  return 1;
+
   return 0;
 }
 

diff  --git a/clang/test/Frontend/plugin-attribute-pp.cpp 
b/clang/test/Frontend/plugin-attribute-pp.cpp
new file mode 100644
index 0..94ba14e272eef
--- /dev/null
+++ b/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

[clang] 446f780 - [clang] Extract ParsedAttrInfo::hasSpelling method (NFC)

2023-03-13 Thread Anders Waldenborg via cfe-commits

Author: Anders Waldenborg
Date: 2023-03-13T16:47:51+01:00
New Revision: 446f78092ffa75274866ec40411a1c0dbec2f13d

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

LOG: [clang] Extract ParsedAttrInfo::hasSpelling method (NFC)

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

No functional change intended.

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

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/ParsedAttrInfo.h 
b/clang/include/clang/Basic/ParsedAttrInfo.h
index 788c960b01bf..f12de9ce 100644
--- a/clang/include/clang/Basic/ParsedAttrInfo.h
+++ b/clang/include/clang/Basic/ParsedAttrInfo.h
@@ -88,6 +88,13 @@ struct ParsedAttrInfo {
 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 {

diff  --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index 50191d45b100..2af688fb58c8 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -126,9 +126,8 @@ const ParsedAttrInfo &ParsedAttrInfo::get(const 
AttributeCommonInfo &A) {
 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(



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