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/Basic/CharInfo.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Scope.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/MathExtras.h"
33 using namespace clang;
36 namespace AttributeLangSupport {
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// isFunctionOrMethod - Return true if the given decl has function
49 /// type (function or function-typed variable) or an Objective-C
51 static bool isFunctionOrMethod(const Decl *D) {
52 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
55 /// Return true if the given decl has a declarator that should have
56 /// been processed by Sema::GetTypeForDeclarator.
57 static bool hasDeclarator(const Decl *D) {
58 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
59 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
60 isa<ObjCPropertyDecl>(D);
63 /// hasFunctionProto - Return true if the given decl has a argument
64 /// information. This decl should have already passed
65 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
66 static bool hasFunctionProto(const Decl *D) {
67 if (const FunctionType *FnTy = D->getFunctionType())
68 return isa<FunctionProtoType>(FnTy);
69 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
72 /// getFunctionOrMethodNumParams - Return number of function or method
73 /// parameters. It is an error to call this on a K&R function (use
74 /// hasFunctionProto first).
75 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
76 if (const FunctionType *FnTy = D->getFunctionType())
77 return cast<FunctionProtoType>(FnTy)->getNumParams();
78 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
79 return BD->getNumParams();
80 return cast<ObjCMethodDecl>(D)->param_size();
83 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
84 if (const FunctionType *FnTy = D->getFunctionType())
85 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
86 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
87 return BD->getParamDecl(Idx)->getType();
89 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
92 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
93 if (const auto *FD = dyn_cast<FunctionDecl>(D))
94 return FD->getParamDecl(Idx)->getSourceRange();
95 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
96 return MD->parameters()[Idx]->getSourceRange();
97 if (const auto *BD = dyn_cast<BlockDecl>(D))
98 return BD->getParamDecl(Idx)->getSourceRange();
102 static QualType getFunctionOrMethodResultType(const Decl *D) {
103 if (const FunctionType *FnTy = D->getFunctionType())
104 return cast<FunctionType>(FnTy)->getReturnType();
105 return cast<ObjCMethodDecl>(D)->getReturnType();
108 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
109 if (const auto *FD = dyn_cast<FunctionDecl>(D))
110 return FD->getReturnTypeSourceRange();
111 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
112 return MD->getReturnTypeSourceRange();
113 return SourceRange();
116 static bool isFunctionOrMethodVariadic(const Decl *D) {
117 if (const FunctionType *FnTy = D->getFunctionType()) {
118 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
119 return proto->isVariadic();
121 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
122 return BD->isVariadic();
124 return cast<ObjCMethodDecl>(D)->isVariadic();
127 static bool isInstanceMethod(const Decl *D) {
128 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
129 return MethodDecl->isInstance();
133 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
134 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
138 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
142 IdentifierInfo* ClsName = Cls->getIdentifier();
144 // FIXME: Should we walk the chain of classes?
145 return ClsName == &Ctx.Idents.get("NSString") ||
146 ClsName == &Ctx.Idents.get("NSMutableString");
149 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
150 const PointerType *PT = T->getAs<PointerType>();
154 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
158 const RecordDecl *RD = RT->getDecl();
159 if (RD->getTagKind() != TTK_Struct)
162 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
165 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
166 // FIXME: Include the type in the argument list.
167 return Attr.getNumArgs() + Attr.hasParsedType();
170 template <typename Compare>
171 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
172 unsigned Num, unsigned Diag,
174 if (Comp(getNumAttributeArgs(Attr), Num)) {
175 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
182 /// \brief Check if the attribute has exactly as many args as Num. May
184 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
186 return checkAttributeNumArgsImpl(S, Attr, Num,
187 diag::err_attribute_wrong_number_arguments,
188 std::not_equal_to<unsigned>());
191 /// \brief Check if the attribute has at least as many args as Num. May
193 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
195 return checkAttributeNumArgsImpl(S, Attr, Num,
196 diag::err_attribute_too_few_arguments,
197 std::less<unsigned>());
200 /// \brief Check if the attribute has at most as many args as Num. May
202 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
204 return checkAttributeNumArgsImpl(S, Attr, Num,
205 diag::err_attribute_too_many_arguments,
206 std::greater<unsigned>());
209 /// \brief If Expr is a valid integer constant, get the value of the integer
210 /// expression and return success or failure. May output an error.
211 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
212 const Expr *Expr, uint32_t &Val,
213 unsigned Idx = UINT_MAX) {
215 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
216 !Expr->isIntegerConstantExpr(I, S.Context)) {
218 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
219 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
220 << Expr->getSourceRange();
222 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
223 << Attr.getName() << AANT_ArgumentIntegerConstant
224 << Expr->getSourceRange();
229 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
230 << I.toString(10, false) << 32 << /* Unsigned */ 1;
234 Val = (uint32_t)I.getZExtValue();
238 /// \brief Diagnose mutually exclusive attributes when present on a given
239 /// declaration. Returns true if diagnosed.
240 template <typename AttrTy>
241 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
242 const AttributeList &Attr) {
243 if (AttrTy *A = D->getAttr<AttrTy>()) {
244 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
245 << Attr.getName() << A;
251 /// \brief Check if IdxExpr is a valid parameter index for a function or
252 /// instance method D. May output an error.
254 /// \returns true if IdxExpr is a valid index.
255 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
256 const AttributeList &Attr,
260 assert(isFunctionOrMethod(D));
262 // In C++ the implicit 'this' function parameter also counts.
263 // Parameters are counted from one.
264 bool HP = hasFunctionProto(D);
265 bool HasImplicitThisParam = isInstanceMethod(D);
266 bool IV = HP && isFunctionOrMethodVariadic(D);
268 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
271 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
272 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
273 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
274 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
275 << IdxExpr->getSourceRange();
279 Idx = IdxInt.getLimitedValue();
280 if (Idx < 1 || (!IV && Idx > NumParams)) {
281 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
282 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
285 Idx--; // Convert to zero-based.
286 if (HasImplicitThisParam) {
288 S.Diag(Attr.getLoc(),
289 diag::err_attribute_invalid_implicit_this_argument)
290 << Attr.getName() << IdxExpr->getSourceRange();
299 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
300 /// If not emit an error and return false. If the argument is an identifier it
301 /// will emit an error with a fixit hint and treat it as if it was a string
303 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
304 unsigned ArgNum, StringRef &Str,
305 SourceLocation *ArgLocation) {
306 // Look for identifiers. If we have one emit a hint to fix it to a literal.
307 if (Attr.isArgIdent(ArgNum)) {
308 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
309 Diag(Loc->Loc, diag::err_attribute_argument_type)
310 << Attr.getName() << AANT_ArgumentString
311 << FixItHint::CreateInsertion(Loc->Loc, "\"")
312 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
313 Str = Loc->Ident->getName();
315 *ArgLocation = Loc->Loc;
319 // Now check for an actual string literal.
320 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
321 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
323 *ArgLocation = ArgExpr->getLocStart();
325 if (!Literal || !Literal->isAscii()) {
326 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
327 << Attr.getName() << AANT_ArgumentString;
331 Str = Literal->getString();
335 /// \brief Applies the given attribute to the Decl without performing any
336 /// additional semantic checking.
337 template <typename AttrType>
338 static void handleSimpleAttribute(Sema &S, Decl *D,
339 const AttributeList &Attr) {
340 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
341 Attr.getAttributeSpellingListIndex()));
344 /// \brief Check if the passed-in expression is of type int or bool.
345 static bool isIntOrBool(Expr *Exp) {
346 QualType QT = Exp->getType();
347 return QT->isBooleanType() || QT->isIntegerType();
351 // Check to see if the type is a smart pointer of some kind. We assume
352 // it's a smart pointer if it defines both operator-> and operator*.
353 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
354 DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
355 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
359 DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
360 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
367 /// \brief Check if passed in Decl is a pointer type.
368 /// Note that this function may produce an error message.
369 /// \return true if the Decl is a pointer type; false otherwise
370 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
371 const AttributeList &Attr) {
372 const ValueDecl *vd = cast<ValueDecl>(D);
373 QualType QT = vd->getType();
374 if (QT->isAnyPointerType())
377 if (const RecordType *RT = QT->getAs<RecordType>()) {
378 // If it's an incomplete type, it could be a smart pointer; skip it.
379 // (We don't want to force template instantiation if we can avoid it,
380 // since that would alter the order in which templates are instantiated.)
381 if (RT->isIncompleteType())
384 if (threadSafetyCheckIsSmartPointer(S, RT))
388 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
389 << Attr.getName() << QT;
393 /// \brief Checks that the passed in QualType either is of RecordType or points
394 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
395 static const RecordType *getRecordType(QualType QT) {
396 if (const RecordType *RT = QT->getAs<RecordType>())
399 // Now check if we point to record type.
400 if (const PointerType *PT = QT->getAs<PointerType>())
401 return PT->getPointeeType()->getAs<RecordType>();
406 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
407 const RecordType *RT = getRecordType(Ty);
412 // Don't check for the capability if the class hasn't been defined yet.
413 if (RT->isIncompleteType())
416 // Allow smart pointers to be used as capability objects.
417 // FIXME -- Check the type that the smart pointer points to.
418 if (threadSafetyCheckIsSmartPointer(S, RT))
421 // Check if the record itself has a capability.
422 RecordDecl *RD = RT->getDecl();
423 if (RD->hasAttr<CapabilityAttr>())
426 // Else check if any base classes have a capability.
427 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
428 CXXBasePaths BPaths(false, false);
429 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
431 return BS->getType()->getAs<RecordType>()
432 ->getDecl()->hasAttr<CapabilityAttr>();
439 static bool checkTypedefTypeForCapability(QualType Ty) {
440 const auto *TD = Ty->getAs<TypedefType>();
444 TypedefNameDecl *TN = TD->getDecl();
448 return TN->hasAttr<CapabilityAttr>();
451 static bool typeHasCapability(Sema &S, QualType Ty) {
452 if (checkTypedefTypeForCapability(Ty))
455 if (checkRecordTypeForCapability(S, Ty))
461 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
462 // Capability expressions are simple expressions involving the boolean logic
463 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
464 // a DeclRefExpr is found, its type should be checked to determine whether it
465 // is a capability or not.
467 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
468 return typeHasCapability(S, E->getType());
469 else if (const auto *E = dyn_cast<CastExpr>(Ex))
470 return isCapabilityExpr(S, E->getSubExpr());
471 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
472 return isCapabilityExpr(S, E->getSubExpr());
473 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
474 if (E->getOpcode() == UO_LNot)
475 return isCapabilityExpr(S, E->getSubExpr());
477 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
478 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
479 return isCapabilityExpr(S, E->getLHS()) &&
480 isCapabilityExpr(S, E->getRHS());
487 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
488 /// a capability object.
489 /// \param Sidx The attribute argument index to start checking with.
490 /// \param ParamIdxOk Whether an argument can be indexing into a function
492 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
493 const AttributeList &Attr,
494 SmallVectorImpl<Expr *> &Args,
496 bool ParamIdxOk = false) {
497 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
498 Expr *ArgExp = Attr.getArgAsExpr(Idx);
500 if (ArgExp->isTypeDependent()) {
501 // FIXME -- need to check this again on template instantiation
502 Args.push_back(ArgExp);
506 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
507 if (StrLit->getLength() == 0 ||
508 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
509 // Pass empty strings to the analyzer without warnings.
510 // Treat "*" as the universal lock.
511 Args.push_back(ArgExp);
515 // We allow constant strings to be used as a placeholder for expressions
516 // that are not valid C++ syntax, but warn that they are ignored.
517 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
519 Args.push_back(ArgExp);
523 QualType ArgTy = ArgExp->getType();
525 // A pointer to member expression of the form &MyClass::mu is treated
526 // specially -- we need to look at the type of the member.
527 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
528 if (UOp->getOpcode() == UO_AddrOf)
529 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
530 if (DRE->getDecl()->isCXXInstanceMember())
531 ArgTy = DRE->getDecl()->getType();
533 // First see if we can just cast to record type, or pointer to record type.
534 const RecordType *RT = getRecordType(ArgTy);
536 // Now check if we index into a record type function param.
537 if(!RT && ParamIdxOk) {
538 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
539 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
541 unsigned int NumParams = FD->getNumParams();
542 llvm::APInt ArgValue = IL->getValue();
543 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
544 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
545 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
546 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
547 << Attr.getName() << Idx + 1 << NumParams;
550 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
554 // If the type does not have a capability, see if the components of the
555 // expression have capabilities. This allows for writing C code where the
556 // capability may be on the type, and the expression is a capability
557 // boolean logic expression. Eg) requires_capability(A || B && !C)
558 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
559 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
560 << Attr.getName() << ArgTy;
562 Args.push_back(ArgExp);
566 //===----------------------------------------------------------------------===//
567 // Attribute Implementations
568 //===----------------------------------------------------------------------===//
570 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
571 const AttributeList &Attr) {
572 if (!threadSafetyCheckIsPointer(S, D, Attr))
575 D->addAttr(::new (S.Context)
576 PtGuardedVarAttr(Attr.getRange(), S.Context,
577 Attr.getAttributeSpellingListIndex()));
580 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
581 const AttributeList &Attr,
583 SmallVector<Expr*, 1> Args;
584 // check that all arguments are lockable objects
585 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
586 unsigned Size = Args.size();
595 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
597 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
600 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
601 Attr.getAttributeSpellingListIndex()));
604 static void handlePtGuardedByAttr(Sema &S, Decl *D,
605 const AttributeList &Attr) {
607 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
610 if (!threadSafetyCheckIsPointer(S, D, Attr))
613 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
615 Attr.getAttributeSpellingListIndex()));
618 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
619 const AttributeList &Attr,
620 SmallVectorImpl<Expr *> &Args) {
621 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
624 // Check that this attribute only applies to lockable types.
625 QualType QT = cast<ValueDecl>(D)->getType();
626 if (!QT->isDependentType()) {
627 const RecordType *RT = getRecordType(QT);
628 if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
629 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
635 // Check that all arguments are lockable objects.
636 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
643 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
644 const AttributeList &Attr) {
645 SmallVector<Expr*, 1> Args;
646 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
649 Expr **StartArg = &Args[0];
650 D->addAttr(::new (S.Context)
651 AcquiredAfterAttr(Attr.getRange(), S.Context,
652 StartArg, Args.size(),
653 Attr.getAttributeSpellingListIndex()));
656 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
657 const AttributeList &Attr) {
658 SmallVector<Expr*, 1> Args;
659 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
662 Expr **StartArg = &Args[0];
663 D->addAttr(::new (S.Context)
664 AcquiredBeforeAttr(Attr.getRange(), S.Context,
665 StartArg, Args.size(),
666 Attr.getAttributeSpellingListIndex()));
669 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
670 const AttributeList &Attr,
671 SmallVectorImpl<Expr *> &Args) {
672 // zero or more arguments ok
673 // check that all arguments are lockable objects
674 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
679 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
680 const AttributeList &Attr) {
681 SmallVector<Expr*, 1> Args;
682 if (!checkLockFunAttrCommon(S, D, Attr, Args))
685 unsigned Size = Args.size();
686 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
687 D->addAttr(::new (S.Context)
688 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
689 Attr.getAttributeSpellingListIndex()));
692 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
693 const AttributeList &Attr) {
694 SmallVector<Expr*, 1> Args;
695 if (!checkLockFunAttrCommon(S, D, Attr, Args))
698 unsigned Size = Args.size();
699 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
700 D->addAttr(::new (S.Context)
701 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
703 Attr.getAttributeSpellingListIndex()));
707 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
708 const AttributeList &Attr,
709 SmallVectorImpl<Expr *> &Args) {
710 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
713 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
714 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
715 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
719 // check that all arguments are lockable objects
720 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
725 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
726 const AttributeList &Attr) {
727 SmallVector<Expr*, 2> Args;
728 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
731 D->addAttr(::new (S.Context)
732 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
733 Attr.getArgAsExpr(0),
734 Args.data(), Args.size(),
735 Attr.getAttributeSpellingListIndex()));
738 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
739 const AttributeList &Attr) {
740 SmallVector<Expr*, 2> Args;
741 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
744 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
745 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
746 Args.size(), Attr.getAttributeSpellingListIndex()));
749 static void handleLockReturnedAttr(Sema &S, Decl *D,
750 const AttributeList &Attr) {
751 // check that the argument is lockable object
752 SmallVector<Expr*, 1> Args;
753 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
754 unsigned Size = Args.size();
758 D->addAttr(::new (S.Context)
759 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
760 Attr.getAttributeSpellingListIndex()));
763 static void handleLocksExcludedAttr(Sema &S, Decl *D,
764 const AttributeList &Attr) {
765 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
768 // check that all arguments are lockable objects
769 SmallVector<Expr*, 1> Args;
770 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
771 unsigned Size = Args.size();
774 Expr **StartArg = &Args[0];
776 D->addAttr(::new (S.Context)
777 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
778 Attr.getAttributeSpellingListIndex()));
781 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
782 Expr *Cond = Attr.getArgAsExpr(0);
783 if (!Cond->isTypeDependent()) {
784 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
785 if (Converted.isInvalid())
787 Cond = Converted.get();
791 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
794 SmallVector<PartialDiagnosticAt, 8> Diags;
795 if (!Cond->isValueDependent() &&
796 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
798 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
799 for (int I = 0, N = Diags.size(); I != N; ++I)
800 S.Diag(Diags[I].first, Diags[I].second);
804 D->addAttr(::new (S.Context)
805 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
806 Attr.getAttributeSpellingListIndex()));
809 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
810 ConsumableAttr::ConsumedState DefaultState;
812 if (Attr.isArgIdent(0)) {
813 IdentifierLoc *IL = Attr.getArgAsIdent(0);
814 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
816 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
817 << Attr.getName() << IL->Ident;
821 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
822 << Attr.getName() << AANT_ArgumentIdentifier;
826 D->addAttr(::new (S.Context)
827 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
828 Attr.getAttributeSpellingListIndex()));
832 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
833 const AttributeList &Attr) {
834 ASTContext &CurrContext = S.getASTContext();
835 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
837 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
838 if (!RD->hasAttr<ConsumableAttr>()) {
839 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
840 RD->getNameAsString();
850 static void handleCallableWhenAttr(Sema &S, Decl *D,
851 const AttributeList &Attr) {
852 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
855 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
858 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
859 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
860 CallableWhenAttr::ConsumedState CallableState;
862 StringRef StateString;
864 if (Attr.isArgIdent(ArgIndex)) {
865 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
866 StateString = Ident->Ident->getName();
869 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
873 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
875 S.Diag(Loc, diag::warn_attribute_type_not_supported)
876 << Attr.getName() << StateString;
880 States.push_back(CallableState);
883 D->addAttr(::new (S.Context)
884 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
885 States.size(), Attr.getAttributeSpellingListIndex()));
889 static void handleParamTypestateAttr(Sema &S, Decl *D,
890 const AttributeList &Attr) {
891 ParamTypestateAttr::ConsumedState ParamState;
893 if (Attr.isArgIdent(0)) {
894 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
895 StringRef StateString = Ident->Ident->getName();
897 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
899 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
900 << Attr.getName() << StateString;
904 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
905 Attr.getName() << AANT_ArgumentIdentifier;
909 // FIXME: This check is currently being done in the analysis. It can be
910 // enabled here only after the parser propagates attributes at
911 // template specialization definition, not declaration.
912 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
913 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
915 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
916 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
917 // ReturnType.getAsString();
921 D->addAttr(::new (S.Context)
922 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
923 Attr.getAttributeSpellingListIndex()));
927 static void handleReturnTypestateAttr(Sema &S, Decl *D,
928 const AttributeList &Attr) {
929 ReturnTypestateAttr::ConsumedState ReturnState;
931 if (Attr.isArgIdent(0)) {
932 IdentifierLoc *IL = Attr.getArgAsIdent(0);
933 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
935 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
936 << Attr.getName() << IL->Ident;
940 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
941 Attr.getName() << AANT_ArgumentIdentifier;
945 // FIXME: This check is currently being done in the analysis. It can be
946 // enabled here only after the parser propagates attributes at
947 // template specialization definition, not declaration.
948 //QualType ReturnType;
950 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
951 // ReturnType = Param->getType();
953 //} else if (const CXXConstructorDecl *Constructor =
954 // dyn_cast<CXXConstructorDecl>(D)) {
955 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
959 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
962 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
964 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
965 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
966 // ReturnType.getAsString();
970 D->addAttr(::new (S.Context)
971 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
972 Attr.getAttributeSpellingListIndex()));
976 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
977 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
980 SetTypestateAttr::ConsumedState NewState;
981 if (Attr.isArgIdent(0)) {
982 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
983 StringRef Param = Ident->Ident->getName();
984 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
985 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
986 << Attr.getName() << Param;
990 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
991 Attr.getName() << AANT_ArgumentIdentifier;
995 D->addAttr(::new (S.Context)
996 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
997 Attr.getAttributeSpellingListIndex()));
1000 static void handleTestTypestateAttr(Sema &S, Decl *D,
1001 const AttributeList &Attr) {
1002 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1005 TestTypestateAttr::ConsumedState TestState;
1006 if (Attr.isArgIdent(0)) {
1007 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1008 StringRef Param = Ident->Ident->getName();
1009 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1010 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1011 << Attr.getName() << Param;
1015 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1016 Attr.getName() << AANT_ArgumentIdentifier;
1020 D->addAttr(::new (S.Context)
1021 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1022 Attr.getAttributeSpellingListIndex()));
1025 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1026 const AttributeList &Attr) {
1027 // Remember this typedef decl, we will need it later for diagnostics.
1028 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1031 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1032 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1033 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1034 Attr.getAttributeSpellingListIndex()));
1035 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1036 // If the alignment is less than or equal to 8 bits, the packed attribute
1038 if (!FD->getType()->isDependentType() &&
1039 !FD->getType()->isIncompleteType() &&
1040 S.Context.getTypeAlign(FD->getType()) <= 8)
1041 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1042 << Attr.getName() << FD->getType();
1044 FD->addAttr(::new (S.Context)
1045 PackedAttr(Attr.getRange(), S.Context,
1046 Attr.getAttributeSpellingListIndex()));
1048 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1051 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1052 // The IBOutlet/IBOutletCollection attributes only apply to instance
1053 // variables or properties of Objective-C classes. The outlet must also
1054 // have an object reference type.
1055 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1056 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1057 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1058 << Attr.getName() << VD->getType() << 0;
1062 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1063 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1064 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1065 << Attr.getName() << PD->getType() << 1;
1070 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1077 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1078 if (!checkIBOutletCommon(S, D, Attr))
1081 D->addAttr(::new (S.Context)
1082 IBOutletAttr(Attr.getRange(), S.Context,
1083 Attr.getAttributeSpellingListIndex()));
1086 static void handleIBOutletCollection(Sema &S, Decl *D,
1087 const AttributeList &Attr) {
1089 // The iboutletcollection attribute can have zero or one arguments.
1090 if (Attr.getNumArgs() > 1) {
1091 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1092 << Attr.getName() << 1;
1096 if (!checkIBOutletCommon(S, D, Attr))
1101 if (Attr.hasParsedType())
1102 PT = Attr.getTypeArg();
1104 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1105 S.getScopeForContext(D->getDeclContext()->getParent()));
1107 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1112 TypeSourceInfo *QTLoc = nullptr;
1113 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1115 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1117 // Diagnose use of non-object type in iboutletcollection attribute.
1118 // FIXME. Gnu attribute extension ignores use of builtin types in
1119 // attributes. So, __attribute__((iboutletcollection(char))) will be
1120 // treated as __attribute__((iboutletcollection())).
1121 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1122 S.Diag(Attr.getLoc(),
1123 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1124 : diag::err_iboutletcollection_type) << QT;
1128 D->addAttr(::new (S.Context)
1129 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1130 Attr.getAttributeSpellingListIndex()));
1133 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1135 if (T->isReferenceType())
1138 T = T.getNonReferenceType();
1141 // The nonnull attribute, and other similar attributes, can be applied to a
1142 // transparent union that contains a pointer type.
1143 if (const RecordType *UT = T->getAsUnionType()) {
1144 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1145 RecordDecl *UD = UT->getDecl();
1146 for (const auto *I : UD->fields()) {
1147 QualType QT = I->getType();
1148 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1154 return T->isAnyPointerType() || T->isBlockPointerType();
1157 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1158 SourceRange AttrParmRange,
1159 SourceRange TypeRange,
1160 bool isReturnValue = false) {
1161 if (!S.isValidPointerAttrType(T)) {
1162 S.Diag(Attr.getLoc(), isReturnValue
1163 ? diag::warn_attribute_return_pointers_only
1164 : diag::warn_attribute_pointers_only)
1165 << Attr.getName() << AttrParmRange << TypeRange;
1171 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1172 SmallVector<unsigned, 8> NonNullArgs;
1173 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1174 Expr *Ex = Attr.getArgAsExpr(I);
1176 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1179 // Is the function argument a pointer type?
1180 if (Idx < getFunctionOrMethodNumParams(D) &&
1181 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1182 Ex->getSourceRange(),
1183 getFunctionOrMethodParamRange(D, Idx)))
1186 NonNullArgs.push_back(Idx);
1189 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1190 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1191 // check if the attribute came from a macro expansion or a template
1193 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1194 S.ActiveTemplateInstantiations.empty()) {
1195 bool AnyPointers = isFunctionOrMethodVariadic(D);
1196 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1197 I != E && !AnyPointers; ++I) {
1198 QualType T = getFunctionOrMethodParamType(D, I);
1199 if (T->isDependentType() || S.isValidPointerAttrType(T))
1204 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1207 unsigned *Start = NonNullArgs.data();
1208 unsigned Size = NonNullArgs.size();
1209 llvm::array_pod_sort(Start, Start + Size);
1210 D->addAttr(::new (S.Context)
1211 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1212 Attr.getAttributeSpellingListIndex()));
1215 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1216 const AttributeList &Attr) {
1217 if (Attr.getNumArgs() > 0) {
1218 if (D->getFunctionType()) {
1219 handleNonNullAttr(S, D, Attr);
1221 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1222 << D->getSourceRange();
1227 // Is the argument a pointer type?
1228 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1229 D->getSourceRange()))
1232 D->addAttr(::new (S.Context)
1233 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1234 Attr.getAttributeSpellingListIndex()));
1237 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1238 const AttributeList &Attr) {
1239 QualType ResultType = getFunctionOrMethodResultType(D);
1240 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1241 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1242 /* isReturnValue */ true))
1245 D->addAttr(::new (S.Context)
1246 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1247 Attr.getAttributeSpellingListIndex()));
1250 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1251 const AttributeList &Attr) {
1252 Expr *E = Attr.getArgAsExpr(0),
1253 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1254 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1255 Attr.getAttributeSpellingListIndex());
1258 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1259 Expr *OE, unsigned SpellingListIndex) {
1260 QualType ResultType = getFunctionOrMethodResultType(D);
1261 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1263 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1264 SourceLocation AttrLoc = AttrRange.getBegin();
1266 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1267 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1268 << &TmpAttr << AttrRange << SR;
1272 if (!E->isValueDependent()) {
1274 if (!E->isIntegerConstantExpr(I, Context)) {
1276 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1277 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1278 << E->getSourceRange();
1280 Diag(AttrLoc, diag::err_attribute_argument_type)
1281 << &TmpAttr << AANT_ArgumentIntegerConstant
1282 << E->getSourceRange();
1286 if (!I.isPowerOf2()) {
1287 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1288 << E->getSourceRange();
1294 if (!OE->isValueDependent()) {
1296 if (!OE->isIntegerConstantExpr(I, Context)) {
1297 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1298 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1299 << OE->getSourceRange();
1305 D->addAttr(::new (Context)
1306 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1309 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1310 // This attribute must be applied to a function declaration. The first
1311 // argument to the attribute must be an identifier, the name of the resource,
1312 // for example: malloc. The following arguments must be argument indexes, the
1313 // arguments must be of integer type for Returns, otherwise of pointer type.
1314 // The difference between Holds and Takes is that a pointer may still be used
1315 // after being held. free() should be __attribute((ownership_takes)), whereas
1316 // a list append function may well be __attribute((ownership_holds)).
1318 if (!AL.isArgIdent(0)) {
1319 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1320 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1324 // Figure out our Kind.
1325 OwnershipAttr::OwnershipKind K =
1326 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1327 AL.getAttributeSpellingListIndex()).getOwnKind();
1331 case OwnershipAttr::Takes:
1332 case OwnershipAttr::Holds:
1333 if (AL.getNumArgs() < 2) {
1334 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1335 << AL.getName() << 2;
1339 case OwnershipAttr::Returns:
1340 if (AL.getNumArgs() > 2) {
1341 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1342 << AL.getName() << 1;
1348 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1350 // Normalize the argument, __foo__ becomes foo.
1351 StringRef ModuleName = Module->getName();
1352 if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1353 ModuleName.size() > 4) {
1354 ModuleName = ModuleName.drop_front(2).drop_back(2);
1355 Module = &S.PP.getIdentifierTable().get(ModuleName);
1358 SmallVector<unsigned, 8> OwnershipArgs;
1359 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1360 Expr *Ex = AL.getArgAsExpr(i);
1362 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1365 // Is the function argument a pointer type?
1366 QualType T = getFunctionOrMethodParamType(D, Idx);
1367 int Err = -1; // No error
1369 case OwnershipAttr::Takes:
1370 case OwnershipAttr::Holds:
1371 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1374 case OwnershipAttr::Returns:
1375 if (!T->isIntegerType())
1380 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1381 << Ex->getSourceRange();
1385 // Check we don't have a conflict with another ownership attribute.
1386 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1387 // Cannot have two ownership attributes of different kinds for the same
1389 if (I->getOwnKind() != K && I->args_end() !=
1390 std::find(I->args_begin(), I->args_end(), Idx)) {
1391 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1392 << AL.getName() << I;
1394 } else if (K == OwnershipAttr::Returns &&
1395 I->getOwnKind() == OwnershipAttr::Returns) {
1396 // A returns attribute conflicts with any other returns attribute using
1397 // a different index. Note, diagnostic reporting is 1-based, but stored
1398 // argument indexes are 0-based.
1399 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1400 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1401 << *(I->args_begin()) + 1;
1403 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1404 << (unsigned)Idx + 1 << Ex->getSourceRange();
1409 OwnershipArgs.push_back(Idx);
1412 unsigned* start = OwnershipArgs.data();
1413 unsigned size = OwnershipArgs.size();
1414 llvm::array_pod_sort(start, start + size);
1416 D->addAttr(::new (S.Context)
1417 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1418 AL.getAttributeSpellingListIndex()));
1421 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1422 // Check the attribute arguments.
1423 if (Attr.getNumArgs() > 1) {
1424 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1425 << Attr.getName() << 1;
1429 NamedDecl *nd = cast<NamedDecl>(D);
1433 // static int a __attribute__((weakref ("v2")));
1434 // static int b() __attribute__((weakref ("f3")));
1436 // and ignores the attributes of
1438 // static int a __attribute__((weakref ("v2")));
1441 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1442 if (!Ctx->isFileContext()) {
1443 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1448 // The GCC manual says
1450 // At present, a declaration to which `weakref' is attached can only
1455 // Without a TARGET,
1456 // given as an argument to `weakref' or to `alias', `weakref' is
1457 // equivalent to `weak'.
1459 // gcc 4.4.1 will accept
1460 // int a7 __attribute__((weakref));
1462 // int a7 __attribute__((weak));
1463 // This looks like a bug in gcc. We reject that for now. We should revisit
1464 // it if this behaviour is actually used.
1467 // static ((alias ("y"), weakref)).
1468 // Should we? How to check that weakref is before or after alias?
1470 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1471 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1472 // StringRef parameter it was given anyway.
1474 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1475 // GCC will accept anything as the argument of weakref. Should we
1476 // check for an existing decl?
1477 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1478 Attr.getAttributeSpellingListIndex()));
1480 D->addAttr(::new (S.Context)
1481 WeakRefAttr(Attr.getRange(), S.Context,
1482 Attr.getAttributeSpellingListIndex()));
1485 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1487 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1490 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1491 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1495 // FIXME: check if target symbol exists in current file
1497 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1498 Attr.getAttributeSpellingListIndex()));
1501 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1502 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1505 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1506 Attr.getAttributeSpellingListIndex()));
1509 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1510 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1513 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1514 Attr.getAttributeSpellingListIndex()));
1517 static void handleTLSModelAttr(Sema &S, Decl *D,
1518 const AttributeList &Attr) {
1520 SourceLocation LiteralLoc;
1521 // Check that it is a string.
1522 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1525 // Check that the value.
1526 if (Model != "global-dynamic" && Model != "local-dynamic"
1527 && Model != "initial-exec" && Model != "local-exec") {
1528 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1532 D->addAttr(::new (S.Context)
1533 TLSModelAttr(Attr.getRange(), S.Context, Model,
1534 Attr.getAttributeSpellingListIndex()));
1537 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1539 QualType RetTy = FD->getReturnType();
1540 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1541 D->addAttr(::new (S.Context)
1542 MallocAttr(Attr.getRange(), S.Context,
1543 Attr.getAttributeSpellingListIndex()));
1548 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1551 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1552 if (S.LangOpts.CPlusPlus) {
1553 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1554 << Attr.getName() << AttributeLangSupport::Cpp;
1558 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1559 Attr.getAttributeSpellingListIndex()));
1562 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1563 if (hasDeclarator(D)) return;
1565 if (S.CheckNoReturnAttr(attr)) return;
1567 if (!isa<ObjCMethodDecl>(D)) {
1568 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1569 << attr.getName() << ExpectedFunctionOrMethod;
1573 D->addAttr(::new (S.Context)
1574 NoReturnAttr(attr.getRange(), S.Context,
1575 attr.getAttributeSpellingListIndex()));
1578 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1579 if (!checkAttributeNumArgs(*this, attr, 0)) {
1587 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1588 const AttributeList &Attr) {
1590 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1591 // because 'analyzer_noreturn' does not impact the type.
1592 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1593 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1594 if (!VD || (!VD->getType()->isBlockPointerType() &&
1595 !VD->getType()->isFunctionPointerType())) {
1596 S.Diag(Attr.getLoc(),
1597 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1598 : diag::warn_attribute_wrong_decl_type)
1599 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1604 D->addAttr(::new (S.Context)
1605 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1606 Attr.getAttributeSpellingListIndex()));
1609 // PS3 PPU-specific.
1610 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1612 Returning a Vector Class in Registers
1614 According to the PPU ABI specifications, a class with a single member of
1615 vector type is returned in memory when used as the return value of a function.
1616 This results in inefficient code when implementing vector classes. To return
1617 the value in a single vector register, add the vecreturn attribute to the
1618 class definition. This attribute is also applicable to struct types.
1624 __vector float xyzw;
1625 } __attribute__((vecreturn));
1627 Vector Add(Vector lhs, Vector rhs)
1630 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1631 return result; // This will be returned in a register
1634 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1635 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1639 RecordDecl *record = cast<RecordDecl>(D);
1642 if (!isa<CXXRecordDecl>(record)) {
1643 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1647 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1648 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1652 for (const auto *I : record->fields()) {
1653 if ((count == 1) || !I->getType()->isVectorType()) {
1654 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1660 D->addAttr(::new (S.Context)
1661 VecReturnAttr(Attr.getRange(), S.Context,
1662 Attr.getAttributeSpellingListIndex()));
1665 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1666 const AttributeList &Attr) {
1667 if (isa<ParmVarDecl>(D)) {
1668 // [[carries_dependency]] can only be applied to a parameter if it is a
1669 // parameter of a function declaration or lambda.
1670 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1671 S.Diag(Attr.getLoc(),
1672 diag::err_carries_dependency_param_not_function_decl);
1677 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1678 Attr.getRange(), S.Context,
1679 Attr.getAttributeSpellingListIndex()));
1682 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1683 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1684 if (VD->hasLocalStorage()) {
1685 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1688 } else if (!isFunctionOrMethod(D)) {
1689 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1690 << Attr.getName() << ExpectedVariableOrFunction;
1694 D->addAttr(::new (S.Context)
1695 UsedAttr(Attr.getRange(), S.Context,
1696 Attr.getAttributeSpellingListIndex()));
1699 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1700 uint32_t priority = ConstructorAttr::DefaultPriority;
1701 if (Attr.getNumArgs() &&
1702 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1705 D->addAttr(::new (S.Context)
1706 ConstructorAttr(Attr.getRange(), S.Context, priority,
1707 Attr.getAttributeSpellingListIndex()));
1710 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1711 uint32_t priority = DestructorAttr::DefaultPriority;
1712 if (Attr.getNumArgs() &&
1713 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1716 D->addAttr(::new (S.Context)
1717 DestructorAttr(Attr.getRange(), S.Context, priority,
1718 Attr.getAttributeSpellingListIndex()));
1721 template <typename AttrTy>
1722 static void handleAttrWithMessage(Sema &S, Decl *D,
1723 const AttributeList &Attr) {
1724 // Handle the case where the attribute has a text message.
1726 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1729 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1730 Attr.getAttributeSpellingListIndex()));
1733 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1734 const AttributeList &Attr) {
1735 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1736 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1737 << Attr.getName() << Attr.getRange();
1741 D->addAttr(::new (S.Context)
1742 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1743 Attr.getAttributeSpellingListIndex()));
1746 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1747 IdentifierInfo *Platform,
1748 VersionTuple Introduced,
1749 VersionTuple Deprecated,
1750 VersionTuple Obsoleted) {
1751 StringRef PlatformName
1752 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1753 if (PlatformName.empty())
1754 PlatformName = Platform->getName();
1756 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1757 // of these steps are needed).
1758 if (!Introduced.empty() && !Deprecated.empty() &&
1759 !(Introduced <= Deprecated)) {
1760 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1761 << 1 << PlatformName << Deprecated.getAsString()
1762 << 0 << Introduced.getAsString();
1766 if (!Introduced.empty() && !Obsoleted.empty() &&
1767 !(Introduced <= Obsoleted)) {
1768 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1769 << 2 << PlatformName << Obsoleted.getAsString()
1770 << 0 << Introduced.getAsString();
1774 if (!Deprecated.empty() && !Obsoleted.empty() &&
1775 !(Deprecated <= Obsoleted)) {
1776 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1777 << 2 << PlatformName << Obsoleted.getAsString()
1778 << 1 << Deprecated.getAsString();
1785 /// \brief Check whether the two versions match.
1787 /// If either version tuple is empty, then they are assumed to match. If
1788 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1789 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1790 bool BeforeIsOkay) {
1791 if (X.empty() || Y.empty())
1797 if (BeforeIsOkay && X < Y)
1803 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1804 IdentifierInfo *Platform,
1805 VersionTuple Introduced,
1806 VersionTuple Deprecated,
1807 VersionTuple Obsoleted,
1811 unsigned AttrSpellingListIndex) {
1812 VersionTuple MergedIntroduced = Introduced;
1813 VersionTuple MergedDeprecated = Deprecated;
1814 VersionTuple MergedObsoleted = Obsoleted;
1815 bool FoundAny = false;
1817 if (D->hasAttrs()) {
1818 AttrVec &Attrs = D->getAttrs();
1819 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1820 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1826 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1827 if (OldPlatform != Platform) {
1833 VersionTuple OldIntroduced = OldAA->getIntroduced();
1834 VersionTuple OldDeprecated = OldAA->getDeprecated();
1835 VersionTuple OldObsoleted = OldAA->getObsoleted();
1836 bool OldIsUnavailable = OldAA->getUnavailable();
1838 if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1839 !versionsMatch(Deprecated, OldDeprecated, Override) ||
1840 !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1841 !(OldIsUnavailable == IsUnavailable ||
1842 (Override && !OldIsUnavailable && IsUnavailable))) {
1845 VersionTuple FirstVersion;
1846 VersionTuple SecondVersion;
1847 if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1849 FirstVersion = OldIntroduced;
1850 SecondVersion = Introduced;
1851 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1853 FirstVersion = Deprecated;
1854 SecondVersion = OldDeprecated;
1855 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1857 FirstVersion = Obsoleted;
1858 SecondVersion = OldObsoleted;
1862 Diag(OldAA->getLocation(),
1863 diag::warn_mismatched_availability_override_unavail)
1864 << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1866 Diag(OldAA->getLocation(),
1867 diag::warn_mismatched_availability_override)
1869 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1870 << FirstVersion.getAsString() << SecondVersion.getAsString();
1872 Diag(Range.getBegin(), diag::note_overridden_method);
1874 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1875 Diag(Range.getBegin(), diag::note_previous_attribute);
1878 Attrs.erase(Attrs.begin() + i);
1883 VersionTuple MergedIntroduced2 = MergedIntroduced;
1884 VersionTuple MergedDeprecated2 = MergedDeprecated;
1885 VersionTuple MergedObsoleted2 = MergedObsoleted;
1887 if (MergedIntroduced2.empty())
1888 MergedIntroduced2 = OldIntroduced;
1889 if (MergedDeprecated2.empty())
1890 MergedDeprecated2 = OldDeprecated;
1891 if (MergedObsoleted2.empty())
1892 MergedObsoleted2 = OldObsoleted;
1894 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1895 MergedIntroduced2, MergedDeprecated2,
1896 MergedObsoleted2)) {
1897 Attrs.erase(Attrs.begin() + i);
1902 MergedIntroduced = MergedIntroduced2;
1903 MergedDeprecated = MergedDeprecated2;
1904 MergedObsoleted = MergedObsoleted2;
1910 MergedIntroduced == Introduced &&
1911 MergedDeprecated == Deprecated &&
1912 MergedObsoleted == Obsoleted)
1915 // Only create a new attribute if !Override, but we want to do
1917 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1918 MergedDeprecated, MergedObsoleted) &&
1920 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1921 Introduced, Deprecated,
1922 Obsoleted, IsUnavailable, Message,
1923 AttrSpellingListIndex);
1928 static void handleAvailabilityAttr(Sema &S, Decl *D,
1929 const AttributeList &Attr) {
1930 if (!checkAttributeNumArgs(S, Attr, 1))
1932 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1933 unsigned Index = Attr.getAttributeSpellingListIndex();
1935 IdentifierInfo *II = Platform->Ident;
1936 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1937 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1940 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1942 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1946 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1947 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1948 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1949 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1951 if (const StringLiteral *SE =
1952 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1953 Str = SE->getString();
1955 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1963 D->addAttr(NewAttr);
1967 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1968 typename T::VisibilityType value,
1969 unsigned attrSpellingListIndex) {
1970 T *existingAttr = D->getAttr<T>();
1972 typename T::VisibilityType existingValue = existingAttr->getVisibility();
1973 if (existingValue == value)
1975 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
1976 S.Diag(range.getBegin(), diag::note_previous_attribute);
1979 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
1982 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
1983 VisibilityAttr::VisibilityType Vis,
1984 unsigned AttrSpellingListIndex) {
1985 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
1986 AttrSpellingListIndex);
1989 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1990 TypeVisibilityAttr::VisibilityType Vis,
1991 unsigned AttrSpellingListIndex) {
1992 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
1993 AttrSpellingListIndex);
1996 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
1997 bool isTypeVisibility) {
1998 // Visibility attributes don't mean anything on a typedef.
1999 if (isa<TypedefNameDecl>(D)) {
2000 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2005 // 'type_visibility' can only go on a type or namespace.
2006 if (isTypeVisibility &&
2007 !(isa<TagDecl>(D) ||
2008 isa<ObjCInterfaceDecl>(D) ||
2009 isa<NamespaceDecl>(D))) {
2010 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2011 << Attr.getName() << ExpectedTypeOrNamespace;
2015 // Check that the argument is a string literal.
2017 SourceLocation LiteralLoc;
2018 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2021 VisibilityAttr::VisibilityType type;
2022 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2023 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2024 << Attr.getName() << TypeStr;
2028 // Complain about attempts to use protected visibility on targets
2029 // (like Darwin) that don't support it.
2030 if (type == VisibilityAttr::Protected &&
2031 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2032 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2033 type = VisibilityAttr::Default;
2036 unsigned Index = Attr.getAttributeSpellingListIndex();
2037 clang::Attr *newAttr;
2038 if (isTypeVisibility) {
2039 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2040 (TypeVisibilityAttr::VisibilityType) type,
2043 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2046 D->addAttr(newAttr);
2049 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2050 const AttributeList &Attr) {
2051 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2052 if (!Attr.isArgIdent(0)) {
2053 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2054 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2058 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2059 ObjCMethodFamilyAttr::FamilyKind F;
2060 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2061 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2066 if (F == ObjCMethodFamilyAttr::OMF_init &&
2067 !method->getReturnType()->isObjCObjectPointerType()) {
2068 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2069 << method->getReturnType();
2070 // Ignore the attribute.
2074 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2076 Attr.getAttributeSpellingListIndex()));
2079 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2080 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2081 QualType T = TD->getUnderlyingType();
2082 if (!T->isCARCBridgableType()) {
2083 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2087 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2088 QualType T = PD->getType();
2089 if (!T->isCARCBridgableType()) {
2090 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2095 // It is okay to include this attribute on properties, e.g.:
2097 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2099 // In this case it follows tradition and suppresses an error in the above
2101 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2103 D->addAttr(::new (S.Context)
2104 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2105 Attr.getAttributeSpellingListIndex()));
2108 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2109 if (!Attr.isArgIdent(0)) {
2110 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2111 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2115 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2116 BlocksAttr::BlockType type;
2117 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2118 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2119 << Attr.getName() << II;
2123 D->addAttr(::new (S.Context)
2124 BlocksAttr(Attr.getRange(), S.Context, type,
2125 Attr.getAttributeSpellingListIndex()));
2128 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2129 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2130 if (Attr.getNumArgs() > 0) {
2131 Expr *E = Attr.getArgAsExpr(0);
2132 llvm::APSInt Idx(32);
2133 if (E->isTypeDependent() || E->isValueDependent() ||
2134 !E->isIntegerConstantExpr(Idx, S.Context)) {
2135 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2136 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2137 << E->getSourceRange();
2141 if (Idx.isSigned() && Idx.isNegative()) {
2142 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2143 << E->getSourceRange();
2147 sentinel = Idx.getZExtValue();
2150 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2151 if (Attr.getNumArgs() > 1) {
2152 Expr *E = Attr.getArgAsExpr(1);
2153 llvm::APSInt Idx(32);
2154 if (E->isTypeDependent() || E->isValueDependent() ||
2155 !E->isIntegerConstantExpr(Idx, S.Context)) {
2156 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2157 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2158 << E->getSourceRange();
2161 nullPos = Idx.getZExtValue();
2163 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2164 // FIXME: This error message could be improved, it would be nice
2165 // to say what the bounds actually are.
2166 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2167 << E->getSourceRange();
2172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2173 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2174 if (isa<FunctionNoProtoType>(FT)) {
2175 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2179 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2180 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2183 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2184 if (!MD->isVariadic()) {
2185 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2188 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2189 if (!BD->isVariadic()) {
2190 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2193 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2194 QualType Ty = V->getType();
2195 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2196 const FunctionType *FT = Ty->isFunctionPointerType()
2197 ? D->getFunctionType()
2198 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2199 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2200 int m = Ty->isFunctionPointerType() ? 0 : 1;
2201 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2205 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2206 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2210 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2211 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2214 D->addAttr(::new (S.Context)
2215 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2216 Attr.getAttributeSpellingListIndex()));
2219 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2220 if (D->getFunctionType() &&
2221 D->getFunctionType()->getReturnType()->isVoidType()) {
2222 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2223 << Attr.getName() << 0;
2226 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2227 if (MD->getReturnType()->isVoidType()) {
2228 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2229 << Attr.getName() << 1;
2233 D->addAttr(::new (S.Context)
2234 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2235 Attr.getAttributeSpellingListIndex()));
2238 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2239 // weak_import only applies to variable & function declarations.
2241 if (!D->canBeWeakImported(isDef)) {
2243 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2245 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2246 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2247 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2248 // Nothing to warn about here.
2250 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2251 << Attr.getName() << ExpectedVariableOrFunction;
2256 D->addAttr(::new (S.Context)
2257 WeakImportAttr(Attr.getRange(), S.Context,
2258 Attr.getAttributeSpellingListIndex()));
2261 // Handles reqd_work_group_size and work_group_size_hint.
2262 template <typename WorkGroupAttr>
2263 static void handleWorkGroupSize(Sema &S, Decl *D,
2264 const AttributeList &Attr) {
2266 for (unsigned i = 0; i < 3; ++i) {
2267 const Expr *E = Attr.getArgAsExpr(i);
2268 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2270 if (WGSize[i] == 0) {
2271 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2272 << Attr.getName() << E->getSourceRange();
2277 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2278 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2279 Existing->getYDim() == WGSize[1] &&
2280 Existing->getZDim() == WGSize[2]))
2281 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2283 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2284 WGSize[0], WGSize[1], WGSize[2],
2285 Attr.getAttributeSpellingListIndex()));
2288 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2289 if (!Attr.hasParsedType()) {
2290 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2291 << Attr.getName() << 1;
2295 TypeSourceInfo *ParmTSI = nullptr;
2296 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2297 assert(ParmTSI && "no type source info for attribute argument");
2299 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2300 (ParmType->isBooleanType() ||
2301 !ParmType->isIntegralType(S.getASTContext()))) {
2302 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2307 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2308 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2309 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2314 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2316 Attr.getAttributeSpellingListIndex()));
2319 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2321 unsigned AttrSpellingListIndex) {
2322 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2323 if (ExistingAttr->getName() == Name)
2325 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2326 Diag(Range.getBegin(), diag::note_previous_attribute);
2329 return ::new (Context) SectionAttr(Range, Context, Name,
2330 AttrSpellingListIndex);
2333 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2334 // Make sure that there is a string literal as the sections's single
2337 SourceLocation LiteralLoc;
2338 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2341 // If the target wants to validate the section specifier, make it happen.
2342 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2343 if (!Error.empty()) {
2344 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2349 unsigned Index = Attr.getAttributeSpellingListIndex();
2350 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2352 D->addAttr(NewAttr);
2356 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2357 VarDecl *VD = cast<VarDecl>(D);
2358 if (!VD->hasLocalStorage()) {
2359 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2363 Expr *E = Attr.getArgAsExpr(0);
2364 SourceLocation Loc = E->getExprLoc();
2365 FunctionDecl *FD = nullptr;
2366 DeclarationNameInfo NI;
2368 // gcc only allows for simple identifiers. Since we support more than gcc, we
2369 // will warn the user.
2370 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2371 if (DRE->hasQualifier())
2372 S.Diag(Loc, diag::warn_cleanup_ext);
2373 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2374 NI = DRE->getNameInfo();
2376 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2380 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2381 if (ULE->hasExplicitTemplateArgs())
2382 S.Diag(Loc, diag::warn_cleanup_ext);
2383 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2384 NI = ULE->getNameInfo();
2386 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2388 if (ULE->getType() == S.Context.OverloadTy)
2389 S.NoteAllOverloadCandidates(ULE);
2393 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2397 if (FD->getNumParams() != 1) {
2398 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2403 // We're currently more strict than GCC about what function types we accept.
2404 // If this ever proves to be a problem it should be easy to fix.
2405 QualType Ty = S.Context.getPointerType(VD->getType());
2406 QualType ParamTy = FD->getParamDecl(0)->getType();
2407 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2408 ParamTy, Ty) != Sema::Compatible) {
2409 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2410 << NI.getName() << ParamTy << Ty;
2414 D->addAttr(::new (S.Context)
2415 CleanupAttr(Attr.getRange(), S.Context, FD,
2416 Attr.getAttributeSpellingListIndex()));
2419 /// Handle __attribute__((format_arg((idx)))) attribute based on
2420 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2421 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2422 Expr *IdxExpr = Attr.getArgAsExpr(0);
2424 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2427 // make sure the format string is really a string
2428 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2430 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2431 if (not_nsstring_type &&
2432 !isCFStringType(Ty, S.Context) &&
2433 (!Ty->isPointerType() ||
2434 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2435 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2436 << (not_nsstring_type ? "a string type" : "an NSString")
2437 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2440 Ty = getFunctionOrMethodResultType(D);
2441 if (!isNSStringType(Ty, S.Context) &&
2442 !isCFStringType(Ty, S.Context) &&
2443 (!Ty->isPointerType() ||
2444 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2445 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2446 << (not_nsstring_type ? "string type" : "NSString")
2447 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2451 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2452 // because that has corrected for the implicit this parameter, and is zero-
2453 // based. The attribute expects what the user wrote explicitly.
2455 IdxExpr->EvaluateAsInt(Val, S.Context);
2457 D->addAttr(::new (S.Context)
2458 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2459 Attr.getAttributeSpellingListIndex()));
2462 enum FormatAttrKind {
2471 /// getFormatAttrKind - Map from format attribute names to supported format
2473 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2474 return llvm::StringSwitch<FormatAttrKind>(Format)
2475 // Check for formats that get handled specially.
2476 .Case("NSString", NSStringFormat)
2477 .Case("CFString", CFStringFormat)
2478 .Case("strftime", StrftimeFormat)
2480 // Otherwise, check for supported formats.
2481 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2482 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2483 .Case("kprintf", SupportedFormat) // OpenBSD.
2484 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2486 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2487 .Default(InvalidFormat);
2490 /// Handle __attribute__((init_priority(priority))) attributes based on
2491 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2492 static void handleInitPriorityAttr(Sema &S, Decl *D,
2493 const AttributeList &Attr) {
2494 if (!S.getLangOpts().CPlusPlus) {
2495 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2499 if (S.getCurFunctionOrMethodDecl()) {
2500 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2504 QualType T = cast<VarDecl>(D)->getType();
2505 if (S.Context.getAsArrayType(T))
2506 T = S.Context.getBaseElementType(T);
2507 if (!T->getAs<RecordType>()) {
2508 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2513 Expr *E = Attr.getArgAsExpr(0);
2514 uint32_t prioritynum;
2515 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2520 if (prioritynum < 101 || prioritynum > 65535) {
2521 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2522 << E->getSourceRange();
2526 D->addAttr(::new (S.Context)
2527 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2528 Attr.getAttributeSpellingListIndex()));
2531 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2532 IdentifierInfo *Format, int FormatIdx,
2534 unsigned AttrSpellingListIndex) {
2535 // Check whether we already have an equivalent format attribute.
2536 for (auto *F : D->specific_attrs<FormatAttr>()) {
2537 if (F->getType() == Format &&
2538 F->getFormatIdx() == FormatIdx &&
2539 F->getFirstArg() == FirstArg) {
2540 // If we don't have a valid location for this attribute, adopt the
2542 if (F->getLocation().isInvalid())
2548 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2549 FirstArg, AttrSpellingListIndex);
2552 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2553 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2554 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2555 if (!Attr.isArgIdent(0)) {
2556 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2557 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2561 // In C++ the implicit 'this' function parameter also counts, and they are
2562 // counted from one.
2563 bool HasImplicitThisParam = isInstanceMethod(D);
2564 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2566 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2567 StringRef Format = II->getName();
2569 // Normalize the argument, __foo__ becomes foo.
2570 if (Format.startswith("__") && Format.endswith("__")) {
2571 Format = Format.substr(2, Format.size() - 4);
2572 // If we've modified the string name, we need a new identifier for it.
2573 II = &S.Context.Idents.get(Format);
2576 // Check for supported formats.
2577 FormatAttrKind Kind = getFormatAttrKind(Format);
2579 if (Kind == IgnoredFormat)
2582 if (Kind == InvalidFormat) {
2583 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2584 << Attr.getName() << II->getName();
2588 // checks for the 2nd argument
2589 Expr *IdxExpr = Attr.getArgAsExpr(1);
2591 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2594 if (Idx < 1 || Idx > NumArgs) {
2595 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2596 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2600 // FIXME: Do we need to bounds check?
2601 unsigned ArgIdx = Idx - 1;
2603 if (HasImplicitThisParam) {
2605 S.Diag(Attr.getLoc(),
2606 diag::err_format_attribute_implicit_this_format_string)
2607 << IdxExpr->getSourceRange();
2613 // make sure the format string is really a string
2614 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2616 if (Kind == CFStringFormat) {
2617 if (!isCFStringType(Ty, S.Context)) {
2618 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2619 << "a CFString" << IdxExpr->getSourceRange()
2620 << getFunctionOrMethodParamRange(D, ArgIdx);
2623 } else if (Kind == NSStringFormat) {
2624 // FIXME: do we need to check if the type is NSString*? What are the
2626 if (!isNSStringType(Ty, S.Context)) {
2627 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2628 << "an NSString" << IdxExpr->getSourceRange()
2629 << getFunctionOrMethodParamRange(D, ArgIdx);
2632 } else if (!Ty->isPointerType() ||
2633 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2634 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2635 << "a string type" << IdxExpr->getSourceRange()
2636 << getFunctionOrMethodParamRange(D, ArgIdx);
2640 // check the 3rd argument
2641 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2643 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2646 // check if the function is variadic if the 3rd argument non-zero
2647 if (FirstArg != 0) {
2648 if (isFunctionOrMethodVariadic(D)) {
2649 ++NumArgs; // +1 for ...
2651 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2656 // strftime requires FirstArg to be 0 because it doesn't read from any
2657 // variable the input is just the current time + the format string.
2658 if (Kind == StrftimeFormat) {
2659 if (FirstArg != 0) {
2660 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2661 << FirstArgExpr->getSourceRange();
2664 // if 0 it disables parameter checking (to use with e.g. va_list)
2665 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2666 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2667 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2671 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2673 Attr.getAttributeSpellingListIndex());
2675 D->addAttr(NewAttr);
2678 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2679 const AttributeList &Attr) {
2680 // Try to find the underlying union declaration.
2681 RecordDecl *RD = nullptr;
2682 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2683 if (TD && TD->getUnderlyingType()->isUnionType())
2684 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2686 RD = dyn_cast<RecordDecl>(D);
2688 if (!RD || !RD->isUnion()) {
2689 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2690 << Attr.getName() << ExpectedUnion;
2694 if (!RD->isCompleteDefinition()) {
2695 S.Diag(Attr.getLoc(),
2696 diag::warn_transparent_union_attribute_not_definition);
2700 RecordDecl::field_iterator Field = RD->field_begin(),
2701 FieldEnd = RD->field_end();
2702 if (Field == FieldEnd) {
2703 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2707 FieldDecl *FirstField = *Field;
2708 QualType FirstType = FirstField->getType();
2709 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2710 S.Diag(FirstField->getLocation(),
2711 diag::warn_transparent_union_attribute_floating)
2712 << FirstType->isVectorType() << FirstType;
2716 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2717 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2718 for (; Field != FieldEnd; ++Field) {
2719 QualType FieldType = Field->getType();
2720 // FIXME: this isn't fully correct; we also need to test whether the
2721 // members of the union would all have the same calling convention as the
2722 // first member of the union. Checking just the size and alignment isn't
2723 // sufficient (consider structs passed on the stack instead of in registers
2725 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2726 S.Context.getTypeAlign(FieldType) > FirstAlign) {
2727 // Warn if we drop the attribute.
2728 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2729 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2730 : S.Context.getTypeAlign(FieldType);
2731 S.Diag(Field->getLocation(),
2732 diag::warn_transparent_union_attribute_field_size_align)
2733 << isSize << Field->getDeclName() << FieldBits;
2734 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2735 S.Diag(FirstField->getLocation(),
2736 diag::note_transparent_union_first_field_size_align)
2737 << isSize << FirstBits;
2742 RD->addAttr(::new (S.Context)
2743 TransparentUnionAttr(Attr.getRange(), S.Context,
2744 Attr.getAttributeSpellingListIndex()));
2747 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2748 // Make sure that there is a string literal as the annotation's single
2751 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2754 // Don't duplicate annotations that are already set.
2755 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2756 if (I->getAnnotation() == Str)
2760 D->addAttr(::new (S.Context)
2761 AnnotateAttr(Attr.getRange(), S.Context, Str,
2762 Attr.getAttributeSpellingListIndex()));
2765 static void handleAlignValueAttr(Sema &S, Decl *D,
2766 const AttributeList &Attr) {
2767 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
2768 Attr.getAttributeSpellingListIndex());
2771 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
2772 unsigned SpellingListIndex) {
2773 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
2774 SourceLocation AttrLoc = AttrRange.getBegin();
2777 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2778 T = TD->getUnderlyingType();
2779 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2782 llvm_unreachable("Unknown decl type for align_value");
2784 if (!T->isDependentType() && !T->isAnyPointerType() &&
2785 !T->isReferenceType() && !T->isMemberPointerType()) {
2786 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
2787 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
2791 if (!E->isValueDependent()) {
2792 llvm::APSInt Alignment(32);
2794 = VerifyIntegerConstantExpression(E, &Alignment,
2795 diag::err_align_value_attribute_argument_not_int,
2796 /*AllowFold*/ false);
2797 if (ICE.isInvalid())
2800 if (!Alignment.isPowerOf2()) {
2801 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2802 << E->getSourceRange();
2806 D->addAttr(::new (Context)
2807 AlignValueAttr(AttrRange, Context, ICE.get(),
2808 SpellingListIndex));
2812 // Save dependent expressions in the AST to be instantiated.
2813 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
2817 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2818 // check the attribute arguments.
2819 if (Attr.getNumArgs() > 1) {
2820 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2821 << Attr.getName() << 1;
2825 if (Attr.getNumArgs() == 0) {
2826 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2827 true, nullptr, Attr.getAttributeSpellingListIndex()));
2831 Expr *E = Attr.getArgAsExpr(0);
2832 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2833 S.Diag(Attr.getEllipsisLoc(),
2834 diag::err_pack_expansion_without_parameter_packs);
2838 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2841 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2842 Attr.isPackExpansion());
2845 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2846 unsigned SpellingListIndex, bool IsPackExpansion) {
2847 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2848 SourceLocation AttrLoc = AttrRange.getBegin();
2850 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2851 if (TmpAttr.isAlignas()) {
2852 // C++11 [dcl.align]p1:
2853 // An alignment-specifier may be applied to a variable or to a class
2854 // data member, but it shall not be applied to a bit-field, a function
2855 // parameter, the formal parameter of a catch clause, or a variable
2856 // declared with the register storage class specifier. An
2857 // alignment-specifier may also be applied to the declaration of a class
2858 // or enumeration type.
2860 // An alignment attribute shall not be specified in a declaration of
2861 // a typedef, or a bit-field, or a function, or a parameter, or an
2862 // object declared with the register storage-class specifier.
2864 if (isa<ParmVarDecl>(D)) {
2866 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2867 if (VD->getStorageClass() == SC_Register)
2869 if (VD->isExceptionVariable())
2871 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2872 if (FD->isBitField())
2874 } else if (!isa<TagDecl>(D)) {
2875 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2876 << (TmpAttr.isC11() ? ExpectedVariableOrField
2877 : ExpectedVariableFieldOrTag);
2880 if (DiagKind != -1) {
2881 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2882 << &TmpAttr << DiagKind;
2887 if (E->isTypeDependent() || E->isValueDependent()) {
2888 // Save dependent expressions in the AST to be instantiated.
2889 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2890 AA->setPackExpansion(IsPackExpansion);
2895 // FIXME: Cache the number on the Attr object?
2896 llvm::APSInt Alignment(32);
2898 = VerifyIntegerConstantExpression(E, &Alignment,
2899 diag::err_aligned_attribute_argument_not_int,
2900 /*AllowFold*/ false);
2901 if (ICE.isInvalid())
2904 // C++11 [dcl.align]p2:
2905 // -- if the constant expression evaluates to zero, the alignment
2906 // specifier shall have no effect
2908 // An alignment specification of zero has no effect.
2909 if (!(TmpAttr.isAlignas() && !Alignment) &&
2910 !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2911 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2912 << E->getSourceRange();
2916 // Alignment calculations can wrap around if it's greater than 2**28.
2917 unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
2918 if (Alignment.getZExtValue() > MaxValidAlignment) {
2919 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
2920 << E->getSourceRange();
2924 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
2925 ICE.get(), SpellingListIndex);
2926 AA->setPackExpansion(IsPackExpansion);
2930 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
2931 unsigned SpellingListIndex, bool IsPackExpansion) {
2932 // FIXME: Cache the number on the Attr object if non-dependent?
2933 // FIXME: Perform checking of type validity
2934 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
2936 AA->setPackExpansion(IsPackExpansion);
2940 void Sema::CheckAlignasUnderalignment(Decl *D) {
2941 assert(D->hasAttrs() && "no attributes on decl");
2944 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2947 Ty = Context.getTagDeclType(cast<TagDecl>(D));
2948 if (Ty->isDependentType() || Ty->isIncompleteType())
2951 // C++11 [dcl.align]p5, C11 6.7.5/4:
2952 // The combined effect of all alignment attributes in a declaration shall
2953 // not specify an alignment that is less strict than the alignment that
2954 // would otherwise be required for the entity being declared.
2955 AlignedAttr *AlignasAttr = nullptr;
2957 for (auto *I : D->specific_attrs<AlignedAttr>()) {
2958 if (I->isAlignmentDependent())
2962 Align = std::max(Align, I->getAlignment(Context));
2965 if (AlignasAttr && Align) {
2966 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
2967 CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
2968 if (NaturalAlign > RequestedAlign)
2969 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
2970 << Ty << (unsigned)NaturalAlign.getQuantity();
2974 bool Sema::checkMSInheritanceAttrOnDefinition(
2975 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2976 MSInheritanceAttr::Spelling SemanticSpelling) {
2977 assert(RD->hasDefinition() && "RD has no definition!");
2979 // We may not have seen base specifiers or any virtual methods yet. We will
2980 // have to wait until the record is defined to catch any mismatches.
2981 if (!RD->getDefinition()->isCompleteDefinition())
2984 // The unspecified model never matches what a definition could need.
2985 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
2989 if (RD->calculateInheritanceModel() == SemanticSpelling)
2992 if (RD->calculateInheritanceModel() <= SemanticSpelling)
2996 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
2997 << 0 /*definition*/;
2998 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
2999 << RD->getNameAsString();
3003 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3006 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3007 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3008 /// HImode, not an intermediate pointer.
3009 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3010 // This attribute isn't documented, but glibc uses it. It changes
3011 // the width of an int or unsigned int to the specified size.
3012 if (!Attr.isArgIdent(0)) {
3013 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3014 << AANT_ArgumentIdentifier;
3018 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3019 StringRef Str = Name->getName();
3021 // Normalize the attribute name, __foo__ becomes foo.
3022 if (Str.startswith("__") && Str.endswith("__"))
3023 Str = Str.substr(2, Str.size() - 4);
3025 unsigned DestWidth = 0;
3026 bool IntegerMode = true;
3027 bool ComplexMode = false;
3028 switch (Str.size()) {
3031 case 'Q': DestWidth = 8; break;
3032 case 'H': DestWidth = 16; break;
3033 case 'S': DestWidth = 32; break;
3034 case 'D': DestWidth = 64; break;
3035 case 'X': DestWidth = 96; break;
3036 case 'T': DestWidth = 128; break;
3038 if (Str[1] == 'F') {
3039 IntegerMode = false;
3040 } else if (Str[1] == 'C') {
3041 IntegerMode = false;
3043 } else if (Str[1] != 'I') {
3048 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3049 // pointer on PIC16 and other embedded platforms.
3051 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3052 else if (Str == "byte")
3053 DestWidth = S.Context.getTargetInfo().getCharWidth();
3056 if (Str == "pointer")
3057 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3060 if (Str == "unwind_word")
3061 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3066 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3067 OldTy = TD->getUnderlyingType();
3068 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3069 OldTy = VD->getType();
3071 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3072 << Attr.getName() << Attr.getRange();
3076 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3077 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3078 else if (IntegerMode) {
3079 if (!OldTy->isIntegralOrEnumerationType())
3080 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3081 } else if (ComplexMode) {
3082 if (!OldTy->isComplexType())
3083 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3085 if (!OldTy->isFloatingType())
3086 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3089 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3090 // and friends, at least with glibc.
3091 // FIXME: Make sure floating-point mappings are accurate
3092 // FIXME: Support XF and TF types
3094 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3101 NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
3102 OldTy->isSignedIntegerType());
3104 NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
3106 if (NewTy.isNull()) {
3107 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3112 NewTy = S.Context.getComplexType(NewTy);
3115 // Install the new type.
3116 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3117 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3119 cast<ValueDecl>(D)->setType(NewTy);
3121 D->addAttr(::new (S.Context)
3122 ModeAttr(Attr.getRange(), S.Context, Name,
3123 Attr.getAttributeSpellingListIndex()));
3126 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3128 if (!VD->hasGlobalStorage())
3129 S.Diag(Attr.getLoc(),
3130 diag::warn_attribute_requires_functions_or_static_globals)
3132 } else if (!isFunctionOrMethod(D)) {
3133 S.Diag(Attr.getLoc(),
3134 diag::warn_attribute_requires_functions_or_static_globals)
3139 D->addAttr(::new (S.Context)
3140 NoDebugAttr(Attr.getRange(), S.Context,
3141 Attr.getAttributeSpellingListIndex()));
3144 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3145 IdentifierInfo *Ident,
3146 unsigned AttrSpellingListIndex) {
3147 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3148 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3149 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3153 if (D->hasAttr<AlwaysInlineAttr>())
3156 return ::new (Context) AlwaysInlineAttr(Range, Context,
3157 AttrSpellingListIndex);
3160 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3161 unsigned AttrSpellingListIndex) {
3162 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3163 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3164 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3168 if (D->hasAttr<MinSizeAttr>())
3171 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3174 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3175 unsigned AttrSpellingListIndex) {
3176 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3177 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3178 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3179 D->dropAttr<AlwaysInlineAttr>();
3181 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3182 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3183 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3184 D->dropAttr<MinSizeAttr>();
3187 if (D->hasAttr<OptimizeNoneAttr>())
3190 return ::new (Context) OptimizeNoneAttr(Range, Context,
3191 AttrSpellingListIndex);
3194 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3195 const AttributeList &Attr) {
3196 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3197 D, Attr.getRange(), Attr.getName(),
3198 Attr.getAttributeSpellingListIndex()))
3202 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3203 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3204 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3205 D->addAttr(MinSize);
3208 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3209 const AttributeList &Attr) {
3210 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3211 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3212 D->addAttr(Optnone);
3215 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3216 FunctionDecl *FD = cast<FunctionDecl>(D);
3217 if (!FD->getReturnType()->isVoidType()) {
3218 SourceRange RTRange = FD->getReturnTypeSourceRange();
3219 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3221 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3226 D->addAttr(::new (S.Context)
3227 CUDAGlobalAttr(Attr.getRange(), S.Context,
3228 Attr.getAttributeSpellingListIndex()));
3231 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3232 FunctionDecl *Fn = cast<FunctionDecl>(D);
3233 if (!Fn->isInlineSpecified()) {
3234 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3238 D->addAttr(::new (S.Context)
3239 GNUInlineAttr(Attr.getRange(), S.Context,
3240 Attr.getAttributeSpellingListIndex()));
3243 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3244 if (hasDeclarator(D)) return;
3246 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3247 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3248 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3250 if (S.CheckCallingConvAttr(Attr, CC, FD))
3253 if (!isa<ObjCMethodDecl>(D)) {
3254 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3255 << Attr.getName() << ExpectedFunctionOrMethod;
3259 switch (Attr.getKind()) {
3260 case AttributeList::AT_FastCall:
3261 D->addAttr(::new (S.Context)
3262 FastCallAttr(Attr.getRange(), S.Context,
3263 Attr.getAttributeSpellingListIndex()));
3265 case AttributeList::AT_StdCall:
3266 D->addAttr(::new (S.Context)
3267 StdCallAttr(Attr.getRange(), S.Context,
3268 Attr.getAttributeSpellingListIndex()));
3270 case AttributeList::AT_ThisCall:
3271 D->addAttr(::new (S.Context)
3272 ThisCallAttr(Attr.getRange(), S.Context,
3273 Attr.getAttributeSpellingListIndex()));
3275 case AttributeList::AT_CDecl:
3276 D->addAttr(::new (S.Context)
3277 CDeclAttr(Attr.getRange(), S.Context,
3278 Attr.getAttributeSpellingListIndex()));
3280 case AttributeList::AT_Pascal:
3281 D->addAttr(::new (S.Context)
3282 PascalAttr(Attr.getRange(), S.Context,
3283 Attr.getAttributeSpellingListIndex()));
3285 case AttributeList::AT_VectorCall:
3286 D->addAttr(::new (S.Context)
3287 VectorCallAttr(Attr.getRange(), S.Context,
3288 Attr.getAttributeSpellingListIndex()));
3290 case AttributeList::AT_MSABI:
3291 D->addAttr(::new (S.Context)
3292 MSABIAttr(Attr.getRange(), S.Context,
3293 Attr.getAttributeSpellingListIndex()));
3295 case AttributeList::AT_SysVABI:
3296 D->addAttr(::new (S.Context)
3297 SysVABIAttr(Attr.getRange(), S.Context,
3298 Attr.getAttributeSpellingListIndex()));
3300 case AttributeList::AT_Pcs: {
3301 PcsAttr::PCSType PCS;
3304 PCS = PcsAttr::AAPCS;
3307 PCS = PcsAttr::AAPCS_VFP;
3310 llvm_unreachable("unexpected calling convention in pcs attribute");
3313 D->addAttr(::new (S.Context)
3314 PcsAttr(Attr.getRange(), S.Context, PCS,
3315 Attr.getAttributeSpellingListIndex()));
3318 case AttributeList::AT_PnaclCall:
3319 D->addAttr(::new (S.Context)
3320 PnaclCallAttr(Attr.getRange(), S.Context,
3321 Attr.getAttributeSpellingListIndex()));
3323 case AttributeList::AT_IntelOclBicc:
3324 D->addAttr(::new (S.Context)
3325 IntelOclBiccAttr(Attr.getRange(), S.Context,
3326 Attr.getAttributeSpellingListIndex()));
3330 llvm_unreachable("unexpected attribute kind");
3334 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3335 const FunctionDecl *FD) {
3336 if (attr.isInvalid())
3339 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3340 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3345 // TODO: diagnose uses of these conventions on the wrong target.
3346 switch (attr.getKind()) {
3347 case AttributeList::AT_CDecl: CC = CC_C; break;
3348 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3349 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3350 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3351 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3352 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3353 case AttributeList::AT_MSABI:
3354 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3357 case AttributeList::AT_SysVABI:
3358 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3361 case AttributeList::AT_Pcs: {
3363 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3367 if (StrRef == "aapcs") {
3370 } else if (StrRef == "aapcs-vfp") {
3376 Diag(attr.getLoc(), diag::err_invalid_pcs);
3379 case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3380 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3381 default: llvm_unreachable("unexpected attribute kind");
3384 const TargetInfo &TI = Context.getTargetInfo();
3385 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3386 if (A == TargetInfo::CCCR_Warning) {
3387 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3389 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3391 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3392 TargetInfo::CCMT_NonMember;
3393 CC = TI.getDefaultCallingConv(MT);
3399 /// Checks a regparm attribute, returning true if it is ill-formed and
3400 /// otherwise setting numParams to the appropriate value.
3401 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3402 if (Attr.isInvalid())
3405 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3411 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3412 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3417 if (Context.getTargetInfo().getRegParmMax() == 0) {
3418 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3419 << NumParamsExpr->getSourceRange();
3425 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3426 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3427 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3435 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3436 const AttributeList &Attr) {
3437 uint32_t MaxThreads, MinBlocks = 0;
3438 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), MaxThreads, 1))
3440 if (Attr.getNumArgs() > 1 && !checkUInt32Argument(S, Attr,
3441 Attr.getArgAsExpr(1),
3445 D->addAttr(::new (S.Context)
3446 CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3447 MaxThreads, MinBlocks,
3448 Attr.getAttributeSpellingListIndex()));
3451 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3452 const AttributeList &Attr) {
3453 if (!Attr.isArgIdent(0)) {
3454 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3455 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3459 if (!checkAttributeNumArgs(S, Attr, 3))
3462 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3464 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3465 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3466 << Attr.getName() << ExpectedFunctionOrMethod;
3470 uint64_t ArgumentIdx;
3471 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3475 uint64_t TypeTagIdx;
3476 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3480 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3482 // Ensure that buffer has a pointer type.
3483 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3484 if (!BufferTy->isPointerType()) {
3485 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3490 D->addAttr(::new (S.Context)
3491 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3492 ArgumentIdx, TypeTagIdx, IsPointer,
3493 Attr.getAttributeSpellingListIndex()));
3496 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3497 const AttributeList &Attr) {
3498 if (!Attr.isArgIdent(0)) {
3499 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3500 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3504 if (!checkAttributeNumArgs(S, Attr, 1))
3507 if (!isa<VarDecl>(D)) {
3508 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3509 << Attr.getName() << ExpectedVariable;
3513 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3514 TypeSourceInfo *MatchingCTypeLoc = nullptr;
3515 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3516 assert(MatchingCTypeLoc && "no type source info for attribute argument");
3518 D->addAttr(::new (S.Context)
3519 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3521 Attr.getLayoutCompatible(),
3522 Attr.getMustBeNull(),
3523 Attr.getAttributeSpellingListIndex()));
3526 //===----------------------------------------------------------------------===//
3527 // Checker-specific attribute handlers.
3528 //===----------------------------------------------------------------------===//
3530 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3531 return type->isDependentType() ||
3532 type->isObjCRetainableType();
3535 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3536 return type->isDependentType() ||
3537 type->isObjCObjectPointerType() ||
3538 S.Context.isObjCNSObjectType(type);
3540 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3541 return type->isDependentType() ||
3542 type->isPointerType() ||
3543 isValidSubjectOfNSAttribute(S, type);
3546 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3547 ParmVarDecl *param = cast<ParmVarDecl>(D);
3550 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3551 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3554 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3559 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3560 << Attr.getRange() << Attr.getName() << cf;
3565 param->addAttr(::new (S.Context)
3566 CFConsumedAttr(Attr.getRange(), S.Context,
3567 Attr.getAttributeSpellingListIndex()));
3569 param->addAttr(::new (S.Context)
3570 NSConsumedAttr(Attr.getRange(), S.Context,
3571 Attr.getAttributeSpellingListIndex()));
3574 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3575 const AttributeList &Attr) {
3577 QualType returnType;
3579 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3580 returnType = MD->getReturnType();
3581 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3582 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3583 return; // ignore: was handled as a type attribute
3584 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3585 returnType = PD->getType();
3586 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3587 returnType = FD->getReturnType();
3589 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3590 << Attr.getRange() << Attr.getName()
3591 << ExpectedFunctionOrMethod;
3597 switch (Attr.getKind()) {
3598 default: llvm_unreachable("invalid ownership attribute");
3599 case AttributeList::AT_NSReturnsRetained:
3600 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
3604 case AttributeList::AT_NSReturnsAutoreleased:
3605 case AttributeList::AT_NSReturnsNotRetained:
3606 typeOK = isValidSubjectOfNSAttribute(S, returnType);
3610 case AttributeList::AT_CFReturnsRetained:
3611 case AttributeList::AT_CFReturnsNotRetained:
3612 typeOK = isValidSubjectOfCFAttribute(S, returnType);
3618 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3619 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3623 switch (Attr.getKind()) {
3625 llvm_unreachable("invalid ownership attribute");
3626 case AttributeList::AT_NSReturnsAutoreleased:
3627 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
3628 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3630 case AttributeList::AT_CFReturnsNotRetained:
3631 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
3632 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3634 case AttributeList::AT_NSReturnsNotRetained:
3635 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
3636 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3638 case AttributeList::AT_CFReturnsRetained:
3639 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
3640 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3642 case AttributeList::AT_NSReturnsRetained:
3643 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
3644 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3649 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3650 const AttributeList &attr) {
3651 const int EP_ObjCMethod = 1;
3652 const int EP_ObjCProperty = 2;
3654 SourceLocation loc = attr.getLoc();
3655 QualType resultType;
3656 if (isa<ObjCMethodDecl>(D))
3657 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3659 resultType = cast<ObjCPropertyDecl>(D)->getType();
3661 if (!resultType->isReferenceType() &&
3662 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3663 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3666 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3667 << /*non-retainable pointer*/ 2;
3669 // Drop the attribute.
3673 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
3674 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
3677 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3678 const AttributeList &attr) {
3679 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3681 DeclContext *DC = method->getDeclContext();
3682 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3683 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3684 << attr.getName() << 0;
3685 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3688 if (method->getMethodFamily() == OMF_dealloc) {
3689 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3690 << attr.getName() << 1;
3694 method->addAttr(::new (S.Context)
3695 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3696 attr.getAttributeSpellingListIndex()));
3699 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3700 const AttributeList &Attr) {
3701 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3704 D->addAttr(::new (S.Context)
3705 CFAuditedTransferAttr(Attr.getRange(), S.Context,
3706 Attr.getAttributeSpellingListIndex()));
3709 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3710 const AttributeList &Attr) {
3711 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3714 D->addAttr(::new (S.Context)
3715 CFUnknownTransferAttr(Attr.getRange(), S.Context,
3716 Attr.getAttributeSpellingListIndex()));
3719 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3720 const AttributeList &Attr) {
3721 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3724 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3728 D->addAttr(::new (S.Context)
3729 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3730 Attr.getAttributeSpellingListIndex()));
3733 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3734 const AttributeList &Attr) {
3735 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3738 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3742 D->addAttr(::new (S.Context)
3743 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3744 Attr.getAttributeSpellingListIndex()));
3747 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3748 const AttributeList &Attr) {
3749 IdentifierInfo *RelatedClass =
3750 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
3751 if (!RelatedClass) {
3752 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3755 IdentifierInfo *ClassMethod =
3756 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
3757 IdentifierInfo *InstanceMethod =
3758 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
3759 D->addAttr(::new (S.Context)
3760 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3761 ClassMethod, InstanceMethod,
3762 Attr.getAttributeSpellingListIndex()));
3765 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3766 const AttributeList &Attr) {
3767 ObjCInterfaceDecl *IFace;
3768 if (ObjCCategoryDecl *CatDecl =
3769 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
3770 IFace = CatDecl->getClassInterface();
3772 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3773 IFace->setHasDesignatedInitializers();
3774 D->addAttr(::new (S.Context)
3775 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3776 Attr.getAttributeSpellingListIndex()));
3779 static void handleObjCRuntimeName(Sema &S, Decl *D,
3780 const AttributeList &Attr) {
3781 StringRef MetaDataName;
3782 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
3784 D->addAttr(::new (S.Context)
3785 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
3787 Attr.getAttributeSpellingListIndex()));
3790 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3791 const AttributeList &Attr) {
3792 if (hasDeclarator(D)) return;
3794 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3795 << Attr.getRange() << Attr.getName() << ExpectedVariable;
3798 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3799 const AttributeList &Attr) {
3800 ValueDecl *vd = cast<ValueDecl>(D);
3801 QualType type = vd->getType();
3803 if (!type->isDependentType() &&
3804 !type->isObjCLifetimeType()) {
3805 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3810 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3812 // If we have no lifetime yet, check the lifetime we're presumably
3814 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3815 lifetime = type->getObjCARCImplicitLifetime();
3818 case Qualifiers::OCL_None:
3819 assert(type->isDependentType() &&
3820 "didn't infer lifetime for non-dependent type?");
3823 case Qualifiers::OCL_Weak: // meaningful
3824 case Qualifiers::OCL_Strong: // meaningful
3827 case Qualifiers::OCL_ExplicitNone:
3828 case Qualifiers::OCL_Autoreleasing:
3829 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3830 << (lifetime == Qualifiers::OCL_Autoreleasing);
3834 D->addAttr(::new (S.Context)
3835 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
3836 Attr.getAttributeSpellingListIndex()));
3839 //===----------------------------------------------------------------------===//
3840 // Microsoft specific attribute handlers.
3841 //===----------------------------------------------------------------------===//
3843 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3844 if (!S.LangOpts.CPlusPlus) {
3845 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3846 << Attr.getName() << AttributeLangSupport::C;
3850 if (!isa<CXXRecordDecl>(D)) {
3851 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3852 << Attr.getName() << ExpectedClass;
3857 SourceLocation LiteralLoc;
3858 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
3861 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
3862 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
3863 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
3864 StrRef = StrRef.drop_front().drop_back();
3866 // Validate GUID length.
3867 if (StrRef.size() != 36) {
3868 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3872 for (unsigned i = 0; i < 36; ++i) {
3873 if (i == 8 || i == 13 || i == 18 || i == 23) {
3874 if (StrRef[i] != '-') {
3875 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3878 } else if (!isHexDigit(StrRef[i])) {
3879 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3884 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
3885 Attr.getAttributeSpellingListIndex()));
3888 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3889 if (!S.LangOpts.CPlusPlus) {
3890 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3891 << Attr.getName() << AttributeLangSupport::C;
3894 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
3895 D, Attr.getRange(), /*BestCase=*/true,
3896 Attr.getAttributeSpellingListIndex(),
3897 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
3902 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
3903 const AttributeList &Attr) {
3904 VarDecl *VD = cast<VarDecl>(D);
3905 if (!S.Context.getTargetInfo().isTLSSupported()) {
3906 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
3909 if (VD->getTSCSpec() != TSCS_unspecified) {
3910 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
3913 if (VD->hasLocalStorage()) {
3914 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
3917 VD->addAttr(::new (S.Context) ThreadAttr(
3918 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3921 static void handleARMInterruptAttr(Sema &S, Decl *D,
3922 const AttributeList &Attr) {
3923 // Check the attribute arguments.
3924 if (Attr.getNumArgs() > 1) {
3925 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
3926 << Attr.getName() << 1;
3931 SourceLocation ArgLoc;
3933 if (Attr.getNumArgs() == 0)
3935 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
3938 ARMInterruptAttr::InterruptType Kind;
3939 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
3940 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3941 << Attr.getName() << Str << ArgLoc;
3945 unsigned Index = Attr.getAttributeSpellingListIndex();
3946 D->addAttr(::new (S.Context)
3947 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
3950 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
3951 const AttributeList &Attr) {
3952 if (!checkAttributeNumArgs(S, Attr, 1))
3955 if (!Attr.isArgExpr(0)) {
3956 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3957 << AANT_ArgumentIntegerConstant;
3961 // FIXME: Check for decl - it should be void ()(void).
3963 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3964 llvm::APSInt NumParams(32);
3965 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
3966 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3967 << Attr.getName() << AANT_ArgumentIntegerConstant
3968 << NumParamsExpr->getSourceRange();
3972 unsigned Num = NumParams.getLimitedValue(255);
3973 if ((Num & 1) || Num > 30) {
3974 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3975 << Attr.getName() << (int)NumParams.getSExtValue()
3976 << NumParamsExpr->getSourceRange();
3980 D->addAttr(::new (S.Context)
3981 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
3982 Attr.getAttributeSpellingListIndex()));
3983 D->addAttr(UsedAttr::CreateImplicit(S.Context));
3986 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3987 // Dispatch the interrupt attribute based on the current target.
3988 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
3989 handleMSP430InterruptAttr(S, D, Attr);
3991 handleARMInterruptAttr(S, D, Attr);
3994 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
3995 const AttributeList &Attr) {
3997 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3998 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4001 D->addAttr(::new (S.Context)
4002 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4004 Attr.getAttributeSpellingListIndex()));
4007 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4008 const AttributeList &Attr) {
4010 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4011 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4014 D->addAttr(::new (S.Context)
4015 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4017 Attr.getAttributeSpellingListIndex()));
4020 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4021 const AttributeList& Attr) {
4022 // If we try to apply it to a function pointer, don't warn, but don't
4023 // do anything, either. It doesn't matter anyway, because there's nothing
4024 // special about calling a force_align_arg_pointer function.
4025 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4026 if (VD && VD->getType()->isFunctionPointerType())
4028 // Also don't warn on function pointer typedefs.
4029 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4030 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4031 TD->getUnderlyingType()->isFunctionType()))
4033 // Attribute can only be applied to function types.
4034 if (!isa<FunctionDecl>(D)) {
4035 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4036 << Attr.getName() << /* function */0;
4040 D->addAttr(::new (S.Context)
4041 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4042 Attr.getAttributeSpellingListIndex()));
4045 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4046 unsigned AttrSpellingListIndex) {
4047 if (D->hasAttr<DLLExportAttr>()) {
4048 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4052 if (D->hasAttr<DLLImportAttr>())
4055 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4058 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4059 unsigned AttrSpellingListIndex) {
4060 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4061 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4062 D->dropAttr<DLLImportAttr>();
4065 if (D->hasAttr<DLLExportAttr>())
4068 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4071 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4072 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4073 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4074 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4079 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4080 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4081 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4082 // MinGW doesn't allow dllimport on inline functions.
4083 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4089 unsigned Index = A.getAttributeSpellingListIndex();
4090 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4091 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4092 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4094 D->addAttr(NewAttr);
4098 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4099 unsigned AttrSpellingListIndex,
4100 MSInheritanceAttr::Spelling SemanticSpelling) {
4101 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4102 if (IA->getSemanticSpelling() == SemanticSpelling)
4104 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4105 << 1 /*previous declaration*/;
4106 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4107 D->dropAttr<MSInheritanceAttr>();
4110 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4111 if (RD->hasDefinition()) {
4112 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4113 SemanticSpelling)) {
4117 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4118 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4119 << 1 /*partial specialization*/;
4122 if (RD->getDescribedClassTemplate()) {
4123 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4124 << 0 /*primary template*/;
4129 return ::new (Context)
4130 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4133 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4134 // The capability attributes take a single string parameter for the name of
4135 // the capability they represent. The lockable attribute does not take any
4136 // parameters. However, semantically, both attributes represent the same
4137 // concept, and so they use the same semantic attribute. Eventually, the
4138 // lockable attribute will be removed.
4140 // For backward compatibility, any capability which has no specified string
4141 // literal will be considered a "mutex."
4142 StringRef N("mutex");
4143 SourceLocation LiteralLoc;
4144 if (Attr.getKind() == AttributeList::AT_Capability &&
4145 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4148 // Currently, there are only two names allowed for a capability: role and
4149 // mutex (case insensitive). Diagnose other capability names.
4150 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4151 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4153 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4154 Attr.getAttributeSpellingListIndex()));
4157 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4158 const AttributeList &Attr) {
4159 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4160 Attr.getArgAsExpr(0),
4161 Attr.getAttributeSpellingListIndex()));
4164 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4165 const AttributeList &Attr) {
4166 SmallVector<Expr*, 1> Args;
4167 if (!checkLockFunAttrCommon(S, D, Attr, Args))
4170 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4172 Args.data(), Args.size(),
4173 Attr.getAttributeSpellingListIndex()));
4176 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4177 const AttributeList &Attr) {
4178 SmallVector<Expr*, 2> Args;
4179 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4182 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4184 Attr.getArgAsExpr(0),
4187 Attr.getAttributeSpellingListIndex()));
4190 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4191 const AttributeList &Attr) {
4192 // Check that all arguments are lockable objects.
4193 SmallVector<Expr *, 1> Args;
4194 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4196 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4197 Attr.getRange(), S.Context, Args.data(), Args.size(),
4198 Attr.getAttributeSpellingListIndex()));
4201 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4202 const AttributeList &Attr) {
4203 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4206 // check that all arguments are lockable objects
4207 SmallVector<Expr*, 1> Args;
4208 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4212 RequiresCapabilityAttr *RCA = ::new (S.Context)
4213 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4214 Args.size(), Attr.getAttributeSpellingListIndex());
4219 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4220 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4221 if (NSD->isAnonymousNamespace()) {
4222 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4223 // Do not want to attach the attribute to the namespace because that will
4224 // cause confusing diagnostic reports for uses of declarations within the
4229 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4232 /// Handles semantic checking for features that are common to all attributes,
4233 /// such as checking whether a parameter was properly specified, or the correct
4234 /// number of arguments were passed, etc.
4235 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4236 const AttributeList &Attr) {
4237 // Several attributes carry different semantics than the parsing requires, so
4238 // those are opted out of the common handling.
4240 // We also bail on unknown and ignored attributes because those are handled
4241 // as part of the target-specific handling logic.
4242 if (Attr.hasCustomParsing() ||
4243 Attr.getKind() == AttributeList::UnknownAttribute)
4246 // Check whether the attribute requires specific language extensions to be
4248 if (!Attr.diagnoseLangOpts(S))
4251 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4252 // If there are no optional arguments, then checking for the argument count
4254 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4257 // There are optional arguments, so checking is slightly more involved.
4258 if (Attr.getMinArgs() &&
4259 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4261 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4262 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4266 // Check whether the attribute appertains to the given subject.
4267 if (!Attr.diagnoseAppertainsTo(S, D))
4273 //===----------------------------------------------------------------------===//
4274 // Top Level Sema Entry Points
4275 //===----------------------------------------------------------------------===//
4277 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4278 /// the attribute applies to decls. If the attribute is a type attribute, just
4279 /// silently ignore it if a GNU attribute.
4280 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4281 const AttributeList &Attr,
4282 bool IncludeCXX11Attributes) {
4283 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4286 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4288 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4291 // Unknown attributes are automatically warned on. Target-specific attributes
4292 // which do not apply to the current target architecture are treated as
4293 // though they were unknown attributes.
4294 if (Attr.getKind() == AttributeList::UnknownAttribute ||
4295 !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4296 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4297 ? diag::warn_unhandled_ms_attribute_ignored
4298 : diag::warn_unknown_attribute_ignored)
4303 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4306 switch (Attr.getKind()) {
4308 // Type attributes are handled elsewhere; silently move on.
4309 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4311 case AttributeList::AT_Interrupt:
4312 handleInterruptAttr(S, D, Attr);
4314 case AttributeList::AT_X86ForceAlignArgPointer:
4315 handleX86ForceAlignArgPointerAttr(S, D, Attr);
4317 case AttributeList::AT_DLLExport:
4318 case AttributeList::AT_DLLImport:
4319 handleDLLAttr(S, D, Attr);
4321 case AttributeList::AT_Mips16:
4322 handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4324 case AttributeList::AT_NoMips16:
4325 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4327 case AttributeList::AT_AMDGPUNumVGPR:
4328 handleAMDGPUNumVGPRAttr(S, D, Attr);
4330 case AttributeList::AT_AMDGPUNumSGPR:
4331 handleAMDGPUNumSGPRAttr(S, D, Attr);
4333 case AttributeList::AT_IBAction:
4334 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4336 case AttributeList::AT_IBOutlet:
4337 handleIBOutlet(S, D, Attr);
4339 case AttributeList::AT_IBOutletCollection:
4340 handleIBOutletCollection(S, D, Attr);
4342 case AttributeList::AT_Alias:
4343 handleAliasAttr(S, D, Attr);
4345 case AttributeList::AT_Aligned:
4346 handleAlignedAttr(S, D, Attr);
4348 case AttributeList::AT_AlignValue:
4349 handleAlignValueAttr(S, D, Attr);
4351 case AttributeList::AT_AlwaysInline:
4352 handleAlwaysInlineAttr(S, D, Attr);
4354 case AttributeList::AT_AnalyzerNoReturn:
4355 handleAnalyzerNoReturnAttr(S, D, Attr);
4357 case AttributeList::AT_TLSModel:
4358 handleTLSModelAttr(S, D, Attr);
4360 case AttributeList::AT_Annotate:
4361 handleAnnotateAttr(S, D, Attr);
4363 case AttributeList::AT_Availability:
4364 handleAvailabilityAttr(S, D, Attr);
4366 case AttributeList::AT_CarriesDependency:
4367 handleDependencyAttr(S, scope, D, Attr);
4369 case AttributeList::AT_Common:
4370 handleCommonAttr(S, D, Attr);
4372 case AttributeList::AT_CUDAConstant:
4373 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4375 case AttributeList::AT_Constructor:
4376 handleConstructorAttr(S, D, Attr);
4378 case AttributeList::AT_CXX11NoReturn:
4379 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4381 case AttributeList::AT_Deprecated:
4382 handleDeprecatedAttr(S, D, Attr);
4384 case AttributeList::AT_Destructor:
4385 handleDestructorAttr(S, D, Attr);
4387 case AttributeList::AT_EnableIf:
4388 handleEnableIfAttr(S, D, Attr);
4390 case AttributeList::AT_ExtVectorType:
4391 handleExtVectorTypeAttr(S, scope, D, Attr);
4393 case AttributeList::AT_MinSize:
4394 handleMinSizeAttr(S, D, Attr);
4396 case AttributeList::AT_OptimizeNone:
4397 handleOptimizeNoneAttr(S, D, Attr);
4399 case AttributeList::AT_Flatten:
4400 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
4402 case AttributeList::AT_Format:
4403 handleFormatAttr(S, D, Attr);
4405 case AttributeList::AT_FormatArg:
4406 handleFormatArgAttr(S, D, Attr);
4408 case AttributeList::AT_CUDAGlobal:
4409 handleGlobalAttr(S, D, Attr);
4411 case AttributeList::AT_CUDADevice:
4412 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4414 case AttributeList::AT_CUDAHost:
4415 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4417 case AttributeList::AT_GNUInline:
4418 handleGNUInlineAttr(S, D, Attr);
4420 case AttributeList::AT_CUDALaunchBounds:
4421 handleLaunchBoundsAttr(S, D, Attr);
4423 case AttributeList::AT_Malloc:
4424 handleMallocAttr(S, D, Attr);
4426 case AttributeList::AT_MayAlias:
4427 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4429 case AttributeList::AT_Mode:
4430 handleModeAttr(S, D, Attr);
4432 case AttributeList::AT_NoCommon:
4433 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4435 case AttributeList::AT_NoSplitStack:
4436 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
4438 case AttributeList::AT_NonNull:
4439 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4440 handleNonNullAttrParameter(S, PVD, Attr);
4442 handleNonNullAttr(S, D, Attr);
4444 case AttributeList::AT_ReturnsNonNull:
4445 handleReturnsNonNullAttr(S, D, Attr);
4447 case AttributeList::AT_AssumeAligned:
4448 handleAssumeAlignedAttr(S, D, Attr);
4450 case AttributeList::AT_Overloadable:
4451 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4453 case AttributeList::AT_Ownership:
4454 handleOwnershipAttr(S, D, Attr);
4456 case AttributeList::AT_Cold:
4457 handleColdAttr(S, D, Attr);
4459 case AttributeList::AT_Hot:
4460 handleHotAttr(S, D, Attr);
4462 case AttributeList::AT_Naked:
4463 handleSimpleAttribute<NakedAttr>(S, D, Attr);
4465 case AttributeList::AT_NoReturn:
4466 handleNoReturnAttr(S, D, Attr);
4468 case AttributeList::AT_NoThrow:
4469 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4471 case AttributeList::AT_CUDAShared:
4472 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4474 case AttributeList::AT_VecReturn:
4475 handleVecReturnAttr(S, D, Attr);
4478 case AttributeList::AT_ObjCOwnership:
4479 handleObjCOwnershipAttr(S, D, Attr);
4481 case AttributeList::AT_ObjCPreciseLifetime:
4482 handleObjCPreciseLifetimeAttr(S, D, Attr);
4485 case AttributeList::AT_ObjCReturnsInnerPointer:
4486 handleObjCReturnsInnerPointerAttr(S, D, Attr);
4489 case AttributeList::AT_ObjCRequiresSuper:
4490 handleObjCRequiresSuperAttr(S, D, Attr);
4493 case AttributeList::AT_ObjCBridge:
4494 handleObjCBridgeAttr(S, scope, D, Attr);
4497 case AttributeList::AT_ObjCBridgeMutable:
4498 handleObjCBridgeMutableAttr(S, scope, D, Attr);
4501 case AttributeList::AT_ObjCBridgeRelated:
4502 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4505 case AttributeList::AT_ObjCDesignatedInitializer:
4506 handleObjCDesignatedInitializer(S, D, Attr);
4509 case AttributeList::AT_ObjCRuntimeName:
4510 handleObjCRuntimeName(S, D, Attr);
4513 case AttributeList::AT_CFAuditedTransfer:
4514 handleCFAuditedTransferAttr(S, D, Attr);
4516 case AttributeList::AT_CFUnknownTransfer:
4517 handleCFUnknownTransferAttr(S, D, Attr);
4520 case AttributeList::AT_CFConsumed:
4521 case AttributeList::AT_NSConsumed:
4522 handleNSConsumedAttr(S, D, Attr);
4524 case AttributeList::AT_NSConsumesSelf:
4525 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4528 case AttributeList::AT_NSReturnsAutoreleased:
4529 case AttributeList::AT_NSReturnsNotRetained:
4530 case AttributeList::AT_CFReturnsNotRetained:
4531 case AttributeList::AT_NSReturnsRetained:
4532 case AttributeList::AT_CFReturnsRetained:
4533 handleNSReturnsRetainedAttr(S, D, Attr);
4535 case AttributeList::AT_WorkGroupSizeHint:
4536 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4538 case AttributeList::AT_ReqdWorkGroupSize:
4539 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4541 case AttributeList::AT_VecTypeHint:
4542 handleVecTypeHint(S, D, Attr);
4545 case AttributeList::AT_InitPriority:
4546 handleInitPriorityAttr(S, D, Attr);
4549 case AttributeList::AT_Packed:
4550 handlePackedAttr(S, D, Attr);
4552 case AttributeList::AT_Section:
4553 handleSectionAttr(S, D, Attr);
4555 case AttributeList::AT_Unavailable:
4556 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4558 case AttributeList::AT_ArcWeakrefUnavailable:
4559 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4561 case AttributeList::AT_ObjCRootClass:
4562 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4564 case AttributeList::AT_ObjCExplicitProtocolImpl:
4565 handleObjCSuppresProtocolAttr(S, D, Attr);
4567 case AttributeList::AT_ObjCRequiresPropertyDefs:
4568 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4570 case AttributeList::AT_Unused:
4571 handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4573 case AttributeList::AT_ReturnsTwice:
4574 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4576 case AttributeList::AT_Used:
4577 handleUsedAttr(S, D, Attr);
4579 case AttributeList::AT_Visibility:
4580 handleVisibilityAttr(S, D, Attr, false);
4582 case AttributeList::AT_TypeVisibility:
4583 handleVisibilityAttr(S, D, Attr, true);
4585 case AttributeList::AT_WarnUnused:
4586 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4588 case AttributeList::AT_WarnUnusedResult:
4589 handleWarnUnusedResult(S, D, Attr);
4591 case AttributeList::AT_Weak:
4592 handleSimpleAttribute<WeakAttr>(S, D, Attr);
4594 case AttributeList::AT_WeakRef:
4595 handleWeakRefAttr(S, D, Attr);
4597 case AttributeList::AT_WeakImport:
4598 handleWeakImportAttr(S, D, Attr);
4600 case AttributeList::AT_TransparentUnion:
4601 handleTransparentUnionAttr(S, D, Attr);
4603 case AttributeList::AT_ObjCException:
4604 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4606 case AttributeList::AT_ObjCMethodFamily:
4607 handleObjCMethodFamilyAttr(S, D, Attr);
4609 case AttributeList::AT_ObjCNSObject:
4610 handleObjCNSObject(S, D, Attr);
4612 case AttributeList::AT_Blocks:
4613 handleBlocksAttr(S, D, Attr);
4615 case AttributeList::AT_Sentinel:
4616 handleSentinelAttr(S, D, Attr);
4618 case AttributeList::AT_Const:
4619 handleSimpleAttribute<ConstAttr>(S, D, Attr);
4621 case AttributeList::AT_Pure:
4622 handleSimpleAttribute<PureAttr>(S, D, Attr);
4624 case AttributeList::AT_Cleanup:
4625 handleCleanupAttr(S, D, Attr);
4627 case AttributeList::AT_NoDebug:
4628 handleNoDebugAttr(S, D, Attr);
4630 case AttributeList::AT_NoDuplicate:
4631 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4633 case AttributeList::AT_NoInline:
4634 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4636 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4637 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4639 case AttributeList::AT_StdCall:
4640 case AttributeList::AT_CDecl:
4641 case AttributeList::AT_FastCall:
4642 case AttributeList::AT_ThisCall:
4643 case AttributeList::AT_Pascal:
4644 case AttributeList::AT_VectorCall:
4645 case AttributeList::AT_MSABI:
4646 case AttributeList::AT_SysVABI:
4647 case AttributeList::AT_Pcs:
4648 case AttributeList::AT_PnaclCall:
4649 case AttributeList::AT_IntelOclBicc:
4650 handleCallConvAttr(S, D, Attr);
4652 case AttributeList::AT_OpenCLKernel:
4653 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4655 case AttributeList::AT_OpenCLImageAccess:
4656 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4659 // Microsoft attributes:
4660 case AttributeList::AT_MsStruct:
4661 handleSimpleAttribute<MsStructAttr>(S, D, Attr);
4663 case AttributeList::AT_Uuid:
4664 handleUuidAttr(S, D, Attr);
4666 case AttributeList::AT_MSInheritance:
4667 handleMSInheritanceAttr(S, D, Attr);
4669 case AttributeList::AT_SelectAny:
4670 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4672 case AttributeList::AT_Thread:
4673 handleDeclspecThreadAttr(S, D, Attr);
4676 // Thread safety attributes:
4677 case AttributeList::AT_AssertExclusiveLock:
4678 handleAssertExclusiveLockAttr(S, D, Attr);
4680 case AttributeList::AT_AssertSharedLock:
4681 handleAssertSharedLockAttr(S, D, Attr);
4683 case AttributeList::AT_GuardedVar:
4684 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4686 case AttributeList::AT_PtGuardedVar:
4687 handlePtGuardedVarAttr(S, D, Attr);
4689 case AttributeList::AT_ScopedLockable:
4690 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4692 case AttributeList::AT_NoSanitizeAddress:
4693 handleSimpleAttribute<NoSanitizeAddressAttr>(S, D, Attr);
4695 case AttributeList::AT_NoThreadSafetyAnalysis:
4696 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
4698 case AttributeList::AT_NoSanitizeThread:
4699 handleSimpleAttribute<NoSanitizeThreadAttr>(S, D, Attr);
4701 case AttributeList::AT_NoSanitizeMemory:
4702 handleSimpleAttribute<NoSanitizeMemoryAttr>(S, D, Attr);
4704 case AttributeList::AT_GuardedBy:
4705 handleGuardedByAttr(S, D, Attr);
4707 case AttributeList::AT_PtGuardedBy:
4708 handlePtGuardedByAttr(S, D, Attr);
4710 case AttributeList::AT_ExclusiveTrylockFunction:
4711 handleExclusiveTrylockFunctionAttr(S, D, Attr);
4713 case AttributeList::AT_LockReturned:
4714 handleLockReturnedAttr(S, D, Attr);
4716 case AttributeList::AT_LocksExcluded:
4717 handleLocksExcludedAttr(S, D, Attr);
4719 case AttributeList::AT_SharedTrylockFunction:
4720 handleSharedTrylockFunctionAttr(S, D, Attr);
4722 case AttributeList::AT_AcquiredBefore:
4723 handleAcquiredBeforeAttr(S, D, Attr);
4725 case AttributeList::AT_AcquiredAfter:
4726 handleAcquiredAfterAttr(S, D, Attr);
4729 // Capability analysis attributes.
4730 case AttributeList::AT_Capability:
4731 case AttributeList::AT_Lockable:
4732 handleCapabilityAttr(S, D, Attr);
4734 case AttributeList::AT_RequiresCapability:
4735 handleRequiresCapabilityAttr(S, D, Attr);
4738 case AttributeList::AT_AssertCapability:
4739 handleAssertCapabilityAttr(S, D, Attr);
4741 case AttributeList::AT_AcquireCapability:
4742 handleAcquireCapabilityAttr(S, D, Attr);
4744 case AttributeList::AT_ReleaseCapability:
4745 handleReleaseCapabilityAttr(S, D, Attr);
4747 case AttributeList::AT_TryAcquireCapability:
4748 handleTryAcquireCapabilityAttr(S, D, Attr);
4751 // Consumed analysis attributes.
4752 case AttributeList::AT_Consumable:
4753 handleConsumableAttr(S, D, Attr);
4755 case AttributeList::AT_ConsumableAutoCast:
4756 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
4758 case AttributeList::AT_ConsumableSetOnRead:
4759 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
4761 case AttributeList::AT_CallableWhen:
4762 handleCallableWhenAttr(S, D, Attr);
4764 case AttributeList::AT_ParamTypestate:
4765 handleParamTypestateAttr(S, D, Attr);
4767 case AttributeList::AT_ReturnTypestate:
4768 handleReturnTypestateAttr(S, D, Attr);
4770 case AttributeList::AT_SetTypestate:
4771 handleSetTypestateAttr(S, D, Attr);
4773 case AttributeList::AT_TestTypestate:
4774 handleTestTypestateAttr(S, D, Attr);
4777 // Type safety attributes.
4778 case AttributeList::AT_ArgumentWithTypeTag:
4779 handleArgumentWithTypeTagAttr(S, D, Attr);
4781 case AttributeList::AT_TypeTagForDatatype:
4782 handleTypeTagForDatatypeAttr(S, D, Attr);
4787 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4788 /// attribute list to the specified decl, ignoring any type attributes.
4789 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4790 const AttributeList *AttrList,
4791 bool IncludeCXX11Attributes) {
4792 for (const AttributeList* l = AttrList; l; l = l->getNext())
4793 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4795 // FIXME: We should be able to handle these cases in TableGen.
4797 // static int a9 __attribute__((weakref));
4798 // but that looks really pointless. We reject it.
4799 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4800 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
4801 << cast<NamedDecl>(D);
4802 D->dropAttr<WeakRefAttr>();
4806 // FIXME: We should be able to handle this in TableGen as well. It would be
4807 // good to have a way to specify "these attributes must appear as a group",
4808 // for these. Additionally, it would be good to have a way to specify "these
4809 // attribute must never appear as a group" for attributes like cold and hot.
4810 if (!D->hasAttr<OpenCLKernelAttr>()) {
4811 // These attributes cannot be applied to a non-kernel function.
4812 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
4813 // FIXME: This emits a different error message than
4814 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
4815 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4816 D->setInvalidDecl();
4817 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
4818 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4819 D->setInvalidDecl();
4820 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
4821 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4822 D->setInvalidDecl();
4823 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
4824 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
4825 << A << ExpectedKernelFunction;
4826 D->setInvalidDecl();
4827 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
4828 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
4829 << A << ExpectedKernelFunction;
4830 D->setInvalidDecl();
4835 // Annotation attributes are the only attributes allowed after an access
4837 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4838 const AttributeList *AttrList) {
4839 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4840 if (l->getKind() == AttributeList::AT_Annotate) {
4841 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
4843 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4851 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4852 /// contains any decl attributes that we should warn about.
4853 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4854 for ( ; A; A = A->getNext()) {
4855 // Only warn if the attribute is an unignored, non-type attribute.
4856 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4857 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4859 if (A->getKind() == AttributeList::UnknownAttribute) {
4860 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4861 << A->getName() << A->getRange();
4863 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4864 << A->getName() << A->getRange();
4869 /// checkUnusedDeclAttributes - Given a declarator which is not being
4870 /// used to build a declaration, complain about any decl attributes
4871 /// which might be lying around on it.
4872 void Sema::checkUnusedDeclAttributes(Declarator &D) {
4873 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4874 ::checkUnusedDeclAttributes(*this, D.getAttributes());
4875 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4876 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4879 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
4880 /// \#pragma weak needs a non-definition decl and source may not have one.
4881 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4882 SourceLocation Loc) {
4883 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4884 NamedDecl *NewD = nullptr;
4885 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4886 FunctionDecl *NewFD;
4887 // FIXME: Missing call to CheckFunctionDeclaration().
4889 // FIXME: Is the qualifier info correct?
4890 // FIXME: Is the DeclContext correct?
4891 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4892 Loc, Loc, DeclarationName(II),
4893 FD->getType(), FD->getTypeSourceInfo(),
4894 SC_None, false/*isInlineSpecified*/,
4896 false/*isConstexprSpecified*/);
4899 if (FD->getQualifier())
4900 NewFD->setQualifierInfo(FD->getQualifierLoc());
4902 // Fake up parameter variables; they are declared as if this were
4904 QualType FDTy = FD->getType();
4905 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4906 SmallVector<ParmVarDecl*, 16> Params;
4907 for (const auto &AI : FT->param_types()) {
4908 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
4909 Param->setScopeInfo(0, Params.size());
4910 Params.push_back(Param);
4912 NewFD->setParams(Params);
4914 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4915 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4916 VD->getInnerLocStart(), VD->getLocation(), II,
4917 VD->getType(), VD->getTypeSourceInfo(),
4918 VD->getStorageClass());
4919 if (VD->getQualifier()) {
4920 VarDecl *NewVD = cast<VarDecl>(NewD);
4921 NewVD->setQualifierInfo(VD->getQualifierLoc());
4927 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4928 /// applied to it, possibly with an alias.
4929 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4930 if (W.getUsed()) return; // only do this once
4932 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4933 IdentifierInfo *NDId = ND->getIdentifier();
4934 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4935 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
4937 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4938 WeakTopLevelDecl.push_back(NewD);
4939 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4940 // to insert Decl at TU scope, sorry.
4941 DeclContext *SavedContext = CurContext;
4942 CurContext = Context.getTranslationUnitDecl();
4943 NewD->setDeclContext(CurContext);
4944 NewD->setLexicalDeclContext(CurContext);
4945 PushOnScopeChains(NewD, S);
4946 CurContext = SavedContext;
4947 } else { // just add weak to existing
4948 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4952 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
4953 // It's valid to "forward-declare" #pragma weak, in which case we
4955 LoadExternalWeakUndeclaredIdentifiers();
4956 if (!WeakUndeclaredIdentifiers.empty()) {
4957 NamedDecl *ND = nullptr;
4958 if (VarDecl *VD = dyn_cast<VarDecl>(D))
4959 if (VD->isExternC())
4961 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4962 if (FD->isExternC())
4965 if (IdentifierInfo *Id = ND->getIdentifier()) {
4966 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4967 = WeakUndeclaredIdentifiers.find(Id);
4968 if (I != WeakUndeclaredIdentifiers.end()) {
4969 WeakInfo W = I->second;
4970 DeclApplyPragmaWeak(S, ND, W);
4971 WeakUndeclaredIdentifiers[Id] = W;
4978 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4979 /// it, apply them to D. This is a bit tricky because PD can have attributes
4980 /// specified in many different places, and we need to find and apply them all.
4981 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
4982 // Apply decl attributes from the DeclSpec if present.
4983 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4984 ProcessDeclAttributeList(S, D, Attrs);
4986 // Walk the declarator structure, applying decl attributes that were in a type
4987 // position to the decl itself. This handles cases like:
4988 // int *__attr__(x)** D;
4989 // when X is a decl attribute.
4990 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
4991 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
4992 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
4994 // Finally, apply any attributes on the decl itself.
4995 if (const AttributeList *Attrs = PD.getAttributes())
4996 ProcessDeclAttributeList(S, D, Attrs);
4999 /// Is the given declaration allowed to use a forbidden type?
5000 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5001 // Private ivars are always okay. Unfortunately, people don't
5002 // always properly make their ivars private, even in system headers.
5003 // Plus we need to make fields okay, too.
5004 // Function declarations in sys headers will be marked unavailable.
5005 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5006 !isa<FunctionDecl>(decl))
5009 // Require it to be declared in a system header.
5010 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5013 /// Handle a delayed forbidden-type diagnostic.
5014 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5016 if (decl && isForbiddenTypeAllowed(S, decl)) {
5017 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
5018 "this system declaration uses an unsupported type",
5022 if (S.getLangOpts().ObjCAutoRefCount)
5023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5024 // FIXME: we may want to suppress diagnostics for all
5025 // kind of forbidden type messages on unavailable functions.
5026 if (FD->hasAttr<UnavailableAttr>() &&
5027 diag.getForbiddenTypeDiagnostic() ==
5028 diag::err_arc_array_param_no_ownership) {
5029 diag.Triggered = true;
5034 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5035 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5036 diag.Triggered = true;
5040 static bool isDeclDeprecated(Decl *D) {
5042 if (D->isDeprecated())
5044 // A category implicitly has the availability of the interface.
5045 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5046 return CatD->getClassInterface()->isDeprecated();
5047 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5051 static bool isDeclUnavailable(Decl *D) {
5053 if (D->isUnavailable())
5055 // A category implicitly has the availability of the interface.
5056 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5057 return CatD->getClassInterface()->isUnavailable();
5058 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5062 static void DoEmitAvailabilityWarning(Sema &S, DelayedDiagnostic::DDKind K,
5063 Decl *Ctx, const NamedDecl *D,
5064 StringRef Message, SourceLocation Loc,
5065 const ObjCInterfaceDecl *UnknownObjCClass,
5066 const ObjCPropertyDecl *ObjCProperty,
5067 bool ObjCPropertyAccess) {
5068 // Diagnostics for deprecated or unavailable.
5069 unsigned diag, diag_message, diag_fwdclass_message;
5071 // Matches 'diag::note_property_attribute' options.
5072 unsigned property_note_select;
5074 // Matches diag::note_availability_specified_here.
5075 unsigned available_here_select_kind;
5077 // Don't warn if our current context is deprecated or unavailable.
5079 case DelayedDiagnostic::Deprecation:
5080 if (isDeclDeprecated(Ctx))
5082 diag = !ObjCPropertyAccess ? diag::warn_deprecated
5083 : diag::warn_property_method_deprecated;
5084 diag_message = diag::warn_deprecated_message;
5085 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5086 property_note_select = /* deprecated */ 0;
5087 available_here_select_kind = /* deprecated */ 2;
5090 case DelayedDiagnostic::Unavailable:
5091 if (isDeclUnavailable(Ctx))
5093 diag = !ObjCPropertyAccess ? diag::err_unavailable
5094 : diag::err_property_method_unavailable;
5095 diag_message = diag::err_unavailable_message;
5096 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5097 property_note_select = /* unavailable */ 1;
5098 available_here_select_kind = /* unavailable */ 0;
5102 llvm_unreachable("Neither a deprecation or unavailable kind");
5105 if (!Message.empty()) {
5106 S.Diag(Loc, diag_message) << D << Message;
5108 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5109 << ObjCProperty->getDeclName() << property_note_select;
5110 } else if (!UnknownObjCClass) {
5111 S.Diag(Loc, diag) << D;
5113 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5114 << ObjCProperty->getDeclName() << property_note_select;
5116 S.Diag(Loc, diag_fwdclass_message) << D;
5117 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5120 S.Diag(D->getLocation(), diag::note_availability_specified_here)
5121 << D << available_here_select_kind;
5124 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5126 DD.Triggered = true;
5127 DoEmitAvailabilityWarning(S, (DelayedDiagnostic::DDKind)DD.Kind, Ctx,
5128 DD.getDeprecationDecl(), DD.getDeprecationMessage(),
5129 DD.Loc, DD.getUnknownObjCClass(),
5130 DD.getObjCProperty(), false);
5133 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5134 assert(DelayedDiagnostics.getCurrentPool());
5135 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5136 DelayedDiagnostics.popWithoutEmitting(state);
5138 // When delaying diagnostics to run in the context of a parsed
5139 // declaration, we only want to actually emit anything if parsing
5143 // We emit all the active diagnostics in this pool or any of its
5144 // parents. In general, we'll get one pool for the decl spec
5145 // and a child pool for each declarator; in a decl group like:
5146 // deprecated_typedef foo, *bar, baz();
5147 // only the declarator pops will be passed decls. This is correct;
5148 // we really do need to consider delayed diagnostics from the decl spec
5149 // for each of the different declarations.
5150 const DelayedDiagnosticPool *pool = &poppedPool;
5152 for (DelayedDiagnosticPool::pool_iterator
5153 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5154 // This const_cast is a bit lame. Really, Triggered should be mutable.
5155 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5159 switch (diag.Kind) {
5160 case DelayedDiagnostic::Deprecation:
5161 case DelayedDiagnostic::Unavailable:
5162 // Don't bother giving deprecation/unavailable diagnostics if
5163 // the decl is invalid.
5164 if (!decl->isInvalidDecl())
5165 handleDelayedAvailabilityCheck(*this, diag, decl);
5168 case DelayedDiagnostic::Access:
5169 HandleDelayedAccessCheck(diag, decl);
5172 case DelayedDiagnostic::ForbiddenType:
5173 handleDelayedForbiddenType(*this, diag, decl);
5177 } while ((pool = pool->getParent()));
5180 /// Given a set of delayed diagnostics, re-emit them as if they had
5181 /// been delayed in the current context instead of in the given pool.
5182 /// Essentially, this just moves them to the current pool.
5183 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5184 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5185 assert(curPool && "re-emitting in undelayed context not supported");
5186 curPool->steal(pool);
5189 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5190 NamedDecl *D, StringRef Message,
5192 const ObjCInterfaceDecl *UnknownObjCClass,
5193 const ObjCPropertyDecl *ObjCProperty,
5194 bool ObjCPropertyAccess) {
5195 // Delay if we're currently parsing a declaration.
5196 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
5197 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5198 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5199 ObjCPropertyAccess));
5203 Decl *Ctx = cast<Decl>(getCurLexicalContext());
5204 DelayedDiagnostic::DDKind K;
5206 case AD_Deprecation:
5207 K = DelayedDiagnostic::Deprecation;
5209 case AD_Unavailable:
5210 K = DelayedDiagnostic::Unavailable;
5214 DoEmitAvailabilityWarning(*this, K, Ctx, D, Message, Loc,
5215 UnknownObjCClass, ObjCProperty, ObjCPropertyAccess);