1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements decl-related attribute processing.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/Cuda.h"
27 #include "clang/Basic/DarwinSDKInfo.h"
28 #include "clang/Basic/HLSLRuntime.h"
29 #include "clang/Basic/LangOptions.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetBuiltins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedAttr.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/IR/Assumptions.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/Error.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
52 using namespace clang
;
55 namespace AttributeLangSupport
{
61 } // end namespace AttributeLangSupport
63 //===----------------------------------------------------------------------===//
65 //===----------------------------------------------------------------------===//
67 /// isFunctionOrMethod - Return true if the given decl has function
68 /// type (function or function-typed variable) or an Objective-C
70 static bool isFunctionOrMethod(const Decl
*D
) {
71 return (D
->getFunctionType() != nullptr) || isa
<ObjCMethodDecl
>(D
);
74 /// Return true if the given decl has function type (function or
75 /// function-typed variable) or an Objective-C method or a block.
76 static bool isFunctionOrMethodOrBlock(const Decl
*D
) {
77 return isFunctionOrMethod(D
) || isa
<BlockDecl
>(D
);
80 /// Return true if the given decl has a declarator that should have
81 /// been processed by Sema::GetTypeForDeclarator.
82 static bool hasDeclarator(const Decl
*D
) {
83 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
84 return isa
<DeclaratorDecl
>(D
) || isa
<BlockDecl
>(D
) || isa
<TypedefNameDecl
>(D
) ||
85 isa
<ObjCPropertyDecl
>(D
);
88 /// hasFunctionProto - Return true if the given decl has a argument
89 /// information. This decl should have already passed
90 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
91 static bool hasFunctionProto(const Decl
*D
) {
92 if (const FunctionType
*FnTy
= D
->getFunctionType())
93 return isa
<FunctionProtoType
>(FnTy
);
94 return isa
<ObjCMethodDecl
>(D
) || isa
<BlockDecl
>(D
);
97 /// getFunctionOrMethodNumParams - Return number of function or method
98 /// parameters. It is an error to call this on a K&R function (use
99 /// hasFunctionProto first).
100 static unsigned getFunctionOrMethodNumParams(const Decl
*D
) {
101 if (const FunctionType
*FnTy
= D
->getFunctionType())
102 return cast
<FunctionProtoType
>(FnTy
)->getNumParams();
103 if (const auto *BD
= dyn_cast
<BlockDecl
>(D
))
104 return BD
->getNumParams();
105 return cast
<ObjCMethodDecl
>(D
)->param_size();
108 static const ParmVarDecl
*getFunctionOrMethodParam(const Decl
*D
,
110 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
111 return FD
->getParamDecl(Idx
);
112 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
113 return MD
->getParamDecl(Idx
);
114 if (const auto *BD
= dyn_cast
<BlockDecl
>(D
))
115 return BD
->getParamDecl(Idx
);
119 static QualType
getFunctionOrMethodParamType(const Decl
*D
, unsigned Idx
) {
120 if (const FunctionType
*FnTy
= D
->getFunctionType())
121 return cast
<FunctionProtoType
>(FnTy
)->getParamType(Idx
);
122 if (const auto *BD
= dyn_cast
<BlockDecl
>(D
))
123 return BD
->getParamDecl(Idx
)->getType();
125 return cast
<ObjCMethodDecl
>(D
)->parameters()[Idx
]->getType();
128 static SourceRange
getFunctionOrMethodParamRange(const Decl
*D
, unsigned Idx
) {
129 if (auto *PVD
= getFunctionOrMethodParam(D
, Idx
))
130 return PVD
->getSourceRange();
131 return SourceRange();
134 static QualType
getFunctionOrMethodResultType(const Decl
*D
) {
135 if (const FunctionType
*FnTy
= D
->getFunctionType())
136 return FnTy
->getReturnType();
137 return cast
<ObjCMethodDecl
>(D
)->getReturnType();
140 static SourceRange
getFunctionOrMethodResultSourceRange(const Decl
*D
) {
141 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
142 return FD
->getReturnTypeSourceRange();
143 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
144 return MD
->getReturnTypeSourceRange();
145 return SourceRange();
148 static bool isFunctionOrMethodVariadic(const Decl
*D
) {
149 if (const FunctionType
*FnTy
= D
->getFunctionType())
150 return cast
<FunctionProtoType
>(FnTy
)->isVariadic();
151 if (const auto *BD
= dyn_cast
<BlockDecl
>(D
))
152 return BD
->isVariadic();
153 return cast
<ObjCMethodDecl
>(D
)->isVariadic();
156 static bool isInstanceMethod(const Decl
*D
) {
157 if (const auto *MethodDecl
= dyn_cast
<CXXMethodDecl
>(D
))
158 return MethodDecl
->isInstance();
162 static inline bool isNSStringType(QualType T
, ASTContext
&Ctx
,
163 bool AllowNSAttributedString
= false) {
164 const auto *PT
= T
->getAs
<ObjCObjectPointerType
>();
168 ObjCInterfaceDecl
*Cls
= PT
->getObjectType()->getInterface();
172 IdentifierInfo
* ClsName
= Cls
->getIdentifier();
174 if (AllowNSAttributedString
&&
175 ClsName
== &Ctx
.Idents
.get("NSAttributedString"))
177 // FIXME: Should we walk the chain of classes?
178 return ClsName
== &Ctx
.Idents
.get("NSString") ||
179 ClsName
== &Ctx
.Idents
.get("NSMutableString");
182 static inline bool isCFStringType(QualType T
, ASTContext
&Ctx
) {
183 const auto *PT
= T
->getAs
<PointerType
>();
187 const auto *RT
= PT
->getPointeeType()->getAs
<RecordType
>();
191 const RecordDecl
*RD
= RT
->getDecl();
192 if (RD
->getTagKind() != TTK_Struct
)
195 return RD
->getIdentifier() == &Ctx
.Idents
.get("__CFString");
198 static unsigned getNumAttributeArgs(const ParsedAttr
&AL
) {
199 // FIXME: Include the type in the argument list.
200 return AL
.getNumArgs() + AL
.hasParsedType();
203 /// A helper function to provide Attribute Location for the Attr types
204 /// AND the ParsedAttr.
205 template <typename AttrInfo
>
206 static std::enable_if_t
<std::is_base_of_v
<Attr
, AttrInfo
>, SourceLocation
>
207 getAttrLoc(const AttrInfo
&AL
) {
208 return AL
.getLocation();
210 static SourceLocation
getAttrLoc(const ParsedAttr
&AL
) { return AL
.getLoc(); }
212 /// If Expr is a valid integer constant, get the value of the integer
213 /// expression and return success or failure. May output an error.
215 /// Negative argument is implicitly converted to unsigned, unless
216 /// \p StrictlyUnsigned is true.
217 template <typename AttrInfo
>
218 static bool checkUInt32Argument(Sema
&S
, const AttrInfo
&AI
, const Expr
*Expr
,
219 uint32_t &Val
, unsigned Idx
= UINT_MAX
,
220 bool StrictlyUnsigned
= false) {
221 std::optional
<llvm::APSInt
> I
= llvm::APSInt(32);
222 if (Expr
->isTypeDependent() ||
223 !(I
= Expr
->getIntegerConstantExpr(S
.Context
))) {
225 S
.Diag(getAttrLoc(AI
), diag::err_attribute_argument_n_type
)
226 << &AI
<< Idx
<< AANT_ArgumentIntegerConstant
227 << Expr
->getSourceRange();
229 S
.Diag(getAttrLoc(AI
), diag::err_attribute_argument_type
)
230 << &AI
<< AANT_ArgumentIntegerConstant
<< Expr
->getSourceRange();
234 if (!I
->isIntN(32)) {
235 S
.Diag(Expr
->getExprLoc(), diag::err_ice_too_large
)
236 << toString(*I
, 10, false) << 32 << /* Unsigned */ 1;
240 if (StrictlyUnsigned
&& I
->isSigned() && I
->isNegative()) {
241 S
.Diag(getAttrLoc(AI
), diag::err_attribute_requires_positive_integer
)
242 << &AI
<< /*non-negative*/ 1;
246 Val
= (uint32_t)I
->getZExtValue();
250 /// Wrapper around checkUInt32Argument, with an extra check to be sure
251 /// that the result will fit into a regular (signed) int. All args have the same
252 /// purpose as they do in checkUInt32Argument.
253 template <typename AttrInfo
>
254 static bool checkPositiveIntArgument(Sema
&S
, const AttrInfo
&AI
, const Expr
*Expr
,
255 int &Val
, unsigned Idx
= UINT_MAX
) {
257 if (!checkUInt32Argument(S
, AI
, Expr
, UVal
, Idx
))
260 if (UVal
> (uint32_t)std::numeric_limits
<int>::max()) {
261 llvm::APSInt
I(32); // for toString
263 S
.Diag(Expr
->getExprLoc(), diag::err_ice_too_large
)
264 << toString(I
, 10, false) << 32 << /* Unsigned */ 0;
272 /// Diagnose mutually exclusive attributes when present on a given
273 /// declaration. Returns true if diagnosed.
274 template <typename AttrTy
>
275 static bool checkAttrMutualExclusion(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
276 if (const auto *A
= D
->getAttr
<AttrTy
>()) {
277 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
279 << (AL
.isRegularKeywordAttribute() || A
->isRegularKeywordAttribute());
280 S
.Diag(A
->getLocation(), diag::note_conflicting_attribute
);
286 template <typename AttrTy
>
287 static bool checkAttrMutualExclusion(Sema
&S
, Decl
*D
, const Attr
&AL
) {
288 if (const auto *A
= D
->getAttr
<AttrTy
>()) {
289 S
.Diag(AL
.getLocation(), diag::err_attributes_are_not_compatible
)
291 << (AL
.isRegularKeywordAttribute() || A
->isRegularKeywordAttribute());
292 S
.Diag(A
->getLocation(), diag::note_conflicting_attribute
);
298 /// Check if IdxExpr is a valid parameter index for a function or
299 /// instance method D. May output an error.
301 /// \returns true if IdxExpr is a valid index.
302 template <typename AttrInfo
>
303 static bool checkFunctionOrMethodParameterIndex(
304 Sema
&S
, const Decl
*D
, const AttrInfo
&AI
, unsigned AttrArgNum
,
305 const Expr
*IdxExpr
, ParamIdx
&Idx
, bool CanIndexImplicitThis
= false) {
306 assert(isFunctionOrMethodOrBlock(D
));
308 // In C++ the implicit 'this' function parameter also counts.
309 // Parameters are counted from one.
310 bool HP
= hasFunctionProto(D
);
311 bool HasImplicitThisParam
= isInstanceMethod(D
);
312 bool IV
= HP
&& isFunctionOrMethodVariadic(D
);
314 (HP
? getFunctionOrMethodNumParams(D
) : 0) + HasImplicitThisParam
;
316 std::optional
<llvm::APSInt
> IdxInt
;
317 if (IdxExpr
->isTypeDependent() ||
318 !(IdxInt
= IdxExpr
->getIntegerConstantExpr(S
.Context
))) {
319 S
.Diag(getAttrLoc(AI
), diag::err_attribute_argument_n_type
)
320 << &AI
<< AttrArgNum
<< AANT_ArgumentIntegerConstant
321 << IdxExpr
->getSourceRange();
325 unsigned IdxSource
= IdxInt
->getLimitedValue(UINT_MAX
);
326 if (IdxSource
< 1 || (!IV
&& IdxSource
> NumParams
)) {
327 S
.Diag(getAttrLoc(AI
), diag::err_attribute_argument_out_of_bounds
)
328 << &AI
<< AttrArgNum
<< IdxExpr
->getSourceRange();
331 if (HasImplicitThisParam
&& !CanIndexImplicitThis
) {
332 if (IdxSource
== 1) {
333 S
.Diag(getAttrLoc(AI
), diag::err_attribute_invalid_implicit_this_argument
)
334 << &AI
<< IdxExpr
->getSourceRange();
339 Idx
= ParamIdx(IdxSource
, D
);
343 /// Check if the argument \p E is a ASCII string literal. If not emit an error
344 /// and return false, otherwise set \p Str to the value of the string literal
346 bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo
&CI
,
347 const Expr
*E
, StringRef
&Str
,
348 SourceLocation
*ArgLocation
) {
349 const auto *Literal
= dyn_cast
<StringLiteral
>(E
->IgnoreParenCasts());
351 *ArgLocation
= E
->getBeginLoc();
353 if (!Literal
|| (!Literal
->isUnevaluated() && !Literal
->isOrdinary())) {
354 Diag(E
->getBeginLoc(), diag::err_attribute_argument_type
)
355 << CI
<< AANT_ArgumentString
;
359 Str
= Literal
->getString();
363 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364 /// If not emit an error and return false. If the argument is an identifier it
365 /// will emit an error with a fixit hint and treat it as if it was a string
367 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr
&AL
, unsigned ArgNum
,
369 SourceLocation
*ArgLocation
) {
370 // Look for identifiers. If we have one emit a hint to fix it to a literal.
371 if (AL
.isArgIdent(ArgNum
)) {
372 IdentifierLoc
*Loc
= AL
.getArgAsIdent(ArgNum
);
373 Diag(Loc
->Loc
, diag::err_attribute_argument_type
)
374 << AL
<< AANT_ArgumentString
375 << FixItHint::CreateInsertion(Loc
->Loc
, "\"")
376 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc
->Loc
), "\"");
377 Str
= Loc
->Ident
->getName();
379 *ArgLocation
= Loc
->Loc
;
383 // Now check for an actual string literal.
384 Expr
*ArgExpr
= AL
.getArgAsExpr(ArgNum
);
385 const auto *Literal
= dyn_cast
<StringLiteral
>(ArgExpr
->IgnoreParenCasts());
387 *ArgLocation
= ArgExpr
->getBeginLoc();
389 if (!Literal
|| (!Literal
->isUnevaluated() && !Literal
->isOrdinary())) {
390 Diag(ArgExpr
->getBeginLoc(), diag::err_attribute_argument_type
)
391 << AL
<< AANT_ArgumentString
;
394 Str
= Literal
->getString();
395 return checkStringLiteralArgumentAttr(AL
, ArgExpr
, Str
, ArgLocation
);
398 /// Applies the given attribute to the Decl without performing any
399 /// additional semantic checking.
400 template <typename AttrType
>
401 static void handleSimpleAttribute(Sema
&S
, Decl
*D
,
402 const AttributeCommonInfo
&CI
) {
403 D
->addAttr(::new (S
.Context
) AttrType(S
.Context
, CI
));
406 template <typename
... DiagnosticArgs
>
407 static const Sema::SemaDiagnosticBuilder
&
408 appendDiagnostics(const Sema::SemaDiagnosticBuilder
&Bldr
) {
412 template <typename T
, typename
... DiagnosticArgs
>
413 static const Sema::SemaDiagnosticBuilder
&
414 appendDiagnostics(const Sema::SemaDiagnosticBuilder
&Bldr
, T
&&ExtraArg
,
415 DiagnosticArgs
&&... ExtraArgs
) {
416 return appendDiagnostics(Bldr
<< std::forward
<T
>(ExtraArg
),
417 std::forward
<DiagnosticArgs
>(ExtraArgs
)...);
420 /// Add an attribute @c AttrType to declaration @c D, provided that
421 /// @c PassesCheck is true.
422 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
423 /// specified in @c ExtraArgs.
424 template <typename AttrType
, typename
... DiagnosticArgs
>
425 static void handleSimpleAttributeOrDiagnose(Sema
&S
, Decl
*D
,
426 const AttributeCommonInfo
&CI
,
427 bool PassesCheck
, unsigned DiagID
,
428 DiagnosticArgs
&&... ExtraArgs
) {
430 Sema::SemaDiagnosticBuilder DB
= S
.Diag(D
->getBeginLoc(), DiagID
);
431 appendDiagnostics(DB
, std::forward
<DiagnosticArgs
>(ExtraArgs
)...);
434 handleSimpleAttribute
<AttrType
>(S
, D
, CI
);
437 /// Check if the passed-in expression is of type int or bool.
438 static bool isIntOrBool(Expr
*Exp
) {
439 QualType QT
= Exp
->getType();
440 return QT
->isBooleanType() || QT
->isIntegerType();
444 // Check to see if the type is a smart pointer of some kind. We assume
445 // it's a smart pointer if it defines both operator-> and operator*.
446 static bool threadSafetyCheckIsSmartPointer(Sema
&S
, const RecordType
* RT
) {
447 auto IsOverloadedOperatorPresent
= [&S
](const RecordDecl
*Record
,
448 OverloadedOperatorKind Op
) {
449 DeclContextLookupResult Result
=
450 Record
->lookup(S
.Context
.DeclarationNames
.getCXXOperatorName(Op
));
451 return !Result
.empty();
454 const RecordDecl
*Record
= RT
->getDecl();
455 bool foundStarOperator
= IsOverloadedOperatorPresent(Record
, OO_Star
);
456 bool foundArrowOperator
= IsOverloadedOperatorPresent(Record
, OO_Arrow
);
457 if (foundStarOperator
&& foundArrowOperator
)
460 const CXXRecordDecl
*CXXRecord
= dyn_cast
<CXXRecordDecl
>(Record
);
464 for (const auto &BaseSpecifier
: CXXRecord
->bases()) {
465 if (!foundStarOperator
)
466 foundStarOperator
= IsOverloadedOperatorPresent(
467 BaseSpecifier
.getType()->getAsRecordDecl(), OO_Star
);
468 if (!foundArrowOperator
)
469 foundArrowOperator
= IsOverloadedOperatorPresent(
470 BaseSpecifier
.getType()->getAsRecordDecl(), OO_Arrow
);
473 if (foundStarOperator
&& foundArrowOperator
)
479 /// Check if passed in Decl is a pointer type.
480 /// Note that this function may produce an error message.
481 /// \return true if the Decl is a pointer type; false otherwise
482 static bool threadSafetyCheckIsPointer(Sema
&S
, const Decl
*D
,
483 const ParsedAttr
&AL
) {
484 const auto *VD
= cast
<ValueDecl
>(D
);
485 QualType QT
= VD
->getType();
486 if (QT
->isAnyPointerType())
489 if (const auto *RT
= QT
->getAs
<RecordType
>()) {
490 // If it's an incomplete type, it could be a smart pointer; skip it.
491 // (We don't want to force template instantiation if we can avoid it,
492 // since that would alter the order in which templates are instantiated.)
493 if (RT
->isIncompleteType())
496 if (threadSafetyCheckIsSmartPointer(S
, RT
))
500 S
.Diag(AL
.getLoc(), diag::warn_thread_attribute_decl_not_pointer
) << AL
<< QT
;
504 /// Checks that the passed in QualType either is of RecordType or points
505 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
506 static const RecordType
*getRecordType(QualType QT
) {
507 if (const auto *RT
= QT
->getAs
<RecordType
>())
510 // Now check if we point to record type.
511 if (const auto *PT
= QT
->getAs
<PointerType
>())
512 return PT
->getPointeeType()->getAs
<RecordType
>();
517 template <typename AttrType
>
518 static bool checkRecordDeclForAttr(const RecordDecl
*RD
) {
519 // Check if the record itself has the attribute.
520 if (RD
->hasAttr
<AttrType
>())
523 // Else check if any base classes have the attribute.
524 if (const auto *CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
525 if (!CRD
->forallBases([](const CXXRecordDecl
*Base
) {
526 return !Base
->hasAttr
<AttrType
>();
533 static bool checkRecordTypeForCapability(Sema
&S
, QualType Ty
) {
534 const RecordType
*RT
= getRecordType(Ty
);
539 // Don't check for the capability if the class hasn't been defined yet.
540 if (RT
->isIncompleteType())
543 // Allow smart pointers to be used as capability objects.
544 // FIXME -- Check the type that the smart pointer points to.
545 if (threadSafetyCheckIsSmartPointer(S
, RT
))
548 return checkRecordDeclForAttr
<CapabilityAttr
>(RT
->getDecl());
551 static bool checkTypedefTypeForCapability(QualType Ty
) {
552 const auto *TD
= Ty
->getAs
<TypedefType
>();
556 TypedefNameDecl
*TN
= TD
->getDecl();
560 return TN
->hasAttr
<CapabilityAttr
>();
563 static bool typeHasCapability(Sema
&S
, QualType Ty
) {
564 if (checkTypedefTypeForCapability(Ty
))
567 if (checkRecordTypeForCapability(S
, Ty
))
573 static bool isCapabilityExpr(Sema
&S
, const Expr
*Ex
) {
574 // Capability expressions are simple expressions involving the boolean logic
575 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
576 // a DeclRefExpr is found, its type should be checked to determine whether it
577 // is a capability or not.
579 if (const auto *E
= dyn_cast
<CastExpr
>(Ex
))
580 return isCapabilityExpr(S
, E
->getSubExpr());
581 else if (const auto *E
= dyn_cast
<ParenExpr
>(Ex
))
582 return isCapabilityExpr(S
, E
->getSubExpr());
583 else if (const auto *E
= dyn_cast
<UnaryOperator
>(Ex
)) {
584 if (E
->getOpcode() == UO_LNot
|| E
->getOpcode() == UO_AddrOf
||
585 E
->getOpcode() == UO_Deref
)
586 return isCapabilityExpr(S
, E
->getSubExpr());
588 } else if (const auto *E
= dyn_cast
<BinaryOperator
>(Ex
)) {
589 if (E
->getOpcode() == BO_LAnd
|| E
->getOpcode() == BO_LOr
)
590 return isCapabilityExpr(S
, E
->getLHS()) &&
591 isCapabilityExpr(S
, E
->getRHS());
595 return typeHasCapability(S
, Ex
->getType());
598 /// Checks that all attribute arguments, starting from Sidx, resolve to
599 /// a capability object.
600 /// \param Sidx The attribute argument index to start checking with.
601 /// \param ParamIdxOk Whether an argument can be indexing into a function
603 static void checkAttrArgsAreCapabilityObjs(Sema
&S
, Decl
*D
,
604 const ParsedAttr
&AL
,
605 SmallVectorImpl
<Expr
*> &Args
,
607 bool ParamIdxOk
= false) {
608 if (Sidx
== AL
.getNumArgs()) {
609 // If we don't have any capability arguments, the attribute implicitly
610 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
611 // a non-static method, and that the class is a (scoped) capability.
612 const auto *MD
= dyn_cast
<const CXXMethodDecl
>(D
);
613 if (MD
&& !MD
->isStatic()) {
614 const CXXRecordDecl
*RD
= MD
->getParent();
615 // FIXME -- need to check this again on template instantiation
616 if (!checkRecordDeclForAttr
<CapabilityAttr
>(RD
) &&
617 !checkRecordDeclForAttr
<ScopedLockableAttr
>(RD
))
619 diag::warn_thread_attribute_not_on_capability_member
)
620 << AL
<< MD
->getParent();
622 S
.Diag(AL
.getLoc(), diag::warn_thread_attribute_not_on_non_static_member
)
627 for (unsigned Idx
= Sidx
; Idx
< AL
.getNumArgs(); ++Idx
) {
628 Expr
*ArgExp
= AL
.getArgAsExpr(Idx
);
630 if (ArgExp
->isTypeDependent()) {
631 // FIXME -- need to check this again on template instantiation
632 Args
.push_back(ArgExp
);
636 if (const auto *StrLit
= dyn_cast
<StringLiteral
>(ArgExp
)) {
637 if (StrLit
->getLength() == 0 ||
638 (StrLit
->isOrdinary() && StrLit
->getString() == StringRef("*"))) {
639 // Pass empty strings to the analyzer without warnings.
640 // Treat "*" as the universal lock.
641 Args
.push_back(ArgExp
);
645 // We allow constant strings to be used as a placeholder for expressions
646 // that are not valid C++ syntax, but warn that they are ignored.
647 S
.Diag(AL
.getLoc(), diag::warn_thread_attribute_ignored
) << AL
;
648 Args
.push_back(ArgExp
);
652 QualType ArgTy
= ArgExp
->getType();
654 // A pointer to member expression of the form &MyClass::mu is treated
655 // specially -- we need to look at the type of the member.
656 if (const auto *UOp
= dyn_cast
<UnaryOperator
>(ArgExp
))
657 if (UOp
->getOpcode() == UO_AddrOf
)
658 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(UOp
->getSubExpr()))
659 if (DRE
->getDecl()->isCXXInstanceMember())
660 ArgTy
= DRE
->getDecl()->getType();
662 // First see if we can just cast to record type, or pointer to record type.
663 const RecordType
*RT
= getRecordType(ArgTy
);
665 // Now check if we index into a record type function param.
666 if(!RT
&& ParamIdxOk
) {
667 const auto *FD
= dyn_cast
<FunctionDecl
>(D
);
668 const auto *IL
= dyn_cast
<IntegerLiteral
>(ArgExp
);
670 unsigned int NumParams
= FD
->getNumParams();
671 llvm::APInt ArgValue
= IL
->getValue();
672 uint64_t ParamIdxFromOne
= ArgValue
.getZExtValue();
673 uint64_t ParamIdxFromZero
= ParamIdxFromOne
- 1;
674 if (!ArgValue
.isStrictlyPositive() || ParamIdxFromOne
> NumParams
) {
676 diag::err_attribute_argument_out_of_bounds_extra_info
)
677 << AL
<< Idx
+ 1 << NumParams
;
680 ArgTy
= FD
->getParamDecl(ParamIdxFromZero
)->getType();
684 // If the type does not have a capability, see if the components of the
685 // expression have capabilities. This allows for writing C code where the
686 // capability may be on the type, and the expression is a capability
687 // boolean logic expression. Eg) requires_capability(A || B && !C)
688 if (!typeHasCapability(S
, ArgTy
) && !isCapabilityExpr(S
, ArgExp
))
689 S
.Diag(AL
.getLoc(), diag::warn_thread_attribute_argument_not_lockable
)
692 Args
.push_back(ArgExp
);
696 //===----------------------------------------------------------------------===//
697 // Attribute Implementations
698 //===----------------------------------------------------------------------===//
700 static void handlePtGuardedVarAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
701 if (!threadSafetyCheckIsPointer(S
, D
, AL
))
704 D
->addAttr(::new (S
.Context
) PtGuardedVarAttr(S
.Context
, AL
));
707 static bool checkGuardedByAttrCommon(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
709 SmallVector
<Expr
*, 1> Args
;
710 // check that all arguments are lockable objects
711 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
);
712 unsigned Size
= Args
.size();
721 static void handleGuardedByAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
723 if (!checkGuardedByAttrCommon(S
, D
, AL
, Arg
))
726 D
->addAttr(::new (S
.Context
) GuardedByAttr(S
.Context
, AL
, Arg
));
729 static void handlePtGuardedByAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
731 if (!checkGuardedByAttrCommon(S
, D
, AL
, Arg
))
734 if (!threadSafetyCheckIsPointer(S
, D
, AL
))
737 D
->addAttr(::new (S
.Context
) PtGuardedByAttr(S
.Context
, AL
, Arg
));
740 static bool checkAcquireOrderAttrCommon(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
741 SmallVectorImpl
<Expr
*> &Args
) {
742 if (!AL
.checkAtLeastNumArgs(S
, 1))
745 // Check that this attribute only applies to lockable types.
746 QualType QT
= cast
<ValueDecl
>(D
)->getType();
747 if (!QT
->isDependentType() && !typeHasCapability(S
, QT
)) {
748 S
.Diag(AL
.getLoc(), diag::warn_thread_attribute_decl_not_lockable
) << AL
;
752 // Check that all arguments are lockable objects.
753 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
);
760 static void handleAcquiredAfterAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
761 SmallVector
<Expr
*, 1> Args
;
762 if (!checkAcquireOrderAttrCommon(S
, D
, AL
, Args
))
765 Expr
**StartArg
= &Args
[0];
766 D
->addAttr(::new (S
.Context
)
767 AcquiredAfterAttr(S
.Context
, AL
, StartArg
, Args
.size()));
770 static void handleAcquiredBeforeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
771 SmallVector
<Expr
*, 1> Args
;
772 if (!checkAcquireOrderAttrCommon(S
, D
, AL
, Args
))
775 Expr
**StartArg
= &Args
[0];
776 D
->addAttr(::new (S
.Context
)
777 AcquiredBeforeAttr(S
.Context
, AL
, StartArg
, Args
.size()));
780 static bool checkLockFunAttrCommon(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
781 SmallVectorImpl
<Expr
*> &Args
) {
782 // zero or more arguments ok
783 // check that all arguments are lockable objects
784 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
, 0, /*ParamIdxOk=*/true);
789 static void handleAssertSharedLockAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
790 SmallVector
<Expr
*, 1> Args
;
791 if (!checkLockFunAttrCommon(S
, D
, AL
, Args
))
794 unsigned Size
= Args
.size();
795 Expr
**StartArg
= Size
== 0 ? nullptr : &Args
[0];
796 D
->addAttr(::new (S
.Context
)
797 AssertSharedLockAttr(S
.Context
, AL
, StartArg
, Size
));
800 static void handleAssertExclusiveLockAttr(Sema
&S
, Decl
*D
,
801 const ParsedAttr
&AL
) {
802 SmallVector
<Expr
*, 1> Args
;
803 if (!checkLockFunAttrCommon(S
, D
, AL
, Args
))
806 unsigned Size
= Args
.size();
807 Expr
**StartArg
= Size
== 0 ? nullptr : &Args
[0];
808 D
->addAttr(::new (S
.Context
)
809 AssertExclusiveLockAttr(S
.Context
, AL
, StartArg
, Size
));
812 /// Checks to be sure that the given parameter number is in bounds, and
813 /// is an integral type. Will emit appropriate diagnostics if this returns
816 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
817 template <typename AttrInfo
>
818 static bool checkParamIsIntegerType(Sema
&S
, const Decl
*D
, const AttrInfo
&AI
,
819 unsigned AttrArgNo
) {
820 assert(AI
.isArgExpr(AttrArgNo
) && "Expected expression argument");
821 Expr
*AttrArg
= AI
.getArgAsExpr(AttrArgNo
);
823 if (!checkFunctionOrMethodParameterIndex(S
, D
, AI
, AttrArgNo
+ 1, AttrArg
,
827 QualType ParamTy
= getFunctionOrMethodParamType(D
, Idx
.getASTIndex());
828 if (!ParamTy
->isIntegerType() && !ParamTy
->isCharType()) {
829 SourceLocation SrcLoc
= AttrArg
->getBeginLoc();
830 S
.Diag(SrcLoc
, diag::err_attribute_integers_only
)
831 << AI
<< getFunctionOrMethodParamRange(D
, Idx
.getASTIndex());
837 static void handleAllocSizeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
838 if (!AL
.checkAtLeastNumArgs(S
, 1) || !AL
.checkAtMostNumArgs(S
, 2))
841 assert(isFunctionOrMethod(D
) && hasFunctionProto(D
));
843 QualType RetTy
= getFunctionOrMethodResultType(D
);
844 if (!RetTy
->isPointerType()) {
845 S
.Diag(AL
.getLoc(), diag::warn_attribute_return_pointers_only
) << AL
;
849 const Expr
*SizeExpr
= AL
.getArgAsExpr(0);
851 // Parameter indices are 1-indexed, hence Index=1
852 if (!checkPositiveIntArgument(S
, AL
, SizeExpr
, SizeArgNoVal
, /*Idx=*/1))
854 if (!checkParamIsIntegerType(S
, D
, AL
, /*AttrArgNo=*/0))
856 ParamIdx
SizeArgNo(SizeArgNoVal
, D
);
858 ParamIdx NumberArgNo
;
859 if (AL
.getNumArgs() == 2) {
860 const Expr
*NumberExpr
= AL
.getArgAsExpr(1);
862 // Parameter indices are 1-based, hence Index=2
863 if (!checkPositiveIntArgument(S
, AL
, NumberExpr
, Val
, /*Idx=*/2))
865 if (!checkParamIsIntegerType(S
, D
, AL
, /*AttrArgNo=*/1))
867 NumberArgNo
= ParamIdx(Val
, D
);
870 D
->addAttr(::new (S
.Context
)
871 AllocSizeAttr(S
.Context
, AL
, SizeArgNo
, NumberArgNo
));
874 static bool checkTryLockFunAttrCommon(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
875 SmallVectorImpl
<Expr
*> &Args
) {
876 if (!AL
.checkAtLeastNumArgs(S
, 1))
879 if (!isIntOrBool(AL
.getArgAsExpr(0))) {
880 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
881 << AL
<< 1 << AANT_ArgumentIntOrBool
;
885 // check that all arguments are lockable objects
886 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
, 1);
891 static void handleSharedTrylockFunctionAttr(Sema
&S
, Decl
*D
,
892 const ParsedAttr
&AL
) {
893 SmallVector
<Expr
*, 2> Args
;
894 if (!checkTryLockFunAttrCommon(S
, D
, AL
, Args
))
897 D
->addAttr(::new (S
.Context
) SharedTrylockFunctionAttr(
898 S
.Context
, AL
, AL
.getArgAsExpr(0), Args
.data(), Args
.size()));
901 static void handleExclusiveTrylockFunctionAttr(Sema
&S
, Decl
*D
,
902 const ParsedAttr
&AL
) {
903 SmallVector
<Expr
*, 2> Args
;
904 if (!checkTryLockFunAttrCommon(S
, D
, AL
, Args
))
907 D
->addAttr(::new (S
.Context
) ExclusiveTrylockFunctionAttr(
908 S
.Context
, AL
, AL
.getArgAsExpr(0), Args
.data(), Args
.size()));
911 static void handleLockReturnedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
912 // check that the argument is lockable object
913 SmallVector
<Expr
*, 1> Args
;
914 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
);
915 unsigned Size
= Args
.size();
919 D
->addAttr(::new (S
.Context
) LockReturnedAttr(S
.Context
, AL
, Args
[0]));
922 static void handleLocksExcludedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
923 if (!AL
.checkAtLeastNumArgs(S
, 1))
926 // check that all arguments are lockable objects
927 SmallVector
<Expr
*, 1> Args
;
928 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
);
929 unsigned Size
= Args
.size();
932 Expr
**StartArg
= &Args
[0];
934 D
->addAttr(::new (S
.Context
)
935 LocksExcludedAttr(S
.Context
, AL
, StartArg
, Size
));
938 static bool checkFunctionConditionAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
939 Expr
*&Cond
, StringRef
&Msg
) {
940 Cond
= AL
.getArgAsExpr(0);
941 if (!Cond
->isTypeDependent()) {
942 ExprResult Converted
= S
.PerformContextuallyConvertToBool(Cond
);
943 if (Converted
.isInvalid())
945 Cond
= Converted
.get();
948 if (!S
.checkStringLiteralArgumentAttr(AL
, 1, Msg
))
952 Msg
= "<no message provided>";
954 SmallVector
<PartialDiagnosticAt
, 8> Diags
;
955 if (isa
<FunctionDecl
>(D
) && !Cond
->isValueDependent() &&
956 !Expr::isPotentialConstantExprUnevaluated(Cond
, cast
<FunctionDecl
>(D
),
958 S
.Diag(AL
.getLoc(), diag::err_attr_cond_never_constant_expr
) << AL
;
959 for (const PartialDiagnosticAt
&PDiag
: Diags
)
960 S
.Diag(PDiag
.first
, PDiag
.second
);
966 static void handleEnableIfAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
967 S
.Diag(AL
.getLoc(), diag::ext_clang_enable_if
);
971 if (checkFunctionConditionAttr(S
, D
, AL
, Cond
, Msg
))
972 D
->addAttr(::new (S
.Context
) EnableIfAttr(S
.Context
, AL
, Cond
, Msg
));
975 static void handleErrorAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
976 StringRef NewUserDiagnostic
;
977 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, NewUserDiagnostic
))
979 if (ErrorAttr
*EA
= S
.mergeErrorAttr(D
, AL
, NewUserDiagnostic
))
984 /// Determines if a given Expr references any of the given function's
985 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
986 class ArgumentDependenceChecker
987 : public RecursiveASTVisitor
<ArgumentDependenceChecker
> {
989 const CXXRecordDecl
*ClassType
;
991 llvm::SmallPtrSet
<const ParmVarDecl
*, 16> Parms
;
995 ArgumentDependenceChecker(const FunctionDecl
*FD
) {
997 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
998 ClassType
= MD
->getParent();
1000 ClassType
= nullptr;
1002 Parms
.insert(FD
->param_begin(), FD
->param_end());
1005 bool referencesArgs(Expr
*E
) {
1011 bool VisitCXXThisExpr(CXXThisExpr
*E
) {
1012 assert(E
->getType()->getPointeeCXXRecordDecl() == ClassType
&&
1013 "`this` doesn't refer to the enclosing class?");
1018 bool VisitDeclRefExpr(DeclRefExpr
*DRE
) {
1019 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl()))
1020 if (Parms
.count(PVD
)) {
1029 static void handleDiagnoseAsBuiltinAttr(Sema
&S
, Decl
*D
,
1030 const ParsedAttr
&AL
) {
1031 const auto *DeclFD
= cast
<FunctionDecl
>(D
);
1033 if (const auto *MethodDecl
= dyn_cast
<CXXMethodDecl
>(DeclFD
))
1034 if (!MethodDecl
->isStatic()) {
1035 S
.Diag(AL
.getLoc(), diag::err_attribute_no_member_function
) << AL
;
1039 auto DiagnoseType
= [&](unsigned Index
, AttributeArgumentNType T
) {
1040 SourceLocation Loc
= [&]() {
1041 auto Union
= AL
.getArg(Index
- 1);
1042 if (Union
.is
<Expr
*>())
1043 return Union
.get
<Expr
*>()->getBeginLoc();
1044 return Union
.get
<IdentifierLoc
*>()->Loc
;
1047 S
.Diag(Loc
, diag::err_attribute_argument_n_type
) << AL
<< Index
<< T
;
1050 FunctionDecl
*AttrFD
= [&]() -> FunctionDecl
* {
1051 if (!AL
.isArgExpr(0))
1053 auto *F
= dyn_cast_if_present
<DeclRefExpr
>(AL
.getArgAsExpr(0));
1056 return dyn_cast_if_present
<FunctionDecl
>(F
->getFoundDecl());
1059 if (!AttrFD
|| !AttrFD
->getBuiltinID(true)) {
1060 DiagnoseType(1, AANT_ArgumentBuiltinFunction
);
1064 if (AttrFD
->getNumParams() != AL
.getNumArgs() - 1) {
1065 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments_for
)
1066 << AL
<< AttrFD
<< AttrFD
->getNumParams();
1070 SmallVector
<unsigned, 8> Indices
;
1072 for (unsigned I
= 1; I
< AL
.getNumArgs(); ++I
) {
1073 if (!AL
.isArgExpr(I
)) {
1074 DiagnoseType(I
+ 1, AANT_ArgumentIntegerConstant
);
1078 const Expr
*IndexExpr
= AL
.getArgAsExpr(I
);
1081 if (!checkUInt32Argument(S
, AL
, IndexExpr
, Index
, I
+ 1, false))
1084 if (Index
> DeclFD
->getNumParams()) {
1085 S
.Diag(AL
.getLoc(), diag::err_attribute_bounds_for_function
)
1086 << AL
<< Index
<< DeclFD
<< DeclFD
->getNumParams();
1090 QualType T1
= AttrFD
->getParamDecl(I
- 1)->getType();
1091 QualType T2
= DeclFD
->getParamDecl(Index
- 1)->getType();
1093 if (T1
.getCanonicalType().getUnqualifiedType() !=
1094 T2
.getCanonicalType().getUnqualifiedType()) {
1095 S
.Diag(IndexExpr
->getBeginLoc(), diag::err_attribute_parameter_types
)
1096 << AL
<< Index
<< DeclFD
<< T2
<< I
<< AttrFD
<< T1
;
1100 Indices
.push_back(Index
- 1);
1103 D
->addAttr(::new (S
.Context
) DiagnoseAsBuiltinAttr(
1104 S
.Context
, AL
, AttrFD
, Indices
.data(), Indices
.size()));
1107 static void handleDiagnoseIfAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1108 S
.Diag(AL
.getLoc(), diag::ext_clang_diagnose_if
);
1112 if (!checkFunctionConditionAttr(S
, D
, AL
, Cond
, Msg
))
1115 StringRef DiagTypeStr
;
1116 if (!S
.checkStringLiteralArgumentAttr(AL
, 2, DiagTypeStr
))
1119 DiagnoseIfAttr::DiagnosticType DiagType
;
1120 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr
, DiagType
)) {
1121 S
.Diag(AL
.getArgAsExpr(2)->getBeginLoc(),
1122 diag::err_diagnose_if_invalid_diagnostic_type
);
1126 bool ArgDependent
= false;
1127 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
1128 ArgDependent
= ArgumentDependenceChecker(FD
).referencesArgs(Cond
);
1129 D
->addAttr(::new (S
.Context
) DiagnoseIfAttr(
1130 S
.Context
, AL
, Cond
, Msg
, DiagType
, ArgDependent
, cast
<NamedDecl
>(D
)));
1133 static void handleNoBuiltinAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1134 static constexpr const StringRef kWildcard
= "*";
1136 llvm::SmallVector
<StringRef
, 16> Names
;
1137 bool HasWildcard
= false;
1139 const auto AddBuiltinName
= [&Names
, &HasWildcard
](StringRef Name
) {
1140 if (Name
== kWildcard
)
1142 Names
.push_back(Name
);
1145 // Add previously defined attributes.
1146 if (const auto *NBA
= D
->getAttr
<NoBuiltinAttr
>())
1147 for (StringRef BuiltinName
: NBA
->builtinNames())
1148 AddBuiltinName(BuiltinName
);
1150 // Add current attributes.
1151 if (AL
.getNumArgs() == 0)
1152 AddBuiltinName(kWildcard
);
1154 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
!= E
; ++I
) {
1155 StringRef BuiltinName
;
1156 SourceLocation LiteralLoc
;
1157 if (!S
.checkStringLiteralArgumentAttr(AL
, I
, BuiltinName
, &LiteralLoc
))
1160 if (Builtin::Context::isBuiltinFunc(BuiltinName
))
1161 AddBuiltinName(BuiltinName
);
1163 S
.Diag(LiteralLoc
, diag::warn_attribute_no_builtin_invalid_builtin_name
)
1164 << BuiltinName
<< AL
;
1167 // Repeating the same attribute is fine.
1169 Names
.erase(std::unique(Names
.begin(), Names
.end()), Names
.end());
1171 // Empty no_builtin must be on its own.
1172 if (HasWildcard
&& Names
.size() > 1)
1173 S
.Diag(D
->getLocation(),
1174 diag::err_attribute_no_builtin_wildcard_or_builtin_name
)
1177 if (D
->hasAttr
<NoBuiltinAttr
>())
1178 D
->dropAttr
<NoBuiltinAttr
>();
1179 D
->addAttr(::new (S
.Context
)
1180 NoBuiltinAttr(S
.Context
, AL
, Names
.data(), Names
.size()));
1183 static void handlePassObjectSizeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1184 if (D
->hasAttr
<PassObjectSizeAttr
>()) {
1185 S
.Diag(D
->getBeginLoc(), diag::err_attribute_only_once_per_parameter
) << AL
;
1189 Expr
*E
= AL
.getArgAsExpr(0);
1191 if (!checkUInt32Argument(S
, AL
, E
, Type
, /*Idx=*/1))
1194 // pass_object_size's argument is passed in as the second argument of
1195 // __builtin_object_size. So, it has the same constraints as that second
1196 // argument; namely, it must be in the range [0, 3].
1198 S
.Diag(E
->getBeginLoc(), diag::err_attribute_argument_out_of_range
)
1199 << AL
<< 0 << 3 << E
->getSourceRange();
1203 // pass_object_size is only supported on constant pointer parameters; as a
1204 // kindness to users, we allow the parameter to be non-const for declarations.
1205 // At this point, we have no clue if `D` belongs to a function declaration or
1206 // definition, so we defer the constness check until later.
1207 if (!cast
<ParmVarDecl
>(D
)->getType()->isPointerType()) {
1208 S
.Diag(D
->getBeginLoc(), diag::err_attribute_pointers_only
) << AL
<< 1;
1212 D
->addAttr(::new (S
.Context
) PassObjectSizeAttr(S
.Context
, AL
, (int)Type
));
1215 static void handleConsumableAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1216 ConsumableAttr::ConsumedState DefaultState
;
1218 if (AL
.isArgIdent(0)) {
1219 IdentifierLoc
*IL
= AL
.getArgAsIdent(0);
1220 if (!ConsumableAttr::ConvertStrToConsumedState(IL
->Ident
->getName(),
1222 S
.Diag(IL
->Loc
, diag::warn_attribute_type_not_supported
) << AL
1227 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
1228 << AL
<< AANT_ArgumentIdentifier
;
1232 D
->addAttr(::new (S
.Context
) ConsumableAttr(S
.Context
, AL
, DefaultState
));
1235 static bool checkForConsumableClass(Sema
&S
, const CXXMethodDecl
*MD
,
1236 const ParsedAttr
&AL
) {
1237 QualType ThisType
= MD
->getFunctionObjectParameterType();
1239 if (const CXXRecordDecl
*RD
= ThisType
->getAsCXXRecordDecl()) {
1240 if (!RD
->hasAttr
<ConsumableAttr
>()) {
1241 S
.Diag(AL
.getLoc(), diag::warn_attr_on_unconsumable_class
) << RD
;
1250 static void handleCallableWhenAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1251 if (!AL
.checkAtLeastNumArgs(S
, 1))
1254 if (!checkForConsumableClass(S
, cast
<CXXMethodDecl
>(D
), AL
))
1257 SmallVector
<CallableWhenAttr::ConsumedState
, 3> States
;
1258 for (unsigned ArgIndex
= 0; ArgIndex
< AL
.getNumArgs(); ++ArgIndex
) {
1259 CallableWhenAttr::ConsumedState CallableState
;
1261 StringRef StateString
;
1263 if (AL
.isArgIdent(ArgIndex
)) {
1264 IdentifierLoc
*Ident
= AL
.getArgAsIdent(ArgIndex
);
1265 StateString
= Ident
->Ident
->getName();
1268 if (!S
.checkStringLiteralArgumentAttr(AL
, ArgIndex
, StateString
, &Loc
))
1272 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString
,
1274 S
.Diag(Loc
, diag::warn_attribute_type_not_supported
) << AL
<< StateString
;
1278 States
.push_back(CallableState
);
1281 D
->addAttr(::new (S
.Context
)
1282 CallableWhenAttr(S
.Context
, AL
, States
.data(), States
.size()));
1285 static void handleParamTypestateAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1286 ParamTypestateAttr::ConsumedState ParamState
;
1288 if (AL
.isArgIdent(0)) {
1289 IdentifierLoc
*Ident
= AL
.getArgAsIdent(0);
1290 StringRef StateString
= Ident
->Ident
->getName();
1292 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString
,
1294 S
.Diag(Ident
->Loc
, diag::warn_attribute_type_not_supported
)
1295 << AL
<< StateString
;
1299 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
1300 << AL
<< AANT_ArgumentIdentifier
;
1304 // FIXME: This check is currently being done in the analysis. It can be
1305 // enabled here only after the parser propagates attributes at
1306 // template specialization definition, not declaration.
1307 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1308 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1310 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1311 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1312 // ReturnType.getAsString();
1316 D
->addAttr(::new (S
.Context
) ParamTypestateAttr(S
.Context
, AL
, ParamState
));
1319 static void handleReturnTypestateAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1320 ReturnTypestateAttr::ConsumedState ReturnState
;
1322 if (AL
.isArgIdent(0)) {
1323 IdentifierLoc
*IL
= AL
.getArgAsIdent(0);
1324 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL
->Ident
->getName(),
1326 S
.Diag(IL
->Loc
, diag::warn_attribute_type_not_supported
) << AL
1331 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
1332 << AL
<< AANT_ArgumentIdentifier
;
1336 // FIXME: This check is currently being done in the analysis. It can be
1337 // enabled here only after the parser propagates attributes at
1338 // template specialization definition, not declaration.
1339 // QualType ReturnType;
1341 // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1342 // ReturnType = Param->getType();
1344 //} else if (const CXXConstructorDecl *Constructor =
1345 // dyn_cast<CXXConstructorDecl>(D)) {
1346 // ReturnType = Constructor->getFunctionObjectParameterType();
1350 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1353 // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1355 // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1356 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1357 // ReturnType.getAsString();
1361 D
->addAttr(::new (S
.Context
) ReturnTypestateAttr(S
.Context
, AL
, ReturnState
));
1364 static void handleSetTypestateAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1365 if (!checkForConsumableClass(S
, cast
<CXXMethodDecl
>(D
), AL
))
1368 SetTypestateAttr::ConsumedState NewState
;
1369 if (AL
.isArgIdent(0)) {
1370 IdentifierLoc
*Ident
= AL
.getArgAsIdent(0);
1371 StringRef Param
= Ident
->Ident
->getName();
1372 if (!SetTypestateAttr::ConvertStrToConsumedState(Param
, NewState
)) {
1373 S
.Diag(Ident
->Loc
, diag::warn_attribute_type_not_supported
) << AL
1378 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
1379 << AL
<< AANT_ArgumentIdentifier
;
1383 D
->addAttr(::new (S
.Context
) SetTypestateAttr(S
.Context
, AL
, NewState
));
1386 static void handleTestTypestateAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1387 if (!checkForConsumableClass(S
, cast
<CXXMethodDecl
>(D
), AL
))
1390 TestTypestateAttr::ConsumedState TestState
;
1391 if (AL
.isArgIdent(0)) {
1392 IdentifierLoc
*Ident
= AL
.getArgAsIdent(0);
1393 StringRef Param
= Ident
->Ident
->getName();
1394 if (!TestTypestateAttr::ConvertStrToConsumedState(Param
, TestState
)) {
1395 S
.Diag(Ident
->Loc
, diag::warn_attribute_type_not_supported
) << AL
1400 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
1401 << AL
<< AANT_ArgumentIdentifier
;
1405 D
->addAttr(::new (S
.Context
) TestTypestateAttr(S
.Context
, AL
, TestState
));
1408 static void handleExtVectorTypeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1409 // Remember this typedef decl, we will need it later for diagnostics.
1410 S
.ExtVectorDecls
.push_back(cast
<TypedefNameDecl
>(D
));
1413 static void handlePackedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1414 if (auto *TD
= dyn_cast
<TagDecl
>(D
))
1415 TD
->addAttr(::new (S
.Context
) PackedAttr(S
.Context
, AL
));
1416 else if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
1417 bool BitfieldByteAligned
= (!FD
->getType()->isDependentType() &&
1418 !FD
->getType()->isIncompleteType() &&
1420 S
.Context
.getTypeAlign(FD
->getType()) <= 8);
1422 if (S
.getASTContext().getTargetInfo().getTriple().isPS()) {
1423 if (BitfieldByteAligned
)
1424 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1425 S
.Diag(AL
.getLoc(), diag::warn_attribute_ignored_for_field_of_type
)
1426 << AL
<< FD
->getType();
1428 FD
->addAttr(::new (S
.Context
) PackedAttr(S
.Context
, AL
));
1430 // Report warning about changed offset in the newer compiler versions.
1431 if (BitfieldByteAligned
)
1432 S
.Diag(AL
.getLoc(), diag::warn_attribute_packed_for_bitfield
);
1434 FD
->addAttr(::new (S
.Context
) PackedAttr(S
.Context
, AL
));
1438 S
.Diag(AL
.getLoc(), diag::warn_attribute_ignored
) << AL
;
1441 static void handlePreferredName(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1442 auto *RD
= cast
<CXXRecordDecl
>(D
);
1443 ClassTemplateDecl
*CTD
= RD
->getDescribedClassTemplate();
1444 assert(CTD
&& "attribute does not appertain to this declaration");
1446 ParsedType PT
= AL
.getTypeArg();
1447 TypeSourceInfo
*TSI
= nullptr;
1448 QualType T
= S
.GetTypeFromParser(PT
, &TSI
);
1450 TSI
= S
.Context
.getTrivialTypeSourceInfo(T
, AL
.getLoc());
1452 if (!T
.hasQualifiers() && T
->isTypedefNameType()) {
1453 // Find the template name, if this type names a template specialization.
1454 const TemplateDecl
*Template
= nullptr;
1455 if (const auto *CTSD
= dyn_cast_if_present
<ClassTemplateSpecializationDecl
>(
1456 T
->getAsCXXRecordDecl())) {
1457 Template
= CTSD
->getSpecializedTemplate();
1458 } else if (const auto *TST
= T
->getAs
<TemplateSpecializationType
>()) {
1459 while (TST
&& TST
->isTypeAlias())
1460 TST
= TST
->getAliasedType()->getAs
<TemplateSpecializationType
>();
1462 Template
= TST
->getTemplateName().getAsTemplateDecl();
1465 if (Template
&& declaresSameEntity(Template
, CTD
)) {
1466 D
->addAttr(::new (S
.Context
) PreferredNameAttr(S
.Context
, AL
, TSI
));
1471 S
.Diag(AL
.getLoc(), diag::err_attribute_preferred_name_arg_invalid
)
1473 if (const auto *TT
= T
->getAs
<TypedefType
>())
1474 S
.Diag(TT
->getDecl()->getLocation(), diag::note_entity_declared_at
)
1478 static bool checkIBOutletCommon(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1479 // The IBOutlet/IBOutletCollection attributes only apply to instance
1480 // variables or properties of Objective-C classes. The outlet must also
1481 // have an object reference type.
1482 if (const auto *VD
= dyn_cast
<ObjCIvarDecl
>(D
)) {
1483 if (!VD
->getType()->getAs
<ObjCObjectPointerType
>()) {
1484 S
.Diag(AL
.getLoc(), diag::warn_iboutlet_object_type
)
1485 << AL
<< VD
->getType() << 0;
1489 else if (const auto *PD
= dyn_cast
<ObjCPropertyDecl
>(D
)) {
1490 if (!PD
->getType()->getAs
<ObjCObjectPointerType
>()) {
1491 S
.Diag(AL
.getLoc(), diag::warn_iboutlet_object_type
)
1492 << AL
<< PD
->getType() << 1;
1497 S
.Diag(AL
.getLoc(), diag::warn_attribute_iboutlet
) << AL
;
1504 static void handleIBOutlet(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1505 if (!checkIBOutletCommon(S
, D
, AL
))
1508 D
->addAttr(::new (S
.Context
) IBOutletAttr(S
.Context
, AL
));
1511 static void handleIBOutletCollection(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1513 // The iboutletcollection attribute can have zero or one arguments.
1514 if (AL
.getNumArgs() > 1) {
1515 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
) << AL
<< 1;
1519 if (!checkIBOutletCommon(S
, D
, AL
))
1524 if (AL
.hasParsedType())
1525 PT
= AL
.getTypeArg();
1527 PT
= S
.getTypeName(S
.Context
.Idents
.get("NSObject"), AL
.getLoc(),
1528 S
.getScopeForContext(D
->getDeclContext()->getParent()));
1530 S
.Diag(AL
.getLoc(), diag::err_iboutletcollection_type
) << "NSObject";
1535 TypeSourceInfo
*QTLoc
= nullptr;
1536 QualType QT
= S
.GetTypeFromParser(PT
, &QTLoc
);
1538 QTLoc
= S
.Context
.getTrivialTypeSourceInfo(QT
, AL
.getLoc());
1540 // Diagnose use of non-object type in iboutletcollection attribute.
1541 // FIXME. Gnu attribute extension ignores use of builtin types in
1542 // attributes. So, __attribute__((iboutletcollection(char))) will be
1543 // treated as __attribute__((iboutletcollection())).
1544 if (!QT
->isObjCIdType() && !QT
->isObjCObjectType()) {
1546 QT
->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1547 : diag::err_iboutletcollection_type
) << QT
;
1551 D
->addAttr(::new (S
.Context
) IBOutletCollectionAttr(S
.Context
, AL
, QTLoc
));
1554 bool Sema::isValidPointerAttrType(QualType T
, bool RefOkay
) {
1556 if (T
->isReferenceType())
1559 T
= T
.getNonReferenceType();
1562 // The nonnull attribute, and other similar attributes, can be applied to a
1563 // transparent union that contains a pointer type.
1564 if (const RecordType
*UT
= T
->getAsUnionType()) {
1565 if (UT
&& UT
->getDecl()->hasAttr
<TransparentUnionAttr
>()) {
1566 RecordDecl
*UD
= UT
->getDecl();
1567 for (const auto *I
: UD
->fields()) {
1568 QualType QT
= I
->getType();
1569 if (QT
->isAnyPointerType() || QT
->isBlockPointerType())
1575 return T
->isAnyPointerType() || T
->isBlockPointerType();
1578 static bool attrNonNullArgCheck(Sema
&S
, QualType T
, const ParsedAttr
&AL
,
1579 SourceRange AttrParmRange
,
1580 SourceRange TypeRange
,
1581 bool isReturnValue
= false) {
1582 if (!S
.isValidPointerAttrType(T
)) {
1584 S
.Diag(AL
.getLoc(), diag::warn_attribute_return_pointers_only
)
1585 << AL
<< AttrParmRange
<< TypeRange
;
1587 S
.Diag(AL
.getLoc(), diag::warn_attribute_pointers_only
)
1588 << AL
<< AttrParmRange
<< TypeRange
<< 0;
1594 static void handleNonNullAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1595 SmallVector
<ParamIdx
, 8> NonNullArgs
;
1596 for (unsigned I
= 0; I
< AL
.getNumArgs(); ++I
) {
1597 Expr
*Ex
= AL
.getArgAsExpr(I
);
1599 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, I
+ 1, Ex
, Idx
))
1602 // Is the function argument a pointer type?
1603 if (Idx
.getASTIndex() < getFunctionOrMethodNumParams(D
) &&
1604 !attrNonNullArgCheck(
1605 S
, getFunctionOrMethodParamType(D
, Idx
.getASTIndex()), AL
,
1606 Ex
->getSourceRange(),
1607 getFunctionOrMethodParamRange(D
, Idx
.getASTIndex())))
1610 NonNullArgs
.push_back(Idx
);
1613 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1614 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1615 // check if the attribute came from a macro expansion or a template
1617 if (NonNullArgs
.empty() && AL
.getLoc().isFileID() &&
1618 !S
.inTemplateInstantiation()) {
1619 bool AnyPointers
= isFunctionOrMethodVariadic(D
);
1620 for (unsigned I
= 0, E
= getFunctionOrMethodNumParams(D
);
1621 I
!= E
&& !AnyPointers
; ++I
) {
1622 QualType T
= getFunctionOrMethodParamType(D
, I
);
1623 if (T
->isDependentType() || S
.isValidPointerAttrType(T
))
1628 S
.Diag(AL
.getLoc(), diag::warn_attribute_nonnull_no_pointers
);
1631 ParamIdx
*Start
= NonNullArgs
.data();
1632 unsigned Size
= NonNullArgs
.size();
1633 llvm::array_pod_sort(Start
, Start
+ Size
);
1634 D
->addAttr(::new (S
.Context
) NonNullAttr(S
.Context
, AL
, Start
, Size
));
1637 static void handleNonNullAttrParameter(Sema
&S
, ParmVarDecl
*D
,
1638 const ParsedAttr
&AL
) {
1639 if (AL
.getNumArgs() > 0) {
1640 if (D
->getFunctionType()) {
1641 handleNonNullAttr(S
, D
, AL
);
1643 S
.Diag(AL
.getLoc(), diag::warn_attribute_nonnull_parm_no_args
)
1644 << D
->getSourceRange();
1649 // Is the argument a pointer type?
1650 if (!attrNonNullArgCheck(S
, D
->getType(), AL
, SourceRange(),
1651 D
->getSourceRange()))
1654 D
->addAttr(::new (S
.Context
) NonNullAttr(S
.Context
, AL
, nullptr, 0));
1657 static void handleReturnsNonNullAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1658 QualType ResultType
= getFunctionOrMethodResultType(D
);
1659 SourceRange SR
= getFunctionOrMethodResultSourceRange(D
);
1660 if (!attrNonNullArgCheck(S
, ResultType
, AL
, SourceRange(), SR
,
1661 /* isReturnValue */ true))
1664 D
->addAttr(::new (S
.Context
) ReturnsNonNullAttr(S
.Context
, AL
));
1667 static void handleNoEscapeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1668 if (D
->isInvalidDecl())
1671 // noescape only applies to pointer types.
1672 QualType T
= cast
<ParmVarDecl
>(D
)->getType();
1673 if (!S
.isValidPointerAttrType(T
, /* RefOkay */ true)) {
1674 S
.Diag(AL
.getLoc(), diag::warn_attribute_pointers_only
)
1675 << AL
<< AL
.getRange() << 0;
1679 D
->addAttr(::new (S
.Context
) NoEscapeAttr(S
.Context
, AL
));
1682 static void handleAssumeAlignedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1683 Expr
*E
= AL
.getArgAsExpr(0),
1684 *OE
= AL
.getNumArgs() > 1 ? AL
.getArgAsExpr(1) : nullptr;
1685 S
.AddAssumeAlignedAttr(D
, AL
, E
, OE
);
1688 static void handleAllocAlignAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1689 S
.AddAllocAlignAttr(D
, AL
, AL
.getArgAsExpr(0));
1692 void Sema::AddAssumeAlignedAttr(Decl
*D
, const AttributeCommonInfo
&CI
, Expr
*E
,
1694 QualType ResultType
= getFunctionOrMethodResultType(D
);
1695 SourceRange SR
= getFunctionOrMethodResultSourceRange(D
);
1697 AssumeAlignedAttr
TmpAttr(Context
, CI
, E
, OE
);
1698 SourceLocation AttrLoc
= TmpAttr
.getLocation();
1700 if (!isValidPointerAttrType(ResultType
, /* RefOkay */ true)) {
1701 Diag(AttrLoc
, diag::warn_attribute_return_pointers_refs_only
)
1702 << &TmpAttr
<< TmpAttr
.getRange() << SR
;
1706 if (!E
->isValueDependent()) {
1707 std::optional
<llvm::APSInt
> I
= llvm::APSInt(64);
1708 if (!(I
= E
->getIntegerConstantExpr(Context
))) {
1710 Diag(AttrLoc
, diag::err_attribute_argument_n_type
)
1711 << &TmpAttr
<< 1 << AANT_ArgumentIntegerConstant
1712 << E
->getSourceRange();
1714 Diag(AttrLoc
, diag::err_attribute_argument_type
)
1715 << &TmpAttr
<< AANT_ArgumentIntegerConstant
1716 << E
->getSourceRange();
1720 if (!I
->isPowerOf2()) {
1721 Diag(AttrLoc
, diag::err_alignment_not_power_of_two
)
1722 << E
->getSourceRange();
1726 if (*I
> Sema::MaximumAlignment
)
1727 Diag(CI
.getLoc(), diag::warn_assume_aligned_too_great
)
1728 << CI
.getRange() << Sema::MaximumAlignment
;
1731 if (OE
&& !OE
->isValueDependent() && !OE
->isIntegerConstantExpr(Context
)) {
1732 Diag(AttrLoc
, diag::err_attribute_argument_n_type
)
1733 << &TmpAttr
<< 2 << AANT_ArgumentIntegerConstant
1734 << OE
->getSourceRange();
1738 D
->addAttr(::new (Context
) AssumeAlignedAttr(Context
, CI
, E
, OE
));
1741 void Sema::AddAllocAlignAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
1743 QualType ResultType
= getFunctionOrMethodResultType(D
);
1745 AllocAlignAttr
TmpAttr(Context
, CI
, ParamIdx());
1746 SourceLocation AttrLoc
= CI
.getLoc();
1748 if (!ResultType
->isDependentType() &&
1749 !isValidPointerAttrType(ResultType
, /* RefOkay */ true)) {
1750 Diag(AttrLoc
, diag::warn_attribute_return_pointers_refs_only
)
1751 << &TmpAttr
<< CI
.getRange() << getFunctionOrMethodResultSourceRange(D
);
1756 const auto *FuncDecl
= cast
<FunctionDecl
>(D
);
1757 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl
, TmpAttr
,
1758 /*AttrArgNum=*/1, ParamExpr
, Idx
))
1761 QualType Ty
= getFunctionOrMethodParamType(D
, Idx
.getASTIndex());
1762 if (!Ty
->isDependentType() && !Ty
->isIntegralType(Context
) &&
1763 !Ty
->isAlignValT()) {
1764 Diag(ParamExpr
->getBeginLoc(), diag::err_attribute_integers_only
)
1766 << FuncDecl
->getParamDecl(Idx
.getASTIndex())->getSourceRange();
1770 D
->addAttr(::new (Context
) AllocAlignAttr(Context
, CI
, Idx
));
1773 /// Check if \p AssumptionStr is a known assumption and warn if not.
1774 static void checkAssumptionAttr(Sema
&S
, SourceLocation Loc
,
1775 StringRef AssumptionStr
) {
1776 if (llvm::KnownAssumptionStrings
.count(AssumptionStr
))
1779 unsigned BestEditDistance
= 3;
1780 StringRef Suggestion
;
1781 for (const auto &KnownAssumptionIt
: llvm::KnownAssumptionStrings
) {
1782 unsigned EditDistance
=
1783 AssumptionStr
.edit_distance(KnownAssumptionIt
.getKey());
1784 if (EditDistance
< BestEditDistance
) {
1785 Suggestion
= KnownAssumptionIt
.getKey();
1786 BestEditDistance
= EditDistance
;
1790 if (!Suggestion
.empty())
1791 S
.Diag(Loc
, diag::warn_assume_attribute_string_unknown_suggested
)
1792 << AssumptionStr
<< Suggestion
;
1794 S
.Diag(Loc
, diag::warn_assume_attribute_string_unknown
) << AssumptionStr
;
1797 static void handleAssumumptionAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1798 // Handle the case where the attribute has a text message.
1800 SourceLocation AttrStrLoc
;
1801 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &AttrStrLoc
))
1804 checkAssumptionAttr(S
, AttrStrLoc
, Str
);
1806 D
->addAttr(::new (S
.Context
) AssumptionAttr(S
.Context
, AL
, Str
));
1809 /// Normalize the attribute, __foo__ becomes foo.
1810 /// Returns true if normalization was applied.
1811 static bool normalizeName(StringRef
&AttrName
) {
1812 if (AttrName
.size() > 4 && AttrName
.startswith("__") &&
1813 AttrName
.endswith("__")) {
1814 AttrName
= AttrName
.drop_front(2).drop_back(2);
1820 static void handleOwnershipAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1821 // This attribute must be applied to a function declaration. The first
1822 // argument to the attribute must be an identifier, the name of the resource,
1823 // for example: malloc. The following arguments must be argument indexes, the
1824 // arguments must be of integer type for Returns, otherwise of pointer type.
1825 // The difference between Holds and Takes is that a pointer may still be used
1826 // after being held. free() should be __attribute((ownership_takes)), whereas
1827 // a list append function may well be __attribute((ownership_holds)).
1829 if (!AL
.isArgIdent(0)) {
1830 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
1831 << AL
<< 1 << AANT_ArgumentIdentifier
;
1835 // Figure out our Kind.
1836 OwnershipAttr::OwnershipKind K
=
1837 OwnershipAttr(S
.Context
, AL
, nullptr, nullptr, 0).getOwnKind();
1841 case OwnershipAttr::Takes
:
1842 case OwnershipAttr::Holds
:
1843 if (AL
.getNumArgs() < 2) {
1844 S
.Diag(AL
.getLoc(), diag::err_attribute_too_few_arguments
) << AL
<< 2;
1848 case OwnershipAttr::Returns
:
1849 if (AL
.getNumArgs() > 2) {
1850 S
.Diag(AL
.getLoc(), diag::err_attribute_too_many_arguments
) << AL
<< 1;
1856 IdentifierInfo
*Module
= AL
.getArgAsIdent(0)->Ident
;
1858 StringRef ModuleName
= Module
->getName();
1859 if (normalizeName(ModuleName
)) {
1860 Module
= &S
.PP
.getIdentifierTable().get(ModuleName
);
1863 SmallVector
<ParamIdx
, 8> OwnershipArgs
;
1864 for (unsigned i
= 1; i
< AL
.getNumArgs(); ++i
) {
1865 Expr
*Ex
= AL
.getArgAsExpr(i
);
1867 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, i
, Ex
, Idx
))
1870 // Is the function argument a pointer type?
1871 QualType T
= getFunctionOrMethodParamType(D
, Idx
.getASTIndex());
1872 int Err
= -1; // No error
1874 case OwnershipAttr::Takes
:
1875 case OwnershipAttr::Holds
:
1876 if (!T
->isAnyPointerType() && !T
->isBlockPointerType())
1879 case OwnershipAttr::Returns
:
1880 if (!T
->isIntegerType())
1885 S
.Diag(AL
.getLoc(), diag::err_ownership_type
) << AL
<< Err
1886 << Ex
->getSourceRange();
1890 // Check we don't have a conflict with another ownership attribute.
1891 for (const auto *I
: D
->specific_attrs
<OwnershipAttr
>()) {
1892 // Cannot have two ownership attributes of different kinds for the same
1894 if (I
->getOwnKind() != K
&& llvm::is_contained(I
->args(), Idx
)) {
1895 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
1897 << (AL
.isRegularKeywordAttribute() ||
1898 I
->isRegularKeywordAttribute());
1900 } else if (K
== OwnershipAttr::Returns
&&
1901 I
->getOwnKind() == OwnershipAttr::Returns
) {
1902 // A returns attribute conflicts with any other returns attribute using
1903 // a different index.
1904 if (!llvm::is_contained(I
->args(), Idx
)) {
1905 S
.Diag(I
->getLocation(), diag::err_ownership_returns_index_mismatch
)
1906 << I
->args_begin()->getSourceIndex();
1908 S
.Diag(AL
.getLoc(), diag::note_ownership_returns_index_mismatch
)
1909 << Idx
.getSourceIndex() << Ex
->getSourceRange();
1914 OwnershipArgs
.push_back(Idx
);
1917 ParamIdx
*Start
= OwnershipArgs
.data();
1918 unsigned Size
= OwnershipArgs
.size();
1919 llvm::array_pod_sort(Start
, Start
+ Size
);
1920 D
->addAttr(::new (S
.Context
)
1921 OwnershipAttr(S
.Context
, AL
, Module
, Start
, Size
));
1924 static void handleWeakRefAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1925 // Check the attribute arguments.
1926 if (AL
.getNumArgs() > 1) {
1927 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
) << AL
<< 1;
1933 // static int a __attribute__((weakref ("v2")));
1934 // static int b() __attribute__((weakref ("f3")));
1936 // and ignores the attributes of
1938 // static int a __attribute__((weakref ("v2")));
1941 const DeclContext
*Ctx
= D
->getDeclContext()->getRedeclContext();
1942 if (!Ctx
->isFileContext()) {
1943 S
.Diag(AL
.getLoc(), diag::err_attribute_weakref_not_global_context
)
1944 << cast
<NamedDecl
>(D
);
1948 // The GCC manual says
1950 // At present, a declaration to which `weakref' is attached can only
1955 // Without a TARGET,
1956 // given as an argument to `weakref' or to `alias', `weakref' is
1957 // equivalent to `weak'.
1959 // gcc 4.4.1 will accept
1960 // int a7 __attribute__((weakref));
1962 // int a7 __attribute__((weak));
1963 // This looks like a bug in gcc. We reject that for now. We should revisit
1964 // it if this behaviour is actually used.
1967 // static ((alias ("y"), weakref)).
1968 // Should we? How to check that weakref is before or after alias?
1970 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1971 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1972 // StringRef parameter it was given anyway.
1974 if (AL
.getNumArgs() && S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
1975 // GCC will accept anything as the argument of weakref. Should we
1976 // check for an existing decl?
1977 D
->addAttr(::new (S
.Context
) AliasAttr(S
.Context
, AL
, Str
));
1979 D
->addAttr(::new (S
.Context
) WeakRefAttr(S
.Context
, AL
));
1982 static void handleIFuncAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1984 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
1987 // Aliases should be on declarations, not definitions.
1988 const auto *FD
= cast
<FunctionDecl
>(D
);
1989 if (FD
->isThisDeclarationADefinition()) {
1990 S
.Diag(AL
.getLoc(), diag::err_alias_is_definition
) << FD
<< 1;
1994 D
->addAttr(::new (S
.Context
) IFuncAttr(S
.Context
, AL
, Str
));
1997 static void handleAliasAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
1999 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
2002 if (S
.Context
.getTargetInfo().getTriple().isOSDarwin()) {
2003 S
.Diag(AL
.getLoc(), diag::err_alias_not_supported_on_darwin
);
2007 if (S
.Context
.getTargetInfo().getTriple().isNVPTX()) {
2008 CudaVersion Version
=
2009 ToCudaVersion(S
.Context
.getTargetInfo().getSDKVersion());
2010 if (Version
!= CudaVersion::UNKNOWN
&& Version
< CudaVersion::CUDA_100
)
2011 S
.Diag(AL
.getLoc(), diag::err_alias_not_supported_on_nvptx
);
2014 // Aliases should be on declarations, not definitions.
2015 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
2016 if (FD
->isThisDeclarationADefinition()) {
2017 S
.Diag(AL
.getLoc(), diag::err_alias_is_definition
) << FD
<< 0;
2021 const auto *VD
= cast
<VarDecl
>(D
);
2022 if (VD
->isThisDeclarationADefinition() && VD
->isExternallyVisible()) {
2023 S
.Diag(AL
.getLoc(), diag::err_alias_is_definition
) << VD
<< 0;
2028 // Mark target used to prevent unneeded-internal-declaration warnings.
2029 if (!S
.LangOpts
.CPlusPlus
) {
2030 // FIXME: demangle Str for C++, as the attribute refers to the mangled
2031 // linkage name, not the pre-mangled identifier.
2032 const DeclarationNameInfo
target(&S
.Context
.Idents
.get(Str
), AL
.getLoc());
2033 LookupResult
LR(S
, target
, Sema::LookupOrdinaryName
);
2034 if (S
.LookupQualifiedName(LR
, S
.getCurLexicalContext()))
2035 for (NamedDecl
*ND
: LR
)
2036 ND
->markUsed(S
.Context
);
2039 D
->addAttr(::new (S
.Context
) AliasAttr(S
.Context
, AL
, Str
));
2042 static void handleTLSModelAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2044 SourceLocation LiteralLoc
;
2045 // Check that it is a string.
2046 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Model
, &LiteralLoc
))
2049 // Check that the value.
2050 if (Model
!= "global-dynamic" && Model
!= "local-dynamic"
2051 && Model
!= "initial-exec" && Model
!= "local-exec") {
2052 S
.Diag(LiteralLoc
, diag::err_attr_tlsmodel_arg
);
2056 if (S
.Context
.getTargetInfo().getTriple().isOSAIX() &&
2057 Model
== "local-dynamic") {
2058 S
.Diag(LiteralLoc
, diag::err_aix_attr_unsupported_tls_model
) << Model
;
2062 D
->addAttr(::new (S
.Context
) TLSModelAttr(S
.Context
, AL
, Model
));
2065 static void handleRestrictAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2066 QualType ResultType
= getFunctionOrMethodResultType(D
);
2067 if (ResultType
->isAnyPointerType() || ResultType
->isBlockPointerType()) {
2068 D
->addAttr(::new (S
.Context
) RestrictAttr(S
.Context
, AL
));
2072 S
.Diag(AL
.getLoc(), diag::warn_attribute_return_pointers_only
)
2073 << AL
<< getFunctionOrMethodResultSourceRange(D
);
2076 static void handleCPUSpecificAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2077 // Ensure we don't combine these with themselves, since that causes some
2078 // confusing behavior.
2079 if (AL
.getParsedKind() == ParsedAttr::AT_CPUDispatch
) {
2080 if (checkAttrMutualExclusion
<CPUSpecificAttr
>(S
, D
, AL
))
2083 if (const auto *Other
= D
->getAttr
<CPUDispatchAttr
>()) {
2084 S
.Diag(AL
.getLoc(), diag::err_disallowed_duplicate_attribute
) << AL
;
2085 S
.Diag(Other
->getLocation(), diag::note_conflicting_attribute
);
2088 } else if (AL
.getParsedKind() == ParsedAttr::AT_CPUSpecific
) {
2089 if (checkAttrMutualExclusion
<CPUDispatchAttr
>(S
, D
, AL
))
2092 if (const auto *Other
= D
->getAttr
<CPUSpecificAttr
>()) {
2093 S
.Diag(AL
.getLoc(), diag::err_disallowed_duplicate_attribute
) << AL
;
2094 S
.Diag(Other
->getLocation(), diag::note_conflicting_attribute
);
2099 FunctionDecl
*FD
= cast
<FunctionDecl
>(D
);
2101 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
2102 if (MD
->getParent()->isLambda()) {
2103 S
.Diag(AL
.getLoc(), diag::err_attribute_dll_lambda
) << AL
;
2108 if (!AL
.checkAtLeastNumArgs(S
, 1))
2111 SmallVector
<IdentifierInfo
*, 8> CPUs
;
2112 for (unsigned ArgNo
= 0; ArgNo
< getNumAttributeArgs(AL
); ++ArgNo
) {
2113 if (!AL
.isArgIdent(ArgNo
)) {
2114 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
2115 << AL
<< AANT_ArgumentIdentifier
;
2119 IdentifierLoc
*CPUArg
= AL
.getArgAsIdent(ArgNo
);
2120 StringRef CPUName
= CPUArg
->Ident
->getName().trim();
2122 if (!S
.Context
.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName
)) {
2123 S
.Diag(CPUArg
->Loc
, diag::err_invalid_cpu_specific_dispatch_value
)
2124 << CPUName
<< (AL
.getKind() == ParsedAttr::AT_CPUDispatch
);
2128 const TargetInfo
&Target
= S
.Context
.getTargetInfo();
2129 if (llvm::any_of(CPUs
, [CPUName
, &Target
](const IdentifierInfo
*Cur
) {
2130 return Target
.CPUSpecificManglingCharacter(CPUName
) ==
2131 Target
.CPUSpecificManglingCharacter(Cur
->getName());
2133 S
.Diag(AL
.getLoc(), diag::warn_multiversion_duplicate_entries
);
2136 CPUs
.push_back(CPUArg
->Ident
);
2139 FD
->setIsMultiVersion(true);
2140 if (AL
.getKind() == ParsedAttr::AT_CPUSpecific
)
2141 D
->addAttr(::new (S
.Context
)
2142 CPUSpecificAttr(S
.Context
, AL
, CPUs
.data(), CPUs
.size()));
2144 D
->addAttr(::new (S
.Context
)
2145 CPUDispatchAttr(S
.Context
, AL
, CPUs
.data(), CPUs
.size()));
2148 static void handleCommonAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2149 if (S
.LangOpts
.CPlusPlus
) {
2150 S
.Diag(AL
.getLoc(), diag::err_attribute_not_supported_in_lang
)
2151 << AL
<< AttributeLangSupport::Cpp
;
2155 D
->addAttr(::new (S
.Context
) CommonAttr(S
.Context
, AL
));
2158 static void handleCmseNSEntryAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2159 if (S
.LangOpts
.CPlusPlus
&& !D
->getDeclContext()->isExternCContext()) {
2160 S
.Diag(AL
.getLoc(), diag::err_attribute_not_clinkage
) << AL
;
2164 const auto *FD
= cast
<FunctionDecl
>(D
);
2165 if (!FD
->isExternallyVisible()) {
2166 S
.Diag(AL
.getLoc(), diag::warn_attribute_cmse_entry_static
);
2170 D
->addAttr(::new (S
.Context
) CmseNSEntryAttr(S
.Context
, AL
));
2173 static void handleNakedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2174 if (AL
.isDeclspecAttribute()) {
2175 const auto &Triple
= S
.getASTContext().getTargetInfo().getTriple();
2176 const auto &Arch
= Triple
.getArch();
2177 if (Arch
!= llvm::Triple::x86
&&
2178 (Arch
!= llvm::Triple::arm
&& Arch
!= llvm::Triple::thumb
)) {
2179 S
.Diag(AL
.getLoc(), diag::err_attribute_not_supported_on_arch
)
2180 << AL
<< Triple
.getArchName();
2184 // This form is not allowed to be written on a member function (static or
2185 // nonstatic) when in Microsoft compatibility mode.
2186 if (S
.getLangOpts().MSVCCompat
&& isa
<CXXMethodDecl
>(D
)) {
2187 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_decl_type_str
)
2188 << AL
<< AL
.isRegularKeywordAttribute() << "non-member functions";
2193 D
->addAttr(::new (S
.Context
) NakedAttr(S
.Context
, AL
));
2196 static void handleNoReturnAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&Attrs
) {
2197 if (hasDeclarator(D
)) return;
2199 if (!isa
<ObjCMethodDecl
>(D
)) {
2200 S
.Diag(Attrs
.getLoc(), diag::warn_attribute_wrong_decl_type
)
2201 << Attrs
<< Attrs
.isRegularKeywordAttribute()
2202 << ExpectedFunctionOrMethod
;
2206 D
->addAttr(::new (S
.Context
) NoReturnAttr(S
.Context
, Attrs
));
2209 static void handleStandardNoReturnAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&A
) {
2210 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2211 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2212 // attribute name comes from a macro expansion. We don't want to punish users
2213 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2214 // is defined as a macro which expands to '_Noreturn').
2215 if (!S
.getLangOpts().CPlusPlus
&&
2216 A
.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn
&&
2217 !(A
.getLoc().isMacroID() &&
2218 S
.getSourceManager().isInSystemMacro(A
.getLoc())))
2219 S
.Diag(A
.getLoc(), diag::warn_deprecated_noreturn_spelling
) << A
.getRange();
2221 D
->addAttr(::new (S
.Context
) CXX11NoReturnAttr(S
.Context
, A
));
2224 static void handleNoCfCheckAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&Attrs
) {
2225 if (!S
.getLangOpts().CFProtectionBranch
)
2226 S
.Diag(Attrs
.getLoc(), diag::warn_nocf_check_attribute_ignored
);
2228 handleSimpleAttribute
<AnyX86NoCfCheckAttr
>(S
, D
, Attrs
);
2231 bool Sema::CheckAttrNoArgs(const ParsedAttr
&Attrs
) {
2232 if (!Attrs
.checkExactlyNumArgs(*this, 0)) {
2240 bool Sema::CheckAttrTarget(const ParsedAttr
&AL
) {
2241 // Check whether the attribute is valid on the current target.
2242 if (!AL
.existsInTarget(Context
.getTargetInfo())) {
2243 Diag(AL
.getLoc(), AL
.isRegularKeywordAttribute()
2244 ? diag::err_keyword_not_supported_on_target
2245 : diag::warn_unknown_attribute_ignored
)
2246 << AL
<< AL
.getRange();
2254 static void handleAnalyzerNoReturnAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2256 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2257 // because 'analyzer_noreturn' does not impact the type.
2258 if (!isFunctionOrMethodOrBlock(D
)) {
2259 ValueDecl
*VD
= dyn_cast
<ValueDecl
>(D
);
2260 if (!VD
|| (!VD
->getType()->isBlockPointerType() &&
2261 !VD
->getType()->isFunctionPointerType())) {
2262 S
.Diag(AL
.getLoc(), AL
.isStandardAttributeSyntax()
2263 ? diag::err_attribute_wrong_decl_type
2264 : diag::warn_attribute_wrong_decl_type
)
2265 << AL
<< AL
.isRegularKeywordAttribute()
2266 << ExpectedFunctionMethodOrBlock
;
2271 D
->addAttr(::new (S
.Context
) AnalyzerNoReturnAttr(S
.Context
, AL
));
2274 // PS3 PPU-specific.
2275 static void handleVecReturnAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2277 Returning a Vector Class in Registers
2279 According to the PPU ABI specifications, a class with a single member of
2280 vector type is returned in memory when used as the return value of a
2282 This results in inefficient code when implementing vector classes. To return
2283 the value in a single vector register, add the vecreturn attribute to the
2284 class definition. This attribute is also applicable to struct types.
2290 __vector float xyzw;
2291 } __attribute__((vecreturn));
2293 Vector Add(Vector lhs, Vector rhs)
2296 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2297 return result; // This will be returned in a register
2300 if (VecReturnAttr
*A
= D
->getAttr
<VecReturnAttr
>()) {
2301 S
.Diag(AL
.getLoc(), diag::err_repeat_attribute
) << A
;
2305 const auto *R
= cast
<RecordDecl
>(D
);
2308 if (!isa
<CXXRecordDecl
>(R
)) {
2309 S
.Diag(AL
.getLoc(), diag::err_attribute_vecreturn_only_vector_member
);
2313 if (!cast
<CXXRecordDecl
>(R
)->isPOD()) {
2314 S
.Diag(AL
.getLoc(), diag::err_attribute_vecreturn_only_pod_record
);
2318 for (const auto *I
: R
->fields()) {
2319 if ((count
== 1) || !I
->getType()->isVectorType()) {
2320 S
.Diag(AL
.getLoc(), diag::err_attribute_vecreturn_only_vector_member
);
2326 D
->addAttr(::new (S
.Context
) VecReturnAttr(S
.Context
, AL
));
2329 static void handleDependencyAttr(Sema
&S
, Scope
*Scope
, Decl
*D
,
2330 const ParsedAttr
&AL
) {
2331 if (isa
<ParmVarDecl
>(D
)) {
2332 // [[carries_dependency]] can only be applied to a parameter if it is a
2333 // parameter of a function declaration or lambda.
2334 if (!(Scope
->getFlags() & clang::Scope::FunctionDeclarationScope
)) {
2336 diag::err_carries_dependency_param_not_function_decl
);
2341 D
->addAttr(::new (S
.Context
) CarriesDependencyAttr(S
.Context
, AL
));
2344 static void handleUnusedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2345 bool IsCXX17Attr
= AL
.isCXX11Attribute() && !AL
.getScopeName();
2347 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2348 // about using it as an extension.
2349 if (!S
.getLangOpts().CPlusPlus17
&& IsCXX17Attr
)
2350 S
.Diag(AL
.getLoc(), diag::ext_cxx17_attr
) << AL
;
2352 D
->addAttr(::new (S
.Context
) UnusedAttr(S
.Context
, AL
));
2355 static void handleConstructorAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2356 uint32_t priority
= ConstructorAttr::DefaultPriority
;
2357 if (S
.getLangOpts().HLSL
&& AL
.getNumArgs()) {
2358 S
.Diag(AL
.getLoc(), diag::err_hlsl_init_priority_unsupported
);
2361 if (AL
.getNumArgs() &&
2362 !checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(0), priority
))
2365 D
->addAttr(::new (S
.Context
) ConstructorAttr(S
.Context
, AL
, priority
));
2368 static void handleDestructorAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2369 uint32_t priority
= DestructorAttr::DefaultPriority
;
2370 if (AL
.getNumArgs() &&
2371 !checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(0), priority
))
2374 D
->addAttr(::new (S
.Context
) DestructorAttr(S
.Context
, AL
, priority
));
2377 template <typename AttrTy
>
2378 static void handleAttrWithMessage(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2379 // Handle the case where the attribute has a text message.
2381 if (AL
.getNumArgs() == 1 && !S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
2384 D
->addAttr(::new (S
.Context
) AttrTy(S
.Context
, AL
, Str
));
2387 static void handleObjCSuppresProtocolAttr(Sema
&S
, Decl
*D
,
2388 const ParsedAttr
&AL
) {
2389 if (!cast
<ObjCProtocolDecl
>(D
)->isThisDeclarationADefinition()) {
2390 S
.Diag(AL
.getLoc(), diag::err_objc_attr_protocol_requires_definition
)
2391 << AL
<< AL
.getRange();
2395 D
->addAttr(::new (S
.Context
) ObjCExplicitProtocolImplAttr(S
.Context
, AL
));
2398 static bool checkAvailabilityAttr(Sema
&S
, SourceRange Range
,
2399 IdentifierInfo
*Platform
,
2400 VersionTuple Introduced
,
2401 VersionTuple Deprecated
,
2402 VersionTuple Obsoleted
) {
2403 StringRef PlatformName
2404 = AvailabilityAttr::getPrettyPlatformName(Platform
->getName());
2405 if (PlatformName
.empty())
2406 PlatformName
= Platform
->getName();
2408 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2409 // of these steps are needed).
2410 if (!Introduced
.empty() && !Deprecated
.empty() &&
2411 !(Introduced
<= Deprecated
)) {
2412 S
.Diag(Range
.getBegin(), diag::warn_availability_version_ordering
)
2413 << 1 << PlatformName
<< Deprecated
.getAsString()
2414 << 0 << Introduced
.getAsString();
2418 if (!Introduced
.empty() && !Obsoleted
.empty() &&
2419 !(Introduced
<= Obsoleted
)) {
2420 S
.Diag(Range
.getBegin(), diag::warn_availability_version_ordering
)
2421 << 2 << PlatformName
<< Obsoleted
.getAsString()
2422 << 0 << Introduced
.getAsString();
2426 if (!Deprecated
.empty() && !Obsoleted
.empty() &&
2427 !(Deprecated
<= Obsoleted
)) {
2428 S
.Diag(Range
.getBegin(), diag::warn_availability_version_ordering
)
2429 << 2 << PlatformName
<< Obsoleted
.getAsString()
2430 << 1 << Deprecated
.getAsString();
2437 /// Check whether the two versions match.
2439 /// If either version tuple is empty, then they are assumed to match. If
2440 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2441 static bool versionsMatch(const VersionTuple
&X
, const VersionTuple
&Y
,
2442 bool BeforeIsOkay
) {
2443 if (X
.empty() || Y
.empty())
2449 if (BeforeIsOkay
&& X
< Y
)
2455 AvailabilityAttr
*Sema::mergeAvailabilityAttr(
2456 NamedDecl
*D
, const AttributeCommonInfo
&CI
, IdentifierInfo
*Platform
,
2457 bool Implicit
, VersionTuple Introduced
, VersionTuple Deprecated
,
2458 VersionTuple Obsoleted
, bool IsUnavailable
, StringRef Message
,
2459 bool IsStrict
, StringRef Replacement
, AvailabilityMergeKind AMK
,
2461 VersionTuple MergedIntroduced
= Introduced
;
2462 VersionTuple MergedDeprecated
= Deprecated
;
2463 VersionTuple MergedObsoleted
= Obsoleted
;
2464 bool FoundAny
= false;
2465 bool OverrideOrImpl
= false;
2468 case AMK_Redeclaration
:
2469 OverrideOrImpl
= false;
2473 case AMK_ProtocolImplementation
:
2474 case AMK_OptionalProtocolImplementation
:
2475 OverrideOrImpl
= true;
2479 if (D
->hasAttrs()) {
2480 AttrVec
&Attrs
= D
->getAttrs();
2481 for (unsigned i
= 0, e
= Attrs
.size(); i
!= e
;) {
2482 const auto *OldAA
= dyn_cast
<AvailabilityAttr
>(Attrs
[i
]);
2488 IdentifierInfo
*OldPlatform
= OldAA
->getPlatform();
2489 if (OldPlatform
!= Platform
) {
2494 // If there is an existing availability attribute for this platform that
2495 // has a lower priority use the existing one and discard the new
2497 if (OldAA
->getPriority() < Priority
)
2500 // If there is an existing attribute for this platform that has a higher
2501 // priority than the new attribute then erase the old one and continue
2502 // processing the attributes.
2503 if (OldAA
->getPriority() > Priority
) {
2504 Attrs
.erase(Attrs
.begin() + i
);
2510 VersionTuple OldIntroduced
= OldAA
->getIntroduced();
2511 VersionTuple OldDeprecated
= OldAA
->getDeprecated();
2512 VersionTuple OldObsoleted
= OldAA
->getObsoleted();
2513 bool OldIsUnavailable
= OldAA
->getUnavailable();
2515 if (!versionsMatch(OldIntroduced
, Introduced
, OverrideOrImpl
) ||
2516 !versionsMatch(Deprecated
, OldDeprecated
, OverrideOrImpl
) ||
2517 !versionsMatch(Obsoleted
, OldObsoleted
, OverrideOrImpl
) ||
2518 !(OldIsUnavailable
== IsUnavailable
||
2519 (OverrideOrImpl
&& !OldIsUnavailable
&& IsUnavailable
))) {
2520 if (OverrideOrImpl
) {
2522 VersionTuple FirstVersion
;
2523 VersionTuple SecondVersion
;
2524 if (!versionsMatch(OldIntroduced
, Introduced
, OverrideOrImpl
)) {
2526 FirstVersion
= OldIntroduced
;
2527 SecondVersion
= Introduced
;
2528 } else if (!versionsMatch(Deprecated
, OldDeprecated
, OverrideOrImpl
)) {
2530 FirstVersion
= Deprecated
;
2531 SecondVersion
= OldDeprecated
;
2532 } else if (!versionsMatch(Obsoleted
, OldObsoleted
, OverrideOrImpl
)) {
2534 FirstVersion
= Obsoleted
;
2535 SecondVersion
= OldObsoleted
;
2539 Diag(OldAA
->getLocation(),
2540 diag::warn_mismatched_availability_override_unavail
)
2541 << AvailabilityAttr::getPrettyPlatformName(Platform
->getName())
2542 << (AMK
== AMK_Override
);
2543 } else if (Which
!= 1 && AMK
== AMK_OptionalProtocolImplementation
) {
2544 // Allow different 'introduced' / 'obsoleted' availability versions
2545 // on a method that implements an optional protocol requirement. It
2546 // makes less sense to allow this for 'deprecated' as the user can't
2547 // see if the method is 'deprecated' as 'respondsToSelector' will
2548 // still return true when the method is deprecated.
2552 Diag(OldAA
->getLocation(),
2553 diag::warn_mismatched_availability_override
)
2555 << AvailabilityAttr::getPrettyPlatformName(Platform
->getName())
2556 << FirstVersion
.getAsString() << SecondVersion
.getAsString()
2557 << (AMK
== AMK_Override
);
2559 if (AMK
== AMK_Override
)
2560 Diag(CI
.getLoc(), diag::note_overridden_method
);
2562 Diag(CI
.getLoc(), diag::note_protocol_method
);
2564 Diag(OldAA
->getLocation(), diag::warn_mismatched_availability
);
2565 Diag(CI
.getLoc(), diag::note_previous_attribute
);
2568 Attrs
.erase(Attrs
.begin() + i
);
2573 VersionTuple MergedIntroduced2
= MergedIntroduced
;
2574 VersionTuple MergedDeprecated2
= MergedDeprecated
;
2575 VersionTuple MergedObsoleted2
= MergedObsoleted
;
2577 if (MergedIntroduced2
.empty())
2578 MergedIntroduced2
= OldIntroduced
;
2579 if (MergedDeprecated2
.empty())
2580 MergedDeprecated2
= OldDeprecated
;
2581 if (MergedObsoleted2
.empty())
2582 MergedObsoleted2
= OldObsoleted
;
2584 if (checkAvailabilityAttr(*this, OldAA
->getRange(), Platform
,
2585 MergedIntroduced2
, MergedDeprecated2
,
2586 MergedObsoleted2
)) {
2587 Attrs
.erase(Attrs
.begin() + i
);
2592 MergedIntroduced
= MergedIntroduced2
;
2593 MergedDeprecated
= MergedDeprecated2
;
2594 MergedObsoleted
= MergedObsoleted2
;
2600 MergedIntroduced
== Introduced
&&
2601 MergedDeprecated
== Deprecated
&&
2602 MergedObsoleted
== Obsoleted
)
2605 // Only create a new attribute if !OverrideOrImpl, but we want to do
2607 if (!checkAvailabilityAttr(*this, CI
.getRange(), Platform
, MergedIntroduced
,
2608 MergedDeprecated
, MergedObsoleted
) &&
2610 auto *Avail
= ::new (Context
) AvailabilityAttr(
2611 Context
, CI
, Platform
, Introduced
, Deprecated
, Obsoleted
, IsUnavailable
,
2612 Message
, IsStrict
, Replacement
, Priority
);
2613 Avail
->setImplicit(Implicit
);
2619 static void handleAvailabilityAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2620 if (isa
<UsingDecl
, UnresolvedUsingTypenameDecl
, UnresolvedUsingValueDecl
>(
2622 S
.Diag(AL
.getRange().getBegin(), diag::warn_deprecated_ignored_on_using
)
2627 if (!AL
.checkExactlyNumArgs(S
, 1))
2629 IdentifierLoc
*Platform
= AL
.getArgAsIdent(0);
2631 IdentifierInfo
*II
= Platform
->Ident
;
2632 if (AvailabilityAttr::getPrettyPlatformName(II
->getName()).empty())
2633 S
.Diag(Platform
->Loc
, diag::warn_availability_unknown_platform
)
2636 auto *ND
= dyn_cast
<NamedDecl
>(D
);
2637 if (!ND
) // We warned about this already, so just return.
2640 AvailabilityChange Introduced
= AL
.getAvailabilityIntroduced();
2641 AvailabilityChange Deprecated
= AL
.getAvailabilityDeprecated();
2642 AvailabilityChange Obsoleted
= AL
.getAvailabilityObsoleted();
2643 bool IsUnavailable
= AL
.getUnavailableLoc().isValid();
2644 bool IsStrict
= AL
.getStrictLoc().isValid();
2646 if (const auto *SE
= dyn_cast_if_present
<StringLiteral
>(AL
.getMessageExpr()))
2647 Str
= SE
->getString();
2648 StringRef Replacement
;
2649 if (const auto *SE
=
2650 dyn_cast_if_present
<StringLiteral
>(AL
.getReplacementExpr()))
2651 Replacement
= SE
->getString();
2653 if (II
->isStr("swift")) {
2654 if (Introduced
.isValid() || Obsoleted
.isValid() ||
2655 (!IsUnavailable
&& !Deprecated
.isValid())) {
2657 diag::warn_availability_swift_unavailable_deprecated_only
);
2662 if (II
->isStr("fuchsia")) {
2663 std::optional
<unsigned> Min
, Sub
;
2664 if ((Min
= Introduced
.Version
.getMinor()) ||
2665 (Sub
= Introduced
.Version
.getSubminor())) {
2666 S
.Diag(AL
.getLoc(), diag::warn_availability_fuchsia_unavailable_minor
);
2671 int PriorityModifier
= AL
.isPragmaClangAttribute()
2672 ? Sema::AP_PragmaClangAttribute
2673 : Sema::AP_Explicit
;
2674 AvailabilityAttr
*NewAttr
= S
.mergeAvailabilityAttr(
2675 ND
, AL
, II
, false /*Implicit*/, Introduced
.Version
, Deprecated
.Version
,
2676 Obsoleted
.Version
, IsUnavailable
, Str
, IsStrict
, Replacement
,
2677 Sema::AMK_None
, PriorityModifier
);
2679 D
->addAttr(NewAttr
);
2681 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2682 // matches before the start of the watchOS platform.
2683 if (S
.Context
.getTargetInfo().getTriple().isWatchOS()) {
2684 IdentifierInfo
*NewII
= nullptr;
2685 if (II
->getName() == "ios")
2686 NewII
= &S
.Context
.Idents
.get("watchos");
2687 else if (II
->getName() == "ios_app_extension")
2688 NewII
= &S
.Context
.Idents
.get("watchos_app_extension");
2691 const auto *SDKInfo
= S
.getDarwinSDKInfoForAvailabilityChecking();
2692 const auto *IOSToWatchOSMapping
=
2693 SDKInfo
? SDKInfo
->getVersionMapping(
2694 DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
2697 auto adjustWatchOSVersion
=
2698 [IOSToWatchOSMapping
](VersionTuple Version
) -> VersionTuple
{
2699 if (Version
.empty())
2701 auto MinimumWatchOSVersion
= VersionTuple(2, 0);
2703 if (IOSToWatchOSMapping
) {
2704 if (auto MappedVersion
= IOSToWatchOSMapping
->map(
2705 Version
, MinimumWatchOSVersion
, std::nullopt
)) {
2706 return *MappedVersion
;
2710 auto Major
= Version
.getMajor();
2711 auto NewMajor
= Major
>= 9 ? Major
- 7 : 0;
2712 if (NewMajor
>= 2) {
2713 if (Version
.getMinor()) {
2714 if (Version
.getSubminor())
2715 return VersionTuple(NewMajor
, *Version
.getMinor(),
2716 *Version
.getSubminor());
2718 return VersionTuple(NewMajor
, *Version
.getMinor());
2720 return VersionTuple(NewMajor
);
2723 return MinimumWatchOSVersion
;
2726 auto NewIntroduced
= adjustWatchOSVersion(Introduced
.Version
);
2727 auto NewDeprecated
= adjustWatchOSVersion(Deprecated
.Version
);
2728 auto NewObsoleted
= adjustWatchOSVersion(Obsoleted
.Version
);
2730 AvailabilityAttr
*NewAttr
= S
.mergeAvailabilityAttr(
2731 ND
, AL
, NewII
, true /*Implicit*/, NewIntroduced
, NewDeprecated
,
2732 NewObsoleted
, IsUnavailable
, Str
, IsStrict
, Replacement
,
2734 PriorityModifier
+ Sema::AP_InferredFromOtherPlatform
);
2736 D
->addAttr(NewAttr
);
2738 } else if (S
.Context
.getTargetInfo().getTriple().isTvOS()) {
2739 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2740 // matches before the start of the tvOS platform.
2741 IdentifierInfo
*NewII
= nullptr;
2742 if (II
->getName() == "ios")
2743 NewII
= &S
.Context
.Idents
.get("tvos");
2744 else if (II
->getName() == "ios_app_extension")
2745 NewII
= &S
.Context
.Idents
.get("tvos_app_extension");
2748 const auto *SDKInfo
= S
.getDarwinSDKInfoForAvailabilityChecking();
2749 const auto *IOSToTvOSMapping
=
2750 SDKInfo
? SDKInfo
->getVersionMapping(
2751 DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
2754 auto AdjustTvOSVersion
=
2755 [IOSToTvOSMapping
](VersionTuple Version
) -> VersionTuple
{
2756 if (Version
.empty())
2759 if (IOSToTvOSMapping
) {
2760 if (auto MappedVersion
= IOSToTvOSMapping
->map(
2761 Version
, VersionTuple(0, 0), std::nullopt
)) {
2762 return *MappedVersion
;
2768 auto NewIntroduced
= AdjustTvOSVersion(Introduced
.Version
);
2769 auto NewDeprecated
= AdjustTvOSVersion(Deprecated
.Version
);
2770 auto NewObsoleted
= AdjustTvOSVersion(Obsoleted
.Version
);
2772 AvailabilityAttr
*NewAttr
= S
.mergeAvailabilityAttr(
2773 ND
, AL
, NewII
, true /*Implicit*/, NewIntroduced
, NewDeprecated
,
2774 NewObsoleted
, IsUnavailable
, Str
, IsStrict
, Replacement
,
2776 PriorityModifier
+ Sema::AP_InferredFromOtherPlatform
);
2778 D
->addAttr(NewAttr
);
2780 } else if (S
.Context
.getTargetInfo().getTriple().getOS() ==
2781 llvm::Triple::IOS
&&
2782 S
.Context
.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2783 auto GetSDKInfo
= [&]() {
2784 return S
.getDarwinSDKInfoForAvailabilityChecking(AL
.getRange().getBegin(),
2788 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2789 IdentifierInfo
*NewII
= nullptr;
2790 if (II
->getName() == "ios")
2791 NewII
= &S
.Context
.Idents
.get("maccatalyst");
2792 else if (II
->getName() == "ios_app_extension")
2793 NewII
= &S
.Context
.Idents
.get("maccatalyst_app_extension");
2795 auto MinMacCatalystVersion
= [](const VersionTuple
&V
) {
2798 if (V
.getMajor() < 13 ||
2799 (V
.getMajor() == 13 && V
.getMinor() && *V
.getMinor() < 1))
2800 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2803 AvailabilityAttr
*NewAttr
= S
.mergeAvailabilityAttr(
2804 ND
, AL
, NewII
, true /*Implicit*/,
2805 MinMacCatalystVersion(Introduced
.Version
),
2806 MinMacCatalystVersion(Deprecated
.Version
),
2807 MinMacCatalystVersion(Obsoleted
.Version
), IsUnavailable
, Str
,
2808 IsStrict
, Replacement
, Sema::AMK_None
,
2809 PriorityModifier
+ Sema::AP_InferredFromOtherPlatform
);
2811 D
->addAttr(NewAttr
);
2812 } else if (II
->getName() == "macos" && GetSDKInfo() &&
2813 (!Introduced
.Version
.empty() || !Deprecated
.Version
.empty() ||
2814 !Obsoleted
.Version
.empty())) {
2815 if (const auto *MacOStoMacCatalystMapping
=
2816 GetSDKInfo()->getVersionMapping(
2817 DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2818 // Infer Mac Catalyst availability from the macOS availability attribute
2819 // if it has versioned availability. Don't infer 'unavailable'. This
2820 // inferred availability has lower priority than the other availability
2821 // attributes that are inferred from 'ios'.
2822 NewII
= &S
.Context
.Idents
.get("maccatalyst");
2823 auto RemapMacOSVersion
=
2824 [&](const VersionTuple
&V
) -> std::optional
<VersionTuple
> {
2826 return std::nullopt
;
2827 // API_TO_BE_DEPRECATED is 100000.
2828 if (V
.getMajor() == 100000)
2829 return VersionTuple(100000);
2830 // The minimum iosmac version is 13.1
2831 return MacOStoMacCatalystMapping
->map(V
, VersionTuple(13, 1),
2834 std::optional
<VersionTuple
> NewIntroduced
=
2835 RemapMacOSVersion(Introduced
.Version
),
2837 RemapMacOSVersion(Deprecated
.Version
),
2839 RemapMacOSVersion(Obsoleted
.Version
);
2840 if (NewIntroduced
|| NewDeprecated
|| NewObsoleted
) {
2841 auto VersionOrEmptyVersion
=
2842 [](const std::optional
<VersionTuple
> &V
) -> VersionTuple
{
2843 return V
? *V
: VersionTuple();
2845 AvailabilityAttr
*NewAttr
= S
.mergeAvailabilityAttr(
2846 ND
, AL
, NewII
, true /*Implicit*/,
2847 VersionOrEmptyVersion(NewIntroduced
),
2848 VersionOrEmptyVersion(NewDeprecated
),
2849 VersionOrEmptyVersion(NewObsoleted
), /*IsUnavailable=*/false, Str
,
2850 IsStrict
, Replacement
, Sema::AMK_None
,
2851 PriorityModifier
+ Sema::AP_InferredFromOtherPlatform
+
2852 Sema::AP_InferredFromOtherPlatform
);
2854 D
->addAttr(NewAttr
);
2861 static void handleExternalSourceSymbolAttr(Sema
&S
, Decl
*D
,
2862 const ParsedAttr
&AL
) {
2863 if (!AL
.checkAtLeastNumArgs(S
, 1) || !AL
.checkAtMostNumArgs(S
, 4))
2867 if (const auto *SE
= dyn_cast_if_present
<StringLiteral
>(AL
.getArgAsExpr(0)))
2868 Language
= SE
->getString();
2869 StringRef DefinedIn
;
2870 if (const auto *SE
= dyn_cast_if_present
<StringLiteral
>(AL
.getArgAsExpr(1)))
2871 DefinedIn
= SE
->getString();
2872 bool IsGeneratedDeclaration
= AL
.getArgAsIdent(2) != nullptr;
2874 if (const auto *SE
= dyn_cast_if_present
<StringLiteral
>(AL
.getArgAsExpr(3)))
2875 USR
= SE
->getString();
2877 D
->addAttr(::new (S
.Context
) ExternalSourceSymbolAttr(
2878 S
.Context
, AL
, Language
, DefinedIn
, IsGeneratedDeclaration
, USR
));
2882 static T
*mergeVisibilityAttr(Sema
&S
, Decl
*D
, const AttributeCommonInfo
&CI
,
2883 typename
T::VisibilityType value
) {
2884 T
*existingAttr
= D
->getAttr
<T
>();
2886 typename
T::VisibilityType existingValue
= existingAttr
->getVisibility();
2887 if (existingValue
== value
)
2889 S
.Diag(existingAttr
->getLocation(), diag::err_mismatched_visibility
);
2890 S
.Diag(CI
.getLoc(), diag::note_previous_attribute
);
2893 return ::new (S
.Context
) T(S
.Context
, CI
, value
);
2896 VisibilityAttr
*Sema::mergeVisibilityAttr(Decl
*D
,
2897 const AttributeCommonInfo
&CI
,
2898 VisibilityAttr::VisibilityType Vis
) {
2899 return ::mergeVisibilityAttr
<VisibilityAttr
>(*this, D
, CI
, Vis
);
2902 TypeVisibilityAttr
*
2903 Sema::mergeTypeVisibilityAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
2904 TypeVisibilityAttr::VisibilityType Vis
) {
2905 return ::mergeVisibilityAttr
<TypeVisibilityAttr
>(*this, D
, CI
, Vis
);
2908 static void handleVisibilityAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
,
2909 bool isTypeVisibility
) {
2910 // Visibility attributes don't mean anything on a typedef.
2911 if (isa
<TypedefNameDecl
>(D
)) {
2912 S
.Diag(AL
.getRange().getBegin(), diag::warn_attribute_ignored
) << AL
;
2916 // 'type_visibility' can only go on a type or namespace.
2917 if (isTypeVisibility
&& !(isa
<TagDecl
>(D
) || isa
<ObjCInterfaceDecl
>(D
) ||
2918 isa
<NamespaceDecl
>(D
))) {
2919 S
.Diag(AL
.getRange().getBegin(), diag::err_attribute_wrong_decl_type
)
2920 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedTypeOrNamespace
;
2924 // Check that the argument is a string literal.
2926 SourceLocation LiteralLoc
;
2927 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, TypeStr
, &LiteralLoc
))
2930 VisibilityAttr::VisibilityType type
;
2931 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr
, type
)) {
2932 S
.Diag(LiteralLoc
, diag::warn_attribute_type_not_supported
) << AL
2937 // Complain about attempts to use protected visibility on targets
2938 // (like Darwin) that don't support it.
2939 if (type
== VisibilityAttr::Protected
&&
2940 !S
.Context
.getTargetInfo().hasProtectedVisibility()) {
2941 S
.Diag(AL
.getLoc(), diag::warn_attribute_protected_visibility
);
2942 type
= VisibilityAttr::Default
;
2946 if (isTypeVisibility
) {
2947 newAttr
= S
.mergeTypeVisibilityAttr(
2948 D
, AL
, (TypeVisibilityAttr::VisibilityType
)type
);
2950 newAttr
= S
.mergeVisibilityAttr(D
, AL
, type
);
2953 D
->addAttr(newAttr
);
2956 static void handleObjCDirectAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2957 // objc_direct cannot be set on methods declared in the context of a protocol
2958 if (isa
<ObjCProtocolDecl
>(D
->getDeclContext())) {
2959 S
.Diag(AL
.getLoc(), diag::err_objc_direct_on_protocol
) << false;
2963 if (S
.getLangOpts().ObjCRuntime
.allowsDirectDispatch()) {
2964 handleSimpleAttribute
<ObjCDirectAttr
>(S
, D
, AL
);
2966 S
.Diag(AL
.getLoc(), diag::warn_objc_direct_ignored
) << AL
;
2970 static void handleObjCDirectMembersAttr(Sema
&S
, Decl
*D
,
2971 const ParsedAttr
&AL
) {
2972 if (S
.getLangOpts().ObjCRuntime
.allowsDirectDispatch()) {
2973 handleSimpleAttribute
<ObjCDirectMembersAttr
>(S
, D
, AL
);
2975 S
.Diag(AL
.getLoc(), diag::warn_objc_direct_ignored
) << AL
;
2979 static void handleObjCMethodFamilyAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
2980 const auto *M
= cast
<ObjCMethodDecl
>(D
);
2981 if (!AL
.isArgIdent(0)) {
2982 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
2983 << AL
<< 1 << AANT_ArgumentIdentifier
;
2987 IdentifierLoc
*IL
= AL
.getArgAsIdent(0);
2988 ObjCMethodFamilyAttr::FamilyKind F
;
2989 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL
->Ident
->getName(), F
)) {
2990 S
.Diag(IL
->Loc
, diag::warn_attribute_type_not_supported
) << AL
<< IL
->Ident
;
2994 if (F
== ObjCMethodFamilyAttr::OMF_init
&&
2995 !M
->getReturnType()->isObjCObjectPointerType()) {
2996 S
.Diag(M
->getLocation(), diag::err_init_method_bad_return_type
)
2997 << M
->getReturnType();
2998 // Ignore the attribute.
3002 D
->addAttr(new (S
.Context
) ObjCMethodFamilyAttr(S
.Context
, AL
, F
));
3005 static void handleObjCNSObject(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3006 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
3007 QualType T
= TD
->getUnderlyingType();
3008 if (!T
->isCARCBridgableType()) {
3009 S
.Diag(TD
->getLocation(), diag::err_nsobject_attribute
);
3013 else if (const auto *PD
= dyn_cast
<ObjCPropertyDecl
>(D
)) {
3014 QualType T
= PD
->getType();
3015 if (!T
->isCARCBridgableType()) {
3016 S
.Diag(PD
->getLocation(), diag::err_nsobject_attribute
);
3021 // It is okay to include this attribute on properties, e.g.:
3023 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
3025 // In this case it follows tradition and suppresses an error in the above
3027 S
.Diag(D
->getLocation(), diag::warn_nsobject_attribute
);
3029 D
->addAttr(::new (S
.Context
) ObjCNSObjectAttr(S
.Context
, AL
));
3032 static void handleObjCIndependentClass(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3033 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
3034 QualType T
= TD
->getUnderlyingType();
3035 if (!T
->isObjCObjectPointerType()) {
3036 S
.Diag(TD
->getLocation(), diag::warn_ptr_independentclass_attribute
);
3040 S
.Diag(D
->getLocation(), diag::warn_independentclass_attribute
);
3043 D
->addAttr(::new (S
.Context
) ObjCIndependentClassAttr(S
.Context
, AL
));
3046 static void handleBlocksAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3047 if (!AL
.isArgIdent(0)) {
3048 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
3049 << AL
<< 1 << AANT_ArgumentIdentifier
;
3053 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
3054 BlocksAttr::BlockType type
;
3055 if (!BlocksAttr::ConvertStrToBlockType(II
->getName(), type
)) {
3056 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< II
;
3060 D
->addAttr(::new (S
.Context
) BlocksAttr(S
.Context
, AL
, type
));
3063 static void handleSentinelAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3064 unsigned sentinel
= (unsigned)SentinelAttr::DefaultSentinel
;
3065 if (AL
.getNumArgs() > 0) {
3066 Expr
*E
= AL
.getArgAsExpr(0);
3067 std::optional
<llvm::APSInt
> Idx
= llvm::APSInt(32);
3068 if (E
->isTypeDependent() || !(Idx
= E
->getIntegerConstantExpr(S
.Context
))) {
3069 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
3070 << AL
<< 1 << AANT_ArgumentIntegerConstant
<< E
->getSourceRange();
3074 if (Idx
->isSigned() && Idx
->isNegative()) {
3075 S
.Diag(AL
.getLoc(), diag::err_attribute_sentinel_less_than_zero
)
3076 << E
->getSourceRange();
3080 sentinel
= Idx
->getZExtValue();
3083 unsigned nullPos
= (unsigned)SentinelAttr::DefaultNullPos
;
3084 if (AL
.getNumArgs() > 1) {
3085 Expr
*E
= AL
.getArgAsExpr(1);
3086 std::optional
<llvm::APSInt
> Idx
= llvm::APSInt(32);
3087 if (E
->isTypeDependent() || !(Idx
= E
->getIntegerConstantExpr(S
.Context
))) {
3088 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
3089 << AL
<< 2 << AANT_ArgumentIntegerConstant
<< E
->getSourceRange();
3092 nullPos
= Idx
->getZExtValue();
3094 if ((Idx
->isSigned() && Idx
->isNegative()) || nullPos
> 1) {
3095 // FIXME: This error message could be improved, it would be nice
3096 // to say what the bounds actually are.
3097 S
.Diag(AL
.getLoc(), diag::err_attribute_sentinel_not_zero_or_one
)
3098 << E
->getSourceRange();
3103 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
3104 const FunctionType
*FT
= FD
->getType()->castAs
<FunctionType
>();
3105 if (isa
<FunctionNoProtoType
>(FT
)) {
3106 S
.Diag(AL
.getLoc(), diag::warn_attribute_sentinel_named_arguments
);
3110 if (!cast
<FunctionProtoType
>(FT
)->isVariadic()) {
3111 S
.Diag(AL
.getLoc(), diag::warn_attribute_sentinel_not_variadic
) << 0;
3114 } else if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
3115 if (!MD
->isVariadic()) {
3116 S
.Diag(AL
.getLoc(), diag::warn_attribute_sentinel_not_variadic
) << 0;
3119 } else if (const auto *BD
= dyn_cast
<BlockDecl
>(D
)) {
3120 if (!BD
->isVariadic()) {
3121 S
.Diag(AL
.getLoc(), diag::warn_attribute_sentinel_not_variadic
) << 1;
3124 } else if (const auto *V
= dyn_cast
<VarDecl
>(D
)) {
3125 QualType Ty
= V
->getType();
3126 if (Ty
->isBlockPointerType() || Ty
->isFunctionPointerType()) {
3127 const FunctionType
*FT
= Ty
->isFunctionPointerType()
3128 ? D
->getFunctionType()
3129 : Ty
->castAs
<BlockPointerType
>()
3131 ->castAs
<FunctionType
>();
3132 if (!cast
<FunctionProtoType
>(FT
)->isVariadic()) {
3133 int m
= Ty
->isFunctionPointerType() ? 0 : 1;
3134 S
.Diag(AL
.getLoc(), diag::warn_attribute_sentinel_not_variadic
) << m
;
3138 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
3139 << AL
<< AL
.isRegularKeywordAttribute()
3140 << ExpectedFunctionMethodOrBlock
;
3144 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
3145 << AL
<< AL
.isRegularKeywordAttribute()
3146 << ExpectedFunctionMethodOrBlock
;
3149 D
->addAttr(::new (S
.Context
) SentinelAttr(S
.Context
, AL
, sentinel
, nullPos
));
3152 static void handleWarnUnusedResult(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3153 if (D
->getFunctionType() &&
3154 D
->getFunctionType()->getReturnType()->isVoidType() &&
3155 !isa
<CXXConstructorDecl
>(D
)) {
3156 S
.Diag(AL
.getLoc(), diag::warn_attribute_void_function_method
) << AL
<< 0;
3159 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
3160 if (MD
->getReturnType()->isVoidType()) {
3161 S
.Diag(AL
.getLoc(), diag::warn_attribute_void_function_method
) << AL
<< 1;
3166 if (AL
.isStandardAttributeSyntax() && !AL
.getScopeName()) {
3167 // The standard attribute cannot be applied to variable declarations such
3168 // as a function pointer.
3169 if (isa
<VarDecl
>(D
))
3170 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type_str
)
3171 << AL
<< AL
.isRegularKeywordAttribute()
3172 << "functions, classes, or enumerations";
3174 // If this is spelled as the standard C++17 attribute, but not in C++17,
3175 // warn about using it as an extension. If there are attribute arguments,
3176 // then claim it's a C++20 extension instead.
3177 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3178 // extension warning for C23 mode.
3179 const LangOptions
&LO
= S
.getLangOpts();
3180 if (AL
.getNumArgs() == 1) {
3181 if (LO
.CPlusPlus
&& !LO
.CPlusPlus20
)
3182 S
.Diag(AL
.getLoc(), diag::ext_cxx20_attr
) << AL
;
3184 // Since this is spelled [[nodiscard]], get the optional string
3185 // literal. If in C++ mode, but not in C++20 mode, diagnose as an
3187 // FIXME: C23 should support this feature as well, even as an extension.
3188 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, nullptr))
3190 } else if (LO
.CPlusPlus
&& !LO
.CPlusPlus17
)
3191 S
.Diag(AL
.getLoc(), diag::ext_cxx17_attr
) << AL
;
3194 if ((!AL
.isGNUAttribute() &&
3195 !(AL
.isStandardAttributeSyntax() && AL
.isClangScope())) &&
3196 isa
<TypedefNameDecl
>(D
)) {
3197 S
.Diag(AL
.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling
)
3202 D
->addAttr(::new (S
.Context
) WarnUnusedResultAttr(S
.Context
, AL
, Str
));
3205 static void handleWeakImportAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3206 // weak_import only applies to variable & function declarations.
3208 if (!D
->canBeWeakImported(isDef
)) {
3210 S
.Diag(AL
.getLoc(), diag::warn_attribute_invalid_on_definition
)
3212 else if (isa
<ObjCPropertyDecl
>(D
) || isa
<ObjCMethodDecl
>(D
) ||
3213 (S
.Context
.getTargetInfo().getTriple().isOSDarwin() &&
3214 (isa
<ObjCInterfaceDecl
>(D
) || isa
<EnumDecl
>(D
)))) {
3215 // Nothing to warn about here.
3217 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
3218 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedVariableOrFunction
;
3223 D
->addAttr(::new (S
.Context
) WeakImportAttr(S
.Context
, AL
));
3226 // Handles reqd_work_group_size and work_group_size_hint.
3227 template <typename WorkGroupAttr
>
3228 static void handleWorkGroupSize(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3230 for (unsigned i
= 0; i
< 3; ++i
) {
3231 const Expr
*E
= AL
.getArgAsExpr(i
);
3232 if (!checkUInt32Argument(S
, AL
, E
, WGSize
[i
], i
,
3233 /*StrictlyUnsigned=*/true))
3235 if (WGSize
[i
] == 0) {
3236 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_is_zero
)
3237 << AL
<< E
->getSourceRange();
3242 WorkGroupAttr
*Existing
= D
->getAttr
<WorkGroupAttr
>();
3243 if (Existing
&& !(Existing
->getXDim() == WGSize
[0] &&
3244 Existing
->getYDim() == WGSize
[1] &&
3245 Existing
->getZDim() == WGSize
[2]))
3246 S
.Diag(AL
.getLoc(), diag::warn_duplicate_attribute
) << AL
;
3248 D
->addAttr(::new (S
.Context
)
3249 WorkGroupAttr(S
.Context
, AL
, WGSize
[0], WGSize
[1], WGSize
[2]));
3252 // Handles intel_reqd_sub_group_size.
3253 static void handleSubGroupSize(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3255 const Expr
*E
= AL
.getArgAsExpr(0);
3256 if (!checkUInt32Argument(S
, AL
, E
, SGSize
))
3259 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_is_zero
)
3260 << AL
<< E
->getSourceRange();
3264 OpenCLIntelReqdSubGroupSizeAttr
*Existing
=
3265 D
->getAttr
<OpenCLIntelReqdSubGroupSizeAttr
>();
3266 if (Existing
&& Existing
->getSubGroupSize() != SGSize
)
3267 S
.Diag(AL
.getLoc(), diag::warn_duplicate_attribute
) << AL
;
3269 D
->addAttr(::new (S
.Context
)
3270 OpenCLIntelReqdSubGroupSizeAttr(S
.Context
, AL
, SGSize
));
3273 static void handleVecTypeHint(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3274 if (!AL
.hasParsedType()) {
3275 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
) << AL
<< 1;
3279 TypeSourceInfo
*ParmTSI
= nullptr;
3280 QualType ParmType
= S
.GetTypeFromParser(AL
.getTypeArg(), &ParmTSI
);
3281 assert(ParmTSI
&& "no type source info for attribute argument");
3283 if (!ParmType
->isExtVectorType() && !ParmType
->isFloatingType() &&
3284 (ParmType
->isBooleanType() ||
3285 !ParmType
->isIntegralType(S
.getASTContext()))) {
3286 S
.Diag(AL
.getLoc(), diag::err_attribute_invalid_argument
) << 2 << AL
;
3290 if (VecTypeHintAttr
*A
= D
->getAttr
<VecTypeHintAttr
>()) {
3291 if (!S
.Context
.hasSameType(A
->getTypeHint(), ParmType
)) {
3292 S
.Diag(AL
.getLoc(), diag::warn_duplicate_attribute
) << AL
;
3297 D
->addAttr(::new (S
.Context
) VecTypeHintAttr(S
.Context
, AL
, ParmTSI
));
3300 SectionAttr
*Sema::mergeSectionAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
3302 // Explicit or partial specializations do not inherit
3303 // the section attribute from the primary template.
3304 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
3305 if (CI
.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate
&&
3306 FD
->isFunctionTemplateSpecialization())
3309 if (SectionAttr
*ExistingAttr
= D
->getAttr
<SectionAttr
>()) {
3310 if (ExistingAttr
->getName() == Name
)
3312 Diag(ExistingAttr
->getLocation(), diag::warn_mismatched_section
)
3314 Diag(CI
.getLoc(), diag::note_previous_attribute
);
3317 return ::new (Context
) SectionAttr(Context
, CI
, Name
);
3320 /// Used to implement to perform semantic checking on
3321 /// attribute((section("foo"))) specifiers.
3323 /// In this case, "foo" is passed in to be checked. If the section
3324 /// specifier is invalid, return an Error that indicates the problem.
3326 /// This is a simple quality of implementation feature to catch errors
3327 /// and give good diagnostics in cases when the assembler or code generator
3328 /// would otherwise reject the section specifier.
3329 llvm::Error
Sema::isValidSectionSpecifier(StringRef SecName
) {
3330 if (!Context
.getTargetInfo().getTriple().isOSDarwin())
3331 return llvm::Error::success();
3333 // Let MCSectionMachO validate this.
3334 StringRef Segment
, Section
;
3335 unsigned TAA
, StubSize
;
3337 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName
, Segment
, Section
,
3338 TAA
, HasTAA
, StubSize
);
3341 bool Sema::checkSectionName(SourceLocation LiteralLoc
, StringRef SecName
) {
3342 if (llvm::Error E
= isValidSectionSpecifier(SecName
)) {
3343 Diag(LiteralLoc
, diag::err_attribute_section_invalid_for_target
)
3344 << toString(std::move(E
)) << 1 /*'section'*/;
3350 static void handleSectionAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3351 // Make sure that there is a string literal as the sections's single
3354 SourceLocation LiteralLoc
;
3355 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &LiteralLoc
))
3358 if (!S
.checkSectionName(LiteralLoc
, Str
))
3361 SectionAttr
*NewAttr
= S
.mergeSectionAttr(D
, AL
, Str
);
3363 D
->addAttr(NewAttr
);
3364 if (isa
<FunctionDecl
, FunctionTemplateDecl
, ObjCMethodDecl
,
3365 ObjCPropertyDecl
>(D
))
3366 S
.UnifySection(NewAttr
->getName(),
3367 ASTContext::PSF_Execute
| ASTContext::PSF_Read
,
3368 cast
<NamedDecl
>(D
));
3372 // This is used for `__declspec(code_seg("segname"))` on a decl.
3373 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3374 static bool checkCodeSegName(Sema
&S
, SourceLocation LiteralLoc
,
3375 StringRef CodeSegName
) {
3376 if (llvm::Error E
= S
.isValidSectionSpecifier(CodeSegName
)) {
3377 S
.Diag(LiteralLoc
, diag::err_attribute_section_invalid_for_target
)
3378 << toString(std::move(E
)) << 0 /*'code-seg'*/;
3385 CodeSegAttr
*Sema::mergeCodeSegAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
3387 // Explicit or partial specializations do not inherit
3388 // the code_seg attribute from the primary template.
3389 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
3390 if (FD
->isFunctionTemplateSpecialization())
3393 if (const auto *ExistingAttr
= D
->getAttr
<CodeSegAttr
>()) {
3394 if (ExistingAttr
->getName() == Name
)
3396 Diag(ExistingAttr
->getLocation(), diag::warn_mismatched_section
)
3398 Diag(CI
.getLoc(), diag::note_previous_attribute
);
3401 return ::new (Context
) CodeSegAttr(Context
, CI
, Name
);
3404 static void handleCodeSegAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3406 SourceLocation LiteralLoc
;
3407 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &LiteralLoc
))
3409 if (!checkCodeSegName(S
, LiteralLoc
, Str
))
3411 if (const auto *ExistingAttr
= D
->getAttr
<CodeSegAttr
>()) {
3412 if (!ExistingAttr
->isImplicit()) {
3414 ExistingAttr
->getName() == Str
3415 ? diag::warn_duplicate_codeseg_attribute
3416 : diag::err_conflicting_codeseg_attribute
);
3419 D
->dropAttr
<CodeSegAttr
>();
3421 if (CodeSegAttr
*CSA
= S
.mergeCodeSegAttr(D
, AL
, Str
))
3425 // Check for things we'd like to warn about. Multiversioning issues are
3426 // handled later in the process, once we know how many exist.
3427 bool Sema::checkTargetAttr(SourceLocation LiteralLoc
, StringRef AttrStr
) {
3428 enum FirstParam
{ Unsupported
, Duplicate
, Unknown
};
3429 enum SecondParam
{ None
, CPU
, Tune
};
3430 enum ThirdParam
{ Target
, TargetClones
};
3431 if (AttrStr
.contains("fpmath="))
3432 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3433 << Unsupported
<< None
<< "fpmath=" << Target
;
3435 // Diagnose use of tune if target doesn't support it.
3436 if (!Context
.getTargetInfo().supportsTargetAttributeTune() &&
3437 AttrStr
.contains("tune="))
3438 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3439 << Unsupported
<< None
<< "tune=" << Target
;
3441 ParsedTargetAttr ParsedAttrs
=
3442 Context
.getTargetInfo().parseTargetAttr(AttrStr
);
3444 if (!ParsedAttrs
.CPU
.empty() &&
3445 !Context
.getTargetInfo().isValidCPUName(ParsedAttrs
.CPU
))
3446 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3447 << Unknown
<< CPU
<< ParsedAttrs
.CPU
<< Target
;
3449 if (!ParsedAttrs
.Tune
.empty() &&
3450 !Context
.getTargetInfo().isValidCPUName(ParsedAttrs
.Tune
))
3451 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3452 << Unknown
<< Tune
<< ParsedAttrs
.Tune
<< Target
;
3454 if (ParsedAttrs
.Duplicate
!= "")
3455 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3456 << Duplicate
<< None
<< ParsedAttrs
.Duplicate
<< Target
;
3458 for (const auto &Feature
: ParsedAttrs
.Features
) {
3459 auto CurFeature
= StringRef(Feature
).drop_front(); // remove + or -.
3460 if (!Context
.getTargetInfo().isValidFeatureName(CurFeature
))
3461 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3462 << Unsupported
<< None
<< CurFeature
<< Target
;
3465 TargetInfo::BranchProtectionInfo BPI
;
3467 if (ParsedAttrs
.BranchProtection
.empty())
3469 if (!Context
.getTargetInfo().validateBranchProtection(
3470 ParsedAttrs
.BranchProtection
, ParsedAttrs
.CPU
, BPI
, DiagMsg
)) {
3471 if (DiagMsg
.empty())
3472 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3473 << Unsupported
<< None
<< "branch-protection" << Target
;
3474 return Diag(LiteralLoc
, diag::err_invalid_branch_protection_spec
)
3477 if (!DiagMsg
.empty())
3478 Diag(LiteralLoc
, diag::warn_unsupported_branch_protection_spec
) << DiagMsg
;
3483 // Check Target Version attrs
3484 bool Sema::checkTargetVersionAttr(SourceLocation LiteralLoc
, StringRef
&AttrStr
,
3486 enum FirstParam
{ Unsupported
};
3487 enum SecondParam
{ None
};
3488 enum ThirdParam
{ Target
, TargetClones
, TargetVersion
};
3489 if (AttrStr
.trim() == "default")
3491 llvm::SmallVector
<StringRef
, 8> Features
;
3492 AttrStr
.split(Features
, "+");
3493 for (auto &CurFeature
: Features
) {
3494 CurFeature
= CurFeature
.trim();
3495 if (CurFeature
== "default")
3497 if (!Context
.getTargetInfo().validateCpuSupports(CurFeature
))
3498 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3499 << Unsupported
<< None
<< CurFeature
<< TargetVersion
;
3504 static void handleTargetVersionAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3506 SourceLocation LiteralLoc
;
3507 bool isDefault
= false;
3508 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &LiteralLoc
) ||
3509 S
.checkTargetVersionAttr(LiteralLoc
, Str
, isDefault
))
3511 // Do not create default only target_version attribute
3513 TargetVersionAttr
*NewAttr
=
3514 ::new (S
.Context
) TargetVersionAttr(S
.Context
, AL
, Str
);
3515 D
->addAttr(NewAttr
);
3519 static void handleTargetAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3521 SourceLocation LiteralLoc
;
3522 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &LiteralLoc
) ||
3523 S
.checkTargetAttr(LiteralLoc
, Str
))
3526 TargetAttr
*NewAttr
= ::new (S
.Context
) TargetAttr(S
.Context
, AL
, Str
);
3527 D
->addAttr(NewAttr
);
3530 bool Sema::checkTargetClonesAttrString(
3531 SourceLocation LiteralLoc
, StringRef Str
, const StringLiteral
*Literal
,
3532 bool &HasDefault
, bool &HasCommas
, bool &HasNotDefault
,
3533 SmallVectorImpl
<SmallString
<64>> &StringsBuffer
) {
3534 enum FirstParam
{ Unsupported
, Duplicate
, Unknown
};
3535 enum SecondParam
{ None
, CPU
, Tune
};
3536 enum ThirdParam
{ Target
, TargetClones
};
3537 HasCommas
= HasCommas
|| Str
.contains(',');
3538 const TargetInfo
&TInfo
= Context
.getTargetInfo();
3539 // Warn on empty at the beginning of a string.
3540 if (Str
.size() == 0)
3541 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3542 << Unsupported
<< None
<< "" << TargetClones
;
3544 std::pair
<StringRef
, StringRef
> Parts
= {{}, Str
};
3545 while (!Parts
.second
.empty()) {
3546 Parts
= Parts
.second
.split(',');
3547 StringRef Cur
= Parts
.first
.trim();
3548 SourceLocation CurLoc
=
3549 Literal
->getLocationOfByte(Cur
.data() - Literal
->getString().data(),
3550 getSourceManager(), getLangOpts(), TInfo
);
3552 bool DefaultIsDupe
= false;
3553 bool HasCodeGenImpact
= false;
3555 return Diag(CurLoc
, diag::warn_unsupported_target_attribute
)
3556 << Unsupported
<< None
<< "" << TargetClones
;
3558 if (TInfo
.getTriple().isAArch64()) {
3559 // AArch64 target clones specific
3560 if (Cur
== "default") {
3561 DefaultIsDupe
= HasDefault
;
3563 if (llvm::is_contained(StringsBuffer
, Cur
) || DefaultIsDupe
)
3564 Diag(CurLoc
, diag::warn_target_clone_duplicate_options
);
3566 StringsBuffer
.push_back(Cur
);
3568 std::pair
<StringRef
, StringRef
> CurParts
= {{}, Cur
};
3569 llvm::SmallVector
<StringRef
, 8> CurFeatures
;
3570 while (!CurParts
.second
.empty()) {
3571 CurParts
= CurParts
.second
.split('+');
3572 StringRef CurFeature
= CurParts
.first
.trim();
3573 if (!TInfo
.validateCpuSupports(CurFeature
)) {
3574 Diag(CurLoc
, diag::warn_unsupported_target_attribute
)
3575 << Unsupported
<< None
<< CurFeature
<< TargetClones
;
3578 if (TInfo
.doesFeatureAffectCodeGen(CurFeature
))
3579 HasCodeGenImpact
= true;
3580 CurFeatures
.push_back(CurFeature
);
3582 // Canonize TargetClones Attributes
3583 llvm::sort(CurFeatures
);
3584 SmallString
<64> Res
;
3585 for (auto &CurFeat
: CurFeatures
) {
3586 if (!Res
.equals(""))
3588 Res
.append(CurFeat
);
3590 if (llvm::is_contained(StringsBuffer
, Res
) || DefaultIsDupe
)
3591 Diag(CurLoc
, diag::warn_target_clone_duplicate_options
);
3592 else if (!HasCodeGenImpact
)
3593 // Ignore features in target_clone attribute that don't impact
3595 Diag(CurLoc
, diag::warn_target_clone_no_impact_options
);
3596 else if (!Res
.empty()) {
3597 StringsBuffer
.push_back(Res
);
3598 HasNotDefault
= true;
3602 // Other targets ( currently X86 )
3603 if (Cur
.startswith("arch=")) {
3604 if (!Context
.getTargetInfo().isValidCPUName(
3605 Cur
.drop_front(sizeof("arch=") - 1)))
3606 return Diag(CurLoc
, diag::warn_unsupported_target_attribute
)
3607 << Unsupported
<< CPU
<< Cur
.drop_front(sizeof("arch=") - 1)
3609 } else if (Cur
== "default") {
3610 DefaultIsDupe
= HasDefault
;
3612 } else if (!Context
.getTargetInfo().isValidFeatureName(Cur
))
3613 return Diag(CurLoc
, diag::warn_unsupported_target_attribute
)
3614 << Unsupported
<< None
<< Cur
<< TargetClones
;
3615 if (llvm::is_contained(StringsBuffer
, Cur
) || DefaultIsDupe
)
3616 Diag(CurLoc
, diag::warn_target_clone_duplicate_options
);
3617 // Note: Add even if there are duplicates, since it changes name mangling.
3618 StringsBuffer
.push_back(Cur
);
3621 if (Str
.rtrim().endswith(","))
3622 return Diag(LiteralLoc
, diag::warn_unsupported_target_attribute
)
3623 << Unsupported
<< None
<< "" << TargetClones
;
3627 static void handleTargetClonesAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3628 if (S
.Context
.getTargetInfo().getTriple().isAArch64() &&
3629 !S
.Context
.getTargetInfo().hasFeature("fmv"))
3632 // Ensure we don't combine these with themselves, since that causes some
3633 // confusing behavior.
3634 if (const auto *Other
= D
->getAttr
<TargetClonesAttr
>()) {
3635 S
.Diag(AL
.getLoc(), diag::err_disallowed_duplicate_attribute
) << AL
;
3636 S
.Diag(Other
->getLocation(), diag::note_conflicting_attribute
);
3639 if (checkAttrMutualExclusion
<TargetClonesAttr
>(S
, D
, AL
))
3642 SmallVector
<StringRef
, 2> Strings
;
3643 SmallVector
<SmallString
<64>, 2> StringsBuffer
;
3644 bool HasCommas
= false, HasDefault
= false, HasNotDefault
= false;
3646 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
!= E
; ++I
) {
3648 SourceLocation LiteralLoc
;
3649 if (!S
.checkStringLiteralArgumentAttr(AL
, I
, CurStr
, &LiteralLoc
) ||
3650 S
.checkTargetClonesAttrString(
3652 cast
<StringLiteral
>(AL
.getArgAsExpr(I
)->IgnoreParenCasts()),
3653 HasDefault
, HasCommas
, HasNotDefault
, StringsBuffer
))
3656 for (auto &SmallStr
: StringsBuffer
)
3657 Strings
.push_back(SmallStr
.str());
3659 if (HasCommas
&& AL
.getNumArgs() > 1)
3660 S
.Diag(AL
.getLoc(), diag::warn_target_clone_mixed_values
);
3662 if (S
.Context
.getTargetInfo().getTriple().isAArch64() && !HasDefault
) {
3663 // Add default attribute if there is no one
3665 Strings
.push_back("default");
3669 S
.Diag(AL
.getLoc(), diag::err_target_clone_must_have_default
);
3673 // FIXME: We could probably figure out how to get this to work for lambdas
3675 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
3676 if (MD
->getParent()->isLambda()) {
3677 S
.Diag(D
->getLocation(), diag::err_multiversion_doesnt_support
)
3678 << static_cast<unsigned>(MultiVersionKind::TargetClones
)
3684 // No multiversion if we have default version only.
3685 if (S
.Context
.getTargetInfo().getTriple().isAArch64() && !HasNotDefault
)
3688 cast
<FunctionDecl
>(D
)->setIsMultiVersion();
3689 TargetClonesAttr
*NewAttr
= ::new (S
.Context
)
3690 TargetClonesAttr(S
.Context
, AL
, Strings
.data(), Strings
.size());
3691 D
->addAttr(NewAttr
);
3694 static void handleMinVectorWidthAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3695 Expr
*E
= AL
.getArgAsExpr(0);
3697 if (!checkUInt32Argument(S
, AL
, E
, VecWidth
)) {
3702 MinVectorWidthAttr
*Existing
= D
->getAttr
<MinVectorWidthAttr
>();
3703 if (Existing
&& Existing
->getVectorWidth() != VecWidth
) {
3704 S
.Diag(AL
.getLoc(), diag::warn_duplicate_attribute
) << AL
;
3708 D
->addAttr(::new (S
.Context
) MinVectorWidthAttr(S
.Context
, AL
, VecWidth
));
3711 static void handleCleanupAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3712 Expr
*E
= AL
.getArgAsExpr(0);
3713 SourceLocation Loc
= E
->getExprLoc();
3714 FunctionDecl
*FD
= nullptr;
3715 DeclarationNameInfo NI
;
3717 // gcc only allows for simple identifiers. Since we support more than gcc, we
3718 // will warn the user.
3719 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
3720 if (DRE
->hasQualifier())
3721 S
.Diag(Loc
, diag::warn_cleanup_ext
);
3722 FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
3723 NI
= DRE
->getNameInfo();
3725 S
.Diag(Loc
, diag::err_attribute_cleanup_arg_not_function
) << 1
3729 } else if (auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
3730 if (ULE
->hasExplicitTemplateArgs())
3731 S
.Diag(Loc
, diag::warn_cleanup_ext
);
3732 FD
= S
.ResolveSingleFunctionTemplateSpecialization(ULE
, true);
3733 NI
= ULE
->getNameInfo();
3735 S
.Diag(Loc
, diag::err_attribute_cleanup_arg_not_function
) << 2
3737 if (ULE
->getType() == S
.Context
.OverloadTy
)
3738 S
.NoteAllOverloadCandidates(ULE
);
3742 S
.Diag(Loc
, diag::err_attribute_cleanup_arg_not_function
) << 0;
3746 if (FD
->getNumParams() != 1) {
3747 S
.Diag(Loc
, diag::err_attribute_cleanup_func_must_take_one_arg
)
3752 // We're currently more strict than GCC about what function types we accept.
3753 // If this ever proves to be a problem it should be easy to fix.
3754 QualType Ty
= S
.Context
.getPointerType(cast
<VarDecl
>(D
)->getType());
3755 QualType ParamTy
= FD
->getParamDecl(0)->getType();
3756 if (S
.CheckAssignmentConstraints(FD
->getParamDecl(0)->getLocation(),
3757 ParamTy
, Ty
) != Sema::Compatible
) {
3758 S
.Diag(Loc
, diag::err_attribute_cleanup_func_arg_incompatible_type
)
3759 << NI
.getName() << ParamTy
<< Ty
;
3763 D
->addAttr(::new (S
.Context
) CleanupAttr(S
.Context
, AL
, FD
));
3766 static void handleEnumExtensibilityAttr(Sema
&S
, Decl
*D
,
3767 const ParsedAttr
&AL
) {
3768 if (!AL
.isArgIdent(0)) {
3769 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
3770 << AL
<< 0 << AANT_ArgumentIdentifier
;
3774 EnumExtensibilityAttr::Kind ExtensibilityKind
;
3775 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
3776 if (!EnumExtensibilityAttr::ConvertStrToKind(II
->getName(),
3777 ExtensibilityKind
)) {
3778 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< II
;
3782 D
->addAttr(::new (S
.Context
)
3783 EnumExtensibilityAttr(S
.Context
, AL
, ExtensibilityKind
));
3786 /// Handle __attribute__((format_arg((idx)))) attribute based on
3787 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3788 static void handleFormatArgAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3789 const Expr
*IdxExpr
= AL
.getArgAsExpr(0);
3791 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, 1, IdxExpr
, Idx
))
3794 // Make sure the format string is really a string.
3795 QualType Ty
= getFunctionOrMethodParamType(D
, Idx
.getASTIndex());
3797 bool NotNSStringTy
= !isNSStringType(Ty
, S
.Context
);
3798 if (NotNSStringTy
&&
3799 !isCFStringType(Ty
, S
.Context
) &&
3800 (!Ty
->isPointerType() ||
3801 !Ty
->castAs
<PointerType
>()->getPointeeType()->isCharType())) {
3802 S
.Diag(AL
.getLoc(), diag::err_format_attribute_not
)
3803 << IdxExpr
->getSourceRange() << getFunctionOrMethodParamRange(D
, 0);
3806 Ty
= getFunctionOrMethodResultType(D
);
3807 // replace instancetype with the class type
3808 auto Instancetype
= S
.Context
.getObjCInstanceTypeDecl()->getTypeForDecl();
3809 if (Ty
->getAs
<TypedefType
>() == Instancetype
)
3810 if (auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
))
3811 if (auto *Interface
= OMD
->getClassInterface())
3812 Ty
= S
.Context
.getObjCObjectPointerType(
3813 QualType(Interface
->getTypeForDecl(), 0));
3814 if (!isNSStringType(Ty
, S
.Context
, /*AllowNSAttributedString=*/true) &&
3815 !isCFStringType(Ty
, S
.Context
) &&
3816 (!Ty
->isPointerType() ||
3817 !Ty
->castAs
<PointerType
>()->getPointeeType()->isCharType())) {
3818 S
.Diag(AL
.getLoc(), diag::err_format_attribute_result_not
)
3819 << (NotNSStringTy
? "string type" : "NSString")
3820 << IdxExpr
->getSourceRange() << getFunctionOrMethodParamRange(D
, 0);
3824 D
->addAttr(::new (S
.Context
) FormatArgAttr(S
.Context
, AL
, Idx
));
3827 enum FormatAttrKind
{
3836 /// getFormatAttrKind - Map from format attribute names to supported format
3838 static FormatAttrKind
getFormatAttrKind(StringRef Format
) {
3839 return llvm::StringSwitch
<FormatAttrKind
>(Format
)
3840 // Check for formats that get handled specially.
3841 .Case("NSString", NSStringFormat
)
3842 .Case("CFString", CFStringFormat
)
3843 .Case("strftime", StrftimeFormat
)
3845 // Otherwise, check for supported formats.
3846 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat
)
3847 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat
)
3848 .Case("kprintf", SupportedFormat
) // OpenBSD.
3849 .Case("freebsd_kprintf", SupportedFormat
) // FreeBSD.
3850 .Case("os_trace", SupportedFormat
)
3851 .Case("os_log", SupportedFormat
)
3853 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat
)
3854 .Default(InvalidFormat
);
3857 /// Handle __attribute__((init_priority(priority))) attributes based on
3858 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3859 static void handleInitPriorityAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3860 if (!S
.getLangOpts().CPlusPlus
) {
3861 S
.Diag(AL
.getLoc(), diag::warn_attribute_ignored
) << AL
;
3865 if (S
.getLangOpts().HLSL
) {
3866 S
.Diag(AL
.getLoc(), diag::err_hlsl_init_priority_unsupported
);
3870 if (S
.getCurFunctionOrMethodDecl()) {
3871 S
.Diag(AL
.getLoc(), diag::err_init_priority_object_attr
);
3875 QualType T
= cast
<VarDecl
>(D
)->getType();
3876 if (S
.Context
.getAsArrayType(T
))
3877 T
= S
.Context
.getBaseElementType(T
);
3878 if (!T
->getAs
<RecordType
>()) {
3879 S
.Diag(AL
.getLoc(), diag::err_init_priority_object_attr
);
3884 Expr
*E
= AL
.getArgAsExpr(0);
3885 uint32_t prioritynum
;
3886 if (!checkUInt32Argument(S
, AL
, E
, prioritynum
)) {
3891 // Only perform the priority check if the attribute is outside of a system
3892 // header. Values <= 100 are reserved for the implementation, and libc++
3893 // benefits from being able to specify values in that range.
3894 if ((prioritynum
< 101 || prioritynum
> 65535) &&
3895 !S
.getSourceManager().isInSystemHeader(AL
.getLoc())) {
3896 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_range
)
3897 << E
->getSourceRange() << AL
<< 101 << 65535;
3901 D
->addAttr(::new (S
.Context
) InitPriorityAttr(S
.Context
, AL
, prioritynum
));
3904 ErrorAttr
*Sema::mergeErrorAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
3905 StringRef NewUserDiagnostic
) {
3906 if (const auto *EA
= D
->getAttr
<ErrorAttr
>()) {
3907 std::string NewAttr
= CI
.getNormalizedFullName();
3908 assert((NewAttr
== "error" || NewAttr
== "warning") &&
3909 "unexpected normalized full name");
3910 bool Match
= (EA
->isError() && NewAttr
== "error") ||
3911 (EA
->isWarning() && NewAttr
== "warning");
3913 Diag(EA
->getLocation(), diag::err_attributes_are_not_compatible
)
3915 << (CI
.isRegularKeywordAttribute() ||
3916 EA
->isRegularKeywordAttribute());
3917 Diag(CI
.getLoc(), diag::note_conflicting_attribute
);
3920 if (EA
->getUserDiagnostic() != NewUserDiagnostic
) {
3921 Diag(CI
.getLoc(), diag::warn_duplicate_attribute
) << EA
;
3922 Diag(EA
->getLoc(), diag::note_previous_attribute
);
3924 D
->dropAttr
<ErrorAttr
>();
3926 return ::new (Context
) ErrorAttr(Context
, CI
, NewUserDiagnostic
);
3929 FormatAttr
*Sema::mergeFormatAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
3930 IdentifierInfo
*Format
, int FormatIdx
,
3932 // Check whether we already have an equivalent format attribute.
3933 for (auto *F
: D
->specific_attrs
<FormatAttr
>()) {
3934 if (F
->getType() == Format
&&
3935 F
->getFormatIdx() == FormatIdx
&&
3936 F
->getFirstArg() == FirstArg
) {
3937 // If we don't have a valid location for this attribute, adopt the
3939 if (F
->getLocation().isInvalid())
3940 F
->setRange(CI
.getRange());
3945 return ::new (Context
) FormatAttr(Context
, CI
, Format
, FormatIdx
, FirstArg
);
3948 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3949 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3950 static void handleFormatAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
3951 if (!AL
.isArgIdent(0)) {
3952 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
3953 << AL
<< 1 << AANT_ArgumentIdentifier
;
3957 // In C++ the implicit 'this' function parameter also counts, and they are
3958 // counted from one.
3959 bool HasImplicitThisParam
= isInstanceMethod(D
);
3960 unsigned NumArgs
= getFunctionOrMethodNumParams(D
) + HasImplicitThisParam
;
3962 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
3963 StringRef Format
= II
->getName();
3965 if (normalizeName(Format
)) {
3966 // If we've modified the string name, we need a new identifier for it.
3967 II
= &S
.Context
.Idents
.get(Format
);
3970 // Check for supported formats.
3971 FormatAttrKind Kind
= getFormatAttrKind(Format
);
3973 if (Kind
== IgnoredFormat
)
3976 if (Kind
== InvalidFormat
) {
3977 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
)
3978 << AL
<< II
->getName();
3982 // checks for the 2nd argument
3983 Expr
*IdxExpr
= AL
.getArgAsExpr(1);
3985 if (!checkUInt32Argument(S
, AL
, IdxExpr
, Idx
, 2))
3988 if (Idx
< 1 || Idx
> NumArgs
) {
3989 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
3990 << AL
<< 2 << IdxExpr
->getSourceRange();
3994 // FIXME: Do we need to bounds check?
3995 unsigned ArgIdx
= Idx
- 1;
3997 if (HasImplicitThisParam
) {
4000 diag::err_format_attribute_implicit_this_format_string
)
4001 << IdxExpr
->getSourceRange();
4007 // make sure the format string is really a string
4008 QualType Ty
= getFunctionOrMethodParamType(D
, ArgIdx
);
4010 if (!isNSStringType(Ty
, S
.Context
, true) &&
4011 !isCFStringType(Ty
, S
.Context
) &&
4012 (!Ty
->isPointerType() ||
4013 !Ty
->castAs
<PointerType
>()->getPointeeType()->isCharType())) {
4014 S
.Diag(AL
.getLoc(), diag::err_format_attribute_not
)
4015 << IdxExpr
->getSourceRange() << getFunctionOrMethodParamRange(D
, ArgIdx
);
4019 // check the 3rd argument
4020 Expr
*FirstArgExpr
= AL
.getArgAsExpr(2);
4022 if (!checkUInt32Argument(S
, AL
, FirstArgExpr
, FirstArg
, 3))
4025 // FirstArg == 0 is is always valid.
4026 if (FirstArg
!= 0) {
4027 if (Kind
== StrftimeFormat
) {
4028 // If the kind is strftime, FirstArg must be 0 because strftime does not
4029 // use any variadic arguments.
4030 S
.Diag(AL
.getLoc(), diag::err_format_strftime_third_parameter
)
4031 << FirstArgExpr
->getSourceRange()
4032 << FixItHint::CreateReplacement(FirstArgExpr
->getSourceRange(), "0");
4034 } else if (isFunctionOrMethodVariadic(D
)) {
4035 // Else, if the function is variadic, then FirstArg must be 0 or the
4036 // "position" of the ... parameter. It's unusual to use 0 with variadic
4037 // functions, so the fixit proposes the latter.
4038 if (FirstArg
!= NumArgs
+ 1) {
4039 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
4040 << AL
<< 3 << FirstArgExpr
->getSourceRange()
4041 << FixItHint::CreateReplacement(FirstArgExpr
->getSourceRange(),
4042 std::to_string(NumArgs
+ 1));
4046 // Inescapable GCC compatibility diagnostic.
4047 S
.Diag(D
->getLocation(), diag::warn_gcc_requires_variadic_function
) << AL
;
4048 if (FirstArg
<= Idx
) {
4049 // Else, the function is not variadic, and FirstArg must be 0 or any
4050 // parameter after the format parameter. We don't offer a fixit because
4051 // there are too many possible good values.
4052 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
4053 << AL
<< 3 << FirstArgExpr
->getSourceRange();
4059 FormatAttr
*NewAttr
= S
.mergeFormatAttr(D
, AL
, II
, Idx
, FirstArg
);
4061 D
->addAttr(NewAttr
);
4064 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
4065 static void handleCallbackAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4066 // The index that identifies the callback callee is mandatory.
4067 if (AL
.getNumArgs() == 0) {
4068 S
.Diag(AL
.getLoc(), diag::err_callback_attribute_no_callee
)
4073 bool HasImplicitThisParam
= isInstanceMethod(D
);
4074 int32_t NumArgs
= getFunctionOrMethodNumParams(D
);
4076 FunctionDecl
*FD
= D
->getAsFunction();
4077 assert(FD
&& "Expected a function declaration!");
4079 llvm::StringMap
<int> NameIdxMapping
;
4080 NameIdxMapping
["__"] = -1;
4082 NameIdxMapping
["this"] = 0;
4085 for (const ParmVarDecl
*PVD
: FD
->parameters())
4086 NameIdxMapping
[PVD
->getName()] = Idx
++;
4088 auto UnknownName
= NameIdxMapping
.end();
4090 SmallVector
<int, 8> EncodingIndices
;
4091 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
< E
; ++I
) {
4095 if (AL
.isArgIdent(I
)) {
4096 IdentifierLoc
*IdLoc
= AL
.getArgAsIdent(I
);
4097 auto It
= NameIdxMapping
.find(IdLoc
->Ident
->getName());
4098 if (It
== UnknownName
) {
4099 S
.Diag(AL
.getLoc(), diag::err_callback_attribute_argument_unknown
)
4100 << IdLoc
->Ident
<< IdLoc
->Loc
;
4104 SR
= SourceRange(IdLoc
->Loc
);
4105 ArgIdx
= It
->second
;
4106 } else if (AL
.isArgExpr(I
)) {
4107 Expr
*IdxExpr
= AL
.getArgAsExpr(I
);
4109 // If the expression is not parseable as an int32_t we have a problem.
4110 if (!checkUInt32Argument(S
, AL
, IdxExpr
, (uint32_t &)ArgIdx
, I
+ 1,
4112 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
4113 << AL
<< (I
+ 1) << IdxExpr
->getSourceRange();
4117 // Check oob, excluding the special values, 0 and -1.
4118 if (ArgIdx
< -1 || ArgIdx
> NumArgs
) {
4119 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
4120 << AL
<< (I
+ 1) << IdxExpr
->getSourceRange();
4124 SR
= IdxExpr
->getSourceRange();
4126 llvm_unreachable("Unexpected ParsedAttr argument type!");
4129 if (ArgIdx
== 0 && !HasImplicitThisParam
) {
4130 S
.Diag(AL
.getLoc(), diag::err_callback_implicit_this_not_available
)
4135 // Adjust for the case we do not have an implicit "this" parameter. In this
4136 // case we decrease all positive values by 1 to get LLVM argument indices.
4137 if (!HasImplicitThisParam
&& ArgIdx
> 0)
4140 EncodingIndices
.push_back(ArgIdx
);
4143 int CalleeIdx
= EncodingIndices
.front();
4144 // Check if the callee index is proper, thus not "this" and not "unknown".
4145 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4146 // is false and positive if "HasImplicitThisParam" is true.
4147 if (CalleeIdx
< (int)HasImplicitThisParam
) {
4148 S
.Diag(AL
.getLoc(), diag::err_callback_attribute_invalid_callee
)
4153 // Get the callee type, note the index adjustment as the AST doesn't contain
4154 // the this type (which the callee cannot reference anyway!).
4155 const Type
*CalleeType
=
4156 getFunctionOrMethodParamType(D
, CalleeIdx
- HasImplicitThisParam
)
4158 if (!CalleeType
|| !CalleeType
->isFunctionPointerType()) {
4159 S
.Diag(AL
.getLoc(), diag::err_callback_callee_no_function_type
)
4164 const Type
*CalleeFnType
=
4165 CalleeType
->getPointeeType()->getUnqualifiedDesugaredType();
4167 // TODO: Check the type of the callee arguments.
4169 const auto *CalleeFnProtoType
= dyn_cast
<FunctionProtoType
>(CalleeFnType
);
4170 if (!CalleeFnProtoType
) {
4171 S
.Diag(AL
.getLoc(), diag::err_callback_callee_no_function_type
)
4176 if (CalleeFnProtoType
->getNumParams() > EncodingIndices
.size() - 1) {
4177 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
)
4178 << AL
<< (unsigned)(EncodingIndices
.size() - 1);
4182 if (CalleeFnProtoType
->getNumParams() < EncodingIndices
.size() - 1) {
4183 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
)
4184 << AL
<< (unsigned)(EncodingIndices
.size() - 1);
4188 if (CalleeFnProtoType
->isVariadic()) {
4189 S
.Diag(AL
.getLoc(), diag::err_callback_callee_is_variadic
) << AL
.getRange();
4193 // Do not allow multiple callback attributes.
4194 if (D
->hasAttr
<CallbackAttr
>()) {
4195 S
.Diag(AL
.getLoc(), diag::err_callback_attribute_multiple
) << AL
.getRange();
4199 D
->addAttr(::new (S
.Context
) CallbackAttr(
4200 S
.Context
, AL
, EncodingIndices
.data(), EncodingIndices
.size()));
4203 static bool isFunctionLike(const Type
&T
) {
4204 // Check for explicit function types.
4205 // 'called_once' is only supported in Objective-C and it has
4206 // function pointers and block pointers.
4207 return T
.isFunctionPointerType() || T
.isBlockPointerType();
4210 /// Handle 'called_once' attribute.
4211 static void handleCalledOnceAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4212 // 'called_once' only applies to parameters representing functions.
4213 QualType T
= cast
<ParmVarDecl
>(D
)->getType();
4215 if (!isFunctionLike(*T
)) {
4216 S
.Diag(AL
.getLoc(), diag::err_called_once_attribute_wrong_type
);
4220 D
->addAttr(::new (S
.Context
) CalledOnceAttr(S
.Context
, AL
));
4223 static void handleTransparentUnionAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4224 // Try to find the underlying union declaration.
4225 RecordDecl
*RD
= nullptr;
4226 const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
);
4227 if (TD
&& TD
->getUnderlyingType()->isUnionType())
4228 RD
= TD
->getUnderlyingType()->getAsUnionType()->getDecl();
4230 RD
= dyn_cast
<RecordDecl
>(D
);
4232 if (!RD
|| !RD
->isUnion()) {
4233 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
4234 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedUnion
;
4238 if (!RD
->isCompleteDefinition()) {
4239 if (!RD
->isBeingDefined())
4241 diag::warn_transparent_union_attribute_not_definition
);
4245 RecordDecl::field_iterator Field
= RD
->field_begin(),
4246 FieldEnd
= RD
->field_end();
4247 if (Field
== FieldEnd
) {
4248 S
.Diag(AL
.getLoc(), diag::warn_transparent_union_attribute_zero_fields
);
4252 FieldDecl
*FirstField
= *Field
;
4253 QualType FirstType
= FirstField
->getType();
4254 if (FirstType
->hasFloatingRepresentation() || FirstType
->isVectorType()) {
4255 S
.Diag(FirstField
->getLocation(),
4256 diag::warn_transparent_union_attribute_floating
)
4257 << FirstType
->isVectorType() << FirstType
;
4261 if (FirstType
->isIncompleteType())
4263 uint64_t FirstSize
= S
.Context
.getTypeSize(FirstType
);
4264 uint64_t FirstAlign
= S
.Context
.getTypeAlign(FirstType
);
4265 for (; Field
!= FieldEnd
; ++Field
) {
4266 QualType FieldType
= Field
->getType();
4267 if (FieldType
->isIncompleteType())
4269 // FIXME: this isn't fully correct; we also need to test whether the
4270 // members of the union would all have the same calling convention as the
4271 // first member of the union. Checking just the size and alignment isn't
4272 // sufficient (consider structs passed on the stack instead of in registers
4274 if (S
.Context
.getTypeSize(FieldType
) != FirstSize
||
4275 S
.Context
.getTypeAlign(FieldType
) > FirstAlign
) {
4276 // Warn if we drop the attribute.
4277 bool isSize
= S
.Context
.getTypeSize(FieldType
) != FirstSize
;
4278 unsigned FieldBits
= isSize
? S
.Context
.getTypeSize(FieldType
)
4279 : S
.Context
.getTypeAlign(FieldType
);
4280 S
.Diag(Field
->getLocation(),
4281 diag::warn_transparent_union_attribute_field_size_align
)
4282 << isSize
<< *Field
<< FieldBits
;
4283 unsigned FirstBits
= isSize
? FirstSize
: FirstAlign
;
4284 S
.Diag(FirstField
->getLocation(),
4285 diag::note_transparent_union_first_field_size_align
)
4286 << isSize
<< FirstBits
;
4291 RD
->addAttr(::new (S
.Context
) TransparentUnionAttr(S
.Context
, AL
));
4294 void Sema::AddAnnotationAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
4295 StringRef Str
, MutableArrayRef
<Expr
*> Args
) {
4296 auto *Attr
= AnnotateAttr::Create(Context
, Str
, Args
.data(), Args
.size(), CI
);
4297 if (ConstantFoldAttrArgs(
4298 CI
, MutableArrayRef
<Expr
*>(Attr
->args_begin(), Attr
->args_end()))) {
4303 static void handleAnnotateAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4304 // Make sure that there is a string literal as the annotation's first
4307 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
4310 llvm::SmallVector
<Expr
*, 4> Args
;
4311 Args
.reserve(AL
.getNumArgs() - 1);
4312 for (unsigned Idx
= 1; Idx
< AL
.getNumArgs(); Idx
++) {
4313 assert(!AL
.isArgIdent(Idx
));
4314 Args
.push_back(AL
.getArgAsExpr(Idx
));
4317 S
.AddAnnotationAttr(D
, AL
, Str
, Args
);
4320 static void handleAlignValueAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4321 S
.AddAlignValueAttr(D
, AL
, AL
.getArgAsExpr(0));
4324 void Sema::AddAlignValueAttr(Decl
*D
, const AttributeCommonInfo
&CI
, Expr
*E
) {
4325 AlignValueAttr
TmpAttr(Context
, CI
, E
);
4326 SourceLocation AttrLoc
= CI
.getLoc();
4329 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
))
4330 T
= TD
->getUnderlyingType();
4331 else if (const auto *VD
= dyn_cast
<ValueDecl
>(D
))
4334 llvm_unreachable("Unknown decl type for align_value");
4336 if (!T
->isDependentType() && !T
->isAnyPointerType() &&
4337 !T
->isReferenceType() && !T
->isMemberPointerType()) {
4338 Diag(AttrLoc
, diag::warn_attribute_pointer_or_reference_only
)
4339 << &TmpAttr
<< T
<< D
->getSourceRange();
4343 if (!E
->isValueDependent()) {
4344 llvm::APSInt Alignment
;
4345 ExprResult ICE
= VerifyIntegerConstantExpression(
4346 E
, &Alignment
, diag::err_align_value_attribute_argument_not_int
);
4347 if (ICE
.isInvalid())
4350 if (!Alignment
.isPowerOf2()) {
4351 Diag(AttrLoc
, diag::err_alignment_not_power_of_two
)
4352 << E
->getSourceRange();
4356 D
->addAttr(::new (Context
) AlignValueAttr(Context
, CI
, ICE
.get()));
4360 // Save dependent expressions in the AST to be instantiated.
4361 D
->addAttr(::new (Context
) AlignValueAttr(Context
, CI
, E
));
4364 static void handleAlignedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4365 if (AL
.hasParsedType()) {
4366 const ParsedType
&TypeArg
= AL
.getTypeArg();
4367 TypeSourceInfo
*TInfo
;
4368 (void)S
.GetTypeFromParser(
4369 ParsedType::getFromOpaquePtr(TypeArg
.getAsOpaquePtr()), &TInfo
);
4370 if (AL
.isPackExpansion() &&
4371 !TInfo
->getType()->containsUnexpandedParameterPack()) {
4372 S
.Diag(AL
.getEllipsisLoc(),
4373 diag::err_pack_expansion_without_parameter_packs
);
4377 if (!AL
.isPackExpansion() &&
4378 S
.DiagnoseUnexpandedParameterPack(TInfo
->getTypeLoc().getBeginLoc(),
4379 TInfo
, Sema::UPPC_Expression
))
4382 S
.AddAlignedAttr(D
, AL
, TInfo
, AL
.isPackExpansion());
4386 // check the attribute arguments.
4387 if (AL
.getNumArgs() > 1) {
4388 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
) << AL
<< 1;
4392 if (AL
.getNumArgs() == 0) {
4393 D
->addAttr(::new (S
.Context
) AlignedAttr(S
.Context
, AL
, true, nullptr));
4397 Expr
*E
= AL
.getArgAsExpr(0);
4398 if (AL
.isPackExpansion() && !E
->containsUnexpandedParameterPack()) {
4399 S
.Diag(AL
.getEllipsisLoc(),
4400 diag::err_pack_expansion_without_parameter_packs
);
4404 if (!AL
.isPackExpansion() && S
.DiagnoseUnexpandedParameterPack(E
))
4407 S
.AddAlignedAttr(D
, AL
, E
, AL
.isPackExpansion());
4410 /// Perform checking of type validity
4412 /// C++11 [dcl.align]p1:
4413 /// An alignment-specifier may be applied to a variable or to a class
4414 /// data member, but it shall not be applied to a bit-field, a function
4415 /// parameter, the formal parameter of a catch clause, or a variable
4416 /// declared with the register storage class specifier. An
4417 /// alignment-specifier may also be applied to the declaration of a class
4418 /// or enumeration type.
4420 /// CWG agreed to remove permission for alignas to be applied to
4423 /// An alignment attribute shall not be specified in a declaration of
4424 /// a typedef, or a bit-field, or a function, or a parameter, or an
4425 /// object declared with the register storage-class specifier.
4426 static bool validateAlignasAppliedType(Sema
&S
, Decl
*D
,
4427 const AlignedAttr
&Attr
,
4428 SourceLocation AttrLoc
) {
4430 if (isa
<ParmVarDecl
>(D
)) {
4432 } else if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
4433 if (VD
->getStorageClass() == SC_Register
)
4435 if (VD
->isExceptionVariable())
4437 } else if (const auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
4438 if (FD
->isBitField())
4440 } else if (const auto *ED
= dyn_cast
<EnumDecl
>(D
)) {
4441 if (ED
->getLangOpts().CPlusPlus
)
4443 } else if (!isa
<TagDecl
>(D
)) {
4444 return S
.Diag(AttrLoc
, diag::err_attribute_wrong_decl_type
)
4445 << &Attr
<< Attr
.isRegularKeywordAttribute()
4446 << (Attr
.isC11() ? ExpectedVariableOrField
4447 : ExpectedVariableFieldOrTag
);
4449 if (DiagKind
!= -1) {
4450 return S
.Diag(AttrLoc
, diag::err_alignas_attribute_wrong_decl_type
)
4451 << &Attr
<< DiagKind
;
4456 void Sema::AddAlignedAttr(Decl
*D
, const AttributeCommonInfo
&CI
, Expr
*E
,
4457 bool IsPackExpansion
) {
4458 AlignedAttr
TmpAttr(Context
, CI
, true, E
);
4459 SourceLocation AttrLoc
= CI
.getLoc();
4461 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4462 if (TmpAttr
.isAlignas() &&
4463 validateAlignasAppliedType(*this, D
, TmpAttr
, AttrLoc
))
4466 if (E
->isValueDependent()) {
4467 // We can't support a dependent alignment on a non-dependent type,
4468 // because we have no way to model that a type is "alignment-dependent"
4469 // but not dependent in any other way.
4470 if (const auto *TND
= dyn_cast
<TypedefNameDecl
>(D
)) {
4471 if (!TND
->getUnderlyingType()->isDependentType()) {
4472 Diag(AttrLoc
, diag::err_alignment_dependent_typedef_name
)
4473 << E
->getSourceRange();
4478 // Save dependent expressions in the AST to be instantiated.
4479 AlignedAttr
*AA
= ::new (Context
) AlignedAttr(Context
, CI
, true, E
);
4480 AA
->setPackExpansion(IsPackExpansion
);
4485 // FIXME: Cache the number on the AL object?
4486 llvm::APSInt Alignment
;
4487 ExprResult ICE
= VerifyIntegerConstantExpression(
4488 E
, &Alignment
, diag::err_aligned_attribute_argument_not_int
);
4489 if (ICE
.isInvalid())
4492 uint64_t MaximumAlignment
= Sema::MaximumAlignment
;
4493 if (Context
.getTargetInfo().getTriple().isOSBinFormatCOFF())
4494 MaximumAlignment
= std::min(MaximumAlignment
, uint64_t(8192));
4495 if (Alignment
> MaximumAlignment
) {
4496 Diag(AttrLoc
, diag::err_attribute_aligned_too_great
)
4497 << MaximumAlignment
<< E
->getSourceRange();
4501 uint64_t AlignVal
= Alignment
.getZExtValue();
4502 // C++11 [dcl.align]p2:
4503 // -- if the constant expression evaluates to zero, the alignment
4504 // specifier shall have no effect
4506 // An alignment specification of zero has no effect.
4507 if (!(TmpAttr
.isAlignas() && !Alignment
)) {
4508 if (!llvm::isPowerOf2_64(AlignVal
)) {
4509 Diag(AttrLoc
, diag::err_alignment_not_power_of_two
)
4510 << E
->getSourceRange();
4515 const auto *VD
= dyn_cast
<VarDecl
>(D
);
4517 unsigned MaxTLSAlign
=
4518 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getMaxTLSAlign())
4520 if (MaxTLSAlign
&& AlignVal
> MaxTLSAlign
&&
4521 VD
->getTLSKind() != VarDecl::TLS_None
) {
4522 Diag(VD
->getLocation(), diag::err_tls_var_aligned_over_maximum
)
4523 << (unsigned)AlignVal
<< VD
<< MaxTLSAlign
;
4528 // On AIX, an aligned attribute can not decrease the alignment when applied
4529 // to a variable declaration with vector type.
4530 if (VD
&& Context
.getTargetInfo().getTriple().isOSAIX()) {
4531 const Type
*Ty
= VD
->getType().getTypePtr();
4532 if (Ty
->isVectorType() && AlignVal
< 16) {
4533 Diag(VD
->getLocation(), diag::warn_aligned_attr_underaligned
)
4534 << VD
->getType() << 16;
4539 AlignedAttr
*AA
= ::new (Context
) AlignedAttr(Context
, CI
, true, ICE
.get());
4540 AA
->setPackExpansion(IsPackExpansion
);
4541 AA
->setCachedAlignmentValue(
4542 static_cast<unsigned>(AlignVal
* Context
.getCharWidth()));
4546 void Sema::AddAlignedAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
4547 TypeSourceInfo
*TS
, bool IsPackExpansion
) {
4548 AlignedAttr
TmpAttr(Context
, CI
, false, TS
);
4549 SourceLocation AttrLoc
= CI
.getLoc();
4551 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4552 if (TmpAttr
.isAlignas() &&
4553 validateAlignasAppliedType(*this, D
, TmpAttr
, AttrLoc
))
4556 if (TS
->getType()->isDependentType()) {
4557 // We can't support a dependent alignment on a non-dependent type,
4558 // because we have no way to model that a type is "type-dependent"
4559 // but not dependent in any other way.
4560 if (const auto *TND
= dyn_cast
<TypedefNameDecl
>(D
)) {
4561 if (!TND
->getUnderlyingType()->isDependentType()) {
4562 Diag(AttrLoc
, diag::err_alignment_dependent_typedef_name
)
4563 << TS
->getTypeLoc().getSourceRange();
4568 AlignedAttr
*AA
= ::new (Context
) AlignedAttr(Context
, CI
, false, TS
);
4569 AA
->setPackExpansion(IsPackExpansion
);
4574 const auto *VD
= dyn_cast
<VarDecl
>(D
);
4575 unsigned AlignVal
= TmpAttr
.getAlignment(Context
);
4576 // On AIX, an aligned attribute can not decrease the alignment when applied
4577 // to a variable declaration with vector type.
4578 if (VD
&& Context
.getTargetInfo().getTriple().isOSAIX()) {
4579 const Type
*Ty
= VD
->getType().getTypePtr();
4580 if (Ty
->isVectorType() &&
4581 Context
.toCharUnitsFromBits(AlignVal
).getQuantity() < 16) {
4582 Diag(VD
->getLocation(), diag::warn_aligned_attr_underaligned
)
4583 << VD
->getType() << 16;
4588 AlignedAttr
*AA
= ::new (Context
) AlignedAttr(Context
, CI
, false, TS
);
4589 AA
->setPackExpansion(IsPackExpansion
);
4590 AA
->setCachedAlignmentValue(AlignVal
);
4594 void Sema::CheckAlignasUnderalignment(Decl
*D
) {
4595 assert(D
->hasAttrs() && "no attributes on decl");
4597 QualType UnderlyingTy
, DiagTy
;
4598 if (const auto *VD
= dyn_cast
<ValueDecl
>(D
)) {
4599 UnderlyingTy
= DiagTy
= VD
->getType();
4601 UnderlyingTy
= DiagTy
= Context
.getTagDeclType(cast
<TagDecl
>(D
));
4602 if (const auto *ED
= dyn_cast
<EnumDecl
>(D
))
4603 UnderlyingTy
= ED
->getIntegerType();
4605 if (DiagTy
->isDependentType() || DiagTy
->isIncompleteType())
4608 // C++11 [dcl.align]p5, C11 6.7.5/4:
4609 // The combined effect of all alignment attributes in a declaration shall
4610 // not specify an alignment that is less strict than the alignment that
4611 // would otherwise be required for the entity being declared.
4612 AlignedAttr
*AlignasAttr
= nullptr;
4613 AlignedAttr
*LastAlignedAttr
= nullptr;
4615 for (auto *I
: D
->specific_attrs
<AlignedAttr
>()) {
4616 if (I
->isAlignmentDependent())
4620 Align
= std::max(Align
, I
->getAlignment(Context
));
4621 LastAlignedAttr
= I
;
4624 if (Align
&& DiagTy
->isSizelessType()) {
4625 Diag(LastAlignedAttr
->getLocation(), diag::err_attribute_sizeless_type
)
4626 << LastAlignedAttr
<< DiagTy
;
4627 } else if (AlignasAttr
&& Align
) {
4628 CharUnits RequestedAlign
= Context
.toCharUnitsFromBits(Align
);
4629 CharUnits NaturalAlign
= Context
.getTypeAlignInChars(UnderlyingTy
);
4630 if (NaturalAlign
> RequestedAlign
)
4631 Diag(AlignasAttr
->getLocation(), diag::err_alignas_underaligned
)
4632 << DiagTy
<< (unsigned)NaturalAlign
.getQuantity();
4636 bool Sema::checkMSInheritanceAttrOnDefinition(
4637 CXXRecordDecl
*RD
, SourceRange Range
, bool BestCase
,
4638 MSInheritanceModel ExplicitModel
) {
4639 assert(RD
->hasDefinition() && "RD has no definition!");
4641 // We may not have seen base specifiers or any virtual methods yet. We will
4642 // have to wait until the record is defined to catch any mismatches.
4643 if (!RD
->getDefinition()->isCompleteDefinition())
4646 // The unspecified model never matches what a definition could need.
4647 if (ExplicitModel
== MSInheritanceModel::Unspecified
)
4651 if (RD
->calculateInheritanceModel() == ExplicitModel
)
4654 if (RD
->calculateInheritanceModel() <= ExplicitModel
)
4658 Diag(Range
.getBegin(), diag::err_mismatched_ms_inheritance
)
4659 << 0 /*definition*/;
4660 Diag(RD
->getDefinition()->getLocation(), diag::note_defined_here
) << RD
;
4664 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4666 static void parseModeAttrArg(Sema
&S
, StringRef Str
, unsigned &DestWidth
,
4667 bool &IntegerMode
, bool &ComplexMode
,
4668 FloatModeKind
&ExplicitType
) {
4670 ComplexMode
= false;
4671 ExplicitType
= FloatModeKind::NoFloat
;
4672 switch (Str
.size()) {
4690 case 'K': // KFmode - IEEE quad precision (__float128)
4691 ExplicitType
= FloatModeKind::Float128
;
4692 DestWidth
= Str
[1] == 'I' ? 0 : 128;
4695 ExplicitType
= FloatModeKind::LongDouble
;
4699 ExplicitType
= FloatModeKind::Ibm128
;
4700 DestWidth
= Str
[1] == 'I' ? 0 : 128;
4703 if (Str
[1] == 'F') {
4704 IntegerMode
= false;
4705 } else if (Str
[1] == 'C') {
4706 IntegerMode
= false;
4708 } else if (Str
[1] != 'I') {
4713 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4714 // pointer on PIC16 and other embedded platforms.
4716 DestWidth
= S
.Context
.getTargetInfo().getRegisterWidth();
4717 else if (Str
== "byte")
4718 DestWidth
= S
.Context
.getTargetInfo().getCharWidth();
4721 if (Str
== "pointer")
4722 DestWidth
= S
.Context
.getTargetInfo().getPointerWidth(LangAS::Default
);
4725 if (Str
== "unwind_word")
4726 DestWidth
= S
.Context
.getTargetInfo().getUnwindWordWidth();
4731 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4734 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4735 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4736 /// HImode, not an intermediate pointer.
4737 static void handleModeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4738 // This attribute isn't documented, but glibc uses it. It changes
4739 // the width of an int or unsigned int to the specified size.
4740 if (!AL
.isArgIdent(0)) {
4741 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
4742 << AL
<< AANT_ArgumentIdentifier
;
4746 IdentifierInfo
*Name
= AL
.getArgAsIdent(0)->Ident
;
4748 S
.AddModeAttr(D
, AL
, Name
);
4751 void Sema::AddModeAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
4752 IdentifierInfo
*Name
, bool InInstantiation
) {
4753 StringRef Str
= Name
->getName();
4755 SourceLocation AttrLoc
= CI
.getLoc();
4757 unsigned DestWidth
= 0;
4758 bool IntegerMode
= true;
4759 bool ComplexMode
= false;
4760 FloatModeKind ExplicitType
= FloatModeKind::NoFloat
;
4761 llvm::APInt
VectorSize(64, 0);
4762 if (Str
.size() >= 4 && Str
[0] == 'V') {
4763 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4764 size_t StrSize
= Str
.size();
4765 size_t VectorStringLength
= 0;
4766 while ((VectorStringLength
+ 1) < StrSize
&&
4767 isdigit(Str
[VectorStringLength
+ 1]))
4768 ++VectorStringLength
;
4769 if (VectorStringLength
&&
4770 !Str
.substr(1, VectorStringLength
).getAsInteger(10, VectorSize
) &&
4771 VectorSize
.isPowerOf2()) {
4772 parseModeAttrArg(*this, Str
.substr(VectorStringLength
+ 1), DestWidth
,
4773 IntegerMode
, ComplexMode
, ExplicitType
);
4774 // Avoid duplicate warning from template instantiation.
4775 if (!InInstantiation
)
4776 Diag(AttrLoc
, diag::warn_vector_mode_deprecated
);
4783 parseModeAttrArg(*this, Str
, DestWidth
, IntegerMode
, ComplexMode
,
4786 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4787 // and friends, at least with glibc.
4788 // FIXME: Make sure floating-point mappings are accurate
4789 // FIXME: Support XF and TF types
4791 Diag(AttrLoc
, diag::err_machine_mode
) << 0 /*Unknown*/ << Name
;
4796 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
))
4797 OldTy
= TD
->getUnderlyingType();
4798 else if (const auto *ED
= dyn_cast
<EnumDecl
>(D
)) {
4799 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4800 // Try to get type from enum declaration, default to int.
4801 OldTy
= ED
->getIntegerType();
4803 OldTy
= Context
.IntTy
;
4805 OldTy
= cast
<ValueDecl
>(D
)->getType();
4807 if (OldTy
->isDependentType()) {
4808 D
->addAttr(::new (Context
) ModeAttr(Context
, CI
, Name
));
4812 // Base type can also be a vector type (see PR17453).
4813 // Distinguish between base type and base element type.
4814 QualType OldElemTy
= OldTy
;
4815 if (const auto *VT
= OldTy
->getAs
<VectorType
>())
4816 OldElemTy
= VT
->getElementType();
4818 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4819 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4820 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4821 if ((isa
<EnumDecl
>(D
) || OldElemTy
->getAs
<EnumType
>()) &&
4822 VectorSize
.getBoolValue()) {
4823 Diag(AttrLoc
, diag::err_enum_mode_vector_type
) << Name
<< CI
.getRange();
4826 bool IntegralOrAnyEnumType
= (OldElemTy
->isIntegralOrEnumerationType() &&
4827 !OldElemTy
->isBitIntType()) ||
4828 OldElemTy
->getAs
<EnumType
>();
4830 if (!OldElemTy
->getAs
<BuiltinType
>() && !OldElemTy
->isComplexType() &&
4831 !IntegralOrAnyEnumType
)
4832 Diag(AttrLoc
, diag::err_mode_not_primitive
);
4833 else if (IntegerMode
) {
4834 if (!IntegralOrAnyEnumType
)
4835 Diag(AttrLoc
, diag::err_mode_wrong_type
);
4836 } else if (ComplexMode
) {
4837 if (!OldElemTy
->isComplexType())
4838 Diag(AttrLoc
, diag::err_mode_wrong_type
);
4840 if (!OldElemTy
->isFloatingType())
4841 Diag(AttrLoc
, diag::err_mode_wrong_type
);
4847 NewElemTy
= Context
.getIntTypeForBitwidth(DestWidth
,
4848 OldElemTy
->isSignedIntegerType());
4850 NewElemTy
= Context
.getRealTypeForBitwidth(DestWidth
, ExplicitType
);
4852 if (NewElemTy
.isNull()) {
4853 Diag(AttrLoc
, diag::err_machine_mode
) << 1 /*Unsupported*/ << Name
;
4858 NewElemTy
= Context
.getComplexType(NewElemTy
);
4861 QualType NewTy
= NewElemTy
;
4862 if (VectorSize
.getBoolValue()) {
4863 NewTy
= Context
.getVectorType(NewTy
, VectorSize
.getZExtValue(),
4864 VectorKind::Generic
);
4865 } else if (const auto *OldVT
= OldTy
->getAs
<VectorType
>()) {
4866 // Complex machine mode does not support base vector types.
4868 Diag(AttrLoc
, diag::err_complex_mode_vector_type
);
4871 unsigned NumElements
= Context
.getTypeSize(OldElemTy
) *
4872 OldVT
->getNumElements() /
4873 Context
.getTypeSize(NewElemTy
);
4875 Context
.getVectorType(NewElemTy
, NumElements
, OldVT
->getVectorKind());
4878 if (NewTy
.isNull()) {
4879 Diag(AttrLoc
, diag::err_mode_wrong_type
);
4883 // Install the new type.
4884 if (auto *TD
= dyn_cast
<TypedefNameDecl
>(D
))
4885 TD
->setModedTypeSourceInfo(TD
->getTypeSourceInfo(), NewTy
);
4886 else if (auto *ED
= dyn_cast
<EnumDecl
>(D
))
4887 ED
->setIntegerType(NewTy
);
4889 cast
<ValueDecl
>(D
)->setType(NewTy
);
4891 D
->addAttr(::new (Context
) ModeAttr(Context
, CI
, Name
));
4894 static void handleNoDebugAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
4895 D
->addAttr(::new (S
.Context
) NoDebugAttr(S
.Context
, AL
));
4898 AlwaysInlineAttr
*Sema::mergeAlwaysInlineAttr(Decl
*D
,
4899 const AttributeCommonInfo
&CI
,
4900 const IdentifierInfo
*Ident
) {
4901 if (OptimizeNoneAttr
*Optnone
= D
->getAttr
<OptimizeNoneAttr
>()) {
4902 Diag(CI
.getLoc(), diag::warn_attribute_ignored
) << Ident
;
4903 Diag(Optnone
->getLocation(), diag::note_conflicting_attribute
);
4907 if (D
->hasAttr
<AlwaysInlineAttr
>())
4910 return ::new (Context
) AlwaysInlineAttr(Context
, CI
);
4913 InternalLinkageAttr
*Sema::mergeInternalLinkageAttr(Decl
*D
,
4914 const ParsedAttr
&AL
) {
4915 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
4916 // Attribute applies to Var but not any subclass of it (like ParmVar,
4917 // ImplicitParm or VarTemplateSpecialization).
4918 if (VD
->getKind() != Decl::Var
) {
4919 Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
4920 << AL
<< AL
.isRegularKeywordAttribute()
4921 << (getLangOpts().CPlusPlus
? ExpectedFunctionVariableOrClass
4922 : ExpectedVariableOrFunction
);
4925 // Attribute does not apply to non-static local variables.
4926 if (VD
->hasLocalStorage()) {
4927 Diag(VD
->getLocation(), diag::warn_internal_linkage_local_storage
);
4932 return ::new (Context
) InternalLinkageAttr(Context
, AL
);
4934 InternalLinkageAttr
*
4935 Sema::mergeInternalLinkageAttr(Decl
*D
, const InternalLinkageAttr
&AL
) {
4936 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
4937 // Attribute applies to Var but not any subclass of it (like ParmVar,
4938 // ImplicitParm or VarTemplateSpecialization).
4939 if (VD
->getKind() != Decl::Var
) {
4940 Diag(AL
.getLocation(), diag::warn_attribute_wrong_decl_type
)
4941 << &AL
<< AL
.isRegularKeywordAttribute()
4942 << (getLangOpts().CPlusPlus
? ExpectedFunctionVariableOrClass
4943 : ExpectedVariableOrFunction
);
4946 // Attribute does not apply to non-static local variables.
4947 if (VD
->hasLocalStorage()) {
4948 Diag(VD
->getLocation(), diag::warn_internal_linkage_local_storage
);
4953 return ::new (Context
) InternalLinkageAttr(Context
, AL
);
4956 MinSizeAttr
*Sema::mergeMinSizeAttr(Decl
*D
, const AttributeCommonInfo
&CI
) {
4957 if (OptimizeNoneAttr
*Optnone
= D
->getAttr
<OptimizeNoneAttr
>()) {
4958 Diag(CI
.getLoc(), diag::warn_attribute_ignored
) << "'minsize'";
4959 Diag(Optnone
->getLocation(), diag::note_conflicting_attribute
);
4963 if (D
->hasAttr
<MinSizeAttr
>())
4966 return ::new (Context
) MinSizeAttr(Context
, CI
);
4969 SwiftNameAttr
*Sema::mergeSwiftNameAttr(Decl
*D
, const SwiftNameAttr
&SNA
,
4971 if (const auto *PrevSNA
= D
->getAttr
<SwiftNameAttr
>()) {
4972 if (PrevSNA
->getName() != Name
&& !PrevSNA
->isImplicit()) {
4973 Diag(PrevSNA
->getLocation(), diag::err_attributes_are_not_compatible
)
4975 << (PrevSNA
->isRegularKeywordAttribute() ||
4976 SNA
.isRegularKeywordAttribute());
4977 Diag(SNA
.getLoc(), diag::note_conflicting_attribute
);
4980 D
->dropAttr
<SwiftNameAttr
>();
4982 return ::new (Context
) SwiftNameAttr(Context
, SNA
, Name
);
4985 OptimizeNoneAttr
*Sema::mergeOptimizeNoneAttr(Decl
*D
,
4986 const AttributeCommonInfo
&CI
) {
4987 if (AlwaysInlineAttr
*Inline
= D
->getAttr
<AlwaysInlineAttr
>()) {
4988 Diag(Inline
->getLocation(), diag::warn_attribute_ignored
) << Inline
;
4989 Diag(CI
.getLoc(), diag::note_conflicting_attribute
);
4990 D
->dropAttr
<AlwaysInlineAttr
>();
4992 if (MinSizeAttr
*MinSize
= D
->getAttr
<MinSizeAttr
>()) {
4993 Diag(MinSize
->getLocation(), diag::warn_attribute_ignored
) << MinSize
;
4994 Diag(CI
.getLoc(), diag::note_conflicting_attribute
);
4995 D
->dropAttr
<MinSizeAttr
>();
4998 if (D
->hasAttr
<OptimizeNoneAttr
>())
5001 return ::new (Context
) OptimizeNoneAttr(Context
, CI
);
5004 static void handleAlwaysInlineAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5005 if (AlwaysInlineAttr
*Inline
=
5006 S
.mergeAlwaysInlineAttr(D
, AL
, AL
.getAttrName()))
5010 static void handleMinSizeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5011 if (MinSizeAttr
*MinSize
= S
.mergeMinSizeAttr(D
, AL
))
5012 D
->addAttr(MinSize
);
5015 static void handleOptimizeNoneAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5016 if (OptimizeNoneAttr
*Optnone
= S
.mergeOptimizeNoneAttr(D
, AL
))
5017 D
->addAttr(Optnone
);
5020 static void handleConstantAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5021 const auto *VD
= cast
<VarDecl
>(D
);
5022 if (VD
->hasLocalStorage()) {
5023 S
.Diag(AL
.getLoc(), diag::err_cuda_nonstatic_constdev
);
5026 // constexpr variable may already get an implicit constant attr, which should
5027 // be replaced by the explicit constant attr.
5028 if (auto *A
= D
->getAttr
<CUDAConstantAttr
>()) {
5029 if (!A
->isImplicit())
5031 D
->dropAttr
<CUDAConstantAttr
>();
5033 D
->addAttr(::new (S
.Context
) CUDAConstantAttr(S
.Context
, AL
));
5036 static void handleSharedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5037 const auto *VD
= cast
<VarDecl
>(D
);
5038 // extern __shared__ is only allowed on arrays with no length (e.g.
5040 if (!S
.getLangOpts().GPURelocatableDeviceCode
&& VD
->hasExternalStorage() &&
5041 !isa
<IncompleteArrayType
>(VD
->getType())) {
5042 S
.Diag(AL
.getLoc(), diag::err_cuda_extern_shared
) << VD
;
5045 if (S
.getLangOpts().CUDA
&& VD
->hasLocalStorage() &&
5046 S
.CUDADiagIfHostCode(AL
.getLoc(), diag::err_cuda_host_shared
)
5047 << S
.CurrentCUDATarget())
5049 D
->addAttr(::new (S
.Context
) CUDASharedAttr(S
.Context
, AL
));
5052 static void handleGlobalAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5053 const auto *FD
= cast
<FunctionDecl
>(D
);
5054 if (!FD
->getReturnType()->isVoidType() &&
5055 !FD
->getReturnType()->getAs
<AutoType
>() &&
5056 !FD
->getReturnType()->isInstantiationDependentType()) {
5057 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
5058 S
.Diag(FD
->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return
)
5060 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "void")
5064 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
)) {
5065 if (Method
->isInstance()) {
5066 S
.Diag(Method
->getBeginLoc(), diag::err_kern_is_nonstatic_method
)
5070 S
.Diag(Method
->getBeginLoc(), diag::warn_kern_is_method
) << Method
;
5072 // Only warn for "inline" when compiling for host, to cut down on noise.
5073 if (FD
->isInlineSpecified() && !S
.getLangOpts().CUDAIsDevice
)
5074 S
.Diag(FD
->getBeginLoc(), diag::warn_kern_is_inline
) << FD
;
5076 if (AL
.getKind() == ParsedAttr::AT_NVPTXKernel
)
5077 D
->addAttr(::new (S
.Context
) NVPTXKernelAttr(S
.Context
, AL
));
5079 D
->addAttr(::new (S
.Context
) CUDAGlobalAttr(S
.Context
, AL
));
5080 // In host compilation the kernel is emitted as a stub function, which is
5081 // a helper function for launching the kernel. The instructions in the helper
5082 // function has nothing to do with the source code of the kernel. Do not emit
5083 // debug info for the stub function to avoid confusing the debugger.
5084 if (S
.LangOpts
.HIP
&& !S
.LangOpts
.CUDAIsDevice
)
5085 D
->addAttr(NoDebugAttr::CreateImplicit(S
.Context
));
5088 static void handleDeviceAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5089 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
5090 if (VD
->hasLocalStorage()) {
5091 S
.Diag(AL
.getLoc(), diag::err_cuda_nonstatic_constdev
);
5096 if (auto *A
= D
->getAttr
<CUDADeviceAttr
>()) {
5097 if (!A
->isImplicit())
5099 D
->dropAttr
<CUDADeviceAttr
>();
5101 D
->addAttr(::new (S
.Context
) CUDADeviceAttr(S
.Context
, AL
));
5104 static void handleManagedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5105 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
5106 if (VD
->hasLocalStorage()) {
5107 S
.Diag(AL
.getLoc(), diag::err_cuda_nonstatic_constdev
);
5111 if (!D
->hasAttr
<HIPManagedAttr
>())
5112 D
->addAttr(::new (S
.Context
) HIPManagedAttr(S
.Context
, AL
));
5113 if (!D
->hasAttr
<CUDADeviceAttr
>())
5114 D
->addAttr(CUDADeviceAttr::CreateImplicit(S
.Context
));
5117 static void handleGNUInlineAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5118 const auto *Fn
= cast
<FunctionDecl
>(D
);
5119 if (!Fn
->isInlineSpecified()) {
5120 S
.Diag(AL
.getLoc(), diag::warn_gnu_inline_attribute_requires_inline
);
5124 if (S
.LangOpts
.CPlusPlus
&& Fn
->getStorageClass() != SC_Extern
)
5125 S
.Diag(AL
.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern
);
5127 D
->addAttr(::new (S
.Context
) GNUInlineAttr(S
.Context
, AL
));
5130 static void handleCallConvAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5131 if (hasDeclarator(D
)) return;
5133 // Diagnostic is emitted elsewhere: here we store the (valid) AL
5134 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
5136 if (S
.CheckCallingConvAttr(AL
, CC
, /*FD*/ nullptr,
5137 S
.IdentifyCUDATarget(dyn_cast
<FunctionDecl
>(D
))))
5140 if (!isa
<ObjCMethodDecl
>(D
)) {
5141 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
5142 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunctionOrMethod
;
5146 switch (AL
.getKind()) {
5147 case ParsedAttr::AT_FastCall
:
5148 D
->addAttr(::new (S
.Context
) FastCallAttr(S
.Context
, AL
));
5150 case ParsedAttr::AT_StdCall
:
5151 D
->addAttr(::new (S
.Context
) StdCallAttr(S
.Context
, AL
));
5153 case ParsedAttr::AT_ThisCall
:
5154 D
->addAttr(::new (S
.Context
) ThisCallAttr(S
.Context
, AL
));
5156 case ParsedAttr::AT_CDecl
:
5157 D
->addAttr(::new (S
.Context
) CDeclAttr(S
.Context
, AL
));
5159 case ParsedAttr::AT_Pascal
:
5160 D
->addAttr(::new (S
.Context
) PascalAttr(S
.Context
, AL
));
5162 case ParsedAttr::AT_SwiftCall
:
5163 D
->addAttr(::new (S
.Context
) SwiftCallAttr(S
.Context
, AL
));
5165 case ParsedAttr::AT_SwiftAsyncCall
:
5166 D
->addAttr(::new (S
.Context
) SwiftAsyncCallAttr(S
.Context
, AL
));
5168 case ParsedAttr::AT_VectorCall
:
5169 D
->addAttr(::new (S
.Context
) VectorCallAttr(S
.Context
, AL
));
5171 case ParsedAttr::AT_MSABI
:
5172 D
->addAttr(::new (S
.Context
) MSABIAttr(S
.Context
, AL
));
5174 case ParsedAttr::AT_SysVABI
:
5175 D
->addAttr(::new (S
.Context
) SysVABIAttr(S
.Context
, AL
));
5177 case ParsedAttr::AT_RegCall
:
5178 D
->addAttr(::new (S
.Context
) RegCallAttr(S
.Context
, AL
));
5180 case ParsedAttr::AT_Pcs
: {
5181 PcsAttr::PCSType PCS
;
5184 PCS
= PcsAttr::AAPCS
;
5187 PCS
= PcsAttr::AAPCS_VFP
;
5190 llvm_unreachable("unexpected calling convention in pcs attribute");
5193 D
->addAttr(::new (S
.Context
) PcsAttr(S
.Context
, AL
, PCS
));
5196 case ParsedAttr::AT_AArch64VectorPcs
:
5197 D
->addAttr(::new (S
.Context
) AArch64VectorPcsAttr(S
.Context
, AL
));
5199 case ParsedAttr::AT_AArch64SVEPcs
:
5200 D
->addAttr(::new (S
.Context
) AArch64SVEPcsAttr(S
.Context
, AL
));
5202 case ParsedAttr::AT_AMDGPUKernelCall
:
5203 D
->addAttr(::new (S
.Context
) AMDGPUKernelCallAttr(S
.Context
, AL
));
5205 case ParsedAttr::AT_IntelOclBicc
:
5206 D
->addAttr(::new (S
.Context
) IntelOclBiccAttr(S
.Context
, AL
));
5208 case ParsedAttr::AT_PreserveMost
:
5209 D
->addAttr(::new (S
.Context
) PreserveMostAttr(S
.Context
, AL
));
5211 case ParsedAttr::AT_PreserveAll
:
5212 D
->addAttr(::new (S
.Context
) PreserveAllAttr(S
.Context
, AL
));
5214 case ParsedAttr::AT_M68kRTD
:
5215 D
->addAttr(::new (S
.Context
) M68kRTDAttr(S
.Context
, AL
));
5218 llvm_unreachable("unexpected attribute kind");
5222 static void handleSuppressAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5223 if (!AL
.checkAtLeastNumArgs(S
, 1))
5226 std::vector
<StringRef
> DiagnosticIdentifiers
;
5227 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
!= E
; ++I
) {
5230 if (!S
.checkStringLiteralArgumentAttr(AL
, I
, RuleName
, nullptr))
5233 // FIXME: Warn if the rule name is unknown. This is tricky because only
5234 // clang-tidy knows about available rules.
5235 DiagnosticIdentifiers
.push_back(RuleName
);
5237 D
->addAttr(::new (S
.Context
)
5238 SuppressAttr(S
.Context
, AL
, DiagnosticIdentifiers
.data(),
5239 DiagnosticIdentifiers
.size()));
5242 static void handleLifetimeCategoryAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5243 TypeSourceInfo
*DerefTypeLoc
= nullptr;
5245 if (AL
.hasParsedType()) {
5246 ParmType
= S
.GetTypeFromParser(AL
.getTypeArg(), &DerefTypeLoc
);
5248 unsigned SelectIdx
= ~0U;
5249 if (ParmType
->isReferenceType())
5251 else if (ParmType
->isArrayType())
5254 if (SelectIdx
!= ~0U) {
5255 S
.Diag(AL
.getLoc(), diag::err_attribute_invalid_argument
)
5261 // To check if earlier decl attributes do not conflict the newly parsed ones
5262 // we always add (and check) the attribute to the canonical decl. We need
5263 // to repeat the check for attribute mutual exclusion because we're attaching
5264 // all of the attributes to the canonical declaration rather than the current
5266 D
= D
->getCanonicalDecl();
5267 if (AL
.getKind() == ParsedAttr::AT_Owner
) {
5268 if (checkAttrMutualExclusion
<PointerAttr
>(S
, D
, AL
))
5270 if (const auto *OAttr
= D
->getAttr
<OwnerAttr
>()) {
5271 const Type
*ExistingDerefType
= OAttr
->getDerefTypeLoc()
5272 ? OAttr
->getDerefType().getTypePtr()
5274 if (ExistingDerefType
!= ParmType
.getTypePtrOrNull()) {
5275 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
5277 << (AL
.isRegularKeywordAttribute() ||
5278 OAttr
->isRegularKeywordAttribute());
5279 S
.Diag(OAttr
->getLocation(), diag::note_conflicting_attribute
);
5283 for (Decl
*Redecl
: D
->redecls()) {
5284 Redecl
->addAttr(::new (S
.Context
) OwnerAttr(S
.Context
, AL
, DerefTypeLoc
));
5287 if (checkAttrMutualExclusion
<OwnerAttr
>(S
, D
, AL
))
5289 if (const auto *PAttr
= D
->getAttr
<PointerAttr
>()) {
5290 const Type
*ExistingDerefType
= PAttr
->getDerefTypeLoc()
5291 ? PAttr
->getDerefType().getTypePtr()
5293 if (ExistingDerefType
!= ParmType
.getTypePtrOrNull()) {
5294 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
5296 << (AL
.isRegularKeywordAttribute() ||
5297 PAttr
->isRegularKeywordAttribute());
5298 S
.Diag(PAttr
->getLocation(), diag::note_conflicting_attribute
);
5302 for (Decl
*Redecl
: D
->redecls()) {
5303 Redecl
->addAttr(::new (S
.Context
)
5304 PointerAttr(S
.Context
, AL
, DerefTypeLoc
));
5309 static void handleRandomizeLayoutAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5310 if (checkAttrMutualExclusion
<NoRandomizeLayoutAttr
>(S
, D
, AL
))
5312 if (!D
->hasAttr
<RandomizeLayoutAttr
>())
5313 D
->addAttr(::new (S
.Context
) RandomizeLayoutAttr(S
.Context
, AL
));
5316 static void handleNoRandomizeLayoutAttr(Sema
&S
, Decl
*D
,
5317 const ParsedAttr
&AL
) {
5318 if (checkAttrMutualExclusion
<RandomizeLayoutAttr
>(S
, D
, AL
))
5320 if (!D
->hasAttr
<NoRandomizeLayoutAttr
>())
5321 D
->addAttr(::new (S
.Context
) NoRandomizeLayoutAttr(S
.Context
, AL
));
5324 bool Sema::CheckCallingConvAttr(const ParsedAttr
&Attrs
, CallingConv
&CC
,
5325 const FunctionDecl
*FD
,
5326 CUDAFunctionTarget CFT
) {
5327 if (Attrs
.isInvalid())
5330 if (Attrs
.hasProcessingCache()) {
5331 CC
= (CallingConv
) Attrs
.getProcessingCache();
5335 unsigned ReqArgs
= Attrs
.getKind() == ParsedAttr::AT_Pcs
? 1 : 0;
5336 if (!Attrs
.checkExactlyNumArgs(*this, ReqArgs
)) {
5341 // TODO: diagnose uses of these conventions on the wrong target.
5342 switch (Attrs
.getKind()) {
5343 case ParsedAttr::AT_CDecl
:
5346 case ParsedAttr::AT_FastCall
:
5347 CC
= CC_X86FastCall
;
5349 case ParsedAttr::AT_StdCall
:
5352 case ParsedAttr::AT_ThisCall
:
5353 CC
= CC_X86ThisCall
;
5355 case ParsedAttr::AT_Pascal
:
5358 case ParsedAttr::AT_SwiftCall
:
5361 case ParsedAttr::AT_SwiftAsyncCall
:
5364 case ParsedAttr::AT_VectorCall
:
5365 CC
= CC_X86VectorCall
;
5367 case ParsedAttr::AT_AArch64VectorPcs
:
5368 CC
= CC_AArch64VectorCall
;
5370 case ParsedAttr::AT_AArch64SVEPcs
:
5371 CC
= CC_AArch64SVEPCS
;
5373 case ParsedAttr::AT_AMDGPUKernelCall
:
5374 CC
= CC_AMDGPUKernelCall
;
5376 case ParsedAttr::AT_RegCall
:
5379 case ParsedAttr::AT_MSABI
:
5380 CC
= Context
.getTargetInfo().getTriple().isOSWindows() ? CC_C
:
5383 case ParsedAttr::AT_SysVABI
:
5384 CC
= Context
.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV
:
5387 case ParsedAttr::AT_Pcs
: {
5389 if (!checkStringLiteralArgumentAttr(Attrs
, 0, StrRef
)) {
5393 if (StrRef
== "aapcs") {
5396 } else if (StrRef
== "aapcs-vfp") {
5402 Diag(Attrs
.getLoc(), diag::err_invalid_pcs
);
5405 case ParsedAttr::AT_IntelOclBicc
:
5406 CC
= CC_IntelOclBicc
;
5408 case ParsedAttr::AT_PreserveMost
:
5409 CC
= CC_PreserveMost
;
5411 case ParsedAttr::AT_PreserveAll
:
5412 CC
= CC_PreserveAll
;
5414 case ParsedAttr::AT_M68kRTD
:
5417 default: llvm_unreachable("unexpected attribute kind");
5420 TargetInfo::CallingConvCheckResult A
= TargetInfo::CCCR_OK
;
5421 const TargetInfo
&TI
= Context
.getTargetInfo();
5422 // CUDA functions may have host and/or device attributes which indicate
5423 // their targeted execution environment, therefore the calling convention
5424 // of functions in CUDA should be checked against the target deduced based
5425 // on their host/device attributes.
5426 if (LangOpts
.CUDA
) {
5427 auto *Aux
= Context
.getAuxTargetInfo();
5428 assert(FD
|| CFT
!= CFT_InvalidTarget
);
5429 auto CudaTarget
= FD
? IdentifyCUDATarget(FD
) : CFT
;
5430 bool CheckHost
= false, CheckDevice
= false;
5431 switch (CudaTarget
) {
5432 case CFT_HostDevice
:
5443 case CFT_InvalidTarget
:
5444 llvm_unreachable("unexpected cuda target");
5446 auto *HostTI
= LangOpts
.CUDAIsDevice
? Aux
: &TI
;
5447 auto *DeviceTI
= LangOpts
.CUDAIsDevice
? &TI
: Aux
;
5448 if (CheckHost
&& HostTI
)
5449 A
= HostTI
->checkCallingConvention(CC
);
5450 if (A
== TargetInfo::CCCR_OK
&& CheckDevice
&& DeviceTI
)
5451 A
= DeviceTI
->checkCallingConvention(CC
);
5453 A
= TI
.checkCallingConvention(CC
);
5457 case TargetInfo::CCCR_OK
:
5460 case TargetInfo::CCCR_Ignore
:
5461 // Treat an ignored convention as if it was an explicit C calling convention
5462 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
5463 // that command line flags that change the default convention to
5464 // __vectorcall don't affect declarations marked __stdcall.
5468 case TargetInfo::CCCR_Error
:
5469 Diag(Attrs
.getLoc(), diag::error_cconv_unsupported
)
5470 << Attrs
<< (int)CallingConventionIgnoredReason::ForThisTarget
;
5473 case TargetInfo::CCCR_Warning
: {
5474 Diag(Attrs
.getLoc(), diag::warn_cconv_unsupported
)
5475 << Attrs
<< (int)CallingConventionIgnoredReason::ForThisTarget
;
5477 // This convention is not valid for the target. Use the default function or
5478 // method calling convention.
5479 bool IsCXXMethod
= false, IsVariadic
= false;
5481 IsCXXMethod
= FD
->isCXXInstanceMember();
5482 IsVariadic
= FD
->isVariadic();
5484 CC
= Context
.getDefaultCallingConvention(IsVariadic
, IsCXXMethod
);
5489 Attrs
.setProcessingCache((unsigned) CC
);
5493 /// Pointer-like types in the default address space.
5494 static bool isValidSwiftContextType(QualType Ty
) {
5495 if (!Ty
->hasPointerRepresentation())
5496 return Ty
->isDependentType();
5497 return Ty
->getPointeeType().getAddressSpace() == LangAS::Default
;
5500 /// Pointers and references in the default address space.
5501 static bool isValidSwiftIndirectResultType(QualType Ty
) {
5502 if (const auto *PtrType
= Ty
->getAs
<PointerType
>()) {
5503 Ty
= PtrType
->getPointeeType();
5504 } else if (const auto *RefType
= Ty
->getAs
<ReferenceType
>()) {
5505 Ty
= RefType
->getPointeeType();
5507 return Ty
->isDependentType();
5509 return Ty
.getAddressSpace() == LangAS::Default
;
5512 /// Pointers and references to pointers in the default address space.
5513 static bool isValidSwiftErrorResultType(QualType Ty
) {
5514 if (const auto *PtrType
= Ty
->getAs
<PointerType
>()) {
5515 Ty
= PtrType
->getPointeeType();
5516 } else if (const auto *RefType
= Ty
->getAs
<ReferenceType
>()) {
5517 Ty
= RefType
->getPointeeType();
5519 return Ty
->isDependentType();
5521 if (!Ty
.getQualifiers().empty())
5523 return isValidSwiftContextType(Ty
);
5526 void Sema::AddParameterABIAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
5529 QualType type
= cast
<ParmVarDecl
>(D
)->getType();
5531 if (auto existingAttr
= D
->getAttr
<ParameterABIAttr
>()) {
5532 if (existingAttr
->getABI() != abi
) {
5533 Diag(CI
.getLoc(), diag::err_attributes_are_not_compatible
)
5534 << getParameterABISpelling(abi
) << existingAttr
5535 << (CI
.isRegularKeywordAttribute() ||
5536 existingAttr
->isRegularKeywordAttribute());
5537 Diag(existingAttr
->getLocation(), diag::note_conflicting_attribute
);
5543 case ParameterABI::Ordinary
:
5544 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5546 case ParameterABI::SwiftContext
:
5547 if (!isValidSwiftContextType(type
)) {
5548 Diag(CI
.getLoc(), diag::err_swift_abi_parameter_wrong_type
)
5549 << getParameterABISpelling(abi
) << /*pointer to pointer */ 0 << type
;
5551 D
->addAttr(::new (Context
) SwiftContextAttr(Context
, CI
));
5554 case ParameterABI::SwiftAsyncContext
:
5555 if (!isValidSwiftContextType(type
)) {
5556 Diag(CI
.getLoc(), diag::err_swift_abi_parameter_wrong_type
)
5557 << getParameterABISpelling(abi
) << /*pointer to pointer */ 0 << type
;
5559 D
->addAttr(::new (Context
) SwiftAsyncContextAttr(Context
, CI
));
5562 case ParameterABI::SwiftErrorResult
:
5563 if (!isValidSwiftErrorResultType(type
)) {
5564 Diag(CI
.getLoc(), diag::err_swift_abi_parameter_wrong_type
)
5565 << getParameterABISpelling(abi
) << /*pointer to pointer */ 1 << type
;
5567 D
->addAttr(::new (Context
) SwiftErrorResultAttr(Context
, CI
));
5570 case ParameterABI::SwiftIndirectResult
:
5571 if (!isValidSwiftIndirectResultType(type
)) {
5572 Diag(CI
.getLoc(), diag::err_swift_abi_parameter_wrong_type
)
5573 << getParameterABISpelling(abi
) << /*pointer*/ 0 << type
;
5575 D
->addAttr(::new (Context
) SwiftIndirectResultAttr(Context
, CI
));
5578 llvm_unreachable("bad parameter ABI attribute");
5581 /// Checks a regparm attribute, returning true if it is ill-formed and
5582 /// otherwise setting numParams to the appropriate value.
5583 bool Sema::CheckRegparmAttr(const ParsedAttr
&AL
, unsigned &numParams
) {
5587 if (!AL
.checkExactlyNumArgs(*this, 1)) {
5593 Expr
*NumParamsExpr
= AL
.getArgAsExpr(0);
5594 if (!checkUInt32Argument(*this, AL
, NumParamsExpr
, NP
)) {
5599 if (Context
.getTargetInfo().getRegParmMax() == 0) {
5600 Diag(AL
.getLoc(), diag::err_attribute_regparm_wrong_platform
)
5601 << NumParamsExpr
->getSourceRange();
5607 if (numParams
> Context
.getTargetInfo().getRegParmMax()) {
5608 Diag(AL
.getLoc(), diag::err_attribute_regparm_invalid_number
)
5609 << Context
.getTargetInfo().getRegParmMax() << NumParamsExpr
->getSourceRange();
5617 // Helper to get CudaArch.
5618 static CudaArch
getCudaArch(const TargetInfo
&TI
) {
5619 if (!TI
.getTriple().isNVPTX())
5620 llvm_unreachable("getCudaArch is only valid for NVPTX triple");
5621 auto &TO
= TI
.getTargetOpts();
5622 return StringToCudaArch(TO
.CPU
);
5625 // Checks whether an argument of launch_bounds attribute is
5626 // acceptable, performs implicit conversion to Rvalue, and returns
5627 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5628 // and may output an error.
5629 static Expr
*makeLaunchBoundsArgExpr(Sema
&S
, Expr
*E
,
5630 const CUDALaunchBoundsAttr
&AL
,
5631 const unsigned Idx
) {
5632 if (S
.DiagnoseUnexpandedParameterPack(E
))
5635 // Accept template arguments for now as they depend on something else.
5636 // We'll get to check them when they eventually get instantiated.
5637 if (E
->isValueDependent())
5640 std::optional
<llvm::APSInt
> I
= llvm::APSInt(64);
5641 if (!(I
= E
->getIntegerConstantExpr(S
.Context
))) {
5642 S
.Diag(E
->getExprLoc(), diag::err_attribute_argument_n_type
)
5643 << &AL
<< Idx
<< AANT_ArgumentIntegerConstant
<< E
->getSourceRange();
5646 // Make sure we can fit it in 32 bits.
5647 if (!I
->isIntN(32)) {
5648 S
.Diag(E
->getExprLoc(), diag::err_ice_too_large
)
5649 << toString(*I
, 10, false) << 32 << /* Unsigned */ 1;
5653 S
.Diag(E
->getExprLoc(), diag::warn_attribute_argument_n_negative
)
5654 << &AL
<< Idx
<< E
->getSourceRange();
5656 // We may need to perform implicit conversion of the argument.
5657 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
5658 S
.Context
, S
.Context
.getConstType(S
.Context
.IntTy
), /*consume*/ false);
5659 ExprResult ValArg
= S
.PerformCopyInitialization(Entity
, SourceLocation(), E
);
5660 assert(!ValArg
.isInvalid() &&
5661 "Unexpected PerformCopyInitialization() failure.");
5663 return ValArg
.getAs
<Expr
>();
5666 CUDALaunchBoundsAttr
*
5667 Sema::CreateLaunchBoundsAttr(const AttributeCommonInfo
&CI
, Expr
*MaxThreads
,
5668 Expr
*MinBlocks
, Expr
*MaxBlocks
) {
5669 CUDALaunchBoundsAttr
TmpAttr(Context
, CI
, MaxThreads
, MinBlocks
, MaxBlocks
);
5670 MaxThreads
= makeLaunchBoundsArgExpr(*this, MaxThreads
, TmpAttr
, 0);
5675 MinBlocks
= makeLaunchBoundsArgExpr(*this, MinBlocks
, TmpAttr
, 1);
5681 // '.maxclusterrank' ptx directive requires .target sm_90 or higher.
5682 auto SM
= getCudaArch(Context
.getTargetInfo());
5683 if (SM
== CudaArch::UNKNOWN
|| SM
< CudaArch::SM_90
) {
5684 Diag(MaxBlocks
->getBeginLoc(), diag::warn_cuda_maxclusterrank_sm_90
)
5685 << CudaArchToString(SM
) << CI
<< MaxBlocks
->getSourceRange();
5686 // Ignore it by setting MaxBlocks to null;
5687 MaxBlocks
= nullptr;
5689 MaxBlocks
= makeLaunchBoundsArgExpr(*this, MaxBlocks
, TmpAttr
, 2);
5695 return ::new (Context
)
5696 CUDALaunchBoundsAttr(Context
, CI
, MaxThreads
, MinBlocks
, MaxBlocks
);
5699 void Sema::AddLaunchBoundsAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
5700 Expr
*MaxThreads
, Expr
*MinBlocks
,
5702 if (auto *Attr
= CreateLaunchBoundsAttr(CI
, MaxThreads
, MinBlocks
, MaxBlocks
))
5706 static void handleLaunchBoundsAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5707 if (!AL
.checkAtLeastNumArgs(S
, 1) || !AL
.checkAtMostNumArgs(S
, 3))
5710 S
.AddLaunchBoundsAttr(D
, AL
, AL
.getArgAsExpr(0),
5711 AL
.getNumArgs() > 1 ? AL
.getArgAsExpr(1) : nullptr,
5712 AL
.getNumArgs() > 2 ? AL
.getArgAsExpr(2) : nullptr);
5715 static void handleArgumentWithTypeTagAttr(Sema
&S
, Decl
*D
,
5716 const ParsedAttr
&AL
) {
5717 if (!AL
.isArgIdent(0)) {
5718 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
5719 << AL
<< /* arg num = */ 1 << AANT_ArgumentIdentifier
;
5723 ParamIdx ArgumentIdx
;
5724 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, 2, AL
.getArgAsExpr(1),
5728 ParamIdx TypeTagIdx
;
5729 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, 3, AL
.getArgAsExpr(2),
5733 bool IsPointer
= AL
.getAttrName()->getName() == "pointer_with_type_tag";
5735 // Ensure that buffer has a pointer type.
5736 unsigned ArgumentIdxAST
= ArgumentIdx
.getASTIndex();
5737 if (ArgumentIdxAST
>= getFunctionOrMethodNumParams(D
) ||
5738 !getFunctionOrMethodParamType(D
, ArgumentIdxAST
)->isPointerType())
5739 S
.Diag(AL
.getLoc(), diag::err_attribute_pointers_only
) << AL
<< 0;
5742 D
->addAttr(::new (S
.Context
) ArgumentWithTypeTagAttr(
5743 S
.Context
, AL
, AL
.getArgAsIdent(0)->Ident
, ArgumentIdx
, TypeTagIdx
,
5747 static void handleTypeTagForDatatypeAttr(Sema
&S
, Decl
*D
,
5748 const ParsedAttr
&AL
) {
5749 if (!AL
.isArgIdent(0)) {
5750 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
5751 << AL
<< 1 << AANT_ArgumentIdentifier
;
5755 if (!AL
.checkExactlyNumArgs(S
, 1))
5758 if (!isa
<VarDecl
>(D
)) {
5759 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_decl_type
)
5760 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedVariable
;
5764 IdentifierInfo
*PointerKind
= AL
.getArgAsIdent(0)->Ident
;
5765 TypeSourceInfo
*MatchingCTypeLoc
= nullptr;
5766 S
.GetTypeFromParser(AL
.getMatchingCType(), &MatchingCTypeLoc
);
5767 assert(MatchingCTypeLoc
&& "no type source info for attribute argument");
5769 D
->addAttr(::new (S
.Context
) TypeTagForDatatypeAttr(
5770 S
.Context
, AL
, PointerKind
, MatchingCTypeLoc
, AL
.getLayoutCompatible(),
5771 AL
.getMustBeNull()));
5774 static void handleXRayLogArgsAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5777 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, 1, AL
.getArgAsExpr(0),
5779 true /* CanIndexImplicitThis */))
5782 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5783 D
->addAttr(::new (S
.Context
)
5784 XRayLogArgsAttr(S
.Context
, AL
, ArgCount
.getSourceIndex()));
5787 static void handlePatchableFunctionEntryAttr(Sema
&S
, Decl
*D
,
5788 const ParsedAttr
&AL
) {
5789 uint32_t Count
= 0, Offset
= 0;
5790 if (!checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(0), Count
, 0, true))
5792 if (AL
.getNumArgs() == 2) {
5793 Expr
*Arg
= AL
.getArgAsExpr(1);
5794 if (!checkUInt32Argument(S
, AL
, Arg
, Offset
, 1, true))
5796 if (Count
< Offset
) {
5797 S
.Diag(getAttrLoc(AL
), diag::err_attribute_argument_out_of_range
)
5798 << &AL
<< 0 << Count
<< Arg
->getBeginLoc();
5802 D
->addAttr(::new (S
.Context
)
5803 PatchableFunctionEntryAttr(S
.Context
, AL
, Count
, Offset
));
5807 struct IntrinToName
{
5812 } // unnamed namespace
5814 static bool ArmBuiltinAliasValid(unsigned BuiltinID
, StringRef AliasName
,
5815 ArrayRef
<IntrinToName
> Map
,
5816 const char *IntrinNames
) {
5817 if (AliasName
.startswith("__arm_"))
5818 AliasName
= AliasName
.substr(6);
5819 const IntrinToName
*It
=
5820 llvm::lower_bound(Map
, BuiltinID
, [](const IntrinToName
&L
, unsigned Id
) {
5823 if (It
== Map
.end() || It
->Id
!= BuiltinID
)
5825 StringRef
FullName(&IntrinNames
[It
->FullName
]);
5826 if (AliasName
== FullName
)
5828 if (It
->ShortName
== -1)
5830 StringRef
ShortName(&IntrinNames
[It
->ShortName
]);
5831 return AliasName
== ShortName
;
5834 static bool ArmMveAliasValid(unsigned BuiltinID
, StringRef AliasName
) {
5835 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5836 // The included file defines:
5837 // - ArrayRef<IntrinToName> Map
5838 // - const char IntrinNames[]
5839 return ArmBuiltinAliasValid(BuiltinID
, AliasName
, Map
, IntrinNames
);
5842 static bool ArmCdeAliasValid(unsigned BuiltinID
, StringRef AliasName
) {
5843 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5844 return ArmBuiltinAliasValid(BuiltinID
, AliasName
, Map
, IntrinNames
);
5847 static bool ArmSveAliasValid(ASTContext
&Context
, unsigned BuiltinID
,
5848 StringRef AliasName
) {
5849 if (Context
.BuiltinInfo
.isAuxBuiltinID(BuiltinID
))
5850 BuiltinID
= Context
.BuiltinInfo
.getAuxBuiltinID(BuiltinID
);
5851 return BuiltinID
>= AArch64::FirstSVEBuiltin
&&
5852 BuiltinID
<= AArch64::LastSVEBuiltin
;
5855 static bool ArmSmeAliasValid(ASTContext
&Context
, unsigned BuiltinID
,
5856 StringRef AliasName
) {
5857 if (Context
.BuiltinInfo
.isAuxBuiltinID(BuiltinID
))
5858 BuiltinID
= Context
.BuiltinInfo
.getAuxBuiltinID(BuiltinID
);
5859 return BuiltinID
>= AArch64::FirstSMEBuiltin
&&
5860 BuiltinID
<= AArch64::LastSMEBuiltin
;
5863 static void handleArmBuiltinAliasAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5864 if (!AL
.isArgIdent(0)) {
5865 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
5866 << AL
<< 1 << AANT_ArgumentIdentifier
;
5870 IdentifierInfo
*Ident
= AL
.getArgAsIdent(0)->Ident
;
5871 unsigned BuiltinID
= Ident
->getBuiltinID();
5872 StringRef AliasName
= cast
<FunctionDecl
>(D
)->getIdentifier()->getName();
5874 bool IsAArch64
= S
.Context
.getTargetInfo().getTriple().isAArch64();
5875 if ((IsAArch64
&& !ArmSveAliasValid(S
.Context
, BuiltinID
, AliasName
) &&
5876 !ArmSmeAliasValid(S
.Context
, BuiltinID
, AliasName
)) ||
5877 (!IsAArch64
&& !ArmMveAliasValid(BuiltinID
, AliasName
) &&
5878 !ArmCdeAliasValid(BuiltinID
, AliasName
))) {
5879 S
.Diag(AL
.getLoc(), diag::err_attribute_arm_builtin_alias
);
5883 D
->addAttr(::new (S
.Context
) ArmBuiltinAliasAttr(S
.Context
, AL
, Ident
));
5886 static bool RISCVAliasValid(unsigned BuiltinID
, StringRef AliasName
) {
5887 return BuiltinID
>= RISCV::FirstRVVBuiltin
&&
5888 BuiltinID
<= RISCV::LastRVVBuiltin
;
5891 static void handleBuiltinAliasAttr(Sema
&S
, Decl
*D
,
5892 const ParsedAttr
&AL
) {
5893 if (!AL
.isArgIdent(0)) {
5894 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
5895 << AL
<< 1 << AANT_ArgumentIdentifier
;
5899 IdentifierInfo
*Ident
= AL
.getArgAsIdent(0)->Ident
;
5900 unsigned BuiltinID
= Ident
->getBuiltinID();
5901 StringRef AliasName
= cast
<FunctionDecl
>(D
)->getIdentifier()->getName();
5903 bool IsAArch64
= S
.Context
.getTargetInfo().getTriple().isAArch64();
5904 bool IsARM
= S
.Context
.getTargetInfo().getTriple().isARM();
5905 bool IsRISCV
= S
.Context
.getTargetInfo().getTriple().isRISCV();
5906 bool IsHLSL
= S
.Context
.getLangOpts().HLSL
;
5907 if ((IsAArch64
&& !ArmSveAliasValid(S
.Context
, BuiltinID
, AliasName
)) ||
5908 (IsARM
&& !ArmMveAliasValid(BuiltinID
, AliasName
) &&
5909 !ArmCdeAliasValid(BuiltinID
, AliasName
)) ||
5910 (IsRISCV
&& !RISCVAliasValid(BuiltinID
, AliasName
)) ||
5911 (!IsAArch64
&& !IsARM
&& !IsRISCV
&& !IsHLSL
)) {
5912 S
.Diag(AL
.getLoc(), diag::err_attribute_builtin_alias
) << AL
;
5916 D
->addAttr(::new (S
.Context
) BuiltinAliasAttr(S
.Context
, AL
, Ident
));
5919 static void handlePreferredTypeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
5920 if (!AL
.hasParsedType()) {
5921 S
.Diag(AL
.getLoc(), diag::err_attribute_wrong_number_arguments
) << AL
<< 1;
5925 TypeSourceInfo
*ParmTSI
= nullptr;
5926 QualType QT
= S
.GetTypeFromParser(AL
.getTypeArg(), &ParmTSI
);
5927 assert(ParmTSI
&& "no type source info for attribute argument");
5928 S
.RequireCompleteType(ParmTSI
->getTypeLoc().getBeginLoc(), QT
,
5929 diag::err_incomplete_type
);
5931 if (QT
->isEnumeralType()) {
5932 auto IsCorrespondingType
= [&](QualType LHS
, QualType RHS
) {
5934 if (LHS
->isSignedIntegerType())
5935 return LHS
== S
.getASTContext().getCorrespondingSignedType(RHS
);
5936 return LHS
== S
.getASTContext().getCorrespondingUnsignedType(RHS
);
5938 QualType BitfieldType
=
5939 cast
<FieldDecl
>(D
)->getType()->getCanonicalTypeUnqualified();
5940 QualType EnumUnderlyingType
= QT
->getAs
<EnumType
>()
5943 ->getCanonicalTypeUnqualified();
5944 if (EnumUnderlyingType
!= BitfieldType
&&
5945 !IsCorrespondingType(EnumUnderlyingType
, BitfieldType
)) {
5946 S
.Diag(ParmTSI
->getTypeLoc().getBeginLoc(),
5947 diag::warn_attribute_underlying_type_mismatch
)
5948 << EnumUnderlyingType
<< QT
<< BitfieldType
;
5953 D
->addAttr(::new (S
.Context
) PreferredTypeAttr(S
.Context
, AL
, ParmTSI
));
5956 //===----------------------------------------------------------------------===//
5957 // Checker-specific attribute handlers.
5958 //===----------------------------------------------------------------------===//
5959 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT
) {
5960 return QT
->isDependentType() || QT
->isObjCRetainableType();
5963 static bool isValidSubjectOfNSAttribute(QualType QT
) {
5964 return QT
->isDependentType() || QT
->isObjCObjectPointerType() ||
5965 QT
->isObjCNSObjectType();
5968 static bool isValidSubjectOfCFAttribute(QualType QT
) {
5969 return QT
->isDependentType() || QT
->isPointerType() ||
5970 isValidSubjectOfNSAttribute(QT
);
5973 static bool isValidSubjectOfOSAttribute(QualType QT
) {
5974 if (QT
->isDependentType())
5976 QualType PT
= QT
->getPointeeType();
5977 return !PT
.isNull() && PT
->getAsCXXRecordDecl() != nullptr;
5980 void Sema::AddXConsumedAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
5981 RetainOwnershipKind K
,
5982 bool IsTemplateInstantiation
) {
5983 ValueDecl
*VD
= cast
<ValueDecl
>(D
);
5985 case RetainOwnershipKind::OS
:
5986 handleSimpleAttributeOrDiagnose
<OSConsumedAttr
>(
5987 *this, VD
, CI
, isValidSubjectOfOSAttribute(VD
->getType()),
5988 diag::warn_ns_attribute_wrong_parameter_type
,
5989 /*ExtraArgs=*/CI
.getRange(), "os_consumed", /*pointers*/ 1);
5991 case RetainOwnershipKind::NS
:
5992 handleSimpleAttributeOrDiagnose
<NSConsumedAttr
>(
5993 *this, VD
, CI
, isValidSubjectOfNSAttribute(VD
->getType()),
5995 // These attributes are normally just advisory, but in ARC, ns_consumed
5996 // is significant. Allow non-dependent code to contain inappropriate
5997 // attributes even in ARC, but require template instantiations to be
5998 // set up correctly.
5999 ((IsTemplateInstantiation
&& getLangOpts().ObjCAutoRefCount
)
6000 ? diag::err_ns_attribute_wrong_parameter_type
6001 : diag::warn_ns_attribute_wrong_parameter_type
),
6002 /*ExtraArgs=*/CI
.getRange(), "ns_consumed", /*objc pointers*/ 0);
6004 case RetainOwnershipKind::CF
:
6005 handleSimpleAttributeOrDiagnose
<CFConsumedAttr
>(
6006 *this, VD
, CI
, isValidSubjectOfCFAttribute(VD
->getType()),
6007 diag::warn_ns_attribute_wrong_parameter_type
,
6008 /*ExtraArgs=*/CI
.getRange(), "cf_consumed", /*pointers*/ 1);
6013 static Sema::RetainOwnershipKind
6014 parsedAttrToRetainOwnershipKind(const ParsedAttr
&AL
) {
6015 switch (AL
.getKind()) {
6016 case ParsedAttr::AT_CFConsumed
:
6017 case ParsedAttr::AT_CFReturnsRetained
:
6018 case ParsedAttr::AT_CFReturnsNotRetained
:
6019 return Sema::RetainOwnershipKind::CF
;
6020 case ParsedAttr::AT_OSConsumesThis
:
6021 case ParsedAttr::AT_OSConsumed
:
6022 case ParsedAttr::AT_OSReturnsRetained
:
6023 case ParsedAttr::AT_OSReturnsNotRetained
:
6024 case ParsedAttr::AT_OSReturnsRetainedOnZero
:
6025 case ParsedAttr::AT_OSReturnsRetainedOnNonZero
:
6026 return Sema::RetainOwnershipKind::OS
;
6027 case ParsedAttr::AT_NSConsumesSelf
:
6028 case ParsedAttr::AT_NSConsumed
:
6029 case ParsedAttr::AT_NSReturnsRetained
:
6030 case ParsedAttr::AT_NSReturnsNotRetained
:
6031 case ParsedAttr::AT_NSReturnsAutoreleased
:
6032 return Sema::RetainOwnershipKind::NS
;
6034 llvm_unreachable("Wrong argument supplied");
6038 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc
, QualType QT
) {
6039 if (isValidSubjectOfNSReturnsRetainedAttribute(QT
))
6042 Diag(Loc
, diag::warn_ns_attribute_wrong_return_type
)
6043 << "'ns_returns_retained'" << 0 << 0;
6047 /// \return whether the parameter is a pointer to OSObject pointer.
6048 static bool isValidOSObjectOutParameter(const Decl
*D
) {
6049 const auto *PVD
= dyn_cast
<ParmVarDecl
>(D
);
6052 QualType QT
= PVD
->getType();
6053 QualType PT
= QT
->getPointeeType();
6054 return !PT
.isNull() && isValidSubjectOfOSAttribute(PT
);
6057 static void handleXReturnsXRetainedAttr(Sema
&S
, Decl
*D
,
6058 const ParsedAttr
&AL
) {
6059 QualType ReturnType
;
6060 Sema::RetainOwnershipKind K
= parsedAttrToRetainOwnershipKind(AL
);
6062 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
6063 ReturnType
= MD
->getReturnType();
6064 } else if (S
.getLangOpts().ObjCAutoRefCount
&& hasDeclarator(D
) &&
6065 (AL
.getKind() == ParsedAttr::AT_NSReturnsRetained
)) {
6066 return; // ignore: was handled as a type attribute
6067 } else if (const auto *PD
= dyn_cast
<ObjCPropertyDecl
>(D
)) {
6068 ReturnType
= PD
->getType();
6069 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
6070 ReturnType
= FD
->getReturnType();
6071 } else if (const auto *Param
= dyn_cast
<ParmVarDecl
>(D
)) {
6072 // Attributes on parameters are used for out-parameters,
6073 // passed as pointers-to-pointers.
6074 unsigned DiagID
= K
== Sema::RetainOwnershipKind::CF
6075 ? /*pointer-to-CF-pointer*/2
6076 : /*pointer-to-OSObject-pointer*/3;
6077 ReturnType
= Param
->getType()->getPointeeType();
6078 if (ReturnType
.isNull()) {
6079 S
.Diag(D
->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type
)
6080 << AL
<< DiagID
<< AL
.getRange();
6083 } else if (AL
.isUsedAsTypeAttr()) {
6086 AttributeDeclKind ExpectedDeclKind
;
6087 switch (AL
.getKind()) {
6088 default: llvm_unreachable("invalid ownership attribute");
6089 case ParsedAttr::AT_NSReturnsRetained
:
6090 case ParsedAttr::AT_NSReturnsAutoreleased
:
6091 case ParsedAttr::AT_NSReturnsNotRetained
:
6092 ExpectedDeclKind
= ExpectedFunctionOrMethod
;
6095 case ParsedAttr::AT_OSReturnsRetained
:
6096 case ParsedAttr::AT_OSReturnsNotRetained
:
6097 case ParsedAttr::AT_CFReturnsRetained
:
6098 case ParsedAttr::AT_CFReturnsNotRetained
:
6099 ExpectedDeclKind
= ExpectedFunctionMethodOrParameter
;
6102 S
.Diag(D
->getBeginLoc(), diag::warn_attribute_wrong_decl_type
)
6103 << AL
.getRange() << AL
<< AL
.isRegularKeywordAttribute()
6104 << ExpectedDeclKind
;
6110 unsigned ParmDiagID
= 2; // Pointer-to-CF-pointer
6111 switch (AL
.getKind()) {
6112 default: llvm_unreachable("invalid ownership attribute");
6113 case ParsedAttr::AT_NSReturnsRetained
:
6114 TypeOK
= isValidSubjectOfNSReturnsRetainedAttribute(ReturnType
);
6118 case ParsedAttr::AT_NSReturnsAutoreleased
:
6119 case ParsedAttr::AT_NSReturnsNotRetained
:
6120 TypeOK
= isValidSubjectOfNSAttribute(ReturnType
);
6124 case ParsedAttr::AT_CFReturnsRetained
:
6125 case ParsedAttr::AT_CFReturnsNotRetained
:
6126 TypeOK
= isValidSubjectOfCFAttribute(ReturnType
);
6130 case ParsedAttr::AT_OSReturnsRetained
:
6131 case ParsedAttr::AT_OSReturnsNotRetained
:
6132 TypeOK
= isValidSubjectOfOSAttribute(ReturnType
);
6134 ParmDiagID
= 3; // Pointer-to-OSObject-pointer
6139 if (AL
.isUsedAsTypeAttr())
6142 if (isa
<ParmVarDecl
>(D
)) {
6143 S
.Diag(D
->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type
)
6144 << AL
<< ParmDiagID
<< AL
.getRange();
6146 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
6151 } SubjectKind
= Function
;
6152 if (isa
<ObjCMethodDecl
>(D
))
6153 SubjectKind
= Method
;
6154 else if (isa
<ObjCPropertyDecl
>(D
))
6155 SubjectKind
= Property
;
6156 S
.Diag(D
->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type
)
6157 << AL
<< SubjectKind
<< Cf
<< AL
.getRange();
6162 switch (AL
.getKind()) {
6164 llvm_unreachable("invalid ownership attribute");
6165 case ParsedAttr::AT_NSReturnsAutoreleased
:
6166 handleSimpleAttribute
<NSReturnsAutoreleasedAttr
>(S
, D
, AL
);
6168 case ParsedAttr::AT_CFReturnsNotRetained
:
6169 handleSimpleAttribute
<CFReturnsNotRetainedAttr
>(S
, D
, AL
);
6171 case ParsedAttr::AT_NSReturnsNotRetained
:
6172 handleSimpleAttribute
<NSReturnsNotRetainedAttr
>(S
, D
, AL
);
6174 case ParsedAttr::AT_CFReturnsRetained
:
6175 handleSimpleAttribute
<CFReturnsRetainedAttr
>(S
, D
, AL
);
6177 case ParsedAttr::AT_NSReturnsRetained
:
6178 handleSimpleAttribute
<NSReturnsRetainedAttr
>(S
, D
, AL
);
6180 case ParsedAttr::AT_OSReturnsRetained
:
6181 handleSimpleAttribute
<OSReturnsRetainedAttr
>(S
, D
, AL
);
6183 case ParsedAttr::AT_OSReturnsNotRetained
:
6184 handleSimpleAttribute
<OSReturnsNotRetainedAttr
>(S
, D
, AL
);
6189 static void handleObjCReturnsInnerPointerAttr(Sema
&S
, Decl
*D
,
6190 const ParsedAttr
&Attrs
) {
6191 const int EP_ObjCMethod
= 1;
6192 const int EP_ObjCProperty
= 2;
6194 SourceLocation loc
= Attrs
.getLoc();
6195 QualType resultType
;
6196 if (isa
<ObjCMethodDecl
>(D
))
6197 resultType
= cast
<ObjCMethodDecl
>(D
)->getReturnType();
6199 resultType
= cast
<ObjCPropertyDecl
>(D
)->getType();
6201 if (!resultType
->isReferenceType() &&
6202 (!resultType
->isPointerType() || resultType
->isObjCRetainableType())) {
6203 S
.Diag(D
->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type
)
6204 << SourceRange(loc
) << Attrs
6205 << (isa
<ObjCMethodDecl
>(D
) ? EP_ObjCMethod
: EP_ObjCProperty
)
6206 << /*non-retainable pointer*/ 2;
6208 // Drop the attribute.
6212 D
->addAttr(::new (S
.Context
) ObjCReturnsInnerPointerAttr(S
.Context
, Attrs
));
6215 static void handleObjCRequiresSuperAttr(Sema
&S
, Decl
*D
,
6216 const ParsedAttr
&Attrs
) {
6217 const auto *Method
= cast
<ObjCMethodDecl
>(D
);
6219 const DeclContext
*DC
= Method
->getDeclContext();
6220 if (const auto *PDecl
= dyn_cast_if_present
<ObjCProtocolDecl
>(DC
)) {
6221 S
.Diag(D
->getBeginLoc(), diag::warn_objc_requires_super_protocol
) << Attrs
6223 S
.Diag(PDecl
->getLocation(), diag::note_protocol_decl
);
6226 if (Method
->getMethodFamily() == OMF_dealloc
) {
6227 S
.Diag(D
->getBeginLoc(), diag::warn_objc_requires_super_protocol
) << Attrs
6232 D
->addAttr(::new (S
.Context
) ObjCRequiresSuperAttr(S
.Context
, Attrs
));
6235 static void handleNSErrorDomain(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6236 auto *E
= AL
.getArgAsExpr(0);
6237 auto Loc
= E
? E
->getBeginLoc() : AL
.getLoc();
6239 auto *DRE
= dyn_cast
<DeclRefExpr
>(AL
.getArgAsExpr(0));
6241 S
.Diag(Loc
, diag::err_nserrordomain_invalid_decl
) << 0;
6245 auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl());
6247 S
.Diag(Loc
, diag::err_nserrordomain_invalid_decl
) << 1 << DRE
->getDecl();
6251 if (!isNSStringType(VD
->getType(), S
.Context
) &&
6252 !isCFStringType(VD
->getType(), S
.Context
)) {
6253 S
.Diag(Loc
, diag::err_nserrordomain_wrong_type
) << VD
;
6257 D
->addAttr(::new (S
.Context
) NSErrorDomainAttr(S
.Context
, AL
, VD
));
6260 static void handleObjCBridgeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6261 IdentifierLoc
*Parm
= AL
.isArgIdent(0) ? AL
.getArgAsIdent(0) : nullptr;
6264 S
.Diag(D
->getBeginLoc(), diag::err_objc_attr_not_id
) << AL
<< 0;
6268 // Typedefs only allow objc_bridge(id) and have some additional checking.
6269 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
6270 if (!Parm
->Ident
->isStr("id")) {
6271 S
.Diag(AL
.getLoc(), diag::err_objc_attr_typedef_not_id
) << AL
;
6275 // Only allow 'cv void *'.
6276 QualType T
= TD
->getUnderlyingType();
6277 if (!T
->isVoidPointerType()) {
6278 S
.Diag(AL
.getLoc(), diag::err_objc_attr_typedef_not_void_pointer
);
6283 D
->addAttr(::new (S
.Context
) ObjCBridgeAttr(S
.Context
, AL
, Parm
->Ident
));
6286 static void handleObjCBridgeMutableAttr(Sema
&S
, Decl
*D
,
6287 const ParsedAttr
&AL
) {
6288 IdentifierLoc
*Parm
= AL
.isArgIdent(0) ? AL
.getArgAsIdent(0) : nullptr;
6291 S
.Diag(D
->getBeginLoc(), diag::err_objc_attr_not_id
) << AL
<< 0;
6295 D
->addAttr(::new (S
.Context
)
6296 ObjCBridgeMutableAttr(S
.Context
, AL
, Parm
->Ident
));
6299 static void handleObjCBridgeRelatedAttr(Sema
&S
, Decl
*D
,
6300 const ParsedAttr
&AL
) {
6301 IdentifierInfo
*RelatedClass
=
6302 AL
.isArgIdent(0) ? AL
.getArgAsIdent(0)->Ident
: nullptr;
6303 if (!RelatedClass
) {
6304 S
.Diag(D
->getBeginLoc(), diag::err_objc_attr_not_id
) << AL
<< 0;
6307 IdentifierInfo
*ClassMethod
=
6308 AL
.getArgAsIdent(1) ? AL
.getArgAsIdent(1)->Ident
: nullptr;
6309 IdentifierInfo
*InstanceMethod
=
6310 AL
.getArgAsIdent(2) ? AL
.getArgAsIdent(2)->Ident
: nullptr;
6311 D
->addAttr(::new (S
.Context
) ObjCBridgeRelatedAttr(
6312 S
.Context
, AL
, RelatedClass
, ClassMethod
, InstanceMethod
));
6315 static void handleObjCDesignatedInitializer(Sema
&S
, Decl
*D
,
6316 const ParsedAttr
&AL
) {
6317 DeclContext
*Ctx
= D
->getDeclContext();
6319 // This attribute can only be applied to methods in interfaces or class
6321 if (!isa
<ObjCInterfaceDecl
>(Ctx
) &&
6322 !(isa
<ObjCCategoryDecl
>(Ctx
) &&
6323 cast
<ObjCCategoryDecl
>(Ctx
)->IsClassExtension())) {
6324 S
.Diag(D
->getLocation(), diag::err_designated_init_attr_non_init
);
6328 ObjCInterfaceDecl
*IFace
;
6329 if (auto *CatDecl
= dyn_cast
<ObjCCategoryDecl
>(Ctx
))
6330 IFace
= CatDecl
->getClassInterface();
6332 IFace
= cast
<ObjCInterfaceDecl
>(Ctx
);
6337 IFace
->setHasDesignatedInitializers();
6338 D
->addAttr(::new (S
.Context
) ObjCDesignatedInitializerAttr(S
.Context
, AL
));
6341 static void handleObjCRuntimeName(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6342 StringRef MetaDataName
;
6343 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, MetaDataName
))
6345 D
->addAttr(::new (S
.Context
)
6346 ObjCRuntimeNameAttr(S
.Context
, AL
, MetaDataName
));
6349 // When a user wants to use objc_boxable with a union or struct
6350 // but they don't have access to the declaration (legacy/third-party code)
6351 // then they can 'enable' this feature with a typedef:
6352 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
6353 static void handleObjCBoxable(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6354 bool notify
= false;
6356 auto *RD
= dyn_cast
<RecordDecl
>(D
);
6357 if (RD
&& RD
->getDefinition()) {
6358 RD
= RD
->getDefinition();
6363 ObjCBoxableAttr
*BoxableAttr
=
6364 ::new (S
.Context
) ObjCBoxableAttr(S
.Context
, AL
);
6365 RD
->addAttr(BoxableAttr
);
6367 // we need to notify ASTReader/ASTWriter about
6368 // modification of existing declaration
6369 if (ASTMutationListener
*L
= S
.getASTMutationListener())
6370 L
->AddedAttributeToRecord(BoxableAttr
, RD
);
6375 static void handleObjCOwnershipAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6376 if (hasDeclarator(D
))
6379 S
.Diag(D
->getBeginLoc(), diag::err_attribute_wrong_decl_type
)
6380 << AL
.getRange() << AL
<< AL
.isRegularKeywordAttribute()
6381 << ExpectedVariable
;
6384 static void handleObjCPreciseLifetimeAttr(Sema
&S
, Decl
*D
,
6385 const ParsedAttr
&AL
) {
6386 const auto *VD
= cast
<ValueDecl
>(D
);
6387 QualType QT
= VD
->getType();
6389 if (!QT
->isDependentType() &&
6390 !QT
->isObjCLifetimeType()) {
6391 S
.Diag(AL
.getLoc(), diag::err_objc_precise_lifetime_bad_type
)
6396 Qualifiers::ObjCLifetime Lifetime
= QT
.getObjCLifetime();
6398 // If we have no lifetime yet, check the lifetime we're presumably
6400 if (Lifetime
== Qualifiers::OCL_None
&& !QT
->isDependentType())
6401 Lifetime
= QT
->getObjCARCImplicitLifetime();
6404 case Qualifiers::OCL_None
:
6405 assert(QT
->isDependentType() &&
6406 "didn't infer lifetime for non-dependent type?");
6409 case Qualifiers::OCL_Weak
: // meaningful
6410 case Qualifiers::OCL_Strong
: // meaningful
6413 case Qualifiers::OCL_ExplicitNone
:
6414 case Qualifiers::OCL_Autoreleasing
:
6415 S
.Diag(AL
.getLoc(), diag::warn_objc_precise_lifetime_meaningless
)
6416 << (Lifetime
== Qualifiers::OCL_Autoreleasing
);
6420 D
->addAttr(::new (S
.Context
) ObjCPreciseLifetimeAttr(S
.Context
, AL
));
6423 static void handleSwiftAttrAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6424 // Make sure that there is a string literal as the annotation's single
6427 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
6430 D
->addAttr(::new (S
.Context
) SwiftAttrAttr(S
.Context
, AL
, Str
));
6433 static void handleSwiftBridge(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6434 // Make sure that there is a string literal as the annotation's single
6437 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, BT
))
6440 // Warn about duplicate attributes if they have different arguments, but drop
6441 // any duplicate attributes regardless.
6442 if (const auto *Other
= D
->getAttr
<SwiftBridgeAttr
>()) {
6443 if (Other
->getSwiftType() != BT
)
6444 S
.Diag(AL
.getLoc(), diag::warn_duplicate_attribute
) << AL
;
6448 D
->addAttr(::new (S
.Context
) SwiftBridgeAttr(S
.Context
, AL
, BT
));
6451 static bool isErrorParameter(Sema
&S
, QualType QT
) {
6452 const auto *PT
= QT
->getAs
<PointerType
>();
6456 QualType Pointee
= PT
->getPointeeType();
6458 // Check for NSError**.
6459 if (const auto *OPT
= Pointee
->getAs
<ObjCObjectPointerType
>())
6460 if (const auto *ID
= OPT
->getInterfaceDecl())
6461 if (ID
->getIdentifier() == S
.getNSErrorIdent())
6464 // Check for CFError**.
6465 if (const auto *PT
= Pointee
->getAs
<PointerType
>())
6466 if (const auto *RT
= PT
->getPointeeType()->getAs
<RecordType
>())
6467 if (S
.isCFError(RT
->getDecl()))
6473 static void handleSwiftError(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6474 auto hasErrorParameter
= [](Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) -> bool {
6475 for (unsigned I
= 0, E
= getFunctionOrMethodNumParams(D
); I
!= E
; ++I
) {
6476 if (isErrorParameter(S
, getFunctionOrMethodParamType(D
, I
)))
6480 S
.Diag(AL
.getLoc(), diag::err_attr_swift_error_no_error_parameter
)
6481 << AL
<< isa
<ObjCMethodDecl
>(D
);
6485 auto hasPointerResult
= [](Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) -> bool {
6486 // - C, ObjC, and block pointers are definitely okay.
6487 // - References are definitely not okay.
6488 // - nullptr_t is weird, but acceptable.
6489 QualType RT
= getFunctionOrMethodResultType(D
);
6490 if (RT
->hasPointerRepresentation() && !RT
->isReferenceType())
6493 S
.Diag(AL
.getLoc(), diag::err_attr_swift_error_return_type
)
6494 << AL
<< AL
.getArgAsIdent(0)->Ident
->getName() << isa
<ObjCMethodDecl
>(D
)
6499 auto hasIntegerResult
= [](Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) -> bool {
6500 QualType RT
= getFunctionOrMethodResultType(D
);
6501 if (RT
->isIntegralType(S
.Context
))
6504 S
.Diag(AL
.getLoc(), diag::err_attr_swift_error_return_type
)
6505 << AL
<< AL
.getArgAsIdent(0)->Ident
->getName() << isa
<ObjCMethodDecl
>(D
)
6510 if (D
->isInvalidDecl())
6513 IdentifierLoc
*Loc
= AL
.getArgAsIdent(0);
6514 SwiftErrorAttr::ConventionKind Convention
;
6515 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc
->Ident
->getName(),
6517 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
)
6518 << AL
<< Loc
->Ident
;
6522 switch (Convention
) {
6523 case SwiftErrorAttr::None
:
6524 // No additional validation required.
6527 case SwiftErrorAttr::NonNullError
:
6528 if (!hasErrorParameter(S
, D
, AL
))
6532 case SwiftErrorAttr::NullResult
:
6533 if (!hasErrorParameter(S
, D
, AL
) || !hasPointerResult(S
, D
, AL
))
6537 case SwiftErrorAttr::NonZeroResult
:
6538 case SwiftErrorAttr::ZeroResult
:
6539 if (!hasErrorParameter(S
, D
, AL
) || !hasIntegerResult(S
, D
, AL
))
6544 D
->addAttr(::new (S
.Context
) SwiftErrorAttr(S
.Context
, AL
, Convention
));
6547 static void checkSwiftAsyncErrorBlock(Sema
&S
, Decl
*D
,
6548 const SwiftAsyncErrorAttr
*ErrorAttr
,
6549 const SwiftAsyncAttr
*AsyncAttr
) {
6550 if (AsyncAttr
->getKind() == SwiftAsyncAttr::None
) {
6551 if (ErrorAttr
->getConvention() != SwiftAsyncErrorAttr::None
) {
6552 S
.Diag(AsyncAttr
->getLocation(),
6553 diag::err_swift_async_error_without_swift_async
)
6554 << AsyncAttr
<< isa
<ObjCMethodDecl
>(D
);
6559 const ParmVarDecl
*HandlerParam
= getFunctionOrMethodParam(
6560 D
, AsyncAttr
->getCompletionHandlerIndex().getASTIndex());
6561 // handleSwiftAsyncAttr already verified the type is correct, so no need to
6562 // double-check it here.
6563 const auto *FuncTy
= HandlerParam
->getType()
6564 ->castAs
<BlockPointerType
>()
6566 ->getAs
<FunctionProtoType
>();
6567 ArrayRef
<QualType
> BlockParams
;
6569 BlockParams
= FuncTy
->getParamTypes();
6571 switch (ErrorAttr
->getConvention()) {
6572 case SwiftAsyncErrorAttr::ZeroArgument
:
6573 case SwiftAsyncErrorAttr::NonZeroArgument
: {
6574 uint32_t ParamIdx
= ErrorAttr
->getHandlerParamIdx();
6575 if (ParamIdx
== 0 || ParamIdx
> BlockParams
.size()) {
6576 S
.Diag(ErrorAttr
->getLocation(),
6577 diag::err_attribute_argument_out_of_bounds
) << ErrorAttr
<< 2;
6580 QualType ErrorParam
= BlockParams
[ParamIdx
- 1];
6581 if (!ErrorParam
->isIntegralType(S
.Context
)) {
6583 ErrorAttr
->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
6585 : "nonzero_argument";
6586 S
.Diag(ErrorAttr
->getLocation(), diag::err_swift_async_error_non_integral
)
6587 << ErrorAttr
<< ConvStr
<< ParamIdx
<< ErrorParam
;
6592 case SwiftAsyncErrorAttr::NonNullError
: {
6593 bool AnyErrorParams
= false;
6594 for (QualType Param
: BlockParams
) {
6595 // Check for NSError *.
6596 if (const auto *ObjCPtrTy
= Param
->getAs
<ObjCObjectPointerType
>()) {
6597 if (const auto *ID
= ObjCPtrTy
->getInterfaceDecl()) {
6598 if (ID
->getIdentifier() == S
.getNSErrorIdent()) {
6599 AnyErrorParams
= true;
6604 // Check for CFError *.
6605 if (const auto *PtrTy
= Param
->getAs
<PointerType
>()) {
6606 if (const auto *RT
= PtrTy
->getPointeeType()->getAs
<RecordType
>()) {
6607 if (S
.isCFError(RT
->getDecl())) {
6608 AnyErrorParams
= true;
6615 if (!AnyErrorParams
) {
6616 S
.Diag(ErrorAttr
->getLocation(),
6617 diag::err_swift_async_error_no_error_parameter
)
6618 << ErrorAttr
<< isa
<ObjCMethodDecl
>(D
);
6623 case SwiftAsyncErrorAttr::None
:
6628 static void handleSwiftAsyncError(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6629 IdentifierLoc
*IDLoc
= AL
.getArgAsIdent(0);
6630 SwiftAsyncErrorAttr::ConventionKind ConvKind
;
6631 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc
->Ident
->getName(),
6633 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
)
6634 << AL
<< IDLoc
->Ident
;
6638 uint32_t ParamIdx
= 0;
6640 case SwiftAsyncErrorAttr::ZeroArgument
:
6641 case SwiftAsyncErrorAttr::NonZeroArgument
: {
6642 if (!AL
.checkExactlyNumArgs(S
, 2))
6645 Expr
*IdxExpr
= AL
.getArgAsExpr(1);
6646 if (!checkUInt32Argument(S
, AL
, IdxExpr
, ParamIdx
))
6650 case SwiftAsyncErrorAttr::NonNullError
:
6651 case SwiftAsyncErrorAttr::None
: {
6652 if (!AL
.checkExactlyNumArgs(S
, 1))
6659 ::new (S
.Context
) SwiftAsyncErrorAttr(S
.Context
, AL
, ConvKind
, ParamIdx
);
6660 D
->addAttr(ErrorAttr
);
6662 if (auto *AsyncAttr
= D
->getAttr
<SwiftAsyncAttr
>())
6663 checkSwiftAsyncErrorBlock(S
, D
, ErrorAttr
, AsyncAttr
);
6666 // For a function, this will validate a compound Swift name, e.g.
6667 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6668 // the function will output the number of parameter names, and whether this is a
6669 // single-arg initializer.
6671 // For a type, enum constant, property, or variable declaration, this will
6672 // validate either a simple identifier, or a qualified
6673 // <code>context.identifier</code> name.
6675 validateSwiftFunctionName(Sema
&S
, const ParsedAttr
&AL
, SourceLocation Loc
,
6676 StringRef Name
, unsigned &SwiftParamCount
,
6677 bool &IsSingleParamInit
) {
6678 SwiftParamCount
= 0;
6679 IsSingleParamInit
= false;
6681 // Check whether this will be mapped to a getter or setter of a property.
6682 bool IsGetter
= false, IsSetter
= false;
6683 if (Name
.startswith("getter:")) {
6685 Name
= Name
.substr(7);
6686 } else if (Name
.startswith("setter:")) {
6688 Name
= Name
.substr(7);
6691 if (Name
.back() != ')') {
6692 S
.Diag(Loc
, diag::warn_attr_swift_name_function
) << AL
;
6696 bool IsMember
= false;
6697 StringRef ContextName
, BaseName
, Parameters
;
6699 std::tie(BaseName
, Parameters
) = Name
.split('(');
6701 // Split at the first '.', if it exists, which separates the context name
6702 // from the base name.
6703 std::tie(ContextName
, BaseName
) = BaseName
.split('.');
6704 if (BaseName
.empty()) {
6705 BaseName
= ContextName
;
6706 ContextName
= StringRef();
6707 } else if (ContextName
.empty() || !isValidAsciiIdentifier(ContextName
)) {
6708 S
.Diag(Loc
, diag::warn_attr_swift_name_invalid_identifier
)
6709 << AL
<< /*context*/ 1;
6715 if (!isValidAsciiIdentifier(BaseName
) || BaseName
== "_") {
6716 S
.Diag(Loc
, diag::warn_attr_swift_name_invalid_identifier
)
6717 << AL
<< /*basename*/ 0;
6721 bool IsSubscript
= BaseName
== "subscript";
6722 // A subscript accessor must be a getter or setter.
6723 if (IsSubscript
&& !IsGetter
&& !IsSetter
) {
6724 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_invalid_parameter
)
6725 << AL
<< /* getter or setter */ 0;
6729 if (Parameters
.empty()) {
6730 S
.Diag(Loc
, diag::warn_attr_swift_name_missing_parameters
) << AL
;
6734 assert(Parameters
.back() == ')' && "expected ')'");
6735 Parameters
= Parameters
.drop_back(); // ')'
6737 if (Parameters
.empty()) {
6738 // Setters and subscripts must have at least one parameter.
6740 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_invalid_parameter
)
6741 << AL
<< /* have at least one parameter */1;
6746 S
.Diag(Loc
, diag::warn_attr_swift_name_setter_parameters
) << AL
;
6753 if (Parameters
.back() != ':') {
6754 S
.Diag(Loc
, diag::warn_attr_swift_name_function
) << AL
;
6758 StringRef CurrentParam
;
6759 std::optional
<unsigned> SelfLocation
;
6760 unsigned NewValueCount
= 0;
6761 std::optional
<unsigned> NewValueLocation
;
6763 std::tie(CurrentParam
, Parameters
) = Parameters
.split(':');
6765 if (!isValidAsciiIdentifier(CurrentParam
)) {
6766 S
.Diag(Loc
, diag::warn_attr_swift_name_invalid_identifier
)
6767 << AL
<< /*parameter*/2;
6771 if (IsMember
&& CurrentParam
== "self") {
6772 // "self" indicates the "self" argument for a member.
6774 // More than one "self"?
6776 S
.Diag(Loc
, diag::warn_attr_swift_name_multiple_selfs
) << AL
;
6780 // The "self" location is the current parameter.
6781 SelfLocation
= SwiftParamCount
;
6782 } else if (CurrentParam
== "newValue") {
6783 // "newValue" indicates the "newValue" argument for a setter.
6785 // There should only be one 'newValue', but it's only significant for
6786 // subscript accessors, so don't error right away.
6789 NewValueLocation
= SwiftParamCount
;
6793 } while (!Parameters
.empty());
6795 // Only instance subscripts are currently supported.
6796 if (IsSubscript
&& !SelfLocation
) {
6797 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_invalid_parameter
)
6798 << AL
<< /*have a 'self:' parameter*/2;
6803 SwiftParamCount
== 1 && BaseName
== "init" && CurrentParam
!= "_";
6805 // Check the number of parameters for a getter/setter.
6806 if (IsGetter
|| IsSetter
) {
6807 // Setters have one parameter for the new value.
6808 unsigned NumExpectedParams
= IsGetter
? 0 : 1;
6809 unsigned ParamDiag
=
6810 IsGetter
? diag::warn_attr_swift_name_getter_parameters
6811 : diag::warn_attr_swift_name_setter_parameters
;
6813 // Instance methods have one parameter for "self".
6815 ++NumExpectedParams
;
6817 // Subscripts may have additional parameters beyond the expected params for
6820 if (SwiftParamCount
< NumExpectedParams
) {
6821 S
.Diag(Loc
, ParamDiag
) << AL
;
6825 // A subscript setter must explicitly label its newValue parameter to
6826 // distinguish it from index parameters.
6828 if (!NewValueLocation
) {
6829 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_setter_no_newValue
)
6833 if (NewValueCount
> 1) {
6834 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_setter_multiple_newValues
)
6839 // Subscript getters should have no 'newValue:' parameter.
6840 if (NewValueLocation
) {
6841 S
.Diag(Loc
, diag::warn_attr_swift_name_subscript_getter_newValue
)
6847 // Property accessors must have exactly the number of expected params.
6848 if (SwiftParamCount
!= NumExpectedParams
) {
6849 S
.Diag(Loc
, ParamDiag
) << AL
;
6858 bool Sema::DiagnoseSwiftName(Decl
*D
, StringRef Name
, SourceLocation Loc
,
6859 const ParsedAttr
&AL
, bool IsAsync
) {
6860 if (isa
<ObjCMethodDecl
>(D
) || isa
<FunctionDecl
>(D
)) {
6861 ArrayRef
<ParmVarDecl
*> Params
;
6862 unsigned ParamCount
;
6864 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(D
)) {
6865 ParamCount
= Method
->getSelector().getNumArgs();
6866 Params
= Method
->parameters().slice(0, ParamCount
);
6868 const auto *F
= cast
<FunctionDecl
>(D
);
6870 ParamCount
= F
->getNumParams();
6871 Params
= F
->parameters();
6873 if (!F
->hasWrittenPrototype()) {
6874 Diag(Loc
, diag::warn_attribute_wrong_decl_type
)
6875 << AL
<< AL
.isRegularKeywordAttribute()
6876 << ExpectedFunctionWithProtoType
;
6881 // The async name drops the last callback parameter.
6883 if (ParamCount
== 0) {
6884 Diag(Loc
, diag::warn_attr_swift_name_decl_missing_params
)
6885 << AL
<< isa
<ObjCMethodDecl
>(D
);
6891 unsigned SwiftParamCount
;
6892 bool IsSingleParamInit
;
6893 if (!validateSwiftFunctionName(*this, AL
, Loc
, Name
,
6894 SwiftParamCount
, IsSingleParamInit
))
6897 bool ParamCountValid
;
6898 if (SwiftParamCount
== ParamCount
) {
6899 ParamCountValid
= true;
6900 } else if (SwiftParamCount
> ParamCount
) {
6901 ParamCountValid
= IsSingleParamInit
&& ParamCount
== 0;
6903 // We have fewer Swift parameters than Objective-C parameters, but that
6904 // might be because we've transformed some of them. Check for potential
6905 // "out" parameters and err on the side of not warning.
6906 unsigned MaybeOutParamCount
=
6907 llvm::count_if(Params
, [](const ParmVarDecl
*Param
) -> bool {
6908 QualType ParamTy
= Param
->getType();
6909 if (ParamTy
->isReferenceType() || ParamTy
->isPointerType())
6910 return !ParamTy
->getPointeeType().isConstQualified();
6914 ParamCountValid
= SwiftParamCount
+ MaybeOutParamCount
>= ParamCount
;
6917 if (!ParamCountValid
) {
6918 Diag(Loc
, diag::warn_attr_swift_name_num_params
)
6919 << (SwiftParamCount
> ParamCount
) << AL
<< ParamCount
6923 } else if ((isa
<EnumConstantDecl
>(D
) || isa
<ObjCProtocolDecl
>(D
) ||
6924 isa
<ObjCInterfaceDecl
>(D
) || isa
<ObjCPropertyDecl
>(D
) ||
6925 isa
<VarDecl
>(D
) || isa
<TypedefNameDecl
>(D
) || isa
<TagDecl
>(D
) ||
6926 isa
<IndirectFieldDecl
>(D
) || isa
<FieldDecl
>(D
)) &&
6928 StringRef ContextName
, BaseName
;
6930 std::tie(ContextName
, BaseName
) = Name
.split('.');
6931 if (BaseName
.empty()) {
6932 BaseName
= ContextName
;
6933 ContextName
= StringRef();
6934 } else if (!isValidAsciiIdentifier(ContextName
)) {
6935 Diag(Loc
, diag::warn_attr_swift_name_invalid_identifier
) << AL
6940 if (!isValidAsciiIdentifier(BaseName
)) {
6941 Diag(Loc
, diag::warn_attr_swift_name_invalid_identifier
) << AL
6946 Diag(Loc
, diag::warn_attr_swift_name_decl_kind
) << AL
;
6952 static void handleSwiftName(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6955 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Name
, &Loc
))
6958 if (!S
.DiagnoseSwiftName(D
, Name
, Loc
, AL
, /*IsAsync=*/false))
6961 D
->addAttr(::new (S
.Context
) SwiftNameAttr(S
.Context
, AL
, Name
));
6964 static void handleSwiftAsyncName(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6967 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Name
, &Loc
))
6970 if (!S
.DiagnoseSwiftName(D
, Name
, Loc
, AL
, /*IsAsync=*/true))
6973 D
->addAttr(::new (S
.Context
) SwiftAsyncNameAttr(S
.Context
, AL
, Name
));
6976 static void handleSwiftNewType(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
6977 // Make sure that there is an identifier as the annotation's single argument.
6978 if (!AL
.checkExactlyNumArgs(S
, 1))
6981 if (!AL
.isArgIdent(0)) {
6982 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
6983 << AL
<< AANT_ArgumentIdentifier
;
6987 SwiftNewTypeAttr::NewtypeKind Kind
;
6988 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
6989 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II
->getName(), Kind
)) {
6990 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< II
;
6994 if (!isa
<TypedefNameDecl
>(D
)) {
6995 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type_str
)
6996 << AL
<< AL
.isRegularKeywordAttribute() << "typedefs";
7000 D
->addAttr(::new (S
.Context
) SwiftNewTypeAttr(S
.Context
, AL
, Kind
));
7003 static void handleSwiftAsyncAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7004 if (!AL
.isArgIdent(0)) {
7005 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_n_type
)
7006 << AL
<< 1 << AANT_ArgumentIdentifier
;
7010 SwiftAsyncAttr::Kind Kind
;
7011 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
7012 if (!SwiftAsyncAttr::ConvertStrToKind(II
->getName(), Kind
)) {
7013 S
.Diag(AL
.getLoc(), diag::err_swift_async_no_access
) << AL
<< II
;
7018 if (Kind
== SwiftAsyncAttr::None
) {
7019 // If this is 'none', then there shouldn't be any additional arguments.
7020 if (!AL
.checkExactlyNumArgs(S
, 1))
7023 // Non-none swift_async requires a completion handler index argument.
7024 if (!AL
.checkExactlyNumArgs(S
, 2))
7027 Expr
*HandlerIdx
= AL
.getArgAsExpr(1);
7028 if (!checkFunctionOrMethodParameterIndex(S
, D
, AL
, 2, HandlerIdx
, Idx
))
7031 const ParmVarDecl
*CompletionBlock
=
7032 getFunctionOrMethodParam(D
, Idx
.getASTIndex());
7033 QualType CompletionBlockType
= CompletionBlock
->getType();
7034 if (!CompletionBlockType
->isBlockPointerType()) {
7035 S
.Diag(CompletionBlock
->getLocation(),
7036 diag::err_swift_async_bad_block_type
)
7037 << CompletionBlock
->getType();
7041 CompletionBlockType
->castAs
<BlockPointerType
>()->getPointeeType();
7042 if (!BlockTy
->castAs
<FunctionType
>()->getReturnType()->isVoidType()) {
7043 S
.Diag(CompletionBlock
->getLocation(),
7044 diag::err_swift_async_bad_block_type
)
7045 << CompletionBlock
->getType();
7051 ::new (S
.Context
) SwiftAsyncAttr(S
.Context
, AL
, Kind
, Idx
);
7052 D
->addAttr(AsyncAttr
);
7054 if (auto *ErrorAttr
= D
->getAttr
<SwiftAsyncErrorAttr
>())
7055 checkSwiftAsyncErrorBlock(S
, D
, ErrorAttr
, AsyncAttr
);
7058 //===----------------------------------------------------------------------===//
7059 // Microsoft specific attribute handlers.
7060 //===----------------------------------------------------------------------===//
7062 UuidAttr
*Sema::mergeUuidAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
7063 StringRef UuidAsWritten
, MSGuidDecl
*GuidDecl
) {
7064 if (const auto *UA
= D
->getAttr
<UuidAttr
>()) {
7065 if (declaresSameEntity(UA
->getGuidDecl(), GuidDecl
))
7067 if (!UA
->getGuid().empty()) {
7068 Diag(UA
->getLocation(), diag::err_mismatched_uuid
);
7069 Diag(CI
.getLoc(), diag::note_previous_uuid
);
7070 D
->dropAttr
<UuidAttr
>();
7074 return ::new (Context
) UuidAttr(Context
, CI
, UuidAsWritten
, GuidDecl
);
7077 static void handleUuidAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7078 if (!S
.LangOpts
.CPlusPlus
) {
7079 S
.Diag(AL
.getLoc(), diag::err_attribute_not_supported_in_lang
)
7080 << AL
<< AttributeLangSupport::C
;
7084 StringRef OrigStrRef
;
7085 SourceLocation LiteralLoc
;
7086 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, OrigStrRef
, &LiteralLoc
))
7089 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
7090 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
7091 StringRef StrRef
= OrigStrRef
;
7092 if (StrRef
.size() == 38 && StrRef
.front() == '{' && StrRef
.back() == '}')
7093 StrRef
= StrRef
.drop_front().drop_back();
7095 // Validate GUID length.
7096 if (StrRef
.size() != 36) {
7097 S
.Diag(LiteralLoc
, diag::err_attribute_uuid_malformed_guid
);
7101 for (unsigned i
= 0; i
< 36; ++i
) {
7102 if (i
== 8 || i
== 13 || i
== 18 || i
== 23) {
7103 if (StrRef
[i
] != '-') {
7104 S
.Diag(LiteralLoc
, diag::err_attribute_uuid_malformed_guid
);
7107 } else if (!isHexDigit(StrRef
[i
])) {
7108 S
.Diag(LiteralLoc
, diag::err_attribute_uuid_malformed_guid
);
7113 // Convert to our parsed format and canonicalize.
7114 MSGuidDecl::Parts Parsed
;
7115 StrRef
.substr(0, 8).getAsInteger(16, Parsed
.Part1
);
7116 StrRef
.substr(9, 4).getAsInteger(16, Parsed
.Part2
);
7117 StrRef
.substr(14, 4).getAsInteger(16, Parsed
.Part3
);
7118 for (unsigned i
= 0; i
!= 8; ++i
)
7119 StrRef
.substr(19 + 2 * i
+ (i
>= 2 ? 1 : 0), 2)
7120 .getAsInteger(16, Parsed
.Part4And5
[i
]);
7121 MSGuidDecl
*Guid
= S
.Context
.getMSGuidDecl(Parsed
);
7123 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
7124 // the only thing in the [] list, the [] too), and add an insertion of
7125 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
7126 // separating attributes nor of the [ and the ] are in the AST.
7127 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
7129 if (AL
.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
7130 S
.Diag(AL
.getLoc(), diag::warn_atl_uuid_deprecated
);
7132 UuidAttr
*UA
= S
.mergeUuidAttr(D
, AL
, OrigStrRef
, Guid
);
7137 static void handleHLSLNumThreadsAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7138 llvm::VersionTuple SMVersion
=
7139 S
.Context
.getTargetInfo().getTriple().getOSVersion();
7140 uint32_t ZMax
= 1024;
7141 uint32_t ThreadMax
= 1024;
7142 if (SMVersion
.getMajor() <= 4) {
7145 } else if (SMVersion
.getMajor() == 5) {
7151 if (!checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(0), X
))
7154 S
.Diag(AL
.getArgAsExpr(0)->getExprLoc(),
7155 diag::err_hlsl_numthreads_argument_oor
) << 0 << 1024;
7159 if (!checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(1), Y
))
7162 S
.Diag(AL
.getArgAsExpr(1)->getExprLoc(),
7163 diag::err_hlsl_numthreads_argument_oor
) << 1 << 1024;
7167 if (!checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(2), Z
))
7170 S
.Diag(AL
.getArgAsExpr(2)->getExprLoc(),
7171 diag::err_hlsl_numthreads_argument_oor
) << 2 << ZMax
;
7175 if (X
* Y
* Z
> ThreadMax
) {
7176 S
.Diag(AL
.getLoc(), diag::err_hlsl_numthreads_invalid
) << ThreadMax
;
7180 HLSLNumThreadsAttr
*NewAttr
= S
.mergeHLSLNumThreadsAttr(D
, AL
, X
, Y
, Z
);
7182 D
->addAttr(NewAttr
);
7185 HLSLNumThreadsAttr
*Sema::mergeHLSLNumThreadsAttr(Decl
*D
,
7186 const AttributeCommonInfo
&AL
,
7187 int X
, int Y
, int Z
) {
7188 if (HLSLNumThreadsAttr
*NT
= D
->getAttr
<HLSLNumThreadsAttr
>()) {
7189 if (NT
->getX() != X
|| NT
->getY() != Y
|| NT
->getZ() != Z
) {
7190 Diag(NT
->getLocation(), diag::err_hlsl_attribute_param_mismatch
) << AL
;
7191 Diag(AL
.getLoc(), diag::note_conflicting_attribute
);
7195 return ::new (Context
) HLSLNumThreadsAttr(Context
, AL
, X
, Y
, Z
);
7198 static bool isLegalTypeForHLSLSV_DispatchThreadID(QualType T
) {
7199 if (!T
->hasUnsignedIntegerRepresentation())
7201 if (const auto *VT
= T
->getAs
<VectorType
>())
7202 return VT
->getNumElements() <= 3;
7206 static void handleHLSLSV_DispatchThreadIDAttr(Sema
&S
, Decl
*D
,
7207 const ParsedAttr
&AL
) {
7208 // FIXME: support semantic on field.
7209 // See https://github.com/llvm/llvm-project/issues/57889.
7210 if (isa
<FieldDecl
>(D
)) {
7211 S
.Diag(AL
.getLoc(), diag::err_hlsl_attr_invalid_ast_node
)
7212 << AL
<< "parameter";
7216 auto *VD
= cast
<ValueDecl
>(D
);
7217 if (!isLegalTypeForHLSLSV_DispatchThreadID(VD
->getType())) {
7218 S
.Diag(AL
.getLoc(), diag::err_hlsl_attr_invalid_type
)
7219 << AL
<< "uint/uint2/uint3";
7223 D
->addAttr(::new (S
.Context
) HLSLSV_DispatchThreadIDAttr(S
.Context
, AL
));
7226 static void handleHLSLShaderAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7228 SourceLocation ArgLoc
;
7229 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7232 HLSLShaderAttr::ShaderType ShaderType
;
7233 if (!HLSLShaderAttr::ConvertStrToShaderType(Str
, ShaderType
)) {
7234 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
)
7235 << AL
<< Str
<< ArgLoc
;
7239 // FIXME: check function match the shader stage.
7241 HLSLShaderAttr
*NewAttr
= S
.mergeHLSLShaderAttr(D
, AL
, ShaderType
);
7243 D
->addAttr(NewAttr
);
7247 Sema::mergeHLSLShaderAttr(Decl
*D
, const AttributeCommonInfo
&AL
,
7248 HLSLShaderAttr::ShaderType ShaderType
) {
7249 if (HLSLShaderAttr
*NT
= D
->getAttr
<HLSLShaderAttr
>()) {
7250 if (NT
->getType() != ShaderType
) {
7251 Diag(NT
->getLocation(), diag::err_hlsl_attribute_param_mismatch
) << AL
;
7252 Diag(AL
.getLoc(), diag::note_conflicting_attribute
);
7256 return HLSLShaderAttr::Create(Context
, ShaderType
, AL
);
7259 static void handleHLSLResourceBindingAttr(Sema
&S
, Decl
*D
,
7260 const ParsedAttr
&AL
) {
7261 StringRef Space
= "space0";
7262 StringRef Slot
= "";
7264 if (!AL
.isArgIdent(0)) {
7265 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7266 << AL
<< AANT_ArgumentIdentifier
;
7270 IdentifierLoc
*Loc
= AL
.getArgAsIdent(0);
7271 StringRef Str
= Loc
->Ident
->getName();
7272 SourceLocation ArgLoc
= Loc
->Loc
;
7274 SourceLocation SpaceArgLoc
;
7275 if (AL
.getNumArgs() == 2) {
7277 if (!AL
.isArgIdent(1)) {
7278 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7279 << AL
<< AANT_ArgumentIdentifier
;
7283 IdentifierLoc
*Loc
= AL
.getArgAsIdent(1);
7284 Space
= Loc
->Ident
->getName();
7285 SpaceArgLoc
= Loc
->Loc
;
7291 if (!Slot
.empty()) {
7299 S
.Diag(ArgLoc
, diag::err_hlsl_unsupported_register_type
)
7300 << Slot
.substr(0, 1);
7304 StringRef SlotNum
= Slot
.substr(1);
7306 if (SlotNum
.getAsInteger(10, Num
)) {
7307 S
.Diag(ArgLoc
, diag::err_hlsl_unsupported_register_number
);
7312 if (!Space
.startswith("space")) {
7313 S
.Diag(SpaceArgLoc
, diag::err_hlsl_expected_space
) << Space
;
7316 StringRef SpaceNum
= Space
.substr(5);
7318 if (SpaceNum
.getAsInteger(10, Num
)) {
7319 S
.Diag(SpaceArgLoc
, diag::err_hlsl_expected_space
) << Space
;
7323 // FIXME: check reg type match decl. Issue
7324 // https://github.com/llvm/llvm-project/issues/57886.
7325 HLSLResourceBindingAttr
*NewAttr
=
7326 HLSLResourceBindingAttr::Create(S
.getASTContext(), Slot
, Space
, AL
);
7328 D
->addAttr(NewAttr
);
7331 static void handleMSInheritanceAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7332 if (!S
.LangOpts
.CPlusPlus
) {
7333 S
.Diag(AL
.getLoc(), diag::err_attribute_not_supported_in_lang
)
7334 << AL
<< AttributeLangSupport::C
;
7337 MSInheritanceAttr
*IA
= S
.mergeMSInheritanceAttr(
7338 D
, AL
, /*BestCase=*/true, (MSInheritanceModel
)AL
.getSemanticSpelling());
7341 S
.Consumer
.AssignInheritanceModel(cast
<CXXRecordDecl
>(D
));
7345 static void handleDeclspecThreadAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7346 const auto *VD
= cast
<VarDecl
>(D
);
7347 if (!S
.Context
.getTargetInfo().isTLSSupported()) {
7348 S
.Diag(AL
.getLoc(), diag::err_thread_unsupported
);
7351 if (VD
->getTSCSpec() != TSCS_unspecified
) {
7352 S
.Diag(AL
.getLoc(), diag::err_declspec_thread_on_thread_variable
);
7355 if (VD
->hasLocalStorage()) {
7356 S
.Diag(AL
.getLoc(), diag::err_thread_non_global
) << "__declspec(thread)";
7359 D
->addAttr(::new (S
.Context
) ThreadAttr(S
.Context
, AL
));
7362 static void handleAbiTagAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7363 SmallVector
<StringRef
, 4> Tags
;
7364 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
!= E
; ++I
) {
7366 if (!S
.checkStringLiteralArgumentAttr(AL
, I
, Tag
))
7368 Tags
.push_back(Tag
);
7371 if (const auto *NS
= dyn_cast
<NamespaceDecl
>(D
)) {
7372 if (!NS
->isInline()) {
7373 S
.Diag(AL
.getLoc(), diag::warn_attr_abi_tag_namespace
) << 0;
7376 if (NS
->isAnonymousNamespace()) {
7377 S
.Diag(AL
.getLoc(), diag::warn_attr_abi_tag_namespace
) << 1;
7380 if (AL
.getNumArgs() == 0)
7381 Tags
.push_back(NS
->getName());
7382 } else if (!AL
.checkAtLeastNumArgs(S
, 1))
7385 // Store tags sorted and without duplicates.
7387 Tags
.erase(std::unique(Tags
.begin(), Tags
.end()), Tags
.end());
7389 D
->addAttr(::new (S
.Context
)
7390 AbiTagAttr(S
.Context
, AL
, Tags
.data(), Tags
.size()));
7393 static void handleARMInterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7394 // Check the attribute arguments.
7395 if (AL
.getNumArgs() > 1) {
7396 S
.Diag(AL
.getLoc(), diag::err_attribute_too_many_arguments
) << AL
<< 1;
7401 SourceLocation ArgLoc
;
7403 if (AL
.getNumArgs() == 0)
7405 else if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7408 ARMInterruptAttr::InterruptType Kind
;
7409 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str
, Kind
)) {
7410 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< Str
7415 D
->addAttr(::new (S
.Context
) ARMInterruptAttr(S
.Context
, AL
, Kind
));
7418 static void handleMSP430InterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7419 // MSP430 'interrupt' attribute is applied to
7420 // a function with no parameters and void return type.
7421 if (!isFunctionOrMethod(D
)) {
7422 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7423 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunctionOrMethod
;
7427 if (hasFunctionProto(D
) && getFunctionOrMethodNumParams(D
) != 0) {
7428 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7429 << /*MSP430*/ 1 << 0;
7433 if (!getFunctionOrMethodResultType(D
)->isVoidType()) {
7434 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7435 << /*MSP430*/ 1 << 1;
7439 // The attribute takes one integer argument.
7440 if (!AL
.checkExactlyNumArgs(S
, 1))
7443 if (!AL
.isArgExpr(0)) {
7444 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7445 << AL
<< AANT_ArgumentIntegerConstant
;
7449 Expr
*NumParamsExpr
= static_cast<Expr
*>(AL
.getArgAsExpr(0));
7450 std::optional
<llvm::APSInt
> NumParams
= llvm::APSInt(32);
7451 if (!(NumParams
= NumParamsExpr
->getIntegerConstantExpr(S
.Context
))) {
7452 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7453 << AL
<< AANT_ArgumentIntegerConstant
7454 << NumParamsExpr
->getSourceRange();
7457 // The argument should be in range 0..63.
7458 unsigned Num
= NumParams
->getLimitedValue(255);
7460 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
7461 << AL
<< (int)NumParams
->getSExtValue()
7462 << NumParamsExpr
->getSourceRange();
7466 D
->addAttr(::new (S
.Context
) MSP430InterruptAttr(S
.Context
, AL
, Num
));
7467 D
->addAttr(UsedAttr::CreateImplicit(S
.Context
));
7470 static void handleMipsInterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7471 // Only one optional argument permitted.
7472 if (AL
.getNumArgs() > 1) {
7473 S
.Diag(AL
.getLoc(), diag::err_attribute_too_many_arguments
) << AL
<< 1;
7478 SourceLocation ArgLoc
;
7480 if (AL
.getNumArgs() == 0)
7482 else if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7485 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
7486 // a) Must be a function.
7487 // b) Must have no parameters.
7488 // c) Must have the 'void' return type.
7489 // d) Cannot have the 'mips16' attribute, as that instruction set
7490 // lacks the 'eret' instruction.
7491 // e) The attribute itself must either have no argument or one of the
7492 // valid interrupt types, see [MipsInterruptDocs].
7494 if (!isFunctionOrMethod(D
)) {
7495 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7496 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunctionOrMethod
;
7500 if (hasFunctionProto(D
) && getFunctionOrMethodNumParams(D
) != 0) {
7501 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7506 if (!getFunctionOrMethodResultType(D
)->isVoidType()) {
7507 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7512 // We still have to do this manually because the Interrupt attributes are
7513 // a bit special due to sharing their spellings across targets.
7514 if (checkAttrMutualExclusion
<Mips16Attr
>(S
, D
, AL
))
7517 MipsInterruptAttr::InterruptType Kind
;
7518 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str
, Kind
)) {
7519 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
)
7520 << AL
<< "'" + std::string(Str
) + "'";
7524 D
->addAttr(::new (S
.Context
) MipsInterruptAttr(S
.Context
, AL
, Kind
));
7527 static void handleM68kInterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7528 if (!AL
.checkExactlyNumArgs(S
, 1))
7531 if (!AL
.isArgExpr(0)) {
7532 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7533 << AL
<< AANT_ArgumentIntegerConstant
;
7537 // FIXME: Check for decl - it should be void ()(void).
7539 Expr
*NumParamsExpr
= static_cast<Expr
*>(AL
.getArgAsExpr(0));
7540 auto MaybeNumParams
= NumParamsExpr
->getIntegerConstantExpr(S
.Context
);
7541 if (!MaybeNumParams
) {
7542 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
7543 << AL
<< AANT_ArgumentIntegerConstant
7544 << NumParamsExpr
->getSourceRange();
7548 unsigned Num
= MaybeNumParams
->getLimitedValue(255);
7549 if ((Num
& 1) || Num
> 30) {
7550 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
7551 << AL
<< (int)MaybeNumParams
->getSExtValue()
7552 << NumParamsExpr
->getSourceRange();
7556 D
->addAttr(::new (S
.Context
) M68kInterruptAttr(S
.Context
, AL
, Num
));
7557 D
->addAttr(UsedAttr::CreateImplicit(S
.Context
));
7560 static void handleAnyX86InterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7561 // Semantic checks for a function with the 'interrupt' attribute.
7562 // a) Must be a function.
7563 // b) Must have the 'void' return type.
7564 // c) Must take 1 or 2 arguments.
7565 // d) The 1st argument must be a pointer.
7566 // e) The 2nd argument (if any) must be an unsigned integer.
7567 if (!isFunctionOrMethod(D
) || !hasFunctionProto(D
) || isInstanceMethod(D
) ||
7568 CXXMethodDecl::isStaticOverloadedOperator(
7569 cast
<NamedDecl
>(D
)->getDeclName().getCXXOverloadedOperator())) {
7570 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
7571 << AL
<< AL
.isRegularKeywordAttribute()
7572 << ExpectedFunctionWithProtoType
;
7575 // Interrupt handler must have void return type.
7576 if (!getFunctionOrMethodResultType(D
)->isVoidType()) {
7577 S
.Diag(getFunctionOrMethodResultSourceRange(D
).getBegin(),
7578 diag::err_anyx86_interrupt_attribute
)
7579 << (S
.Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7585 // Interrupt handler must have 1 or 2 parameters.
7586 unsigned NumParams
= getFunctionOrMethodNumParams(D
);
7587 if (NumParams
< 1 || NumParams
> 2) {
7588 S
.Diag(D
->getBeginLoc(), diag::err_anyx86_interrupt_attribute
)
7589 << (S
.Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7595 // The first argument must be a pointer.
7596 if (!getFunctionOrMethodParamType(D
, 0)->isPointerType()) {
7597 S
.Diag(getFunctionOrMethodParamRange(D
, 0).getBegin(),
7598 diag::err_anyx86_interrupt_attribute
)
7599 << (S
.Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7605 // The second argument, if present, must be an unsigned integer.
7607 S
.Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
7610 if (NumParams
== 2 &&
7611 (!getFunctionOrMethodParamType(D
, 1)->isUnsignedIntegerType() ||
7612 S
.Context
.getTypeSize(getFunctionOrMethodParamType(D
, 1)) != TypeSize
)) {
7613 S
.Diag(getFunctionOrMethodParamRange(D
, 1).getBegin(),
7614 diag::err_anyx86_interrupt_attribute
)
7615 << (S
.Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7618 << 3 << S
.Context
.getIntTypeForBitwidth(TypeSize
, /*Signed=*/false);
7621 D
->addAttr(::new (S
.Context
) AnyX86InterruptAttr(S
.Context
, AL
));
7622 D
->addAttr(UsedAttr::CreateImplicit(S
.Context
));
7625 static void handleAVRInterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7626 if (!isFunctionOrMethod(D
)) {
7627 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7628 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
7632 if (!AL
.checkExactlyNumArgs(S
, 0))
7635 handleSimpleAttribute
<AVRInterruptAttr
>(S
, D
, AL
);
7638 static void handleAVRSignalAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7639 if (!isFunctionOrMethod(D
)) {
7640 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7641 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
7645 if (!AL
.checkExactlyNumArgs(S
, 0))
7648 handleSimpleAttribute
<AVRSignalAttr
>(S
, D
, AL
);
7651 static void handleBPFPreserveAIRecord(Sema
&S
, RecordDecl
*RD
) {
7652 // Add preserve_access_index attribute to all fields and inner records.
7653 for (auto *D
: RD
->decls()) {
7654 if (D
->hasAttr
<BPFPreserveAccessIndexAttr
>())
7657 D
->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S
.Context
));
7658 if (auto *Rec
= dyn_cast
<RecordDecl
>(D
))
7659 handleBPFPreserveAIRecord(S
, Rec
);
7663 static void handleBPFPreserveAccessIndexAttr(Sema
&S
, Decl
*D
,
7664 const ParsedAttr
&AL
) {
7665 auto *Rec
= cast
<RecordDecl
>(D
);
7666 handleBPFPreserveAIRecord(S
, Rec
);
7667 Rec
->addAttr(::new (S
.Context
) BPFPreserveAccessIndexAttr(S
.Context
, AL
));
7670 static bool hasBTFDeclTagAttr(Decl
*D
, StringRef Tag
) {
7671 for (const auto *I
: D
->specific_attrs
<BTFDeclTagAttr
>()) {
7672 if (I
->getBTFDeclTag() == Tag
)
7678 static void handleBTFDeclTagAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7680 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
7682 if (hasBTFDeclTagAttr(D
, Str
))
7685 D
->addAttr(::new (S
.Context
) BTFDeclTagAttr(S
.Context
, AL
, Str
));
7688 BTFDeclTagAttr
*Sema::mergeBTFDeclTagAttr(Decl
*D
, const BTFDeclTagAttr
&AL
) {
7689 if (hasBTFDeclTagAttr(D
, AL
.getBTFDeclTag()))
7691 return ::new (Context
) BTFDeclTagAttr(Context
, AL
, AL
.getBTFDeclTag());
7694 static void handleWebAssemblyExportNameAttr(Sema
&S
, Decl
*D
,
7695 const ParsedAttr
&AL
) {
7696 if (!isFunctionOrMethod(D
)) {
7697 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7698 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
7702 auto *FD
= cast
<FunctionDecl
>(D
);
7703 if (FD
->isThisDeclarationADefinition()) {
7704 S
.Diag(D
->getLocation(), diag::err_alias_is_definition
) << FD
<< 0;
7709 SourceLocation ArgLoc
;
7710 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7713 D
->addAttr(::new (S
.Context
) WebAssemblyExportNameAttr(S
.Context
, AL
, Str
));
7714 D
->addAttr(UsedAttr::CreateImplicit(S
.Context
));
7717 WebAssemblyImportModuleAttr
*
7718 Sema::mergeImportModuleAttr(Decl
*D
, const WebAssemblyImportModuleAttr
&AL
) {
7719 auto *FD
= cast
<FunctionDecl
>(D
);
7721 if (const auto *ExistingAttr
= FD
->getAttr
<WebAssemblyImportModuleAttr
>()) {
7722 if (ExistingAttr
->getImportModule() == AL
.getImportModule())
7724 Diag(ExistingAttr
->getLocation(), diag::warn_mismatched_import
) << 0
7725 << ExistingAttr
->getImportModule() << AL
.getImportModule();
7726 Diag(AL
.getLoc(), diag::note_previous_attribute
);
7729 if (FD
->hasBody()) {
7730 Diag(AL
.getLoc(), diag::warn_import_on_definition
) << 0;
7733 return ::new (Context
) WebAssemblyImportModuleAttr(Context
, AL
,
7734 AL
.getImportModule());
7737 WebAssemblyImportNameAttr
*
7738 Sema::mergeImportNameAttr(Decl
*D
, const WebAssemblyImportNameAttr
&AL
) {
7739 auto *FD
= cast
<FunctionDecl
>(D
);
7741 if (const auto *ExistingAttr
= FD
->getAttr
<WebAssemblyImportNameAttr
>()) {
7742 if (ExistingAttr
->getImportName() == AL
.getImportName())
7744 Diag(ExistingAttr
->getLocation(), diag::warn_mismatched_import
) << 1
7745 << ExistingAttr
->getImportName() << AL
.getImportName();
7746 Diag(AL
.getLoc(), diag::note_previous_attribute
);
7749 if (FD
->hasBody()) {
7750 Diag(AL
.getLoc(), diag::warn_import_on_definition
) << 1;
7753 return ::new (Context
) WebAssemblyImportNameAttr(Context
, AL
,
7754 AL
.getImportName());
7758 handleWebAssemblyImportModuleAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7759 auto *FD
= cast
<FunctionDecl
>(D
);
7762 SourceLocation ArgLoc
;
7763 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7765 if (FD
->hasBody()) {
7766 S
.Diag(AL
.getLoc(), diag::warn_import_on_definition
) << 0;
7770 FD
->addAttr(::new (S
.Context
)
7771 WebAssemblyImportModuleAttr(S
.Context
, AL
, Str
));
7775 handleWebAssemblyImportNameAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7776 auto *FD
= cast
<FunctionDecl
>(D
);
7779 SourceLocation ArgLoc
;
7780 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7782 if (FD
->hasBody()) {
7783 S
.Diag(AL
.getLoc(), diag::warn_import_on_definition
) << 1;
7787 FD
->addAttr(::new (S
.Context
) WebAssemblyImportNameAttr(S
.Context
, AL
, Str
));
7790 static void handleRISCVInterruptAttr(Sema
&S
, Decl
*D
,
7791 const ParsedAttr
&AL
) {
7792 // Warn about repeated attributes.
7793 if (const auto *A
= D
->getAttr
<RISCVInterruptAttr
>()) {
7794 S
.Diag(AL
.getRange().getBegin(),
7795 diag::warn_riscv_repeated_interrupt_attribute
);
7796 S
.Diag(A
->getLocation(), diag::note_riscv_repeated_interrupt_attribute
);
7800 // Check the attribute argument. Argument is optional.
7801 if (!AL
.checkAtMostNumArgs(S
, 1))
7805 SourceLocation ArgLoc
;
7807 // 'machine'is the default interrupt mode.
7808 if (AL
.getNumArgs() == 0)
7810 else if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Str
, &ArgLoc
))
7813 // Semantic checks for a function with the 'interrupt' attribute:
7814 // - Must be a function.
7815 // - Must have no parameters.
7816 // - Must have the 'void' return type.
7817 // - The attribute itself must either have no argument or one of the
7818 // valid interrupt types, see [RISCVInterruptDocs].
7820 if (D
->getFunctionType() == nullptr) {
7821 S
.Diag(D
->getLocation(), diag::warn_attribute_wrong_decl_type
)
7822 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
7826 if (hasFunctionProto(D
) && getFunctionOrMethodNumParams(D
) != 0) {
7827 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7828 << /*RISC-V*/ 2 << 0;
7832 if (!getFunctionOrMethodResultType(D
)->isVoidType()) {
7833 S
.Diag(D
->getLocation(), diag::warn_interrupt_attribute_invalid
)
7834 << /*RISC-V*/ 2 << 1;
7838 RISCVInterruptAttr::InterruptType Kind
;
7839 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str
, Kind
)) {
7840 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< Str
7845 D
->addAttr(::new (S
.Context
) RISCVInterruptAttr(S
.Context
, AL
, Kind
));
7848 static void handleInterruptAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7849 // Dispatch the interrupt attribute based on the current target.
7850 switch (S
.Context
.getTargetInfo().getTriple().getArch()) {
7851 case llvm::Triple::msp430
:
7852 handleMSP430InterruptAttr(S
, D
, AL
);
7854 case llvm::Triple::mipsel
:
7855 case llvm::Triple::mips
:
7856 handleMipsInterruptAttr(S
, D
, AL
);
7858 case llvm::Triple::m68k
:
7859 handleM68kInterruptAttr(S
, D
, AL
);
7861 case llvm::Triple::x86
:
7862 case llvm::Triple::x86_64
:
7863 handleAnyX86InterruptAttr(S
, D
, AL
);
7865 case llvm::Triple::avr
:
7866 handleAVRInterruptAttr(S
, D
, AL
);
7868 case llvm::Triple::riscv32
:
7869 case llvm::Triple::riscv64
:
7870 handleRISCVInterruptAttr(S
, D
, AL
);
7873 handleARMInterruptAttr(S
, D
, AL
);
7879 checkAMDGPUFlatWorkGroupSizeArguments(Sema
&S
, Expr
*MinExpr
, Expr
*MaxExpr
,
7880 const AMDGPUFlatWorkGroupSizeAttr
&Attr
) {
7881 // Accept template arguments for now as they depend on something else.
7882 // We'll get to check them when they eventually get instantiated.
7883 if (MinExpr
->isValueDependent() || MaxExpr
->isValueDependent())
7887 if (!checkUInt32Argument(S
, Attr
, MinExpr
, Min
, 0))
7891 if (!checkUInt32Argument(S
, Attr
, MaxExpr
, Max
, 1))
7894 if (Min
== 0 && Max
!= 0) {
7895 S
.Diag(Attr
.getLocation(), diag::err_attribute_argument_invalid
)
7900 S
.Diag(Attr
.getLocation(), diag::err_attribute_argument_invalid
)
7908 AMDGPUFlatWorkGroupSizeAttr
*
7909 Sema::CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo
&CI
,
7910 Expr
*MinExpr
, Expr
*MaxExpr
) {
7911 AMDGPUFlatWorkGroupSizeAttr
TmpAttr(Context
, CI
, MinExpr
, MaxExpr
);
7913 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr
, MaxExpr
, TmpAttr
))
7915 return ::new (Context
)
7916 AMDGPUFlatWorkGroupSizeAttr(Context
, CI
, MinExpr
, MaxExpr
);
7919 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl
*D
,
7920 const AttributeCommonInfo
&CI
,
7921 Expr
*MinExpr
, Expr
*MaxExpr
) {
7922 if (auto *Attr
= CreateAMDGPUFlatWorkGroupSizeAttr(CI
, MinExpr
, MaxExpr
))
7926 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema
&S
, Decl
*D
,
7927 const ParsedAttr
&AL
) {
7928 Expr
*MinExpr
= AL
.getArgAsExpr(0);
7929 Expr
*MaxExpr
= AL
.getArgAsExpr(1);
7931 S
.addAMDGPUFlatWorkGroupSizeAttr(D
, AL
, MinExpr
, MaxExpr
);
7934 static bool checkAMDGPUWavesPerEUArguments(Sema
&S
, Expr
*MinExpr
,
7936 const AMDGPUWavesPerEUAttr
&Attr
) {
7937 if (S
.DiagnoseUnexpandedParameterPack(MinExpr
) ||
7938 (MaxExpr
&& S
.DiagnoseUnexpandedParameterPack(MaxExpr
)))
7941 // Accept template arguments for now as they depend on something else.
7942 // We'll get to check them when they eventually get instantiated.
7943 if (MinExpr
->isValueDependent() || (MaxExpr
&& MaxExpr
->isValueDependent()))
7947 if (!checkUInt32Argument(S
, Attr
, MinExpr
, Min
, 0))
7951 if (MaxExpr
&& !checkUInt32Argument(S
, Attr
, MaxExpr
, Max
, 1))
7954 if (Min
== 0 && Max
!= 0) {
7955 S
.Diag(Attr
.getLocation(), diag::err_attribute_argument_invalid
)
7959 if (Max
!= 0 && Min
> Max
) {
7960 S
.Diag(Attr
.getLocation(), diag::err_attribute_argument_invalid
)
7968 AMDGPUWavesPerEUAttr
*
7969 Sema::CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo
&CI
, Expr
*MinExpr
,
7971 AMDGPUWavesPerEUAttr
TmpAttr(Context
, CI
, MinExpr
, MaxExpr
);
7973 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr
, MaxExpr
, TmpAttr
))
7976 return ::new (Context
) AMDGPUWavesPerEUAttr(Context
, CI
, MinExpr
, MaxExpr
);
7979 void Sema::addAMDGPUWavesPerEUAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
7980 Expr
*MinExpr
, Expr
*MaxExpr
) {
7981 if (auto *Attr
= CreateAMDGPUWavesPerEUAttr(CI
, MinExpr
, MaxExpr
))
7985 static void handleAMDGPUWavesPerEUAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7986 if (!AL
.checkAtLeastNumArgs(S
, 1) || !AL
.checkAtMostNumArgs(S
, 2))
7989 Expr
*MinExpr
= AL
.getArgAsExpr(0);
7990 Expr
*MaxExpr
= (AL
.getNumArgs() > 1) ? AL
.getArgAsExpr(1) : nullptr;
7992 S
.addAMDGPUWavesPerEUAttr(D
, AL
, MinExpr
, MaxExpr
);
7995 static void handleAMDGPUNumSGPRAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
7996 uint32_t NumSGPR
= 0;
7997 Expr
*NumSGPRExpr
= AL
.getArgAsExpr(0);
7998 if (!checkUInt32Argument(S
, AL
, NumSGPRExpr
, NumSGPR
))
8001 D
->addAttr(::new (S
.Context
) AMDGPUNumSGPRAttr(S
.Context
, AL
, NumSGPR
));
8004 static void handleAMDGPUNumVGPRAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8005 uint32_t NumVGPR
= 0;
8006 Expr
*NumVGPRExpr
= AL
.getArgAsExpr(0);
8007 if (!checkUInt32Argument(S
, AL
, NumVGPRExpr
, NumVGPR
))
8010 D
->addAttr(::new (S
.Context
) AMDGPUNumVGPRAttr(S
.Context
, AL
, NumVGPR
));
8013 static void handleX86ForceAlignArgPointerAttr(Sema
&S
, Decl
*D
,
8014 const ParsedAttr
&AL
) {
8015 // If we try to apply it to a function pointer, don't warn, but don't
8016 // do anything, either. It doesn't matter anyway, because there's nothing
8017 // special about calling a force_align_arg_pointer function.
8018 const auto *VD
= dyn_cast
<ValueDecl
>(D
);
8019 if (VD
&& VD
->getType()->isFunctionPointerType())
8021 // Also don't warn on function pointer typedefs.
8022 const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
);
8023 if (TD
&& (TD
->getUnderlyingType()->isFunctionPointerType() ||
8024 TD
->getUnderlyingType()->isFunctionType()))
8026 // Attribute can only be applied to function types.
8027 if (!isa
<FunctionDecl
>(D
)) {
8028 S
.Diag(AL
.getLoc(), diag::warn_attribute_wrong_decl_type
)
8029 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
8033 D
->addAttr(::new (S
.Context
) X86ForceAlignArgPointerAttr(S
.Context
, AL
));
8036 static void handleLayoutVersion(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8038 Expr
*VersionExpr
= static_cast<Expr
*>(AL
.getArgAsExpr(0));
8039 if (!checkUInt32Argument(S
, AL
, AL
.getArgAsExpr(0), Version
))
8042 // TODO: Investigate what happens with the next major version of MSVC.
8043 if (Version
!= LangOptions::MSVC2015
/ 100) {
8044 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_out_of_bounds
)
8045 << AL
<< Version
<< VersionExpr
->getSourceRange();
8049 // The attribute expects a "major" version number like 19, but new versions of
8050 // MSVC have moved to updating the "minor", or less significant numbers, so we
8051 // have to multiply by 100 now.
8054 D
->addAttr(::new (S
.Context
) LayoutVersionAttr(S
.Context
, AL
, Version
));
8057 DLLImportAttr
*Sema::mergeDLLImportAttr(Decl
*D
,
8058 const AttributeCommonInfo
&CI
) {
8059 if (D
->hasAttr
<DLLExportAttr
>()) {
8060 Diag(CI
.getLoc(), diag::warn_attribute_ignored
) << "'dllimport'";
8064 if (D
->hasAttr
<DLLImportAttr
>())
8067 return ::new (Context
) DLLImportAttr(Context
, CI
);
8070 DLLExportAttr
*Sema::mergeDLLExportAttr(Decl
*D
,
8071 const AttributeCommonInfo
&CI
) {
8072 if (DLLImportAttr
*Import
= D
->getAttr
<DLLImportAttr
>()) {
8073 Diag(Import
->getLocation(), diag::warn_attribute_ignored
) << Import
;
8074 D
->dropAttr
<DLLImportAttr
>();
8077 if (D
->hasAttr
<DLLExportAttr
>())
8080 return ::new (Context
) DLLExportAttr(Context
, CI
);
8083 static void handleDLLAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&A
) {
8084 if (isa
<ClassTemplatePartialSpecializationDecl
>(D
) &&
8085 (S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols())) {
8086 S
.Diag(A
.getRange().getBegin(), diag::warn_attribute_ignored
) << A
;
8090 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
8091 if (FD
->isInlined() && A
.getKind() == ParsedAttr::AT_DLLImport
&&
8092 !(S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols())) {
8093 // MinGW doesn't allow dllimport on inline functions.
8094 S
.Diag(A
.getRange().getBegin(), diag::warn_attribute_ignored_on_inline
)
8100 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
8101 if ((S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols()) &&
8102 MD
->getParent()->isLambda()) {
8103 S
.Diag(A
.getRange().getBegin(), diag::err_attribute_dll_lambda
) << A
;
8108 Attr
*NewAttr
= A
.getKind() == ParsedAttr::AT_DLLExport
8109 ? (Attr
*)S
.mergeDLLExportAttr(D
, A
)
8110 : (Attr
*)S
.mergeDLLImportAttr(D
, A
);
8112 D
->addAttr(NewAttr
);
8116 Sema::mergeMSInheritanceAttr(Decl
*D
, const AttributeCommonInfo
&CI
,
8118 MSInheritanceModel Model
) {
8119 if (MSInheritanceAttr
*IA
= D
->getAttr
<MSInheritanceAttr
>()) {
8120 if (IA
->getInheritanceModel() == Model
)
8122 Diag(IA
->getLocation(), diag::err_mismatched_ms_inheritance
)
8123 << 1 /*previous declaration*/;
8124 Diag(CI
.getLoc(), diag::note_previous_ms_inheritance
);
8125 D
->dropAttr
<MSInheritanceAttr
>();
8128 auto *RD
= cast
<CXXRecordDecl
>(D
);
8129 if (RD
->hasDefinition()) {
8130 if (checkMSInheritanceAttrOnDefinition(RD
, CI
.getRange(), BestCase
,
8135 if (isa
<ClassTemplatePartialSpecializationDecl
>(RD
)) {
8136 Diag(CI
.getLoc(), diag::warn_ignored_ms_inheritance
)
8137 << 1 /*partial specialization*/;
8140 if (RD
->getDescribedClassTemplate()) {
8141 Diag(CI
.getLoc(), diag::warn_ignored_ms_inheritance
)
8142 << 0 /*primary template*/;
8147 return ::new (Context
) MSInheritanceAttr(Context
, CI
, BestCase
);
8150 static void handleCapabilityAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8151 // The capability attributes take a single string parameter for the name of
8152 // the capability they represent. The lockable attribute does not take any
8153 // parameters. However, semantically, both attributes represent the same
8154 // concept, and so they use the same semantic attribute. Eventually, the
8155 // lockable attribute will be removed.
8157 // For backward compatibility, any capability which has no specified string
8158 // literal will be considered a "mutex."
8159 StringRef
N("mutex");
8160 SourceLocation LiteralLoc
;
8161 if (AL
.getKind() == ParsedAttr::AT_Capability
&&
8162 !S
.checkStringLiteralArgumentAttr(AL
, 0, N
, &LiteralLoc
))
8165 D
->addAttr(::new (S
.Context
) CapabilityAttr(S
.Context
, AL
, N
));
8168 static void handleAssertCapabilityAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8169 SmallVector
<Expr
*, 1> Args
;
8170 if (!checkLockFunAttrCommon(S
, D
, AL
, Args
))
8173 D
->addAttr(::new (S
.Context
)
8174 AssertCapabilityAttr(S
.Context
, AL
, Args
.data(), Args
.size()));
8177 static void handleAcquireCapabilityAttr(Sema
&S
, Decl
*D
,
8178 const ParsedAttr
&AL
) {
8179 SmallVector
<Expr
*, 1> Args
;
8180 if (!checkLockFunAttrCommon(S
, D
, AL
, Args
))
8183 D
->addAttr(::new (S
.Context
) AcquireCapabilityAttr(S
.Context
, AL
, Args
.data(),
8187 static void handleTryAcquireCapabilityAttr(Sema
&S
, Decl
*D
,
8188 const ParsedAttr
&AL
) {
8189 SmallVector
<Expr
*, 2> Args
;
8190 if (!checkTryLockFunAttrCommon(S
, D
, AL
, Args
))
8193 D
->addAttr(::new (S
.Context
) TryAcquireCapabilityAttr(
8194 S
.Context
, AL
, AL
.getArgAsExpr(0), Args
.data(), Args
.size()));
8197 static void handleReleaseCapabilityAttr(Sema
&S
, Decl
*D
,
8198 const ParsedAttr
&AL
) {
8199 // Check that all arguments are lockable objects.
8200 SmallVector
<Expr
*, 1> Args
;
8201 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
, 0, true);
8203 D
->addAttr(::new (S
.Context
) ReleaseCapabilityAttr(S
.Context
, AL
, Args
.data(),
8207 static void handleRequiresCapabilityAttr(Sema
&S
, Decl
*D
,
8208 const ParsedAttr
&AL
) {
8209 if (!AL
.checkAtLeastNumArgs(S
, 1))
8212 // check that all arguments are lockable objects
8213 SmallVector
<Expr
*, 1> Args
;
8214 checkAttrArgsAreCapabilityObjs(S
, D
, AL
, Args
);
8218 RequiresCapabilityAttr
*RCA
= ::new (S
.Context
)
8219 RequiresCapabilityAttr(S
.Context
, AL
, Args
.data(), Args
.size());
8224 static void handleDeprecatedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8225 if (const auto *NSD
= dyn_cast
<NamespaceDecl
>(D
)) {
8226 if (NSD
->isAnonymousNamespace()) {
8227 S
.Diag(AL
.getLoc(), diag::warn_deprecated_anonymous_namespace
);
8228 // Do not want to attach the attribute to the namespace because that will
8229 // cause confusing diagnostic reports for uses of declarations within the
8233 } else if (isa
<UsingDecl
, UnresolvedUsingTypenameDecl
,
8234 UnresolvedUsingValueDecl
>(D
)) {
8235 S
.Diag(AL
.getRange().getBegin(), diag::warn_deprecated_ignored_on_using
)
8240 // Handle the cases where the attribute has a text message.
8241 StringRef Str
, Replacement
;
8242 if (AL
.isArgExpr(0) && AL
.getArgAsExpr(0) &&
8243 !S
.checkStringLiteralArgumentAttr(AL
, 0, Str
))
8246 // Support a single optional message only for Declspec and [[]] spellings.
8247 if (AL
.isDeclspecAttribute() || AL
.isStandardAttributeSyntax())
8248 AL
.checkAtMostNumArgs(S
, 1);
8249 else if (AL
.isArgExpr(1) && AL
.getArgAsExpr(1) &&
8250 !S
.checkStringLiteralArgumentAttr(AL
, 1, Replacement
))
8253 if (!S
.getLangOpts().CPlusPlus14
&& AL
.isCXX11Attribute() && !AL
.isGNUScope())
8254 S
.Diag(AL
.getLoc(), diag::ext_cxx14_attr
) << AL
;
8256 D
->addAttr(::new (S
.Context
) DeprecatedAttr(S
.Context
, AL
, Str
, Replacement
));
8259 static bool isGlobalVar(const Decl
*D
) {
8260 if (const auto *S
= dyn_cast
<VarDecl
>(D
))
8261 return S
->hasGlobalStorage();
8265 static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer
) {
8266 return Sanitizer
== "address" || Sanitizer
== "hwaddress" ||
8267 Sanitizer
== "memtag";
8270 static void handleNoSanitizeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8271 if (!AL
.checkAtLeastNumArgs(S
, 1))
8274 std::vector
<StringRef
> Sanitizers
;
8276 for (unsigned I
= 0, E
= AL
.getNumArgs(); I
!= E
; ++I
) {
8277 StringRef SanitizerName
;
8278 SourceLocation LiteralLoc
;
8280 if (!S
.checkStringLiteralArgumentAttr(AL
, I
, SanitizerName
, &LiteralLoc
))
8283 if (parseSanitizerValue(SanitizerName
, /*AllowGroups=*/true) ==
8285 SanitizerName
!= "coverage")
8286 S
.Diag(LiteralLoc
, diag::warn_unknown_sanitizer_ignored
) << SanitizerName
;
8287 else if (isGlobalVar(D
) && !isSanitizerAttributeAllowedOnGlobals(SanitizerName
))
8288 S
.Diag(D
->getLocation(), diag::warn_attribute_type_not_supported_global
)
8289 << AL
<< SanitizerName
;
8290 Sanitizers
.push_back(SanitizerName
);
8293 D
->addAttr(::new (S
.Context
) NoSanitizeAttr(S
.Context
, AL
, Sanitizers
.data(),
8294 Sanitizers
.size()));
8297 static void handleNoSanitizeSpecificAttr(Sema
&S
, Decl
*D
,
8298 const ParsedAttr
&AL
) {
8299 StringRef AttrName
= AL
.getAttrName()->getName();
8300 normalizeName(AttrName
);
8301 StringRef SanitizerName
= llvm::StringSwitch
<StringRef
>(AttrName
)
8302 .Case("no_address_safety_analysis", "address")
8303 .Case("no_sanitize_address", "address")
8304 .Case("no_sanitize_thread", "thread")
8305 .Case("no_sanitize_memory", "memory");
8306 if (isGlobalVar(D
) && SanitizerName
!= "address")
8307 S
.Diag(D
->getLocation(), diag::err_attribute_wrong_decl_type
)
8308 << AL
<< AL
.isRegularKeywordAttribute() << ExpectedFunction
;
8310 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
8311 // NoSanitizeAttr object; but we need to calculate the correct spelling list
8312 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
8313 // has the same spellings as the index for NoSanitizeAttr. We don't have a
8314 // general way to "translate" between the two, so this hack attempts to work
8315 // around the issue with hard-coded indices. This is critical for calling
8316 // getSpelling() or prettyPrint() on the resulting semantic attribute object
8317 // without failing assertions.
8318 unsigned TranslatedSpellingIndex
= 0;
8319 if (AL
.isStandardAttributeSyntax())
8320 TranslatedSpellingIndex
= 1;
8322 AttributeCommonInfo Info
= AL
;
8323 Info
.setAttributeSpellingListIndex(TranslatedSpellingIndex
);
8324 D
->addAttr(::new (S
.Context
)
8325 NoSanitizeAttr(S
.Context
, Info
, &SanitizerName
, 1));
8328 static void handleInternalLinkageAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8329 if (InternalLinkageAttr
*Internal
= S
.mergeInternalLinkageAttr(D
, AL
))
8330 D
->addAttr(Internal
);
8333 static void handleOpenCLNoSVMAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8334 if (S
.LangOpts
.getOpenCLCompatibleVersion() < 200)
8335 S
.Diag(AL
.getLoc(), diag::err_attribute_requires_opencl_version
)
8336 << AL
<< "2.0" << 1;
8338 S
.Diag(AL
.getLoc(), diag::warn_opencl_attr_deprecated_ignored
)
8339 << AL
<< S
.LangOpts
.getOpenCLVersionString();
8342 static void handleOpenCLAccessAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8343 if (D
->isInvalidDecl())
8346 // Check if there is only one access qualifier.
8347 if (D
->hasAttr
<OpenCLAccessAttr
>()) {
8348 if (D
->getAttr
<OpenCLAccessAttr
>()->getSemanticSpelling() ==
8349 AL
.getSemanticSpelling()) {
8350 S
.Diag(AL
.getLoc(), diag::warn_duplicate_declspec
)
8351 << AL
.getAttrName()->getName() << AL
.getRange();
8353 S
.Diag(AL
.getLoc(), diag::err_opencl_multiple_access_qualifiers
)
8354 << D
->getSourceRange();
8355 D
->setInvalidDecl(true);
8360 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
8361 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
8362 // cannot read from and write to the same pipe object. Using the read_write
8363 // (or __read_write) qualifier with the pipe qualifier is a compilation error.
8364 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
8365 // __opencl_c_read_write_images feature, image objects specified as arguments
8366 // to a kernel can additionally be declared to be read-write.
8367 // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
8368 // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
8369 if (const auto *PDecl
= dyn_cast
<ParmVarDecl
>(D
)) {
8370 const Type
*DeclTy
= PDecl
->getType().getCanonicalType().getTypePtr();
8371 if (AL
.getAttrName()->getName().contains("read_write")) {
8372 bool ReadWriteImagesUnsupported
=
8373 (S
.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
8374 (S
.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
8375 !S
.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
8377 if (ReadWriteImagesUnsupported
|| DeclTy
->isPipeType()) {
8378 S
.Diag(AL
.getLoc(), diag::err_opencl_invalid_read_write
)
8379 << AL
<< PDecl
->getType() << DeclTy
->isImageType();
8380 D
->setInvalidDecl(true);
8386 D
->addAttr(::new (S
.Context
) OpenCLAccessAttr(S
.Context
, AL
));
8389 static void handleZeroCallUsedRegsAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8390 // Check that the argument is a string literal.
8392 SourceLocation LiteralLoc
;
8393 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, KindStr
, &LiteralLoc
))
8396 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind
;
8397 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr
, Kind
)) {
8398 S
.Diag(LiteralLoc
, diag::warn_attribute_type_not_supported
)
8403 D
->dropAttr
<ZeroCallUsedRegsAttr
>();
8404 D
->addAttr(ZeroCallUsedRegsAttr::Create(S
.Context
, Kind
, AL
));
8407 static void handleCountedByAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8408 if (!AL
.isArgIdent(0)) {
8409 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
8410 << AL
<< AANT_ArgumentIdentifier
;
8414 IdentifierLoc
*IL
= AL
.getArgAsIdent(0);
8415 CountedByAttr
*CBA
=
8416 ::new (S
.Context
) CountedByAttr(S
.Context
, AL
, IL
->Ident
);
8417 CBA
->setCountedByFieldLoc(IL
->Loc
);
8421 bool Sema::CheckCountedByAttr(Scope
*S
, const FieldDecl
*FD
) {
8422 const auto *CBA
= FD
->getAttr
<CountedByAttr
>();
8423 const IdentifierInfo
*FieldName
= CBA
->getCountedByField();
8424 DeclarationNameInfo
NameInfo(FieldName
,
8425 CBA
->getCountedByFieldLoc().getBegin());
8427 LookupResult
MemResult(*this, NameInfo
, Sema::LookupMemberName
);
8428 LookupName(MemResult
, S
);
8430 if (MemResult
.empty()) {
8431 // The "counted_by" field needs to exist within the struct.
8432 LookupResult
OrdResult(*this, NameInfo
, Sema::LookupOrdinaryName
);
8433 LookupName(OrdResult
, S
);
8435 if (!OrdResult
.empty()) {
8436 SourceRange SR
= FD
->getLocation();
8437 Diag(SR
.getBegin(), diag::err_counted_by_must_be_in_structure
)
8440 if (auto *ND
= OrdResult
.getAsSingle
<NamedDecl
>()) {
8441 SR
= ND
->getLocation();
8442 Diag(SR
.getBegin(), diag::note_flexible_array_counted_by_attr_field
)
8449 DeclFilterCCC
<FieldDecl
> Filter(FieldName
);
8450 return DiagnoseEmptyLookup(S
, SS
, MemResult
, Filter
, nullptr, std::nullopt
,
8451 const_cast<DeclContext
*>(FD
->getDeclContext()));
8454 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel
=
8455 Context
.getLangOpts().getStrictFlexArraysLevel();
8457 if (!Decl::isFlexibleArrayMemberLike(Context
, FD
, FD
->getType(),
8458 StrictFlexArraysLevel
, true)) {
8459 // The "counted_by" attribute must be on a flexible array member.
8460 SourceRange SR
= FD
->getLocation();
8461 Diag(SR
.getBegin(), diag::err_counted_by_attr_not_on_flexible_array_member
)
8466 if (const FieldDecl
*Field
= MemResult
.getAsSingle
<FieldDecl
>()) {
8467 if (Field
->hasAttr
<CountedByAttr
>()) {
8468 // The "counted_by" field can't point to the flexible array member.
8469 SourceRange SR
= CBA
->getCountedByFieldLoc();
8470 Diag(SR
.getBegin(), diag::err_counted_by_attr_refers_to_flexible_array
)
8471 << CBA
->getCountedByField() << SR
;
8475 if (!Field
->getType()->isIntegerType() ||
8476 Field
->getType()->isBooleanType()) {
8477 // The "counted_by" field must have an integer type.
8478 SourceRange SR
= CBA
->getCountedByFieldLoc();
8480 diag::err_flexible_array_counted_by_attr_field_not_integer
)
8481 << CBA
->getCountedByField() << SR
;
8483 SR
= Field
->getLocation();
8484 Diag(SR
.getBegin(), diag::note_flexible_array_counted_by_attr_field
)
8493 static void handleFunctionReturnThunksAttr(Sema
&S
, Decl
*D
,
8494 const ParsedAttr
&AL
) {
8496 SourceLocation LiteralLoc
;
8497 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, KindStr
, &LiteralLoc
))
8500 FunctionReturnThunksAttr::Kind Kind
;
8501 if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr
, Kind
)) {
8502 S
.Diag(LiteralLoc
, diag::warn_attribute_type_not_supported
)
8506 // FIXME: it would be good to better handle attribute merging rather than
8507 // silently replacing the existing attribute, so long as it does not break
8508 // the expected codegen tests.
8509 D
->dropAttr
<FunctionReturnThunksAttr
>();
8510 D
->addAttr(FunctionReturnThunksAttr::Create(S
.Context
, Kind
, AL
));
8513 static void handleAvailableOnlyInDefaultEvalMethod(Sema
&S
, Decl
*D
,
8514 const ParsedAttr
&AL
) {
8515 assert(isa
<TypedefNameDecl
>(D
) && "This attribute only applies to a typedef");
8516 handleSimpleAttribute
<AvailableOnlyInDefaultEvalMethodAttr
>(S
, D
, AL
);
8519 static void handleNoMergeAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8520 auto *VDecl
= dyn_cast
<VarDecl
>(D
);
8521 if (VDecl
&& !VDecl
->isFunctionPointerType()) {
8522 S
.Diag(AL
.getLoc(), diag::warn_attribute_ignored_non_function_pointer
)
8526 D
->addAttr(NoMergeAttr::Create(S
.Context
, AL
));
8529 static void handleNoUniqueAddressAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8530 D
->addAttr(NoUniqueAddressAttr::Create(S
.Context
, AL
));
8533 static void handleSYCLKernelAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8534 // The 'sycl_kernel' attribute applies only to function templates.
8535 const auto *FD
= cast
<FunctionDecl
>(D
);
8536 const FunctionTemplateDecl
*FT
= FD
->getDescribedFunctionTemplate();
8537 assert(FT
&& "Function template is expected");
8539 // Function template must have at least two template parameters.
8540 const TemplateParameterList
*TL
= FT
->getTemplateParameters();
8541 if (TL
->size() < 2) {
8542 S
.Diag(FT
->getLocation(), diag::warn_sycl_kernel_num_of_template_params
);
8546 // Template parameters must be typenames.
8547 for (unsigned I
= 0; I
< 2; ++I
) {
8548 const NamedDecl
*TParam
= TL
->getParam(I
);
8549 if (isa
<NonTypeTemplateParmDecl
>(TParam
)) {
8550 S
.Diag(FT
->getLocation(),
8551 diag::warn_sycl_kernel_invalid_template_param_type
);
8556 // Function must have at least one argument.
8557 if (getFunctionOrMethodNumParams(D
) != 1) {
8558 S
.Diag(FT
->getLocation(), diag::warn_sycl_kernel_num_of_function_params
);
8562 // Function must return void.
8563 QualType RetTy
= getFunctionOrMethodResultType(D
);
8564 if (!RetTy
->isVoidType()) {
8565 S
.Diag(FT
->getLocation(), diag::warn_sycl_kernel_return_type
);
8569 handleSimpleAttribute
<SYCLKernelAttr
>(S
, D
, AL
);
8572 static void handleDestroyAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&A
) {
8573 if (!cast
<VarDecl
>(D
)->hasGlobalStorage()) {
8574 S
.Diag(D
->getLocation(), diag::err_destroy_attr_on_non_static_var
)
8575 << (A
.getKind() == ParsedAttr::AT_AlwaysDestroy
);
8579 if (A
.getKind() == ParsedAttr::AT_AlwaysDestroy
)
8580 handleSimpleAttribute
<AlwaysDestroyAttr
>(S
, D
, A
);
8582 handleSimpleAttribute
<NoDestroyAttr
>(S
, D
, A
);
8585 static void handleUninitializedAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8586 assert(cast
<VarDecl
>(D
)->getStorageDuration() == SD_Automatic
&&
8587 "uninitialized is only valid on automatic duration variables");
8588 D
->addAttr(::new (S
.Context
) UninitializedAttr(S
.Context
, AL
));
8591 static bool tryMakeVariablePseudoStrong(Sema
&S
, VarDecl
*VD
,
8592 bool DiagnoseFailure
) {
8593 QualType Ty
= VD
->getType();
8594 if (!Ty
->isObjCRetainableType()) {
8595 if (DiagnoseFailure
) {
8596 S
.Diag(VD
->getBeginLoc(), diag::warn_ignored_objc_externally_retained
)
8602 Qualifiers::ObjCLifetime LifetimeQual
= Ty
.getQualifiers().getObjCLifetime();
8604 // Sema::inferObjCARCLifetime must run after processing decl attributes
8605 // (because __block lowers to an attribute), so if the lifetime hasn't been
8606 // explicitly specified, infer it locally now.
8607 if (LifetimeQual
== Qualifiers::OCL_None
)
8608 LifetimeQual
= Ty
->getObjCARCImplicitLifetime();
8610 // The attributes only really makes sense for __strong variables; ignore any
8611 // attempts to annotate a parameter with any other lifetime qualifier.
8612 if (LifetimeQual
!= Qualifiers::OCL_Strong
) {
8613 if (DiagnoseFailure
) {
8614 S
.Diag(VD
->getBeginLoc(), diag::warn_ignored_objc_externally_retained
)
8620 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
8621 // to ensure that the variable is 'const' so that we can error on
8622 // modification, which can otherwise over-release.
8623 VD
->setType(Ty
.withConst());
8624 VD
->setARCPseudoStrong(true);
8628 static void handleObjCExternallyRetainedAttr(Sema
&S
, Decl
*D
,
8629 const ParsedAttr
&AL
) {
8630 if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
8631 assert(!isa
<ParmVarDecl
>(VD
) && "should be diagnosed automatically");
8632 if (!VD
->hasLocalStorage()) {
8633 S
.Diag(D
->getBeginLoc(), diag::warn_ignored_objc_externally_retained
)
8638 if (!tryMakeVariablePseudoStrong(S
, VD
, /*DiagnoseFailure=*/true))
8641 handleSimpleAttribute
<ObjCExternallyRetainedAttr
>(S
, D
, AL
);
8645 // If D is a function-like declaration (method, block, or function), then we
8646 // make every parameter psuedo-strong.
8647 unsigned NumParams
=
8648 hasFunctionProto(D
) ? getFunctionOrMethodNumParams(D
) : 0;
8649 for (unsigned I
= 0; I
!= NumParams
; ++I
) {
8650 auto *PVD
= const_cast<ParmVarDecl
*>(getFunctionOrMethodParam(D
, I
));
8651 QualType Ty
= PVD
->getType();
8653 // If a user wrote a parameter with __strong explicitly, then assume they
8654 // want "real" strong semantics for that parameter. This works because if
8655 // the parameter was written with __strong, then the strong qualifier will
8657 if (Ty
.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
8658 Qualifiers::OCL_Strong
)
8661 tryMakeVariablePseudoStrong(S
, PVD
, /*DiagnoseFailure=*/false);
8663 handleSimpleAttribute
<ObjCExternallyRetainedAttr
>(S
, D
, AL
);
8666 static void handleMIGServerRoutineAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8667 // Check that the return type is a `typedef int kern_return_t` or a typedef
8668 // around it, because otherwise MIG convention checks make no sense.
8669 // BlockDecl doesn't store a return type, so it's annoying to check,
8670 // so let's skip it for now.
8671 if (!isa
<BlockDecl
>(D
)) {
8672 QualType T
= getFunctionOrMethodResultType(D
);
8673 bool IsKernReturnT
= false;
8674 while (const auto *TT
= T
->getAs
<TypedefType
>()) {
8675 IsKernReturnT
= (TT
->getDecl()->getName() == "kern_return_t");
8678 if (!IsKernReturnT
|| T
.getCanonicalType() != S
.getASTContext().IntTy
) {
8679 S
.Diag(D
->getBeginLoc(),
8680 diag::warn_mig_server_routine_does_not_return_kern_return_t
);
8685 handleSimpleAttribute
<MIGServerRoutineAttr
>(S
, D
, AL
);
8688 static void handleMSAllocatorAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8689 // Warn if the return type is not a pointer or reference type.
8690 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
8691 QualType RetTy
= FD
->getReturnType();
8692 if (!RetTy
->isPointerType() && !RetTy
->isReferenceType()) {
8693 S
.Diag(AL
.getLoc(), diag::warn_declspec_allocator_nonpointer
)
8694 << AL
.getRange() << RetTy
;
8699 handleSimpleAttribute
<MSAllocatorAttr
>(S
, D
, AL
);
8702 static void handleAcquireHandleAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8703 if (AL
.isUsedAsTypeAttr())
8705 // Warn if the parameter is definitely not an output parameter.
8706 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(D
)) {
8707 if (PVD
->getType()->isIntegerType()) {
8708 S
.Diag(AL
.getLoc(), diag::err_attribute_output_parameter
)
8714 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Argument
))
8716 D
->addAttr(AcquireHandleAttr::Create(S
.Context
, Argument
, AL
));
8719 template<typename Attr
>
8720 static void handleHandleAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8722 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Argument
))
8724 D
->addAttr(Attr::Create(S
.Context
, Argument
, AL
));
8727 template<typename Attr
>
8728 static void handleUnsafeBufferUsage(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8729 D
->addAttr(Attr::Create(S
.Context
, AL
));
8732 static void handleCFGuardAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8733 // The guard attribute takes a single identifier argument.
8735 if (!AL
.isArgIdent(0)) {
8736 S
.Diag(AL
.getLoc(), diag::err_attribute_argument_type
)
8737 << AL
<< AANT_ArgumentIdentifier
;
8741 CFGuardAttr::GuardArg Arg
;
8742 IdentifierInfo
*II
= AL
.getArgAsIdent(0)->Ident
;
8743 if (!CFGuardAttr::ConvertStrToGuardArg(II
->getName(), Arg
)) {
8744 S
.Diag(AL
.getLoc(), diag::warn_attribute_type_not_supported
) << AL
<< II
;
8748 D
->addAttr(::new (S
.Context
) CFGuardAttr(S
.Context
, AL
, Arg
));
8752 template <typename AttrTy
>
8753 static const AttrTy
*findEnforceTCBAttrByName(Decl
*D
, StringRef Name
) {
8754 auto Attrs
= D
->specific_attrs
<AttrTy
>();
8755 auto I
= llvm::find_if(Attrs
,
8756 [Name
](const AttrTy
*A
) {
8757 return A
->getTCBName() == Name
;
8759 return I
== Attrs
.end() ? nullptr : *I
;
8762 template <typename AttrTy
, typename ConflictingAttrTy
>
8763 static void handleEnforceTCBAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8765 if (!S
.checkStringLiteralArgumentAttr(AL
, 0, Argument
))
8768 // A function cannot be have both regular and leaf membership in the same TCB.
8769 if (const ConflictingAttrTy
*ConflictingAttr
=
8770 findEnforceTCBAttrByName
<ConflictingAttrTy
>(D
, Argument
)) {
8771 // We could attach a note to the other attribute but in this case
8772 // there's no need given how the two are very close to each other.
8773 S
.Diag(AL
.getLoc(), diag::err_tcb_conflicting_attributes
)
8774 << AL
.getAttrName()->getName() << ConflictingAttr
->getAttrName()->getName()
8777 // Error recovery: drop the non-leaf attribute so that to suppress
8778 // all future warnings caused by erroneous attributes. The leaf attribute
8779 // needs to be kept because it can only suppresses warnings, not cause them.
8780 D
->dropAttr
<EnforceTCBAttr
>();
8784 D
->addAttr(AttrTy::Create(S
.Context
, Argument
, AL
));
8787 template <typename AttrTy
, typename ConflictingAttrTy
>
8788 static AttrTy
*mergeEnforceTCBAttrImpl(Sema
&S
, Decl
*D
, const AttrTy
&AL
) {
8789 // Check if the new redeclaration has different leaf-ness in the same TCB.
8790 StringRef TCBName
= AL
.getTCBName();
8791 if (const ConflictingAttrTy
*ConflictingAttr
=
8792 findEnforceTCBAttrByName
<ConflictingAttrTy
>(D
, TCBName
)) {
8793 S
.Diag(ConflictingAttr
->getLoc(), diag::err_tcb_conflicting_attributes
)
8794 << ConflictingAttr
->getAttrName()->getName()
8795 << AL
.getAttrName()->getName() << TCBName
;
8797 // Add a note so that the user could easily find the conflicting attribute.
8798 S
.Diag(AL
.getLoc(), diag::note_conflicting_attribute
);
8800 // More error recovery.
8801 D
->dropAttr
<EnforceTCBAttr
>();
8805 ASTContext
&Context
= S
.getASTContext();
8806 return ::new(Context
) AttrTy(Context
, AL
, AL
.getTCBName());
8809 EnforceTCBAttr
*Sema::mergeEnforceTCBAttr(Decl
*D
, const EnforceTCBAttr
&AL
) {
8810 return mergeEnforceTCBAttrImpl
<EnforceTCBAttr
, EnforceTCBLeafAttr
>(
8814 EnforceTCBLeafAttr
*Sema::mergeEnforceTCBLeafAttr(
8815 Decl
*D
, const EnforceTCBLeafAttr
&AL
) {
8816 return mergeEnforceTCBAttrImpl
<EnforceTCBLeafAttr
, EnforceTCBAttr
>(
8820 //===----------------------------------------------------------------------===//
8821 // Top Level Sema Entry Points
8822 //===----------------------------------------------------------------------===//
8824 // Returns true if the attribute must delay setting its arguments until after
8825 // template instantiation, and false otherwise.
8826 static bool MustDelayAttributeArguments(const ParsedAttr
&AL
) {
8827 // Only attributes that accept expression parameter packs can delay arguments.
8828 if (!AL
.acceptsExprPack())
8831 bool AttrHasVariadicArg
= AL
.hasVariadicArg();
8832 unsigned AttrNumArgs
= AL
.getNumArgMembers();
8833 for (size_t I
= 0; I
< std::min(AL
.getNumArgs(), AttrNumArgs
); ++I
) {
8834 bool IsLastAttrArg
= I
== (AttrNumArgs
- 1);
8835 // If the argument is the last argument and it is variadic it can contain
8837 if (IsLastAttrArg
&& AttrHasVariadicArg
)
8839 Expr
*E
= AL
.getArgAsExpr(I
);
8840 bool ArgMemberCanHoldExpr
= AL
.isParamExpr(I
);
8841 // If the expression is a pack expansion then arguments must be delayed
8842 // unless the argument is an expression and it is the last argument of the
8844 if (isa
<PackExpansionExpr
>(E
))
8845 return !(IsLastAttrArg
&& ArgMemberCanHoldExpr
);
8846 // Last case is if the expression is value dependent then it must delay
8847 // arguments unless the corresponding argument is able to hold the
8849 if (E
->isValueDependent() && !ArgMemberCanHoldExpr
)
8856 static void handleArmNewZaAttr(Sema
&S
, Decl
*D
, const ParsedAttr
&AL
) {
8857 if (auto *FPT
= dyn_cast
<FunctionProtoType
>(D
->getFunctionType())) {
8858 if (FPT
->getAArch64SMEAttributes() &
8859 FunctionType::SME_PStateZASharedMask
) {
8860 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
8861 << AL
<< "'__arm_shared_za'" << true;
8864 if (FPT
->getAArch64SMEAttributes() &
8865 FunctionType::SME_PStateZAPreservedMask
) {
8866 S
.Diag(AL
.getLoc(), diag::err_attributes_are_not_compatible
)
8867 << AL
<< "'__arm_preserves_za'" << true;
8874 handleSimpleAttribute
<ArmNewZAAttr
>(S
, D
, AL
);
8877 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
8878 /// the attribute applies to decls. If the attribute is a type attribute, just
8879 /// silently ignore it if a GNU attribute.
8881 ProcessDeclAttribute(Sema
&S
, Scope
*scope
, Decl
*D
, const ParsedAttr
&AL
,
8882 const Sema::ProcessDeclAttributeOptions
&Options
) {
8883 if (AL
.isInvalid() || AL
.getKind() == ParsedAttr::IgnoredAttribute
)
8886 // Ignore C++11 attributes on declarator chunks: they appertain to the type
8888 if (AL
.isCXX11Attribute() && !Options
.IncludeCXX11Attributes
)
8891 // Unknown attributes are automatically warned on. Target-specific attributes
8892 // which do not apply to the current target architecture are treated as
8893 // though they were unknown attributes.
8894 if (AL
.getKind() == ParsedAttr::UnknownAttribute
||
8895 !AL
.existsInTarget(S
.Context
.getTargetInfo())) {
8897 AL
.isRegularKeywordAttribute()
8898 ? (unsigned)diag::err_keyword_not_supported_on_target
8899 : AL
.isDeclspecAttribute()
8900 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
8901 : (unsigned)diag::warn_unknown_attribute_ignored
)
8902 << AL
<< AL
.getRange();
8906 // Check if argument population must delayed to after template instantiation.
8907 bool MustDelayArgs
= MustDelayAttributeArguments(AL
);
8909 // Argument number check must be skipped if arguments are delayed.
8910 if (S
.checkCommonAttributeFeatures(D
, AL
, MustDelayArgs
))
8913 if (MustDelayArgs
) {
8914 AL
.handleAttrWithDelayedArgs(S
, D
);
8918 switch (AL
.getKind()) {
8920 if (AL
.getInfo().handleDeclAttribute(S
, D
, AL
) != ParsedAttrInfo::NotHandled
)
8922 if (!AL
.isStmtAttr()) {
8923 assert(AL
.isTypeAttr() && "Non-type attribute not handled");
8925 if (AL
.isTypeAttr()) {
8926 if (Options
.IgnoreTypeAttributes
)
8928 if (!AL
.isStandardAttributeSyntax() && !AL
.isRegularKeywordAttribute()) {
8929 // Non-[[]] type attributes are handled in processTypeAttrs(); silently
8934 // According to the C and C++ standards, we should never see a
8935 // [[]] type attribute on a declaration. However, we have in the past
8936 // allowed some type attributes to "slide" to the `DeclSpec`, so we need
8937 // to continue to support this legacy behavior. We only do this, however,
8939 // - we actually have a `DeclSpec`, i.e. if we're looking at a
8940 // `DeclaratorDecl`, or
8941 // - we are looking at an alias-declaration, where historically we have
8942 // allowed type attributes after the identifier to slide to the type.
8943 if (AL
.slidesFromDeclToDeclSpecLegacyBehavior() &&
8944 isa
<DeclaratorDecl
, TypeAliasDecl
>(D
)) {
8945 // Suggest moving the attribute to the type instead, but only for our
8946 // own vendor attributes; moving other vendors' attributes might hurt
8948 if (AL
.isClangScope()) {
8949 S
.Diag(AL
.getLoc(), diag::warn_type_attribute_deprecated_on_decl
)
8950 << AL
<< D
->getLocation();
8953 // Allow this type attribute to be handled in processTypeAttrs();
8954 // silently move on.
8958 if (AL
.getKind() == ParsedAttr::AT_Regparm
) {
8959 // `regparm` is a special case: It's a type attribute but we still want
8960 // to treat it as if it had been written on the declaration because that
8961 // way we'll be able to handle it directly in `processTypeAttr()`.
8962 // If we treated `regparm` it as if it had been written on the
8963 // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
8964 // would try to move it to the declarator, but that doesn't work: We
8965 // can't remove the attribute from the list of declaration attributes
8966 // because it might be needed by other declarators in the same
8971 if (AL
.getKind() == ParsedAttr::AT_VectorSize
) {
8972 // `vector_size` is a special case: It's a type attribute semantically,
8973 // but GCC expects the [[]] syntax to be written on the declaration (and
8974 // warns that the attribute has no effect if it is placed on the
8975 // decl-specifier-seq).
8976 // Silently move on and allow the attribute to be handled in
8977 // processTypeAttr().
8981 if (AL
.getKind() == ParsedAttr::AT_NoDeref
) {
8982 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8983 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8984 // We allow processTypeAttrs() to emit a warning and silently move on.
8988 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
8989 // statement attribute is not written on a declaration, but this code is
8990 // needed for type attributes as well as statement attributes in Attr.td
8991 // that do not list any subjects.
8992 S
.Diag(AL
.getLoc(), diag::err_attribute_invalid_on_decl
)
8993 << AL
<< AL
.isRegularKeywordAttribute() << D
->getLocation();
8995 case ParsedAttr::AT_Interrupt
:
8996 handleInterruptAttr(S
, D
, AL
);
8998 case ParsedAttr::AT_X86ForceAlignArgPointer
:
8999 handleX86ForceAlignArgPointerAttr(S
, D
, AL
);
9001 case ParsedAttr::AT_ReadOnlyPlacement
:
9002 handleSimpleAttribute
<ReadOnlyPlacementAttr
>(S
, D
, AL
);
9004 case ParsedAttr::AT_DLLExport
:
9005 case ParsedAttr::AT_DLLImport
:
9006 handleDLLAttr(S
, D
, AL
);
9008 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize
:
9009 handleAMDGPUFlatWorkGroupSizeAttr(S
, D
, AL
);
9011 case ParsedAttr::AT_AMDGPUWavesPerEU
:
9012 handleAMDGPUWavesPerEUAttr(S
, D
, AL
);
9014 case ParsedAttr::AT_AMDGPUNumSGPR
:
9015 handleAMDGPUNumSGPRAttr(S
, D
, AL
);
9017 case ParsedAttr::AT_AMDGPUNumVGPR
:
9018 handleAMDGPUNumVGPRAttr(S
, D
, AL
);
9020 case ParsedAttr::AT_AVRSignal
:
9021 handleAVRSignalAttr(S
, D
, AL
);
9023 case ParsedAttr::AT_BPFPreserveAccessIndex
:
9024 handleBPFPreserveAccessIndexAttr(S
, D
, AL
);
9026 case ParsedAttr::AT_BTFDeclTag
:
9027 handleBTFDeclTagAttr(S
, D
, AL
);
9029 case ParsedAttr::AT_WebAssemblyExportName
:
9030 handleWebAssemblyExportNameAttr(S
, D
, AL
);
9032 case ParsedAttr::AT_WebAssemblyImportModule
:
9033 handleWebAssemblyImportModuleAttr(S
, D
, AL
);
9035 case ParsedAttr::AT_WebAssemblyImportName
:
9036 handleWebAssemblyImportNameAttr(S
, D
, AL
);
9038 case ParsedAttr::AT_IBOutlet
:
9039 handleIBOutlet(S
, D
, AL
);
9041 case ParsedAttr::AT_IBOutletCollection
:
9042 handleIBOutletCollection(S
, D
, AL
);
9044 case ParsedAttr::AT_IFunc
:
9045 handleIFuncAttr(S
, D
, AL
);
9047 case ParsedAttr::AT_Alias
:
9048 handleAliasAttr(S
, D
, AL
);
9050 case ParsedAttr::AT_Aligned
:
9051 handleAlignedAttr(S
, D
, AL
);
9053 case ParsedAttr::AT_AlignValue
:
9054 handleAlignValueAttr(S
, D
, AL
);
9056 case ParsedAttr::AT_AllocSize
:
9057 handleAllocSizeAttr(S
, D
, AL
);
9059 case ParsedAttr::AT_AlwaysInline
:
9060 handleAlwaysInlineAttr(S
, D
, AL
);
9062 case ParsedAttr::AT_AnalyzerNoReturn
:
9063 handleAnalyzerNoReturnAttr(S
, D
, AL
);
9065 case ParsedAttr::AT_TLSModel
:
9066 handleTLSModelAttr(S
, D
, AL
);
9068 case ParsedAttr::AT_Annotate
:
9069 handleAnnotateAttr(S
, D
, AL
);
9071 case ParsedAttr::AT_Availability
:
9072 handleAvailabilityAttr(S
, D
, AL
);
9074 case ParsedAttr::AT_CarriesDependency
:
9075 handleDependencyAttr(S
, scope
, D
, AL
);
9077 case ParsedAttr::AT_CPUDispatch
:
9078 case ParsedAttr::AT_CPUSpecific
:
9079 handleCPUSpecificAttr(S
, D
, AL
);
9081 case ParsedAttr::AT_Common
:
9082 handleCommonAttr(S
, D
, AL
);
9084 case ParsedAttr::AT_CUDAConstant
:
9085 handleConstantAttr(S
, D
, AL
);
9087 case ParsedAttr::AT_PassObjectSize
:
9088 handlePassObjectSizeAttr(S
, D
, AL
);
9090 case ParsedAttr::AT_Constructor
:
9091 handleConstructorAttr(S
, D
, AL
);
9093 case ParsedAttr::AT_Deprecated
:
9094 handleDeprecatedAttr(S
, D
, AL
);
9096 case ParsedAttr::AT_Destructor
:
9097 handleDestructorAttr(S
, D
, AL
);
9099 case ParsedAttr::AT_EnableIf
:
9100 handleEnableIfAttr(S
, D
, AL
);
9102 case ParsedAttr::AT_Error
:
9103 handleErrorAttr(S
, D
, AL
);
9105 case ParsedAttr::AT_DiagnoseIf
:
9106 handleDiagnoseIfAttr(S
, D
, AL
);
9108 case ParsedAttr::AT_DiagnoseAsBuiltin
:
9109 handleDiagnoseAsBuiltinAttr(S
, D
, AL
);
9111 case ParsedAttr::AT_NoBuiltin
:
9112 handleNoBuiltinAttr(S
, D
, AL
);
9114 case ParsedAttr::AT_ExtVectorType
:
9115 handleExtVectorTypeAttr(S
, D
, AL
);
9117 case ParsedAttr::AT_ExternalSourceSymbol
:
9118 handleExternalSourceSymbolAttr(S
, D
, AL
);
9120 case ParsedAttr::AT_MinSize
:
9121 handleMinSizeAttr(S
, D
, AL
);
9123 case ParsedAttr::AT_OptimizeNone
:
9124 handleOptimizeNoneAttr(S
, D
, AL
);
9126 case ParsedAttr::AT_EnumExtensibility
:
9127 handleEnumExtensibilityAttr(S
, D
, AL
);
9129 case ParsedAttr::AT_SYCLKernel
:
9130 handleSYCLKernelAttr(S
, D
, AL
);
9132 case ParsedAttr::AT_SYCLSpecialClass
:
9133 handleSimpleAttribute
<SYCLSpecialClassAttr
>(S
, D
, AL
);
9135 case ParsedAttr::AT_Format
:
9136 handleFormatAttr(S
, D
, AL
);
9138 case ParsedAttr::AT_FormatArg
:
9139 handleFormatArgAttr(S
, D
, AL
);
9141 case ParsedAttr::AT_Callback
:
9142 handleCallbackAttr(S
, D
, AL
);
9144 case ParsedAttr::AT_CalledOnce
:
9145 handleCalledOnceAttr(S
, D
, AL
);
9147 case ParsedAttr::AT_NVPTXKernel
:
9148 case ParsedAttr::AT_CUDAGlobal
:
9149 handleGlobalAttr(S
, D
, AL
);
9151 case ParsedAttr::AT_CUDADevice
:
9152 handleDeviceAttr(S
, D
, AL
);
9154 case ParsedAttr::AT_HIPManaged
:
9155 handleManagedAttr(S
, D
, AL
);
9157 case ParsedAttr::AT_GNUInline
:
9158 handleGNUInlineAttr(S
, D
, AL
);
9160 case ParsedAttr::AT_CUDALaunchBounds
:
9161 handleLaunchBoundsAttr(S
, D
, AL
);
9163 case ParsedAttr::AT_Restrict
:
9164 handleRestrictAttr(S
, D
, AL
);
9166 case ParsedAttr::AT_Mode
:
9167 handleModeAttr(S
, D
, AL
);
9169 case ParsedAttr::AT_NonNull
:
9170 if (auto *PVD
= dyn_cast
<ParmVarDecl
>(D
))
9171 handleNonNullAttrParameter(S
, PVD
, AL
);
9173 handleNonNullAttr(S
, D
, AL
);
9175 case ParsedAttr::AT_ReturnsNonNull
:
9176 handleReturnsNonNullAttr(S
, D
, AL
);
9178 case ParsedAttr::AT_NoEscape
:
9179 handleNoEscapeAttr(S
, D
, AL
);
9181 case ParsedAttr::AT_MaybeUndef
:
9182 handleSimpleAttribute
<MaybeUndefAttr
>(S
, D
, AL
);
9184 case ParsedAttr::AT_AssumeAligned
:
9185 handleAssumeAlignedAttr(S
, D
, AL
);
9187 case ParsedAttr::AT_AllocAlign
:
9188 handleAllocAlignAttr(S
, D
, AL
);
9190 case ParsedAttr::AT_Ownership
:
9191 handleOwnershipAttr(S
, D
, AL
);
9193 case ParsedAttr::AT_Naked
:
9194 handleNakedAttr(S
, D
, AL
);
9196 case ParsedAttr::AT_NoReturn
:
9197 handleNoReturnAttr(S
, D
, AL
);
9199 case ParsedAttr::AT_CXX11NoReturn
:
9200 handleStandardNoReturnAttr(S
, D
, AL
);
9202 case ParsedAttr::AT_AnyX86NoCfCheck
:
9203 handleNoCfCheckAttr(S
, D
, AL
);
9205 case ParsedAttr::AT_NoThrow
:
9206 if (!AL
.isUsedAsTypeAttr())
9207 handleSimpleAttribute
<NoThrowAttr
>(S
, D
, AL
);
9209 case ParsedAttr::AT_CUDAShared
:
9210 handleSharedAttr(S
, D
, AL
);
9212 case ParsedAttr::AT_VecReturn
:
9213 handleVecReturnAttr(S
, D
, AL
);
9215 case ParsedAttr::AT_ObjCOwnership
:
9216 handleObjCOwnershipAttr(S
, D
, AL
);
9218 case ParsedAttr::AT_ObjCPreciseLifetime
:
9219 handleObjCPreciseLifetimeAttr(S
, D
, AL
);
9221 case ParsedAttr::AT_ObjCReturnsInnerPointer
:
9222 handleObjCReturnsInnerPointerAttr(S
, D
, AL
);
9224 case ParsedAttr::AT_ObjCRequiresSuper
:
9225 handleObjCRequiresSuperAttr(S
, D
, AL
);
9227 case ParsedAttr::AT_ObjCBridge
:
9228 handleObjCBridgeAttr(S
, D
, AL
);
9230 case ParsedAttr::AT_ObjCBridgeMutable
:
9231 handleObjCBridgeMutableAttr(S
, D
, AL
);
9233 case ParsedAttr::AT_ObjCBridgeRelated
:
9234 handleObjCBridgeRelatedAttr(S
, D
, AL
);
9236 case ParsedAttr::AT_ObjCDesignatedInitializer
:
9237 handleObjCDesignatedInitializer(S
, D
, AL
);
9239 case ParsedAttr::AT_ObjCRuntimeName
:
9240 handleObjCRuntimeName(S
, D
, AL
);
9242 case ParsedAttr::AT_ObjCBoxable
:
9243 handleObjCBoxable(S
, D
, AL
);
9245 case ParsedAttr::AT_NSErrorDomain
:
9246 handleNSErrorDomain(S
, D
, AL
);
9248 case ParsedAttr::AT_CFConsumed
:
9249 case ParsedAttr::AT_NSConsumed
:
9250 case ParsedAttr::AT_OSConsumed
:
9251 S
.AddXConsumedAttr(D
, AL
, parsedAttrToRetainOwnershipKind(AL
),
9252 /*IsTemplateInstantiation=*/false);
9254 case ParsedAttr::AT_OSReturnsRetainedOnZero
:
9255 handleSimpleAttributeOrDiagnose
<OSReturnsRetainedOnZeroAttr
>(
9256 S
, D
, AL
, isValidOSObjectOutParameter(D
),
9257 diag::warn_ns_attribute_wrong_parameter_type
,
9258 /*Extra Args=*/AL
, /*pointer-to-OSObject-pointer*/ 3, AL
.getRange());
9260 case ParsedAttr::AT_OSReturnsRetainedOnNonZero
:
9261 handleSimpleAttributeOrDiagnose
<OSReturnsRetainedOnNonZeroAttr
>(
9262 S
, D
, AL
, isValidOSObjectOutParameter(D
),
9263 diag::warn_ns_attribute_wrong_parameter_type
,
9264 /*Extra Args=*/AL
, /*pointer-to-OSObject-poointer*/ 3, AL
.getRange());
9266 case ParsedAttr::AT_NSReturnsAutoreleased
:
9267 case ParsedAttr::AT_NSReturnsNotRetained
:
9268 case ParsedAttr::AT_NSReturnsRetained
:
9269 case ParsedAttr::AT_CFReturnsNotRetained
:
9270 case ParsedAttr::AT_CFReturnsRetained
:
9271 case ParsedAttr::AT_OSReturnsNotRetained
:
9272 case ParsedAttr::AT_OSReturnsRetained
:
9273 handleXReturnsXRetainedAttr(S
, D
, AL
);
9275 case ParsedAttr::AT_WorkGroupSizeHint
:
9276 handleWorkGroupSize
<WorkGroupSizeHintAttr
>(S
, D
, AL
);
9278 case ParsedAttr::AT_ReqdWorkGroupSize
:
9279 handleWorkGroupSize
<ReqdWorkGroupSizeAttr
>(S
, D
, AL
);
9281 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize
:
9282 handleSubGroupSize(S
, D
, AL
);
9284 case ParsedAttr::AT_VecTypeHint
:
9285 handleVecTypeHint(S
, D
, AL
);
9287 case ParsedAttr::AT_InitPriority
:
9288 handleInitPriorityAttr(S
, D
, AL
);
9290 case ParsedAttr::AT_Packed
:
9291 handlePackedAttr(S
, D
, AL
);
9293 case ParsedAttr::AT_PreferredName
:
9294 handlePreferredName(S
, D
, AL
);
9296 case ParsedAttr::AT_Section
:
9297 handleSectionAttr(S
, D
, AL
);
9299 case ParsedAttr::AT_RandomizeLayout
:
9300 handleRandomizeLayoutAttr(S
, D
, AL
);
9302 case ParsedAttr::AT_NoRandomizeLayout
:
9303 handleNoRandomizeLayoutAttr(S
, D
, AL
);
9305 case ParsedAttr::AT_CodeSeg
:
9306 handleCodeSegAttr(S
, D
, AL
);
9308 case ParsedAttr::AT_Target
:
9309 handleTargetAttr(S
, D
, AL
);
9311 case ParsedAttr::AT_TargetVersion
:
9312 handleTargetVersionAttr(S
, D
, AL
);
9314 case ParsedAttr::AT_TargetClones
:
9315 handleTargetClonesAttr(S
, D
, AL
);
9317 case ParsedAttr::AT_MinVectorWidth
:
9318 handleMinVectorWidthAttr(S
, D
, AL
);
9320 case ParsedAttr::AT_Unavailable
:
9321 handleAttrWithMessage
<UnavailableAttr
>(S
, D
, AL
);
9323 case ParsedAttr::AT_Assumption
:
9324 handleAssumumptionAttr(S
, D
, AL
);
9326 case ParsedAttr::AT_ObjCDirect
:
9327 handleObjCDirectAttr(S
, D
, AL
);
9329 case ParsedAttr::AT_ObjCDirectMembers
:
9330 handleObjCDirectMembersAttr(S
, D
, AL
);
9331 handleSimpleAttribute
<ObjCDirectMembersAttr
>(S
, D
, AL
);
9333 case ParsedAttr::AT_ObjCExplicitProtocolImpl
:
9334 handleObjCSuppresProtocolAttr(S
, D
, AL
);
9336 case ParsedAttr::AT_Unused
:
9337 handleUnusedAttr(S
, D
, AL
);
9339 case ParsedAttr::AT_Visibility
:
9340 handleVisibilityAttr(S
, D
, AL
, false);
9342 case ParsedAttr::AT_TypeVisibility
:
9343 handleVisibilityAttr(S
, D
, AL
, true);
9345 case ParsedAttr::AT_WarnUnusedResult
:
9346 handleWarnUnusedResult(S
, D
, AL
);
9348 case ParsedAttr::AT_WeakRef
:
9349 handleWeakRefAttr(S
, D
, AL
);
9351 case ParsedAttr::AT_WeakImport
:
9352 handleWeakImportAttr(S
, D
, AL
);
9354 case ParsedAttr::AT_TransparentUnion
:
9355 handleTransparentUnionAttr(S
, D
, AL
);
9357 case ParsedAttr::AT_ObjCMethodFamily
:
9358 handleObjCMethodFamilyAttr(S
, D
, AL
);
9360 case ParsedAttr::AT_ObjCNSObject
:
9361 handleObjCNSObject(S
, D
, AL
);
9363 case ParsedAttr::AT_ObjCIndependentClass
:
9364 handleObjCIndependentClass(S
, D
, AL
);
9366 case ParsedAttr::AT_Blocks
:
9367 handleBlocksAttr(S
, D
, AL
);
9369 case ParsedAttr::AT_Sentinel
:
9370 handleSentinelAttr(S
, D
, AL
);
9372 case ParsedAttr::AT_Cleanup
:
9373 handleCleanupAttr(S
, D
, AL
);
9375 case ParsedAttr::AT_NoDebug
:
9376 handleNoDebugAttr(S
, D
, AL
);
9378 case ParsedAttr::AT_CmseNSEntry
:
9379 handleCmseNSEntryAttr(S
, D
, AL
);
9381 case ParsedAttr::AT_StdCall
:
9382 case ParsedAttr::AT_CDecl
:
9383 case ParsedAttr::AT_FastCall
:
9384 case ParsedAttr::AT_ThisCall
:
9385 case ParsedAttr::AT_Pascal
:
9386 case ParsedAttr::AT_RegCall
:
9387 case ParsedAttr::AT_SwiftCall
:
9388 case ParsedAttr::AT_SwiftAsyncCall
:
9389 case ParsedAttr::AT_VectorCall
:
9390 case ParsedAttr::AT_MSABI
:
9391 case ParsedAttr::AT_SysVABI
:
9392 case ParsedAttr::AT_Pcs
:
9393 case ParsedAttr::AT_IntelOclBicc
:
9394 case ParsedAttr::AT_PreserveMost
:
9395 case ParsedAttr::AT_PreserveAll
:
9396 case ParsedAttr::AT_AArch64VectorPcs
:
9397 case ParsedAttr::AT_AArch64SVEPcs
:
9398 case ParsedAttr::AT_AMDGPUKernelCall
:
9399 case ParsedAttr::AT_M68kRTD
:
9400 handleCallConvAttr(S
, D
, AL
);
9402 case ParsedAttr::AT_Suppress
:
9403 handleSuppressAttr(S
, D
, AL
);
9405 case ParsedAttr::AT_Owner
:
9406 case ParsedAttr::AT_Pointer
:
9407 handleLifetimeCategoryAttr(S
, D
, AL
);
9409 case ParsedAttr::AT_OpenCLAccess
:
9410 handleOpenCLAccessAttr(S
, D
, AL
);
9412 case ParsedAttr::AT_OpenCLNoSVM
:
9413 handleOpenCLNoSVMAttr(S
, D
, AL
);
9415 case ParsedAttr::AT_SwiftContext
:
9416 S
.AddParameterABIAttr(D
, AL
, ParameterABI::SwiftContext
);
9418 case ParsedAttr::AT_SwiftAsyncContext
:
9419 S
.AddParameterABIAttr(D
, AL
, ParameterABI::SwiftAsyncContext
);
9421 case ParsedAttr::AT_SwiftErrorResult
:
9422 S
.AddParameterABIAttr(D
, AL
, ParameterABI::SwiftErrorResult
);
9424 case ParsedAttr::AT_SwiftIndirectResult
:
9425 S
.AddParameterABIAttr(D
, AL
, ParameterABI::SwiftIndirectResult
);
9427 case ParsedAttr::AT_InternalLinkage
:
9428 handleInternalLinkageAttr(S
, D
, AL
);
9430 case ParsedAttr::AT_ZeroCallUsedRegs
:
9431 handleZeroCallUsedRegsAttr(S
, D
, AL
);
9433 case ParsedAttr::AT_FunctionReturnThunks
:
9434 handleFunctionReturnThunksAttr(S
, D
, AL
);
9436 case ParsedAttr::AT_NoMerge
:
9437 handleNoMergeAttr(S
, D
, AL
);
9439 case ParsedAttr::AT_NoUniqueAddress
:
9440 handleNoUniqueAddressAttr(S
, D
, AL
);
9443 case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod
:
9444 handleAvailableOnlyInDefaultEvalMethod(S
, D
, AL
);
9447 case ParsedAttr::AT_CountedBy
:
9448 handleCountedByAttr(S
, D
, AL
);
9451 // Microsoft attributes:
9452 case ParsedAttr::AT_LayoutVersion
:
9453 handleLayoutVersion(S
, D
, AL
);
9455 case ParsedAttr::AT_Uuid
:
9456 handleUuidAttr(S
, D
, AL
);
9458 case ParsedAttr::AT_MSInheritance
:
9459 handleMSInheritanceAttr(S
, D
, AL
);
9461 case ParsedAttr::AT_Thread
:
9462 handleDeclspecThreadAttr(S
, D
, AL
);
9466 case ParsedAttr::AT_HLSLNumThreads
:
9467 handleHLSLNumThreadsAttr(S
, D
, AL
);
9469 case ParsedAttr::AT_HLSLSV_GroupIndex
:
9470 handleSimpleAttribute
<HLSLSV_GroupIndexAttr
>(S
, D
, AL
);
9472 case ParsedAttr::AT_HLSLSV_DispatchThreadID
:
9473 handleHLSLSV_DispatchThreadIDAttr(S
, D
, AL
);
9475 case ParsedAttr::AT_HLSLShader
:
9476 handleHLSLShaderAttr(S
, D
, AL
);
9478 case ParsedAttr::AT_HLSLResourceBinding
:
9479 handleHLSLResourceBindingAttr(S
, D
, AL
);
9482 case ParsedAttr::AT_AbiTag
:
9483 handleAbiTagAttr(S
, D
, AL
);
9485 case ParsedAttr::AT_CFGuard
:
9486 handleCFGuardAttr(S
, D
, AL
);
9489 // Thread safety attributes:
9490 case ParsedAttr::AT_AssertExclusiveLock
:
9491 handleAssertExclusiveLockAttr(S
, D
, AL
);
9493 case ParsedAttr::AT_AssertSharedLock
:
9494 handleAssertSharedLockAttr(S
, D
, AL
);
9496 case ParsedAttr::AT_PtGuardedVar
:
9497 handlePtGuardedVarAttr(S
, D
, AL
);
9499 case ParsedAttr::AT_NoSanitize
:
9500 handleNoSanitizeAttr(S
, D
, AL
);
9502 case ParsedAttr::AT_NoSanitizeSpecific
:
9503 handleNoSanitizeSpecificAttr(S
, D
, AL
);
9505 case ParsedAttr::AT_GuardedBy
:
9506 handleGuardedByAttr(S
, D
, AL
);
9508 case ParsedAttr::AT_PtGuardedBy
:
9509 handlePtGuardedByAttr(S
, D
, AL
);
9511 case ParsedAttr::AT_ExclusiveTrylockFunction
:
9512 handleExclusiveTrylockFunctionAttr(S
, D
, AL
);
9514 case ParsedAttr::AT_LockReturned
:
9515 handleLockReturnedAttr(S
, D
, AL
);
9517 case ParsedAttr::AT_LocksExcluded
:
9518 handleLocksExcludedAttr(S
, D
, AL
);
9520 case ParsedAttr::AT_SharedTrylockFunction
:
9521 handleSharedTrylockFunctionAttr(S
, D
, AL
);
9523 case ParsedAttr::AT_AcquiredBefore
:
9524 handleAcquiredBeforeAttr(S
, D
, AL
);
9526 case ParsedAttr::AT_AcquiredAfter
:
9527 handleAcquiredAfterAttr(S
, D
, AL
);
9530 // Capability analysis attributes.
9531 case ParsedAttr::AT_Capability
:
9532 case ParsedAttr::AT_Lockable
:
9533 handleCapabilityAttr(S
, D
, AL
);
9535 case ParsedAttr::AT_RequiresCapability
:
9536 handleRequiresCapabilityAttr(S
, D
, AL
);
9539 case ParsedAttr::AT_AssertCapability
:
9540 handleAssertCapabilityAttr(S
, D
, AL
);
9542 case ParsedAttr::AT_AcquireCapability
:
9543 handleAcquireCapabilityAttr(S
, D
, AL
);
9545 case ParsedAttr::AT_ReleaseCapability
:
9546 handleReleaseCapabilityAttr(S
, D
, AL
);
9548 case ParsedAttr::AT_TryAcquireCapability
:
9549 handleTryAcquireCapabilityAttr(S
, D
, AL
);
9552 // Consumed analysis attributes.
9553 case ParsedAttr::AT_Consumable
:
9554 handleConsumableAttr(S
, D
, AL
);
9556 case ParsedAttr::AT_CallableWhen
:
9557 handleCallableWhenAttr(S
, D
, AL
);
9559 case ParsedAttr::AT_ParamTypestate
:
9560 handleParamTypestateAttr(S
, D
, AL
);
9562 case ParsedAttr::AT_ReturnTypestate
:
9563 handleReturnTypestateAttr(S
, D
, AL
);
9565 case ParsedAttr::AT_SetTypestate
:
9566 handleSetTypestateAttr(S
, D
, AL
);
9568 case ParsedAttr::AT_TestTypestate
:
9569 handleTestTypestateAttr(S
, D
, AL
);
9572 // Type safety attributes.
9573 case ParsedAttr::AT_ArgumentWithTypeTag
:
9574 handleArgumentWithTypeTagAttr(S
, D
, AL
);
9576 case ParsedAttr::AT_TypeTagForDatatype
:
9577 handleTypeTagForDatatypeAttr(S
, D
, AL
);
9580 // Swift attributes.
9581 case ParsedAttr::AT_SwiftAsyncName
:
9582 handleSwiftAsyncName(S
, D
, AL
);
9584 case ParsedAttr::AT_SwiftAttr
:
9585 handleSwiftAttrAttr(S
, D
, AL
);
9587 case ParsedAttr::AT_SwiftBridge
:
9588 handleSwiftBridge(S
, D
, AL
);
9590 case ParsedAttr::AT_SwiftError
:
9591 handleSwiftError(S
, D
, AL
);
9593 case ParsedAttr::AT_SwiftName
:
9594 handleSwiftName(S
, D
, AL
);
9596 case ParsedAttr::AT_SwiftNewType
:
9597 handleSwiftNewType(S
, D
, AL
);
9599 case ParsedAttr::AT_SwiftAsync
:
9600 handleSwiftAsyncAttr(S
, D
, AL
);
9602 case ParsedAttr::AT_SwiftAsyncError
:
9603 handleSwiftAsyncError(S
, D
, AL
);
9607 case ParsedAttr::AT_XRayLogArgs
:
9608 handleXRayLogArgsAttr(S
, D
, AL
);
9611 case ParsedAttr::AT_PatchableFunctionEntry
:
9612 handlePatchableFunctionEntryAttr(S
, D
, AL
);
9615 case ParsedAttr::AT_AlwaysDestroy
:
9616 case ParsedAttr::AT_NoDestroy
:
9617 handleDestroyAttr(S
, D
, AL
);
9620 case ParsedAttr::AT_Uninitialized
:
9621 handleUninitializedAttr(S
, D
, AL
);
9624 case ParsedAttr::AT_ObjCExternallyRetained
:
9625 handleObjCExternallyRetainedAttr(S
, D
, AL
);
9628 case ParsedAttr::AT_MIGServerRoutine
:
9629 handleMIGServerRoutineAttr(S
, D
, AL
);
9632 case ParsedAttr::AT_MSAllocator
:
9633 handleMSAllocatorAttr(S
, D
, AL
);
9636 case ParsedAttr::AT_ArmBuiltinAlias
:
9637 handleArmBuiltinAliasAttr(S
, D
, AL
);
9640 case ParsedAttr::AT_ArmLocallyStreaming
:
9641 handleSimpleAttribute
<ArmLocallyStreamingAttr
>(S
, D
, AL
);
9644 case ParsedAttr::AT_ArmNewZA
:
9645 handleArmNewZaAttr(S
, D
, AL
);
9648 case ParsedAttr::AT_AcquireHandle
:
9649 handleAcquireHandleAttr(S
, D
, AL
);
9652 case ParsedAttr::AT_ReleaseHandle
:
9653 handleHandleAttr
<ReleaseHandleAttr
>(S
, D
, AL
);
9656 case ParsedAttr::AT_UnsafeBufferUsage
:
9657 handleUnsafeBufferUsage
<UnsafeBufferUsageAttr
>(S
, D
, AL
);
9660 case ParsedAttr::AT_UseHandle
:
9661 handleHandleAttr
<UseHandleAttr
>(S
, D
, AL
);
9664 case ParsedAttr::AT_EnforceTCB
:
9665 handleEnforceTCBAttr
<EnforceTCBAttr
, EnforceTCBLeafAttr
>(S
, D
, AL
);
9668 case ParsedAttr::AT_EnforceTCBLeaf
:
9669 handleEnforceTCBAttr
<EnforceTCBLeafAttr
, EnforceTCBAttr
>(S
, D
, AL
);
9672 case ParsedAttr::AT_BuiltinAlias
:
9673 handleBuiltinAliasAttr(S
, D
, AL
);
9676 case ParsedAttr::AT_PreferredType
:
9677 handlePreferredTypeAttr(S
, D
, AL
);
9680 case ParsedAttr::AT_UsingIfExists
:
9681 handleSimpleAttribute
<UsingIfExistsAttr
>(S
, D
, AL
);
9686 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
9687 /// attribute list to the specified decl, ignoring any type attributes.
9688 void Sema::ProcessDeclAttributeList(
9689 Scope
*S
, Decl
*D
, const ParsedAttributesView
&AttrList
,
9690 const ProcessDeclAttributeOptions
&Options
) {
9691 if (AttrList
.empty())
9694 for (const ParsedAttr
&AL
: AttrList
)
9695 ProcessDeclAttribute(*this, S
, D
, AL
, Options
);
9697 // FIXME: We should be able to handle these cases in TableGen.
9699 // static int a9 __attribute__((weakref));
9700 // but that looks really pointless. We reject it.
9701 if (D
->hasAttr
<WeakRefAttr
>() && !D
->hasAttr
<AliasAttr
>()) {
9702 Diag(AttrList
.begin()->getLoc(), diag::err_attribute_weakref_without_alias
)
9703 << cast
<NamedDecl
>(D
);
9704 D
->dropAttr
<WeakRefAttr
>();
9708 // FIXME: We should be able to handle this in TableGen as well. It would be
9709 // good to have a way to specify "these attributes must appear as a group",
9710 // for these. Additionally, it would be good to have a way to specify "these
9711 // attribute must never appear as a group" for attributes like cold and hot.
9712 if (!D
->hasAttr
<OpenCLKernelAttr
>()) {
9713 // These attributes cannot be applied to a non-kernel function.
9714 if (const auto *A
= D
->getAttr
<ReqdWorkGroupSizeAttr
>()) {
9715 // FIXME: This emits a different error message than
9716 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
9717 Diag(D
->getLocation(), diag::err_opencl_kernel_attr
) << A
;
9718 D
->setInvalidDecl();
9719 } else if (const auto *A
= D
->getAttr
<WorkGroupSizeHintAttr
>()) {
9720 Diag(D
->getLocation(), diag::err_opencl_kernel_attr
) << A
;
9721 D
->setInvalidDecl();
9722 } else if (const auto *A
= D
->getAttr
<VecTypeHintAttr
>()) {
9723 Diag(D
->getLocation(), diag::err_opencl_kernel_attr
) << A
;
9724 D
->setInvalidDecl();
9725 } else if (const auto *A
= D
->getAttr
<OpenCLIntelReqdSubGroupSizeAttr
>()) {
9726 Diag(D
->getLocation(), diag::err_opencl_kernel_attr
) << A
;
9727 D
->setInvalidDecl();
9728 } else if (!D
->hasAttr
<CUDAGlobalAttr
>()) {
9729 if (const auto *A
= D
->getAttr
<AMDGPUFlatWorkGroupSizeAttr
>()) {
9730 Diag(D
->getLocation(), diag::err_attribute_wrong_decl_type
)
9731 << A
<< A
->isRegularKeywordAttribute() << ExpectedKernelFunction
;
9732 D
->setInvalidDecl();
9733 } else if (const auto *A
= D
->getAttr
<AMDGPUWavesPerEUAttr
>()) {
9734 Diag(D
->getLocation(), diag::err_attribute_wrong_decl_type
)
9735 << A
<< A
->isRegularKeywordAttribute() << ExpectedKernelFunction
;
9736 D
->setInvalidDecl();
9737 } else if (const auto *A
= D
->getAttr
<AMDGPUNumSGPRAttr
>()) {
9738 Diag(D
->getLocation(), diag::err_attribute_wrong_decl_type
)
9739 << A
<< A
->isRegularKeywordAttribute() << ExpectedKernelFunction
;
9740 D
->setInvalidDecl();
9741 } else if (const auto *A
= D
->getAttr
<AMDGPUNumVGPRAttr
>()) {
9742 Diag(D
->getLocation(), diag::err_attribute_wrong_decl_type
)
9743 << A
<< A
->isRegularKeywordAttribute() << ExpectedKernelFunction
;
9744 D
->setInvalidDecl();
9749 // Do this check after processing D's attributes because the attribute
9750 // objc_method_family can change whether the given method is in the init
9751 // family, and it can be applied after objc_designated_initializer. This is a
9752 // bit of a hack, but we need it to be compatible with versions of clang that
9753 // processed the attribute list in the wrong order.
9754 if (D
->hasAttr
<ObjCDesignatedInitializerAttr
>() &&
9755 cast
<ObjCMethodDecl
>(D
)->getMethodFamily() != OMF_init
) {
9756 Diag(D
->getLocation(), diag::err_designated_init_attr_non_init
);
9757 D
->dropAttr
<ObjCDesignatedInitializerAttr
>();
9761 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
9763 void Sema::ProcessDeclAttributeDelayed(Decl
*D
,
9764 const ParsedAttributesView
&AttrList
) {
9765 for (const ParsedAttr
&AL
: AttrList
)
9766 if (AL
.getKind() == ParsedAttr::AT_TransparentUnion
) {
9767 handleTransparentUnionAttr(*this, D
, AL
);
9771 // For BPFPreserveAccessIndexAttr, we want to populate the attributes
9772 // to fields and inner records as well.
9773 if (D
&& D
->hasAttr
<BPFPreserveAccessIndexAttr
>())
9774 handleBPFPreserveAIRecord(*this, cast
<RecordDecl
>(D
));
9777 // Annotation attributes are the only attributes allowed after an access
9779 bool Sema::ProcessAccessDeclAttributeList(
9780 AccessSpecDecl
*ASDecl
, const ParsedAttributesView
&AttrList
) {
9781 for (const ParsedAttr
&AL
: AttrList
) {
9782 if (AL
.getKind() == ParsedAttr::AT_Annotate
) {
9783 ProcessDeclAttribute(*this, nullptr, ASDecl
, AL
,
9784 ProcessDeclAttributeOptions());
9786 Diag(AL
.getLoc(), diag::err_only_annotate_after_access_spec
);
9793 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
9794 /// contains any decl attributes that we should warn about.
9795 static void checkUnusedDeclAttributes(Sema
&S
, const ParsedAttributesView
&A
) {
9796 for (const ParsedAttr
&AL
: A
) {
9797 // Only warn if the attribute is an unignored, non-type attribute.
9798 if (AL
.isUsedAsTypeAttr() || AL
.isInvalid())
9800 if (AL
.getKind() == ParsedAttr::IgnoredAttribute
)
9803 if (AL
.getKind() == ParsedAttr::UnknownAttribute
) {
9804 S
.Diag(AL
.getLoc(), diag::warn_unknown_attribute_ignored
)
9805 << AL
<< AL
.getRange();
9807 S
.Diag(AL
.getLoc(), diag::warn_attribute_not_on_decl
) << AL
9813 /// checkUnusedDeclAttributes - Given a declarator which is not being
9814 /// used to build a declaration, complain about any decl attributes
9815 /// which might be lying around on it.
9816 void Sema::checkUnusedDeclAttributes(Declarator
&D
) {
9817 ::checkUnusedDeclAttributes(*this, D
.getDeclarationAttributes());
9818 ::checkUnusedDeclAttributes(*this, D
.getDeclSpec().getAttributes());
9819 ::checkUnusedDeclAttributes(*this, D
.getAttributes());
9820 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
)
9821 ::checkUnusedDeclAttributes(*this, D
.getTypeObject(i
).getAttrs());
9824 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
9825 /// \#pragma weak needs a non-definition decl and source may not have one.
9826 NamedDecl
*Sema::DeclClonePragmaWeak(NamedDecl
*ND
, const IdentifierInfo
*II
,
9827 SourceLocation Loc
) {
9828 assert(isa
<FunctionDecl
>(ND
) || isa
<VarDecl
>(ND
));
9829 NamedDecl
*NewD
= nullptr;
9830 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
)) {
9831 FunctionDecl
*NewFD
;
9832 // FIXME: Missing call to CheckFunctionDeclaration().
9834 // FIXME: Is the qualifier info correct?
9835 // FIXME: Is the DeclContext correct?
9836 NewFD
= FunctionDecl::Create(
9837 FD
->getASTContext(), FD
->getDeclContext(), Loc
, Loc
,
9838 DeclarationName(II
), FD
->getType(), FD
->getTypeSourceInfo(), SC_None
,
9839 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
9840 FD
->hasPrototype(), ConstexprSpecKind::Unspecified
,
9841 FD
->getTrailingRequiresClause());
9844 if (FD
->getQualifier())
9845 NewFD
->setQualifierInfo(FD
->getQualifierLoc());
9847 // Fake up parameter variables; they are declared as if this were
9849 QualType FDTy
= FD
->getType();
9850 if (const auto *FT
= FDTy
->getAs
<FunctionProtoType
>()) {
9851 SmallVector
<ParmVarDecl
*, 16> Params
;
9852 for (const auto &AI
: FT
->param_types()) {
9853 ParmVarDecl
*Param
= BuildParmVarDeclForTypedef(NewFD
, Loc
, AI
);
9854 Param
->setScopeInfo(0, Params
.size());
9855 Params
.push_back(Param
);
9857 NewFD
->setParams(Params
);
9859 } else if (auto *VD
= dyn_cast
<VarDecl
>(ND
)) {
9860 NewD
= VarDecl::Create(VD
->getASTContext(), VD
->getDeclContext(),
9861 VD
->getInnerLocStart(), VD
->getLocation(), II
,
9862 VD
->getType(), VD
->getTypeSourceInfo(),
9863 VD
->getStorageClass());
9864 if (VD
->getQualifier())
9865 cast
<VarDecl
>(NewD
)->setQualifierInfo(VD
->getQualifierLoc());
9870 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
9871 /// applied to it, possibly with an alias.
9872 void Sema::DeclApplyPragmaWeak(Scope
*S
, NamedDecl
*ND
, const WeakInfo
&W
) {
9873 if (W
.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
9874 IdentifierInfo
*NDId
= ND
->getIdentifier();
9875 NamedDecl
*NewD
= DeclClonePragmaWeak(ND
, W
.getAlias(), W
.getLocation());
9877 AliasAttr::CreateImplicit(Context
, NDId
->getName(), W
.getLocation()));
9878 NewD
->addAttr(WeakAttr::CreateImplicit(Context
, W
.getLocation()));
9879 WeakTopLevelDecl
.push_back(NewD
);
9880 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
9881 // to insert Decl at TU scope, sorry.
9882 DeclContext
*SavedContext
= CurContext
;
9883 CurContext
= Context
.getTranslationUnitDecl();
9884 NewD
->setDeclContext(CurContext
);
9885 NewD
->setLexicalDeclContext(CurContext
);
9886 PushOnScopeChains(NewD
, S
);
9887 CurContext
= SavedContext
;
9888 } else { // just add weak to existing
9889 ND
->addAttr(WeakAttr::CreateImplicit(Context
, W
.getLocation()));
9893 void Sema::ProcessPragmaWeak(Scope
*S
, Decl
*D
) {
9894 // It's valid to "forward-declare" #pragma weak, in which case we
9896 LoadExternalWeakUndeclaredIdentifiers();
9897 if (WeakUndeclaredIdentifiers
.empty())
9899 NamedDecl
*ND
= nullptr;
9900 if (auto *VD
= dyn_cast
<VarDecl
>(D
))
9901 if (VD
->isExternC())
9903 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
))
9904 if (FD
->isExternC())
9908 if (IdentifierInfo
*Id
= ND
->getIdentifier()) {
9909 auto I
= WeakUndeclaredIdentifiers
.find(Id
);
9910 if (I
!= WeakUndeclaredIdentifiers
.end()) {
9911 auto &WeakInfos
= I
->second
;
9912 for (const auto &W
: WeakInfos
)
9913 DeclApplyPragmaWeak(S
, ND
, W
);
9914 std::remove_reference_t
<decltype(WeakInfos
)> EmptyWeakInfos
;
9915 WeakInfos
.swap(EmptyWeakInfos
);
9920 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
9921 /// it, apply them to D. This is a bit tricky because PD can have attributes
9922 /// specified in many different places, and we need to find and apply them all.
9923 void Sema::ProcessDeclAttributes(Scope
*S
, Decl
*D
, const Declarator
&PD
) {
9924 // Ordering of attributes can be important, so we take care to process
9925 // attributes in the order in which they appeared in the source code.
9927 // First, process attributes that appeared on the declaration itself (but
9928 // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
9929 ParsedAttributesView NonSlidingAttrs
;
9930 for (ParsedAttr
&AL
: PD
.getDeclarationAttributes()) {
9931 if (AL
.slidesFromDeclToDeclSpecLegacyBehavior()) {
9932 // Skip processing the attribute, but do check if it appertains to the
9933 // declaration. This is needed for the `MatrixType` attribute, which,
9934 // despite being a type attribute, defines a `SubjectList` that only
9935 // allows it to be used on typedef declarations.
9936 AL
.diagnoseAppertainsTo(*this, D
);
9938 NonSlidingAttrs
.addAtEnd(&AL
);
9941 ProcessDeclAttributeList(S
, D
, NonSlidingAttrs
);
9943 // Apply decl attributes from the DeclSpec if present.
9944 if (!PD
.getDeclSpec().getAttributes().empty()) {
9945 ProcessDeclAttributeList(S
, D
, PD
.getDeclSpec().getAttributes(),
9946 ProcessDeclAttributeOptions()
9947 .WithIncludeCXX11Attributes(false)
9948 .WithIgnoreTypeAttributes(true));
9951 // Walk the declarator structure, applying decl attributes that were in a type
9952 // position to the decl itself. This handles cases like:
9953 // int *__attr__(x)** D;
9954 // when X is a decl attribute.
9955 for (unsigned i
= 0, e
= PD
.getNumTypeObjects(); i
!= e
; ++i
) {
9956 ProcessDeclAttributeList(S
, D
, PD
.getTypeObject(i
).getAttrs(),
9957 ProcessDeclAttributeOptions()
9958 .WithIncludeCXX11Attributes(false)
9959 .WithIgnoreTypeAttributes(true));
9962 // Finally, apply any attributes on the decl itself.
9963 ProcessDeclAttributeList(S
, D
, PD
.getAttributes());
9965 // Apply additional attributes specified by '#pragma clang attribute'.
9966 AddPragmaAttributes(S
, D
);
9969 /// Is the given declaration allowed to use a forbidden type?
9970 /// If so, it'll still be annotated with an attribute that makes it
9971 /// illegal to actually use.
9972 static bool isForbiddenTypeAllowed(Sema
&S
, Decl
*D
,
9973 const DelayedDiagnostic
&diag
,
9974 UnavailableAttr::ImplicitReason
&reason
) {
9975 // Private ivars are always okay. Unfortunately, people don't
9976 // always properly make their ivars private, even in system headers.
9977 // Plus we need to make fields okay, too.
9978 if (!isa
<FieldDecl
>(D
) && !isa
<ObjCPropertyDecl
>(D
) &&
9979 !isa
<FunctionDecl
>(D
))
9982 // Silently accept unsupported uses of __weak in both user and system
9983 // declarations when it's been disabled, for ease of integration with
9984 // -fno-objc-arc files. We do have to take some care against attempts
9985 // to define such things; for now, we've only done that for ivars
9987 if ((isa
<ObjCIvarDecl
>(D
) || isa
<ObjCPropertyDecl
>(D
))) {
9988 if (diag
.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled
||
9989 diag
.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime
) {
9990 reason
= UnavailableAttr::IR_ForbiddenWeak
;
9995 // Allow all sorts of things in system headers.
9996 if (S
.Context
.getSourceManager().isInSystemHeader(D
->getLocation())) {
9997 // Currently, all the failures dealt with this way are due to ARC
9999 reason
= UnavailableAttr::IR_ARCForbiddenType
;
10006 /// Handle a delayed forbidden-type diagnostic.
10007 static void handleDelayedForbiddenType(Sema
&S
, DelayedDiagnostic
&DD
,
10009 auto Reason
= UnavailableAttr::IR_None
;
10010 if (D
&& isForbiddenTypeAllowed(S
, D
, DD
, Reason
)) {
10011 assert(Reason
&& "didn't set reason?");
10012 D
->addAttr(UnavailableAttr::CreateImplicit(S
.Context
, "", Reason
, DD
.Loc
));
10015 if (S
.getLangOpts().ObjCAutoRefCount
)
10016 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
10017 // FIXME: we may want to suppress diagnostics for all
10018 // kind of forbidden type messages on unavailable functions.
10019 if (FD
->hasAttr
<UnavailableAttr
>() &&
10020 DD
.getForbiddenTypeDiagnostic() ==
10021 diag::err_arc_array_param_no_ownership
) {
10022 DD
.Triggered
= true;
10027 S
.Diag(DD
.Loc
, DD
.getForbiddenTypeDiagnostic())
10028 << DD
.getForbiddenTypeOperand() << DD
.getForbiddenTypeArgument();
10029 DD
.Triggered
= true;
10033 void Sema::PopParsingDeclaration(ParsingDeclState state
, Decl
*decl
) {
10034 assert(DelayedDiagnostics
.getCurrentPool());
10035 DelayedDiagnosticPool
&poppedPool
= *DelayedDiagnostics
.getCurrentPool();
10036 DelayedDiagnostics
.popWithoutEmitting(state
);
10038 // When delaying diagnostics to run in the context of a parsed
10039 // declaration, we only want to actually emit anything if parsing
10043 // We emit all the active diagnostics in this pool or any of its
10044 // parents. In general, we'll get one pool for the decl spec
10045 // and a child pool for each declarator; in a decl group like:
10046 // deprecated_typedef foo, *bar, baz();
10047 // only the declarator pops will be passed decls. This is correct;
10048 // we really do need to consider delayed diagnostics from the decl spec
10049 // for each of the different declarations.
10050 const DelayedDiagnosticPool
*pool
= &poppedPool
;
10052 bool AnyAccessFailures
= false;
10053 for (DelayedDiagnosticPool::pool_iterator
10054 i
= pool
->pool_begin(), e
= pool
->pool_end(); i
!= e
; ++i
) {
10055 // This const_cast is a bit lame. Really, Triggered should be mutable.
10056 DelayedDiagnostic
&diag
= const_cast<DelayedDiagnostic
&>(*i
);
10057 if (diag
.Triggered
)
10060 switch (diag
.Kind
) {
10061 case DelayedDiagnostic::Availability
:
10062 // Don't bother giving deprecation/unavailable diagnostics if
10063 // the decl is invalid.
10064 if (!decl
->isInvalidDecl())
10065 handleDelayedAvailabilityCheck(diag
, decl
);
10068 case DelayedDiagnostic::Access
:
10069 // Only produce one access control diagnostic for a structured binding
10070 // declaration: we don't need to tell the user that all the fields are
10071 // inaccessible one at a time.
10072 if (AnyAccessFailures
&& isa
<DecompositionDecl
>(decl
))
10074 HandleDelayedAccessCheck(diag
, decl
);
10075 if (diag
.Triggered
)
10076 AnyAccessFailures
= true;
10079 case DelayedDiagnostic::ForbiddenType
:
10080 handleDelayedForbiddenType(*this, diag
, decl
);
10084 } while ((pool
= pool
->getParent()));
10087 /// Given a set of delayed diagnostics, re-emit them as if they had
10088 /// been delayed in the current context instead of in the given pool.
10089 /// Essentially, this just moves them to the current pool.
10090 void Sema::redelayDiagnostics(DelayedDiagnosticPool
&pool
) {
10091 DelayedDiagnosticPool
*curPool
= DelayedDiagnostics
.getCurrentPool();
10092 assert(curPool
&& "re-emitting in undelayed context not supported");
10093 curPool
->steal(pool
);