Skip to content

Commit ebf3703

Browse files
committed
[clang][nullability] allow _Nonnull etc on nullable class types
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.
1 parent 360da83 commit ebf3703

File tree

18 files changed

+196
-43
lines changed

18 files changed

+196
-43
lines changed

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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4151,6 +4151,11 @@ 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, ithe nullability attributes can be attached
4156+
to nullable types from the C++ standard library such as ``std::unique_ptr`` and
4157+
``std::function``, as well as C++ classes marked with the ``_Nullable``
4158+
attribute.
41544159
}];
41554160
}
41564161

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

41874192
a caller of ``fetch_or_zero`` can provide null.
4193+
4194+
The ``_Nullable`` attribute on classes indicates that the given class can
4195+
represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
4196+
make sense for this type. For example:
4197+
4198+
.. code-block:: c
4199+
4200+
class _Nullable ArenaPointer { ... };
4201+
4202+
ArenaPointer _Nonnull x = ...;
4203+
ArenaPointer _Nullable y = nullptr;
41884204
}];
41894205
}
41904206

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: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13261,19 +13261,6 @@ class Sema final {
1326113261
/// from \p Caller context and erases all functions with lower
1326213262
/// calling priority.
1326313263
void EraseUnwantedCUDAMatches(
13264-
const FunctionDecl *Caller,
13265-
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
13266-
13267-
/// Given a implicit special member, infer its CUDA target from the
13268-
/// calls it needs to make to underlying base/field special members.
13269-
/// \param ClassDecl the class for which the member is being created.
13270-
/// \param CSM the kind of special member.
13271-
/// \param MemberDecl the special member itself.
13272-
/// \param ConstRHS true if this is a copy operation with a const object on
13273-
/// its RHS.
13274-
/// \param Diagnose true if this call should emit diagnostics.
13275-
/// \return true if there was an error inferring.
13276-
/// The result of this call is implicit CUDA target attribute(s) attached to
1327713264
/// the member declaration.
1327813265
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
1327913266
CXXSpecialMember CSM,
@@ -13300,7 +13287,6 @@ class Sema final {
1330013287
void checkCUDATargetOverload(FunctionDecl *NewFD,
1330113288
const LookupResult &Previous);
1330213289
/// Copies target attributes from the template TD to the function FD.
13303-
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
1330413290

1330513291
/// Returns the name of the launch configuration function. This is the name
1330613292
/// of the function that will be called to configure kernel call, with the

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

clang/lib/Sema/SemaAttr.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,18 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
215215
inferGslPointerAttribute(Record, Record);
216216
}
217217

218+
void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
219+
static llvm::StringSet<> Nullable{
220+
"auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
221+
"coroutine_handle", "function", "move_only_function",
222+
};
223+
224+
if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&
225+
!CRD->hasAttr<TypeNullableAttr>())
226+
for (Decl *Redecl : CRD->redecls())
227+
Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));
228+
}
229+
218230
void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
219231
SourceLocation PragmaLoc) {
220232
PragmaMsStackAction Action = Sema::PSK_Reset;

clang/lib/Sema/SemaChecking.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include "clang/AST/ExprObjC.h"
2828
#include "clang/AST/ExprOpenMP.h"
2929
#include "clang/AST/FormatString.h"
30+
#include "clang/AST/IgnoreExpr.h"
3031
#include "clang/AST/NSAPI.h"
3132
#include "clang/AST/NonTrivialTypeVisitor.h"
3233
#include "clang/AST/OperationKinds.h"
@@ -7316,6 +7317,14 @@ bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
73167317
///
73177318
/// Returns true if the value evaluates to null.
73187319
static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
7320+
// Treat (smart) pointers constructed from nullptr as null, whether we can
7321+
// const-evaluate them or not.
7322+
// This must happen first: the smart pointer expr might have _Nonnull type!
7323+
if (isa<CXXNullPtrLiteralExpr>(
7324+
IgnoreExprNodes(Expr, IgnoreImplicitAsWrittenSingleStep,
7325+
IgnoreElidableImplicitConstructorSingleStep)))
7326+
return true;
7327+
73197328
// If the expression has non-null type, it doesn't evaluate to null.
73207329
if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
73217330
if (*nullability == NullabilityKind::NonNull)

clang/lib/Sema/SemaDecl.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18250,8 +18250,10 @@ Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1825018250
if (PrevDecl)
1825118251
mergeDeclAttributes(New, PrevDecl);
1825218252

18253-
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
18253+
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
1825418254
inferGslOwnerPointerAttribute(CXXRD);
18255+
inferNullableClassAttribute(CXXRD);
18256+
}
1825518257

