Skip to content

Commit c39871e

Browse files
committed
[BoundsSafety] Introduce CountAttributedType
CountAttributedType is a sugar type to represent a type with a 'counted_by' attribute and the likes, which provides bounds information to the underlying type. The type contains an the argument of attribute as an expression. Additionally, the type holds metadata about declarations referenced by the expression in order to make it easier for Sema to access declarations on which the type depends. This also adjusts the CountedBy attribute definition and implements parsing CountAttributedType. __bdos and array-checks sanitizer use CountAttributedType instead of hasAttr<CountedByAttr>. Implements special lookup for counted_by argument in structs. Adjust test/Sema/attr-counted-by.c to match the default diags generated by the expression parser.
1 parent 20a9fa3 commit c39871e

35 files changed

+692
-163
lines changed

clang/include/clang/AST/ASTContext.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
250250
DependentBitIntTypes;
251251
llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes;
252252

253+
mutable llvm::FoldingSet<CountAttributedType> CountAttributedTypes;
254+
253255
mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
254256
mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
255257
mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
@@ -1341,6 +1343,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
13411343
return CanQualType::CreateUnsafe(getPointerType((QualType) T));
13421344
}
13431345

1346+
QualType
1347+
getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes,
1348+
bool OrNull,
1349+
ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const;
1350+
13441351
/// Return the uniqued reference to a type adjusted from the original
13451352
/// type to a new type.
13461353
QualType getAdjustedType(QualType Orig, QualType New) const;

clang/include/clang/AST/PropertiesBase.td

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ def UInt32 : CountPropertyType<"uint32_t">;
143143
def UInt64 : CountPropertyType<"uint64_t">;
144144
def UnaryTypeTransformKind : EnumPropertyType<"UnaryTransformType::UTTKind">;
145145
def VectorKind : EnumPropertyType<"VectorKind">;
146+
def TypeCoupledDeclRefInfo : PropertyType;
146147

