Skip to content

Commit 92a09c0

Browse files
authored
[clang][nullability] allow _Nonnull etc on nullable class types (#82705)
This enables clang and external nullability checkers to make use of these annotations on nullable C++ class types like unique_ptr. These types are recognized by the presence of the _Nullable attribute. Nullable standard library types implicitly receive this attribute. Existing static warnings for raw pointers are extended to smart pointers: - nullptr used as return value or argument for non-null functions (`-Wnonnull`) - assigning or initializing nonnull variables with nullable values (`-Wnullable-to-nonnull-conversion`) It doesn't implicitly add these attributes based on the assume_nonnull pragma, nor warn on missing attributes where the pragma would apply them. I'm not confident that the pragma's current behavior will work well for C++ (where type-based metaprogramming is much more common than C/ObjC). We'd like to revisit this once we have more implementation experience. Support can be detected as `__has_feature(nullability_on_classes)`. This is needed for back-compatibility, as previously clang would issue a hard error when _Nullable appears on a smart pointer. UBSan's `-fsanitize=nullability` will not check smart-pointer types. It can be made to do so by synthesizing calls to `operator bool`, but that's left for future work. Discussion: https://discourse.llvm.org/t/rfc-allowing-nonnull-etc-on-smart-pointers/77201/26
1 parent 8481fb1 commit 92a09c0

20 files changed

+225
-29
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,21 @@ Attribute Changes in Clang
201201
and each must be a positive integer when provided. The parameter ``x`` is required, while ``y`` and
202202
``z`` are optional with default value of 1.
203203

204+
- The ``_Nullable`` and ``_Nonnull`` family of type attributes can now apply
205+
to certain C++ class types, such as smart pointers:
206+
``void useObject(std::unique_ptr<Object> _Nonnull obj);``.
207+
208+
This works for standard library types including ``unique_ptr``, ``shared_ptr``
209+
and ``function``. See `the attribute reference
210+
documentation <https://llvm.org/docs/AttributeReference.html#nullability-attributes>`_
211+
for the full list.
212+
213+
- The ``_Nullable`` attribute can be applied to C++ class declarations:
214+
``template <class T> class _Nullable MySmartPointer {};``.
215+
216+
This allows the ``_Nullable`` and ``_Nonnull` family of type attributes to
217+
apply to this class.
218+
204219
Improvements to Clang's diagnostics
205220
-----------------------------------
206221
- Clang now applies syntax highlighting to the code snippets it

clang/include/clang/Basic/Attr.td

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2178,9 +2178,10 @@ def TypeNonNull : TypeAttr {
21782178
let Documentation = [TypeNonNullDocs];
21792179
}
21802180

2181-
def TypeNullable : TypeAttr {
2181+
def TypeNullable : DeclOrTypeAttr {
21822182
let Spellings = [CustomKeyword<"_Nullable">];
21832183
let Documentation = [TypeNullableDocs];
2184+
// let Subjects = SubjectList<[CXXRecord], ErrorDiag>;
21842185
}
21852186

21862187
def TypeNullableResult : TypeAttr {

clang/include/clang/Basic/AttrDocs.td

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4151,6 +4151,20 @@ non-underscored keywords. For example:
41514151
@property (assign, nullable) NSView *superview;
41524152
@property (readonly, nonnull) NSArray *subviews;
41534153
@end
4154+
4155+
As well as built-in pointer types, the nullability attributes can be attached
4156+
to C++ classes marked with the ``_Nullable`` attribute.
4157+
4158+
The following C++ standard library types are considered nullable:
4159+
``unique_ptr``, ``shared_ptr``, ``auto_ptr``, ``exception_ptr``, ``function``,
4160+
``move_only_function`` and ``coroutine_handle``.
4161+
4162+
Types should be marked nullable only where the type itself leaves nullability
4163+
ambiguous. For example, ``std::optional`` is not marked ``_Nullable``, because
4164+
``optional<int> _Nullable`` is redundant and ``optional<int> _Nonnull`` is
4165+
not a useful type. ``std::weak_ptr`` is not nullable, because its nullability
4166+
can change with no visible modification, so static annotation is unlikely to be
4167+
unhelpful.
41544168
}];
41554169
}
41564170

@@ -4185,6 +4199,17 @@ The ``_Nullable`` nullability qualifier indicates that a value of the
41854199
int fetch_or_zero(int * _Nullable ptr);
41864200

41874201
a caller of ``fetch_or_zero`` can provide null.
4202+
4203+
The ``_Nullable`` attribute on classes indicates that the given class can
4204+
represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
4205+
make sense for this type. For example:
4206+
4207+
.. code-block:: c
4208+
4209+
class _Nullable ArenaPointer { ... };
4210+
4211+
ArenaPointer _Nonnull x = ...;
4212+
ArenaPointer _Nullable y = nullptr;
41884213
}];
41894214
}
41904215

clang/include/clang/Basic/Features.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ EXTENSION(define_target_os_macros,
9494
FEATURE(enumerator_attributes, true)
9595
FEATURE(nullability, true)
9696
FEATURE(nullability_on_arrays, true)
97+
FEATURE(nullability_on_classes, true)
9798
FEATURE(nullability_nullable_result, true)
9899
FEATURE(memory_sanitizer,
99100
LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |

clang/include/clang/Parse/Parser.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3014,6 +3014,7 @@ class Parser : public CodeCompletionHandler {
30143014
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
30153015
SourceLocation SkipExtendedMicrosoftTypeAttributes();
30163016
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3017+
void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
30173018
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
30183019
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
30193020
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);

clang/include/clang/Sema/Sema.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1655,6 +1655,9 @@ class Sema final {
16551655
/// Add [[gsl::Pointer]] attributes for std:: types.
16561656
void inferGslPointerAttribute(TypedefNameDecl *TD);
16571657

1658+
/// Add _Nullable attributes for std:: types.
1659+
void inferNullableClassAttribute(CXXRecordDecl *CRD);
1660+
16581661
enum PragmaOptionsAlignKind {
16591662
POAK_Native, // #pragma options align=native
16601663
POAK_Natural, // #pragma options align=natural

clang/lib/AST/Type.cpp

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4558,16 +4558,15 @@ bool Type::canHaveNullability(bool ResultIfUnknown) const {
45584558
case Type::Auto:
45594559
return ResultIfUnknown;
45604560

4561-
// Dependent template specializations can instantiate to pointer
4562-
// types unless they're known to be specializations of a class
4563-
// template.
4561+
// Dependent template specializations could instantiate to pointer types.
45644562
case Type::TemplateSpecialization:
4565-
if (TemplateDecl *templateDecl
4566-
= cast<TemplateSpecializationType>(type.getTypePtr())
4567-
->getTemplateName().getAsTemplateDecl()) {
4568-
if (isa<ClassTemplateDecl>(templateDecl))
4569-
return false;
4570-
}
4563+
// If it's a known class template, we can already check if it's nullable.
4564+
if (TemplateDecl *templateDecl =
4565+
cast<TemplateSpecializationType>(type.getTypePtr())
4566+
->getTemplateName()
4567+
.getAsTemplateDecl())
4568+
if (auto *CTD = dyn_cast<ClassTemplateDecl>(templateDecl))
4569+
return CTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
45714570
return ResultIfUnknown;
45724571

45734572
case Type::Builtin:
@@ -4624,6 +4623,17 @@ bool Type::canHaveNullability(bool ResultIfUnknown) const {
46244623
}
46254624
llvm_unreachable("unknown builtin type");
46264625

4626+
case Type::Record: {
4627+
const RecordDecl *RD = cast<RecordType>(type)->getDecl();
4628+
// For template specializations, look only at primary template attributes.
4629+
// This is a consistent regardless of whether the instantiation is known.
4630+
if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
4631+
return CTSD->getSpecializedTemplate()
4632+
->getTemplatedDecl()
4633+
->hasAttr<TypeNullableAttr>();
4634+
return RD->hasAttr<TypeNullableAttr>();
4635+
}
4636+
46274637
// Non-pointer types.
46284638
case Type::Complex:
46294639
case Type::LValueReference:
@@ -4641,7 +4651,6 @@ bool Type::canHaveNullability(bool ResultIfUnknown) const {
46414651
case Type::DependentAddressSpace:
46424652
case Type::FunctionProto:
46434653
case Type::FunctionNoProto:
4644-
case Type::Record:
46454654
case Type::DeducedTemplateSpecialization:
46464655
case Type::Enum:
46474656
case Type::InjectedClassName:

clang/lib/CodeGen/CGCall.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4372,7 +4372,8 @@ void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
43724372
NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
43734373

43744374
bool CanCheckNullability = false;
4375-
if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
4375+
if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4376+
!PVD->getType()->isRecordType()) {
43764377
auto Nullability = PVD->getType()->getNullability();
43774378
CanCheckNullability = Nullability &&
43784379
*Nullability == NullabilityKind::NonNull &&

clang/lib/CodeGen/CodeGenFunction.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -979,7 +979,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
979979
// return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
980980
if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
981981
auto Nullability = FnRetTy->getNullability();
982-
if (Nullability && *Nullability == NullabilityKind::NonNull) {
982+
if (Nullability && *Nullability == NullabilityKind::NonNull &&
983+
!FnRetTy->isRecordType()) {
983984
if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
984985
CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
985986
RetValNullabilityPrecondition =

clang/lib/Parse/ParseDeclCXX.cpp

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1494,6 +1494,15 @@ void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
14941494
}
14951495
}
14961496

1497+
void Parser::ParseNullabilityClassAttributes(ParsedAttributes &attrs) {
1498+
while (Tok.is(tok::kw__Nullable)) {
1499+
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1500+
auto Kind = Tok.getKind();
1501+
SourceLocation AttrNameLoc = ConsumeToken();
1502+
attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
1503+
}
1504+
}
1505+
14971506
/// Determine whether the following tokens are valid after a type-specifier
14981507
/// which could be a standalone declaration. This will conservatively return
14991508
/// true if there's any doubt, and is appropriate for insert-';' fixits.
@@ -1675,15 +1684,21 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
16751684

16761685
ParsedAttributes attrs(AttrFactory);
16771686
// If attributes exist after tag, parse them.
1678-
MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1679-
1680-
// Parse inheritance specifiers.
1681-
if (Tok.isOneOf(tok::kw___single_inheritance, tok::kw___multiple_inheritance,
1682-
tok::kw___virtual_inheritance))
1683-
ParseMicrosoftInheritanceClassAttributes(attrs);
1684-
1685-
// Allow attributes to precede or succeed the inheritance specifiers.
1686-
MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1687+
for (;;) {
1688+
MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1689+
// Parse inheritance specifiers.
1690+
if (Tok.isOneOf(tok::kw___single_inheritance,
1691+
tok::kw___multiple_inheritance,
1692+
tok::kw___virtual_inheritance)) {
1693+
ParseMicrosoftInheritanceClassAttributes(attrs);
1694+
continue;
1695+
}
1696+
if (Tok.is(tok::kw__Nullable)) {
1697+
ParseNullabilityClassAttributes(attrs);
1698+
continue;
1699+
}
1700+
break;
1701+
}
16871702

16881703
// Source location used by FIXIT to insert misplaced
16891704
// C++11 attributes

0 commit comments

Comments
 (0)