1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.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/ASTMutationListener.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/MathExtras.h"
34 using namespace clang;
37 namespace AttributeLangSupport {
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// isFunctionOrMethod - Return true if the given decl has function
50 /// type (function or function-typed variable) or an Objective-C
52 static bool isFunctionOrMethod(const Decl *D) {
53 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
55 /// \brief Return true if the given decl has function type (function or
56 /// function-typed variable) or an Objective-C method or a block.
57 static bool isFunctionOrMethodOrBlock(const Decl *D) {
58 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
61 /// Return true if the given decl has a declarator that should have
62 /// been processed by Sema::GetTypeForDeclarator.
63 static bool hasDeclarator(const Decl *D) {
64 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
65 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
66 isa<ObjCPropertyDecl>(D);
69 /// hasFunctionProto - Return true if the given decl has a argument
70 /// information. This decl should have already passed
71 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
72 static bool hasFunctionProto(const Decl *D) {
73 if (const FunctionType *FnTy = D->getFunctionType())
74 return isa<FunctionProtoType>(FnTy);
75 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
78 /// getFunctionOrMethodNumParams - Return number of function or method
79 /// parameters. It is an error to call this on a K&R function (use
80 /// hasFunctionProto first).
81 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
82 if (const FunctionType *FnTy = D->getFunctionType())
83 return cast<FunctionProtoType>(FnTy)->getNumParams();
84 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
85 return BD->getNumParams();
86 return cast<ObjCMethodDecl>(D)->param_size();
89 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
90 if (const FunctionType *FnTy = D->getFunctionType())
91 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
92 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
93 return BD->getParamDecl(Idx)->getType();
95 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
98 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
99 if (const auto *FD = dyn_cast<FunctionDecl>(D))
100 return FD->getParamDecl(Idx)->getSourceRange();
101 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
102 return MD->parameters()[Idx]->getSourceRange();
103 if (const auto *BD = dyn_cast<BlockDecl>(D))
104 return BD->getParamDecl(Idx)->getSourceRange();
105 return SourceRange();
108 static QualType getFunctionOrMethodResultType(const Decl *D) {
109 if (const FunctionType *FnTy = D->getFunctionType())
110 return cast<FunctionType>(FnTy)->getReturnType();
111 return cast<ObjCMethodDecl>(D)->getReturnType();
114 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
115 if (const auto *FD = dyn_cast<FunctionDecl>(D))
116 return FD->getReturnTypeSourceRange();
117 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
118 return MD->getReturnTypeSourceRange();
119 return SourceRange();
122 static bool isFunctionOrMethodVariadic(const Decl *D) {
123 if (const FunctionType *FnTy = D->getFunctionType()) {
124 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
125 return proto->isVariadic();
127 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
128 return BD->isVariadic();
130 return cast<ObjCMethodDecl>(D)->isVariadic();
133 static bool isInstanceMethod(const Decl *D) {
134 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
135 return MethodDecl->isInstance();
139 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
140 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
144 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
148 IdentifierInfo* ClsName = Cls->getIdentifier();
150 // FIXME: Should we walk the chain of classes?
151 return ClsName == &Ctx.Idents.get("NSString") ||
152 ClsName == &Ctx.Idents.get("NSMutableString");
155 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
156 const PointerType *PT = T->getAs<PointerType>();
160 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
164 const RecordDecl *RD = RT->getDecl();
165 if (RD->getTagKind() != TTK_Struct)
168 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
171 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
172 // FIXME: Include the type in the argument list.
173 return Attr.getNumArgs() + Attr.hasParsedType();
176 template <typename Compare>
177 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
178 unsigned Num, unsigned Diag,
180 if (Comp(getNumAttributeArgs(Attr), Num)) {
181 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
188 /// \brief Check if the attribute has exactly as many args as Num. May
190 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
192 return checkAttributeNumArgsImpl(S, Attr, Num,
193 diag::err_attribute_wrong_number_arguments,
194 std::not_equal_to<unsigned>());
197 /// \brief Check if the attribute has at least as many args as Num. May
199 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
201 return checkAttributeNumArgsImpl(S, Attr, Num,
202 diag::err_attribute_too_few_arguments,
203 std::less<unsigned>());
206 /// \brief Check if the attribute has at most as many args as Num. May
208 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
210 return checkAttributeNumArgsImpl(S, Attr, Num,
211 diag::err_attribute_too_many_arguments,
212 std::greater<unsigned>());
215 /// \brief If Expr is a valid integer constant, get the value of the integer
216 /// expression and return success or failure. May output an error.
217 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
218 const Expr *Expr, uint32_t &Val,
219 unsigned Idx = UINT_MAX) {
221 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
222 !Expr->isIntegerConstantExpr(I, S.Context)) {
224 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
225 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
226 << Expr->getSourceRange();
228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
229 << Attr.getName() << AANT_ArgumentIntegerConstant
230 << Expr->getSourceRange();
235 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
236 << I.toString(10, false) << 32 << /* Unsigned */ 1;
240 Val = (uint32_t)I.getZExtValue();
244 /// \brief Diagnose mutually exclusive attributes when present on a given
245 /// declaration. Returns true if diagnosed.
246 template <typename AttrTy>
247 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
248 const AttributeList &Attr) {
249 if (AttrTy *A = D->getAttr<AttrTy>()) {
250 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
251 << Attr.getName() << A;
257 /// \brief Check if IdxExpr is a valid parameter index for a function or
258 /// instance method D. May output an error.
260 /// \returns true if IdxExpr is a valid index.
261 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
262 const AttributeList &Attr,
266 assert(isFunctionOrMethodOrBlock(D));
268 // In C++ the implicit 'this' function parameter also counts.
269 // Parameters are counted from one.
270 bool HP = hasFunctionProto(D);
271 bool HasImplicitThisParam = isInstanceMethod(D);
272 bool IV = HP && isFunctionOrMethodVariadic(D);
274 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
277 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
278 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
279 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
280 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
281 << IdxExpr->getSourceRange();
285 Idx = IdxInt.getLimitedValue();
286 if (Idx < 1 || (!IV && Idx > NumParams)) {
287 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
288 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
291 Idx--; // Convert to zero-based.
292 if (HasImplicitThisParam) {
294 S.Diag(Attr.getLoc(),
295 diag::err_attribute_invalid_implicit_this_argument)
296 << Attr.getName() << IdxExpr->getSourceRange();
305 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
306 /// If not emit an error and return false. If the argument is an identifier it
307 /// will emit an error with a fixit hint and treat it as if it was a string
309 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
310 unsigned ArgNum, StringRef &Str,
311 SourceLocation *ArgLocation) {
312 // Look for identifiers. If we have one emit a hint to fix it to a literal.
313 if (Attr.isArgIdent(ArgNum)) {
314 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
315 Diag(Loc->Loc, diag::err_attribute_argument_type)
316 << Attr.getName() << AANT_ArgumentString
317 << FixItHint::CreateInsertion(Loc->Loc, "\"")
318 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
319 Str = Loc->Ident->getName();
321 *ArgLocation = Loc->Loc;
325 // Now check for an actual string literal.
326 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
327 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
329 *ArgLocation = ArgExpr->getLocStart();
331 if (!Literal || !Literal->isAscii()) {
332 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
333 << Attr.getName() << AANT_ArgumentString;
337 Str = Literal->getString();
341 /// \brief Applies the given attribute to the Decl without performing any
342 /// additional semantic checking.
343 template <typename AttrType>
344 static void handleSimpleAttribute(Sema &S, Decl *D,
345 const AttributeList &Attr) {
346 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
347 Attr.getAttributeSpellingListIndex()));
350 /// \brief Check if the passed-in expression is of type int or bool.
351 static bool isIntOrBool(Expr *Exp) {
352 QualType QT = Exp->getType();
353 return QT->isBooleanType() || QT->isIntegerType();
357 // Check to see if the type is a smart pointer of some kind. We assume
358 // it's a smart pointer if it defines both operator-> and operator*.
359 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
360 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
361 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
365 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
366 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
373 /// \brief Check if passed in Decl is a pointer type.
374 /// Note that this function may produce an error message.
375 /// \return true if the Decl is a pointer type; false otherwise
376 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
377 const AttributeList &Attr) {
378 const ValueDecl *vd = cast<ValueDecl>(D);
379 QualType QT = vd->getType();
380 if (QT->isAnyPointerType())
383 if (const RecordType *RT = QT->getAs<RecordType>()) {
384 // If it's an incomplete type, it could be a smart pointer; skip it.
385 // (We don't want to force template instantiation if we can avoid it,
386 // since that would alter the order in which templates are instantiated.)
387 if (RT->isIncompleteType())
390 if (threadSafetyCheckIsSmartPointer(S, RT))
394 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
395 << Attr.getName() << QT;
399 /// \brief Checks that the passed in QualType either is of RecordType or points
400 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
401 static const RecordType *getRecordType(QualType QT) {
402 if (const RecordType *RT = QT->getAs<RecordType>())
405 // Now check if we point to record type.
406 if (const PointerType *PT = QT->getAs<PointerType>())
407 return PT->getPointeeType()->getAs<RecordType>();
412 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
413 const RecordType *RT = getRecordType(Ty);
418 // Don't check for the capability if the class hasn't been defined yet.
419 if (RT->isIncompleteType())
422 // Allow smart pointers to be used as capability objects.
423 // FIXME -- Check the type that the smart pointer points to.
424 if (threadSafetyCheckIsSmartPointer(S, RT))
427 // Check if the record itself has a capability.
428 RecordDecl *RD = RT->getDecl();
429 if (RD->hasAttr<CapabilityAttr>())
432 // Else check if any base classes have a capability.
433 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
434 CXXBasePaths BPaths(false, false);
435 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
437 return BS->getType()->getAs<RecordType>()
438 ->getDecl()->hasAttr<CapabilityAttr>();
445 static bool checkTypedefTypeForCapability(QualType Ty) {
446 const auto *TD = Ty->getAs<TypedefType>();
450 TypedefNameDecl *TN = TD->getDecl();
454 return TN->hasAttr<CapabilityAttr>();
457 static bool typeHasCapability(Sema &S, QualType Ty) {
458 if (checkTypedefTypeForCapability(Ty))
461 if (checkRecordTypeForCapability(S, Ty))
467 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
468 // Capability expressions are simple expressions involving the boolean logic
469 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
470 // a DeclRefExpr is found, its type should be checked to determine whether it
471 // is a capability or not.
473 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
474 return typeHasCapability(S, E->getType());
475 else if (const auto *E = dyn_cast<CastExpr>(Ex))
476 return isCapabilityExpr(S, E->getSubExpr());
477 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
478 return isCapabilityExpr(S, E->getSubExpr());
479 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
480 if (E->getOpcode() == UO_LNot)
481 return isCapabilityExpr(S, E->getSubExpr());
483 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
484 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
485 return isCapabilityExpr(S, E->getLHS()) &&
486 isCapabilityExpr(S, E->getRHS());
493 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
494 /// a capability object.
495 /// \param Sidx The attribute argument index to start checking with.
496 /// \param ParamIdxOk Whether an argument can be indexing into a function
498 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
499 const AttributeList &Attr,
500 SmallVectorImpl<Expr *> &Args,
502 bool ParamIdxOk = false) {
503 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
504 Expr *ArgExp = Attr.getArgAsExpr(Idx);
506 if (ArgExp->isTypeDependent()) {
507 // FIXME -- need to check this again on template instantiation
508 Args.push_back(ArgExp);
512 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
513 if (StrLit->getLength() == 0 ||
514 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
515 // Pass empty strings to the analyzer without warnings.
516 // Treat "*" as the universal lock.
517 Args.push_back(ArgExp);
521 // We allow constant strings to be used as a placeholder for expressions
522 // that are not valid C++ syntax, but warn that they are ignored.
523 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
525 Args.push_back(ArgExp);
529 QualType ArgTy = ArgExp->getType();
531 // A pointer to member expression of the form &MyClass::mu is treated
532 // specially -- we need to look at the type of the member.
533 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
534 if (UOp->getOpcode() == UO_AddrOf)
535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
536 if (DRE->getDecl()->isCXXInstanceMember())
537 ArgTy = DRE->getDecl()->getType();
539 // First see if we can just cast to record type, or pointer to record type.
540 const RecordType *RT = getRecordType(ArgTy);
542 // Now check if we index into a record type function param.
543 if(!RT && ParamIdxOk) {
544 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
545 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
547 unsigned int NumParams = FD->getNumParams();
548 llvm::APInt ArgValue = IL->getValue();
549 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
550 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
551 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
552 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
553 << Attr.getName() << Idx + 1 << NumParams;
556 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
560 // If the type does not have a capability, see if the components of the
561 // expression have capabilities. This allows for writing C code where the
562 // capability may be on the type, and the expression is a capability
563 // boolean logic expression. Eg) requires_capability(A || B && !C)
564 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
565 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
566 << Attr.getName() << ArgTy;
568 Args.push_back(ArgExp);
572 //===----------------------------------------------------------------------===//
573 // Attribute Implementations
574 //===----------------------------------------------------------------------===//
576 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
577 const AttributeList &Attr) {
578 if (!threadSafetyCheckIsPointer(S, D, Attr))
581 D->addAttr(::new (S.Context)
582 PtGuardedVarAttr(Attr.getRange(), S.Context,
583 Attr.getAttributeSpellingListIndex()));
586 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
587 const AttributeList &Attr,
589 SmallVector<Expr*, 1> Args;
590 // check that all arguments are lockable objects
591 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
592 unsigned Size = Args.size();
601 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
603 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
606 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
607 Attr.getAttributeSpellingListIndex()));
610 static void handlePtGuardedByAttr(Sema &S, Decl *D,
611 const AttributeList &Attr) {
613 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
616 if (!threadSafetyCheckIsPointer(S, D, Attr))
619 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
621 Attr.getAttributeSpellingListIndex()));
624 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
625 const AttributeList &Attr,
626 SmallVectorImpl<Expr *> &Args) {
627 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
630 // Check that this attribute only applies to lockable types.
631 QualType QT = cast<ValueDecl>(D)->getType();
632 if (!QT->isDependentType()) {
633 const RecordType *RT = getRecordType(QT);
634 if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
641 // Check that all arguments are lockable objects.
642 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
649 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
650 const AttributeList &Attr) {
651 SmallVector<Expr*, 1> Args;
652 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
655 Expr **StartArg = &Args[0];
656 D->addAttr(::new (S.Context)
657 AcquiredAfterAttr(Attr.getRange(), S.Context,
658 StartArg, Args.size(),
659 Attr.getAttributeSpellingListIndex()));
662 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
663 const AttributeList &Attr) {
664 SmallVector<Expr*, 1> Args;
665 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
668 Expr **StartArg = &Args[0];
669 D->addAttr(::new (S.Context)
670 AcquiredBeforeAttr(Attr.getRange(), S.Context,
671 StartArg, Args.size(),
672 Attr.getAttributeSpellingListIndex()));
675 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
676 const AttributeList &Attr,
677 SmallVectorImpl<Expr *> &Args) {
678 // zero or more arguments ok
679 // check that all arguments are lockable objects
680 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
685 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
686 const AttributeList &Attr) {
687 SmallVector<Expr*, 1> Args;
688 if (!checkLockFunAttrCommon(S, D, Attr, Args))
691 unsigned Size = Args.size();
692 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
693 D->addAttr(::new (S.Context)
694 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
695 Attr.getAttributeSpellingListIndex()));
698 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
699 const AttributeList &Attr) {
700 SmallVector<Expr*, 1> Args;
701 if (!checkLockFunAttrCommon(S, D, Attr, Args))
704 unsigned Size = Args.size();
705 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
706 D->addAttr(::new (S.Context)
707 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
709 Attr.getAttributeSpellingListIndex()));
713 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
714 const AttributeList &Attr,
715 SmallVectorImpl<Expr *> &Args) {
716 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
719 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
720 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
721 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
725 // check that all arguments are lockable objects
726 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
731 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
732 const AttributeList &Attr) {
733 SmallVector<Expr*, 2> Args;
734 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
737 D->addAttr(::new (S.Context)
738 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
739 Attr.getArgAsExpr(0),
740 Args.data(), Args.size(),
741 Attr.getAttributeSpellingListIndex()));
744 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
745 const AttributeList &Attr) {
746 SmallVector<Expr*, 2> Args;
747 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
750 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
751 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
752 Args.size(), Attr.getAttributeSpellingListIndex()));
755 static void handleLockReturnedAttr(Sema &S, Decl *D,
756 const AttributeList &Attr) {
757 // check that the argument is lockable object
758 SmallVector<Expr*, 1> Args;
759 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
760 unsigned Size = Args.size();
764 D->addAttr(::new (S.Context)
765 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
766 Attr.getAttributeSpellingListIndex()));
769 static void handleLocksExcludedAttr(Sema &S, Decl *D,
770 const AttributeList &Attr) {
771 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
774 // check that all arguments are lockable objects
775 SmallVector<Expr*, 1> Args;
776 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
777 unsigned Size = Args.size();
780 Expr **StartArg = &Args[0];
782 D->addAttr(::new (S.Context)
783 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
784 Attr.getAttributeSpellingListIndex()));
787 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
788 Expr *Cond = Attr.getArgAsExpr(0);
789 if (!Cond->isTypeDependent()) {
790 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
791 if (Converted.isInvalid())
793 Cond = Converted.get();
797 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
800 SmallVector<PartialDiagnosticAt, 8> Diags;
801 if (!Cond->isValueDependent() &&
802 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
804 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
805 for (int I = 0, N = Diags.size(); I != N; ++I)
806 S.Diag(Diags[I].first, Diags[I].second);
810 D->addAttr(::new (S.Context)
811 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
812 Attr.getAttributeSpellingListIndex()));
815 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
816 ConsumableAttr::ConsumedState DefaultState;
818 if (Attr.isArgIdent(0)) {
819 IdentifierLoc *IL = Attr.getArgAsIdent(0);
820 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
822 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
823 << Attr.getName() << IL->Ident;
827 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
828 << Attr.getName() << AANT_ArgumentIdentifier;
832 D->addAttr(::new (S.Context)
833 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
834 Attr.getAttributeSpellingListIndex()));
838 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
839 const AttributeList &Attr) {
840 ASTContext &CurrContext = S.getASTContext();
841 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
843 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
844 if (!RD->hasAttr<ConsumableAttr>()) {
845 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
846 RD->getNameAsString();
856 static void handleCallableWhenAttr(Sema &S, Decl *D,
857 const AttributeList &Attr) {
858 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
861 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
864 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
865 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
866 CallableWhenAttr::ConsumedState CallableState;
868 StringRef StateString;
870 if (Attr.isArgIdent(ArgIndex)) {
871 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
872 StateString = Ident->Ident->getName();
875 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
879 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
881 S.Diag(Loc, diag::warn_attribute_type_not_supported)
882 << Attr.getName() << StateString;
886 States.push_back(CallableState);
889 D->addAttr(::new (S.Context)
890 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
891 States.size(), Attr.getAttributeSpellingListIndex()));
895 static void handleParamTypestateAttr(Sema &S, Decl *D,
896 const AttributeList &Attr) {
897 ParamTypestateAttr::ConsumedState ParamState;
899 if (Attr.isArgIdent(0)) {
900 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
901 StringRef StateString = Ident->Ident->getName();
903 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
905 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
906 << Attr.getName() << StateString;
910 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
911 Attr.getName() << AANT_ArgumentIdentifier;
915 // FIXME: This check is currently being done in the analysis. It can be
916 // enabled here only after the parser propagates attributes at
917 // template specialization definition, not declaration.
918 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
919 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
921 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
922 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
923 // ReturnType.getAsString();
927 D->addAttr(::new (S.Context)
928 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
929 Attr.getAttributeSpellingListIndex()));
933 static void handleReturnTypestateAttr(Sema &S, Decl *D,
934 const AttributeList &Attr) {
935 ReturnTypestateAttr::ConsumedState ReturnState;
937 if (Attr.isArgIdent(0)) {
938 IdentifierLoc *IL = Attr.getArgAsIdent(0);
939 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
941 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
942 << Attr.getName() << IL->Ident;
946 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
947 Attr.getName() << AANT_ArgumentIdentifier;
951 // FIXME: This check is currently being done in the analysis. It can be
952 // enabled here only after the parser propagates attributes at
953 // template specialization definition, not declaration.
954 //QualType ReturnType;
956 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
957 // ReturnType = Param->getType();
959 //} else if (const CXXConstructorDecl *Constructor =
960 // dyn_cast<CXXConstructorDecl>(D)) {
961 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
965 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
968 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
970 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
971 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
972 // ReturnType.getAsString();
976 D->addAttr(::new (S.Context)
977 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
978 Attr.getAttributeSpellingListIndex()));
982 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
983 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
986 SetTypestateAttr::ConsumedState NewState;
987 if (Attr.isArgIdent(0)) {
988 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
989 StringRef Param = Ident->Ident->getName();
990 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
991 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
992 << Attr.getName() << Param;
996 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
997 Attr.getName() << AANT_ArgumentIdentifier;
1001 D->addAttr(::new (S.Context)
1002 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1003 Attr.getAttributeSpellingListIndex()));
1006 static void handleTestTypestateAttr(Sema &S, Decl *D,
1007 const AttributeList &Attr) {
1008 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1011 TestTypestateAttr::ConsumedState TestState;
1012 if (Attr.isArgIdent(0)) {
1013 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1014 StringRef Param = Ident->Ident->getName();
1015 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1016 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1017 << Attr.getName() << Param;
1021 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1022 Attr.getName() << AANT_ArgumentIdentifier;
1026 D->addAttr(::new (S.Context)
1027 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1028 Attr.getAttributeSpellingListIndex()));
1031 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1032 const AttributeList &Attr) {
1033 // Remember this typedef decl, we will need it later for diagnostics.
1034 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1037 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1038 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1039 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1040 Attr.getAttributeSpellingListIndex()));
1041 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1042 // If the alignment is less than or equal to 8 bits, the packed attribute
1044 if (!FD->getType()->isDependentType() &&
1045 !FD->getType()->isIncompleteType() &&
1046 S.Context.getTypeAlign(FD->getType()) <= 8)
1047 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1048 << Attr.getName() << FD->getType();
1050 FD->addAttr(::new (S.Context)
1051 PackedAttr(Attr.getRange(), S.Context,
1052 Attr.getAttributeSpellingListIndex()));
1054 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1057 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1058 // The IBOutlet/IBOutletCollection attributes only apply to instance
1059 // variables or properties of Objective-C classes. The outlet must also
1060 // have an object reference type.
1061 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1062 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1063 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1064 << Attr.getName() << VD->getType() << 0;
1068 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1069 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1070 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1071 << Attr.getName() << PD->getType() << 1;
1076 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1083 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1084 if (!checkIBOutletCommon(S, D, Attr))
1087 D->addAttr(::new (S.Context)
1088 IBOutletAttr(Attr.getRange(), S.Context,
1089 Attr.getAttributeSpellingListIndex()));
1092 static void handleIBOutletCollection(Sema &S, Decl *D,
1093 const AttributeList &Attr) {
1095 // The iboutletcollection attribute can have zero or one arguments.
1096 if (Attr.getNumArgs() > 1) {
1097 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1098 << Attr.getName() << 1;
1102 if (!checkIBOutletCommon(S, D, Attr))
1107 if (Attr.hasParsedType())
1108 PT = Attr.getTypeArg();
1110 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1111 S.getScopeForContext(D->getDeclContext()->getParent()));
1113 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1118 TypeSourceInfo *QTLoc = nullptr;
1119 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1121 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1123 // Diagnose use of non-object type in iboutletcollection attribute.
1124 // FIXME. Gnu attribute extension ignores use of builtin types in
1125 // attributes. So, __attribute__((iboutletcollection(char))) will be
1126 // treated as __attribute__((iboutletcollection())).
1127 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1128 S.Diag(Attr.getLoc(),
1129 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1130 : diag::err_iboutletcollection_type) << QT;
1134 D->addAttr(::new (S.Context)
1135 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1136 Attr.getAttributeSpellingListIndex()));
1139 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1141 if (T->isReferenceType())
1144 T = T.getNonReferenceType();
1147 // The nonnull attribute, and other similar attributes, can be applied to a
1148 // transparent union that contains a pointer type.
1149 if (const RecordType *UT = T->getAsUnionType()) {
1150 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1151 RecordDecl *UD = UT->getDecl();
1152 for (const auto *I : UD->fields()) {
1153 QualType QT = I->getType();
1154 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1160 return T->isAnyPointerType() || T->isBlockPointerType();
1163 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1164 SourceRange AttrParmRange,
1165 SourceRange TypeRange,
1166 bool isReturnValue = false) {
1167 if (!S.isValidPointerAttrType(T)) {
1168 S.Diag(Attr.getLoc(), isReturnValue
1169 ? diag::warn_attribute_return_pointers_only
1170 : diag::warn_attribute_pointers_only)
1171 << Attr.getName() << AttrParmRange << TypeRange;
1177 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1178 SmallVector<unsigned, 8> NonNullArgs;
1179 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1180 Expr *Ex = Attr.getArgAsExpr(I);
1182 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1185 // Is the function argument a pointer type?
1186 if (Idx < getFunctionOrMethodNumParams(D) &&
1187 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1188 Ex->getSourceRange(),
1189 getFunctionOrMethodParamRange(D, Idx)))
1192 NonNullArgs.push_back(Idx);
1195 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1196 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1197 // check if the attribute came from a macro expansion or a template
1199 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1200 S.ActiveTemplateInstantiations.empty()) {
1201 bool AnyPointers = isFunctionOrMethodVariadic(D);
1202 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1203 I != E && !AnyPointers; ++I) {
1204 QualType T = getFunctionOrMethodParamType(D, I);
1205 if (T->isDependentType() || S.isValidPointerAttrType(T))
1210 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1213 unsigned *Start = NonNullArgs.data();
1214 unsigned Size = NonNullArgs.size();
1215 llvm::array_pod_sort(Start, Start + Size);
1216 D->addAttr(::new (S.Context)
1217 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1218 Attr.getAttributeSpellingListIndex()));
1221 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1222 const AttributeList &Attr) {
1223 if (Attr.getNumArgs() > 0) {
1224 if (D->getFunctionType()) {
1225 handleNonNullAttr(S, D, Attr);
1227 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1228 << D->getSourceRange();
1233 // Is the argument a pointer type?
1234 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1235 D->getSourceRange()))
1238 D->addAttr(::new (S.Context)
1239 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1240 Attr.getAttributeSpellingListIndex()));
1243 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1244 const AttributeList &Attr) {
1245 QualType ResultType = getFunctionOrMethodResultType(D);
1246 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1247 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1248 /* isReturnValue */ true))
1251 D->addAttr(::new (S.Context)
1252 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1253 Attr.getAttributeSpellingListIndex()));
1256 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1257 const AttributeList &Attr) {
1258 Expr *E = Attr.getArgAsExpr(0),
1259 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1260 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1261 Attr.getAttributeSpellingListIndex());
1264 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1265 Expr *OE, unsigned SpellingListIndex) {
1266 QualType ResultType = getFunctionOrMethodResultType(D);
1267 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1269 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1270 SourceLocation AttrLoc = AttrRange.getBegin();
1272 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1273 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1274 << &TmpAttr << AttrRange << SR;
1278 if (!E->isValueDependent()) {
1280 if (!E->isIntegerConstantExpr(I, Context)) {
1282 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1283 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1284 << E->getSourceRange();
1286 Diag(AttrLoc, diag::err_attribute_argument_type)
1287 << &TmpAttr << AANT_ArgumentIntegerConstant
1288 << E->getSourceRange();
1292 if (!I.isPowerOf2()) {
1293 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1294 << E->getSourceRange();
1300 if (!OE->isValueDependent()) {
1302 if (!OE->isIntegerConstantExpr(I, Context)) {
1303 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1304 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1305 << OE->getSourceRange();
1311 D->addAttr(::new (Context)
1312 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1315 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1316 // This attribute must be applied to a function declaration. The first
1317 // argument to the attribute must be an identifier, the name of the resource,
1318 // for example: malloc. The following arguments must be argument indexes, the
1319 // arguments must be of integer type for Returns, otherwise of pointer type.
1320 // The difference between Holds and Takes is that a pointer may still be used
1321 // after being held. free() should be __attribute((ownership_takes)), whereas
1322 // a list append function may well be __attribute((ownership_holds)).
1324 if (!AL.isArgIdent(0)) {
1325 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1326 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1330 // Figure out our Kind.
1331 OwnershipAttr::OwnershipKind K =
1332 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1333 AL.getAttributeSpellingListIndex()).getOwnKind();
1337 case OwnershipAttr::Takes:
1338 case OwnershipAttr::Holds:
1339 if (AL.getNumArgs() < 2) {
1340 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1341 << AL.getName() << 2;
1345 case OwnershipAttr::Returns:
1346 if (AL.getNumArgs() > 2) {
1347 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1348 << AL.getName() << 1;
1354 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1356 // Normalize the argument, __foo__ becomes foo.
1357 StringRef ModuleName = Module->getName();
1358 if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1359 ModuleName.size() > 4) {
1360 ModuleName = ModuleName.drop_front(2).drop_back(2);
1361 Module = &S.PP.getIdentifierTable().get(ModuleName);
1364 SmallVector<unsigned, 8> OwnershipArgs;
1365 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1366 Expr *Ex = AL.getArgAsExpr(i);
1368 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1371 // Is the function argument a pointer type?
1372 QualType T = getFunctionOrMethodParamType(D, Idx);
1373 int Err = -1; // No error
1375 case OwnershipAttr::Takes:
1376 case OwnershipAttr::Holds:
1377 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1380 case OwnershipAttr::Returns:
1381 if (!T->isIntegerType())
1386 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1387 << Ex->getSourceRange();
1391 // Check we don't have a conflict with another ownership attribute.
1392 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1393 // Cannot have two ownership attributes of different kinds for the same
1395 if (I->getOwnKind() != K && I->args_end() !=
1396 std::find(I->args_begin(), I->args_end(), Idx)) {
1397 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1398 << AL.getName() << I;
1400 } else if (K == OwnershipAttr::Returns &&
1401 I->getOwnKind() == OwnershipAttr::Returns) {
1402 // A returns attribute conflicts with any other returns attribute using
1403 // a different index. Note, diagnostic reporting is 1-based, but stored
1404 // argument indexes are 0-based.
1405 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1406 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1407 << *(I->args_begin()) + 1;
1409 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1410 << (unsigned)Idx + 1 << Ex->getSourceRange();
1415 OwnershipArgs.push_back(Idx);
1418 unsigned* start = OwnershipArgs.data();
1419 unsigned size = OwnershipArgs.size();
1420 llvm::array_pod_sort(start, start + size);
1422 D->addAttr(::new (S.Context)
1423 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1424 AL.getAttributeSpellingListIndex()));
1427 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1428 // Check the attribute arguments.
1429 if (Attr.getNumArgs() > 1) {
1430 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1431 << Attr.getName() << 1;
1435 NamedDecl *nd = cast<NamedDecl>(D);
1439 // static int a __attribute__((weakref ("v2")));
1440 // static int b() __attribute__((weakref ("f3")));
1442 // and ignores the attributes of
1444 // static int a __attribute__((weakref ("v2")));
1447 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1448 if (!Ctx->isFileContext()) {
1449 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1454 // The GCC manual says
1456 // At present, a declaration to which `weakref' is attached can only
1461 // Without a TARGET,
1462 // given as an argument to `weakref' or to `alias', `weakref' is
1463 // equivalent to `weak'.
1465 // gcc 4.4.1 will accept
1466 // int a7 __attribute__((weakref));
1468 // int a7 __attribute__((weak));
1469 // This looks like a bug in gcc. We reject that for now. We should revisit
1470 // it if this behaviour is actually used.
1473 // static ((alias ("y"), weakref)).
1474 // Should we? How to check that weakref is before or after alias?
1476 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1477 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1478 // StringRef parameter it was given anyway.
1480 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1481 // GCC will accept anything as the argument of weakref. Should we
1482 // check for an existing decl?
1483 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1484 Attr.getAttributeSpellingListIndex()));
1486 D->addAttr(::new (S.Context)
1487 WeakRefAttr(Attr.getRange(), S.Context,
1488 Attr.getAttributeSpellingListIndex()));
1491 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1493 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1496 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1497 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1501 // Aliases should be on declarations, not definitions.
1502 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1503 if (FD->isThisDeclarationADefinition()) {
1504 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1508 const auto *VD = cast<VarDecl>(D);
1509 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1510 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1515 // FIXME: check if target symbol exists in current file
1517 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1518 Attr.getAttributeSpellingListIndex()));
1521 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1522 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1525 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1526 Attr.getAttributeSpellingListIndex()));
1529 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1530 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1533 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1534 Attr.getAttributeSpellingListIndex()));
1537 static void handleTLSModelAttr(Sema &S, Decl *D,
1538 const AttributeList &Attr) {
1540 SourceLocation LiteralLoc;
1541 // Check that it is a string.
1542 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1545 // Check that the value.
1546 if (Model != "global-dynamic" && Model != "local-dynamic"
1547 && Model != "initial-exec" && Model != "local-exec") {
1548 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1552 D->addAttr(::new (S.Context)
1553 TLSModelAttr(Attr.getRange(), S.Context, Model,
1554 Attr.getAttributeSpellingListIndex()));
1557 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1558 QualType ResultType = getFunctionOrMethodResultType(D);
1559 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1560 D->addAttr(::new (S.Context) RestrictAttr(
1561 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1565 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1566 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1569 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1570 if (S.LangOpts.CPlusPlus) {
1571 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1572 << Attr.getName() << AttributeLangSupport::Cpp;
1576 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1577 Attr.getAttributeSpellingListIndex()));
1580 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1581 if (hasDeclarator(D)) return;
1583 if (S.CheckNoReturnAttr(attr)) return;
1585 if (!isa<ObjCMethodDecl>(D)) {
1586 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1587 << attr.getName() << ExpectedFunctionOrMethod;
1591 D->addAttr(::new (S.Context)
1592 NoReturnAttr(attr.getRange(), S.Context,
1593 attr.getAttributeSpellingListIndex()));
1596 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1597 if (!checkAttributeNumArgs(*this, attr, 0)) {
1605 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1606 const AttributeList &Attr) {
1608 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1609 // because 'analyzer_noreturn' does not impact the type.
1610 if (!isFunctionOrMethodOrBlock(D)) {
1611 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1612 if (!VD || (!VD->getType()->isBlockPointerType() &&
1613 !VD->getType()->isFunctionPointerType())) {
1614 S.Diag(Attr.getLoc(),
1615 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1616 : diag::warn_attribute_wrong_decl_type)
1617 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1622 D->addAttr(::new (S.Context)
1623 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1624 Attr.getAttributeSpellingListIndex()));
1627 // PS3 PPU-specific.
1628 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1630 Returning a Vector Class in Registers
1632 According to the PPU ABI specifications, a class with a single member of
1633 vector type is returned in memory when used as the return value of a function.
1634 This results in inefficient code when implementing vector classes. To return
1635 the value in a single vector register, add the vecreturn attribute to the
1636 class definition. This attribute is also applicable to struct types.
1642 __vector float xyzw;
1643 } __attribute__((vecreturn));
1645 Vector Add(Vector lhs, Vector rhs)
1648 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1649 return result; // This will be returned in a register
1652 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1653 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1657 RecordDecl *record = cast<RecordDecl>(D);
1660 if (!isa<CXXRecordDecl>(record)) {
1661 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1665 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1666 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1670 for (const auto *I : record->fields()) {
1671 if ((count == 1) || !I->getType()->isVectorType()) {
1672 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1678 D->addAttr(::new (S.Context)
1679 VecReturnAttr(Attr.getRange(), S.Context,
1680 Attr.getAttributeSpellingListIndex()));
1683 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1684 const AttributeList &Attr) {
1685 if (isa<ParmVarDecl>(D)) {
1686 // [[carries_dependency]] can only be applied to a parameter if it is a
1687 // parameter of a function declaration or lambda.
1688 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1689 S.Diag(Attr.getLoc(),
1690 diag::err_carries_dependency_param_not_function_decl);
1695 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1696 Attr.getRange(), S.Context,
1697 Attr.getAttributeSpellingListIndex()));
1700 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1701 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1702 if (VD->hasLocalStorage()) {
1703 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1706 } else if (!isFunctionOrMethod(D)) {
1707 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1708 << Attr.getName() << ExpectedVariableOrFunction;
1712 D->addAttr(::new (S.Context)
1713 UsedAttr(Attr.getRange(), S.Context,
1714 Attr.getAttributeSpellingListIndex()));
1717 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1718 uint32_t priority = ConstructorAttr::DefaultPriority;
1719 if (Attr.getNumArgs() &&
1720 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1723 D->addAttr(::new (S.Context)
1724 ConstructorAttr(Attr.getRange(), S.Context, priority,
1725 Attr.getAttributeSpellingListIndex()));
1728 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1729 uint32_t priority = DestructorAttr::DefaultPriority;
1730 if (Attr.getNumArgs() &&
1731 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1734 D->addAttr(::new (S.Context)
1735 DestructorAttr(Attr.getRange(), S.Context, priority,
1736 Attr.getAttributeSpellingListIndex()));
1739 template <typename AttrTy>
1740 static void handleAttrWithMessage(Sema &S, Decl *D,
1741 const AttributeList &Attr) {
1742 // Handle the case where the attribute has a text message.
1744 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1747 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1748 Attr.getAttributeSpellingListIndex()));
1751 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1752 const AttributeList &Attr) {
1753 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1754 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1755 << Attr.getName() << Attr.getRange();
1759 D->addAttr(::new (S.Context)
1760 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1761 Attr.getAttributeSpellingListIndex()));
1764 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1765 IdentifierInfo *Platform,
1766 VersionTuple Introduced,
1767 VersionTuple Deprecated,
1768 VersionTuple Obsoleted) {
1769 StringRef PlatformName
1770 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1771 if (PlatformName.empty())
1772 PlatformName = Platform->getName();
1774 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1775 // of these steps are needed).
1776 if (!Introduced.empty() && !Deprecated.empty() &&
1777 !(Introduced <= Deprecated)) {
1778 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1779 << 1 << PlatformName << Deprecated.getAsString()
1780 << 0 << Introduced.getAsString();
1784 if (!Introduced.empty() && !Obsoleted.empty() &&
1785 !(Introduced <= Obsoleted)) {
1786 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1787 << 2 << PlatformName << Obsoleted.getAsString()
1788 << 0 << Introduced.getAsString();
1792 if (!Deprecated.empty() && !Obsoleted.empty() &&
1793 !(Deprecated <= Obsoleted)) {
1794 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1795 << 2 << PlatformName << Obsoleted.getAsString()
1796 << 1 << Deprecated.getAsString();
1803 /// \brief Check whether the two versions match.
1805 /// If either version tuple is empty, then they are assumed to match. If
1806 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1807 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1808 bool BeforeIsOkay) {
1809 if (X.empty() || Y.empty())
1815 if (BeforeIsOkay && X < Y)
1821 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1822 IdentifierInfo *Platform,
1823 VersionTuple Introduced,
1824 VersionTuple Deprecated,
1825 VersionTuple Obsoleted,
1829 unsigned AttrSpellingListIndex) {
1830 VersionTuple MergedIntroduced = Introduced;
1831 VersionTuple MergedDeprecated = Deprecated;
1832 VersionTuple MergedObsoleted = Obsoleted;
1833 bool FoundAny = false;
1835 if (D->hasAttrs()) {
1836 AttrVec &Attrs = D->getAttrs();
1837 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1838 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1844 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1845 if (OldPlatform != Platform) {
1851 VersionTuple OldIntroduced = OldAA->getIntroduced();
1852 VersionTuple OldDeprecated = OldAA->getDeprecated();
1853 VersionTuple OldObsoleted = OldAA->getObsoleted();
1854 bool OldIsUnavailable = OldAA->getUnavailable();
1856 if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1857 !versionsMatch(Deprecated, OldDeprecated, Override) ||
1858 !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1859 !(OldIsUnavailable == IsUnavailable ||
1860 (Override && !OldIsUnavailable && IsUnavailable))) {
1863 VersionTuple FirstVersion;
1864 VersionTuple SecondVersion;
1865 if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1867 FirstVersion = OldIntroduced;
1868 SecondVersion = Introduced;
1869 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1871 FirstVersion = Deprecated;
1872 SecondVersion = OldDeprecated;
1873 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1875 FirstVersion = Obsoleted;
1876 SecondVersion = OldObsoleted;
1880 Diag(OldAA->getLocation(),
1881 diag::warn_mismatched_availability_override_unavail)
1882 << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1884 Diag(OldAA->getLocation(),
1885 diag::warn_mismatched_availability_override)
1887 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1888 << FirstVersion.getAsString() << SecondVersion.getAsString();
1890 Diag(Range.getBegin(), diag::note_overridden_method);
1892 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1893 Diag(Range.getBegin(), diag::note_previous_attribute);
1896 Attrs.erase(Attrs.begin() + i);
1901 VersionTuple MergedIntroduced2 = MergedIntroduced;
1902 VersionTuple MergedDeprecated2 = MergedDeprecated;
1903 VersionTuple MergedObsoleted2 = MergedObsoleted;
1905 if (MergedIntroduced2.empty())
1906 MergedIntroduced2 = OldIntroduced;
1907 if (MergedDeprecated2.empty())
1908 MergedDeprecated2 = OldDeprecated;
1909 if (MergedObsoleted2.empty())
1910 MergedObsoleted2 = OldObsoleted;
1912 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1913 MergedIntroduced2, MergedDeprecated2,
1914 MergedObsoleted2)) {
1915 Attrs.erase(Attrs.begin() + i);
1920 MergedIntroduced = MergedIntroduced2;
1921 MergedDeprecated = MergedDeprecated2;
1922 MergedObsoleted = MergedObsoleted2;
1928 MergedIntroduced == Introduced &&
1929 MergedDeprecated == Deprecated &&
1930 MergedObsoleted == Obsoleted)
1933 // Only create a new attribute if !Override, but we want to do
1935 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1936 MergedDeprecated, MergedObsoleted) &&
1938 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1939 Introduced, Deprecated,
1940 Obsoleted, IsUnavailable, Message,
1941 AttrSpellingListIndex);
1946 static void handleAvailabilityAttr(Sema &S, Decl *D,
1947 const AttributeList &Attr) {
1948 if (!checkAttributeNumArgs(S, Attr, 1))
1950 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1951 unsigned Index = Attr.getAttributeSpellingListIndex();
1953 IdentifierInfo *II = Platform->Ident;
1954 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1955 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1958 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1960 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1964 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1965 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1966 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1967 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1969 if (const StringLiteral *SE =
1970 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1971 Str = SE->getString();
1973 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1981 D->addAttr(NewAttr);
1985 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1986 typename T::VisibilityType value,
1987 unsigned attrSpellingListIndex) {
1988 T *existingAttr = D->getAttr<T>();
1990 typename T::VisibilityType existingValue = existingAttr->getVisibility();
1991 if (existingValue == value)
1993 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
1994 S.Diag(range.getBegin(), diag::note_previous_attribute);
1997 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2000 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2001 VisibilityAttr::VisibilityType Vis,
2002 unsigned AttrSpellingListIndex) {
2003 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2004 AttrSpellingListIndex);
2007 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2008 TypeVisibilityAttr::VisibilityType Vis,
2009 unsigned AttrSpellingListIndex) {
2010 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2011 AttrSpellingListIndex);
2014 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2015 bool isTypeVisibility) {
2016 // Visibility attributes don't mean anything on a typedef.
2017 if (isa<TypedefNameDecl>(D)) {
2018 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2023 // 'type_visibility' can only go on a type or namespace.
2024 if (isTypeVisibility &&
2025 !(isa<TagDecl>(D) ||
2026 isa<ObjCInterfaceDecl>(D) ||
2027 isa<NamespaceDecl>(D))) {
2028 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2029 << Attr.getName() << ExpectedTypeOrNamespace;
2033 // Check that the argument is a string literal.
2035 SourceLocation LiteralLoc;
2036 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2039 VisibilityAttr::VisibilityType type;
2040 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2041 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2042 << Attr.getName() << TypeStr;
2046 // Complain about attempts to use protected visibility on targets
2047 // (like Darwin) that don't support it.
2048 if (type == VisibilityAttr::Protected &&
2049 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2050 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2051 type = VisibilityAttr::Default;
2054 unsigned Index = Attr.getAttributeSpellingListIndex();
2055 clang::Attr *newAttr;
2056 if (isTypeVisibility) {
2057 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2058 (TypeVisibilityAttr::VisibilityType) type,
2061 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2064 D->addAttr(newAttr);
2067 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2068 const AttributeList &Attr) {
2069 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2070 if (!Attr.isArgIdent(0)) {
2071 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2072 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2076 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2077 ObjCMethodFamilyAttr::FamilyKind F;
2078 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2079 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2084 if (F == ObjCMethodFamilyAttr::OMF_init &&
2085 !method->getReturnType()->isObjCObjectPointerType()) {
2086 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2087 << method->getReturnType();
2088 // Ignore the attribute.
2092 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2094 Attr.getAttributeSpellingListIndex()));
2097 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2098 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2099 QualType T = TD->getUnderlyingType();
2100 if (!T->isCARCBridgableType()) {
2101 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2105 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2106 QualType T = PD->getType();
2107 if (!T->isCARCBridgableType()) {
2108 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2113 // It is okay to include this attribute on properties, e.g.:
2115 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2117 // In this case it follows tradition and suppresses an error in the above
2119 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2121 D->addAttr(::new (S.Context)
2122 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2123 Attr.getAttributeSpellingListIndex()));
2126 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2127 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2128 QualType T = TD->getUnderlyingType();
2129 if (!T->isObjCObjectPointerType()) {
2130 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2134 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2137 D->addAttr(::new (S.Context)
2138 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2139 Attr.getAttributeSpellingListIndex()));
2142 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2143 if (!Attr.isArgIdent(0)) {
2144 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2145 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2149 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2150 BlocksAttr::BlockType type;
2151 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2152 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2153 << Attr.getName() << II;
2157 D->addAttr(::new (S.Context)
2158 BlocksAttr(Attr.getRange(), S.Context, type,
2159 Attr.getAttributeSpellingListIndex()));
2162 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2163 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2164 if (Attr.getNumArgs() > 0) {
2165 Expr *E = Attr.getArgAsExpr(0);
2166 llvm::APSInt Idx(32);
2167 if (E->isTypeDependent() || E->isValueDependent() ||
2168 !E->isIntegerConstantExpr(Idx, S.Context)) {
2169 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2170 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2171 << E->getSourceRange();
2175 if (Idx.isSigned() && Idx.isNegative()) {
2176 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2177 << E->getSourceRange();
2181 sentinel = Idx.getZExtValue();
2184 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2185 if (Attr.getNumArgs() > 1) {
2186 Expr *E = Attr.getArgAsExpr(1);
2187 llvm::APSInt Idx(32);
2188 if (E->isTypeDependent() || E->isValueDependent() ||
2189 !E->isIntegerConstantExpr(Idx, S.Context)) {
2190 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2191 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2192 << E->getSourceRange();
2195 nullPos = Idx.getZExtValue();
2197 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2198 // FIXME: This error message could be improved, it would be nice
2199 // to say what the bounds actually are.
2200 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2201 << E->getSourceRange();
2206 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2207 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2208 if (isa<FunctionNoProtoType>(FT)) {
2209 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2213 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2214 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2217 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2218 if (!MD->isVariadic()) {
2219 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2222 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2223 if (!BD->isVariadic()) {
2224 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2227 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2228 QualType Ty = V->getType();
2229 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2230 const FunctionType *FT = Ty->isFunctionPointerType()
2231 ? D->getFunctionType()
2232 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2233 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2234 int m = Ty->isFunctionPointerType() ? 0 : 1;
2235 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2239 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2240 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2244 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2245 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2248 D->addAttr(::new (S.Context)
2249 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2250 Attr.getAttributeSpellingListIndex()));
2253 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2254 if (D->getFunctionType() &&
2255 D->getFunctionType()->getReturnType()->isVoidType()) {
2256 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2257 << Attr.getName() << 0;
2260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2261 if (MD->getReturnType()->isVoidType()) {
2262 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2263 << Attr.getName() << 1;
2267 D->addAttr(::new (S.Context)
2268 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2269 Attr.getAttributeSpellingListIndex()));
2272 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2273 // weak_import only applies to variable & function declarations.
2275 if (!D->canBeWeakImported(isDef)) {
2277 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2279 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2280 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2281 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2282 // Nothing to warn about here.
2284 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2285 << Attr.getName() << ExpectedVariableOrFunction;
2290 D->addAttr(::new (S.Context)
2291 WeakImportAttr(Attr.getRange(), S.Context,
2292 Attr.getAttributeSpellingListIndex()));
2295 // Handles reqd_work_group_size and work_group_size_hint.
2296 template <typename WorkGroupAttr>
2297 static void handleWorkGroupSize(Sema &S, Decl *D,
2298 const AttributeList &Attr) {
2300 for (unsigned i = 0; i < 3; ++i) {
2301 const Expr *E = Attr.getArgAsExpr(i);
2302 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2304 if (WGSize[i] == 0) {
2305 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2306 << Attr.getName() << E->getSourceRange();
2311 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2312 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2313 Existing->getYDim() == WGSize[1] &&
2314 Existing->getZDim() == WGSize[2]))
2315 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2317 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2318 WGSize[0], WGSize[1], WGSize[2],
2319 Attr.getAttributeSpellingListIndex()));
2322 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2323 if (!Attr.hasParsedType()) {
2324 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2325 << Attr.getName() << 1;
2329 TypeSourceInfo *ParmTSI = nullptr;
2330 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2331 assert(ParmTSI && "no type source info for attribute argument");
2333 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2334 (ParmType->isBooleanType() ||
2335 !ParmType->isIntegralType(S.getASTContext()))) {
2336 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2341 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2342 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2343 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2348 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2350 Attr.getAttributeSpellingListIndex()));
2353 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2355 unsigned AttrSpellingListIndex) {
2356 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2357 if (ExistingAttr->getName() == Name)
2359 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2360 Diag(Range.getBegin(), diag::note_previous_attribute);
2363 return ::new (Context) SectionAttr(Range, Context, Name,
2364 AttrSpellingListIndex);
2367 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2368 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2369 if (!Error.empty()) {
2370 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2376 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2377 // Make sure that there is a string literal as the sections's single
2380 SourceLocation LiteralLoc;
2381 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2384 if (!S.checkSectionName(LiteralLoc, Str))
2387 // If the target wants to validate the section specifier, make it happen.
2388 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2389 if (!Error.empty()) {
2390 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2395 unsigned Index = Attr.getAttributeSpellingListIndex();
2396 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2398 D->addAttr(NewAttr);
2401 // Check for things we'd like to warn about, no errors or validation for now.
2402 // TODO: Validation should use a backend target library that specifies
2403 // the allowable subtarget features and cpus. We could use something like a
2404 // TargetCodeGenInfo hook here to do validation.
2405 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2406 for (auto Str : {"tune=", "fpmath="})
2407 if (AttrStr.find(Str) != StringRef::npos)
2408 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2411 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2413 SourceLocation LiteralLoc;
2414 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2416 S.checkTargetAttr(LiteralLoc, Str);
2417 unsigned Index = Attr.getAttributeSpellingListIndex();
2418 TargetAttr *NewAttr =
2419 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2420 D->addAttr(NewAttr);
2424 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2425 VarDecl *VD = cast<VarDecl>(D);
2426 if (!VD->hasLocalStorage()) {
2427 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2431 Expr *E = Attr.getArgAsExpr(0);
2432 SourceLocation Loc = E->getExprLoc();
2433 FunctionDecl *FD = nullptr;
2434 DeclarationNameInfo NI;
2436 // gcc only allows for simple identifiers. Since we support more than gcc, we
2437 // will warn the user.
2438 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2439 if (DRE->hasQualifier())
2440 S.Diag(Loc, diag::warn_cleanup_ext);
2441 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2442 NI = DRE->getNameInfo();
2444 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2448 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2449 if (ULE->hasExplicitTemplateArgs())
2450 S.Diag(Loc, diag::warn_cleanup_ext);
2451 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2452 NI = ULE->getNameInfo();
2454 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2456 if (ULE->getType() == S.Context.OverloadTy)
2457 S.NoteAllOverloadCandidates(ULE);
2461 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2465 if (FD->getNumParams() != 1) {
2466 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2471 // We're currently more strict than GCC about what function types we accept.
2472 // If this ever proves to be a problem it should be easy to fix.
2473 QualType Ty = S.Context.getPointerType(VD->getType());
2474 QualType ParamTy = FD->getParamDecl(0)->getType();
2475 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2476 ParamTy, Ty) != Sema::Compatible) {
2477 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2478 << NI.getName() << ParamTy << Ty;
2482 D->addAttr(::new (S.Context)
2483 CleanupAttr(Attr.getRange(), S.Context, FD,
2484 Attr.getAttributeSpellingListIndex()));
2487 /// Handle __attribute__((format_arg((idx)))) attribute based on
2488 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2489 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2490 Expr *IdxExpr = Attr.getArgAsExpr(0);
2492 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2495 // make sure the format string is really a string
2496 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2498 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2499 if (not_nsstring_type &&
2500 !isCFStringType(Ty, S.Context) &&
2501 (!Ty->isPointerType() ||
2502 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2503 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2504 << (not_nsstring_type ? "a string type" : "an NSString")
2505 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2508 Ty = getFunctionOrMethodResultType(D);
2509 if (!isNSStringType(Ty, S.Context) &&
2510 !isCFStringType(Ty, S.Context) &&
2511 (!Ty->isPointerType() ||
2512 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2513 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2514 << (not_nsstring_type ? "string type" : "NSString")
2515 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2519 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2520 // because that has corrected for the implicit this parameter, and is zero-
2521 // based. The attribute expects what the user wrote explicitly.
2523 IdxExpr->EvaluateAsInt(Val, S.Context);
2525 D->addAttr(::new (S.Context)
2526 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2527 Attr.getAttributeSpellingListIndex()));
2530 enum FormatAttrKind {
2539 /// getFormatAttrKind - Map from format attribute names to supported format
2541 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2542 return llvm::StringSwitch<FormatAttrKind>(Format)
2543 // Check for formats that get handled specially.
2544 .Case("NSString", NSStringFormat)
2545 .Case("CFString", CFStringFormat)
2546 .Case("strftime", StrftimeFormat)
2548 // Otherwise, check for supported formats.
2549 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2550 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2551 .Case("kprintf", SupportedFormat) // OpenBSD.
2552 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2553 .Case("os_trace", SupportedFormat)
2555 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2556 .Default(InvalidFormat);
2559 /// Handle __attribute__((init_priority(priority))) attributes based on
2560 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2561 static void handleInitPriorityAttr(Sema &S, Decl *D,
2562 const AttributeList &Attr) {
2563 if (!S.getLangOpts().CPlusPlus) {
2564 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2568 if (S.getCurFunctionOrMethodDecl()) {
2569 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2573 QualType T = cast<VarDecl>(D)->getType();
2574 if (S.Context.getAsArrayType(T))
2575 T = S.Context.getBaseElementType(T);
2576 if (!T->getAs<RecordType>()) {
2577 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2582 Expr *E = Attr.getArgAsExpr(0);
2583 uint32_t prioritynum;
2584 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2589 if (prioritynum < 101 || prioritynum > 65535) {
2590 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2591 << E->getSourceRange();
2595 D->addAttr(::new (S.Context)
2596 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2597 Attr.getAttributeSpellingListIndex()));
2600 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2601 IdentifierInfo *Format, int FormatIdx,
2603 unsigned AttrSpellingListIndex) {
2604 // Check whether we already have an equivalent format attribute.
2605 for (auto *F : D->specific_attrs<FormatAttr>()) {
2606 if (F->getType() == Format &&
2607 F->getFormatIdx() == FormatIdx &&
2608 F->getFirstArg() == FirstArg) {
2609 // If we don't have a valid location for this attribute, adopt the
2611 if (F->getLocation().isInvalid())
2617 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2618 FirstArg, AttrSpellingListIndex);
2621 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2622 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2623 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2624 if (!Attr.isArgIdent(0)) {
2625 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2626 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2630 // In C++ the implicit 'this' function parameter also counts, and they are
2631 // counted from one.
2632 bool HasImplicitThisParam = isInstanceMethod(D);
2633 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2635 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2636 StringRef Format = II->getName();
2638 // Normalize the argument, __foo__ becomes foo.
2639 if (Format.startswith("__") && Format.endswith("__")) {
2640 Format = Format.substr(2, Format.size() - 4);
2641 // If we've modified the string name, we need a new identifier for it.
2642 II = &S.Context.Idents.get(Format);
2645 // Check for supported formats.
2646 FormatAttrKind Kind = getFormatAttrKind(Format);
2648 if (Kind == IgnoredFormat)
2651 if (Kind == InvalidFormat) {
2652 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2653 << Attr.getName() << II->getName();
2657 // checks for the 2nd argument
2658 Expr *IdxExpr = Attr.getArgAsExpr(1);
2660 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2663 if (Idx < 1 || Idx > NumArgs) {
2664 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2665 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2669 // FIXME: Do we need to bounds check?
2670 unsigned ArgIdx = Idx - 1;
2672 if (HasImplicitThisParam) {
2674 S.Diag(Attr.getLoc(),
2675 diag::err_format_attribute_implicit_this_format_string)
2676 << IdxExpr->getSourceRange();
2682 // make sure the format string is really a string
2683 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2685 if (Kind == CFStringFormat) {
2686 if (!isCFStringType(Ty, S.Context)) {
2687 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2688 << "a CFString" << IdxExpr->getSourceRange()
2689 << getFunctionOrMethodParamRange(D, ArgIdx);
2692 } else if (Kind == NSStringFormat) {
2693 // FIXME: do we need to check if the type is NSString*? What are the
2695 if (!isNSStringType(Ty, S.Context)) {
2696 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2697 << "an NSString" << IdxExpr->getSourceRange()
2698 << getFunctionOrMethodParamRange(D, ArgIdx);
2701 } else if (!Ty->isPointerType() ||
2702 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2703 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2704 << "a string type" << IdxExpr->getSourceRange()
2705 << getFunctionOrMethodParamRange(D, ArgIdx);
2709 // check the 3rd argument
2710 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2712 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2715 // check if the function is variadic if the 3rd argument non-zero
2716 if (FirstArg != 0) {
2717 if (isFunctionOrMethodVariadic(D)) {
2718 ++NumArgs; // +1 for ...
2720 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2725 // strftime requires FirstArg to be 0 because it doesn't read from any
2726 // variable the input is just the current time + the format string.
2727 if (Kind == StrftimeFormat) {
2728 if (FirstArg != 0) {
2729 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2730 << FirstArgExpr->getSourceRange();
2733 // if 0 it disables parameter checking (to use with e.g. va_list)
2734 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2735 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2736 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2740 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2742 Attr.getAttributeSpellingListIndex());
2744 D->addAttr(NewAttr);
2747 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2748 const AttributeList &Attr) {
2749 // Try to find the underlying union declaration.
2750 RecordDecl *RD = nullptr;
2751 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2752 if (TD && TD->getUnderlyingType()->isUnionType())
2753 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2755 RD = dyn_cast<RecordDecl>(D);
2757 if (!RD || !RD->isUnion()) {
2758 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2759 << Attr.getName() << ExpectedUnion;
2763 if (!RD->isCompleteDefinition()) {
2764 S.Diag(Attr.getLoc(),
2765 diag::warn_transparent_union_attribute_not_definition);
2769 RecordDecl::field_iterator Field = RD->field_begin(),
2770 FieldEnd = RD->field_end();
2771 if (Field == FieldEnd) {
2772 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2776 FieldDecl *FirstField = *Field;
2777 QualType FirstType = FirstField->getType();
2778 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2779 S.Diag(FirstField->getLocation(),
2780 diag::warn_transparent_union_attribute_floating)
2781 << FirstType->isVectorType() << FirstType;
2785 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2786 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2787 for (; Field != FieldEnd; ++Field) {
2788 QualType FieldType = Field->getType();
2789 // FIXME: this isn't fully correct; we also need to test whether the
2790 // members of the union would all have the same calling convention as the
2791 // first member of the union. Checking just the size and alignment isn't
2792 // sufficient (consider structs passed on the stack instead of in registers
2794 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2795 S.Context.getTypeAlign(FieldType) > FirstAlign) {
2796 // Warn if we drop the attribute.
2797 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2798 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2799 : S.Context.getTypeAlign(FieldType);
2800 S.Diag(Field->getLocation(),
2801 diag::warn_transparent_union_attribute_field_size_align)
2802 << isSize << Field->getDeclName() << FieldBits;
2803 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2804 S.Diag(FirstField->getLocation(),
2805 diag::note_transparent_union_first_field_size_align)
2806 << isSize << FirstBits;
2811 RD->addAttr(::new (S.Context)
2812 TransparentUnionAttr(Attr.getRange(), S.Context,
2813 Attr.getAttributeSpellingListIndex()));
2816 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2817 // Make sure that there is a string literal as the annotation's single
2820 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2823 // Don't duplicate annotations that are already set.
2824 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2825 if (I->getAnnotation() == Str)
2829 D->addAttr(::new (S.Context)
2830 AnnotateAttr(Attr.getRange(), S.Context, Str,
2831 Attr.getAttributeSpellingListIndex()));
2834 static void handleAlignValueAttr(Sema &S, Decl *D,
2835 const AttributeList &Attr) {
2836 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
2837 Attr.getAttributeSpellingListIndex());
2840 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
2841 unsigned SpellingListIndex) {
2842 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
2843 SourceLocation AttrLoc = AttrRange.getBegin();
2846 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2847 T = TD->getUnderlyingType();
2848 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2851 llvm_unreachable("Unknown decl type for align_value");
2853 if (!T->isDependentType() && !T->isAnyPointerType() &&
2854 !T->isReferenceType() && !T->isMemberPointerType()) {
2855 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
2856 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
2860 if (!E->isValueDependent()) {
2861 llvm::APSInt Alignment(32);
2863 = VerifyIntegerConstantExpression(E, &Alignment,
2864 diag::err_align_value_attribute_argument_not_int,
2865 /*AllowFold*/ false);
2866 if (ICE.isInvalid())
2869 if (!Alignment.isPowerOf2()) {
2870 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2871 << E->getSourceRange();
2875 D->addAttr(::new (Context)
2876 AlignValueAttr(AttrRange, Context, ICE.get(),
2877 SpellingListIndex));
2881 // Save dependent expressions in the AST to be instantiated.
2882 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
2886 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2887 // check the attribute arguments.
2888 if (Attr.getNumArgs() > 1) {
2889 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2890 << Attr.getName() << 1;
2894 if (Attr.getNumArgs() == 0) {
2895 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2896 true, nullptr, Attr.getAttributeSpellingListIndex()));
2900 Expr *E = Attr.getArgAsExpr(0);
2901 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2902 S.Diag(Attr.getEllipsisLoc(),
2903 diag::err_pack_expansion_without_parameter_packs);
2907 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2910 if (E->isValueDependent()) {
2911 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
2912 if (!TND->getUnderlyingType()->isDependentType()) {
2913 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
2914 << E->getSourceRange();
2920 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2921 Attr.isPackExpansion());
2924 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2925 unsigned SpellingListIndex, bool IsPackExpansion) {
2926 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2927 SourceLocation AttrLoc = AttrRange.getBegin();
2929 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2930 if (TmpAttr.isAlignas()) {
2931 // C++11 [dcl.align]p1:
2932 // An alignment-specifier may be applied to a variable or to a class
2933 // data member, but it shall not be applied to a bit-field, a function
2934 // parameter, the formal parameter of a catch clause, or a variable
2935 // declared with the register storage class specifier. An
2936 // alignment-specifier may also be applied to the declaration of a class
2937 // or enumeration type.
2939 // An alignment attribute shall not be specified in a declaration of
2940 // a typedef, or a bit-field, or a function, or a parameter, or an
2941 // object declared with the register storage-class specifier.
2943 if (isa<ParmVarDecl>(D)) {
2945 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2946 if (VD->getStorageClass() == SC_Register)
2948 if (VD->isExceptionVariable())
2950 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2951 if (FD->isBitField())
2953 } else if (!isa<TagDecl>(D)) {
2954 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2955 << (TmpAttr.isC11() ? ExpectedVariableOrField
2956 : ExpectedVariableFieldOrTag);
2959 if (DiagKind != -1) {
2960 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2961 << &TmpAttr << DiagKind;
2966 if (E->isTypeDependent() || E->isValueDependent()) {
2967 // Save dependent expressions in the AST to be instantiated.
2968 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2969 AA->setPackExpansion(IsPackExpansion);
2974 // FIXME: Cache the number on the Attr object?
2975 llvm::APSInt Alignment(32);
2977 = VerifyIntegerConstantExpression(E, &Alignment,
2978 diag::err_aligned_attribute_argument_not_int,
2979 /*AllowFold*/ false);
2980 if (ICE.isInvalid())
2983 // C++11 [dcl.align]p2:
2984 // -- if the constant expression evaluates to zero, the alignment
2985 // specifier shall have no effect
2987 // An alignment specification of zero has no effect.
2988 if (!(TmpAttr.isAlignas() && !Alignment)) {
2989 if(!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2990 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2991 << E->getSourceRange();
2994 if (Context.getTargetInfo().isTLSSupported()) {
2995 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
2996 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2997 if (VD->getTLSKind()) {
2998 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
2999 if (Alignment.getSExtValue() > MaxAlignChars.getQuantity()) {
3000 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3001 << (unsigned)Alignment.getZExtValue() << VD
3002 << (unsigned)MaxAlignChars.getQuantity();
3011 // Alignment calculations can wrap around if it's greater than 2**28.
3012 unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
3013 if (Alignment.getZExtValue() > MaxValidAlignment) {
3014 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3015 << E->getSourceRange();
3019 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3020 ICE.get(), SpellingListIndex);
3021 AA->setPackExpansion(IsPackExpansion);
3025 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3026 unsigned SpellingListIndex, bool IsPackExpansion) {
3027 // FIXME: Cache the number on the Attr object if non-dependent?
3028 // FIXME: Perform checking of type validity
3029 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3031 AA->setPackExpansion(IsPackExpansion);
3035 void Sema::CheckAlignasUnderalignment(Decl *D) {
3036 assert(D->hasAttrs() && "no attributes on decl");
3038 QualType UnderlyingTy, DiagTy;
3039 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3040 UnderlyingTy = DiagTy = VD->getType();
3042 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3043 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3044 UnderlyingTy = ED->getIntegerType();
3046 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3049 // C++11 [dcl.align]p5, C11 6.7.5/4:
3050 // The combined effect of all alignment attributes in a declaration shall
3051 // not specify an alignment that is less strict than the alignment that
3052 // would otherwise be required for the entity being declared.
3053 AlignedAttr *AlignasAttr = nullptr;
3055 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3056 if (I->isAlignmentDependent())
3060 Align = std::max(Align, I->getAlignment(Context));
3063 if (AlignasAttr && Align) {
3064 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3065 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3066 if (NaturalAlign > RequestedAlign)
3067 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3068 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3072 bool Sema::checkMSInheritanceAttrOnDefinition(
3073 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3074 MSInheritanceAttr::Spelling SemanticSpelling) {
3075 assert(RD->hasDefinition() && "RD has no definition!");
3077 // We may not have seen base specifiers or any virtual methods yet. We will
3078 // have to wait until the record is defined to catch any mismatches.
3079 if (!RD->getDefinition()->isCompleteDefinition())
3082 // The unspecified model never matches what a definition could need.
3083 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3087 if (RD->calculateInheritanceModel() == SemanticSpelling)
3090 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3094 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3095 << 0 /*definition*/;
3096 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3097 << RD->getNameAsString();
3101 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3104 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3105 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3106 /// HImode, not an intermediate pointer.
3107 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3108 // This attribute isn't documented, but glibc uses it. It changes
3109 // the width of an int or unsigned int to the specified size.
3110 if (!Attr.isArgIdent(0)) {
3111 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3112 << AANT_ArgumentIdentifier;
3116 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3117 StringRef Str = Name->getName();
3119 // Normalize the attribute name, __foo__ becomes foo.
3120 if (Str.startswith("__") && Str.endswith("__"))
3121 Str = Str.substr(2, Str.size() - 4);
3123 unsigned DestWidth = 0;
3124 bool IntegerMode = true;
3125 bool ComplexMode = false;
3126 switch (Str.size()) {
3129 case 'Q': DestWidth = 8; break;
3130 case 'H': DestWidth = 16; break;
3131 case 'S': DestWidth = 32; break;
3132 case 'D': DestWidth = 64; break;
3133 case 'X': DestWidth = 96; break;
3134 case 'T': DestWidth = 128; break;
3136 if (Str[1] == 'F') {
3137 IntegerMode = false;
3138 } else if (Str[1] == 'C') {
3139 IntegerMode = false;
3141 } else if (Str[1] != 'I') {
3146 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3147 // pointer on PIC16 and other embedded platforms.
3149 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3150 else if (Str == "byte")
3151 DestWidth = S.Context.getTargetInfo().getCharWidth();
3154 if (Str == "pointer")
3155 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3158 if (Str == "unwind_word")
3159 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3164 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3165 OldTy = TD->getUnderlyingType();
3166 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3167 OldTy = VD->getType();
3169 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3170 << Attr.getName() << Attr.getRange();
3174 // Base type can also be a vector type (see PR17453).
3175 // Distinguish between base type and base element type.
3176 QualType OldElemTy = OldTy;
3177 if (const VectorType *VT = OldTy->getAs<VectorType>())
3178 OldElemTy = VT->getElementType();
3180 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
3181 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3182 else if (IntegerMode) {
3183 if (!OldElemTy->isIntegralOrEnumerationType())
3184 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3185 } else if (ComplexMode) {
3186 if (!OldElemTy->isComplexType())
3187 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3189 if (!OldElemTy->isFloatingType())
3190 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3193 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3194 // and friends, at least with glibc.
3195 // FIXME: Make sure floating-point mappings are accurate
3196 // FIXME: Support XF and TF types
3198 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3205 NewElemTy = S.Context.getIntTypeForBitwidth(
3206 DestWidth, OldElemTy->isSignedIntegerType());
3208 NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
3210 if (NewElemTy.isNull()) {
3211 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3216 NewElemTy = S.Context.getComplexType(NewElemTy);
3219 QualType NewTy = NewElemTy;
3220 if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3221 // Complex machine mode does not support base vector types.
3223 S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
3226 unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
3227 OldVT->getNumElements() /
3228 S.Context.getTypeSize(NewElemTy);
3230 S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3233 if (NewTy.isNull()) {
3234 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3238 // Install the new type.
3239 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3240 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3242 cast<ValueDecl>(D)->setType(NewTy);
3244 D->addAttr(::new (S.Context)
3245 ModeAttr(Attr.getRange(), S.Context, Name,
3246 Attr.getAttributeSpellingListIndex()));
3249 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3250 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3251 if (!VD->hasGlobalStorage())
3252 S.Diag(Attr.getLoc(),
3253 diag::warn_attribute_requires_functions_or_static_globals)
3255 } else if (!isFunctionOrMethod(D)) {
3256 S.Diag(Attr.getLoc(),
3257 diag::warn_attribute_requires_functions_or_static_globals)
3262 D->addAttr(::new (S.Context)
3263 NoDebugAttr(Attr.getRange(), S.Context,
3264 Attr.getAttributeSpellingListIndex()));
3267 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3268 IdentifierInfo *Ident,
3269 unsigned AttrSpellingListIndex) {
3270 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3271 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3272 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3276 if (D->hasAttr<AlwaysInlineAttr>())
3279 return ::new (Context) AlwaysInlineAttr(Range, Context,
3280 AttrSpellingListIndex);
3283 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3284 unsigned AttrSpellingListIndex) {
3285 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3286 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3287 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3291 if (D->hasAttr<MinSizeAttr>())
3294 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3297 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3298 unsigned AttrSpellingListIndex) {
3299 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3300 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3301 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3302 D->dropAttr<AlwaysInlineAttr>();
3304 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3305 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3306 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3307 D->dropAttr<MinSizeAttr>();
3310 if (D->hasAttr<OptimizeNoneAttr>())
3313 return ::new (Context) OptimizeNoneAttr(Range, Context,
3314 AttrSpellingListIndex);
3317 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3318 const AttributeList &Attr) {
3319 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3320 D, Attr.getRange(), Attr.getName(),
3321 Attr.getAttributeSpellingListIndex()))
3325 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3326 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3327 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3328 D->addAttr(MinSize);
3331 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3332 const AttributeList &Attr) {
3333 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3334 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3335 D->addAttr(Optnone);
3338 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3339 FunctionDecl *FD = cast<FunctionDecl>(D);
3340 if (!FD->getReturnType()->isVoidType()) {
3341 SourceRange RTRange = FD->getReturnTypeSourceRange();
3342 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3344 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3349 D->addAttr(::new (S.Context)
3350 CUDAGlobalAttr(Attr.getRange(), S.Context,
3351 Attr.getAttributeSpellingListIndex()));
3354 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3355 FunctionDecl *Fn = cast<FunctionDecl>(D);
3356 if (!Fn->isInlineSpecified()) {
3357 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3361 D->addAttr(::new (S.Context)
3362 GNUInlineAttr(Attr.getRange(), S.Context,
3363 Attr.getAttributeSpellingListIndex()));
3366 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3367 if (hasDeclarator(D)) return;
3369 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3370 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3372 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3375 if (!isa<ObjCMethodDecl>(D)) {
3376 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3377 << Attr.getName() << ExpectedFunctionOrMethod;
3381 switch (Attr.getKind()) {
3382 case AttributeList::AT_FastCall:
3383 D->addAttr(::new (S.Context)
3384 FastCallAttr(Attr.getRange(), S.Context,
3385 Attr.getAttributeSpellingListIndex()));
3387 case AttributeList::AT_StdCall:
3388 D->addAttr(::new (S.Context)
3389 StdCallAttr(Attr.getRange(), S.Context,
3390 Attr.getAttributeSpellingListIndex()));
3392 case AttributeList::AT_ThisCall:
3393 D->addAttr(::new (S.Context)
3394 ThisCallAttr(Attr.getRange(), S.Context,
3395 Attr.getAttributeSpellingListIndex()));
3397 case AttributeList::AT_CDecl:
3398 D->addAttr(::new (S.Context)
3399 CDeclAttr(Attr.getRange(), S.Context,
3400 Attr.getAttributeSpellingListIndex()));
3402 case AttributeList::AT_Pascal:
3403 D->addAttr(::new (S.Context)
3404 PascalAttr(Attr.getRange(), S.Context,
3405 Attr.getAttributeSpellingListIndex()));
3407 case AttributeList::AT_VectorCall:
3408 D->addAttr(::new (S.Context)
3409 VectorCallAttr(Attr.getRange(), S.Context,
3410 Attr.getAttributeSpellingListIndex()));
3412 case AttributeList::AT_MSABI:
3413 D->addAttr(::new (S.Context)
3414 MSABIAttr(Attr.getRange(), S.Context,
3415 Attr.getAttributeSpellingListIndex()));
3417 case AttributeList::AT_SysVABI:
3418 D->addAttr(::new (S.Context)
3419 SysVABIAttr(Attr.getRange(), S.Context,
3420 Attr.getAttributeSpellingListIndex()));
3422 case AttributeList::AT_Pcs: {
3423 PcsAttr::PCSType PCS;
3426 PCS = PcsAttr::AAPCS;
3429 PCS = PcsAttr::AAPCS_VFP;
3432 llvm_unreachable("unexpected calling convention in pcs attribute");
3435 D->addAttr(::new (S.Context)
3436 PcsAttr(Attr.getRange(), S.Context, PCS,
3437 Attr.getAttributeSpellingListIndex()));
3440 case AttributeList::AT_IntelOclBicc:
3441 D->addAttr(::new (S.Context)
3442 IntelOclBiccAttr(Attr.getRange(), S.Context,
3443 Attr.getAttributeSpellingListIndex()));
3447 llvm_unreachable("unexpected attribute kind");
3451 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3452 const FunctionDecl *FD) {
3453 if (attr.isInvalid())
3456 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3457 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3462 // TODO: diagnose uses of these conventions on the wrong target.
3463 switch (attr.getKind()) {
3464 case AttributeList::AT_CDecl: CC = CC_C; break;
3465 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3466 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3467 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3468 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3469 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3470 case AttributeList::AT_MSABI:
3471 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3474 case AttributeList::AT_SysVABI:
3475 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3478 case AttributeList::AT_Pcs: {
3480 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3484 if (StrRef == "aapcs") {
3487 } else if (StrRef == "aapcs-vfp") {
3493 Diag(attr.getLoc(), diag::err_invalid_pcs);
3496 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3497 default: llvm_unreachable("unexpected attribute kind");
3500 const TargetInfo &TI = Context.getTargetInfo();
3501 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3502 if (A != TargetInfo::CCCR_OK) {
3503 if (A == TargetInfo::CCCR_Warning)
3504 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3506 // This convention is not valid for the target. Use the default function or
3507 // method calling convention.
3508 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3510 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3511 TargetInfo::CCMT_NonMember;
3512 CC = TI.getDefaultCallingConv(MT);
3518 /// Checks a regparm attribute, returning true if it is ill-formed and
3519 /// otherwise setting numParams to the appropriate value.
3520 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3521 if (Attr.isInvalid())
3524 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3530 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3531 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3536 if (Context.getTargetInfo().getRegParmMax() == 0) {
3537 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3538 << NumParamsExpr->getSourceRange();
3544 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3545 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3546 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3554 // Checks whether an argument of launch_bounds attribute is acceptable
3555 // May output an error.
3556 static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
3557 const CUDALaunchBoundsAttr &Attr,
3558 const unsigned Idx) {
3560 if (S.DiagnoseUnexpandedParameterPack(E))
3563 // Accept template arguments for now as they depend on something else.
3564 // We'll get to check them when they eventually get instantiated.
3565 if (E->isValueDependent())
3569 if (!E->isIntegerConstantExpr(I, S.Context)) {
3570 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
3571 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
3574 // Make sure we can fit it in 32 bits.
3575 if (!I.isIntN(32)) {
3576 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
3577 << 32 << /* Unsigned */ 1;
3581 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
3582 << &Attr << Idx << E->getSourceRange();
3587 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
3588 Expr *MinBlocks, unsigned SpellingListIndex) {
3589 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
3592 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
3595 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
3598 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
3599 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
3602 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3603 const AttributeList &Attr) {
3604 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
3605 !checkAttributeAtMostNumArgs(S, Attr, 2))
3608 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3609 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
3610 Attr.getAttributeSpellingListIndex());
3613 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3614 const AttributeList &Attr) {
3615 if (!Attr.isArgIdent(0)) {
3616 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3617 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3621 if (!checkAttributeNumArgs(S, Attr, 3))
3624 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3626 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3627 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3628 << Attr.getName() << ExpectedFunctionOrMethod;
3632 uint64_t ArgumentIdx;
3633 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3637 uint64_t TypeTagIdx;
3638 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3642 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3644 // Ensure that buffer has a pointer type.
3645 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3646 if (!BufferTy->isPointerType()) {
3647 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3652 D->addAttr(::new (S.Context)
3653 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3654 ArgumentIdx, TypeTagIdx, IsPointer,
3655 Attr.getAttributeSpellingListIndex()));
3658 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3659 const AttributeList &Attr) {
3660 if (!Attr.isArgIdent(0)) {
3661 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3662 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3666 if (!checkAttributeNumArgs(S, Attr, 1))
3669 if (!isa<VarDecl>(D)) {
3670 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3671 << Attr.getName() << ExpectedVariable;
3675 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3676 TypeSourceInfo *MatchingCTypeLoc = nullptr;
3677 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3678 assert(MatchingCTypeLoc && "no type source info for attribute argument");
3680 D->addAttr(::new (S.Context)
3681 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3683 Attr.getLayoutCompatible(),
3684 Attr.getMustBeNull(),
3685 Attr.getAttributeSpellingListIndex()));
3688 //===----------------------------------------------------------------------===//
3689 // Checker-specific attribute handlers.
3690 //===----------------------------------------------------------------------===//
3692 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3693 return type->isDependentType() ||
3694 type->isObjCRetainableType();
3697 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3698 return type->isDependentType() ||
3699 type->isObjCObjectPointerType() ||
3700 S.Context.isObjCNSObjectType(type);
3702 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3703 return type->isDependentType() ||
3704 type->isPointerType() ||
3705 isValidSubjectOfNSAttribute(S, type);
3708 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3709 ParmVarDecl *param = cast<ParmVarDecl>(D);
3712 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3713 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3716 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3721 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3722 << Attr.getRange() << Attr.getName() << cf;
3727 param->addAttr(::new (S.Context)
3728 CFConsumedAttr(Attr.getRange(), S.Context,
3729 Attr.getAttributeSpellingListIndex()));
3731 param->addAttr(::new (S.Context)
3732 NSConsumedAttr(Attr.getRange(), S.Context,
3733 Attr.getAttributeSpellingListIndex()));
3736 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3737 const AttributeList &Attr) {
3739 QualType returnType;
3741 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3742 returnType = MD->getReturnType();
3743 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3744 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3745 return; // ignore: was handled as a type attribute
3746 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3747 returnType = PD->getType();
3748 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3749 returnType = FD->getReturnType();
3750 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
3751 returnType = Param->getType()->getPointeeType();
3752 if (returnType.isNull()) {
3753 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3754 << Attr.getName() << /*pointer-to-CF*/2
3759 AttributeDeclKind ExpectedDeclKind;
3760 switch (Attr.getKind()) {
3761 default: llvm_unreachable("invalid ownership attribute");
3762 case AttributeList::AT_NSReturnsRetained:
3763 case AttributeList::AT_NSReturnsAutoreleased:
3764 case AttributeList::AT_NSReturnsNotRetained:
3765 ExpectedDeclKind = ExpectedFunctionOrMethod;
3768 case AttributeList::AT_CFReturnsRetained:
3769 case AttributeList::AT_CFReturnsNotRetained:
3770 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
3773 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3774 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
3780 switch (Attr.getKind()) {
3781 default: llvm_unreachable("invalid ownership attribute");
3782 case AttributeList::AT_NSReturnsRetained:
3783 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
3787 case AttributeList::AT_NSReturnsAutoreleased:
3788 case AttributeList::AT_NSReturnsNotRetained:
3789 typeOK = isValidSubjectOfNSAttribute(S, returnType);
3793 case AttributeList::AT_CFReturnsRetained:
3794 case AttributeList::AT_CFReturnsNotRetained:
3795 typeOK = isValidSubjectOfCFAttribute(S, returnType);
3801 if (isa<ParmVarDecl>(D)) {
3802 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3803 << Attr.getName() << /*pointer-to-CF*/2
3806 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
3811 } SubjectKind = Function;
3812 if (isa<ObjCMethodDecl>(D))
3813 SubjectKind = Method;
3814 else if (isa<ObjCPropertyDecl>(D))
3815 SubjectKind = Property;
3816 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3817 << Attr.getName() << SubjectKind << cf
3823 switch (Attr.getKind()) {
3825 llvm_unreachable("invalid ownership attribute");
3826 case AttributeList::AT_NSReturnsAutoreleased:
3827 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
3828 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3830 case AttributeList::AT_CFReturnsNotRetained:
3831 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
3832 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3834 case AttributeList::AT_NSReturnsNotRetained:
3835 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
3836 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3838 case AttributeList::AT_CFReturnsRetained:
3839 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
3840 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3842 case AttributeList::AT_NSReturnsRetained:
3843 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
3844 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3849 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3850 const AttributeList &attr) {
3851 const int EP_ObjCMethod = 1;
3852 const int EP_ObjCProperty = 2;
3854 SourceLocation loc = attr.getLoc();
3855 QualType resultType;
3856 if (isa<ObjCMethodDecl>(D))
3857 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3859 resultType = cast<ObjCPropertyDecl>(D)->getType();
3861 if (!resultType->isReferenceType() &&
3862 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3863 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3866 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3867 << /*non-retainable pointer*/ 2;
3869 // Drop the attribute.
3873 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
3874 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
3877 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3878 const AttributeList &attr) {
3879 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3881 DeclContext *DC = method->getDeclContext();
3882 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3883 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3884 << attr.getName() << 0;
3885 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3888 if (method->getMethodFamily() == OMF_dealloc) {
3889 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3890 << attr.getName() << 1;
3894 method->addAttr(::new (S.Context)
3895 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3896 attr.getAttributeSpellingListIndex()));
3899 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3900 const AttributeList &Attr) {
3901 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3904 D->addAttr(::new (S.Context)
3905 CFAuditedTransferAttr(Attr.getRange(), S.Context,
3906 Attr.getAttributeSpellingListIndex()));
3909 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3910 const AttributeList &Attr) {
3911 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3914 D->addAttr(::new (S.Context)
3915 CFUnknownTransferAttr(Attr.getRange(), S.Context,
3916 Attr.getAttributeSpellingListIndex()));
3919 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3920 const AttributeList &Attr) {
3921 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3924 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3928 // Typedefs only allow objc_bridge(id) and have some additional checking.
3929 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
3930 if (!Parm->Ident->isStr("id")) {
3931 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
3936 // Only allow 'cv void *'.
3937 QualType T = TD->getUnderlyingType();
3938 if (!T->isVoidPointerType()) {
3939 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
3944 D->addAttr(::new (S.Context)
3945 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3946 Attr.getAttributeSpellingListIndex()));
3949 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3950 const AttributeList &Attr) {
3951 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3954 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3958 D->addAttr(::new (S.Context)
3959 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3960 Attr.getAttributeSpellingListIndex()));
3963 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3964 const AttributeList &Attr) {
3965 IdentifierInfo *RelatedClass =
3966 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
3967 if (!RelatedClass) {
3968 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3971 IdentifierInfo *ClassMethod =
3972 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
3973 IdentifierInfo *InstanceMethod =
3974 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
3975 D->addAttr(::new (S.Context)
3976 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3977 ClassMethod, InstanceMethod,
3978 Attr.getAttributeSpellingListIndex()));
3981 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3982 const AttributeList &Attr) {
3983 ObjCInterfaceDecl *IFace;
3984 if (ObjCCategoryDecl *CatDecl =
3985 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
3986 IFace = CatDecl->getClassInterface();
3988 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3993 IFace->setHasDesignatedInitializers();
3994 D->addAttr(::new (S.Context)
3995 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3996 Attr.getAttributeSpellingListIndex()));
3999 static void handleObjCRuntimeName(Sema &S, Decl *D,
4000 const AttributeList &Attr) {
4001 StringRef MetaDataName;
4002 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4004 D->addAttr(::new (S.Context)
4005 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4007 Attr.getAttributeSpellingListIndex()));
4010 // when a user wants to use objc_boxable with a union or struct
4011 // but she doesn't have access to the declaration (legacy/third-party code)
4012 // then she can 'enable' this feature via trick with a typedef
4014 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4015 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4016 bool notify = false;
4018 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4019 if (RD && RD->getDefinition()) {
4020 RD = RD->getDefinition();
4025 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4026 ObjCBoxableAttr(Attr.getRange(), S.Context,
4027 Attr.getAttributeSpellingListIndex());
4028 RD->addAttr(BoxableAttr);
4030 // we need to notify ASTReader/ASTWriter about
4031 // modification of existing declaration
4032 if (ASTMutationListener *L = S.getASTMutationListener())
4033 L->AddedAttributeToRecord(BoxableAttr, RD);
4038 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4039 const AttributeList &Attr) {
4040 if (hasDeclarator(D)) return;
4042 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4043 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4046 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4047 const AttributeList &Attr) {
4048 ValueDecl *vd = cast<ValueDecl>(D);
4049 QualType type = vd->getType();
4051 if (!type->isDependentType() &&
4052 !type->isObjCLifetimeType()) {
4053 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4058 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4060 // If we have no lifetime yet, check the lifetime we're presumably
4062 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4063 lifetime = type->getObjCARCImplicitLifetime();
4066 case Qualifiers::OCL_None:
4067 assert(type->isDependentType() &&
4068 "didn't infer lifetime for non-dependent type?");
4071 case Qualifiers::OCL_Weak: // meaningful
4072 case Qualifiers::OCL_Strong: // meaningful
4075 case Qualifiers::OCL_ExplicitNone:
4076 case Qualifiers::OCL_Autoreleasing:
4077 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4078 << (lifetime == Qualifiers::OCL_Autoreleasing);
4082 D->addAttr(::new (S.Context)
4083 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4084 Attr.getAttributeSpellingListIndex()));
4087 //===----------------------------------------------------------------------===//
4088 // Microsoft specific attribute handlers.
4089 //===----------------------------------------------------------------------===//
4091 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4092 if (!S.LangOpts.CPlusPlus) {
4093 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4094 << Attr.getName() << AttributeLangSupport::C;
4098 if (!isa<CXXRecordDecl>(D)) {
4099 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4100 << Attr.getName() << ExpectedClass;
4105 SourceLocation LiteralLoc;
4106 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4109 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4110 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4111 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4112 StrRef = StrRef.drop_front().drop_back();
4114 // Validate GUID length.
4115 if (StrRef.size() != 36) {
4116 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4120 for (unsigned i = 0; i < 36; ++i) {
4121 if (i == 8 || i == 13 || i == 18 || i == 23) {
4122 if (StrRef[i] != '-') {
4123 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4126 } else if (!isHexDigit(StrRef[i])) {
4127 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4132 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4133 Attr.getAttributeSpellingListIndex()));
4136 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4137 if (!S.LangOpts.CPlusPlus) {
4138 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4139 << Attr.getName() << AttributeLangSupport::C;
4142 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4143 D, Attr.getRange(), /*BestCase=*/true,
4144 Attr.getAttributeSpellingListIndex(),
4145 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4150 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4151 const AttributeList &Attr) {
4152 VarDecl *VD = cast<VarDecl>(D);
4153 if (!S.Context.getTargetInfo().isTLSSupported()) {
4154 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4157 if (VD->getTSCSpec() != TSCS_unspecified) {
4158 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4161 if (VD->hasLocalStorage()) {
4162 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4165 VD->addAttr(::new (S.Context) ThreadAttr(
4166 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4169 static void handleARMInterruptAttr(Sema &S, Decl *D,
4170 const AttributeList &Attr) {
4171 // Check the attribute arguments.
4172 if (Attr.getNumArgs() > 1) {
4173 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4174 << Attr.getName() << 1;
4179 SourceLocation ArgLoc;
4181 if (Attr.getNumArgs() == 0)
4183 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4186 ARMInterruptAttr::InterruptType Kind;
4187 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4188 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4189 << Attr.getName() << Str << ArgLoc;
4193 unsigned Index = Attr.getAttributeSpellingListIndex();
4194 D->addAttr(::new (S.Context)
4195 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4198 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4199 const AttributeList &Attr) {
4200 if (!checkAttributeNumArgs(S, Attr, 1))
4203 if (!Attr.isArgExpr(0)) {
4204 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4205 << AANT_ArgumentIntegerConstant;
4209 // FIXME: Check for decl - it should be void ()(void).
4211 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4212 llvm::APSInt NumParams(32);
4213 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4214 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4215 << Attr.getName() << AANT_ArgumentIntegerConstant
4216 << NumParamsExpr->getSourceRange();
4220 unsigned Num = NumParams.getLimitedValue(255);
4221 if ((Num & 1) || Num > 30) {
4222 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4223 << Attr.getName() << (int)NumParams.getSExtValue()
4224 << NumParamsExpr->getSourceRange();
4228 D->addAttr(::new (S.Context)
4229 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4230 Attr.getAttributeSpellingListIndex()));
4231 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4234 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4235 // Dispatch the interrupt attribute based on the current target.
4236 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
4237 handleMSP430InterruptAttr(S, D, Attr);
4239 handleARMInterruptAttr(S, D, Attr);
4242 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4243 const AttributeList &Attr) {
4245 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4246 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4249 D->addAttr(::new (S.Context)
4250 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4252 Attr.getAttributeSpellingListIndex()));
4255 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4256 const AttributeList &Attr) {
4258 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4259 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4262 D->addAttr(::new (S.Context)
4263 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4265 Attr.getAttributeSpellingListIndex()));
4268 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4269 const AttributeList& Attr) {
4270 // If we try to apply it to a function pointer, don't warn, but don't
4271 // do anything, either. It doesn't matter anyway, because there's nothing
4272 // special about calling a force_align_arg_pointer function.
4273 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4274 if (VD && VD->getType()->isFunctionPointerType())
4276 // Also don't warn on function pointer typedefs.
4277 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4278 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4279 TD->getUnderlyingType()->isFunctionType()))
4281 // Attribute can only be applied to function types.
4282 if (!isa<FunctionDecl>(D)) {
4283 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4284 << Attr.getName() << /* function */0;
4288 D->addAttr(::new (S.Context)
4289 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4290 Attr.getAttributeSpellingListIndex()));
4293 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4294 unsigned AttrSpellingListIndex) {
4295 if (D->hasAttr<DLLExportAttr>()) {
4296 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4300 if (D->hasAttr<DLLImportAttr>())
4303 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4306 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4307 unsigned AttrSpellingListIndex) {
4308 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4309 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4310 D->dropAttr<DLLImportAttr>();
4313 if (D->hasAttr<DLLExportAttr>())
4316 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4319 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4320 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4321 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4322 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4327 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4328 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4329 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4330 // MinGW doesn't allow dllimport on inline functions.
4331 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4337 unsigned Index = A.getAttributeSpellingListIndex();
4338 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4339 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4340 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4342 D->addAttr(NewAttr);
4346 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4347 unsigned AttrSpellingListIndex,
4348 MSInheritanceAttr::Spelling SemanticSpelling) {
4349 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4350 if (IA->getSemanticSpelling() == SemanticSpelling)
4352 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4353 << 1 /*previous declaration*/;
4354 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4355 D->dropAttr<MSInheritanceAttr>();
4358 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4359 if (RD->hasDefinition()) {
4360 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4361 SemanticSpelling)) {
4365 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4366 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4367 << 1 /*partial specialization*/;
4370 if (RD->getDescribedClassTemplate()) {
4371 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4372 << 0 /*primary template*/;
4377 return ::new (Context)
4378 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4381 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4382 // The capability attributes take a single string parameter for the name of
4383 // the capability they represent. The lockable attribute does not take any
4384 // parameters. However, semantically, both attributes represent the same
4385 // concept, and so they use the same semantic attribute. Eventually, the
4386 // lockable attribute will be removed.
4388 // For backward compatibility, any capability which has no specified string
4389 // literal will be considered a "mutex."
4390 StringRef N("mutex");
4391 SourceLocation LiteralLoc;
4392 if (Attr.getKind() == AttributeList::AT_Capability &&
4393 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4396 // Currently, there are only two names allowed for a capability: role and
4397 // mutex (case insensitive). Diagnose other capability names.
4398 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4399 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4401 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4402 Attr.getAttributeSpellingListIndex()));
4405 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4406 const AttributeList &Attr) {
4407 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4408 Attr.getArgAsExpr(0),
4409 Attr.getAttributeSpellingListIndex()));
4412 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4413 const AttributeList &Attr) {
4414 SmallVector<Expr*, 1> Args;
4415 if (!checkLockFunAttrCommon(S, D, Attr, Args))
4418 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4420 Args.data(), Args.size(),
4421 Attr.getAttributeSpellingListIndex()));
4424 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4425 const AttributeList &Attr) {
4426 SmallVector<Expr*, 2> Args;
4427 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4430 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4432 Attr.getArgAsExpr(0),
4435 Attr.getAttributeSpellingListIndex()));
4438 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4439 const AttributeList &Attr) {
4440 // Check that all arguments are lockable objects.
4441 SmallVector<Expr *, 1> Args;
4442 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4444 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4445 Attr.getRange(), S.Context, Args.data(), Args.size(),
4446 Attr.getAttributeSpellingListIndex()));
4449 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4450 const AttributeList &Attr) {
4451 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4454 // check that all arguments are lockable objects
4455 SmallVector<Expr*, 1> Args;
4456 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4460 RequiresCapabilityAttr *RCA = ::new (S.Context)
4461 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4462 Args.size(), Attr.getAttributeSpellingListIndex());
4467 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4468 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4469 if (NSD->isAnonymousNamespace()) {
4470 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4471 // Do not want to attach the attribute to the namespace because that will
4472 // cause confusing diagnostic reports for uses of declarations within the
4478 if (!S.getLangOpts().CPlusPlus14)
4479 if (Attr.isCXX11Attribute() &&
4480 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
4481 S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
4483 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4486 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4487 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4490 std::vector<std::string> Sanitizers;
4492 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4493 StringRef SanitizerName;
4494 SourceLocation LiteralLoc;
4496 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
4499 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
4500 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
4502 Sanitizers.push_back(SanitizerName);
4505 D->addAttr(::new (S.Context) NoSanitizeAttr(
4506 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
4507 Attr.getAttributeSpellingListIndex()));
4510 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
4511 const AttributeList &Attr) {
4512 std::string SanitizerName =
4513 llvm::StringSwitch<std::string>(Attr.getName()->getName())
4514 .Case("no_address_safety_analysis", "address")
4515 .Case("no_sanitize_address", "address")
4516 .Case("no_sanitize_thread", "thread")
4517 .Case("no_sanitize_memory", "memory");
4518 D->addAttr(::new (S.Context)
4519 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
4520 Attr.getAttributeSpellingListIndex()));
4523 /// Handles semantic checking for features that are common to all attributes,
4524 /// such as checking whether a parameter was properly specified, or the correct
4525 /// number of arguments were passed, etc.
4526 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4527 const AttributeList &Attr) {
4528 // Several attributes carry different semantics than the parsing requires, so
4529 // those are opted out of the common handling.
4531 // We also bail on unknown and ignored attributes because those are handled
4532 // as part of the target-specific handling logic.
4533 if (Attr.hasCustomParsing() ||
4534 Attr.getKind() == AttributeList::UnknownAttribute)
4537 // Check whether the attribute requires specific language extensions to be
4539 if (!Attr.diagnoseLangOpts(S))
4542 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4543 // If there are no optional arguments, then checking for the argument count
4545 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4548 // There are optional arguments, so checking is slightly more involved.
4549 if (Attr.getMinArgs() &&
4550 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4552 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4553 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4557 // Check whether the attribute appertains to the given subject.
4558 if (!Attr.diagnoseAppertainsTo(S, D))
4564 //===----------------------------------------------------------------------===//
4565 // Top Level Sema Entry Points
4566 //===----------------------------------------------------------------------===//
4568 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4569 /// the attribute applies to decls. If the attribute is a type attribute, just
4570 /// silently ignore it if a GNU attribute.
4571 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4572 const AttributeList &Attr,
4573 bool IncludeCXX11Attributes) {
4574 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4577 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4579 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4582 // Unknown attributes are automatically warned on. Target-specific attributes
4583 // which do not apply to the current target architecture are treated as
4584 // though they were unknown attributes.
4585 if (Attr.getKind() == AttributeList::UnknownAttribute ||
4586 !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4587 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4588 ? diag::warn_unhandled_ms_attribute_ignored
4589 : diag::warn_unknown_attribute_ignored)
4594 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4597 switch (Attr.getKind()) {
4599 // Type attributes are handled elsewhere; silently move on.
4600 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4602 case AttributeList::AT_Interrupt:
4603 handleInterruptAttr(S, D, Attr);
4605 case AttributeList::AT_X86ForceAlignArgPointer:
4606 handleX86ForceAlignArgPointerAttr(S, D, Attr);
4608 case AttributeList::AT_DLLExport:
4609 case AttributeList::AT_DLLImport:
4610 handleDLLAttr(S, D, Attr);
4612 case AttributeList::AT_Mips16:
4613 handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4615 case AttributeList::AT_NoMips16:
4616 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4618 case AttributeList::AT_AMDGPUNumVGPR:
4619 handleAMDGPUNumVGPRAttr(S, D, Attr);
4621 case AttributeList::AT_AMDGPUNumSGPR:
4622 handleAMDGPUNumSGPRAttr(S, D, Attr);
4624 case AttributeList::AT_IBAction:
4625 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4627 case AttributeList::AT_IBOutlet:
4628 handleIBOutlet(S, D, Attr);
4630 case AttributeList::AT_IBOutletCollection:
4631 handleIBOutletCollection(S, D, Attr);
4633 case AttributeList::AT_Alias:
4634 handleAliasAttr(S, D, Attr);
4636 case AttributeList::AT_Aligned:
4637 handleAlignedAttr(S, D, Attr);
4639 case AttributeList::AT_AlignValue:
4640 handleAlignValueAttr(S, D, Attr);
4642 case AttributeList::AT_AlwaysInline:
4643 handleAlwaysInlineAttr(S, D, Attr);
4645 case AttributeList::AT_AnalyzerNoReturn:
4646 handleAnalyzerNoReturnAttr(S, D, Attr);
4648 case AttributeList::AT_TLSModel:
4649 handleTLSModelAttr(S, D, Attr);
4651 case AttributeList::AT_Annotate:
4652 handleAnnotateAttr(S, D, Attr);
4654 case AttributeList::AT_Availability:
4655 handleAvailabilityAttr(S, D, Attr);
4657 case AttributeList::AT_CarriesDependency:
4658 handleDependencyAttr(S, scope, D, Attr);
4660 case AttributeList::AT_Common:
4661 handleCommonAttr(S, D, Attr);
4663 case AttributeList::AT_CUDAConstant:
4664 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4666 case AttributeList::AT_Constructor:
4667 handleConstructorAttr(S, D, Attr);
4669 case AttributeList::AT_CXX11NoReturn:
4670 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4672 case AttributeList::AT_Deprecated:
4673 handleDeprecatedAttr(S, D, Attr);
4675 case AttributeList::AT_Destructor:
4676 handleDestructorAttr(S, D, Attr);
4678 case AttributeList::AT_EnableIf:
4679 handleEnableIfAttr(S, D, Attr);
4681 case AttributeList::AT_ExtVectorType:
4682 handleExtVectorTypeAttr(S, scope, D, Attr);
4684 case AttributeList::AT_MinSize:
4685 handleMinSizeAttr(S, D, Attr);
4687 case AttributeList::AT_OptimizeNone:
4688 handleOptimizeNoneAttr(S, D, Attr);
4690 case AttributeList::AT_FlagEnum:
4691 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
4693 case AttributeList::AT_Flatten:
4694 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
4696 case AttributeList::AT_Format:
4697 handleFormatAttr(S, D, Attr);
4699 case AttributeList::AT_FormatArg:
4700 handleFormatArgAttr(S, D, Attr);
4702 case AttributeList::AT_CUDAGlobal:
4703 handleGlobalAttr(S, D, Attr);
4705 case AttributeList::AT_CUDADevice:
4706 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4708 case AttributeList::AT_CUDAHost:
4709 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4711 case AttributeList::AT_GNUInline:
4712 handleGNUInlineAttr(S, D, Attr);
4714 case AttributeList::AT_CUDALaunchBounds:
4715 handleLaunchBoundsAttr(S, D, Attr);
4717 case AttributeList::AT_Restrict:
4718 handleRestrictAttr(S, D, Attr);
4720 case AttributeList::AT_MayAlias:
4721 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4723 case AttributeList::AT_Mode:
4724 handleModeAttr(S, D, Attr);
4726 case AttributeList::AT_NoCommon:
4727 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4729 case AttributeList::AT_NoSplitStack:
4730 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
4732 case AttributeList::AT_NonNull:
4733 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4734 handleNonNullAttrParameter(S, PVD, Attr);
4736 handleNonNullAttr(S, D, Attr);
4738 case AttributeList::AT_ReturnsNonNull:
4739 handleReturnsNonNullAttr(S, D, Attr);
4741 case AttributeList::AT_AssumeAligned:
4742 handleAssumeAlignedAttr(S, D, Attr);
4744 case AttributeList::AT_Overloadable:
4745 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4747 case AttributeList::AT_Ownership:
4748 handleOwnershipAttr(S, D, Attr);
4750 case AttributeList::AT_Cold:
4751 handleColdAttr(S, D, Attr);
4753 case AttributeList::AT_Hot:
4754 handleHotAttr(S, D, Attr);
4756 case AttributeList::AT_Naked:
4757 handleSimpleAttribute<NakedAttr>(S, D, Attr);
4759 case AttributeList::AT_NoReturn:
4760 handleNoReturnAttr(S, D, Attr);
4762 case AttributeList::AT_NoThrow:
4763 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4765 case AttributeList::AT_CUDAShared:
4766 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4768 case AttributeList::AT_VecReturn:
4769 handleVecReturnAttr(S, D, Attr);
4772 case AttributeList::AT_ObjCOwnership:
4773 handleObjCOwnershipAttr(S, D, Attr);
4775 case AttributeList::AT_ObjCPreciseLifetime:
4776 handleObjCPreciseLifetimeAttr(S, D, Attr);
4779 case AttributeList::AT_ObjCReturnsInnerPointer:
4780 handleObjCReturnsInnerPointerAttr(S, D, Attr);
4783 case AttributeList::AT_ObjCRequiresSuper:
4784 handleObjCRequiresSuperAttr(S, D, Attr);
4787 case AttributeList::AT_ObjCBridge:
4788 handleObjCBridgeAttr(S, scope, D, Attr);
4791 case AttributeList::AT_ObjCBridgeMutable:
4792 handleObjCBridgeMutableAttr(S, scope, D, Attr);
4795 case AttributeList::AT_ObjCBridgeRelated:
4796 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4799 case AttributeList::AT_ObjCDesignatedInitializer:
4800 handleObjCDesignatedInitializer(S, D, Attr);
4803 case AttributeList::AT_ObjCRuntimeName:
4804 handleObjCRuntimeName(S, D, Attr);
4807 case AttributeList::AT_ObjCBoxable:
4808 handleObjCBoxable(S, D, Attr);
4811 case AttributeList::AT_CFAuditedTransfer:
4812 handleCFAuditedTransferAttr(S, D, Attr);
4814 case AttributeList::AT_CFUnknownTransfer:
4815 handleCFUnknownTransferAttr(S, D, Attr);
4818 case AttributeList::AT_CFConsumed:
4819 case AttributeList::AT_NSConsumed:
4820 handleNSConsumedAttr(S, D, Attr);
4822 case AttributeList::AT_NSConsumesSelf:
4823 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4826 case AttributeList::AT_NSReturnsAutoreleased:
4827 case AttributeList::AT_NSReturnsNotRetained:
4828 case AttributeList::AT_CFReturnsNotRetained:
4829 case AttributeList::AT_NSReturnsRetained:
4830 case AttributeList::AT_CFReturnsRetained:
4831 handleNSReturnsRetainedAttr(S, D, Attr);
4833 case AttributeList::AT_WorkGroupSizeHint:
4834 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4836 case AttributeList::AT_ReqdWorkGroupSize:
4837 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4839 case AttributeList::AT_VecTypeHint:
4840 handleVecTypeHint(S, D, Attr);
4843 case AttributeList::AT_InitPriority:
4844 handleInitPriorityAttr(S, D, Attr);
4847 case AttributeList::AT_Packed:
4848 handlePackedAttr(S, D, Attr);
4850 case AttributeList::AT_Section:
4851 handleSectionAttr(S, D, Attr);
4853 case AttributeList::AT_Target:
4854 handleTargetAttr(S, D, Attr);
4856 case AttributeList::AT_Unavailable:
4857 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4859 case AttributeList::AT_ArcWeakrefUnavailable:
4860 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4862 case AttributeList::AT_ObjCRootClass:
4863 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4865 case AttributeList::AT_ObjCExplicitProtocolImpl:
4866 handleObjCSuppresProtocolAttr(S, D, Attr);
4868 case AttributeList::AT_ObjCRequiresPropertyDefs:
4869 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4871 case AttributeList::AT_Unused:
4872 handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4874 case AttributeList::AT_ReturnsTwice:
4875 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4877 case AttributeList::AT_Used:
4878 handleUsedAttr(S, D, Attr);
4880 case AttributeList::AT_Visibility:
4881 handleVisibilityAttr(S, D, Attr, false);
4883 case AttributeList::AT_TypeVisibility:
4884 handleVisibilityAttr(S, D, Attr, true);
4886 case AttributeList::AT_WarnUnused:
4887 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4889 case AttributeList::AT_WarnUnusedResult:
4890 handleWarnUnusedResult(S, D, Attr);
4892 case AttributeList::AT_Weak:
4893 handleSimpleAttribute<WeakAttr>(S, D, Attr);
4895 case AttributeList::AT_WeakRef:
4896 handleWeakRefAttr(S, D, Attr);
4898 case AttributeList::AT_WeakImport:
4899 handleWeakImportAttr(S, D, Attr);
4901 case AttributeList::AT_TransparentUnion:
4902 handleTransparentUnionAttr(S, D, Attr);
4904 case AttributeList::AT_ObjCException:
4905 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4907 case AttributeList::AT_ObjCMethodFamily:
4908 handleObjCMethodFamilyAttr(S, D, Attr);
4910 case AttributeList::AT_ObjCNSObject:
4911 handleObjCNSObject(S, D, Attr);
4913 case AttributeList::AT_ObjCIndependentClass:
4914 handleObjCIndependentClass(S, D, Attr);
4916 case AttributeList::AT_Blocks:
4917 handleBlocksAttr(S, D, Attr);
4919 case AttributeList::AT_Sentinel:
4920 handleSentinelAttr(S, D, Attr);
4922 case AttributeList::AT_Const:
4923 handleSimpleAttribute<ConstAttr>(S, D, Attr);
4925 case AttributeList::AT_Pure:
4926 handleSimpleAttribute<PureAttr>(S, D, Attr);
4928 case AttributeList::AT_Cleanup:
4929 handleCleanupAttr(S, D, Attr);
4931 case AttributeList::AT_NoDebug:
4932 handleNoDebugAttr(S, D, Attr);
4934 case AttributeList::AT_NoDuplicate:
4935 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4937 case AttributeList::AT_NoInline:
4938 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4940 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4941 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4943 case AttributeList::AT_StdCall:
4944 case AttributeList::AT_CDecl:
4945 case AttributeList::AT_FastCall:
4946 case AttributeList::AT_ThisCall:
4947 case AttributeList::AT_Pascal:
4948 case AttributeList::AT_VectorCall:
4949 case AttributeList::AT_MSABI:
4950 case AttributeList::AT_SysVABI:
4951 case AttributeList::AT_Pcs:
4952 case AttributeList::AT_IntelOclBicc:
4953 handleCallConvAttr(S, D, Attr);
4955 case AttributeList::AT_OpenCLKernel:
4956 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4958 case AttributeList::AT_OpenCLImageAccess:
4959 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4962 // Microsoft attributes:
4963 case AttributeList::AT_MSNoVTable:
4964 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
4966 case AttributeList::AT_MSStruct:
4967 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
4969 case AttributeList::AT_Uuid:
4970 handleUuidAttr(S, D, Attr);
4972 case AttributeList::AT_MSInheritance:
4973 handleMSInheritanceAttr(S, D, Attr);
4975 case AttributeList::AT_SelectAny:
4976 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4978 case AttributeList::AT_Thread:
4979 handleDeclspecThreadAttr(S, D, Attr);
4982 // Thread safety attributes:
4983 case AttributeList::AT_AssertExclusiveLock:
4984 handleAssertExclusiveLockAttr(S, D, Attr);
4986 case AttributeList::AT_AssertSharedLock:
4987 handleAssertSharedLockAttr(S, D, Attr);
4989 case AttributeList::AT_GuardedVar:
4990 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4992 case AttributeList::AT_PtGuardedVar:
4993 handlePtGuardedVarAttr(S, D, Attr);
4995 case AttributeList::AT_ScopedLockable:
4996 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4998 case AttributeList::AT_NoSanitize:
4999 handleNoSanitizeAttr(S, D, Attr);
5001 case AttributeList::AT_NoSanitizeSpecific:
5002 handleNoSanitizeSpecificAttr(S, D, Attr);
5004 case AttributeList::AT_NoThreadSafetyAnalysis:
5005 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
5007 case AttributeList::AT_GuardedBy:
5008 handleGuardedByAttr(S, D, Attr);
5010 case AttributeList::AT_PtGuardedBy:
5011 handlePtGuardedByAttr(S, D, Attr);
5013 case AttributeList::AT_ExclusiveTrylockFunction:
5014 handleExclusiveTrylockFunctionAttr(S, D, Attr);
5016 case AttributeList::AT_LockReturned:
5017 handleLockReturnedAttr(S, D, Attr);
5019 case AttributeList::AT_LocksExcluded:
5020 handleLocksExcludedAttr(S, D, Attr);
5022 case AttributeList::AT_SharedTrylockFunction:
5023 handleSharedTrylockFunctionAttr(S, D, Attr);
5025 case AttributeList::AT_AcquiredBefore:
5026 handleAcquiredBeforeAttr(S, D, Attr);
5028 case AttributeList::AT_AcquiredAfter:
5029 handleAcquiredAfterAttr(S, D, Attr);
5032 // Capability analysis attributes.
5033 case AttributeList::AT_Capability:
5034 case AttributeList::AT_Lockable:
5035 handleCapabilityAttr(S, D, Attr);
5037 case AttributeList::AT_RequiresCapability:
5038 handleRequiresCapabilityAttr(S, D, Attr);
5041 case AttributeList::AT_AssertCapability:
5042 handleAssertCapabilityAttr(S, D, Attr);
5044 case AttributeList::AT_AcquireCapability:
5045 handleAcquireCapabilityAttr(S, D, Attr);
5047 case AttributeList::AT_ReleaseCapability:
5048 handleReleaseCapabilityAttr(S, D, Attr);
5050 case AttributeList::AT_TryAcquireCapability:
5051 handleTryAcquireCapabilityAttr(S, D, Attr);
5054 // Consumed analysis attributes.
5055 case AttributeList::AT_Consumable:
5056 handleConsumableAttr(S, D, Attr);
5058 case AttributeList::AT_ConsumableAutoCast:
5059 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5061 case AttributeList::AT_ConsumableSetOnRead:
5062 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5064 case AttributeList::AT_CallableWhen:
5065 handleCallableWhenAttr(S, D, Attr);
5067 case AttributeList::AT_ParamTypestate:
5068 handleParamTypestateAttr(S, D, Attr);
5070 case AttributeList::AT_ReturnTypestate:
5071 handleReturnTypestateAttr(S, D, Attr);
5073 case AttributeList::AT_SetTypestate:
5074 handleSetTypestateAttr(S, D, Attr);
5076 case AttributeList::AT_TestTypestate:
5077 handleTestTypestateAttr(S, D, Attr);
5080 // Type safety attributes.
5081 case AttributeList::AT_ArgumentWithTypeTag:
5082 handleArgumentWithTypeTagAttr(S, D, Attr);
5084 case AttributeList::AT_TypeTagForDatatype:
5085 handleTypeTagForDatatypeAttr(S, D, Attr);
5090 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5091 /// attribute list to the specified decl, ignoring any type attributes.
5092 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5093 const AttributeList *AttrList,
5094 bool IncludeCXX11Attributes) {
5095 for (const AttributeList* l = AttrList; l; l = l->getNext())
5096 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
5098 // FIXME: We should be able to handle these cases in TableGen.
5100 // static int a9 __attribute__((weakref));
5101 // but that looks really pointless. We reject it.
5102 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5103 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5104 << cast<NamedDecl>(D);
5105 D->dropAttr<WeakRefAttr>();
5109 // FIXME: We should be able to handle this in TableGen as well. It would be
5110 // good to have a way to specify "these attributes must appear as a group",
5111 // for these. Additionally, it would be good to have a way to specify "these
5112 // attribute must never appear as a group" for attributes like cold and hot.
5113 if (!D->hasAttr<OpenCLKernelAttr>()) {
5114 // These attributes cannot be applied to a non-kernel function.
5115 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
5116 // FIXME: This emits a different error message than
5117 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
5118 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5119 D->setInvalidDecl();
5120 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
5121 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5122 D->setInvalidDecl();
5123 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
5124 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5125 D->setInvalidDecl();
5126 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5127 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5128 << A << ExpectedKernelFunction;
5129 D->setInvalidDecl();
5130 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5131 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5132 << A << ExpectedKernelFunction;
5133 D->setInvalidDecl();
5138 // Annotation attributes are the only attributes allowed after an access
5140 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5141 const AttributeList *AttrList) {
5142 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5143 if (l->getKind() == AttributeList::AT_Annotate) {
5144 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
5146 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5154 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5155 /// contains any decl attributes that we should warn about.
5156 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5157 for ( ; A; A = A->getNext()) {
5158 // Only warn if the attribute is an unignored, non-type attribute.
5159 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5160 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5162 if (A->getKind() == AttributeList::UnknownAttribute) {
5163 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5164 << A->getName() << A->getRange();
5166 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5167 << A->getName() << A->getRange();
5172 /// checkUnusedDeclAttributes - Given a declarator which is not being
5173 /// used to build a declaration, complain about any decl attributes
5174 /// which might be lying around on it.
5175 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5176 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5177 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5178 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5179 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5182 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5183 /// \#pragma weak needs a non-definition decl and source may not have one.
5184 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5185 SourceLocation Loc) {
5186 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5187 NamedDecl *NewD = nullptr;
5188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5189 FunctionDecl *NewFD;
5190 // FIXME: Missing call to CheckFunctionDeclaration().
5192 // FIXME: Is the qualifier info correct?
5193 // FIXME: Is the DeclContext correct?
5194 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5195 Loc, Loc, DeclarationName(II),
5196 FD->getType(), FD->getTypeSourceInfo(),
5197 SC_None, false/*isInlineSpecified*/,
5199 false/*isConstexprSpecified*/);
5202 if (FD->getQualifier())
5203 NewFD->setQualifierInfo(FD->getQualifierLoc());
5205 // Fake up parameter variables; they are declared as if this were
5207 QualType FDTy = FD->getType();
5208 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5209 SmallVector<ParmVarDecl*, 16> Params;
5210 for (const auto &AI : FT->param_types()) {
5211 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
5212 Param->setScopeInfo(0, Params.size());
5213 Params.push_back(Param);
5215 NewFD->setParams(Params);
5217 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5218 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5219 VD->getInnerLocStart(), VD->getLocation(), II,
5220 VD->getType(), VD->getTypeSourceInfo(),
5221 VD->getStorageClass());
5222 if (VD->getQualifier()) {
5223 VarDecl *NewVD = cast<VarDecl>(NewD);
5224 NewVD->setQualifierInfo(VD->getQualifierLoc());
5230 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5231 /// applied to it, possibly with an alias.
5232 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5233 if (W.getUsed()) return; // only do this once
5235 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5236 IdentifierInfo *NDId = ND->getIdentifier();
5237 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5238 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5240 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5241 WeakTopLevelDecl.push_back(NewD);
5242 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5243 // to insert Decl at TU scope, sorry.
5244 DeclContext *SavedContext = CurContext;
5245 CurContext = Context.getTranslationUnitDecl();
5246 NewD->setDeclContext(CurContext);
5247 NewD->setLexicalDeclContext(CurContext);
5248 PushOnScopeChains(NewD, S);
5249 CurContext = SavedContext;
5250 } else { // just add weak to existing
5251 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5255 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5256 // It's valid to "forward-declare" #pragma weak, in which case we
5258 LoadExternalWeakUndeclaredIdentifiers();
5259 if (!WeakUndeclaredIdentifiers.empty()) {
5260 NamedDecl *ND = nullptr;
5261 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5262 if (VD->isExternC())
5264 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5265 if (FD->isExternC())
5268 if (IdentifierInfo *Id = ND->getIdentifier()) {
5269 auto I = WeakUndeclaredIdentifiers.find(Id);
5270 if (I != WeakUndeclaredIdentifiers.end()) {
5271 WeakInfo W = I->second;
5272 DeclApplyPragmaWeak(S, ND, W);
5273 WeakUndeclaredIdentifiers[Id] = W;
5280 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5281 /// it, apply them to D. This is a bit tricky because PD can have attributes
5282 /// specified in many different places, and we need to find and apply them all.
5283 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5284 // Apply decl attributes from the DeclSpec if present.
5285 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5286 ProcessDeclAttributeList(S, D, Attrs);
5288 // Walk the declarator structure, applying decl attributes that were in a type
5289 // position to the decl itself. This handles cases like:
5290 // int *__attr__(x)** D;
5291 // when X is a decl attribute.
5292 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5293 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5294 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5296 // Finally, apply any attributes on the decl itself.
5297 if (const AttributeList *Attrs = PD.getAttributes())
5298 ProcessDeclAttributeList(S, D, Attrs);
5301 /// Is the given declaration allowed to use a forbidden type?
5302 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5303 // Private ivars are always okay. Unfortunately, people don't
5304 // always properly make their ivars private, even in system headers.
5305 // Plus we need to make fields okay, too.
5306 // Function declarations in sys headers will be marked unavailable.
5307 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5308 !isa<FunctionDecl>(decl))
5311 // Require it to be declared in a system header.
5312 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5315 /// Handle a delayed forbidden-type diagnostic.
5316 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5318 if (decl && isForbiddenTypeAllowed(S, decl)) {
5319 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
5320 "this system declaration uses an unsupported type",
5324 if (S.getLangOpts().ObjCAutoRefCount)
5325 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5326 // FIXME: we may want to suppress diagnostics for all
5327 // kind of forbidden type messages on unavailable functions.
5328 if (FD->hasAttr<UnavailableAttr>() &&
5329 diag.getForbiddenTypeDiagnostic() ==
5330 diag::err_arc_array_param_no_ownership) {
5331 diag.Triggered = true;
5336 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5337 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5338 diag.Triggered = true;
5342 static bool isDeclDeprecated(Decl *D) {
5344 if (D->isDeprecated())
5346 // A category implicitly has the availability of the interface.
5347 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5348 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5349 return Interface->isDeprecated();
5350 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5354 static bool isDeclUnavailable(Decl *D) {
5356 if (D->isUnavailable())
5358 // A category implicitly has the availability of the interface.
5359 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5360 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5361 return Interface->isUnavailable();
5362 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5366 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
5367 Decl *Ctx, const NamedDecl *D,
5368 StringRef Message, SourceLocation Loc,
5369 const ObjCInterfaceDecl *UnknownObjCClass,
5370 const ObjCPropertyDecl *ObjCProperty,
5371 bool ObjCPropertyAccess) {
5372 // Diagnostics for deprecated or unavailable.
5373 unsigned diag, diag_message, diag_fwdclass_message;
5375 // Matches 'diag::note_property_attribute' options.
5376 unsigned property_note_select;
5378 // Matches diag::note_availability_specified_here.
5379 unsigned available_here_select_kind;
5381 // Don't warn if our current context is deprecated or unavailable.
5383 case Sema::AD_Deprecation:
5384 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
5386 diag = !ObjCPropertyAccess ? diag::warn_deprecated
5387 : diag::warn_property_method_deprecated;
5388 diag_message = diag::warn_deprecated_message;
5389 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5390 property_note_select = /* deprecated */ 0;
5391 available_here_select_kind = /* deprecated */ 2;
5394 case Sema::AD_Unavailable:
5395 if (isDeclUnavailable(Ctx))
5397 diag = !ObjCPropertyAccess ? diag::err_unavailable
5398 : diag::err_property_method_unavailable;
5399 diag_message = diag::err_unavailable_message;
5400 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5401 property_note_select = /* unavailable */ 1;
5402 available_here_select_kind = /* unavailable */ 0;
5405 case Sema::AD_Partial:
5406 diag = diag::warn_partial_availability;
5407 diag_message = diag::warn_partial_message;
5408 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
5409 property_note_select = /* partial */ 2;
5410 available_here_select_kind = /* partial */ 3;
5414 if (!Message.empty()) {
5415 S.Diag(Loc, diag_message) << D << Message;
5417 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5418 << ObjCProperty->getDeclName() << property_note_select;
5419 } else if (!UnknownObjCClass) {
5420 S.Diag(Loc, diag) << D;
5422 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5423 << ObjCProperty->getDeclName() << property_note_select;
5425 S.Diag(Loc, diag_fwdclass_message) << D;
5426 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5429 S.Diag(D->getLocation(), diag::note_availability_specified_here)
5430 << D << available_here_select_kind;
5431 if (K == Sema::AD_Partial)
5432 S.Diag(Loc, diag::note_partial_availability_silence) << D;
5435 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5437 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
5438 DD.Kind == DelayedDiagnostic::Unavailable);
5439 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
5440 ? Sema::AD_Deprecation
5441 : Sema::AD_Unavailable;
5442 DD.Triggered = true;
5443 DoEmitAvailabilityWarning(
5444 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
5445 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
5448 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5449 assert(DelayedDiagnostics.getCurrentPool());
5450 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5451 DelayedDiagnostics.popWithoutEmitting(state);
5453 // When delaying diagnostics to run in the context of a parsed
5454 // declaration, we only want to actually emit anything if parsing
5458 // We emit all the active diagnostics in this pool or any of its
5459 // parents. In general, we'll get one pool for the decl spec
5460 // and a child pool for each declarator; in a decl group like:
5461 // deprecated_typedef foo, *bar, baz();
5462 // only the declarator pops will be passed decls. This is correct;
5463 // we really do need to consider delayed diagnostics from the decl spec
5464 // for each of the different declarations.
5465 const DelayedDiagnosticPool *pool = &poppedPool;
5467 for (DelayedDiagnosticPool::pool_iterator
5468 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5469 // This const_cast is a bit lame. Really, Triggered should be mutable.
5470 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5474 switch (diag.Kind) {
5475 case DelayedDiagnostic::Deprecation:
5476 case DelayedDiagnostic::Unavailable:
5477 // Don't bother giving deprecation/unavailable diagnostics if
5478 // the decl is invalid.
5479 if (!decl->isInvalidDecl())
5480 handleDelayedAvailabilityCheck(*this, diag, decl);
5483 case DelayedDiagnostic::Access:
5484 HandleDelayedAccessCheck(diag, decl);
5487 case DelayedDiagnostic::ForbiddenType:
5488 handleDelayedForbiddenType(*this, diag, decl);
5492 } while ((pool = pool->getParent()));
5495 /// Given a set of delayed diagnostics, re-emit them as if they had
5496 /// been delayed in the current context instead of in the given pool.
5497 /// Essentially, this just moves them to the current pool.
5498 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5499 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5500 assert(curPool && "re-emitting in undelayed context not supported");
5501 curPool->steal(pool);
5504 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5505 NamedDecl *D, StringRef Message,
5507 const ObjCInterfaceDecl *UnknownObjCClass,
5508 const ObjCPropertyDecl *ObjCProperty,
5509 bool ObjCPropertyAccess) {
5510 // Delay if we're currently parsing a declaration.
5511 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
5512 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5513 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5514 ObjCPropertyAccess));
5518 Decl *Ctx = cast<Decl>(getCurLexicalContext());
5519 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
5520 ObjCProperty, ObjCPropertyAccess);