147148
def ExceptionSpecInfo : PropertyType<"FunctionProtoType::ExceptionSpecInfo"> {
148149
let BufferElementTypes = [ QualType ];

clang/include/clang/AST/RecursiveASTVisitor.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,12 @@ DEF_TRAVERSE_TYPE(InjectedClassNameType, {})
11061106
DEF_TRAVERSE_TYPE(AttributedType,
11071107
{ TRY_TO(TraverseType(T->getModifiedType())); })
11081108

1109+
DEF_TRAVERSE_TYPE(CountAttributedType, {
1110+
if (T->getCountExpr())
1111+
TRY_TO(TraverseStmt(T->getCountExpr()));
1112+
TRY_TO(TraverseType(T->desugar()));
1113+
})
1114+
11091115
DEF_TRAVERSE_TYPE(BTFTagAttributedType,
11101116
{ TRY_TO(TraverseType(T->getWrappedType())); })
11111117

@@ -1397,6 +1403,9 @@ DEF_TRAVERSE_TYPELOC(MacroQualifiedType,
13971403
DEF_TRAVERSE_TYPELOC(AttributedType,
13981404
{ TRY_TO(TraverseTypeLoc(TL.getModifiedLoc())); })
13991405

1406+
DEF_TRAVERSE_TYPELOC(CountAttributedType,
1407+
{ TRY_TO(TraverseTypeLoc(TL.getInnerLoc())); })
1408+
14001409
DEF_TRAVERSE_TYPELOC(BTFTagAttributedType,
14011410
{ TRY_TO(TraverseTypeLoc(TL.getWrappedLoc())); })
14021411

clang/include/clang/AST/Type.h

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ class BTFTypeTagAttr;
6161
class ExtQuals;
6262
class QualType;
6363
class ConceptDecl;
64+
class ValueDecl;
6465
class TagDecl;
6566
class TemplateParameterList;
6667
class Type;
@@ -2000,6 +2001,21 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
20002001
unsigned NumExpansions;
20012002
};
20022003

2004+
class CountAttributedTypeBitfields {
2005+
friend class CountAttributedType;
2006+
2007+
LLVM_PREFERRED_TYPE(TypeBitfields)
2008+
unsigned : NumTypeBits;
2009+
2010+
/// The limit is 15.
2011+
static constexpr unsigned NumCoupledDeclsBits = 4;
2012+
unsigned NumCoupledDecls : NumCoupledDeclsBits;
2013+
LLVM_PREFERRED_TYPE(bool)
2014+
unsigned CountInBytes : 1;
2015+
LLVM_PREFERRED_TYPE(bool)
2016+
unsigned OrNull : 1;
2017+
};
2018+
20032019
union {
20042020
TypeBitfields TypeBits;
20052021
ArrayTypeBitfields ArrayTypeBits;
@@ -2022,6 +2038,7 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
20222038
DependentTemplateSpecializationTypeBitfields
20232039
DependentTemplateSpecializationTypeBits;
20242040
PackExpansionTypeBitfields PackExpansionTypeBits;
2041+
CountAttributedTypeBitfields CountAttributedTypeBits;
20252042
};
20262043

20272044
private:
@@ -2719,6 +2736,14 @@ template <> const TemplateSpecializationType *Type::getAs() const;
27192736
/// until it reaches an AttributedType or a non-sugared type.
27202737
template <> const AttributedType *Type::getAs() const;
27212738

2739+
/// This will check for a BoundsAttributedType by removing any existing
2740+
/// sugar until it reaches an BoundsAttributedType or a non-sugared type.
2741+
template <> const BoundsAttributedType *Type::getAs() const;
2742+
2743+
/// This will check for a CountAttributedType by removing any existing
2744+
/// sugar until it reaches an CountAttributedType or a non-sugared type.
2745+
template <> const CountAttributedType *Type::getAs() const;
2746+
27222747
// We can do canonical leaf types faster, because we don't have to
27232748
// worry about preserving child type decoration.
27242749
#define TYPE(Class, Base)
@@ -2917,6 +2942,133 @@ class PointerType : public Type, public llvm::FoldingSetNode {
29172942
static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
29182943
};
29192944

2945+
/// [BoundsSafety] Represents information of declarations referenced by the
2946+
/// arguments of the `counted_by` attribute and the likes.
2947+
class TypeCoupledDeclRefInfo {
2948+
public:
2949+
using BaseTy = llvm::PointerIntPair<ValueDecl *, 1, unsigned>;
2950+
2951+
private:
2952+
enum {
2953+
DerefShift = 0,
2954+
DerefMask = 1,
2955+
};
2956+
BaseTy Data;
2957+
2958+
public:
2959+
/// \p D is to a declaration referenced by the argument of attribute. \p Deref
2960+
/// indicates whether \p D is referenced as a dereferenced form, e.g., \p
2961+
/// Deref is true for `*n` in `int *__counted_by(*n)`.
2962+
TypeCoupledDeclRefInfo(ValueDecl *D = nullptr, bool Deref = false);
2963+
2964+
bool isDeref() const;
2965+
ValueDecl *getDecl() const;
2966+
unsigned getInt() const;
2967+
void *getOpaqueValue() const;
2968+
bool operator==(const TypeCoupledDeclRefInfo &Other) const;
2969+
void setFromOpaqueValue(void *V);
2970+
};
2971+
2972+
/// [BoundsSafety] Represents a parent type class for CountAttributedType and
2973+
/// similar sugar types that will be introduced to represent a type with a
2974+
/// bounds attribute.
2975+
///
2976+
/// Provides a common interface to navigate declarations referred to by the
2977+
/// bounds expression.
2978+
2979+
class BoundsAttributedType : public Type, public llvm::FoldingSetNode {
2980+
QualType WrappedTy;
2981+
2982+
protected:
2983+
ArrayRef<TypeCoupledDeclRefInfo> Decls; // stored in trailing objects
2984+
2985+
BoundsAttributedType(TypeClass TC, QualType Wrapped, QualType Canon);
2986+
2987+
public:
2988+
bool isSugared() const { return true; }
2989+
QualType desugar() const { return WrappedTy; }
2990+
2991+
using decl_iterator = const TypeCoupledDeclRefInfo *;
2992+
using decl_range = llvm::iterator_range<decl_iterator>;
2993+
2994+
decl_iterator dependent_decl_begin() const { return Decls.begin(); }
2995+
decl_iterator dependent_decl_end() const { return Decls.end(); }
2996+
2997+
unsigned getNumCoupledDecls() const { return Decls.size(); }
2998+
2999+
decl_range dependent_decls() const {
3000+
return decl_range(dependent_decl_begin(), dependent_decl_end());
3001+
}
3002+
3003+
ArrayRef<TypeCoupledDeclRefInfo> getCoupledDecls() const {
3004+
return {dependent_decl_begin(), dependent_decl_end()};
3005+
}
3006+
3007+
bool referencesFieldDecls() const;
3008+
3009+
static bool classof(const Type *T) {
3010+
switch (T->getTypeClass()) {
3011+
case CountAttributed:
3012+
return true;
3013+
default:
3014+
return false;
3015+
}
3016+
}
3017+
};
3018+
3019+
/// Represents a sugar type with `__counted_by` or `__sized_by` annotations,
3020+
/// including their `_or_null` variants.
3021+
class CountAttributedType final
3022+
: public BoundsAttributedType,
3023+
public llvm::TrailingObjects<CountAttributedType,
3024+
TypeCoupledDeclRefInfo> {
3025+
friend class ASTContext;
3026+
3027+
Expr *CountExpr;
3028+
/// \p CountExpr represents the argument of __counted_by or the likes. \p
3029+
/// CountInBytes indicates that \p CountExpr is a byte count (i.e.,
3030+
/// __sized_by(_or_null)) \p OrNull means it's an or_null variant (i.e.,
3031+
/// __counted_by_or_null or __sized_by_or_null) \p CoupledDecls contains the
3032+
/// list of declarations referenced by \p CountExpr, which the type depends on
3033+
/// for the bounds information.
3034+
CountAttributedType(QualType Wrapped, QualType Canon, Expr *CountExpr,
3035+
bool CountInBytes, bool OrNull,
3036+
ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls);
3037+
3038+
unsigned numTrailingObjects(OverloadToken<TypeCoupledDeclRefInfo>) const {
3039+
return CountAttributedTypeBits.NumCoupledDecls;
3040+
}
3041+
3042+
public:
3043+
enum DynamicCountPointerKind {
3044+
CountedBy = 0,
3045+
SizedBy,
3046+
CountedByOrNull,
3047+
SizedByOrNull,
3048+
};
3049+
3050+
Expr *getCountExpr() const { return CountExpr; }
3051+
bool isCountInBytes() const { return CountAttributedTypeBits.CountInBytes; }
3052+
bool isOrNull() const { return CountAttributedTypeBits.OrNull; }
3053+
3054+
DynamicCountPointerKind getKind() const {
3055+
if (isOrNull())
3056+
return isCountInBytes() ? SizedByOrNull : CountedByOrNull;
3057+
return isCountInBytes() ? SizedBy : CountedBy;
3058+
}
3059+
3060+
void Profile(llvm::FoldingSetNodeID &ID) {
3061+
Profile(ID, desugar(), CountExpr, isCountInBytes(), isOrNull());
3062+
}
3063+
3064+
static void Profile(llvm::FoldingSetNodeID &ID, QualType WrappedTy,
3065+
Expr *CountExpr, bool CountInBytes, bool Nullable);
3066+
3067+
static bool classof(const Type *T) {
3068+
return T->getTypeClass() == CountAttributed;
3069+
}
3070+
};
3071+
29203072
/// Represents a type which was implicitly adjusted by the semantic
29213073
/// engine for arbitrary reasons. For example, array and function types can
29223074
/// decay, and function types can have their calling conventions adjusted.

clang/include/clang/AST/TypeLoc.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,6 +1117,32 @@ class ObjCInterfaceTypeLoc : public ConcreteTypeLoc<ObjCObjectTypeLoc,
11171117
}
11181118
};
11191119

