Skip to content

Commit d5cef39

Browse files
authored
[Clang] Make '-Wglobal-constructors` work on the GNU attributes (#129917)
Summary: The `-Wglobal-constructors` option is useful for restricting the usage of global constructors / destructors. However, it currently ignores the attributes that introduce global constructors, meaning that the module can still have ctors if `-Werror` is set. If this is intentional by the user, I believe it would be more correct to push the diagnostic.
1 parent f5eeeec commit d5cef39

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ AST Dumping Potentially Breaking Changes
6262
Clang Frontend Potentially Breaking Changes
6363
-------------------------------------------
6464

65+
- The ``-Wglobal-constructors`` flag now applies to ``[[gnu::constructor]]`` and
66+
``[[gnu::destructor]]`` attributes.
67+
6568
Clang Python Bindings Potentially Breaking Changes
6669
--------------------------------------------------
6770

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2138,6 +2138,8 @@ static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
21382138
if (AL.getNumArgs() &&
21392139
!S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
21402140
return;
2141+
S.Diag(D->getLocation(), diag::warn_global_constructor)
2142+
<< D->getSourceRange();
21412143

21422144
D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
21432145
}
@@ -2147,6 +2149,7 @@ static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
21472149
if (AL.getNumArgs() &&
21482150
!S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
21492151
return;
2152+
S.Diag(D->getLocation(), diag::warn_global_destructor) << D->getSourceRange();
21502153

21512154
D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
21522155
}

clang/test/SemaCXX/attr-require-constant-initialization.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,11 @@ constexpr TestCtor<NotC> inval_constexpr(42); // expected-error {{must be initia
337337
ATTR constexpr TestCtor<NotC> inval_constexpr2(42); // expected-error {{must be initialized by a constant expression}}
338338
// expected-note@-1 {{in call to 'TestCtor(42)'}}
339339

340+
[[gnu::constructor]] void ctor() {}
341+
// expected-warning@-1 {{declaration requires a global constructor}}
342+
[[gnu::destructor]] void dtor() {}
343+
// expected-warning@-1 {{declaration requires a global destructor}}
344+
340345
#elif defined(TEST_THREE)
341346
#if defined(__cplusplus)
342347
#error This test requires C

0 commit comments

Comments
 (0)