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 "TargetAttributesSema.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/DelayedDiagnostic.h"
26 #include "clang/Sema/Lookup.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace clang;
31 /// These constants match the enumerated choices of
32 /// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
33 enum AttributeDeclKind {
36 ExpectedVariableOrFunction,
37 ExpectedFunctionOrMethod,
39 ExpectedFunctionMethodOrBlock,
40 ExpectedFunctionMethodOrParameter,
44 ExpectedVariableFunctionOrLabel,
45 ExpectedFieldOrGlobalVar,
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 static const FunctionType *getFunctionType(const Decl *D,
55 bool blocksToo = true) {
57 if (const ValueDecl *decl = dyn_cast<ValueDecl>(D))
59 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(D))
61 else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(D))
62 Ty = decl->getUnderlyingType();
66 if (Ty->isFunctionPointerType())
67 Ty = Ty->getAs<PointerType>()->getPointeeType();
68 else if (blocksToo && Ty->isBlockPointerType())
69 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
71 return Ty->getAs<FunctionType>();
74 // FIXME: We should provide an abstraction around a method or function
75 // to provide the following bits of information.
77 /// isFunction - Return true if the given decl has function
78 /// type (function or function-typed variable).
79 static bool isFunction(const Decl *D) {
80 return getFunctionType(D, false) != NULL;
83 /// isFunctionOrMethod - Return true if the given decl has function
84 /// type (function or function-typed variable) or an Objective-C
86 static bool isFunctionOrMethod(const Decl *D) {
87 return isFunction(D) || isa<ObjCMethodDecl>(D);
90 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
91 /// type (function or function-typed variable) or an Objective-C
92 /// method or a block.
93 static bool isFunctionOrMethodOrBlock(const Decl *D) {
94 if (isFunctionOrMethod(D))
96 // check for block is more involved.
97 if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
98 QualType Ty = V->getType();
99 return Ty->isBlockPointerType();
101 return isa<BlockDecl>(D);
104 /// Return true if the given decl has a declarator that should have
105 /// been processed by Sema::GetTypeForDeclarator.
106 static bool hasDeclarator(const Decl *D) {
107 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
108 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
109 isa<ObjCPropertyDecl>(D);
112 /// hasFunctionProto - Return true if the given decl has a argument
113 /// information. This decl should have already passed
114 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
115 static bool hasFunctionProto(const Decl *D) {
116 if (const FunctionType *FnTy = getFunctionType(D))
117 return isa<FunctionProtoType>(FnTy);
119 assert(isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D));
124 /// getFunctionOrMethodNumArgs - Return number of function or method
125 /// arguments. It is an error to call this on a K&R function (use
126 /// hasFunctionProto first).
127 static unsigned getFunctionOrMethodNumArgs(const Decl *D) {
128 if (const FunctionType *FnTy = getFunctionType(D))
129 return cast<FunctionProtoType>(FnTy)->getNumArgs();
130 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
131 return BD->getNumParams();
132 return cast<ObjCMethodDecl>(D)->param_size();
135 static QualType getFunctionOrMethodArgType(const Decl *D, unsigned Idx) {
136 if (const FunctionType *FnTy = getFunctionType(D))
137 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
138 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
139 return BD->getParamDecl(Idx)->getType();
141 return cast<ObjCMethodDecl>(D)->param_begin()[Idx]->getType();
144 static QualType getFunctionOrMethodResultType(const Decl *D) {
145 if (const FunctionType *FnTy = getFunctionType(D))
146 return cast<FunctionProtoType>(FnTy)->getResultType();
147 return cast<ObjCMethodDecl>(D)->getResultType();
150 static bool isFunctionOrMethodVariadic(const Decl *D) {
151 if (const FunctionType *FnTy = getFunctionType(D)) {
152 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
153 return proto->isVariadic();
154 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
155 return BD->isVariadic();
157 return cast<ObjCMethodDecl>(D)->isVariadic();
161 static bool isInstanceMethod(const Decl *D) {
162 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
163 return MethodDecl->isInstance();
167 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
168 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
172 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
176 IdentifierInfo* ClsName = Cls->getIdentifier();
178 // FIXME: Should we walk the chain of classes?
179 return ClsName == &Ctx.Idents.get("NSString") ||
180 ClsName == &Ctx.Idents.get("NSMutableString");
183 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
184 const PointerType *PT = T->getAs<PointerType>();
188 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
192 const RecordDecl *RD = RT->getDecl();
193 if (RD->getTagKind() != TTK_Struct)
196 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
199 /// \brief Check if the attribute has exactly as many args as Num. May
201 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
203 if (Attr.getNumArgs() != Num) {
204 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Num;
212 /// \brief Check if the attribute has at least as many args as Num. May
214 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
216 if (Attr.getNumArgs() < Num) {
217 S.Diag(Attr.getLoc(), diag::err_attribute_too_few_arguments) << Num;
225 /// \brief Check if passed in Decl is a field or potentially shared global var
226 /// \return true if the Decl is a field or potentially shared global variable
228 static bool mayBeSharedVariable(const Decl *D) {
229 if (isa<FieldDecl>(D))
231 if (const VarDecl *vd = dyn_cast<VarDecl>(D))
232 return (vd->hasGlobalStorage() && !(vd->isThreadSpecified()));
237 /// \brief Check if the passed-in expression is of type int or bool.
238 static bool isIntOrBool(Expr *Exp) {
239 QualType QT = Exp->getType();
240 return QT->isBooleanType() || QT->isIntegerType();
244 // Check to see if the type is a smart pointer of some kind. We assume
245 // it's a smart pointer if it defines both operator-> and operator*.
246 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
247 DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
248 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
249 if (Res1.first == Res1.second)
252 DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
253 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
254 if (Res2.first == Res2.second)
260 /// \brief Check if passed in Decl is a pointer type.
261 /// Note that this function may produce an error message.
262 /// \return true if the Decl is a pointer type; false otherwise
263 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
264 const AttributeList &Attr) {
265 if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) {
266 QualType QT = vd->getType();
267 if (QT->isAnyPointerType())
270 if (const RecordType *RT = QT->getAs<RecordType>()) {
271 // If it's an incomplete type, it could be a smart pointer; skip it.
272 // (We don't want to force template instantiation if we can avoid it,
273 // since that would alter the order in which templates are instantiated.)
274 if (RT->isIncompleteType())
277 if (threadSafetyCheckIsSmartPointer(S, RT))
281 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
282 << Attr.getName()->getName() << QT;
284 S.Diag(Attr.getLoc(), diag::err_attribute_can_be_applied_only_to_value_decl)
290 /// \brief Checks that the passed in QualType either is of RecordType or points
291 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
292 static const RecordType *getRecordType(QualType QT) {
293 if (const RecordType *RT = QT->getAs<RecordType>())
296 // Now check if we point to record type.
297 if (const PointerType *PT = QT->getAs<PointerType>())
298 return PT->getPointeeType()->getAs<RecordType>();
304 static bool checkBaseClassIsLockableCallback(const CXXBaseSpecifier *Specifier,
305 CXXBasePath &Path, void *Unused) {
306 const RecordType *RT = Specifier->getType()->getAs<RecordType>();
307 if (RT->getDecl()->getAttr<LockableAttr>())
313 /// \brief Thread Safety Analysis: Checks that the passed in RecordType
314 /// resolves to a lockable object.
315 static void checkForLockableRecord(Sema &S, Decl *D, const AttributeList &Attr,
317 const RecordType *RT = getRecordType(Ty);
319 // Warn if could not get record type for this argument.
321 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_class)
322 << Attr.getName() << Ty.getAsString();
326 // Don't check for lockable if the class hasn't been defined yet.
327 if (RT->isIncompleteType())
330 // Allow smart pointers to be used as lockable objects.
331 // FIXME -- Check the type that the smart pointer points to.
332 if (threadSafetyCheckIsSmartPointer(S, RT))
335 // Check if the type is lockable.
336 RecordDecl *RD = RT->getDecl();
337 if (RD->getAttr<LockableAttr>())
340 // Else check if any base classes are lockable.
341 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
342 CXXBasePaths BPaths(false, false);
343 if (CRD->lookupInBases(checkBaseClassIsLockableCallback, 0, BPaths))
347 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
348 << Attr.getName() << Ty.getAsString();
351 /// \brief Thread Safety Analysis: Checks that all attribute arguments, starting
352 /// from Sidx, resolve to a lockable object.
353 /// \param Sidx The attribute argument index to start checking with.
354 /// \param ParamIdxOk Whether an argument can be indexing into a function
356 static void checkAttrArgsAreLockableObjs(Sema &S, Decl *D,
357 const AttributeList &Attr,
358 SmallVectorImpl<Expr*> &Args,
360 bool ParamIdxOk = false) {
361 for(unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
362 Expr *ArgExp = Attr.getArg(Idx);
364 if (ArgExp->isTypeDependent()) {
365 // FIXME -- need to check this again on template instantiation
366 Args.push_back(ArgExp);
370 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
371 // Ignore empty strings without warnings
372 if (StrLit->getLength() == 0)
375 // We allow constant strings to be used as a placeholder for expressions
376 // that are not valid C++ syntax, but warn that they are ignored.
377 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
382 QualType ArgTy = ArgExp->getType();
384 // A pointer to member expression of the form &MyClass::mu is treated
385 // specially -- we need to look at the type of the member.
386 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
387 if (UOp->getOpcode() == UO_AddrOf)
388 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
389 if (DRE->getDecl()->isCXXInstanceMember())
390 ArgTy = DRE->getDecl()->getType();
392 // First see if we can just cast to record type, or point to record type.
393 const RecordType *RT = getRecordType(ArgTy);
395 // Now check if we index into a record type function param.
396 if(!RT && ParamIdxOk) {
397 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
398 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
400 unsigned int NumParams = FD->getNumParams();
401 llvm::APInt ArgValue = IL->getValue();
402 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
403 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
404 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
405 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
406 << Attr.getName() << Idx + 1 << NumParams;
409 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
413 checkForLockableRecord(S, D, Attr, ArgTy);
415 Args.push_back(ArgExp);
419 //===----------------------------------------------------------------------===//
420 // Attribute Implementations
421 //===----------------------------------------------------------------------===//
423 // FIXME: All this manual attribute parsing code is gross. At the
424 // least add some helper functions to check most argument patterns (#
425 // and types of args).
427 enum ThreadAttributeDeclKind {
428 ThreadExpectedFieldOrGlobalVar,
429 ThreadExpectedFunctionOrMethod,
430 ThreadExpectedClassOrStruct
433 static bool checkGuardedVarAttrCommon(Sema &S, Decl *D,
434 const AttributeList &Attr) {
435 assert(!Attr.isInvalid());
437 if (!checkAttributeNumArgs(S, Attr, 0))
440 // D must be either a member field or global (potentially shared) variable.
441 if (!mayBeSharedVariable(D)) {
442 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
443 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
450 static void handleGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr) {
451 if (!checkGuardedVarAttrCommon(S, D, Attr))
454 D->addAttr(::new (S.Context) GuardedVarAttr(Attr.getRange(), S.Context));
457 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
458 const AttributeList &Attr) {
459 if (!checkGuardedVarAttrCommon(S, D, Attr))
462 if (!threadSafetyCheckIsPointer(S, D, Attr))
465 D->addAttr(::new (S.Context) PtGuardedVarAttr(Attr.getRange(), S.Context));
468 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
469 const AttributeList &Attr,
471 assert(!Attr.isInvalid());
473 if (!checkAttributeNumArgs(S, Attr, 1))
476 // D must be either a member field or global (potentially shared) variable.
477 if (!mayBeSharedVariable(D)) {
478 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
479 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
483 SmallVector<Expr*, 1> Args;
484 // check that all arguments are lockable objects
485 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
486 unsigned Size = Args.size();
495 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
497 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
500 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg));
503 static void handlePtGuardedByAttr(Sema &S, Decl *D,
504 const AttributeList &Attr) {
506 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
509 if (!threadSafetyCheckIsPointer(S, D, Attr))
512 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
516 static bool checkLockableAttrCommon(Sema &S, Decl *D,
517 const AttributeList &Attr) {
518 assert(!Attr.isInvalid());
520 if (!checkAttributeNumArgs(S, Attr, 0))
523 // FIXME: Lockable structs for C code.
524 if (!isa<CXXRecordDecl>(D)) {
525 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
526 << Attr.getName() << ThreadExpectedClassOrStruct;
533 static void handleLockableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
534 if (!checkLockableAttrCommon(S, D, Attr))
537 D->addAttr(::new (S.Context) LockableAttr(Attr.getRange(), S.Context));
540 static void handleScopedLockableAttr(Sema &S, Decl *D,
541 const AttributeList &Attr) {
542 if (!checkLockableAttrCommon(S, D, Attr))
545 D->addAttr(::new (S.Context) ScopedLockableAttr(Attr.getRange(), S.Context));
548 static void handleNoThreadSafetyAttr(Sema &S, Decl *D,
549 const AttributeList &Attr) {
550 assert(!Attr.isInvalid());
552 if (!checkAttributeNumArgs(S, Attr, 0))
555 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
556 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
557 << Attr.getName() << ThreadExpectedFunctionOrMethod;
561 D->addAttr(::new (S.Context) NoThreadSafetyAnalysisAttr(Attr.getRange(),
565 static void handleNoAddressSafetyAttr(Sema &S, Decl *D,
566 const AttributeList &Attr) {
567 assert(!Attr.isInvalid());
569 if (!checkAttributeNumArgs(S, Attr, 0))
572 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
573 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
574 << Attr.getName() << ExpectedFunctionOrMethod;
578 D->addAttr(::new (S.Context) NoAddressSafetyAnalysisAttr(Attr.getRange(),
582 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
583 const AttributeList &Attr,
584 SmallVector<Expr*, 1> &Args) {
585 assert(!Attr.isInvalid());
587 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
590 // D must be either a member field or global (potentially shared) variable.
591 ValueDecl *VD = dyn_cast<ValueDecl>(D);
592 if (!VD || !mayBeSharedVariable(D)) {
593 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
594 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
598 // Check that this attribute only applies to lockable types.
599 QualType QT = VD->getType();
600 if (!QT->isDependentType()) {
601 const RecordType *RT = getRecordType(QT);
602 if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
603 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
609 // Check that all arguments are lockable objects.
610 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
611 if (Args.size() == 0)
617 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
618 const AttributeList &Attr) {
619 SmallVector<Expr*, 1> Args;
620 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
623 Expr **StartArg = &Args[0];
624 D->addAttr(::new (S.Context) AcquiredAfterAttr(Attr.getRange(), S.Context,
625 StartArg, Args.size()));
628 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
629 const AttributeList &Attr) {
630 SmallVector<Expr*, 1> Args;
631 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
634 Expr **StartArg = &Args[0];
635 D->addAttr(::new (S.Context) AcquiredBeforeAttr(Attr.getRange(), S.Context,
636 StartArg, Args.size()));
639 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
640 const AttributeList &Attr,
641 SmallVector<Expr*, 1> &Args) {
642 assert(!Attr.isInvalid());
644 // zero or more arguments ok
646 // check that the attribute is applied to a function
647 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
648 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
649 << Attr.getName() << ThreadExpectedFunctionOrMethod;
653 // check that all arguments are lockable objects
654 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
659 static void handleSharedLockFunctionAttr(Sema &S, Decl *D,
660 const AttributeList &Attr) {
661 SmallVector<Expr*, 1> Args;
662 if (!checkLockFunAttrCommon(S, D, Attr, Args))
665 unsigned Size = Args.size();
666 Expr **StartArg = Size == 0 ? 0 : &Args[0];
667 D->addAttr(::new (S.Context) SharedLockFunctionAttr(Attr.getRange(),
672 static void handleExclusiveLockFunctionAttr(Sema &S, Decl *D,
673 const AttributeList &Attr) {
674 SmallVector<Expr*, 1> Args;
675 if (!checkLockFunAttrCommon(S, D, Attr, Args))
678 unsigned Size = Args.size();
679 Expr **StartArg = Size == 0 ? 0 : &Args[0];
680 D->addAttr(::new (S.Context) ExclusiveLockFunctionAttr(Attr.getRange(),
685 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
686 const AttributeList &Attr,
687 SmallVector<Expr*, 2> &Args) {
688 assert(!Attr.isInvalid());
690 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
693 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
694 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
695 << Attr.getName() << ThreadExpectedFunctionOrMethod;
699 if (!isIntOrBool(Attr.getArg(0))) {
700 S.Diag(Attr.getLoc(), diag::err_attribute_first_argument_not_int_or_bool)
705 // check that all arguments are lockable objects
706 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 1);
711 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
712 const AttributeList &Attr) {
713 SmallVector<Expr*, 2> Args;
714 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
717 unsigned Size = Args.size();
718 Expr **StartArg = Size == 0 ? 0 : &Args[0];
719 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(Attr.getRange(),
725 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
726 const AttributeList &Attr) {
727 SmallVector<Expr*, 2> Args;
728 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
731 unsigned Size = Args.size();
732 Expr **StartArg = Size == 0 ? 0 : &Args[0];
733 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(Attr.getRange(),
739 static bool checkLocksRequiredCommon(Sema &S, Decl *D,
740 const AttributeList &Attr,
741 SmallVector<Expr*, 1> &Args) {
742 assert(!Attr.isInvalid());
744 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
747 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
748 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
749 << Attr.getName() << ThreadExpectedFunctionOrMethod;
753 // check that all arguments are lockable objects
754 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
755 if (Args.size() == 0)
761 static void handleExclusiveLocksRequiredAttr(Sema &S, Decl *D,
762 const AttributeList &Attr) {
763 SmallVector<Expr*, 1> Args;
764 if (!checkLocksRequiredCommon(S, D, Attr, Args))
767 Expr **StartArg = &Args[0];
768 D->addAttr(::new (S.Context) ExclusiveLocksRequiredAttr(Attr.getRange(),
774 static void handleSharedLocksRequiredAttr(Sema &S, Decl *D,
775 const AttributeList &Attr) {
776 SmallVector<Expr*, 1> Args;
777 if (!checkLocksRequiredCommon(S, D, Attr, Args))
780 Expr **StartArg = &Args[0];
781 D->addAttr(::new (S.Context) SharedLocksRequiredAttr(Attr.getRange(),
787 static void handleUnlockFunAttr(Sema &S, Decl *D,
788 const AttributeList &Attr) {
789 assert(!Attr.isInvalid());
791 // zero or more arguments ok
793 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
794 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
795 << Attr.getName() << ThreadExpectedFunctionOrMethod;
799 // check that all arguments are lockable objects
800 SmallVector<Expr*, 1> Args;
801 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
802 unsigned Size = Args.size();
803 Expr **StartArg = Size == 0 ? 0 : &Args[0];
805 D->addAttr(::new (S.Context) UnlockFunctionAttr(Attr.getRange(), S.Context,
809 static void handleLockReturnedAttr(Sema &S, Decl *D,
810 const AttributeList &Attr) {
811 assert(!Attr.isInvalid());
813 if (!checkAttributeNumArgs(S, Attr, 1))
815 Expr *Arg = Attr.getArg(0);
817 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
818 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
819 << Attr.getName() << ThreadExpectedFunctionOrMethod;
823 if (Arg->isTypeDependent())
826 // check that the argument is lockable object
827 SmallVector<Expr*, 1> Args;
828 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
829 unsigned Size = Args.size();
833 D->addAttr(::new (S.Context) LockReturnedAttr(Attr.getRange(), S.Context,
837 static void handleLocksExcludedAttr(Sema &S, Decl *D,
838 const AttributeList &Attr) {
839 assert(!Attr.isInvalid());
841 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
844 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
845 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
846 << Attr.getName() << ThreadExpectedFunctionOrMethod;
850 // check that all arguments are lockable objects
851 SmallVector<Expr*, 1> Args;
852 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
853 unsigned Size = Args.size();
856 Expr **StartArg = &Args[0];
858 D->addAttr(::new (S.Context) LocksExcludedAttr(Attr.getRange(), S.Context,
863 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
864 const AttributeList &Attr) {
865 TypedefNameDecl *tDecl = dyn_cast<TypedefNameDecl>(D);
867 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
871 QualType curType = tDecl->getUnderlyingType();
875 // Special case where the argument is a template id.
876 if (Attr.getParameterName()) {
878 SourceLocation TemplateKWLoc;
880 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
882 ExprResult Size = S.ActOnIdExpression(scope, SS, TemplateKWLoc, id,
884 if (Size.isInvalid())
887 sizeExpr = Size.get();
889 // check the attribute arguments.
890 if (!checkAttributeNumArgs(S, Attr, 1))
893 sizeExpr = Attr.getArg(0);
896 // Instantiate/Install the vector type, and let Sema build the type for us.
897 // This will run the reguired checks.
898 QualType T = S.BuildExtVectorType(curType, sizeExpr, Attr.getLoc());
900 // FIXME: preserve the old source info.
901 tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
903 // Remember this typedef decl, we will need it later for diagnostics.
904 S.ExtVectorDecls.push_back(tDecl);
908 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
909 // check the attribute arguments.
910 if (!checkAttributeNumArgs(S, Attr, 0))
913 if (TagDecl *TD = dyn_cast<TagDecl>(D))
914 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
915 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
916 // If the alignment is less than or equal to 8 bits, the packed attribute
918 if (!FD->getType()->isIncompleteType() &&
919 S.Context.getTypeAlign(FD->getType()) <= 8)
920 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
921 << Attr.getName() << FD->getType();
923 FD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
925 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
928 static void handleMsStructAttr(Sema &S, Decl *D, const AttributeList &Attr) {
929 if (TagDecl *TD = dyn_cast<TagDecl>(D))
930 TD->addAttr(::new (S.Context) MsStructAttr(Attr.getRange(), S.Context));
932 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
935 static void handleIBAction(Sema &S, Decl *D, const AttributeList &Attr) {
936 // check the attribute arguments.
937 if (!checkAttributeNumArgs(S, Attr, 0))
940 // The IBAction attributes only apply to instance methods.
941 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
942 if (MD->isInstanceMethod()) {
943 D->addAttr(::new (S.Context) IBActionAttr(Attr.getRange(), S.Context));
947 S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
950 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
951 // The IBOutlet/IBOutletCollection attributes only apply to instance
952 // variables or properties of Objective-C classes. The outlet must also
953 // have an object reference type.
954 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
955 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
956 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
957 << Attr.getName() << VD->getType() << 0;
961 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
962 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
963 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
964 << Attr.getName() << PD->getType() << 1;
969 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
976 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
977 // check the attribute arguments.
978 if (!checkAttributeNumArgs(S, Attr, 0))
981 if (!checkIBOutletCommon(S, D, Attr))
984 D->addAttr(::new (S.Context) IBOutletAttr(Attr.getRange(), S.Context));
987 static void handleIBOutletCollection(Sema &S, Decl *D,
988 const AttributeList &Attr) {
990 // The iboutletcollection attribute can have zero or one arguments.
991 if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
992 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
996 if (!checkIBOutletCommon(S, D, Attr))
999 IdentifierInfo *II = Attr.getParameterName();
1001 II = &S.Context.Idents.get("NSObject");
1003 ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
1004 S.getScopeForContext(D->getDeclContext()->getParent()));
1006 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1009 QualType QT = TypeRep.get();
1010 // Diagnose use of non-object type in iboutletcollection attribute.
1011 // FIXME. Gnu attribute extension ignores use of builtin types in
1012 // attributes. So, __attribute__((iboutletcollection(char))) will be
1013 // treated as __attribute__((iboutletcollection())).
1014 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1015 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1018 D->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getRange(),S.Context,
1019 QT, Attr.getParameterLoc()));
1022 static void possibleTransparentUnionPointerType(QualType &T) {
1023 if (const RecordType *UT = T->getAsUnionType())
1024 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1025 RecordDecl *UD = UT->getDecl();
1026 for (RecordDecl::field_iterator it = UD->field_begin(),
1027 itend = UD->field_end(); it != itend; ++it) {
1028 QualType QT = it->getType();
1029 if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
1037 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1038 if (!isFunctionOrMethod(D)) {
1039 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1040 << "alloc_size" << ExpectedFunctionOrMethod;
1044 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1047 // In C++ the implicit 'this' function parameter also counts, and they are
1048 // counted from one.
1049 bool HasImplicitThisParam = isInstanceMethod(D);
1050 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1052 SmallVector<unsigned, 8> SizeArgs;
1054 for (AttributeList::arg_iterator I = Attr.arg_begin(),
1055 E = Attr.arg_end(); I!=E; ++I) {
1056 // The argument must be an integer constant expression.
1058 llvm::APSInt ArgNum;
1059 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
1060 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
1061 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1062 << "alloc_size" << Ex->getSourceRange();
1066 uint64_t x = ArgNum.getZExtValue();
1068 if (x < 1 || x > NumArgs) {
1069 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1070 << "alloc_size" << I.getArgNum() << Ex->getSourceRange();
1075 if (HasImplicitThisParam) {
1077 S.Diag(Attr.getLoc(),
1078 diag::err_attribute_invalid_implicit_this_argument)
1079 << "alloc_size" << Ex->getSourceRange();
1085 // check if the function argument is of an integer type
1086 QualType T = getFunctionOrMethodArgType(D, x).getNonReferenceType();
1087 if (!T->isIntegerType()) {
1088 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1089 << "alloc_size" << Ex->getSourceRange();
1093 SizeArgs.push_back(x);
1096 // check if the function returns a pointer
1097 if (!getFunctionType(D)->getResultType()->isAnyPointerType()) {
1098 S.Diag(Attr.getLoc(), diag::warn_ns_attribute_wrong_return_type)
1099 << "alloc_size" << 0 /*function*/<< 1 /*pointer*/ << D->getSourceRange();
1102 D->addAttr(::new (S.Context) AllocSizeAttr(Attr.getRange(), S.Context,
1103 SizeArgs.data(), SizeArgs.size()));
1106 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1107 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
1108 // ignore it as well
1109 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
1110 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1111 << Attr.getName() << ExpectedFunction;
1115 // In C++ the implicit 'this' function parameter also counts, and they are
1116 // counted from one.
1117 bool HasImplicitThisParam = isInstanceMethod(D);
1118 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1120 // The nonnull attribute only applies to pointers.
1121 SmallVector<unsigned, 10> NonNullArgs;
1123 for (AttributeList::arg_iterator I=Attr.arg_begin(),
1124 E=Attr.arg_end(); I!=E; ++I) {
1127 // The argument must be an integer constant expression.
1129 llvm::APSInt ArgNum(32);
1130 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
1131 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
1132 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1133 << "nonnull" << Ex->getSourceRange();
1137 unsigned x = (unsigned) ArgNum.getZExtValue();
1139 if (x < 1 || x > NumArgs) {
1140 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1141 << "nonnull" << I.getArgNum() << Ex->getSourceRange();
1146 if (HasImplicitThisParam) {
1148 S.Diag(Attr.getLoc(),
1149 diag::err_attribute_invalid_implicit_this_argument)
1150 << "nonnull" << Ex->getSourceRange();
1156 // Is the function argument a pointer type?
1157 QualType T = getFunctionOrMethodArgType(D, x).getNonReferenceType();
1158 possibleTransparentUnionPointerType(T);
1160 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1161 // FIXME: Should also highlight argument in decl.
1162 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
1163 << "nonnull" << Ex->getSourceRange();
1167 NonNullArgs.push_back(x);
1170 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1171 // arguments have a nonnull attribute.
1172 if (NonNullArgs.empty()) {
1173 for (unsigned I = 0, E = getFunctionOrMethodNumArgs(D); I != E; ++I) {
1174 QualType T = getFunctionOrMethodArgType(D, I).getNonReferenceType();
1175 possibleTransparentUnionPointerType(T);
1176 if (T->isAnyPointerType() || T->isBlockPointerType())
1177 NonNullArgs.push_back(I);
1180 // No pointer arguments?
1181 if (NonNullArgs.empty()) {
1182 // Warn the trivial case only if attribute is not coming from a
1183 // macro instantiation.
1184 if (Attr.getLoc().isFileID())
1185 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1190 unsigned* start = &NonNullArgs[0];
1191 unsigned size = NonNullArgs.size();
1192 llvm::array_pod_sort(start, start + size);
1193 D->addAttr(::new (S.Context) NonNullAttr(Attr.getRange(), S.Context, start,
1197 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1198 // This attribute must be applied to a function declaration.
1199 // The first argument to the attribute must be a string,
1200 // the name of the resource, for example "malloc".
1201 // The following arguments must be argument indexes, the arguments must be
1202 // of integer type for Returns, otherwise of pointer type.
1203 // The difference between Holds and Takes is that a pointer may still be used
1204 // after being held. free() should be __attribute((ownership_takes)), whereas
1205 // a list append function may well be __attribute((ownership_holds)).
1207 if (!AL.getParameterName()) {
1208 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
1209 << AL.getName()->getName() << 1;
1212 // Figure out our Kind, and check arguments while we're at it.
1213 OwnershipAttr::OwnershipKind K;
1214 switch (AL.getKind()) {
1215 case AttributeList::AT_ownership_takes:
1216 K = OwnershipAttr::Takes;
1217 if (AL.getNumArgs() < 1) {
1218 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1222 case AttributeList::AT_ownership_holds:
1223 K = OwnershipAttr::Holds;
1224 if (AL.getNumArgs() < 1) {
1225 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1229 case AttributeList::AT_ownership_returns:
1230 K = OwnershipAttr::Returns;
1231 if (AL.getNumArgs() > 1) {
1232 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
1233 << AL.getNumArgs() + 1;
1238 // This should never happen given how we are called.
1239 llvm_unreachable("Unknown ownership attribute");
1242 if (!isFunction(D) || !hasFunctionProto(D)) {
1243 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
1244 << AL.getName() << ExpectedFunction;
1248 // In C++ the implicit 'this' function parameter also counts, and they are
1249 // counted from one.
1250 bool HasImplicitThisParam = isInstanceMethod(D);
1251 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1253 StringRef Module = AL.getParameterName()->getName();
1255 // Normalize the argument, __foo__ becomes foo.
1256 if (Module.startswith("__") && Module.endswith("__"))
1257 Module = Module.substr(2, Module.size() - 4);
1259 SmallVector<unsigned, 10> OwnershipArgs;
1261 for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
1265 llvm::APSInt ArgNum(32);
1266 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1267 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1268 S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
1269 << AL.getName()->getName() << IdxExpr->getSourceRange();
1273 unsigned x = (unsigned) ArgNum.getZExtValue();
1275 if (x > NumArgs || x < 1) {
1276 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
1277 << AL.getName()->getName() << x << IdxExpr->getSourceRange();
1281 if (HasImplicitThisParam) {
1283 S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1284 << "ownership" << IdxExpr->getSourceRange();
1291 case OwnershipAttr::Takes:
1292 case OwnershipAttr::Holds: {
1293 // Is the function argument a pointer type?
1294 QualType T = getFunctionOrMethodArgType(D, x);
1295 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1296 // FIXME: Should also highlight argument in decl.
1297 S.Diag(AL.getLoc(), diag::err_ownership_type)
1298 << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
1300 << IdxExpr->getSourceRange();
1305 case OwnershipAttr::Returns: {
1306 if (AL.getNumArgs() > 1) {
1307 // Is the function argument an integer type?
1308 Expr *IdxExpr = AL.getArg(0);
1309 llvm::APSInt ArgNum(32);
1310 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1311 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1312 S.Diag(AL.getLoc(), diag::err_ownership_type)
1313 << "ownership_returns" << "integer"
1314 << IdxExpr->getSourceRange();
1322 // Check we don't have a conflict with another ownership attribute.
1323 for (specific_attr_iterator<OwnershipAttr>
1324 i = D->specific_attr_begin<OwnershipAttr>(),
1325 e = D->specific_attr_end<OwnershipAttr>();
1327 if ((*i)->getOwnKind() != K) {
1328 for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
1331 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1332 << AL.getName()->getName() << "ownership_*";
1337 OwnershipArgs.push_back(x);
1340 unsigned* start = OwnershipArgs.data();
1341 unsigned size = OwnershipArgs.size();
1342 llvm::array_pod_sort(start, start + size);
1344 if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
1345 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1349 D->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, K, Module,
1353 /// Whether this declaration has internal linkage for the purposes of
1354 /// things that want to complain about things not have internal linkage.
1355 static bool hasEffectivelyInternalLinkage(NamedDecl *D) {
1356 switch (D->getLinkage()) {
1358 case InternalLinkage:
1361 // Template instantiations that go from external to unique-external
1362 // shouldn't get diagnosed.
1363 case UniqueExternalLinkage:
1366 case ExternalLinkage:
1369 llvm_unreachable("unknown linkage kind!");
1372 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1373 // Check the attribute arguments.
1374 if (Attr.getNumArgs() > 1) {
1375 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1379 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1380 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1381 << Attr.getName() << ExpectedVariableOrFunction;
1385 NamedDecl *nd = cast<NamedDecl>(D);
1389 // static int a __attribute__((weakref ("v2")));
1390 // static int b() __attribute__((weakref ("f3")));
1392 // and ignores the attributes of
1394 // static int a __attribute__((weakref ("v2")));
1397 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1398 if (!Ctx->isFileContext()) {
1399 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
1400 nd->getNameAsString();
1404 // The GCC manual says
1406 // At present, a declaration to which `weakref' is attached can only
1411 // Without a TARGET,
1412 // given as an argument to `weakref' or to `alias', `weakref' is
1413 // equivalent to `weak'.
1415 // gcc 4.4.1 will accept
1416 // int a7 __attribute__((weakref));
1418 // int a7 __attribute__((weak));
1419 // This looks like a bug in gcc. We reject that for now. We should revisit
1420 // it if this behaviour is actually used.
1422 if (!hasEffectivelyInternalLinkage(nd)) {
1423 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static);
1428 // static ((alias ("y"), weakref)).
1429 // Should we? How to check that weakref is before or after alias?
1431 if (Attr.getNumArgs() == 1) {
1432 Expr *Arg = Attr.getArg(0);
1433 Arg = Arg->IgnoreParenCasts();
1434 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1436 if (!Str || !Str->isAscii()) {
1437 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1441 // GCC will accept anything as the argument of weakref. Should we
1442 // check for an existing decl?
1443 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1447 D->addAttr(::new (S.Context) WeakRefAttr(Attr.getRange(), S.Context));
1450 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1451 // check the attribute arguments.
1452 if (Attr.getNumArgs() != 1) {
1453 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1457 Expr *Arg = Attr.getArg(0);
1458 Arg = Arg->IgnoreParenCasts();
1459 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1461 if (!Str || !Str->isAscii()) {
1462 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1467 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1468 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1472 // FIXME: check if target symbol exists in current file
1474 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1478 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1479 // Check the attribute arguments.
1480 if (!checkAttributeNumArgs(S, Attr, 0))
1483 if (!isa<FunctionDecl>(D)) {
1484 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1485 << Attr.getName() << ExpectedFunction;
1489 if (D->hasAttr<HotAttr>()) {
1490 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1491 << Attr.getName() << "hot";
1495 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context));
1498 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1499 // Check the attribute arguments.
1500 if (!checkAttributeNumArgs(S, Attr, 0))
1503 if (!isa<FunctionDecl>(D)) {
1504 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1505 << Attr.getName() << ExpectedFunction;
1509 if (D->hasAttr<ColdAttr>()) {
1510 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1511 << Attr.getName() << "cold";
1515 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context));
1518 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1519 // Check the attribute arguments.
1520 if (!checkAttributeNumArgs(S, Attr, 0))
1523 if (!isa<FunctionDecl>(D)) {
1524 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1525 << Attr.getName() << ExpectedFunction;
1529 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context));
1532 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
1533 const AttributeList &Attr) {
1534 // Check the attribute arguments.
1535 if (Attr.hasParameterOrArguments()) {
1536 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1540 if (!isa<FunctionDecl>(D)) {
1541 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1542 << Attr.getName() << ExpectedFunction;
1546 D->addAttr(::new (S.Context) AlwaysInlineAttr(Attr.getRange(), S.Context));
1549 static void handleTLSModelAttr(Sema &S, Decl *D,
1550 const AttributeList &Attr) {
1551 // Check the attribute arguments.
1552 if (Attr.getNumArgs() != 1) {
1553 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1557 Expr *Arg = Attr.getArg(0);
1558 Arg = Arg->IgnoreParenCasts();
1559 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1561 // Check that it is a string.
1563 S.Diag(Attr.getLoc(), diag::err_attribute_not_string) << "tls_model";
1567 if (!isa<VarDecl>(D) || !cast<VarDecl>(D)->isThreadSpecified()) {
1568 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1569 << Attr.getName() << ExpectedTLSVar;
1573 // Check that the value.
1574 StringRef Model = Str->getString();
1575 if (Model != "global-dynamic" && Model != "local-dynamic"
1576 && Model != "initial-exec" && Model != "local-exec") {
1577 S.Diag(Attr.getLoc(), diag::err_attr_tlsmodel_arg);
1581 D->addAttr(::new (S.Context) TLSModelAttr(Attr.getRange(), S.Context,
1585 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1586 // Check the attribute arguments.
1587 if (Attr.hasParameterOrArguments()) {
1588 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1593 QualType RetTy = FD->getResultType();
1594 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1595 D->addAttr(::new (S.Context) MallocAttr(Attr.getRange(), S.Context));
1600 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1603 static void handleMayAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1604 // check the attribute arguments.
1605 if (!checkAttributeNumArgs(S, Attr, 0))
1608 D->addAttr(::new (S.Context) MayAliasAttr(Attr.getRange(), S.Context));
1611 static void handleNoCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1612 assert(!Attr.isInvalid());
1613 if (isa<VarDecl>(D))
1614 D->addAttr(::new (S.Context) NoCommonAttr(Attr.getRange(), S.Context));
1616 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1617 << Attr.getName() << ExpectedVariable;
1620 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1621 assert(!Attr.isInvalid());
1622 if (isa<VarDecl>(D))
1623 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context));
1625 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1626 << Attr.getName() << ExpectedVariable;
1629 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1630 if (hasDeclarator(D)) return;
1632 if (S.CheckNoReturnAttr(attr)) return;
1634 if (!isa<ObjCMethodDecl>(D)) {
1635 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1636 << attr.getName() << ExpectedFunctionOrMethod;
1640 D->addAttr(::new (S.Context) NoReturnAttr(attr.getRange(), S.Context));
1643 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1644 if (attr.hasParameterOrArguments()) {
1645 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1653 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1654 const AttributeList &Attr) {
1656 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1657 // because 'analyzer_noreturn' does not impact the type.
1659 if(!checkAttributeNumArgs(S, Attr, 0))
1662 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1663 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1664 if (VD == 0 || (!VD->getType()->isBlockPointerType()
1665 && !VD->getType()->isFunctionPointerType())) {
1666 S.Diag(Attr.getLoc(),
1667 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1668 : diag::warn_attribute_wrong_decl_type)
1669 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1674 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getRange(), S.Context));
1677 // PS3 PPU-specific.
1678 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1680 Returning a Vector Class in Registers
1682 According to the PPU ABI specifications, a class with a single member of
1683 vector type is returned in memory when used as the return value of a function.
1684 This results in inefficient code when implementing vector classes. To return
1685 the value in a single vector register, add the vecreturn attribute to the
1686 class definition. This attribute is also applicable to struct types.
1692 __vector float xyzw;
1693 } __attribute__((vecreturn));
1695 Vector Add(Vector lhs, Vector rhs)
1698 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1699 return result; // This will be returned in a register
1702 if (!isa<RecordDecl>(D)) {
1703 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1704 << Attr.getName() << ExpectedClass;
1708 if (D->getAttr<VecReturnAttr>()) {
1709 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
1713 RecordDecl *record = cast<RecordDecl>(D);
1716 if (!isa<CXXRecordDecl>(record)) {
1717 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1721 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1722 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1726 for (RecordDecl::field_iterator iter = record->field_begin();
1727 iter != record->field_end(); iter++) {
1728 if ((count == 1) || !iter->getType()->isVectorType()) {
1729 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1735 D->addAttr(::new (S.Context) VecReturnAttr(Attr.getRange(), S.Context));
1738 static void handleDependencyAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1739 if (!isFunctionOrMethod(D) && !isa<ParmVarDecl>(D)) {
1740 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1741 << Attr.getName() << ExpectedFunctionMethodOrParameter;
1744 // FIXME: Actually store the attribute on the declaration
1747 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1748 // check the attribute arguments.
1749 if (Attr.hasParameterOrArguments()) {
1750 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1754 if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isFunctionOrMethod(D) &&
1755 !isa<TypeDecl>(D) && !isa<LabelDecl>(D) && !isa<FieldDecl>(D)) {
1756 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1757 << Attr.getName() << ExpectedVariableFunctionOrLabel;
1761 D->addAttr(::new (S.Context) UnusedAttr(Attr.getRange(), S.Context));
1764 static void handleReturnsTwiceAttr(Sema &S, Decl *D,
1765 const AttributeList &Attr) {
1766 // check the attribute arguments.
1767 if (Attr.hasParameterOrArguments()) {
1768 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1772 if (!isa<FunctionDecl>(D)) {
1773 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1774 << Attr.getName() << ExpectedFunction;
1778 D->addAttr(::new (S.Context) ReturnsTwiceAttr(Attr.getRange(), S.Context));
1781 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1782 // check the attribute arguments.
1783 if (Attr.hasParameterOrArguments()) {
1784 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1788 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1789 if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
1790 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
1793 } else if (!isFunctionOrMethod(D)) {
1794 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1795 << Attr.getName() << ExpectedVariableOrFunction;
1799 D->addAttr(::new (S.Context) UsedAttr(Attr.getRange(), S.Context));
1802 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1803 // check the attribute arguments.
1804 if (Attr.getNumArgs() > 1) {
1805 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1809 int priority = 65535; // FIXME: Do not hardcode such constants.
1810 if (Attr.getNumArgs() > 0) {
1811 Expr *E = Attr.getArg(0);
1812 llvm::APSInt Idx(32);
1813 if (E->isTypeDependent() || E->isValueDependent() ||
1814 !E->isIntegerConstantExpr(Idx, S.Context)) {
1815 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1816 << "constructor" << 1 << E->getSourceRange();
1819 priority = Idx.getZExtValue();
1822 if (!isa<FunctionDecl>(D)) {
1823 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1824 << Attr.getName() << ExpectedFunction;
1828 D->addAttr(::new (S.Context) ConstructorAttr(Attr.getRange(), S.Context,
1832 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1833 // check the attribute arguments.
1834 if (Attr.getNumArgs() > 1) {
1835 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1839 int priority = 65535; // FIXME: Do not hardcode such constants.
1840 if (Attr.getNumArgs() > 0) {
1841 Expr *E = Attr.getArg(0);
1842 llvm::APSInt Idx(32);
1843 if (E->isTypeDependent() || E->isValueDependent() ||
1844 !E->isIntegerConstantExpr(Idx, S.Context)) {
1845 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1846 << "destructor" << 1 << E->getSourceRange();
1849 priority = Idx.getZExtValue();
1852 if (!isa<FunctionDecl>(D)) {
1853 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1854 << Attr.getName() << ExpectedFunction;
1858 D->addAttr(::new (S.Context) DestructorAttr(Attr.getRange(), S.Context,
1862 template <typename AttrTy>
1863 static void handleAttrWithMessage(Sema &S, Decl *D, const AttributeList &Attr,
1865 unsigned NumArgs = Attr.getNumArgs();
1867 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1871 // Handle the case where the attribute has a text message.
1874 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
1876 S.Diag(Attr.getArg(0)->getLocStart(), diag::err_attribute_not_string)
1880 Str = SE->getString();
1883 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str));
1886 static void handleArcWeakrefUnavailableAttr(Sema &S, Decl *D,
1887 const AttributeList &Attr) {
1888 unsigned NumArgs = Attr.getNumArgs();
1890 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
1894 D->addAttr(::new (S.Context) ArcWeakrefUnavailableAttr(
1895 Attr.getRange(), S.Context));
1898 static void handleObjCRootClassAttr(Sema &S, Decl *D,
1899 const AttributeList &Attr) {
1900 if (!isa<ObjCInterfaceDecl>(D)) {
1901 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
1905 unsigned NumArgs = Attr.getNumArgs();
1907 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
1911 D->addAttr(::new (S.Context) ObjCRootClassAttr(Attr.getRange(), S.Context));
1914 static void handleObjCRequiresPropertyDefsAttr(Sema &S, Decl *D,
1915 const AttributeList &Attr) {
1916 if (!isa<ObjCInterfaceDecl>(D)) {
1917 S.Diag(Attr.getLoc(), diag::err_suppress_autosynthesis);
1921 unsigned NumArgs = Attr.getNumArgs();
1923 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
1927 D->addAttr(::new (S.Context) ObjCRequiresPropertyDefsAttr(
1928 Attr.getRange(), S.Context));
1931 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1932 IdentifierInfo *Platform,
1933 VersionTuple Introduced,
1934 VersionTuple Deprecated,
1935 VersionTuple Obsoleted) {
1936 StringRef PlatformName
1937 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1938 if (PlatformName.empty())
1939 PlatformName = Platform->getName();
1941 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1942 // of these steps are needed).
1943 if (!Introduced.empty() && !Deprecated.empty() &&
1944 !(Introduced <= Deprecated)) {
1945 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1946 << 1 << PlatformName << Deprecated.getAsString()
1947 << 0 << Introduced.getAsString();
1951 if (!Introduced.empty() && !Obsoleted.empty() &&
1952 !(Introduced <= Obsoleted)) {
1953 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1954 << 2 << PlatformName << Obsoleted.getAsString()
1955 << 0 << Introduced.getAsString();
1959 if (!Deprecated.empty() && !Obsoleted.empty() &&
1960 !(Deprecated <= Obsoleted)) {
1961 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1962 << 2 << PlatformName << Obsoleted.getAsString()
1963 << 1 << Deprecated.getAsString();
1970 AvailabilityAttr *Sema::mergeAvailabilityAttr(Decl *D, SourceRange Range,
1971 IdentifierInfo *Platform,
1972 VersionTuple Introduced,
1973 VersionTuple Deprecated,
1974 VersionTuple Obsoleted,
1976 StringRef Message) {
1977 VersionTuple MergedIntroduced = Introduced;
1978 VersionTuple MergedDeprecated = Deprecated;
1979 VersionTuple MergedObsoleted = Obsoleted;
1980 bool FoundAny = false;
1982 if (D->hasAttrs()) {
1983 AttrVec &Attrs = D->getAttrs();
1984 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1985 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1991 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1992 if (OldPlatform != Platform) {
1998 VersionTuple OldIntroduced = OldAA->getIntroduced();
1999 VersionTuple OldDeprecated = OldAA->getDeprecated();
2000 VersionTuple OldObsoleted = OldAA->getObsoleted();
2001 bool OldIsUnavailable = OldAA->getUnavailable();
2002 StringRef OldMessage = OldAA->getMessage();
2004 if ((!OldIntroduced.empty() && !Introduced.empty() &&
2005 OldIntroduced != Introduced) ||
2006 (!OldDeprecated.empty() && !Deprecated.empty() &&
2007 OldDeprecated != Deprecated) ||
2008 (!OldObsoleted.empty() && !Obsoleted.empty() &&
2009 OldObsoleted != Obsoleted) ||
2010 (OldIsUnavailable != IsUnavailable) ||
2011 (OldMessage != Message)) {
2012 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2013 Diag(Range.getBegin(), diag::note_previous_attribute);
2014 Attrs.erase(Attrs.begin() + i);
2019 VersionTuple MergedIntroduced2 = MergedIntroduced;
2020 VersionTuple MergedDeprecated2 = MergedDeprecated;
2021 VersionTuple MergedObsoleted2 = MergedObsoleted;
2023 if (MergedIntroduced2.empty())
2024 MergedIntroduced2 = OldIntroduced;
2025 if (MergedDeprecated2.empty())
2026 MergedDeprecated2 = OldDeprecated;
2027 if (MergedObsoleted2.empty())
2028 MergedObsoleted2 = OldObsoleted;
2030 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2031 MergedIntroduced2, MergedDeprecated2,
2032 MergedObsoleted2)) {
2033 Attrs.erase(Attrs.begin() + i);
2038 MergedIntroduced = MergedIntroduced2;
2039 MergedDeprecated = MergedDeprecated2;
2040 MergedObsoleted = MergedObsoleted2;
2046 MergedIntroduced == Introduced &&
2047 MergedDeprecated == Deprecated &&
2048 MergedObsoleted == Obsoleted)
2051 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2052 MergedDeprecated, MergedObsoleted)) {
2053 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2054 Introduced, Deprecated,
2055 Obsoleted, IsUnavailable, Message);
2060 static void handleAvailabilityAttr(Sema &S, Decl *D,
2061 const AttributeList &Attr) {
2062 IdentifierInfo *Platform = Attr.getParameterName();
2063 SourceLocation PlatformLoc = Attr.getParameterLoc();
2065 if (AvailabilityAttr::getPrettyPlatformName(Platform->getName()).empty())
2066 S.Diag(PlatformLoc, diag::warn_availability_unknown_platform)
2069 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2070 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2071 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2072 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2074 const StringLiteral *SE =
2075 dyn_cast_or_null<const StringLiteral>(Attr.getMessageExpr());
2077 Str = SE->getString();
2079 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(D, Attr.getRange(),
2084 IsUnavailable, Str);
2086 D->addAttr(NewAttr);
2089 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2090 VisibilityAttr::VisibilityType Vis) {
2091 if (isa<TypedefNameDecl>(D)) {
2092 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "visibility";
2095 VisibilityAttr *ExistingAttr = D->getAttr<VisibilityAttr>();
2097 VisibilityAttr::VisibilityType ExistingVis = ExistingAttr->getVisibility();
2098 if (ExistingVis == Vis)
2100 Diag(ExistingAttr->getLocation(), diag::err_mismatched_visibility);
2101 Diag(Range.getBegin(), diag::note_previous_attribute);
2102 D->dropAttr<VisibilityAttr>();
2104 return ::new (Context) VisibilityAttr(Range, Context, Vis);
2107 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2108 // check the attribute arguments.
2109 if(!checkAttributeNumArgs(S, Attr, 1))
2112 Expr *Arg = Attr.getArg(0);
2113 Arg = Arg->IgnoreParenCasts();
2114 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2116 if (!Str || !Str->isAscii()) {
2117 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2118 << "visibility" << 1;
2122 StringRef TypeStr = Str->getString();
2123 VisibilityAttr::VisibilityType type;
2125 if (TypeStr == "default")
2126 type = VisibilityAttr::Default;
2127 else if (TypeStr == "hidden")
2128 type = VisibilityAttr::Hidden;
2129 else if (TypeStr == "internal")
2130 type = VisibilityAttr::Hidden; // FIXME
2131 else if (TypeStr == "protected") {
2132 // Complain about attempts to use protected visibility on targets
2133 // (like Darwin) that don't support it.
2134 if (!S.Context.getTargetInfo().hasProtectedVisibility()) {
2135 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2136 type = VisibilityAttr::Default;
2138 type = VisibilityAttr::Protected;
2141 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
2145 VisibilityAttr *NewAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type);
2147 D->addAttr(NewAttr);
2150 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2151 const AttributeList &Attr) {
2152 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
2154 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2159 if (Attr.getNumArgs() != 0 || !Attr.getParameterName()) {
2160 if (!Attr.getParameterName() && Attr.getNumArgs() == 1) {
2161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2162 << "objc_method_family" << 1;
2164 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2170 StringRef param = Attr.getParameterName()->getName();
2171 ObjCMethodFamilyAttr::FamilyKind family;
2172 if (param == "none")
2173 family = ObjCMethodFamilyAttr::OMF_None;
2174 else if (param == "alloc")
2175 family = ObjCMethodFamilyAttr::OMF_alloc;
2176 else if (param == "copy")
2177 family = ObjCMethodFamilyAttr::OMF_copy;
2178 else if (param == "init")
2179 family = ObjCMethodFamilyAttr::OMF_init;
2180 else if (param == "mutableCopy")
2181 family = ObjCMethodFamilyAttr::OMF_mutableCopy;
2182 else if (param == "new")
2183 family = ObjCMethodFamilyAttr::OMF_new;
2185 // Just warn and ignore it. This is future-proof against new
2186 // families being used in system headers.
2187 S.Diag(Attr.getParameterLoc(), diag::warn_unknown_method_family);
2191 if (family == ObjCMethodFamilyAttr::OMF_init &&
2192 !method->getResultType()->isObjCObjectPointerType()) {
2193 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2194 << method->getResultType();
2195 // Ignore the attribute.
2199 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2200 S.Context, family));
2203 static void handleObjCExceptionAttr(Sema &S, Decl *D,
2204 const AttributeList &Attr) {
2205 if (!checkAttributeNumArgs(S, Attr, 0))
2208 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
2210 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
2214 D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getRange(), S.Context));
2217 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2218 if (Attr.getNumArgs() != 0) {
2219 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2222 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2223 QualType T = TD->getUnderlyingType();
2224 if (!T->isPointerType() ||
2225 !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
2226 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2230 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2231 QualType T = PD->getType();
2232 if (!T->isPointerType() ||
2233 !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
2234 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2239 // It is okay to include this attribute on properties, e.g.:
2241 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2243 // In this case it follows tradition and suppresses an error in the above
2245 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2247 D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getRange(), S.Context));
2251 handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2252 if (Attr.getNumArgs() != 0) {
2253 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2257 if (!isa<FunctionDecl>(D)) {
2258 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
2262 D->addAttr(::new (S.Context) OverloadableAttr(Attr.getRange(), S.Context));
2265 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2266 if (!Attr.getParameterName()) {
2267 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2272 if (Attr.getNumArgs() != 0) {
2273 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2277 BlocksAttr::BlockType type;
2278 if (Attr.getParameterName()->isStr("byref"))
2279 type = BlocksAttr::ByRef;
2281 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2282 << "blocks" << Attr.getParameterName();
2286 D->addAttr(::new (S.Context) BlocksAttr(Attr.getRange(), S.Context, type));
2289 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2290 // check the attribute arguments.
2291 if (Attr.getNumArgs() > 2) {
2292 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2296 unsigned sentinel = 0;
2297 if (Attr.getNumArgs() > 0) {
2298 Expr *E = Attr.getArg(0);
2299 llvm::APSInt Idx(32);
2300 if (E->isTypeDependent() || E->isValueDependent() ||
2301 !E->isIntegerConstantExpr(Idx, S.Context)) {
2302 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2303 << "sentinel" << 1 << E->getSourceRange();
2307 if (Idx.isSigned() && Idx.isNegative()) {
2308 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2309 << E->getSourceRange();
2313 sentinel = Idx.getZExtValue();
2316 unsigned nullPos = 0;
2317 if (Attr.getNumArgs() > 1) {
2318 Expr *E = Attr.getArg(1);
2319 llvm::APSInt Idx(32);
2320 if (E->isTypeDependent() || E->isValueDependent() ||
2321 !E->isIntegerConstantExpr(Idx, S.Context)) {
2322 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2323 << "sentinel" << 2 << E->getSourceRange();
2326 nullPos = Idx.getZExtValue();
2328 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2329 // FIXME: This error message could be improved, it would be nice
2330 // to say what the bounds actually are.
2331 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2332 << E->getSourceRange();
2337 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2338 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2339 if (isa<FunctionNoProtoType>(FT)) {
2340 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2344 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2345 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2348 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2349 if (!MD->isVariadic()) {
2350 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2353 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2354 if (!BD->isVariadic()) {
2355 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2358 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2359 QualType Ty = V->getType();
2360 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2361 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
2362 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2363 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2364 int m = Ty->isFunctionPointerType() ? 0 : 1;
2365 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2369 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2370 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2374 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2375 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2378 D->addAttr(::new (S.Context) SentinelAttr(Attr.getRange(), S.Context, sentinel,
2382 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2383 // check the attribute arguments.
2384 if (!checkAttributeNumArgs(S, Attr, 0))
2387 if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
2388 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2389 << Attr.getName() << ExpectedFunctionOrMethod;
2393 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
2394 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2395 << Attr.getName() << 0;
2398 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2399 if (MD->getResultType()->isVoidType()) {
2400 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2401 << Attr.getName() << 1;
2405 D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getRange(), S.Context));
2408 static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2409 // check the attribute arguments.
2410 if (Attr.hasParameterOrArguments()) {
2411 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2415 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
2416 if (isa<CXXRecordDecl>(D)) {
2417 D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2420 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2421 << Attr.getName() << ExpectedVariableOrFunction;
2425 NamedDecl *nd = cast<NamedDecl>(D);
2427 // 'weak' only applies to declarations with external linkage.
2428 if (hasEffectivelyInternalLinkage(nd)) {
2429 S.Diag(Attr.getLoc(), diag::err_attribute_weak_static);
2433 nd->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2436 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2437 // check the attribute arguments.
2438 if (!checkAttributeNumArgs(S, Attr, 0))
2442 // weak_import only applies to variable & function declarations.
2444 if (!D->canBeWeakImported(isDef)) {
2446 S.Diag(Attr.getLoc(),
2447 diag::warn_attribute_weak_import_invalid_on_definition)
2448 << "weak_import" << 2 /*variable and function*/;
2449 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2450 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2451 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2452 // Nothing to warn about here.
2454 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2455 << Attr.getName() << ExpectedVariableOrFunction;
2460 D->addAttr(::new (S.Context) WeakImportAttr(Attr.getRange(), S.Context));
2463 // Handles reqd_work_group_size and work_group_size_hint.
2464 static void handleWorkGroupSize(Sema &S, Decl *D,
2465 const AttributeList &Attr) {
2466 assert(Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2467 || Attr.getKind() == AttributeList::AT_WorkGroupSizeHint);
2469 // Attribute has 3 arguments.
2470 if (!checkAttributeNumArgs(S, Attr, 3)) return;
2473 for (unsigned i = 0; i < 3; ++i) {
2474 Expr *E = Attr.getArg(i);
2475 llvm::APSInt ArgNum(32);
2476 if (E->isTypeDependent() || E->isValueDependent() ||
2477 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
2478 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2479 << Attr.getName()->getName() << E->getSourceRange();
2482 WGSize[i] = (unsigned) ArgNum.getZExtValue();
2485 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2486 && D->hasAttr<ReqdWorkGroupSizeAttr>()) {
2487 ReqdWorkGroupSizeAttr *A = D->getAttr<ReqdWorkGroupSizeAttr>();
2488 if (!(A->getXDim() == WGSize[0] &&
2489 A->getYDim() == WGSize[1] &&
2490 A->getZDim() == WGSize[2])) {
2491 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2496 if (Attr.getKind() == AttributeList::AT_WorkGroupSizeHint
2497 && D->hasAttr<WorkGroupSizeHintAttr>()) {
2498 WorkGroupSizeHintAttr *A = D->getAttr<WorkGroupSizeHintAttr>();
2499 if (!(A->getXDim() == WGSize[0] &&
2500 A->getYDim() == WGSize[1] &&
2501 A->getZDim() == WGSize[2])) {
2502 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2507 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize)
2508 D->addAttr(::new (S.Context)
2509 ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
2510 WGSize[0], WGSize[1], WGSize[2]));
2512 D->addAttr(::new (S.Context)
2513 WorkGroupSizeHintAttr(Attr.getRange(), S.Context,
2514 WGSize[0], WGSize[1], WGSize[2]));
2517 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2519 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2520 if (ExistingAttr->getName() == Name)
2522 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2523 Diag(Range.getBegin(), diag::note_previous_attribute);
2526 return ::new (Context) SectionAttr(Range, Context, Name);
2529 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2530 // Attribute has no arguments.
2531 if (!checkAttributeNumArgs(S, Attr, 1))
2534 // Make sure that there is a string literal as the sections's single
2536 Expr *ArgExpr = Attr.getArg(0);
2537 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
2539 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
2543 // If the target wants to validate the section specifier, make it happen.
2544 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(SE->getString());
2545 if (!Error.empty()) {
2546 S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
2551 // This attribute cannot be applied to local variables.
2552 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2553 S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
2556 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(),
2559 D->addAttr(NewAttr);
2563 static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2564 // check the attribute arguments.
2565 if (Attr.hasParameterOrArguments()) {
2566 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2570 if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2571 if (Existing->getLocation().isInvalid())
2572 Existing->setRange(Attr.getRange());
2574 D->addAttr(::new (S.Context) NoThrowAttr(Attr.getRange(), S.Context));
2578 static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2579 // check the attribute arguments.
2580 if (Attr.hasParameterOrArguments()) {
2581 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2585 if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2586 if (Existing->getLocation().isInvalid())
2587 Existing->setRange(Attr.getRange());
2589 D->addAttr(::new (S.Context) ConstAttr(Attr.getRange(), S.Context));
2593 static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2594 // check the attribute arguments.
2595 if (!checkAttributeNumArgs(S, Attr, 0))
2598 D->addAttr(::new (S.Context) PureAttr(Attr.getRange(), S.Context));
2601 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2602 if (!Attr.getParameterName()) {
2603 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2607 if (Attr.getNumArgs() != 0) {
2608 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2612 VarDecl *VD = dyn_cast<VarDecl>(D);
2614 if (!VD || !VD->hasLocalStorage()) {
2615 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
2619 // Look up the function
2620 // FIXME: Lookup probably isn't looking in the right place
2621 NamedDecl *CleanupDecl
2622 = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
2623 Attr.getParameterLoc(), Sema::LookupOrdinaryName);
2625 S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
2626 Attr.getParameterName();
2630 FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
2632 S.Diag(Attr.getParameterLoc(),
2633 diag::err_attribute_cleanup_arg_not_function)
2634 << Attr.getParameterName();
2638 if (FD->getNumParams() != 1) {
2639 S.Diag(Attr.getParameterLoc(),
2640 diag::err_attribute_cleanup_func_must_take_one_arg)
2641 << Attr.getParameterName();
2645 // We're currently more strict than GCC about what function types we accept.
2646 // If this ever proves to be a problem it should be easy to fix.
2647 QualType Ty = S.Context.getPointerType(VD->getType());
2648 QualType ParamTy = FD->getParamDecl(0)->getType();
2649 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2650 ParamTy, Ty) != Sema::Compatible) {
2651 S.Diag(Attr.getParameterLoc(),
2652 diag::err_attribute_cleanup_func_arg_incompatible_type) <<
2653 Attr.getParameterName() << ParamTy << Ty;
2657 D->addAttr(::new (S.Context) CleanupAttr(Attr.getRange(), S.Context, FD));
2658 S.MarkFunctionReferenced(Attr.getParameterLoc(), FD);
2661 /// Handle __attribute__((format_arg((idx)))) attribute based on
2662 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2663 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2664 if (!checkAttributeNumArgs(S, Attr, 1))
2667 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2668 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2669 << Attr.getName() << ExpectedFunction;
2673 // In C++ the implicit 'this' function parameter also counts, and they are
2674 // counted from one.
2675 bool HasImplicitThisParam = isInstanceMethod(D);
2676 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2677 unsigned FirstIdx = 1;
2679 // checks for the 2nd argument
2680 Expr *IdxExpr = Attr.getArg(0);
2681 llvm::APSInt Idx(32);
2682 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2683 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2684 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2685 << "format" << 2 << IdxExpr->getSourceRange();
2689 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2690 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2691 << "format" << 2 << IdxExpr->getSourceRange();
2695 unsigned ArgIdx = Idx.getZExtValue() - 1;
2697 if (HasImplicitThisParam) {
2699 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
2700 << "format_arg" << IdxExpr->getSourceRange();
2706 // make sure the format string is really a string
2707 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2709 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2710 if (not_nsstring_type &&
2711 !isCFStringType(Ty, S.Context) &&
2712 (!Ty->isPointerType() ||
2713 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2714 // FIXME: Should highlight the actual expression that has the wrong type.
2715 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2716 << (not_nsstring_type ? "a string type" : "an NSString")
2717 << IdxExpr->getSourceRange();
2720 Ty = getFunctionOrMethodResultType(D);
2721 if (!isNSStringType(Ty, S.Context) &&
2722 !isCFStringType(Ty, S.Context) &&
2723 (!Ty->isPointerType() ||
2724 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2725 // FIXME: Should highlight the actual expression that has the wrong type.
2726 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2727 << (not_nsstring_type ? "string type" : "NSString")
2728 << IdxExpr->getSourceRange();
2732 D->addAttr(::new (S.Context) FormatArgAttr(Attr.getRange(), S.Context,
2733 Idx.getZExtValue()));
2736 enum FormatAttrKind {
2745 /// getFormatAttrKind - Map from format attribute names to supported format
2747 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2748 return llvm::StringSwitch<FormatAttrKind>(Format)
2749 // Check for formats that get handled specially.
2750 .Case("NSString", NSStringFormat)
2751 .Case("CFString", CFStringFormat)
2752 .Case("strftime", StrftimeFormat)
2754 // Otherwise, check for supported formats.
2755 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2756 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2757 .Case("kprintf", SupportedFormat) // OpenBSD.
2759 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2760 .Default(InvalidFormat);
2763 /// Handle __attribute__((init_priority(priority))) attributes based on
2764 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2765 static void handleInitPriorityAttr(Sema &S, Decl *D,
2766 const AttributeList &Attr) {
2767 if (!S.getLangOpts().CPlusPlus) {
2768 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2772 if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
2773 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2777 QualType T = dyn_cast<VarDecl>(D)->getType();
2778 if (S.Context.getAsArrayType(T))
2779 T = S.Context.getBaseElementType(T);
2780 if (!T->getAs<RecordType>()) {
2781 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2786 if (Attr.getNumArgs() != 1) {
2787 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2791 Expr *priorityExpr = Attr.getArg(0);
2793 llvm::APSInt priority(32);
2794 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
2795 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
2796 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2797 << "init_priority" << priorityExpr->getSourceRange();
2801 unsigned prioritynum = priority.getZExtValue();
2802 if (prioritynum < 101 || prioritynum > 65535) {
2803 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2804 << priorityExpr->getSourceRange();
2808 D->addAttr(::new (S.Context) InitPriorityAttr(Attr.getRange(), S.Context,
2812 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
2813 int FormatIdx, int FirstArg) {
2814 // Check whether we already have an equivalent format attribute.
2815 for (specific_attr_iterator<FormatAttr>
2816 i = D->specific_attr_begin<FormatAttr>(),
2817 e = D->specific_attr_end<FormatAttr>();
2820 if (f->getType() == Format &&
2821 f->getFormatIdx() == FormatIdx &&
2822 f->getFirstArg() == FirstArg) {
2823 // If we don't have a valid location for this attribute, adopt the
2825 if (f->getLocation().isInvalid())
2831 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2835 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2836 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2837 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2839 if (!Attr.getParameterName()) {
2840 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2845 if (Attr.getNumArgs() != 2) {
2846 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
2850 if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
2851 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2852 << Attr.getName() << ExpectedFunction;
2856 // In C++ the implicit 'this' function parameter also counts, and they are
2857 // counted from one.
2858 bool HasImplicitThisParam = isInstanceMethod(D);
2859 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2860 unsigned FirstIdx = 1;
2862 StringRef Format = Attr.getParameterName()->getName();
2864 // Normalize the argument, __foo__ becomes foo.
2865 if (Format.startswith("__") && Format.endswith("__"))
2866 Format = Format.substr(2, Format.size() - 4);
2868 // Check for supported formats.
2869 FormatAttrKind Kind = getFormatAttrKind(Format);
2871 if (Kind == IgnoredFormat)
2874 if (Kind == InvalidFormat) {
2875 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2876 << "format" << Attr.getParameterName()->getName();
2880 // checks for the 2nd argument
2881 Expr *IdxExpr = Attr.getArg(0);
2882 llvm::APSInt Idx(32);
2883 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2884 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2885 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2886 << "format" << 2 << IdxExpr->getSourceRange();
2890 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2891 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2892 << "format" << 2 << IdxExpr->getSourceRange();
2896 // FIXME: Do we need to bounds check?
2897 unsigned ArgIdx = Idx.getZExtValue() - 1;
2899 if (HasImplicitThisParam) {
2901 S.Diag(Attr.getLoc(),
2902 diag::err_format_attribute_implicit_this_format_string)
2903 << IdxExpr->getSourceRange();
2909 // make sure the format string is really a string
2910 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2912 if (Kind == CFStringFormat) {
2913 if (!isCFStringType(Ty, S.Context)) {
2914 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2915 << "a CFString" << IdxExpr->getSourceRange();
2918 } else if (Kind == NSStringFormat) {
2919 // FIXME: do we need to check if the type is NSString*? What are the
2921 if (!isNSStringType(Ty, S.Context)) {
2922 // FIXME: Should highlight the actual expression that has the wrong type.
2923 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2924 << "an NSString" << IdxExpr->getSourceRange();
2927 } else if (!Ty->isPointerType() ||
2928 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2929 // FIXME: Should highlight the actual expression that has the wrong type.
2930 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2931 << "a string type" << IdxExpr->getSourceRange();
2935 // check the 3rd argument
2936 Expr *FirstArgExpr = Attr.getArg(1);
2937 llvm::APSInt FirstArg(32);
2938 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
2939 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
2940 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2941 << "format" << 3 << FirstArgExpr->getSourceRange();
2945 // check if the function is variadic if the 3rd argument non-zero
2946 if (FirstArg != 0) {
2947 if (isFunctionOrMethodVariadic(D)) {
2948 ++NumArgs; // +1 for ...
2950 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2955 // strftime requires FirstArg to be 0 because it doesn't read from any
2956 // variable the input is just the current time + the format string.
2957 if (Kind == StrftimeFormat) {
2958 if (FirstArg != 0) {
2959 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2960 << FirstArgExpr->getSourceRange();
2963 // if 0 it disables parameter checking (to use with e.g. va_list)
2964 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2965 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2966 << "format" << 3 << FirstArgExpr->getSourceRange();
2970 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), Format,
2972 FirstArg.getZExtValue());
2974 D->addAttr(NewAttr);
2977 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2978 const AttributeList &Attr) {
2979 // check the attribute arguments.
2980 if (!checkAttributeNumArgs(S, Attr, 0))
2984 // Try to find the underlying union declaration.
2986 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2987 if (TD && TD->getUnderlyingType()->isUnionType())
2988 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2990 RD = dyn_cast<RecordDecl>(D);
2992 if (!RD || !RD->isUnion()) {
2993 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2994 << Attr.getName() << ExpectedUnion;
2998 if (!RD->isCompleteDefinition()) {
2999 S.Diag(Attr.getLoc(),
3000 diag::warn_transparent_union_attribute_not_definition);
3004 RecordDecl::field_iterator Field = RD->field_begin(),
3005 FieldEnd = RD->field_end();
3006 if (Field == FieldEnd) {
3007 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3011 FieldDecl *FirstField = *Field;
3012 QualType FirstType = FirstField->getType();
3013 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3014 S.Diag(FirstField->getLocation(),
3015 diag::warn_transparent_union_attribute_floating)
3016 << FirstType->isVectorType() << FirstType;
3020 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3021 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3022 for (; Field != FieldEnd; ++Field) {
3023 QualType FieldType = Field->getType();
3024 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3025 S.Context.getTypeAlign(FieldType) != FirstAlign) {
3026 // Warn if we drop the attribute.
3027 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3028 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3029 : S.Context.getTypeAlign(FieldType);
3030 S.Diag(Field->getLocation(),
3031 diag::warn_transparent_union_attribute_field_size_align)
3032 << isSize << Field->getDeclName() << FieldBits;
3033 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3034 S.Diag(FirstField->getLocation(),
3035 diag::note_transparent_union_first_field_size_align)
3036 << isSize << FirstBits;
3041 RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getRange(), S.Context));
3044 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3045 // check the attribute arguments.
3046 if (!checkAttributeNumArgs(S, Attr, 1))
3049 Expr *ArgExpr = Attr.getArg(0);
3050 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
3052 // Make sure that there is a string literal as the annotation's single
3055 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
3059 // Don't duplicate annotations that are already set.
3060 for (specific_attr_iterator<AnnotateAttr>
3061 i = D->specific_attr_begin<AnnotateAttr>(),
3062 e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
3063 if ((*i)->getAnnotation() == SE->getString())
3066 D->addAttr(::new (S.Context) AnnotateAttr(Attr.getRange(), S.Context,
3070 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3071 // check the attribute arguments.
3072 if (Attr.getNumArgs() > 1) {
3073 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3077 //FIXME: The C++0x version of this attribute has more limited applicabilty
3078 // than GNU's, and should error out when it is used to specify a
3079 // weaker alignment, rather than being silently ignored.
3081 if (Attr.getNumArgs() == 0) {
3082 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3083 true, 0, Attr.isDeclspecAttribute()));
3087 S.AddAlignedAttr(Attr.getRange(), D, Attr.getArg(0),
3088 Attr.isDeclspecAttribute());
3091 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3093 // FIXME: Handle pack-expansions here.
3094 if (DiagnoseUnexpandedParameterPack(E))
3097 if (E->isTypeDependent() || E->isValueDependent()) {
3098 // Save dependent expressions in the AST to be instantiated.
3099 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E,
3104 SourceLocation AttrLoc = AttrRange.getBegin();
3105 // FIXME: Cache the number on the Attr object?
3106 llvm::APSInt Alignment(32);
3108 = VerifyIntegerConstantExpression(E, &Alignment,
3109 diag::err_aligned_attribute_argument_not_int,
3110 /*AllowFold*/ false);
3111 if (ICE.isInvalid())
3113 if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
3114 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
3115 << E->getSourceRange();
3119 // We've already verified it's a power of 2, now let's make sure it's
3121 if (Alignment.getZExtValue() > 8192) {
3122 Diag(AttrLoc, diag::err_attribute_aligned_greater_than_8192)
3123 << E->getSourceRange();
3128 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, ICE.take(),
3132 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3134 // FIXME: Cache the number on the Attr object if non-dependent?
3135 // FIXME: Perform checking of type validity
3136 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3141 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3144 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3145 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3146 /// HImode, not an intermediate pointer.
3147 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3148 // This attribute isn't documented, but glibc uses it. It changes
3149 // the width of an int or unsigned int to the specified size.
3151 // Check that there aren't any arguments
3152 if (!checkAttributeNumArgs(S, Attr, 0))
3156 IdentifierInfo *Name = Attr.getParameterName();
3158 S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
3162 StringRef Str = Attr.getParameterName()->getName();
3164 // Normalize the attribute name, __foo__ becomes foo.
3165 if (Str.startswith("__") && Str.endswith("__"))
3166 Str = Str.substr(2, Str.size() - 4);
3168 unsigned DestWidth = 0;
3169 bool IntegerMode = true;
3170 bool ComplexMode = false;
3171 switch (Str.size()) {
3174 case 'Q': DestWidth = 8; break;
3175 case 'H': DestWidth = 16; break;
3176 case 'S': DestWidth = 32; break;
3177 case 'D': DestWidth = 64; break;
3178 case 'X': DestWidth = 96; break;
3179 case 'T': DestWidth = 128; break;
3181 if (Str[1] == 'F') {
3182 IntegerMode = false;
3183 } else if (Str[1] == 'C') {
3184 IntegerMode = false;
3186 } else if (Str[1] != 'I') {
3191 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3192 // pointer on PIC16 and other embedded platforms.
3194 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3195 else if (Str == "byte")
3196 DestWidth = S.Context.getTargetInfo().getCharWidth();
3199 if (Str == "pointer")
3200 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3205 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3206 OldTy = TD->getUnderlyingType();
3207 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3208 OldTy = VD->getType();
3210 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3211 << "mode" << Attr.getRange();
3215 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3216 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3217 else if (IntegerMode) {
3218 if (!OldTy->isIntegralOrEnumerationType())
3219 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3220 } else if (ComplexMode) {
3221 if (!OldTy->isComplexType())
3222 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3224 if (!OldTy->isFloatingType())
3225 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3228 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3229 // and friends, at least with glibc.
3230 // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
3231 // width on unusual platforms.
3232 // FIXME: Make sure floating-point mappings are accurate
3233 // FIXME: Support XF and TF types
3235 switch (DestWidth) {
3237 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
3240 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3244 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3247 if (OldTy->isSignedIntegerType())
3248 NewTy = S.Context.SignedCharTy;
3250 NewTy = S.Context.UnsignedCharTy;
3254 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3257 if (OldTy->isSignedIntegerType())
3258 NewTy = S.Context.ShortTy;
3260 NewTy = S.Context.UnsignedShortTy;
3264 NewTy = S.Context.FloatTy;
3265 else if (OldTy->isSignedIntegerType())
3266 NewTy = S.Context.IntTy;
3268 NewTy = S.Context.UnsignedIntTy;
3272 NewTy = S.Context.DoubleTy;
3273 else if (OldTy->isSignedIntegerType())
3274 if (S.Context.getTargetInfo().getLongWidth() == 64)
3275 NewTy = S.Context.LongTy;
3277 NewTy = S.Context.LongLongTy;
3279 if (S.Context.getTargetInfo().getLongWidth() == 64)
3280 NewTy = S.Context.UnsignedLongTy;
3282 NewTy = S.Context.UnsignedLongLongTy;
3285 NewTy = S.Context.LongDoubleTy;
3289 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3292 if (OldTy->isSignedIntegerType())
3293 NewTy = S.Context.Int128Ty;
3295 NewTy = S.Context.UnsignedInt128Ty;
3300 NewTy = S.Context.getComplexType(NewTy);
3303 // Install the new type.
3304 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
3305 // FIXME: preserve existing source info.
3306 TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
3308 cast<ValueDecl>(D)->setType(NewTy);
3311 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3312 // check the attribute arguments.
3313 if (!checkAttributeNumArgs(S, Attr, 0))
3316 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3317 if (!VD->hasGlobalStorage())
3318 S.Diag(Attr.getLoc(),
3319 diag::warn_attribute_requires_functions_or_static_globals)
3321 } else if (!isFunctionOrMethod(D)) {
3322 S.Diag(Attr.getLoc(),
3323 diag::warn_attribute_requires_functions_or_static_globals)
3328 D->addAttr(::new (S.Context) NoDebugAttr(Attr.getRange(), S.Context));
3331 static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3332 // check the attribute arguments.
3333 if (!checkAttributeNumArgs(S, Attr, 0))
3337 if (!isa<FunctionDecl>(D)) {
3338 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3339 << Attr.getName() << ExpectedFunction;
3343 D->addAttr(::new (S.Context) NoInlineAttr(Attr.getRange(), S.Context));
3346 static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
3347 const AttributeList &Attr) {
3348 // check the attribute arguments.
3349 if (!checkAttributeNumArgs(S, Attr, 0))
3353 if (!isa<FunctionDecl>(D)) {
3354 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3355 << Attr.getName() << ExpectedFunction;
3359 D->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getRange(),
3363 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3364 if (S.LangOpts.CUDA) {
3365 // check the attribute arguments.
3366 if (Attr.hasParameterOrArguments()) {
3367 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3371 if (!isa<VarDecl>(D)) {
3372 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3373 << Attr.getName() << ExpectedVariable;
3377 D->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getRange(), S.Context));
3379 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
3383 static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3384 if (S.LangOpts.CUDA) {
3385 // check the attribute arguments.
3386 if (Attr.getNumArgs() != 0) {
3387 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3391 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
3392 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3393 << Attr.getName() << ExpectedVariableOrFunction;
3397 D->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getRange(), S.Context));
3399 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
3403 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3404 if (S.LangOpts.CUDA) {
3405 // check the attribute arguments.
3406 if (!checkAttributeNumArgs(S, Attr, 0))
3409 if (!isa<FunctionDecl>(D)) {
3410 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3411 << Attr.getName() << ExpectedFunction;
3415 FunctionDecl *FD = cast<FunctionDecl>(D);
3416 if (!FD->getResultType()->isVoidType()) {
3417 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3418 if (FunctionTypeLoc* FTL = dyn_cast<FunctionTypeLoc>(&TL)) {
3419 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3421 << FixItHint::CreateReplacement(FTL->getResultLoc().getSourceRange(),
3424 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3430 D->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getRange(), S.Context));
3432 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
3436 static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3437 if (S.LangOpts.CUDA) {
3438 // check the attribute arguments.
3439 if (!checkAttributeNumArgs(S, Attr, 0))
3443 if (!isa<FunctionDecl>(D)) {
3444 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3445 << Attr.getName() << ExpectedFunction;
3449 D->addAttr(::new (S.Context) CUDAHostAttr(Attr.getRange(), S.Context));
3451 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
3455 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3456 if (S.LangOpts.CUDA) {
3457 // check the attribute arguments.
3458 if (!checkAttributeNumArgs(S, Attr, 0))
3462 if (!isa<VarDecl>(D)) {
3463 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3464 << Attr.getName() << ExpectedVariable;
3468 D->addAttr(::new (S.Context) CUDASharedAttr(Attr.getRange(), S.Context));
3470 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
3474 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3475 // check the attribute arguments.
3476 if (!checkAttributeNumArgs(S, Attr, 0))
3479 FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
3481 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3482 << Attr.getName() << ExpectedFunction;
3486 if (!Fn->isInlineSpecified()) {
3487 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3491 D->addAttr(::new (S.Context) GNUInlineAttr(Attr.getRange(), S.Context));
3494 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3495 if (hasDeclarator(D)) return;
3497 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3498 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3500 if (S.CheckCallingConvAttr(Attr, CC))
3503 if (!isa<ObjCMethodDecl>(D)) {
3504 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3505 << Attr.getName() << ExpectedFunctionOrMethod;
3509 switch (Attr.getKind()) {
3510 case AttributeList::AT_FastCall:
3511 D->addAttr(::new (S.Context) FastCallAttr(Attr.getRange(), S.Context));
3513 case AttributeList::AT_StdCall:
3514 D->addAttr(::new (S.Context) StdCallAttr(Attr.getRange(), S.Context));
3516 case AttributeList::AT_ThisCall:
3517 D->addAttr(::new (S.Context) ThisCallAttr(Attr.getRange(), S.Context));
3519 case AttributeList::AT_CDecl:
3520 D->addAttr(::new (S.Context) CDeclAttr(Attr.getRange(), S.Context));
3522 case AttributeList::AT_Pascal:
3523 D->addAttr(::new (S.Context) PascalAttr(Attr.getRange(), S.Context));
3525 case AttributeList::AT_Pcs: {
3526 Expr *Arg = Attr.getArg(0);
3527 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3528 if (!Str || !Str->isAscii()) {
3529 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
3535 StringRef StrRef = Str->getString();
3536 PcsAttr::PCSType PCS;
3537 if (StrRef == "aapcs")
3538 PCS = PcsAttr::AAPCS;
3539 else if (StrRef == "aapcs-vfp")
3540 PCS = PcsAttr::AAPCS_VFP;
3542 S.Diag(Attr.getLoc(), diag::err_invalid_pcs);
3547 D->addAttr(::new (S.Context) PcsAttr(Attr.getRange(), S.Context, PCS));
3550 llvm_unreachable("unexpected attribute kind");
3554 static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
3555 assert(!Attr.isInvalid());
3556 D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
3559 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC) {
3560 if (attr.isInvalid())
3563 if ((attr.getNumArgs() != 0 &&
3564 !(attr.getKind() == AttributeList::AT_Pcs && attr.getNumArgs() == 1)) ||
3565 attr.getParameterName()) {
3566 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3571 // TODO: diagnose uses of these conventions on the wrong target. Or, better
3572 // move to TargetAttributesSema one day.
3573 switch (attr.getKind()) {
3574 case AttributeList::AT_CDecl: CC = CC_C; break;
3575 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3576 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3577 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3578 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3579 case AttributeList::AT_Pcs: {
3580 Expr *Arg = attr.getArg(0);
3581 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3582 if (!Str || !Str->isAscii()) {
3583 Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3589 StringRef StrRef = Str->getString();
3590 if (StrRef == "aapcs") {
3593 } else if (StrRef == "aapcs-vfp") {
3599 default: llvm_unreachable("unexpected attribute kind");
3605 static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3606 if (hasDeclarator(D)) return;
3609 if (S.CheckRegparmAttr(Attr, numParams))
3612 if (!isa<ObjCMethodDecl>(D)) {
3613 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3614 << Attr.getName() << ExpectedFunctionOrMethod;
3618 D->addAttr(::new (S.Context) RegparmAttr(Attr.getRange(), S.Context, numParams));
3621 /// Checks a regparm attribute, returning true if it is ill-formed and
3622 /// otherwise setting numParams to the appropriate value.
3623 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3624 if (Attr.isInvalid())
3627 if (Attr.getNumArgs() != 1) {
3628 Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3633 Expr *NumParamsExpr = Attr.getArg(0);
3634 llvm::APSInt NumParams(32);
3635 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
3636 !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
3637 Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3638 << "regparm" << NumParamsExpr->getSourceRange();
3643 if (Context.getTargetInfo().getRegParmMax() == 0) {
3644 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3645 << NumParamsExpr->getSourceRange();
3650 numParams = NumParams.getZExtValue();
3651 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3652 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3653 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3661 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
3662 if (S.LangOpts.CUDA) {
3663 // check the attribute arguments.
3664 if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
3665 // FIXME: 0 is not okay.
3666 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
3670 if (!isFunctionOrMethod(D)) {
3671 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3672 << Attr.getName() << ExpectedFunctionOrMethod;
3676 Expr *MaxThreadsExpr = Attr.getArg(0);
3677 llvm::APSInt MaxThreads(32);
3678 if (MaxThreadsExpr->isTypeDependent() ||
3679 MaxThreadsExpr->isValueDependent() ||
3680 !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
3681 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3682 << "launch_bounds" << 1 << MaxThreadsExpr->getSourceRange();
3686 llvm::APSInt MinBlocks(32);
3687 if (Attr.getNumArgs() > 1) {
3688 Expr *MinBlocksExpr = Attr.getArg(1);
3689 if (MinBlocksExpr->isTypeDependent() ||
3690 MinBlocksExpr->isValueDependent() ||
3691 !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
3692 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3693 << "launch_bounds" << 2 << MinBlocksExpr->getSourceRange();
3698 D->addAttr(::new (S.Context) CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3699 MaxThreads.getZExtValue(),
3700 MinBlocks.getZExtValue()));
3702 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
3706 //===----------------------------------------------------------------------===//
3707 // Checker-specific attribute handlers.
3708 //===----------------------------------------------------------------------===//
3710 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3711 return type->isDependentType() ||
3712 type->isObjCObjectPointerType() ||
3713 S.Context.isObjCNSObjectType(type);
3715 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3716 return type->isDependentType() ||
3717 type->isPointerType() ||
3718 isValidSubjectOfNSAttribute(S, type);
3721 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3722 ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
3724 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3725 << Attr.getRange() << Attr.getName() << ExpectedParameter;
3730 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3731 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3734 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3739 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3740 << Attr.getRange() << Attr.getName() << cf;
3745 param->addAttr(::new (S.Context) CFConsumedAttr(Attr.getRange(), S.Context));
3747 param->addAttr(::new (S.Context) NSConsumedAttr(Attr.getRange(), S.Context));
3750 static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
3751 const AttributeList &Attr) {
3752 if (!isa<ObjCMethodDecl>(D)) {
3753 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3754 << Attr.getRange() << Attr.getName() << ExpectedMethod;
3758 D->addAttr(::new (S.Context) NSConsumesSelfAttr(Attr.getRange(), S.Context));
3761 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3762 const AttributeList &Attr) {
3764 QualType returnType;
3766 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3767 returnType = MD->getResultType();
3768 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3769 returnType = PD->getType();
3770 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3771 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3772 return; // ignore: was handled as a type attribute
3773 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3774 returnType = FD->getResultType();
3776 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3777 << Attr.getRange() << Attr.getName()
3778 << ExpectedFunctionOrMethod;
3784 switch (Attr.getKind()) {
3785 default: llvm_unreachable("invalid ownership attribute");
3786 case AttributeList::AT_NSReturnsAutoreleased:
3787 case AttributeList::AT_NSReturnsRetained:
3788 case AttributeList::AT_NSReturnsNotRetained:
3789 typeOK = isValidSubjectOfNSAttribute(S, returnType);
3793 case AttributeList::AT_CFReturnsRetained:
3794 case AttributeList::AT_CFReturnsNotRetained:
3795 typeOK = isValidSubjectOfCFAttribute(S, returnType);
3801 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3802 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3806 switch (Attr.getKind()) {
3808 llvm_unreachable("invalid ownership attribute");
3809 case AttributeList::AT_NSReturnsAutoreleased:
3810 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(Attr.getRange(),
3813 case AttributeList::AT_CFReturnsNotRetained:
3814 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getRange(),
3817 case AttributeList::AT_NSReturnsNotRetained:
3818 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getRange(),
3821 case AttributeList::AT_CFReturnsRetained:
3822 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getRange(),
3825 case AttributeList::AT_NSReturnsRetained:
3826 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getRange(),
3832 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3833 const AttributeList &attr) {
3834 SourceLocation loc = attr.getLoc();
3836 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
3839 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3840 << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
3844 // Check that the method returns a normal pointer.
3845 QualType resultType = method->getResultType();
3847 if (!resultType->isReferenceType() &&
3848 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3849 S.Diag(method->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3851 << attr.getName() << /*method*/ 1 << /*non-retainable pointer*/ 2;
3853 // Drop the attribute.
3858 ::new (S.Context) ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context));
3861 /// Handle cf_audited_transfer and cf_unknown_transfer.
3862 static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
3863 if (!isa<FunctionDecl>(D)) {
3864 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3865 << A.getRange() << A.getName() << ExpectedFunction;
3869 bool IsAudited = (A.getKind() == AttributeList::AT_CFAuditedTransfer);
3871 // Check whether there's a conflicting attribute already present.
3874 Existing = D->getAttr<CFUnknownTransferAttr>();
3876 Existing = D->getAttr<CFAuditedTransferAttr>();
3879 S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
3881 << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
3882 << A.getRange() << Existing->getRange();
3886 // All clear; add the attribute.
3889 ::new (S.Context) CFAuditedTransferAttr(A.getRange(), S.Context));
3892 ::new (S.Context) CFUnknownTransferAttr(A.getRange(), S.Context));
3896 static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
3897 const AttributeList &Attr) {
3898 RecordDecl *RD = dyn_cast<RecordDecl>(D);
3899 if (!RD || RD->isUnion()) {
3900 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3901 << Attr.getRange() << Attr.getName() << ExpectedStruct;
3904 IdentifierInfo *ParmName = Attr.getParameterName();
3906 // In Objective-C, verify that the type names an Objective-C type.
3907 // We don't want to check this outside of ObjC because people sometimes
3908 // do crazy C declarations of Objective-C types.
3909 if (ParmName && S.getLangOpts().ObjC1) {
3910 // Check for an existing type with this name.
3911 LookupResult R(S, DeclarationName(ParmName), Attr.getParameterLoc(),
3912 Sema::LookupOrdinaryName);
3913 if (S.LookupName(R, Sc)) {
3914 NamedDecl *Target = R.getFoundDecl();
3915 if (Target && !isa<ObjCInterfaceDecl>(Target)) {
3916 S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
3917 S.Diag(Target->getLocStart(), diag::note_declared_at);
3922 D->addAttr(::new (S.Context) NSBridgedAttr(Attr.getRange(), S.Context,
3926 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3927 const AttributeList &Attr) {
3928 if (hasDeclarator(D)) return;
3930 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3931 << Attr.getRange() << Attr.getName() << ExpectedVariable;
3934 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3935 const AttributeList &Attr) {
3936 if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
3937 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3938 << Attr.getRange() << Attr.getName() << ExpectedVariable;
3942 ValueDecl *vd = cast<ValueDecl>(D);
3943 QualType type = vd->getType();
3945 if (!type->isDependentType() &&
3946 !type->isObjCLifetimeType()) {
3947 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3952 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3954 // If we have no lifetime yet, check the lifetime we're presumably
3956 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3957 lifetime = type->getObjCARCImplicitLifetime();
3960 case Qualifiers::OCL_None:
3961 assert(type->isDependentType() &&
3962 "didn't infer lifetime for non-dependent type?");
3965 case Qualifiers::OCL_Weak: // meaningful
3966 case Qualifiers::OCL_Strong: // meaningful
3969 case Qualifiers::OCL_ExplicitNone:
3970 case Qualifiers::OCL_Autoreleasing:
3971 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3972 << (lifetime == Qualifiers::OCL_Autoreleasing);
3976 D->addAttr(::new (S.Context)
3977 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context));
3980 //===----------------------------------------------------------------------===//
3981 // Microsoft specific attribute handlers.
3982 //===----------------------------------------------------------------------===//
3984 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3985 if (S.LangOpts.MicrosoftExt || S.LangOpts.Borland) {
3986 // check the attribute arguments.
3987 if (!checkAttributeNumArgs(S, Attr, 1))
3990 Expr *Arg = Attr.getArg(0);
3991 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3992 if (!Str || !Str->isAscii()) {
3993 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
3998 StringRef StrRef = Str->getString();
4000 bool IsCurly = StrRef.size() > 1 && StrRef.front() == '{' &&
4001 StrRef.back() == '}';
4003 // Validate GUID length.
4004 if (IsCurly && StrRef.size() != 38) {
4005 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4008 if (!IsCurly && StrRef.size() != 36) {
4009 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4013 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4014 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
4015 StringRef::iterator I = StrRef.begin();
4016 if (IsCurly) // Skip the optional '{'
4019 for (int i = 0; i < 36; ++i) {
4020 if (i == 8 || i == 13 || i == 18 || i == 23) {
4022 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4025 } else if (!isxdigit(*I)) {
4026 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4032 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context,
4035 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "uuid";
4038 static void handleInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4039 if (S.LangOpts.MicrosoftExt) {
4040 AttributeList::Kind Kind = Attr.getKind();
4041 if (Kind == AttributeList::AT_SingleInheritance)
4043 ::new (S.Context) SingleInheritanceAttr(Attr.getRange(), S.Context));
4044 else if (Kind == AttributeList::AT_MultipleInheritance)
4046 ::new (S.Context) MultipleInheritanceAttr(Attr.getRange(), S.Context));
4047 else if (Kind == AttributeList::AT_VirtualInheritance)
4049 ::new (S.Context) VirtualInheritanceAttr(Attr.getRange(), S.Context));
4051 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4054 static void handlePortabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4055 if (S.LangOpts.MicrosoftExt) {
4056 AttributeList::Kind Kind = Attr.getKind();
4057 if (Kind == AttributeList::AT_Ptr32)
4059 ::new (S.Context) Ptr32Attr(Attr.getRange(), S.Context));
4060 else if (Kind == AttributeList::AT_Ptr64)
4062 ::new (S.Context) Ptr64Attr(Attr.getRange(), S.Context));
4063 else if (Kind == AttributeList::AT_Win64)
4065 ::new (S.Context) Win64Attr(Attr.getRange(), S.Context));
4067 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4070 static void handleForceInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4071 if (S.LangOpts.MicrosoftExt)
4072 D->addAttr(::new (S.Context) ForceInlineAttr(Attr.getRange(), S.Context));
4074 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4077 //===----------------------------------------------------------------------===//
4078 // Top Level Sema Entry Points
4079 //===----------------------------------------------------------------------===//
4081 static void ProcessNonInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4082 const AttributeList &Attr) {
4083 switch (Attr.getKind()) {
4084 case AttributeList::AT_CUDADevice: handleDeviceAttr (S, D, Attr); break;
4085 case AttributeList::AT_CUDAHost: handleHostAttr (S, D, Attr); break;
4086 case AttributeList::AT_Overloadable:handleOverloadableAttr(S, D, Attr); break;
4092 static void ProcessInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4093 const AttributeList &Attr) {
4094 switch (Attr.getKind()) {
4095 case AttributeList::AT_IBAction: handleIBAction(S, D, Attr); break;
4096 case AttributeList::AT_IBOutlet: handleIBOutlet(S, D, Attr); break;
4097 case AttributeList::AT_IBOutletCollection:
4098 handleIBOutletCollection(S, D, Attr); break;
4099 case AttributeList::AT_AddressSpace:
4100 case AttributeList::AT_OpenCLImageAccess:
4101 case AttributeList::AT_ObjCGC:
4102 case AttributeList::AT_VectorSize:
4103 case AttributeList::AT_NeonVectorType:
4104 case AttributeList::AT_NeonPolyVectorType:
4105 // Ignore these, these are type attributes, handled by
4106 // ProcessTypeAttributes.
4108 case AttributeList::AT_CUDADevice:
4109 case AttributeList::AT_CUDAHost:
4110 case AttributeList::AT_Overloadable:
4111 // Ignore, this is a non-inheritable attribute, handled
4112 // by ProcessNonInheritableDeclAttr.
4114 case AttributeList::AT_Alias: handleAliasAttr (S, D, Attr); break;
4115 case AttributeList::AT_Aligned: handleAlignedAttr (S, D, Attr); break;
4116 case AttributeList::AT_AllocSize: handleAllocSizeAttr (S, D, Attr); break;
4117 case AttributeList::AT_AlwaysInline:
4118 handleAlwaysInlineAttr (S, D, Attr); break;
4119 case AttributeList::AT_AnalyzerNoReturn:
4120 handleAnalyzerNoReturnAttr (S, D, Attr); break;
4121 case AttributeList::AT_TLSModel: handleTLSModelAttr (S, D, Attr); break;
4122 case AttributeList::AT_Annotate: handleAnnotateAttr (S, D, Attr); break;
4123 case AttributeList::AT_Availability:handleAvailabilityAttr(S, D, Attr); break;
4124 case AttributeList::AT_CarriesDependency:
4125 handleDependencyAttr (S, D, Attr); break;
4126 case AttributeList::AT_Common: handleCommonAttr (S, D, Attr); break;
4127 case AttributeList::AT_CUDAConstant:handleConstantAttr (S, D, Attr); break;
4128 case AttributeList::AT_Constructor: handleConstructorAttr (S, D, Attr); break;
4129 case AttributeList::AT_Deprecated:
4130 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr, "deprecated");
4132 case AttributeList::AT_Destructor: handleDestructorAttr (S, D, Attr); break;
4133 case AttributeList::AT_ExtVectorType:
4134 handleExtVectorTypeAttr(S, scope, D, Attr);
4136 case AttributeList::AT_Format: handleFormatAttr (S, D, Attr); break;
4137 case AttributeList::AT_FormatArg: handleFormatArgAttr (S, D, Attr); break;
4138 case AttributeList::AT_CUDAGlobal: handleGlobalAttr (S, D, Attr); break;
4139 case AttributeList::AT_GNUInline: handleGNUInlineAttr (S, D, Attr); break;
4140 case AttributeList::AT_CUDALaunchBounds:
4141 handleLaunchBoundsAttr(S, D, Attr);
4143 case AttributeList::AT_Mode: handleModeAttr (S, D, Attr); break;
4144 case AttributeList::AT_Malloc: handleMallocAttr (S, D, Attr); break;
4145 case AttributeList::AT_MayAlias: handleMayAliasAttr (S, D, Attr); break;
4146 case AttributeList::AT_NoCommon: handleNoCommonAttr (S, D, Attr); break;
4147 case AttributeList::AT_NonNull: handleNonNullAttr (S, D, Attr); break;
4148 case AttributeList::AT_ownership_returns:
4149 case AttributeList::AT_ownership_takes:
4150 case AttributeList::AT_ownership_holds:
4151 handleOwnershipAttr (S, D, Attr); break;
4152 case AttributeList::AT_Cold: handleColdAttr (S, D, Attr); break;
4153 case AttributeList::AT_Hot: handleHotAttr (S, D, Attr); break;
4154 case AttributeList::AT_Naked: handleNakedAttr (S, D, Attr); break;
4155 case AttributeList::AT_NoReturn: handleNoReturnAttr (S, D, Attr); break;
4156 case AttributeList::AT_NoThrow: handleNothrowAttr (S, D, Attr); break;
4157 case AttributeList::AT_CUDAShared: handleSharedAttr (S, D, Attr); break;
4158 case AttributeList::AT_VecReturn: handleVecReturnAttr (S, D, Attr); break;
4160 case AttributeList::AT_ObjCOwnership:
4161 handleObjCOwnershipAttr(S, D, Attr); break;
4162 case AttributeList::AT_ObjCPreciseLifetime:
4163 handleObjCPreciseLifetimeAttr(S, D, Attr); break;
4165 case AttributeList::AT_ObjCReturnsInnerPointer:
4166 handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
4168 case AttributeList::AT_NSBridged:
4169 handleNSBridgedAttr(S, scope, D, Attr); break;
4171 case AttributeList::AT_CFAuditedTransfer:
4172 case AttributeList::AT_CFUnknownTransfer:
4173 handleCFTransferAttr(S, D, Attr); break;
4175 // Checker-specific.
4176 case AttributeList::AT_CFConsumed:
4177 case AttributeList::AT_NSConsumed: handleNSConsumedAttr (S, D, Attr); break;
4178 case AttributeList::AT_NSConsumesSelf:
4179 handleNSConsumesSelfAttr(S, D, Attr); break;
4181 case AttributeList::AT_NSReturnsAutoreleased:
4182 case AttributeList::AT_NSReturnsNotRetained:
4183 case AttributeList::AT_CFReturnsNotRetained:
4184 case AttributeList::AT_NSReturnsRetained:
4185 case AttributeList::AT_CFReturnsRetained:
4186 handleNSReturnsRetainedAttr(S, D, Attr); break;
4188 case AttributeList::AT_WorkGroupSizeHint:
4189 case AttributeList::AT_ReqdWorkGroupSize:
4190 handleWorkGroupSize(S, D, Attr); break;
4192 case AttributeList::AT_InitPriority:
4193 handleInitPriorityAttr(S, D, Attr); break;
4195 case AttributeList::AT_Packed: handlePackedAttr (S, D, Attr); break;
4196 case AttributeList::AT_Section: handleSectionAttr (S, D, Attr); break;
4197 case AttributeList::AT_Unavailable:
4198 handleAttrWithMessage<UnavailableAttr>(S, D, Attr, "unavailable");
4200 case AttributeList::AT_ArcWeakrefUnavailable:
4201 handleArcWeakrefUnavailableAttr (S, D, Attr);
4203 case AttributeList::AT_ObjCRootClass:
4204 handleObjCRootClassAttr(S, D, Attr);
4206 case AttributeList::AT_ObjCRequiresPropertyDefs:
4207 handleObjCRequiresPropertyDefsAttr (S, D, Attr);
4209 case AttributeList::AT_Unused: handleUnusedAttr (S, D, Attr); break;
4210 case AttributeList::AT_ReturnsTwice:
4211 handleReturnsTwiceAttr(S, D, Attr);
4213 case AttributeList::AT_Used: handleUsedAttr (S, D, Attr); break;
4214 case AttributeList::AT_Visibility: handleVisibilityAttr (S, D, Attr); break;
4215 case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr);
4217 case AttributeList::AT_Weak: handleWeakAttr (S, D, Attr); break;
4218 case AttributeList::AT_WeakRef: handleWeakRefAttr (S, D, Attr); break;
4219 case AttributeList::AT_WeakImport: handleWeakImportAttr (S, D, Attr); break;
4220 case AttributeList::AT_TransparentUnion:
4221 handleTransparentUnionAttr(S, D, Attr);
4223 case AttributeList::AT_ObjCException:
4224 handleObjCExceptionAttr(S, D, Attr);
4226 case AttributeList::AT_ObjCMethodFamily:
4227 handleObjCMethodFamilyAttr(S, D, Attr);
4229 case AttributeList::AT_ObjCNSObject:handleObjCNSObject (S, D, Attr); break;
4230 case AttributeList::AT_Blocks: handleBlocksAttr (S, D, Attr); break;
4231 case AttributeList::AT_Sentinel: handleSentinelAttr (S, D, Attr); break;
4232 case AttributeList::AT_Const: handleConstAttr (S, D, Attr); break;
4233 case AttributeList::AT_Pure: handlePureAttr (S, D, Attr); break;
4234 case AttributeList::AT_Cleanup: handleCleanupAttr (S, D, Attr); break;
4235 case AttributeList::AT_NoDebug: handleNoDebugAttr (S, D, Attr); break;
4236 case AttributeList::AT_NoInline: handleNoInlineAttr (S, D, Attr); break;
4237 case AttributeList::AT_Regparm: handleRegparmAttr (S, D, Attr); break;
4238 case AttributeList::IgnoredAttribute:
4241 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4242 handleNoInstrumentFunctionAttr(S, D, Attr);
4244 case AttributeList::AT_StdCall:
4245 case AttributeList::AT_CDecl:
4246 case AttributeList::AT_FastCall:
4247 case AttributeList::AT_ThisCall:
4248 case AttributeList::AT_Pascal:
4249 case AttributeList::AT_Pcs:
4250 handleCallConvAttr(S, D, Attr);
4252 case AttributeList::AT_OpenCLKernel:
4253 handleOpenCLKernelAttr(S, D, Attr);
4256 // Microsoft attributes:
4257 case AttributeList::AT_MsStruct:
4258 handleMsStructAttr(S, D, Attr);
4260 case AttributeList::AT_Uuid:
4261 handleUuidAttr(S, D, Attr);
4263 case AttributeList::AT_SingleInheritance:
4264 case AttributeList::AT_MultipleInheritance:
4265 case AttributeList::AT_VirtualInheritance:
4266 handleInheritanceAttr(S, D, Attr);
4268 case AttributeList::AT_Win64:
4269 case AttributeList::AT_Ptr32:
4270 case AttributeList::AT_Ptr64:
4271 handlePortabilityAttr(S, D, Attr);
4273 case AttributeList::AT_ForceInline:
4274 handleForceInlineAttr(S, D, Attr);
4277 // Thread safety attributes:
4278 case AttributeList::AT_GuardedVar:
4279 handleGuardedVarAttr(S, D, Attr);
4281 case AttributeList::AT_PtGuardedVar:
4282 handlePtGuardedVarAttr(S, D, Attr);
4284 case AttributeList::AT_ScopedLockable:
4285 handleScopedLockableAttr(S, D, Attr);
4287 case AttributeList::AT_NoAddressSafetyAnalysis:
4288 handleNoAddressSafetyAttr(S, D, Attr);
4290 case AttributeList::AT_NoThreadSafetyAnalysis:
4291 handleNoThreadSafetyAttr(S, D, Attr);
4293 case AttributeList::AT_Lockable:
4294 handleLockableAttr(S, D, Attr);
4296 case AttributeList::AT_GuardedBy:
4297 handleGuardedByAttr(S, D, Attr);
4299 case AttributeList::AT_PtGuardedBy:
4300 handlePtGuardedByAttr(S, D, Attr);
4302 case AttributeList::AT_ExclusiveLockFunction:
4303 handleExclusiveLockFunctionAttr(S, D, Attr);
4305 case AttributeList::AT_ExclusiveLocksRequired:
4306 handleExclusiveLocksRequiredAttr(S, D, Attr);
4308 case AttributeList::AT_ExclusiveTrylockFunction:
4309 handleExclusiveTrylockFunctionAttr(S, D, Attr);
4311 case AttributeList::AT_LockReturned:
4312 handleLockReturnedAttr(S, D, Attr);
4314 case AttributeList::AT_LocksExcluded:
4315 handleLocksExcludedAttr(S, D, Attr);
4317 case AttributeList::AT_SharedLockFunction:
4318 handleSharedLockFunctionAttr(S, D, Attr);
4320 case AttributeList::AT_SharedLocksRequired:
4321 handleSharedLocksRequiredAttr(S, D, Attr);
4323 case AttributeList::AT_SharedTrylockFunction:
4324 handleSharedTrylockFunctionAttr(S, D, Attr);
4326 case AttributeList::AT_UnlockFunction:
4327 handleUnlockFunAttr(S, D, Attr);
4329 case AttributeList::AT_AcquiredBefore:
4330 handleAcquiredBeforeAttr(S, D, Attr);
4332 case AttributeList::AT_AcquiredAfter:
4333 handleAcquiredAfterAttr(S, D, Attr);
4337 // Ask target about the attribute.
4338 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
4339 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
4340 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ?
4341 diag::warn_unhandled_ms_attribute_ignored :
4342 diag::warn_unknown_attribute_ignored) << Attr.getName();
4347 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4348 /// the attribute applies to decls. If the attribute is a type attribute, just
4349 /// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
4350 /// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
4351 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4352 const AttributeList &Attr,
4353 bool NonInheritable, bool Inheritable) {
4354 if (Attr.isInvalid())
4357 // Type attributes are still treated as declaration attributes by
4358 // ParseMicrosoftTypeAttributes and ParseBorlandTypeAttributes. We don't
4359 // want to process them, however, because we will simply warn about ignoring
4360 // them. So instead, we will bail out early.
4361 if (Attr.isMSTypespecAttribute())
4365 ProcessNonInheritableDeclAttr(S, scope, D, Attr);
4368 ProcessInheritableDeclAttr(S, scope, D, Attr);
4371 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4372 /// attribute list to the specified decl, ignoring any type attributes.
4373 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4374 const AttributeList *AttrList,
4375 bool NonInheritable, bool Inheritable) {
4376 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4377 ProcessDeclAttribute(*this, S, D, *l, NonInheritable, Inheritable);
4381 // static int a9 __attribute__((weakref));
4382 // but that looks really pointless. We reject it.
4383 if (Inheritable && D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4384 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
4385 dyn_cast<NamedDecl>(D)->getNameAsString();
4390 // Annotation attributes are the only attributes allowed after an access
4392 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4393 const AttributeList *AttrList) {
4394 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4395 if (l->getKind() == AttributeList::AT_Annotate) {
4396 handleAnnotateAttr(*this, ASDecl, *l);
4398 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4406 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4407 /// contains any decl attributes that we should warn about.
4408 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4409 for ( ; A; A = A->getNext()) {
4410 // Only warn if the attribute is an unignored, non-type attribute.
4411 if (A->isUsedAsTypeAttr()) continue;
4412 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4414 if (A->getKind() == AttributeList::UnknownAttribute) {
4415 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4416 << A->getName() << A->getRange();
4418 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4419 << A->getName() << A->getRange();
4424 /// checkUnusedDeclAttributes - Given a declarator which is not being
4425 /// used to build a declaration, complain about any decl attributes
4426 /// which might be lying around on it.
4427 void Sema::checkUnusedDeclAttributes(Declarator &D) {
4428 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4429 ::checkUnusedDeclAttributes(*this, D.getAttributes());
4430 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4431 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4434 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
4435 /// \#pragma weak needs a non-definition decl and source may not have one.
4436 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4437 SourceLocation Loc) {
4438 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4439 NamedDecl *NewD = 0;
4440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4441 FunctionDecl *NewFD;
4442 // FIXME: Missing call to CheckFunctionDeclaration().
4444 // FIXME: Is the qualifier info correct?
4445 // FIXME: Is the DeclContext correct?
4446 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4447 Loc, Loc, DeclarationName(II),
4448 FD->getType(), FD->getTypeSourceInfo(),
4450 false/*isInlineSpecified*/,
4452 false/*isConstexprSpecified*/);
4455 if (FD->getQualifier())
4456 NewFD->setQualifierInfo(FD->getQualifierLoc());
4458 // Fake up parameter variables; they are declared as if this were
4460 QualType FDTy = FD->getType();
4461 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4462 SmallVector<ParmVarDecl*, 16> Params;
4463 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4464 AE = FT->arg_type_end(); AI != AE; ++AI) {
4465 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
4466 Param->setScopeInfo(0, Params.size());
4467 Params.push_back(Param);
4469 NewFD->setParams(Params);
4471 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4472 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4473 VD->getInnerLocStart(), VD->getLocation(), II,
4474 VD->getType(), VD->getTypeSourceInfo(),
4475 VD->getStorageClass(),
4476 VD->getStorageClassAsWritten());
4477 if (VD->getQualifier()) {
4478 VarDecl *NewVD = cast<VarDecl>(NewD);
4479 NewVD->setQualifierInfo(VD->getQualifierLoc());
4485 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4486 /// applied to it, possibly with an alias.
4487 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4488 if (W.getUsed()) return; // only do this once
4490 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4491 IdentifierInfo *NDId = ND->getIdentifier();
4492 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4493 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
4495 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4496 WeakTopLevelDecl.push_back(NewD);
4497 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4498 // to insert Decl at TU scope, sorry.
4499 DeclContext *SavedContext = CurContext;
4500 CurContext = Context.getTranslationUnitDecl();
4501 PushOnScopeChains(NewD, S);
4502 CurContext = SavedContext;
4503 } else { // just add weak to existing
4504 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4508 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4509 /// it, apply them to D. This is a bit tricky because PD can have attributes
4510 /// specified in many different places, and we need to find and apply them all.
4511 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
4512 bool NonInheritable, bool Inheritable) {
4513 // It's valid to "forward-declare" #pragma weak, in which case we
4516 LoadExternalWeakUndeclaredIdentifiers();
4517 if (!WeakUndeclaredIdentifiers.empty()) {
4518 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
4519 if (IdentifierInfo *Id = ND->getIdentifier()) {
4520 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4521 = WeakUndeclaredIdentifiers.find(Id);
4522 if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
4523 WeakInfo W = I->second;
4524 DeclApplyPragmaWeak(S, ND, W);
4525 WeakUndeclaredIdentifiers[Id] = W;
4532 // Apply decl attributes from the DeclSpec if present.
4533 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4534 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4536 // Walk the declarator structure, applying decl attributes that were in a type
4537 // position to the decl itself. This handles cases like:
4538 // int *__attr__(x)** D;
4539 // when X is a decl attribute.
4540 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
4541 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
4542 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4544 // Finally, apply any attributes on the decl itself.
4545 if (const AttributeList *Attrs = PD.getAttributes())
4546 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4549 /// Is the given declaration allowed to use a forbidden type?
4550 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
4551 // Private ivars are always okay. Unfortunately, people don't
4552 // always properly make their ivars private, even in system headers.
4553 // Plus we need to make fields okay, too.
4554 // Function declarations in sys headers will be marked unavailable.
4555 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
4556 !isa<FunctionDecl>(decl))
4559 // Require it to be declared in a system header.
4560 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
4563 /// Handle a delayed forbidden-type diagnostic.
4564 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
4566 if (decl && isForbiddenTypeAllowed(S, decl)) {
4567 decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
4568 "this system declaration uses an unsupported type"));
4571 if (S.getLangOpts().ObjCAutoRefCount)
4572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
4573 // FIXME: we may want to suppress diagnostics for all
4574 // kind of forbidden type messages on unavailable functions.
4575 if (FD->hasAttr<UnavailableAttr>() &&
4576 diag.getForbiddenTypeDiagnostic() ==
4577 diag::err_arc_array_param_no_ownership) {
4578 diag.Triggered = true;
4583 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
4584 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
4585 diag.Triggered = true;
4588 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
4589 assert(DelayedDiagnostics.getCurrentPool());
4590 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
4591 DelayedDiagnostics.popWithoutEmitting(state);
4593 // When delaying diagnostics to run in the context of a parsed
4594 // declaration, we only want to actually emit anything if parsing
4598 // We emit all the active diagnostics in this pool or any of its
4599 // parents. In general, we'll get one pool for the decl spec
4600 // and a child pool for each declarator; in a decl group like:
4601 // deprecated_typedef foo, *bar, baz();
4602 // only the declarator pops will be passed decls. This is correct;
4603 // we really do need to consider delayed diagnostics from the decl spec
4604 // for each of the different declarations.
4605 const DelayedDiagnosticPool *pool = &poppedPool;
4607 for (DelayedDiagnosticPool::pool_iterator
4608 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
4609 // This const_cast is a bit lame. Really, Triggered should be mutable.
4610 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
4614 switch (diag.Kind) {
4615 case DelayedDiagnostic::Deprecation:
4616 // Don't bother giving deprecation diagnostics if the decl is invalid.
4617 if (!decl->isInvalidDecl())
4618 HandleDelayedDeprecationCheck(diag, decl);
4621 case DelayedDiagnostic::Access:
4622 HandleDelayedAccessCheck(diag, decl);
4625 case DelayedDiagnostic::ForbiddenType:
4626 handleDelayedForbiddenType(*this, diag, decl);
4630 } while ((pool = pool->getParent()));
4633 /// Given a set of delayed diagnostics, re-emit them as if they had
4634 /// been delayed in the current context instead of in the given pool.
4635 /// Essentially, this just moves them to the current pool.
4636 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
4637 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
4638 assert(curPool && "re-emitting in undelayed context not supported");
4639 curPool->steal(pool);
4642 static bool isDeclDeprecated(Decl *D) {
4644 if (D->isDeprecated())
4646 // A category implicitly has the availability of the interface.
4647 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4648 return CatD->getClassInterface()->isDeprecated();
4649 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4654 DoEmitDeprecationWarning(Sema &S, const NamedDecl *D, StringRef Message,
4656 const ObjCInterfaceDecl *UnknownObjCClass) {
4657 DeclarationName Name = D->getDeclName();
4658 if (!Message.empty()) {
4659 S.Diag(Loc, diag::warn_deprecated_message) << Name << Message;
4660 S.Diag(D->getLocation(),
4661 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
4662 : diag::note_previous_decl) << Name;
4663 } else if (!UnknownObjCClass) {
4664 S.Diag(Loc, diag::warn_deprecated) << D->getDeclName();
4665 S.Diag(D->getLocation(),
4666 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
4667 : diag::note_previous_decl) << Name;
4669 S.Diag(Loc, diag::warn_deprecated_fwdclass_message) << Name;
4670 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
4674 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
4676 if (isDeclDeprecated(Ctx))
4679 DD.Triggered = true;
4680 DoEmitDeprecationWarning(*this, DD.getDeprecationDecl(),
4681 DD.getDeprecationMessage(), DD.Loc,
4682 DD.getUnknownObjCClass());
4685 void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
4687 const ObjCInterfaceDecl *UnknownObjCClass) {
4688 // Delay if we're currently parsing a declaration.
4689 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
4690 DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,
4696 // Otherwise, don't warn if our current context is deprecated.
4697 if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
4699 DoEmitDeprecationWarning(*this, D, Message, Loc, UnknownObjCClass);