1120+
struct BoundsAttributedLocInfo {};
1121+
class BoundsAttributedTypeLoc
1122+
: public ConcreteTypeLoc<UnqualTypeLoc, BoundsAttributedTypeLoc,
1123+
BoundsAttributedType, BoundsAttributedLocInfo> {
1124+
public:
1125+
TypeLoc getInnerLoc() const { return this->getInnerTypeLoc(); }
1126+
QualType getInnerType() const { return this->getTypePtr()->desugar(); }
1127+
void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1128+
// nothing to do
1129+
}
1130+
unsigned getLocalDataAlignment() const { return 1; }
1131+
unsigned getLocalDataSize() const { return 0; }
1132+
};
1133+
1134+
class CountAttributedTypeLoc final
1135+
: public InheritingConcreteTypeLoc<BoundsAttributedTypeLoc,
1136+
CountAttributedTypeLoc,
1137+
CountAttributedType> {
1138+
public:
1139+
Expr *getCountExpr() const { return getTypePtr()->getCountExpr(); }
1140+
bool isCountInBytes() const { return getTypePtr()->isCountInBytes(); }
1141+
bool isOrNull() const { return getTypePtr()->isOrNull(); }
1142+
1143+
SourceRange getLocalSourceRange() const;
1144+
};
1145+
11201146
struct MacroQualifiedLocInfo {
11211147
SourceLocation ExpansionLoc;
11221148
};

clang/include/clang/AST/TypeProperties.td

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,25 @@ let Class = PointerType in {
2525
def : Creator<[{ return ctx.getPointerType(pointeeType); }]>;
2626
}
2727