1825618258
// If there's a #pragma GCC visibility in scope, set the visibility of this
1825718259
// record.

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5976,6 +5976,20 @@ static void handleBuiltinAliasAttr(Sema &S, Decl *D,
59765976
D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
59775977
}
59785978

5979+
static void handleNullableTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5980+
if (AL.isUsedAsTypeAttr())
5981+
return;
5982+
5983+
if (auto *CRD = dyn_cast<CXXRecordDecl>(D);
5984+
!D || !(CRD->isClass() || CRD->isStruct())) {
5985+
S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type_str)
5986+
<< AL << AL.isRegularKeywordAttribute() << "classes";
5987+
return;
5988+
}
5989+
5990+
handleSimpleAttribute<TypeNullableAttr>(S, D, AL);
5991+
}
5992+
59795993
static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
59805994
if (!AL.hasParsedType()) {
59815995
S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
@@ -9945,6 +9959,10 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
99459959
case ParsedAttr::AT_UsingIfExists:
99469960
handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
99479961
break;
9962+
9963+
case ParsedAttr::AT_TypeNullable:
9964+
handleNullableTypeAttr(S, D, AL);
9965+
break;
99489966
}
99499967
}
99509968

clang/lib/Sema/SemaInit.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7075,6 +7075,11 @@ PerformConstructorInitialization(Sema &S,
70757075
hasCopyOrMoveCtorParam(S.Context,
70767076
getConstructorInfo(Step.Function.FoundDecl));
70777077

7078+
// A smart pointer constructed from a nullable pointer is nullable.
7079+
if (NumArgs == 1 && !Kind.isExplicitCast())
7080+
S.diagnoseNullableToNonnullConversion(
7081+
Entity.getType(), Args.front()->getType(), Kind.getLocation());
7082+
70787083
// Determine the arguments required to actually perform the constructor
70797084
// call.
70807085
if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,

clang/lib/Sema/SemaOverload.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14797,6 +14797,13 @@ ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
1479714797
}
1479814798
}
1479914799

14800+
// Check for nonnull = nullable.
14801+
// This won't be caught in the arg's initialization: the parameter to
14802+
// the assignment operator is not marked nonnull.
14803+
if (Op == OO_Equal)
14804+
diagnoseNullableToNonnullConversion(Args[0]->getType(),
14805+
Args[1]->getType(), OpLoc);
14806+
1480014807
// Convert the arguments.
1480114808
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1480214809
// Best->Access is only meaningful for class members.

clang/lib/Sema/SemaTemplate.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2168,6 +2168,7 @@ DeclResult Sema::CheckClassTemplate(
21682168

21692169
AddPushedVisibilityAttribute(NewClass);
21702170
inferGslOwnerPointerAttribute(NewClass);
2171+
inferNullableClassAttribute(NewClass);
21712172

21722173
if (TUK != TUK_Friend) {
21732174
// Per C++ [basic.scope.temp]p2, skip the template parameter scopes.

clang/lib/Sema/SemaType.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4705,6 +4705,18 @@ static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
47054705
return false;
47064706
}
47074707

4708+
// Whether this is a type broadly expected to have nullability attached.
4709+
// These types are affected by `#pragma assume_nonnull`, and missing nullability
4710+
// will be diagnosed with -Wnullability-completeness.
4711+
static bool shouldHaveNullability(QualType T) {
4712+
return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4713+
// For now, do not infer/require nullability on C++ smart pointers.
4714+
// It's unclear whether the pragma's behavior is useful for C++.
4715+
// e.g. treating type-aliases and template-type-parameters differently
4716+
// from types of declarations can be surprising.
4717+
!isa<RecordType>(T);
4718+
}
4719+
47084720
static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
47094721
QualType declSpecType,
47104722
TypeSourceInfo *TInfo) {
@@ -4823,8 +4835,7 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
48234835
// inner pointers.
48244836
complainAboutMissingNullability = CAMN_InnerPointers;
48254837

4826-
if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4827-
!T->getNullability()) {
4838+
if (shouldHaveNullability(T) && !T->getNullability()) {
48284839
// Note that we allow but don't require nullability on dependent types.
48294840
++NumPointersRemaining;
48304841
}
@@ -5047,8 +5058,7 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
50475058
// If the type itself could have nullability but does not, infer pointer
50485059
// nullability and perform consistency checking.
50495060
if (S.CodeSynthesisContexts.empty()) {
5050-
if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
5051-
!T->getNullability()) {
5061+
if (shouldHaveNullability(T) && !T->getNullability()) {
50525062
if (isVaList(T)) {
50535063
// Record that we've seen a pointer, but do nothing else.
50545064
if (NumPointersRemaining > 0)

0 commit comments

Comments
 (0)