28+
let Class = CountAttributedType in {
29+
def : Property<"WrappedTy", QualType> {
30+
let Read = [{ node->desugar() }];
31+
}
32+
def : Property<"CountExpr", ExprRef> {
33+
let Read = [{ node->getCountExpr() }];
34+
}
35+
def : Property<"CountInBytes", Bool> {
36+
let Read = [{ node->isCountInBytes() }];
37+
}
38+
def : Property<"OrNull", Bool> {
39+
let Read = [{ node->isOrNull() }];
40+
}
41+
def : Property<"CoupledDecls", Array<TypeCoupledDeclRefInfo>> {
42+
let Read = [{ node->getCoupledDecls() }];
43+
}
44+
def : Creator<[{ return ctx.getCountAttributedType(WrappedTy, CountExpr, CountInBytes, OrNull, CoupledDecls); }]>;
45+
}
46+
2847
let Class = AdjustedType in {
2948
def : Property<"originalType", QualType> {
3049
let Read = [{ node->getOriginalType() }];

clang/include/clang/Basic/Attr.td

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4441,10 +4441,11 @@ def CodeAlign: StmtAttr {
44414441
}];
44424442
}
44434443

4444-
def CountedBy : InheritableAttr {
4444+
def CountedBy : DeclOrTypeAttr {
44454445
let Spellings = [Clang<"counted_by">];
4446-
let Subjects = SubjectList<[Field]>;
4447-
let Args = [IdentifierArgument<"CountedByField">];
4446+
let Subjects = SubjectList<[Field], ErrorDiag>;
4447+
let Args = [ExprArgument<"Count">, IntArgument<"NestedLevel">];
4448+
let ParseArgumentsAsUnevaluated = 1;
44484449
let Documentation = [CountedByDocs];
44494450
let LangOpts = [COnly];
44504451
// FIXME: This is ugly. Let using a DeclArgument would be nice, but a Decl

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6472,12 +6472,18 @@ def err_flexible_array_count_not_in_same_struct : Error<
64726472
"'counted_by' field %0 isn't within the same struct as the flexible array">;
64736473
def err_counted_by_attr_not_on_flexible_array_member : Error<
64746474
"'counted_by' only applies to C99 flexible array members">;
6475-
def err_counted_by_attr_refers_to_flexible_array : Error<
6476-
"'counted_by' cannot refer to the flexible array %0">;
6475+
def err_counted_by_attr_refer_to_itself : Error<
6476+
"'counted_by' cannot refer to the flexible array member %0">;
64776477
def err_counted_by_must_be_in_structure : Error<
64786478
"field %0 in 'counted_by' not inside structure">;
6479-
def err_flexible_array_counted_by_attr_field_not_integer : Error<
6480-
"field %0 in 'counted_by' must be a non-boolean integer type">;
6479+
def err_counted_by_attr_argument_not_integer : Error<
6480+
"'counted_by' requires a non-boolean integer type argument">;
6481+
def err_counted_by_attr_only_support_simple_decl_reference : Error<
6482+
"'counted_by' argument must be a simple declaration reference">;
6483+
def err_counted_by_attr_in_union : Error<
6484+
"'counted_by' cannot be applied to a union member">;
6485+
def err_counted_by_attr_refer_to_union : Error<
6486+
"'counted_by' argument cannot refer to a union member">;
64816487
def note_flexible_array_counted_by_attr_field : Note<
64826488
"field %0 declared here">;
64836489

clang/include/clang/Basic/TypeNodes.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,8 @@ def ObjCTypeParamType : TypeNode<Type>, NeverCanonical;
108108
def ObjCObjectType : TypeNode<Type>;
109109
def ObjCInterfaceType : TypeNode<ObjCObjectType>, LeafType;
110110
def ObjCObjectPointerType : TypeNode<Type>;
111+
def BoundsAttributedType : TypeNode<Type, 1>;
112+
def CountAttributedType : TypeNode<BoundsAttributedType>, NeverCanonical;
111113
def PipeType : TypeNode<Type>;
112114
def AtomicType : TypeNode<Type>;
113115
def BitIntType : TypeNode<Type>;

clang/include/clang/Parse/Parser.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3064,6 +3064,11 @@ class Parser : public CodeCompletionHandler {
30643064
SourceLocation ScopeLoc,
30653065
ParsedAttr::Form Form);
30663066

3067+
void ParseBoundsAttribute(IdentifierInfo &AttrName,
3068+
SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
3069+
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3070+
ParsedAttr::Form Form);
3071+
30673072
void ParseTypeofSpecifier(DeclSpec &DS);
30683073
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
30693074
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,

0 commit comments

Comments
 (0)