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/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/Basic/CharInfo.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/DeclSpec.h"
27 #include "clang/Sema/DelayedDiagnostic.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "llvm/ADT/StringExtras.h"
31 using namespace clang;
34 /// These constants match the enumerated choices of
35 /// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
36 enum AttributeDeclKind {
39 ExpectedVariableOrFunction,
40 ExpectedFunctionOrMethod,
42 ExpectedFunctionMethodOrBlock,
43 ExpectedFunctionMethodOrClass,
44 ExpectedFunctionMethodOrParameter,
48 ExpectedVariableFunctionOrLabel,
49 ExpectedFieldOrGlobalVar,
51 ExpectedVariableFunctionOrTag,
53 ExpectedVariableOrField,
54 ExpectedVariableFieldOrTag,
55 ExpectedTypeOrNamespace
58 //===----------------------------------------------------------------------===//
60 //===----------------------------------------------------------------------===//
62 static const FunctionType *getFunctionType(const Decl *D,
63 bool blocksToo = true) {
65 if (const ValueDecl *decl = dyn_cast<ValueDecl>(D))
67 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(D))
69 else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(D))
70 Ty = decl->getUnderlyingType();
74 if (Ty->isFunctionPointerType())
75 Ty = Ty->getAs<PointerType>()->getPointeeType();
76 else if (blocksToo && Ty->isBlockPointerType())
77 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
79 return Ty->getAs<FunctionType>();
82 // FIXME: We should provide an abstraction around a method or function
83 // to provide the following bits of information.
85 /// isFunction - Return true if the given decl has function
86 /// type (function or function-typed variable).
87 static bool isFunction(const Decl *D) {
88 return getFunctionType(D, false) != NULL;
91 /// isFunctionOrMethod - Return true if the given decl has function
92 /// type (function or function-typed variable) or an Objective-C
94 static bool isFunctionOrMethod(const Decl *D) {
95 return isFunction(D) || isa<ObjCMethodDecl>(D);
98 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
99 /// type (function or function-typed variable) or an Objective-C
100 /// method or a block.
101 static bool isFunctionOrMethodOrBlock(const Decl *D) {
102 if (isFunctionOrMethod(D))
104 // check for block is more involved.
105 if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
106 QualType Ty = V->getType();
107 return Ty->isBlockPointerType();
109 return isa<BlockDecl>(D);
112 /// Return true if the given decl has a declarator that should have
113 /// been processed by Sema::GetTypeForDeclarator.
114 static bool hasDeclarator(const Decl *D) {
115 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
116 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
117 isa<ObjCPropertyDecl>(D);
120 /// hasFunctionProto - Return true if the given decl has a argument
121 /// information. This decl should have already passed
122 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
123 static bool hasFunctionProto(const Decl *D) {
124 if (const FunctionType *FnTy = getFunctionType(D))
125 return isa<FunctionProtoType>(FnTy);
127 assert(isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D));
132 /// getFunctionOrMethodNumArgs - Return number of function or method
133 /// arguments. It is an error to call this on a K&R function (use
134 /// hasFunctionProto first).
135 static unsigned getFunctionOrMethodNumArgs(const Decl *D) {
136 if (const FunctionType *FnTy = getFunctionType(D))
137 return cast<FunctionProtoType>(FnTy)->getNumArgs();
138 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
139 return BD->getNumParams();
140 return cast<ObjCMethodDecl>(D)->param_size();
143 static QualType getFunctionOrMethodArgType(const Decl *D, unsigned Idx) {
144 if (const FunctionType *FnTy = getFunctionType(D))
145 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
146 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
147 return BD->getParamDecl(Idx)->getType();
149 return cast<ObjCMethodDecl>(D)->param_begin()[Idx]->getType();
152 static QualType getFunctionOrMethodResultType(const Decl *D) {
153 if (const FunctionType *FnTy = getFunctionType(D))
154 return cast<FunctionProtoType>(FnTy)->getResultType();
155 return cast<ObjCMethodDecl>(D)->getResultType();
158 static bool isFunctionOrMethodVariadic(const Decl *D) {
159 if (const FunctionType *FnTy = getFunctionType(D)) {
160 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
161 return proto->isVariadic();
162 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
163 return BD->isVariadic();
165 return cast<ObjCMethodDecl>(D)->isVariadic();
169 static bool isInstanceMethod(const Decl *D) {
170 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
171 return MethodDecl->isInstance();
175 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
176 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
180 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
184 IdentifierInfo* ClsName = Cls->getIdentifier();
186 // FIXME: Should we walk the chain of classes?
187 return ClsName == &Ctx.Idents.get("NSString") ||
188 ClsName == &Ctx.Idents.get("NSMutableString");
191 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
192 const PointerType *PT = T->getAs<PointerType>();
196 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
200 const RecordDecl *RD = RT->getDecl();
201 if (RD->getTagKind() != TTK_Struct)
204 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
207 /// \brief Check if the attribute has exactly as many args as Num. May
209 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
211 if (Attr.getNumArgs() != Num) {
212 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Num;
220 /// \brief Check if the attribute has at least as many args as Num. May
222 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
224 if (Attr.getNumArgs() < Num) {
225 S.Diag(Attr.getLoc(), diag::err_attribute_too_few_arguments) << Num;
232 /// \brief Check if IdxExpr is a valid argument index for a function or
233 /// instance method D. May output an error.
235 /// \returns true if IdxExpr is a valid index.
236 static bool checkFunctionOrMethodArgumentIndex(Sema &S, const Decl *D,
238 SourceLocation AttrLoc,
243 assert(isFunctionOrMethod(D) && hasFunctionProto(D));
245 // In C++ the implicit 'this' function parameter also counts.
246 // Parameters are counted from one.
247 const bool HasImplicitThisParam = isInstanceMethod(D);
248 const unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
249 const unsigned FirstIdx = 1;
252 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
253 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
254 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_int)
255 << AttrName << AttrArgNum << IdxExpr->getSourceRange();
259 Idx = IdxInt.getLimitedValue();
260 if (Idx < FirstIdx || (!isFunctionOrMethodVariadic(D) && Idx > NumArgs)) {
261 S.Diag(AttrLoc, diag::err_attribute_argument_out_of_bounds)
262 << AttrName << AttrArgNum << IdxExpr->getSourceRange();
265 Idx--; // Convert to zero-based.
266 if (HasImplicitThisParam) {
269 diag::err_attribute_invalid_implicit_this_argument)
270 << AttrName << IdxExpr->getSourceRange();
280 /// \brief Check if passed in Decl is a field or potentially shared global var
281 /// \return true if the Decl is a field or potentially shared global variable
283 static bool mayBeSharedVariable(const Decl *D) {
284 if (isa<FieldDecl>(D))
286 if (const VarDecl *vd = dyn_cast<VarDecl>(D))
287 return vd->hasGlobalStorage() && !vd->getTLSKind();
292 /// \brief Check if the passed-in expression is of type int or bool.
293 static bool isIntOrBool(Expr *Exp) {
294 QualType QT = Exp->getType();
295 return QT->isBooleanType() || QT->isIntegerType();
299 // Check to see if the type is a smart pointer of some kind. We assume
300 // it's a smart pointer if it defines both operator-> and operator*.
301 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
302 DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
303 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
307 DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
308 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
315 /// \brief Check if passed in Decl is a pointer type.
316 /// Note that this function may produce an error message.
317 /// \return true if the Decl is a pointer type; false otherwise
318 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
319 const AttributeList &Attr) {
320 if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) {
321 QualType QT = vd->getType();
322 if (QT->isAnyPointerType())
325 if (const RecordType *RT = QT->getAs<RecordType>()) {
326 // If it's an incomplete type, it could be a smart pointer; skip it.
327 // (We don't want to force template instantiation if we can avoid it,
328 // since that would alter the order in which templates are instantiated.)
329 if (RT->isIncompleteType())
332 if (threadSafetyCheckIsSmartPointer(S, RT))
336 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
337 << Attr.getName()->getName() << QT;
339 S.Diag(Attr.getLoc(), diag::err_attribute_can_be_applied_only_to_value_decl)
345 /// \brief Checks that the passed in QualType either is of RecordType or points
346 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
347 static const RecordType *getRecordType(QualType QT) {
348 if (const RecordType *RT = QT->getAs<RecordType>())
351 // Now check if we point to record type.
352 if (const PointerType *PT = QT->getAs<PointerType>())
353 return PT->getPointeeType()->getAs<RecordType>();
359 static bool checkBaseClassIsLockableCallback(const CXXBaseSpecifier *Specifier,
360 CXXBasePath &Path, void *Unused) {
361 const RecordType *RT = Specifier->getType()->getAs<RecordType>();
362 if (RT->getDecl()->getAttr<LockableAttr>())
368 /// \brief Thread Safety Analysis: Checks that the passed in RecordType
369 /// resolves to a lockable object.
370 static void checkForLockableRecord(Sema &S, Decl *D, const AttributeList &Attr,
372 const RecordType *RT = getRecordType(Ty);
374 // Warn if could not get record type for this argument.
376 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_class)
377 << Attr.getName() << Ty.getAsString();
381 // Don't check for lockable if the class hasn't been defined yet.
382 if (RT->isIncompleteType())
385 // Allow smart pointers to be used as lockable objects.
386 // FIXME -- Check the type that the smart pointer points to.
387 if (threadSafetyCheckIsSmartPointer(S, RT))
390 // Check if the type is lockable.
391 RecordDecl *RD = RT->getDecl();
392 if (RD->getAttr<LockableAttr>())
395 // Else check if any base classes are lockable.
396 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
397 CXXBasePaths BPaths(false, false);
398 if (CRD->lookupInBases(checkBaseClassIsLockableCallback, 0, BPaths))
402 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
403 << Attr.getName() << Ty.getAsString();
406 /// \brief Thread Safety Analysis: Checks that all attribute arguments, starting
407 /// from Sidx, resolve to a lockable object.
408 /// \param Sidx The attribute argument index to start checking with.
409 /// \param ParamIdxOk Whether an argument can be indexing into a function
411 static void checkAttrArgsAreLockableObjs(Sema &S, Decl *D,
412 const AttributeList &Attr,
413 SmallVectorImpl<Expr*> &Args,
415 bool ParamIdxOk = false) {
416 for(unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
417 Expr *ArgExp = Attr.getArg(Idx);
419 if (ArgExp->isTypeDependent()) {
420 // FIXME -- need to check this again on template instantiation
421 Args.push_back(ArgExp);
425 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
426 if (StrLit->getLength() == 0 ||
427 StrLit->getString() == StringRef("*")) {
428 // Pass empty strings to the analyzer without warnings.
429 // Treat "*" as the universal lock.
430 Args.push_back(ArgExp);
434 // We allow constant strings to be used as a placeholder for expressions
435 // that are not valid C++ syntax, but warn that they are ignored.
436 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
438 Args.push_back(ArgExp);
442 QualType ArgTy = ArgExp->getType();
444 // A pointer to member expression of the form &MyClass::mu is treated
445 // specially -- we need to look at the type of the member.
446 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
447 if (UOp->getOpcode() == UO_AddrOf)
448 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
449 if (DRE->getDecl()->isCXXInstanceMember())
450 ArgTy = DRE->getDecl()->getType();
452 // First see if we can just cast to record type, or point to record type.
453 const RecordType *RT = getRecordType(ArgTy);
455 // Now check if we index into a record type function param.
456 if(!RT && ParamIdxOk) {
457 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
458 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
460 unsigned int NumParams = FD->getNumParams();
461 llvm::APInt ArgValue = IL->getValue();
462 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
463 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
464 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
465 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
466 << Attr.getName() << Idx + 1 << NumParams;
469 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
473 checkForLockableRecord(S, D, Attr, ArgTy);
475 Args.push_back(ArgExp);
479 //===----------------------------------------------------------------------===//
480 // Attribute Implementations
481 //===----------------------------------------------------------------------===//
483 // FIXME: All this manual attribute parsing code is gross. At the
484 // least add some helper functions to check most argument patterns (#
485 // and types of args).
487 enum ThreadAttributeDeclKind {
488 ThreadExpectedFieldOrGlobalVar,
489 ThreadExpectedFunctionOrMethod,
490 ThreadExpectedClassOrStruct
493 static bool checkGuardedVarAttrCommon(Sema &S, Decl *D,
494 const AttributeList &Attr) {
495 assert(!Attr.isInvalid());
497 if (!checkAttributeNumArgs(S, Attr, 0))
500 // D must be either a member field or global (potentially shared) variable.
501 if (!mayBeSharedVariable(D)) {
502 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
503 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
510 static void handleGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr) {
511 if (!checkGuardedVarAttrCommon(S, D, Attr))
514 D->addAttr(::new (S.Context)
515 GuardedVarAttr(Attr.getRange(), S.Context,
516 Attr.getAttributeSpellingListIndex()));
519 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
520 const AttributeList &Attr) {
521 if (!checkGuardedVarAttrCommon(S, D, Attr))
524 if (!threadSafetyCheckIsPointer(S, D, Attr))
527 D->addAttr(::new (S.Context)
528 PtGuardedVarAttr(Attr.getRange(), S.Context,
529 Attr.getAttributeSpellingListIndex()));
532 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
533 const AttributeList &Attr,
535 assert(!Attr.isInvalid());
537 if (!checkAttributeNumArgs(S, Attr, 1))
540 // D must be either a member field or global (potentially shared) variable.
541 if (!mayBeSharedVariable(D)) {
542 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
543 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
547 SmallVector<Expr*, 1> Args;
548 // check that all arguments are lockable objects
549 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
550 unsigned Size = Args.size();
559 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
561 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
564 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg));
567 static void handlePtGuardedByAttr(Sema &S, Decl *D,
568 const AttributeList &Attr) {
570 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
573 if (!threadSafetyCheckIsPointer(S, D, Attr))
576 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
580 static bool checkLockableAttrCommon(Sema &S, Decl *D,
581 const AttributeList &Attr) {
582 assert(!Attr.isInvalid());
584 if (!checkAttributeNumArgs(S, Attr, 0))
587 // FIXME: Lockable structs for C code.
588 if (!isa<CXXRecordDecl>(D)) {
589 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
590 << Attr.getName() << ThreadExpectedClassOrStruct;
597 static void handleLockableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
598 if (!checkLockableAttrCommon(S, D, Attr))
601 D->addAttr(::new (S.Context) LockableAttr(Attr.getRange(), S.Context));
604 static void handleScopedLockableAttr(Sema &S, Decl *D,
605 const AttributeList &Attr) {
606 if (!checkLockableAttrCommon(S, D, Attr))
609 D->addAttr(::new (S.Context)
610 ScopedLockableAttr(Attr.getRange(), S.Context,
611 Attr.getAttributeSpellingListIndex()));
614 static void handleNoThreadSafetyAnalysis(Sema &S, Decl *D,
615 const AttributeList &Attr) {
616 assert(!Attr.isInvalid());
618 if (!checkAttributeNumArgs(S, Attr, 0))
621 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
622 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
623 << Attr.getName() << ThreadExpectedFunctionOrMethod;
627 D->addAttr(::new (S.Context) NoThreadSafetyAnalysisAttr(Attr.getRange(),
631 static void handleNoSanitizeAddressAttr(Sema &S, Decl *D,
632 const AttributeList &Attr) {
633 assert(!Attr.isInvalid());
635 if (!checkAttributeNumArgs(S, Attr, 0))
638 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
639 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
640 << Attr.getName() << ExpectedFunctionOrMethod;
644 D->addAttr(::new (S.Context)
645 NoSanitizeAddressAttr(Attr.getRange(), S.Context,
646 Attr.getAttributeSpellingListIndex()));
649 static void handleNoSanitizeMemory(Sema &S, Decl *D,
650 const AttributeList &Attr) {
651 assert(!Attr.isInvalid());
653 if (!checkAttributeNumArgs(S, Attr, 0))
656 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
657 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
658 << Attr.getName() << ExpectedFunctionOrMethod;
662 D->addAttr(::new (S.Context) NoSanitizeMemoryAttr(Attr.getRange(),
666 static void handleNoSanitizeThread(Sema &S, Decl *D,
667 const AttributeList &Attr) {
668 assert(!Attr.isInvalid());
670 if (!checkAttributeNumArgs(S, Attr, 0))
673 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
674 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
675 << Attr.getName() << ExpectedFunctionOrMethod;
679 D->addAttr(::new (S.Context) NoSanitizeThreadAttr(Attr.getRange(),
683 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
684 const AttributeList &Attr,
685 SmallVector<Expr*, 1> &Args) {
686 assert(!Attr.isInvalid());
688 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
691 // D must be either a member field or global (potentially shared) variable.
692 ValueDecl *VD = dyn_cast<ValueDecl>(D);
693 if (!VD || !mayBeSharedVariable(D)) {
694 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
695 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
699 // Check that this attribute only applies to lockable types.
700 QualType QT = VD->getType();
701 if (!QT->isDependentType()) {
702 const RecordType *RT = getRecordType(QT);
703 if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
704 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
710 // Check that all arguments are lockable objects.
711 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
718 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
719 const AttributeList &Attr) {
720 SmallVector<Expr*, 1> Args;
721 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
724 Expr **StartArg = &Args[0];
725 D->addAttr(::new (S.Context)
726 AcquiredAfterAttr(Attr.getRange(), S.Context,
727 StartArg, Args.size(),
728 Attr.getAttributeSpellingListIndex()));
731 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
732 const AttributeList &Attr) {
733 SmallVector<Expr*, 1> Args;
734 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
737 Expr **StartArg = &Args[0];
738 D->addAttr(::new (S.Context)
739 AcquiredBeforeAttr(Attr.getRange(), S.Context,
740 StartArg, Args.size(),
741 Attr.getAttributeSpellingListIndex()));
744 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
745 const AttributeList &Attr,
746 SmallVector<Expr*, 1> &Args) {
747 assert(!Attr.isInvalid());
749 // zero or more arguments ok
751 // check that the attribute is applied to a function
752 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
753 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
754 << Attr.getName() << ThreadExpectedFunctionOrMethod;
758 // check that all arguments are lockable objects
759 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
764 static void handleSharedLockFunctionAttr(Sema &S, Decl *D,
765 const AttributeList &Attr) {
766 SmallVector<Expr*, 1> Args;
767 if (!checkLockFunAttrCommon(S, D, Attr, Args))
770 unsigned Size = Args.size();
771 Expr **StartArg = Size == 0 ? 0 : &Args[0];
772 D->addAttr(::new (S.Context)
773 SharedLockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
774 Attr.getAttributeSpellingListIndex()));
777 static void handleExclusiveLockFunctionAttr(Sema &S, Decl *D,
778 const AttributeList &Attr) {
779 SmallVector<Expr*, 1> Args;
780 if (!checkLockFunAttrCommon(S, D, Attr, Args))
783 unsigned Size = Args.size();
784 Expr **StartArg = Size == 0 ? 0 : &Args[0];
785 D->addAttr(::new (S.Context)
786 ExclusiveLockFunctionAttr(Attr.getRange(), S.Context,
788 Attr.getAttributeSpellingListIndex()));
791 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
792 const AttributeList &Attr,
793 SmallVector<Expr*, 2> &Args) {
794 assert(!Attr.isInvalid());
796 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
799 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
800 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
801 << Attr.getName() << ThreadExpectedFunctionOrMethod;
805 if (!isIntOrBool(Attr.getArg(0))) {
806 S.Diag(Attr.getLoc(), diag::err_attribute_first_argument_not_int_or_bool)
811 // check that all arguments are lockable objects
812 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 1);
817 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
818 const AttributeList &Attr) {
819 SmallVector<Expr*, 2> Args;
820 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
823 unsigned Size = Args.size();
824 Expr **StartArg = Size == 0 ? 0 : &Args[0];
825 D->addAttr(::new (S.Context)
826 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
827 Attr.getArg(0), StartArg, Size,
828 Attr.getAttributeSpellingListIndex()));
831 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
832 const AttributeList &Attr) {
833 SmallVector<Expr*, 2> Args;
834 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
837 unsigned Size = Args.size();
838 Expr **StartArg = Size == 0 ? 0 : &Args[0];
839 D->addAttr(::new (S.Context)
840 ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context,
841 Attr.getArg(0), StartArg, Size,
842 Attr.getAttributeSpellingListIndex()));
845 static bool checkLocksRequiredCommon(Sema &S, Decl *D,
846 const AttributeList &Attr,
847 SmallVector<Expr*, 1> &Args) {
848 assert(!Attr.isInvalid());
850 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
853 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
854 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
855 << Attr.getName() << ThreadExpectedFunctionOrMethod;
859 // check that all arguments are lockable objects
860 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
867 static void handleExclusiveLocksRequiredAttr(Sema &S, Decl *D,
868 const AttributeList &Attr) {
869 SmallVector<Expr*, 1> Args;
870 if (!checkLocksRequiredCommon(S, D, Attr, Args))
873 Expr **StartArg = &Args[0];
874 D->addAttr(::new (S.Context)
875 ExclusiveLocksRequiredAttr(Attr.getRange(), S.Context,
876 StartArg, Args.size(),
877 Attr.getAttributeSpellingListIndex()));
880 static void handleSharedLocksRequiredAttr(Sema &S, Decl *D,
881 const AttributeList &Attr) {
882 SmallVector<Expr*, 1> Args;
883 if (!checkLocksRequiredCommon(S, D, Attr, Args))
886 Expr **StartArg = &Args[0];
887 D->addAttr(::new (S.Context)
888 SharedLocksRequiredAttr(Attr.getRange(), S.Context,
889 StartArg, Args.size(),
890 Attr.getAttributeSpellingListIndex()));
893 static void handleUnlockFunAttr(Sema &S, Decl *D,
894 const AttributeList &Attr) {
895 assert(!Attr.isInvalid());
897 // zero or more arguments ok
899 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
900 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
901 << Attr.getName() << ThreadExpectedFunctionOrMethod;
905 // check that all arguments are lockable objects
906 SmallVector<Expr*, 1> Args;
907 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
908 unsigned Size = Args.size();
909 Expr **StartArg = Size == 0 ? 0 : &Args[0];
911 D->addAttr(::new (S.Context)
912 UnlockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
913 Attr.getAttributeSpellingListIndex()));
916 static void handleLockReturnedAttr(Sema &S, Decl *D,
917 const AttributeList &Attr) {
918 assert(!Attr.isInvalid());
920 if (!checkAttributeNumArgs(S, Attr, 1))
923 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
924 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
925 << Attr.getName() << ThreadExpectedFunctionOrMethod;
929 // check that the argument is lockable object
930 SmallVector<Expr*, 1> Args;
931 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
932 unsigned Size = Args.size();
936 D->addAttr(::new (S.Context)
937 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
938 Attr.getAttributeSpellingListIndex()));
941 static void handleLocksExcludedAttr(Sema &S, Decl *D,
942 const AttributeList &Attr) {
943 assert(!Attr.isInvalid());
945 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
948 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
949 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
950 << Attr.getName() << ThreadExpectedFunctionOrMethod;
954 // check that all arguments are lockable objects
955 SmallVector<Expr*, 1> Args;
956 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
957 unsigned Size = Args.size();
960 Expr **StartArg = &Args[0];
962 D->addAttr(::new (S.Context)
963 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
964 Attr.getAttributeSpellingListIndex()));
968 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
969 const AttributeList &Attr) {
970 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
972 // __attribute__((ext_vector_type(N))) can only be applied to typedefs
974 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
978 // Remember this typedef decl, we will need it later for diagnostics.
979 S.ExtVectorDecls.push_back(TD);
982 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
983 // check the attribute arguments.
984 if (!checkAttributeNumArgs(S, Attr, 0))
987 if (TagDecl *TD = dyn_cast<TagDecl>(D))
988 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
989 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
990 // If the alignment is less than or equal to 8 bits, the packed attribute
992 if (!FD->getType()->isDependentType() &&
993 !FD->getType()->isIncompleteType() &&
994 S.Context.getTypeAlign(FD->getType()) <= 8)
995 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
996 << Attr.getName() << FD->getType();
998 FD->addAttr(::new (S.Context)
999 PackedAttr(Attr.getRange(), S.Context,
1000 Attr.getAttributeSpellingListIndex()));
1002 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1005 static void handleMsStructAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1006 if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
1007 RD->addAttr(::new (S.Context)
1008 MsStructAttr(Attr.getRange(), S.Context,
1009 Attr.getAttributeSpellingListIndex()));
1011 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1014 static void handleIBAction(Sema &S, Decl *D, const AttributeList &Attr) {
1015 // check the attribute arguments.
1016 if (!checkAttributeNumArgs(S, Attr, 0))
1019 // The IBAction attributes only apply to instance methods.
1020 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1021 if (MD->isInstanceMethod()) {
1022 D->addAttr(::new (S.Context)
1023 IBActionAttr(Attr.getRange(), S.Context,
1024 Attr.getAttributeSpellingListIndex()));
1028 S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
1031 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1032 // The IBOutlet/IBOutletCollection attributes only apply to instance
1033 // variables or properties of Objective-C classes. The outlet must also
1034 // have an object reference type.
1035 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1036 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1037 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1038 << Attr.getName() << VD->getType() << 0;
1042 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1043 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1044 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1045 << Attr.getName() << PD->getType() << 1;
1050 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1057 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1058 // check the attribute arguments.
1059 if (!checkAttributeNumArgs(S, Attr, 0))
1062 if (!checkIBOutletCommon(S, D, Attr))
1065 D->addAttr(::new (S.Context)
1066 IBOutletAttr(Attr.getRange(), S.Context,
1067 Attr.getAttributeSpellingListIndex()));
1070 static void handleIBOutletCollection(Sema &S, Decl *D,
1071 const AttributeList &Attr) {
1073 // The iboutletcollection attribute can have zero or one arguments.
1074 if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
1075 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1079 if (!checkIBOutletCommon(S, D, Attr))
1082 IdentifierInfo *II = Attr.getParameterName();
1084 II = &S.Context.Idents.get("NSObject");
1086 ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
1087 S.getScopeForContext(D->getDeclContext()->getParent()));
1089 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1092 QualType QT = TypeRep.get();
1093 // Diagnose use of non-object type in iboutletcollection attribute.
1094 // FIXME. Gnu attribute extension ignores use of builtin types in
1095 // attributes. So, __attribute__((iboutletcollection(char))) will be
1096 // treated as __attribute__((iboutletcollection())).
1097 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1098 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1101 D->addAttr(::new (S.Context)
1102 IBOutletCollectionAttr(Attr.getRange(),S.Context,
1103 QT, Attr.getParameterLoc(),
1104 Attr.getAttributeSpellingListIndex()));
1107 static void possibleTransparentUnionPointerType(QualType &T) {
1108 if (const RecordType *UT = T->getAsUnionType())
1109 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1110 RecordDecl *UD = UT->getDecl();
1111 for (RecordDecl::field_iterator it = UD->field_begin(),
1112 itend = UD->field_end(); it != itend; ++it) {
1113 QualType QT = it->getType();
1114 if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
1122 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1123 if (!isFunctionOrMethod(D)) {
1124 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1125 << "alloc_size" << ExpectedFunctionOrMethod;
1129 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1132 // In C++ the implicit 'this' function parameter also counts, and they are
1133 // counted from one.
1134 bool HasImplicitThisParam = isInstanceMethod(D);
1136 if (hasFunctionProto(D))
1137 NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1141 SmallVector<unsigned, 8> SizeArgs;
1143 for (AttributeList::arg_iterator I = Attr.arg_begin(),
1144 E = Attr.arg_end(); I!=E; ++I) {
1145 // The argument must be an integer constant expression.
1147 llvm::APSInt ArgNum;
1148 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
1149 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
1150 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1151 << "alloc_size" << Ex->getSourceRange();
1155 uint64_t x = ArgNum.getZExtValue();
1157 if (x < 1 || x > NumArgs) {
1158 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1159 << "alloc_size" << I.getArgNum() << Ex->getSourceRange();
1164 if (HasImplicitThisParam) {
1166 S.Diag(Attr.getLoc(),
1167 diag::err_attribute_invalid_implicit_this_argument)
1168 << "alloc_size" << Ex->getSourceRange();
1174 // check if the function argument is of an integer type
1175 QualType T = getFunctionOrMethodArgType(D, x).getNonReferenceType();
1176 if (!T->isIntegerType()) {
1177 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1178 << "alloc_size" << Ex->getSourceRange();
1182 SizeArgs.push_back(x);
1185 // check if the function returns a pointer
1186 if (!getFunctionType(D)->getResultType()->isAnyPointerType()) {
1187 S.Diag(Attr.getLoc(), diag::warn_ns_attribute_wrong_return_type)
1188 << "alloc_size" << 0 /*function*/<< 1 /*pointer*/ << D->getSourceRange();
1191 D->addAttr(::new (S.Context)
1192 AllocSizeAttr(Attr.getRange(), S.Context,
1193 SizeArgs.data(), SizeArgs.size(),
1194 Attr.getAttributeSpellingListIndex()));
1197 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1198 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
1199 // ignore it as well
1200 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
1201 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1202 << Attr.getName() << ExpectedFunction;
1206 // In C++ the implicit 'this' function parameter also counts, and they are
1207 // counted from one.
1208 bool HasImplicitThisParam = isInstanceMethod(D);
1209 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1211 // The nonnull attribute only applies to pointers.
1212 SmallVector<unsigned, 10> NonNullArgs;
1214 for (AttributeList::arg_iterator I = Attr.arg_begin(),
1215 E = Attr.arg_end(); I != E; ++I) {
1216 // The argument must be an integer constant expression.
1218 llvm::APSInt ArgNum(32);
1219 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
1220 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
1221 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1222 << "nonnull" << Ex->getSourceRange();
1226 unsigned x = (unsigned) ArgNum.getZExtValue();
1228 if (x < 1 || x > NumArgs) {
1229 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1230 << "nonnull" << I.getArgNum() << Ex->getSourceRange();
1235 if (HasImplicitThisParam) {
1237 S.Diag(Attr.getLoc(),
1238 diag::err_attribute_invalid_implicit_this_argument)
1239 << "nonnull" << Ex->getSourceRange();
1245 // Is the function argument a pointer type?
1246 QualType T = getFunctionOrMethodArgType(D, x).getNonReferenceType();
1247 possibleTransparentUnionPointerType(T);
1249 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1250 // FIXME: Should also highlight argument in decl.
1251 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
1252 << "nonnull" << Ex->getSourceRange();
1256 NonNullArgs.push_back(x);
1259 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1260 // arguments have a nonnull attribute.
1261 if (NonNullArgs.empty()) {
1262 for (unsigned i = 0, e = getFunctionOrMethodNumArgs(D); i != e; ++i) {
1263 QualType T = getFunctionOrMethodArgType(D, i).getNonReferenceType();
1264 possibleTransparentUnionPointerType(T);
1265 if (T->isAnyPointerType() || T->isBlockPointerType())
1266 NonNullArgs.push_back(i);
1269 // No pointer arguments?
1270 if (NonNullArgs.empty()) {
1271 // Warn the trivial case only if attribute is not coming from a
1272 // macro instantiation.
1273 if (Attr.getLoc().isFileID())
1274 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1279 unsigned *start = &NonNullArgs[0];
1280 unsigned size = NonNullArgs.size();
1281 llvm::array_pod_sort(start, start + size);
1282 D->addAttr(::new (S.Context)
1283 NonNullAttr(Attr.getRange(), S.Context, start, size,
1284 Attr.getAttributeSpellingListIndex()));
1287 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1288 // This attribute must be applied to a function declaration.
1289 // The first argument to the attribute must be a string,
1290 // the name of the resource, for example "malloc".
1291 // The following arguments must be argument indexes, the arguments must be
1292 // of integer type for Returns, otherwise of pointer type.
1293 // The difference between Holds and Takes is that a pointer may still be used
1294 // after being held. free() should be __attribute((ownership_takes)), whereas
1295 // a list append function may well be __attribute((ownership_holds)).
1297 if (!AL.getParameterName()) {
1298 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
1299 << AL.getName()->getName() << 1;
1302 // Figure out our Kind, and check arguments while we're at it.
1303 OwnershipAttr::OwnershipKind K;
1304 switch (AL.getKind()) {
1305 case AttributeList::AT_ownership_takes:
1306 K = OwnershipAttr::Takes;
1307 if (AL.getNumArgs() < 1) {
1308 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1312 case AttributeList::AT_ownership_holds:
1313 K = OwnershipAttr::Holds;
1314 if (AL.getNumArgs() < 1) {
1315 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1319 case AttributeList::AT_ownership_returns:
1320 K = OwnershipAttr::Returns;
1321 if (AL.getNumArgs() > 1) {
1322 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
1323 << AL.getNumArgs() + 1;
1328 // This should never happen given how we are called.
1329 llvm_unreachable("Unknown ownership attribute");
1332 if (!isFunction(D) || !hasFunctionProto(D)) {
1333 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
1334 << AL.getName() << ExpectedFunction;
1338 // In C++ the implicit 'this' function parameter also counts, and they are
1339 // counted from one.
1340 bool HasImplicitThisParam = isInstanceMethod(D);
1341 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
1343 StringRef Module = AL.getParameterName()->getName();
1345 // Normalize the argument, __foo__ becomes foo.
1346 if (Module.startswith("__") && Module.endswith("__"))
1347 Module = Module.substr(2, Module.size() - 4);
1349 SmallVector<unsigned, 10> OwnershipArgs;
1351 for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
1355 llvm::APSInt ArgNum(32);
1356 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1357 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1358 S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
1359 << AL.getName()->getName() << IdxExpr->getSourceRange();
1363 unsigned x = (unsigned) ArgNum.getZExtValue();
1365 if (x > NumArgs || x < 1) {
1366 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
1367 << AL.getName()->getName() << x << IdxExpr->getSourceRange();
1371 if (HasImplicitThisParam) {
1373 S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1374 << "ownership" << IdxExpr->getSourceRange();
1381 case OwnershipAttr::Takes:
1382 case OwnershipAttr::Holds: {
1383 // Is the function argument a pointer type?
1384 QualType T = getFunctionOrMethodArgType(D, x);
1385 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1386 // FIXME: Should also highlight argument in decl.
1387 S.Diag(AL.getLoc(), diag::err_ownership_type)
1388 << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
1390 << IdxExpr->getSourceRange();
1395 case OwnershipAttr::Returns: {
1396 if (AL.getNumArgs() > 1) {
1397 // Is the function argument an integer type?
1398 Expr *IdxExpr = AL.getArg(0);
1399 llvm::APSInt ArgNum(32);
1400 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1401 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1402 S.Diag(AL.getLoc(), diag::err_ownership_type)
1403 << "ownership_returns" << "integer"
1404 << IdxExpr->getSourceRange();
1412 // Check we don't have a conflict with another ownership attribute.
1413 for (specific_attr_iterator<OwnershipAttr>
1414 i = D->specific_attr_begin<OwnershipAttr>(),
1415 e = D->specific_attr_end<OwnershipAttr>();
1417 if ((*i)->getOwnKind() != K) {
1418 for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
1421 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1422 << AL.getName()->getName() << "ownership_*";
1427 OwnershipArgs.push_back(x);
1430 unsigned* start = OwnershipArgs.data();
1431 unsigned size = OwnershipArgs.size();
1432 llvm::array_pod_sort(start, start + size);
1434 if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
1435 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1439 D->addAttr(::new (S.Context)
1440 OwnershipAttr(AL.getLoc(), S.Context, K, Module, start, size,
1441 AL.getAttributeSpellingListIndex()));
1444 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1445 // Check the attribute arguments.
1446 if (Attr.getNumArgs() > 1) {
1447 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1451 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1452 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1453 << Attr.getName() << ExpectedVariableOrFunction;
1457 NamedDecl *nd = cast<NamedDecl>(D);
1461 // static int a __attribute__((weakref ("v2")));
1462 // static int b() __attribute__((weakref ("f3")));
1464 // and ignores the attributes of
1466 // static int a __attribute__((weakref ("v2")));
1469 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1470 if (!Ctx->isFileContext()) {
1471 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
1472 nd->getNameAsString();
1476 // The GCC manual says
1478 // At present, a declaration to which `weakref' is attached can only
1483 // Without a TARGET,
1484 // given as an argument to `weakref' or to `alias', `weakref' is
1485 // equivalent to `weak'.
1487 // gcc 4.4.1 will accept
1488 // int a7 __attribute__((weakref));
1490 // int a7 __attribute__((weak));
1491 // This looks like a bug in gcc. We reject that for now. We should revisit
1492 // it if this behaviour is actually used.
1495 // static ((alias ("y"), weakref)).
1496 // Should we? How to check that weakref is before or after alias?
1498 if (Attr.getNumArgs() == 1) {
1499 Expr *Arg = Attr.getArg(0);
1500 Arg = Arg->IgnoreParenCasts();
1501 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1503 if (!Str || !Str->isAscii()) {
1504 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1508 // GCC will accept anything as the argument of weakref. Should we
1509 // check for an existing decl?
1510 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1514 D->addAttr(::new (S.Context)
1515 WeakRefAttr(Attr.getRange(), S.Context,
1516 Attr.getAttributeSpellingListIndex()));
1519 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1520 // check the attribute arguments.
1521 if (Attr.getNumArgs() != 1) {
1522 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1526 Expr *Arg = Attr.getArg(0);
1527 Arg = Arg->IgnoreParenCasts();
1528 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1530 if (!Str || !Str->isAscii()) {
1531 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1536 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1537 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1541 // FIXME: check if target symbol exists in current file
1543 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1545 Attr.getAttributeSpellingListIndex()));
1548 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1549 // Check the attribute arguments.
1550 if (!checkAttributeNumArgs(S, Attr, 0))
1553 if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
1554 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1555 << Attr.getName() << ExpectedFunctionOrMethod;
1559 D->addAttr(::new (S.Context)
1560 MinSizeAttr(Attr.getRange(), S.Context,
1561 Attr.getAttributeSpellingListIndex()));
1564 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1565 // Check the attribute arguments.
1566 if (!checkAttributeNumArgs(S, Attr, 0))
1569 if (!isa<FunctionDecl>(D)) {
1570 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1571 << Attr.getName() << ExpectedFunction;
1575 if (D->hasAttr<HotAttr>()) {
1576 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1577 << Attr.getName() << "hot";
1581 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1582 Attr.getAttributeSpellingListIndex()));
1585 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1586 // Check the attribute arguments.
1587 if (!checkAttributeNumArgs(S, Attr, 0))
1590 if (!isa<FunctionDecl>(D)) {
1591 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1592 << Attr.getName() << ExpectedFunction;
1596 if (D->hasAttr<ColdAttr>()) {
1597 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1598 << Attr.getName() << "cold";
1602 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1603 Attr.getAttributeSpellingListIndex()));
1606 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1607 // Check the attribute arguments.
1608 if (!checkAttributeNumArgs(S, Attr, 0))
1611 if (!isa<FunctionDecl>(D)) {
1612 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1613 << Attr.getName() << ExpectedFunction;
1617 D->addAttr(::new (S.Context)
1618 NakedAttr(Attr.getRange(), S.Context,
1619 Attr.getAttributeSpellingListIndex()));
1622 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
1623 const AttributeList &Attr) {
1624 // Check the attribute arguments.
1625 if (Attr.hasParameterOrArguments()) {
1626 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1630 if (!isa<FunctionDecl>(D)) {
1631 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1632 << Attr.getName() << ExpectedFunction;
1636 D->addAttr(::new (S.Context)
1637 AlwaysInlineAttr(Attr.getRange(), S.Context,
1638 Attr.getAttributeSpellingListIndex()));
1641 static void handleTLSModelAttr(Sema &S, Decl *D,
1642 const AttributeList &Attr) {
1643 // Check the attribute arguments.
1644 if (Attr.getNumArgs() != 1) {
1645 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1649 Expr *Arg = Attr.getArg(0);
1650 Arg = Arg->IgnoreParenCasts();
1651 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1653 // Check that it is a string.
1655 S.Diag(Attr.getLoc(), diag::err_attribute_not_string) << "tls_model";
1659 if (!isa<VarDecl>(D) || !cast<VarDecl>(D)->getTLSKind()) {
1660 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1661 << Attr.getName() << ExpectedTLSVar;
1665 // Check that the value.
1666 StringRef Model = Str->getString();
1667 if (Model != "global-dynamic" && Model != "local-dynamic"
1668 && Model != "initial-exec" && Model != "local-exec") {
1669 S.Diag(Attr.getLoc(), diag::err_attr_tlsmodel_arg);
1673 D->addAttr(::new (S.Context)
1674 TLSModelAttr(Attr.getRange(), S.Context, Model,
1675 Attr.getAttributeSpellingListIndex()));
1678 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1679 // Check the attribute arguments.
1680 if (Attr.hasParameterOrArguments()) {
1681 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1686 QualType RetTy = FD->getResultType();
1687 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1688 D->addAttr(::new (S.Context)
1689 MallocAttr(Attr.getRange(), S.Context,
1690 Attr.getAttributeSpellingListIndex()));
1695 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1698 static void handleMayAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1699 // check the attribute arguments.
1700 if (!checkAttributeNumArgs(S, Attr, 0))
1703 D->addAttr(::new (S.Context)
1704 MayAliasAttr(Attr.getRange(), S.Context,
1705 Attr.getAttributeSpellingListIndex()));
1708 static void handleNoCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1709 assert(!Attr.isInvalid());
1710 if (isa<VarDecl>(D))
1711 D->addAttr(::new (S.Context)
1712 NoCommonAttr(Attr.getRange(), S.Context,
1713 Attr.getAttributeSpellingListIndex()));
1715 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1716 << Attr.getName() << ExpectedVariable;
1719 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1720 assert(!Attr.isInvalid());
1721 if (isa<VarDecl>(D))
1722 D->addAttr(::new (S.Context)
1723 CommonAttr(Attr.getRange(), S.Context,
1724 Attr.getAttributeSpellingListIndex()));
1726 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1727 << Attr.getName() << ExpectedVariable;
1730 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1731 if (hasDeclarator(D)) return;
1733 if (S.CheckNoReturnAttr(attr)) return;
1735 if (!isa<ObjCMethodDecl>(D)) {
1736 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1737 << attr.getName() << ExpectedFunctionOrMethod;
1741 D->addAttr(::new (S.Context)
1742 NoReturnAttr(attr.getRange(), S.Context,
1743 attr.getAttributeSpellingListIndex()));
1746 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1747 if (attr.hasParameterOrArguments()) {
1748 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1756 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1757 const AttributeList &Attr) {
1759 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1760 // because 'analyzer_noreturn' does not impact the type.
1762 if(!checkAttributeNumArgs(S, Attr, 0))
1765 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1766 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1767 if (VD == 0 || (!VD->getType()->isBlockPointerType()
1768 && !VD->getType()->isFunctionPointerType())) {
1769 S.Diag(Attr.getLoc(),
1770 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1771 : diag::warn_attribute_wrong_decl_type)
1772 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1777 D->addAttr(::new (S.Context)
1778 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1779 Attr.getAttributeSpellingListIndex()));
1782 static void handleCXX11NoReturnAttr(Sema &S, Decl *D,
1783 const AttributeList &Attr) {
1784 // C++11 [dcl.attr.noreturn]p1:
1785 // The attribute may be applied to the declarator-id in a function
1787 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1789 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1790 << Attr.getName() << ExpectedFunctionOrMethod;
1794 D->addAttr(::new (S.Context)
1795 CXX11NoReturnAttr(Attr.getRange(), S.Context,
1796 Attr.getAttributeSpellingListIndex()));
1799 // PS3 PPU-specific.
1800 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1802 Returning a Vector Class in Registers
1804 According to the PPU ABI specifications, a class with a single member of
1805 vector type is returned in memory when used as the return value of a function.
1806 This results in inefficient code when implementing vector classes. To return
1807 the value in a single vector register, add the vecreturn attribute to the
1808 class definition. This attribute is also applicable to struct types.
1814 __vector float xyzw;
1815 } __attribute__((vecreturn));
1817 Vector Add(Vector lhs, Vector rhs)
1820 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1821 return result; // This will be returned in a register
1824 if (!isa<RecordDecl>(D)) {
1825 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1826 << Attr.getName() << ExpectedClass;
1830 if (D->getAttr<VecReturnAttr>()) {
1831 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
1835 RecordDecl *record = cast<RecordDecl>(D);
1838 if (!isa<CXXRecordDecl>(record)) {
1839 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1843 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1844 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1848 for (RecordDecl::field_iterator iter = record->field_begin();
1849 iter != record->field_end(); iter++) {
1850 if ((count == 1) || !iter->getType()->isVectorType()) {
1851 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1857 D->addAttr(::new (S.Context)
1858 VecReturnAttr(Attr.getRange(), S.Context,
1859 Attr.getAttributeSpellingListIndex()));
1862 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1863 const AttributeList &Attr) {
1864 if (isa<ParmVarDecl>(D)) {
1865 // [[carries_dependency]] can only be applied to a parameter if it is a
1866 // parameter of a function declaration or lambda.
1867 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1868 S.Diag(Attr.getLoc(),
1869 diag::err_carries_dependency_param_not_function_decl);
1872 } else if (!isa<FunctionDecl>(D)) {
1873 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1874 << Attr.getName() << ExpectedFunctionMethodOrParameter;
1878 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1879 Attr.getRange(), S.Context,
1880 Attr.getAttributeSpellingListIndex()));
1883 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1884 // check the attribute arguments.
1885 if (Attr.hasParameterOrArguments()) {
1886 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1890 if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isFunctionOrMethod(D) &&
1891 !isa<TypeDecl>(D) && !isa<LabelDecl>(D) && !isa<FieldDecl>(D)) {
1892 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1893 << Attr.getName() << ExpectedVariableFunctionOrLabel;
1897 D->addAttr(::new (S.Context)
1898 UnusedAttr(Attr.getRange(), S.Context,
1899 Attr.getAttributeSpellingListIndex()));
1902 static void handleReturnsTwiceAttr(Sema &S, Decl *D,
1903 const AttributeList &Attr) {
1904 // check the attribute arguments.
1905 if (Attr.hasParameterOrArguments()) {
1906 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1910 if (!isa<FunctionDecl>(D)) {
1911 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1912 << Attr.getName() << ExpectedFunction;
1916 D->addAttr(::new (S.Context)
1917 ReturnsTwiceAttr(Attr.getRange(), S.Context,
1918 Attr.getAttributeSpellingListIndex()));
1921 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1922 // check the attribute arguments.
1923 if (Attr.hasParameterOrArguments()) {
1924 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1928 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1929 if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
1930 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
1933 } else if (!isFunctionOrMethod(D)) {
1934 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1935 << Attr.getName() << ExpectedVariableOrFunction;
1939 D->addAttr(::new (S.Context)
1940 UsedAttr(Attr.getRange(), S.Context,
1941 Attr.getAttributeSpellingListIndex()));
1944 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1945 // check the attribute arguments.
1946 if (Attr.getNumArgs() > 1) {
1947 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1951 int priority = 65535; // FIXME: Do not hardcode such constants.
1952 if (Attr.getNumArgs() > 0) {
1953 Expr *E = Attr.getArg(0);
1954 llvm::APSInt Idx(32);
1955 if (E->isTypeDependent() || E->isValueDependent() ||
1956 !E->isIntegerConstantExpr(Idx, S.Context)) {
1957 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1958 << "constructor" << 1 << E->getSourceRange();
1961 priority = Idx.getZExtValue();
1964 if (!isa<FunctionDecl>(D)) {
1965 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1966 << Attr.getName() << ExpectedFunction;
1970 D->addAttr(::new (S.Context)
1971 ConstructorAttr(Attr.getRange(), S.Context, priority,
1972 Attr.getAttributeSpellingListIndex()));
1975 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1976 // check the attribute arguments.
1977 if (Attr.getNumArgs() > 1) {
1978 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1982 int priority = 65535; // FIXME: Do not hardcode such constants.
1983 if (Attr.getNumArgs() > 0) {
1984 Expr *E = Attr.getArg(0);
1985 llvm::APSInt Idx(32);
1986 if (E->isTypeDependent() || E->isValueDependent() ||
1987 !E->isIntegerConstantExpr(Idx, S.Context)) {
1988 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1989 << "destructor" << 1 << E->getSourceRange();
1992 priority = Idx.getZExtValue();
1995 if (!isa<FunctionDecl>(D)) {
1996 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1997 << Attr.getName() << ExpectedFunction;
2001 D->addAttr(::new (S.Context)
2002 DestructorAttr(Attr.getRange(), S.Context, priority,
2003 Attr.getAttributeSpellingListIndex()));
2006 template <typename AttrTy>
2007 static void handleAttrWithMessage(Sema &S, Decl *D, const AttributeList &Attr,
2009 unsigned NumArgs = Attr.getNumArgs();
2011 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
2015 // Handle the case where the attribute has a text message.
2018 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
2020 S.Diag(Attr.getArg(0)->getLocStart(), diag::err_attribute_not_string)
2024 Str = SE->getString();
2027 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2028 Attr.getAttributeSpellingListIndex()));
2031 static void handleArcWeakrefUnavailableAttr(Sema &S, Decl *D,
2032 const AttributeList &Attr) {
2033 unsigned NumArgs = Attr.getNumArgs();
2035 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
2039 D->addAttr(::new (S.Context)
2040 ArcWeakrefUnavailableAttr(Attr.getRange(), S.Context,
2041 Attr.getAttributeSpellingListIndex()));
2044 static void handleObjCRootClassAttr(Sema &S, Decl *D,
2045 const AttributeList &Attr) {
2046 if (!isa<ObjCInterfaceDecl>(D)) {
2047 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
2051 unsigned NumArgs = Attr.getNumArgs();
2053 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
2057 D->addAttr(::new (S.Context)
2058 ObjCRootClassAttr(Attr.getRange(), S.Context,
2059 Attr.getAttributeSpellingListIndex()));
2062 static void handleObjCRequiresPropertyDefsAttr(Sema &S, Decl *D,
2063 const AttributeList &Attr) {
2064 if (!isa<ObjCInterfaceDecl>(D)) {
2065 S.Diag(Attr.getLoc(), diag::err_suppress_autosynthesis);
2069 unsigned NumArgs = Attr.getNumArgs();
2071 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
2075 D->addAttr(::new (S.Context)
2076 ObjCRequiresPropertyDefsAttr(Attr.getRange(), S.Context,
2077 Attr.getAttributeSpellingListIndex()));
2080 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2081 IdentifierInfo *Platform,
2082 VersionTuple Introduced,
2083 VersionTuple Deprecated,
2084 VersionTuple Obsoleted) {
2085 StringRef PlatformName
2086 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2087 if (PlatformName.empty())
2088 PlatformName = Platform->getName();
2090 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2091 // of these steps are needed).
2092 if (!Introduced.empty() && !Deprecated.empty() &&
2093 !(Introduced <= Deprecated)) {
2094 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2095 << 1 << PlatformName << Deprecated.getAsString()
2096 << 0 << Introduced.getAsString();
2100 if (!Introduced.empty() && !Obsoleted.empty() &&
2101 !(Introduced <= Obsoleted)) {
2102 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2103 << 2 << PlatformName << Obsoleted.getAsString()
2104 << 0 << Introduced.getAsString();
2108 if (!Deprecated.empty() && !Obsoleted.empty() &&
2109 !(Deprecated <= Obsoleted)) {
2110 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2111 << 2 << PlatformName << Obsoleted.getAsString()
2112 << 1 << Deprecated.getAsString();
2119 /// \brief Check whether the two versions match.
2121 /// If either version tuple is empty, then they are assumed to match. If
2122 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2123 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2124 bool BeforeIsOkay) {
2125 if (X.empty() || Y.empty())
2131 if (BeforeIsOkay && X < Y)
2137 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2138 IdentifierInfo *Platform,
2139 VersionTuple Introduced,
2140 VersionTuple Deprecated,
2141 VersionTuple Obsoleted,
2145 unsigned AttrSpellingListIndex) {
2146 VersionTuple MergedIntroduced = Introduced;
2147 VersionTuple MergedDeprecated = Deprecated;
2148 VersionTuple MergedObsoleted = Obsoleted;
2149 bool FoundAny = false;
2151 if (D->hasAttrs()) {
2152 AttrVec &Attrs = D->getAttrs();
2153 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2154 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2160 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2161 if (OldPlatform != Platform) {
2167 VersionTuple OldIntroduced = OldAA->getIntroduced();
2168 VersionTuple OldDeprecated = OldAA->getDeprecated();
2169 VersionTuple OldObsoleted = OldAA->getObsoleted();
2170 bool OldIsUnavailable = OldAA->getUnavailable();
2172 if (!versionsMatch(OldIntroduced, Introduced, Override) ||
2173 !versionsMatch(Deprecated, OldDeprecated, Override) ||
2174 !versionsMatch(Obsoleted, OldObsoleted, Override) ||
2175 !(OldIsUnavailable == IsUnavailable ||
2176 (Override && !OldIsUnavailable && IsUnavailable))) {
2179 VersionTuple FirstVersion;
2180 VersionTuple SecondVersion;
2181 if (!versionsMatch(OldIntroduced, Introduced, Override)) {
2183 FirstVersion = OldIntroduced;
2184 SecondVersion = Introduced;
2185 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
2187 FirstVersion = Deprecated;
2188 SecondVersion = OldDeprecated;
2189 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
2191 FirstVersion = Obsoleted;
2192 SecondVersion = OldObsoleted;
2196 Diag(OldAA->getLocation(),
2197 diag::warn_mismatched_availability_override_unavail)
2198 << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2200 Diag(OldAA->getLocation(),
2201 diag::warn_mismatched_availability_override)
2203 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2204 << FirstVersion.getAsString() << SecondVersion.getAsString();
2206 Diag(Range.getBegin(), diag::note_overridden_method);
2208 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2209 Diag(Range.getBegin(), diag::note_previous_attribute);
2212 Attrs.erase(Attrs.begin() + i);
2217 VersionTuple MergedIntroduced2 = MergedIntroduced;
2218 VersionTuple MergedDeprecated2 = MergedDeprecated;
2219 VersionTuple MergedObsoleted2 = MergedObsoleted;
2221 if (MergedIntroduced2.empty())
2222 MergedIntroduced2 = OldIntroduced;
2223 if (MergedDeprecated2.empty())
2224 MergedDeprecated2 = OldDeprecated;
2225 if (MergedObsoleted2.empty())
2226 MergedObsoleted2 = OldObsoleted;
2228 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2229 MergedIntroduced2, MergedDeprecated2,
2230 MergedObsoleted2)) {
2231 Attrs.erase(Attrs.begin() + i);
2236 MergedIntroduced = MergedIntroduced2;
2237 MergedDeprecated = MergedDeprecated2;
2238 MergedObsoleted = MergedObsoleted2;
2244 MergedIntroduced == Introduced &&
2245 MergedDeprecated == Deprecated &&
2246 MergedObsoleted == Obsoleted)
2249 // Only create a new attribute if !Override, but we want to do
2251 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2252 MergedDeprecated, MergedObsoleted) &&
2254 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2255 Introduced, Deprecated,
2256 Obsoleted, IsUnavailable, Message,
2257 AttrSpellingListIndex);
2262 static void handleAvailabilityAttr(Sema &S, Decl *D,
2263 const AttributeList &Attr) {
2264 IdentifierInfo *Platform = Attr.getParameterName();
2265 SourceLocation PlatformLoc = Attr.getParameterLoc();
2266 unsigned Index = Attr.getAttributeSpellingListIndex();
2268 if (AvailabilityAttr::getPrettyPlatformName(Platform->getName()).empty())
2269 S.Diag(PlatformLoc, diag::warn_availability_unknown_platform)
2272 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2274 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2278 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2279 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2280 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2281 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2283 const StringLiteral *SE =
2284 dyn_cast_or_null<const StringLiteral>(Attr.getMessageExpr());
2286 Str = SE->getString();
2288 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(),
2297 D->addAttr(NewAttr);
2301 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2302 typename T::VisibilityType value,
2303 unsigned attrSpellingListIndex) {
2304 T *existingAttr = D->getAttr<T>();
2306 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2307 if (existingValue == value)
2309 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2310 S.Diag(range.getBegin(), diag::note_previous_attribute);
2313 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2316 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2317 VisibilityAttr::VisibilityType Vis,
2318 unsigned AttrSpellingListIndex) {
2319 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2320 AttrSpellingListIndex);
2323 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2324 TypeVisibilityAttr::VisibilityType Vis,
2325 unsigned AttrSpellingListIndex) {
2326 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2327 AttrSpellingListIndex);
2330 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2331 bool isTypeVisibility) {
2332 // Visibility attributes don't mean anything on a typedef.
2333 if (isa<TypedefNameDecl>(D)) {
2334 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2339 // 'type_visibility' can only go on a type or namespace.
2340 if (isTypeVisibility &&
2341 !(isa<TagDecl>(D) ||
2342 isa<ObjCInterfaceDecl>(D) ||
2343 isa<NamespaceDecl>(D))) {
2344 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2345 << Attr.getName() << ExpectedTypeOrNamespace;
2349 // check the attribute arguments.
2350 if (!checkAttributeNumArgs(S, Attr, 1))
2353 Expr *Arg = Attr.getArg(0);
2354 Arg = Arg->IgnoreParenCasts();
2355 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2357 if (!Str || !Str->isAscii()) {
2358 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2359 << (isTypeVisibility ? "type_visibility" : "visibility") << 1;
2363 StringRef TypeStr = Str->getString();
2364 VisibilityAttr::VisibilityType type;
2366 if (TypeStr == "default")
2367 type = VisibilityAttr::Default;
2368 else if (TypeStr == "hidden")
2369 type = VisibilityAttr::Hidden;
2370 else if (TypeStr == "internal")
2371 type = VisibilityAttr::Hidden; // FIXME
2372 else if (TypeStr == "protected") {
2373 // Complain about attempts to use protected visibility on targets
2374 // (like Darwin) that don't support it.
2375 if (!S.Context.getTargetInfo().hasProtectedVisibility()) {
2376 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2377 type = VisibilityAttr::Default;
2379 type = VisibilityAttr::Protected;
2382 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
2386 unsigned Index = Attr.getAttributeSpellingListIndex();
2387 clang::Attr *newAttr;
2388 if (isTypeVisibility) {
2389 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2390 (TypeVisibilityAttr::VisibilityType) type,
2393 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2396 D->addAttr(newAttr);
2399 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2400 const AttributeList &Attr) {
2401 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
2403 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2408 if (Attr.getNumArgs() != 0 || !Attr.getParameterName()) {
2409 if (!Attr.getParameterName() && Attr.getNumArgs() == 1) {
2410 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2411 << "objc_method_family" << 1;
2413 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2419 StringRef param = Attr.getParameterName()->getName();
2420 ObjCMethodFamilyAttr::FamilyKind family;
2421 if (param == "none")
2422 family = ObjCMethodFamilyAttr::OMF_None;
2423 else if (param == "alloc")
2424 family = ObjCMethodFamilyAttr::OMF_alloc;
2425 else if (param == "copy")
2426 family = ObjCMethodFamilyAttr::OMF_copy;
2427 else if (param == "init")
2428 family = ObjCMethodFamilyAttr::OMF_init;
2429 else if (param == "mutableCopy")
2430 family = ObjCMethodFamilyAttr::OMF_mutableCopy;
2431 else if (param == "new")
2432 family = ObjCMethodFamilyAttr::OMF_new;
2434 // Just warn and ignore it. This is future-proof against new
2435 // families being used in system headers.
2436 S.Diag(Attr.getParameterLoc(), diag::warn_unknown_method_family);
2440 if (family == ObjCMethodFamilyAttr::OMF_init &&
2441 !method->getResultType()->isObjCObjectPointerType()) {
2442 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2443 << method->getResultType();
2444 // Ignore the attribute.
2448 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2449 S.Context, family));
2452 static void handleObjCExceptionAttr(Sema &S, Decl *D,
2453 const AttributeList &Attr) {
2454 if (!checkAttributeNumArgs(S, Attr, 0))
2457 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
2459 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
2463 D->addAttr(::new (S.Context)
2464 ObjCExceptionAttr(Attr.getRange(), S.Context,
2465 Attr.getAttributeSpellingListIndex()));
2468 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2469 if (Attr.getNumArgs() != 0) {
2470 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2473 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2474 QualType T = TD->getUnderlyingType();
2475 if (!T->isCARCBridgableType()) {
2476 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2480 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2481 QualType T = PD->getType();
2482 if (!T->isCARCBridgableType()) {
2483 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2488 // It is okay to include this attribute on properties, e.g.:
2490 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2492 // In this case it follows tradition and suppresses an error in the above
2494 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2496 D->addAttr(::new (S.Context)
2497 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2498 Attr.getAttributeSpellingListIndex()));
2502 handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2503 if (Attr.getNumArgs() != 0) {
2504 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2508 if (!isa<FunctionDecl>(D)) {
2509 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
2513 D->addAttr(::new (S.Context)
2514 OverloadableAttr(Attr.getRange(), S.Context,
2515 Attr.getAttributeSpellingListIndex()));
2518 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2519 if (!Attr.getParameterName()) {
2520 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2525 if (Attr.getNumArgs() != 0) {
2526 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2530 BlocksAttr::BlockType type;
2531 if (Attr.getParameterName()->isStr("byref"))
2532 type = BlocksAttr::ByRef;
2534 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2535 << "blocks" << Attr.getParameterName();
2539 D->addAttr(::new (S.Context)
2540 BlocksAttr(Attr.getRange(), S.Context, type,
2541 Attr.getAttributeSpellingListIndex()));
2544 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2545 // check the attribute arguments.
2546 if (Attr.getNumArgs() > 2) {
2547 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2551 unsigned sentinel = 0;
2552 if (Attr.getNumArgs() > 0) {
2553 Expr *E = Attr.getArg(0);
2554 llvm::APSInt Idx(32);
2555 if (E->isTypeDependent() || E->isValueDependent() ||
2556 !E->isIntegerConstantExpr(Idx, S.Context)) {
2557 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2558 << "sentinel" << 1 << E->getSourceRange();
2562 if (Idx.isSigned() && Idx.isNegative()) {
2563 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2564 << E->getSourceRange();
2568 sentinel = Idx.getZExtValue();
2571 unsigned nullPos = 0;
2572 if (Attr.getNumArgs() > 1) {
2573 Expr *E = Attr.getArg(1);
2574 llvm::APSInt Idx(32);
2575 if (E->isTypeDependent() || E->isValueDependent() ||
2576 !E->isIntegerConstantExpr(Idx, S.Context)) {
2577 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2578 << "sentinel" << 2 << E->getSourceRange();
2581 nullPos = Idx.getZExtValue();
2583 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2584 // FIXME: This error message could be improved, it would be nice
2585 // to say what the bounds actually are.
2586 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2587 << E->getSourceRange();
2592 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2593 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2594 if (isa<FunctionNoProtoType>(FT)) {
2595 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2599 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2600 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2603 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2604 if (!MD->isVariadic()) {
2605 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2608 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2609 if (!BD->isVariadic()) {
2610 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2613 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2614 QualType Ty = V->getType();
2615 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2616 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
2617 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2618 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2619 int m = Ty->isFunctionPointerType() ? 0 : 1;
2620 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2624 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2625 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2629 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2630 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2633 D->addAttr(::new (S.Context)
2634 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2635 Attr.getAttributeSpellingListIndex()));
2638 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2639 // check the attribute arguments.
2640 if (!checkAttributeNumArgs(S, Attr, 0))
2643 if (!isFunction(D) && !isa<ObjCMethodDecl>(D) && !isa<CXXRecordDecl>(D)) {
2644 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2645 << Attr.getName() << ExpectedFunctionMethodOrClass;
2649 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
2650 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2651 << Attr.getName() << 0;
2654 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2655 if (MD->getResultType()->isVoidType()) {
2656 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2657 << Attr.getName() << 1;
2661 D->addAttr(::new (S.Context)
2662 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2663 Attr.getAttributeSpellingListIndex()));
2666 static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2667 // check the attribute arguments.
2668 if (Attr.hasParameterOrArguments()) {
2669 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2673 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
2674 if (isa<CXXRecordDecl>(D)) {
2675 D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2678 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2679 << Attr.getName() << ExpectedVariableOrFunction;
2683 NamedDecl *nd = cast<NamedDecl>(D);
2685 nd->addAttr(::new (S.Context)
2686 WeakAttr(Attr.getRange(), S.Context,
2687 Attr.getAttributeSpellingListIndex()));
2690 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2691 // check the attribute arguments.
2692 if (!checkAttributeNumArgs(S, Attr, 0))
2696 // weak_import only applies to variable & function declarations.
2698 if (!D->canBeWeakImported(isDef)) {
2700 S.Diag(Attr.getLoc(),
2701 diag::warn_attribute_weak_import_invalid_on_definition)
2702 << "weak_import" << 2 /*variable and function*/;
2703 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2704 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2705 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2706 // Nothing to warn about here.
2708 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2709 << Attr.getName() << ExpectedVariableOrFunction;
2714 D->addAttr(::new (S.Context)
2715 WeakImportAttr(Attr.getRange(), S.Context,
2716 Attr.getAttributeSpellingListIndex()));
2719 // Handles reqd_work_group_size and work_group_size_hint.
2720 static void handleWorkGroupSize(Sema &S, Decl *D,
2721 const AttributeList &Attr) {
2722 assert(Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2723 || Attr.getKind() == AttributeList::AT_WorkGroupSizeHint);
2725 // Attribute has 3 arguments.
2726 if (!checkAttributeNumArgs(S, Attr, 3)) return;
2729 for (unsigned i = 0; i < 3; ++i) {
2730 Expr *E = Attr.getArg(i);
2731 llvm::APSInt ArgNum(32);
2732 if (E->isTypeDependent() || E->isValueDependent() ||
2733 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
2734 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2735 << Attr.getName()->getName() << E->getSourceRange();
2738 WGSize[i] = (unsigned) ArgNum.getZExtValue();
2741 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2742 && D->hasAttr<ReqdWorkGroupSizeAttr>()) {
2743 ReqdWorkGroupSizeAttr *A = D->getAttr<ReqdWorkGroupSizeAttr>();
2744 if (!(A->getXDim() == WGSize[0] &&
2745 A->getYDim() == WGSize[1] &&
2746 A->getZDim() == WGSize[2])) {
2747 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2752 if (Attr.getKind() == AttributeList::AT_WorkGroupSizeHint
2753 && D->hasAttr<WorkGroupSizeHintAttr>()) {
2754 WorkGroupSizeHintAttr *A = D->getAttr<WorkGroupSizeHintAttr>();
2755 if (!(A->getXDim() == WGSize[0] &&
2756 A->getYDim() == WGSize[1] &&
2757 A->getZDim() == WGSize[2])) {
2758 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2763 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize)
2764 D->addAttr(::new (S.Context)
2765 ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
2766 WGSize[0], WGSize[1], WGSize[2],
2767 Attr.getAttributeSpellingListIndex()));
2769 D->addAttr(::new (S.Context)
2770 WorkGroupSizeHintAttr(Attr.getRange(), S.Context,
2771 WGSize[0], WGSize[1], WGSize[2],
2772 Attr.getAttributeSpellingListIndex()));
2775 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2776 assert(Attr.getKind() == AttributeList::AT_VecTypeHint);
2778 // Attribute has 1 argument.
2779 if (!checkAttributeNumArgs(S, Attr, 1))
2782 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg());
2784 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2785 (ParmType->isBooleanType() ||
2786 !ParmType->isIntegralType(S.getASTContext()))) {
2787 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2792 if (Attr.getKind() == AttributeList::AT_VecTypeHint &&
2793 D->hasAttr<VecTypeHintAttr>()) {
2794 VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>();
2795 if (A->getTypeHint() != ParmType) {
2796 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2801 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2802 ParmType, Attr.getLoc()));
2805 static void handleEndianAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2806 if (!dyn_cast<VarDecl>(D))
2807 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << "endian"
2809 StringRef EndianType = Attr.getParameterName()->getName();
2810 if (EndianType != "host" && EndianType != "device")
2811 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_endian) << EndianType;
2814 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2816 unsigned AttrSpellingListIndex) {
2817 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2818 if (ExistingAttr->getName() == Name)
2820 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2821 Diag(Range.getBegin(), diag::note_previous_attribute);
2824 return ::new (Context) SectionAttr(Range, Context, Name,
2825 AttrSpellingListIndex);
2828 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2829 // Attribute has no arguments.
2830 if (!checkAttributeNumArgs(S, Attr, 1))
2833 // Make sure that there is a string literal as the sections's single
2835 Expr *ArgExpr = Attr.getArg(0);
2836 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
2838 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
2842 // If the target wants to validate the section specifier, make it happen.
2843 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(SE->getString());
2844 if (!Error.empty()) {
2845 S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
2850 // This attribute cannot be applied to local variables.
2851 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2852 S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
2856 unsigned Index = Attr.getAttributeSpellingListIndex();
2857 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(),
2858 SE->getString(), Index);
2860 D->addAttr(NewAttr);
2864 static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2865 // check the attribute arguments.
2866 if (Attr.hasParameterOrArguments()) {
2867 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2871 if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2872 if (Existing->getLocation().isInvalid())
2873 Existing->setRange(Attr.getRange());
2875 D->addAttr(::new (S.Context)
2876 NoThrowAttr(Attr.getRange(), S.Context,
2877 Attr.getAttributeSpellingListIndex()));
2881 static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2882 // check the attribute arguments.
2883 if (Attr.hasParameterOrArguments()) {
2884 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2888 if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2889 if (Existing->getLocation().isInvalid())
2890 Existing->setRange(Attr.getRange());
2892 D->addAttr(::new (S.Context)
2893 ConstAttr(Attr.getRange(), S.Context,
2894 Attr.getAttributeSpellingListIndex() ));
2898 static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2899 // check the attribute arguments.
2900 if (!checkAttributeNumArgs(S, Attr, 0))
2903 D->addAttr(::new (S.Context)
2904 PureAttr(Attr.getRange(), S.Context,
2905 Attr.getAttributeSpellingListIndex()));
2908 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2909 if (!Attr.getParameterName()) {
2910 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2914 if (Attr.getNumArgs() != 0) {
2915 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2919 VarDecl *VD = dyn_cast<VarDecl>(D);
2921 if (!VD || !VD->hasLocalStorage()) {
2922 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
2926 // Look up the function
2927 // FIXME: Lookup probably isn't looking in the right place
2928 NamedDecl *CleanupDecl
2929 = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
2930 Attr.getParameterLoc(), Sema::LookupOrdinaryName);
2932 S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
2933 Attr.getParameterName();
2937 FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
2939 S.Diag(Attr.getParameterLoc(),
2940 diag::err_attribute_cleanup_arg_not_function)
2941 << Attr.getParameterName();
2945 if (FD->getNumParams() != 1) {
2946 S.Diag(Attr.getParameterLoc(),
2947 diag::err_attribute_cleanup_func_must_take_one_arg)
2948 << Attr.getParameterName();
2952 // We're currently more strict than GCC about what function types we accept.
2953 // If this ever proves to be a problem it should be easy to fix.
2954 QualType Ty = S.Context.getPointerType(VD->getType());
2955 QualType ParamTy = FD->getParamDecl(0)->getType();
2956 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2957 ParamTy, Ty) != Sema::Compatible) {
2958 S.Diag(Attr.getParameterLoc(),
2959 diag::err_attribute_cleanup_func_arg_incompatible_type) <<
2960 Attr.getParameterName() << ParamTy << Ty;
2964 D->addAttr(::new (S.Context)
2965 CleanupAttr(Attr.getRange(), S.Context, FD,
2966 Attr.getAttributeSpellingListIndex()));
2967 S.MarkFunctionReferenced(Attr.getParameterLoc(), FD);
2968 S.DiagnoseUseOfDecl(FD, Attr.getParameterLoc());
2971 /// Handle __attribute__((format_arg((idx)))) attribute based on
2972 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2973 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2974 if (!checkAttributeNumArgs(S, Attr, 1))
2977 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2978 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2979 << Attr.getName() << ExpectedFunction;
2983 // In C++ the implicit 'this' function parameter also counts, and they are
2984 // counted from one.
2985 bool HasImplicitThisParam = isInstanceMethod(D);
2986 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2987 unsigned FirstIdx = 1;
2989 // checks for the 2nd argument
2990 Expr *IdxExpr = Attr.getArg(0);
2991 llvm::APSInt Idx(32);
2992 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2993 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2994 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2995 << "format" << 2 << IdxExpr->getSourceRange();
2999 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
3000 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3001 << "format" << 2 << IdxExpr->getSourceRange();
3005 unsigned ArgIdx = Idx.getZExtValue() - 1;
3007 if (HasImplicitThisParam) {
3009 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
3010 << "format_arg" << IdxExpr->getSourceRange();
3016 // make sure the format string is really a string
3017 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
3019 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
3020 if (not_nsstring_type &&
3021 !isCFStringType(Ty, S.Context) &&
3022 (!Ty->isPointerType() ||
3023 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3024 // FIXME: Should highlight the actual expression that has the wrong type.
3025 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3026 << (not_nsstring_type ? "a string type" : "an NSString")
3027 << IdxExpr->getSourceRange();
3030 Ty = getFunctionOrMethodResultType(D);
3031 if (!isNSStringType(Ty, S.Context) &&
3032 !isCFStringType(Ty, S.Context) &&
3033 (!Ty->isPointerType() ||
3034 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3035 // FIXME: Should highlight the actual expression that has the wrong type.
3036 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3037 << (not_nsstring_type ? "string type" : "NSString")
3038 << IdxExpr->getSourceRange();
3042 D->addAttr(::new (S.Context)
3043 FormatArgAttr(Attr.getRange(), S.Context, Idx.getZExtValue(),
3044 Attr.getAttributeSpellingListIndex()));
3047 enum FormatAttrKind {
3056 /// getFormatAttrKind - Map from format attribute names to supported format
3058 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3059 return llvm::StringSwitch<FormatAttrKind>(Format)
3060 // Check for formats that get handled specially.
3061 .Case("NSString", NSStringFormat)
3062 .Case("CFString", CFStringFormat)
3063 .Case("strftime", StrftimeFormat)
3065 // Otherwise, check for supported formats.
3066 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3067 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3068 .Case("kprintf", SupportedFormat) // OpenBSD.
3070 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3071 .Default(InvalidFormat);
3074 /// Handle __attribute__((init_priority(priority))) attributes based on
3075 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3076 static void handleInitPriorityAttr(Sema &S, Decl *D,
3077 const AttributeList &Attr) {
3078 if (!S.getLangOpts().CPlusPlus) {
3079 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3083 if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
3084 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3088 QualType T = dyn_cast<VarDecl>(D)->getType();
3089 if (S.Context.getAsArrayType(T))
3090 T = S.Context.getBaseElementType(T);
3091 if (!T->getAs<RecordType>()) {
3092 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3097 if (Attr.getNumArgs() != 1) {
3098 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3102 Expr *priorityExpr = Attr.getArg(0);
3104 llvm::APSInt priority(32);
3105 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
3106 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
3107 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3108 << "init_priority" << priorityExpr->getSourceRange();
3112 unsigned prioritynum = priority.getZExtValue();
3113 if (prioritynum < 101 || prioritynum > 65535) {
3114 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3115 << priorityExpr->getSourceRange();
3119 D->addAttr(::new (S.Context)
3120 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3121 Attr.getAttributeSpellingListIndex()));
3124 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
3125 int FormatIdx, int FirstArg,
3126 unsigned AttrSpellingListIndex) {
3127 // Check whether we already have an equivalent format attribute.
3128 for (specific_attr_iterator<FormatAttr>
3129 i = D->specific_attr_begin<FormatAttr>(),
3130 e = D->specific_attr_end<FormatAttr>();
3133 if (f->getType() == Format &&
3134 f->getFormatIdx() == FormatIdx &&
3135 f->getFirstArg() == FirstArg) {
3136 // If we don't have a valid location for this attribute, adopt the
3138 if (f->getLocation().isInvalid())
3144 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, FirstArg,
3145 AttrSpellingListIndex);
3148 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3149 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3150 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3152 if (!Attr.getParameterName()) {
3153 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
3158 if (Attr.getNumArgs() != 2) {
3159 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
3163 if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
3164 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3165 << Attr.getName() << ExpectedFunction;
3169 // In C++ the implicit 'this' function parameter also counts, and they are
3170 // counted from one.
3171 bool HasImplicitThisParam = isInstanceMethod(D);
3172 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
3173 unsigned FirstIdx = 1;
3175 StringRef Format = Attr.getParameterName()->getName();
3177 // Normalize the argument, __foo__ becomes foo.
3178 if (Format.startswith("__") && Format.endswith("__"))
3179 Format = Format.substr(2, Format.size() - 4);
3181 // Check for supported formats.
3182 FormatAttrKind Kind = getFormatAttrKind(Format);
3184 if (Kind == IgnoredFormat)
3187 if (Kind == InvalidFormat) {
3188 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3189 << "format" << Attr.getParameterName()->getName();
3193 // checks for the 2nd argument
3194 Expr *IdxExpr = Attr.getArg(0);
3195 llvm::APSInt Idx(32);
3196 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
3197 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
3198 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3199 << "format" << 2 << IdxExpr->getSourceRange();
3203 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
3204 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3205 << "format" << 2 << IdxExpr->getSourceRange();
3209 // FIXME: Do we need to bounds check?
3210 unsigned ArgIdx = Idx.getZExtValue() - 1;
3212 if (HasImplicitThisParam) {
3214 S.Diag(Attr.getLoc(),
3215 diag::err_format_attribute_implicit_this_format_string)
3216 << IdxExpr->getSourceRange();
3222 // make sure the format string is really a string
3223 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
3225 if (Kind == CFStringFormat) {
3226 if (!isCFStringType(Ty, S.Context)) {
3227 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3228 << "a CFString" << IdxExpr->getSourceRange();
3231 } else if (Kind == NSStringFormat) {
3232 // FIXME: do we need to check if the type is NSString*? What are the
3234 if (!isNSStringType(Ty, S.Context)) {
3235 // FIXME: Should highlight the actual expression that has the wrong type.
3236 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3237 << "an NSString" << IdxExpr->getSourceRange();
3240 } else if (!Ty->isPointerType() ||
3241 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3242 // FIXME: Should highlight the actual expression that has the wrong type.
3243 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3244 << "a string type" << IdxExpr->getSourceRange();
3248 // check the 3rd argument
3249 Expr *FirstArgExpr = Attr.getArg(1);
3250 llvm::APSInt FirstArg(32);
3251 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
3252 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
3253 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3254 << "format" << 3 << FirstArgExpr->getSourceRange();
3258 // check if the function is variadic if the 3rd argument non-zero
3259 if (FirstArg != 0) {
3260 if (isFunctionOrMethodVariadic(D)) {
3261 ++NumArgs; // +1 for ...
3263 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3268 // strftime requires FirstArg to be 0 because it doesn't read from any
3269 // variable the input is just the current time + the format string.
3270 if (Kind == StrftimeFormat) {
3271 if (FirstArg != 0) {
3272 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3273 << FirstArgExpr->getSourceRange();
3276 // if 0 it disables parameter checking (to use with e.g. va_list)
3277 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3278 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3279 << "format" << 3 << FirstArgExpr->getSourceRange();
3283 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), Format,
3285 FirstArg.getZExtValue(),
3286 Attr.getAttributeSpellingListIndex());
3288 D->addAttr(NewAttr);
3291 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3292 const AttributeList &Attr) {
3293 // check the attribute arguments.
3294 if (!checkAttributeNumArgs(S, Attr, 0))
3298 // Try to find the underlying union declaration.
3300 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3301 if (TD && TD->getUnderlyingType()->isUnionType())
3302 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3304 RD = dyn_cast<RecordDecl>(D);
3306 if (!RD || !RD->isUnion()) {
3307 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3308 << Attr.getName() << ExpectedUnion;
3312 if (!RD->isCompleteDefinition()) {
3313 S.Diag(Attr.getLoc(),
3314 diag::warn_transparent_union_attribute_not_definition);
3318 RecordDecl::field_iterator Field = RD->field_begin(),
3319 FieldEnd = RD->field_end();
3320 if (Field == FieldEnd) {
3321 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3325 FieldDecl *FirstField = *Field;
3326 QualType FirstType = FirstField->getType();
3327 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3328 S.Diag(FirstField->getLocation(),
3329 diag::warn_transparent_union_attribute_floating)
3330 << FirstType->isVectorType() << FirstType;
3334 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3335 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3336 for (; Field != FieldEnd; ++Field) {
3337 QualType FieldType = Field->getType();
3338 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3339 S.Context.getTypeAlign(FieldType) != FirstAlign) {
3340 // Warn if we drop the attribute.
3341 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3342 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3343 : S.Context.getTypeAlign(FieldType);
3344 S.Diag(Field->getLocation(),
3345 diag::warn_transparent_union_attribute_field_size_align)
3346 << isSize << Field->getDeclName() << FieldBits;
3347 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3348 S.Diag(FirstField->getLocation(),
3349 diag::note_transparent_union_first_field_size_align)
3350 << isSize << FirstBits;
3355 RD->addAttr(::new (S.Context)
3356 TransparentUnionAttr(Attr.getRange(), S.Context,
3357 Attr.getAttributeSpellingListIndex()));
3360 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3361 // check the attribute arguments.
3362 if (!checkAttributeNumArgs(S, Attr, 1))
3365 Expr *ArgExpr = Attr.getArg(0);
3366 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
3368 // Make sure that there is a string literal as the annotation's single
3371 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
3375 // Don't duplicate annotations that are already set.
3376 for (specific_attr_iterator<AnnotateAttr>
3377 i = D->specific_attr_begin<AnnotateAttr>(),
3378 e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
3379 if ((*i)->getAnnotation() == SE->getString())
3383 D->addAttr(::new (S.Context)
3384 AnnotateAttr(Attr.getRange(), S.Context, SE->getString(),
3385 Attr.getAttributeSpellingListIndex()));
3388 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3389 // check the attribute arguments.
3390 if (Attr.getNumArgs() > 1) {
3391 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3395 if (Attr.getNumArgs() == 0) {
3396 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3397 true, 0, Attr.getAttributeSpellingListIndex()));
3401 Expr *E = Attr.getArg(0);
3402 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3403 S.Diag(Attr.getEllipsisLoc(),
3404 diag::err_pack_expansion_without_parameter_packs);
3408 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3411 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3412 Attr.isPackExpansion());
3415 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3416 unsigned SpellingListIndex, bool IsPackExpansion) {
3417 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3418 SourceLocation AttrLoc = AttrRange.getBegin();
3420 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3421 if (TmpAttr.isAlignas()) {
3422 // C++11 [dcl.align]p1:
3423 // An alignment-specifier may be applied to a variable or to a class
3424 // data member, but it shall not be applied to a bit-field, a function
3425 // parameter, the formal parameter of a catch clause, or a variable
3426 // declared with the register storage class specifier. An
3427 // alignment-specifier may also be applied to the declaration of a class
3428 // or enumeration type.
3430 // An alignment attribute shall not be specified in a declaration of
3431 // a typedef, or a bit-field, or a function, or a parameter, or an
3432 // object declared with the register storage-class specifier.
3434 if (isa<ParmVarDecl>(D)) {
3436 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3437 if (VD->getStorageClass() == SC_Register)
3439 if (VD->isExceptionVariable())
3441 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3442 if (FD->isBitField())
3444 } else if (!isa<TagDecl>(D)) {
3445 Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
3446 << (TmpAttr.isC11() ? "'_Alignas'" : "'alignas'")
3447 << (TmpAttr.isC11() ? ExpectedVariableOrField
3448 : ExpectedVariableFieldOrTag);
3451 if (DiagKind != -1) {
3452 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3453 << TmpAttr.isC11() << DiagKind;
3458 if (E->isTypeDependent() || E->isValueDependent()) {
3459 // Save dependent expressions in the AST to be instantiated.
3460 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3461 AA->setPackExpansion(IsPackExpansion);
3466 // FIXME: Cache the number on the Attr object?
3467 llvm::APSInt Alignment(32);
3469 = VerifyIntegerConstantExpression(E, &Alignment,
3470 diag::err_aligned_attribute_argument_not_int,
3471 /*AllowFold*/ false);
3472 if (ICE.isInvalid())
3475 // C++11 [dcl.align]p2:
3476 // -- if the constant expression evaluates to zero, the alignment
3477 // specifier shall have no effect
3479 // An alignment specification of zero has no effect.
3480 if (!(TmpAttr.isAlignas() && !Alignment) &&
3481 !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
3482 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
3483 << E->getSourceRange();
3487 if (TmpAttr.isDeclspec()) {
3488 // We've already verified it's a power of 2, now let's make sure it's
3490 if (Alignment.getZExtValue() > 8192) {
3491 Diag(AttrLoc, diag::err_attribute_aligned_greater_than_8192)
3492 << E->getSourceRange();
3497 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3498 ICE.take(), SpellingListIndex);
3499 AA->setPackExpansion(IsPackExpansion);
3503 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3504 unsigned SpellingListIndex, bool IsPackExpansion) {
3505 // FIXME: Cache the number on the Attr object if non-dependent?
3506 // FIXME: Perform checking of type validity
3507 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3509 AA->setPackExpansion(IsPackExpansion);
3513 void Sema::CheckAlignasUnderalignment(Decl *D) {
3514 assert(D->hasAttrs() && "no attributes on decl");
3517 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3520 Ty = Context.getTagDeclType(cast<TagDecl>(D));
3521 if (Ty->isDependentType() || Ty->isIncompleteType())
3524 // C++11 [dcl.align]p5, C11 6.7.5/4:
3525 // The combined effect of all alignment attributes in a declaration shall
3526 // not specify an alignment that is less strict than the alignment that
3527 // would otherwise be required for the entity being declared.
3528 AlignedAttr *AlignasAttr = 0;
3530 for (specific_attr_iterator<AlignedAttr>
3531 I = D->specific_attr_begin<AlignedAttr>(),
3532 E = D->specific_attr_end<AlignedAttr>(); I != E; ++I) {
3533 if (I->isAlignmentDependent())
3537 Align = std::max(Align, I->getAlignment(Context));
3540 if (AlignasAttr && Align) {
3541 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3542 CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
3543 if (NaturalAlign > RequestedAlign)
3544 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3545 << Ty << (unsigned)NaturalAlign.getQuantity();
3549 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3552 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3553 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3554 /// HImode, not an intermediate pointer.
3555 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3556 // This attribute isn't documented, but glibc uses it. It changes
3557 // the width of an int or unsigned int to the specified size.
3559 // Check that there aren't any arguments
3560 if (!checkAttributeNumArgs(S, Attr, 0))
3564 IdentifierInfo *Name = Attr.getParameterName();
3566 S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
3570 StringRef Str = Attr.getParameterName()->getName();
3572 // Normalize the attribute name, __foo__ becomes foo.
3573 if (Str.startswith("__") && Str.endswith("__"))
3574 Str = Str.substr(2, Str.size() - 4);
3576 unsigned DestWidth = 0;
3577 bool IntegerMode = true;
3578 bool ComplexMode = false;
3579 switch (Str.size()) {
3582 case 'Q': DestWidth = 8; break;
3583 case 'H': DestWidth = 16; break;
3584 case 'S': DestWidth = 32; break;
3585 case 'D': DestWidth = 64; break;
3586 case 'X': DestWidth = 96; break;
3587 case 'T': DestWidth = 128; break;
3589 if (Str[1] == 'F') {
3590 IntegerMode = false;
3591 } else if (Str[1] == 'C') {
3592 IntegerMode = false;
3594 } else if (Str[1] != 'I') {
3599 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3600 // pointer on PIC16 and other embedded platforms.
3602 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3603 else if (Str == "byte")
3604 DestWidth = S.Context.getTargetInfo().getCharWidth();
3607 if (Str == "pointer")
3608 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3611 if (Str == "unwind_word")
3612 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3617 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3618 OldTy = TD->getUnderlyingType();
3619 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3620 OldTy = VD->getType();
3622 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3623 << "mode" << Attr.getRange();
3627 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3628 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3629 else if (IntegerMode) {
3630 if (!OldTy->isIntegralOrEnumerationType())
3631 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3632 } else if (ComplexMode) {
3633 if (!OldTy->isComplexType())
3634 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3636 if (!OldTy->isFloatingType())
3637 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3640 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3641 // and friends, at least with glibc.
3642 // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
3643 // width on unusual platforms.
3644 // FIXME: Make sure floating-point mappings are accurate
3645 // FIXME: Support XF and TF types
3647 switch (DestWidth) {
3649 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
3652 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3656 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3659 if (OldTy->isSignedIntegerType())
3660 NewTy = S.Context.SignedCharTy;
3662 NewTy = S.Context.UnsignedCharTy;
3666 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3669 if (OldTy->isSignedIntegerType())
3670 NewTy = S.Context.ShortTy;
3672 NewTy = S.Context.UnsignedShortTy;
3676 NewTy = S.Context.FloatTy;
3677 else if (OldTy->isSignedIntegerType())
3678 NewTy = S.Context.IntTy;
3680 NewTy = S.Context.UnsignedIntTy;
3684 NewTy = S.Context.DoubleTy;
3685 else if (OldTy->isSignedIntegerType())
3686 if (S.Context.getTargetInfo().getLongWidth() == 64)
3687 NewTy = S.Context.LongTy;
3689 NewTy = S.Context.LongLongTy;
3691 if (S.Context.getTargetInfo().getLongWidth() == 64)
3692 NewTy = S.Context.UnsignedLongTy;
3694 NewTy = S.Context.UnsignedLongLongTy;
3697 NewTy = S.Context.LongDoubleTy;
3701 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3704 if (OldTy->isSignedIntegerType())
3705 NewTy = S.Context.Int128Ty;
3707 NewTy = S.Context.UnsignedInt128Ty;
3712 NewTy = S.Context.getComplexType(NewTy);
3715 // Install the new type.
3716 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
3717 // FIXME: preserve existing source info.
3718 TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
3720 cast<ValueDecl>(D)->setType(NewTy);
3723 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3724 // check the attribute arguments.
3725 if (!checkAttributeNumArgs(S, Attr, 0))
3728 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3729 if (!VD->hasGlobalStorage())
3730 S.Diag(Attr.getLoc(),
3731 diag::warn_attribute_requires_functions_or_static_globals)
3733 } else if (!isFunctionOrMethod(D)) {
3734 S.Diag(Attr.getLoc(),
3735 diag::warn_attribute_requires_functions_or_static_globals)
3740 D->addAttr(::new (S.Context)
3741 NoDebugAttr(Attr.getRange(), S.Context,
3742 Attr.getAttributeSpellingListIndex()));
3745 static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3746 // check the attribute arguments.
3747 if (!checkAttributeNumArgs(S, Attr, 0))
3751 if (!isa<FunctionDecl>(D)) {
3752 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3753 << Attr.getName() << ExpectedFunction;
3757 D->addAttr(::new (S.Context)
3758 NoInlineAttr(Attr.getRange(), S.Context,
3759 Attr.getAttributeSpellingListIndex()));
3762 static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
3763 const AttributeList &Attr) {
3764 // check the attribute arguments.
3765 if (!checkAttributeNumArgs(S, Attr, 0))
3769 if (!isa<FunctionDecl>(D)) {
3770 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3771 << Attr.getName() << ExpectedFunction;
3775 D->addAttr(::new (S.Context)
3776 NoInstrumentFunctionAttr(Attr.getRange(), S.Context,
3777 Attr.getAttributeSpellingListIndex()));
3780 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3781 if (S.LangOpts.CUDA) {
3782 // check the attribute arguments.
3783 if (Attr.hasParameterOrArguments()) {
3784 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3788 if (!isa<VarDecl>(D)) {
3789 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3790 << Attr.getName() << ExpectedVariable;
3794 D->addAttr(::new (S.Context)
3795 CUDAConstantAttr(Attr.getRange(), S.Context,
3796 Attr.getAttributeSpellingListIndex()));
3798 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
3802 static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3803 if (S.LangOpts.CUDA) {
3804 // check the attribute arguments.
3805 if (Attr.getNumArgs() != 0) {
3806 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3810 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
3811 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3812 << Attr.getName() << ExpectedVariableOrFunction;
3816 D->addAttr(::new (S.Context)
3817 CUDADeviceAttr(Attr.getRange(), S.Context,
3818 Attr.getAttributeSpellingListIndex()));
3820 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
3824 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3825 if (S.LangOpts.CUDA) {
3826 // check the attribute arguments.
3827 if (!checkAttributeNumArgs(S, Attr, 0))
3830 if (!isa<FunctionDecl>(D)) {
3831 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3832 << Attr.getName() << ExpectedFunction;
3836 FunctionDecl *FD = cast<FunctionDecl>(D);
3837 if (!FD->getResultType()->isVoidType()) {
3838 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3839 if (FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>()) {
3840 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3842 << FixItHint::CreateReplacement(FTL.getResultLoc().getSourceRange(),
3845 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3851 D->addAttr(::new (S.Context)
3852 CUDAGlobalAttr(Attr.getRange(), S.Context,
3853 Attr.getAttributeSpellingListIndex()));
3855 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
3859 static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3860 if (S.LangOpts.CUDA) {
3861 // check the attribute arguments.
3862 if (!checkAttributeNumArgs(S, Attr, 0))
3866 if (!isa<FunctionDecl>(D)) {
3867 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3868 << Attr.getName() << ExpectedFunction;
3872 D->addAttr(::new (S.Context)
3873 CUDAHostAttr(Attr.getRange(), S.Context,
3874 Attr.getAttributeSpellingListIndex()));
3876 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
3880 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3881 if (S.LangOpts.CUDA) {
3882 // check the attribute arguments.
3883 if (!checkAttributeNumArgs(S, Attr, 0))
3886 if (!isa<VarDecl>(D)) {
3887 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3888 << Attr.getName() << ExpectedVariable;
3892 D->addAttr(::new (S.Context)
3893 CUDASharedAttr(Attr.getRange(), S.Context,
3894 Attr.getAttributeSpellingListIndex()));
3896 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
3900 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3901 // check the attribute arguments.
3902 if (!checkAttributeNumArgs(S, Attr, 0))
3905 FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
3907 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3908 << Attr.getName() << ExpectedFunction;
3912 if (!Fn->isInlineSpecified()) {
3913 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3917 D->addAttr(::new (S.Context)
3918 GNUInlineAttr(Attr.getRange(), S.Context,
3919 Attr.getAttributeSpellingListIndex()));
3922 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3923 if (hasDeclarator(D)) return;
3925 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3926 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3927 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3929 if (S.CheckCallingConvAttr(Attr, CC, FD))
3932 if (!isa<ObjCMethodDecl>(D)) {
3933 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3934 << Attr.getName() << ExpectedFunctionOrMethod;
3938 switch (Attr.getKind()) {
3939 case AttributeList::AT_FastCall:
3940 D->addAttr(::new (S.Context)
3941 FastCallAttr(Attr.getRange(), S.Context,
3942 Attr.getAttributeSpellingListIndex()));
3944 case AttributeList::AT_StdCall:
3945 D->addAttr(::new (S.Context)
3946 StdCallAttr(Attr.getRange(), S.Context,
3947 Attr.getAttributeSpellingListIndex()));
3949 case AttributeList::AT_ThisCall:
3950 D->addAttr(::new (S.Context)
3951 ThisCallAttr(Attr.getRange(), S.Context,
3952 Attr.getAttributeSpellingListIndex()));
3954 case AttributeList::AT_CDecl:
3955 D->addAttr(::new (S.Context)
3956 CDeclAttr(Attr.getRange(), S.Context,
3957 Attr.getAttributeSpellingListIndex()));
3959 case AttributeList::AT_Pascal:
3960 D->addAttr(::new (S.Context)
3961 PascalAttr(Attr.getRange(), S.Context,
3962 Attr.getAttributeSpellingListIndex()));
3964 case AttributeList::AT_MSABI:
3965 D->addAttr(::new (S.Context)
3966 MSABIAttr(Attr.getRange(), S.Context,
3967 Attr.getAttributeSpellingListIndex()));
3969 case AttributeList::AT_SysVABI:
3970 D->addAttr(::new (S.Context)
3971 SysVABIAttr(Attr.getRange(), S.Context,
3972 Attr.getAttributeSpellingListIndex()));
3974 case AttributeList::AT_Pcs: {
3975 PcsAttr::PCSType PCS;
3978 PCS = PcsAttr::AAPCS;
3981 PCS = PcsAttr::AAPCS_VFP;
3984 llvm_unreachable("unexpected calling convention in pcs attribute");
3987 D->addAttr(::new (S.Context)
3988 PcsAttr(Attr.getRange(), S.Context, PCS,
3989 Attr.getAttributeSpellingListIndex()));
3992 case AttributeList::AT_PnaclCall:
3993 D->addAttr(::new (S.Context)
3994 PnaclCallAttr(Attr.getRange(), S.Context,
3995 Attr.getAttributeSpellingListIndex()));
3997 case AttributeList::AT_IntelOclBicc:
3998 D->addAttr(::new (S.Context)
3999 IntelOclBiccAttr(Attr.getRange(), S.Context,
4000 Attr.getAttributeSpellingListIndex()));
4004 llvm_unreachable("unexpected attribute kind");
4008 static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
4009 assert(!Attr.isInvalid());
4010 D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
4013 static void handleOpenCLImageAccessAttr(Sema &S, Decl *D, const AttributeList &Attr){
4014 assert(!Attr.isInvalid());
4016 Expr *E = Attr.getArg(0);
4017 llvm::APSInt ArgNum(32);
4018 if (E->isTypeDependent() || E->isValueDependent() ||
4019 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
4020 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4021 << Attr.getName()->getName() << E->getSourceRange();
4025 D->addAttr(::new (S.Context) OpenCLImageAccessAttr(
4026 Attr.getRange(), S.Context, ArgNum.getZExtValue()));
4029 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4030 const FunctionDecl *FD) {
4031 if (attr.isInvalid())
4034 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4035 if (attr.getNumArgs() != ReqArgs || attr.getParameterName()) {
4036 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << ReqArgs;
4041 // TODO: diagnose uses of these conventions on the wrong target. Or, better
4042 // move to TargetAttributesSema one day.
4043 switch (attr.getKind()) {
4044 case AttributeList::AT_CDecl: CC = CC_C; break;
4045 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4046 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4047 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4048 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4049 case AttributeList::AT_MSABI:
4050 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4053 case AttributeList::AT_SysVABI:
4054 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4057 case AttributeList::AT_Pcs: {
4058 Expr *Arg = attr.getArg(0);
4059 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
4060 if (!Str || !Str->isAscii()) {
4061 Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
4067 StringRef StrRef = Str->getString();
4068 if (StrRef == "aapcs") {
4071 } else if (StrRef == "aapcs-vfp") {
4077 Diag(attr.getLoc(), diag::err_invalid_pcs);
4080 case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
4081 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4082 default: llvm_unreachable("unexpected attribute kind");
4085 const TargetInfo &TI = Context.getTargetInfo();
4086 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4087 if (A == TargetInfo::CCCR_Warning) {
4088 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4090 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
4092 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
4093 TargetInfo::CCMT_NonMember;
4094 CC = TI.getDefaultCallingConv(MT);
4100 static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4101 if (hasDeclarator(D)) return;
4104 if (S.CheckRegparmAttr(Attr, numParams))
4107 if (!isa<ObjCMethodDecl>(D)) {
4108 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4109 << Attr.getName() << ExpectedFunctionOrMethod;
4113 D->addAttr(::new (S.Context)
4114 RegparmAttr(Attr.getRange(), S.Context, numParams,
4115 Attr.getAttributeSpellingListIndex()));
4118 /// Checks a regparm attribute, returning true if it is ill-formed and
4119 /// otherwise setting numParams to the appropriate value.
4120 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4121 if (Attr.isInvalid())
4124 if (Attr.getNumArgs() != 1) {
4125 Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4130 Expr *NumParamsExpr = Attr.getArg(0);
4131 llvm::APSInt NumParams(32);
4132 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
4133 !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
4134 Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4135 << "regparm" << NumParamsExpr->getSourceRange();
4140 if (Context.getTargetInfo().getRegParmMax() == 0) {
4141 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4142 << NumParamsExpr->getSourceRange();
4147 numParams = NumParams.getZExtValue();
4148 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4149 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4150 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4158 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
4159 if (S.LangOpts.CUDA) {
4160 // check the attribute arguments.
4161 if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
4162 // FIXME: 0 is not okay.
4163 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
4167 if (!isFunctionOrMethod(D)) {
4168 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4169 << Attr.getName() << ExpectedFunctionOrMethod;
4173 Expr *MaxThreadsExpr = Attr.getArg(0);
4174 llvm::APSInt MaxThreads(32);
4175 if (MaxThreadsExpr->isTypeDependent() ||
4176 MaxThreadsExpr->isValueDependent() ||
4177 !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
4178 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
4179 << "launch_bounds" << 1 << MaxThreadsExpr->getSourceRange();
4183 llvm::APSInt MinBlocks(32);
4184 if (Attr.getNumArgs() > 1) {
4185 Expr *MinBlocksExpr = Attr.getArg(1);
4186 if (MinBlocksExpr->isTypeDependent() ||
4187 MinBlocksExpr->isValueDependent() ||
4188 !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
4189 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
4190 << "launch_bounds" << 2 << MinBlocksExpr->getSourceRange();
4195 D->addAttr(::new (S.Context)
4196 CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
4197 MaxThreads.getZExtValue(),
4198 MinBlocks.getZExtValue(),
4199 Attr.getAttributeSpellingListIndex()));
4201 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
4205 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4206 const AttributeList &Attr) {
4207 StringRef AttrName = Attr.getName()->getName();
4208 if (!Attr.getParameterName()) {
4209 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_identifier)
4210 << Attr.getName() << /* arg num = */ 1;
4214 if (Attr.getNumArgs() != 2) {
4215 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4216 << /* required args = */ 3;
4220 IdentifierInfo *ArgumentKind = Attr.getParameterName();
4222 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4223 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4224 << Attr.getName() << ExpectedFunctionOrMethod;
4228 uint64_t ArgumentIdx;
4229 if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
4231 Attr.getArg(0), ArgumentIdx))
4234 uint64_t TypeTagIdx;
4235 if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
4237 Attr.getArg(1), TypeTagIdx))
4240 bool IsPointer = (AttrName == "pointer_with_type_tag");
4242 // Ensure that buffer has a pointer type.
4243 QualType BufferTy = getFunctionOrMethodArgType(D, ArgumentIdx);
4244 if (!BufferTy->isPointerType()) {
4245 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4250 D->addAttr(::new (S.Context)
4251 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4252 ArgumentIdx, TypeTagIdx, IsPointer,
4253 Attr.getAttributeSpellingListIndex()));
4256 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4257 const AttributeList &Attr) {
4258 IdentifierInfo *PointerKind = Attr.getParameterName();
4260 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_identifier)
4261 << "type_tag_for_datatype" << 1;
4265 QualType MatchingCType = S.GetTypeFromParser(Attr.getMatchingCType(), NULL);
4267 D->addAttr(::new (S.Context)
4268 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4270 Attr.getLayoutCompatible(),
4271 Attr.getMustBeNull(),
4272 Attr.getAttributeSpellingListIndex()));
4275 //===----------------------------------------------------------------------===//
4276 // Checker-specific attribute handlers.
4277 //===----------------------------------------------------------------------===//
4279 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4280 return type->isDependentType() ||
4281 type->isObjCObjectPointerType() ||
4282 S.Context.isObjCNSObjectType(type);
4284 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4285 return type->isDependentType() ||
4286 type->isPointerType() ||
4287 isValidSubjectOfNSAttribute(S, type);
4290 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4291 ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
4293 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4294 << Attr.getRange() << Attr.getName() << ExpectedParameter;
4299 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
4300 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
4303 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
4308 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4309 << Attr.getRange() << Attr.getName() << cf;
4314 param->addAttr(::new (S.Context)
4315 CFConsumedAttr(Attr.getRange(), S.Context,
4316 Attr.getAttributeSpellingListIndex()));
4318 param->addAttr(::new (S.Context)
4319 NSConsumedAttr(Attr.getRange(), S.Context,
4320 Attr.getAttributeSpellingListIndex()));
4323 static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
4324 const AttributeList &Attr) {
4325 if (!isa<ObjCMethodDecl>(D)) {
4326 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4327 << Attr.getRange() << Attr.getName() << ExpectedMethod;
4331 D->addAttr(::new (S.Context)
4332 NSConsumesSelfAttr(Attr.getRange(), S.Context,
4333 Attr.getAttributeSpellingListIndex()));
4336 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4337 const AttributeList &Attr) {
4339 QualType returnType;
4341 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4342 returnType = MD->getResultType();
4343 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4344 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4345 return; // ignore: was handled as a type attribute
4346 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4347 returnType = PD->getType();
4348 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4349 returnType = FD->getResultType();
4351 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4352 << Attr.getRange() << Attr.getName()
4353 << ExpectedFunctionOrMethod;
4359 switch (Attr.getKind()) {
4360 default: llvm_unreachable("invalid ownership attribute");
4361 case AttributeList::AT_NSReturnsAutoreleased:
4362 case AttributeList::AT_NSReturnsRetained:
4363 case AttributeList::AT_NSReturnsNotRetained:
4364 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4368 case AttributeList::AT_CFReturnsRetained:
4369 case AttributeList::AT_CFReturnsNotRetained:
4370 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4376 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4377 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
4381 switch (Attr.getKind()) {
4383 llvm_unreachable("invalid ownership attribute");
4384 case AttributeList::AT_NSReturnsAutoreleased:
4385 D->addAttr(::new (S.Context)
4386 NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
4387 Attr.getAttributeSpellingListIndex()));
4389 case AttributeList::AT_CFReturnsNotRetained:
4390 D->addAttr(::new (S.Context)
4391 CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4392 Attr.getAttributeSpellingListIndex()));
4394 case AttributeList::AT_NSReturnsNotRetained:
4395 D->addAttr(::new (S.Context)
4396 NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4397 Attr.getAttributeSpellingListIndex()));
4399 case AttributeList::AT_CFReturnsRetained:
4400 D->addAttr(::new (S.Context)
4401 CFReturnsRetainedAttr(Attr.getRange(), S.Context,
4402 Attr.getAttributeSpellingListIndex()));
4404 case AttributeList::AT_NSReturnsRetained:
4405 D->addAttr(::new (S.Context)
4406 NSReturnsRetainedAttr(Attr.getRange(), S.Context,
4407 Attr.getAttributeSpellingListIndex()));
4412 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4413 const AttributeList &attr) {
4414 SourceLocation loc = attr.getLoc();
4416 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4419 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4420 << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
4424 // Check that the method returns a normal pointer.
4425 QualType resultType = method->getResultType();
4427 if (!resultType->isReferenceType() &&
4428 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4429 S.Diag(method->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4431 << attr.getName() << /*method*/ 1 << /*non-retainable pointer*/ 2;
4433 // Drop the attribute.
4437 method->addAttr(::new (S.Context)
4438 ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
4439 attr.getAttributeSpellingListIndex()));
4442 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4443 const AttributeList &attr) {
4444 SourceLocation loc = attr.getLoc();
4445 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4448 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4449 << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
4452 DeclContext *DC = method->getDeclContext();
4453 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4454 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4455 << attr.getName() << 0;
4456 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4459 if (method->getMethodFamily() == OMF_dealloc) {
4460 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4461 << attr.getName() << 1;
4465 method->addAttr(::new (S.Context)
4466 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4467 attr.getAttributeSpellingListIndex()));
4470 /// Handle cf_audited_transfer and cf_unknown_transfer.
4471 static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
4472 if (!isa<FunctionDecl>(D)) {
4473 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4474 << A.getRange() << A.getName() << ExpectedFunction;
4478 bool IsAudited = (A.getKind() == AttributeList::AT_CFAuditedTransfer);
4480 // Check whether there's a conflicting attribute already present.
4483 Existing = D->getAttr<CFUnknownTransferAttr>();
4485 Existing = D->getAttr<CFAuditedTransferAttr>();
4488 S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
4490 << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
4491 << A.getRange() << Existing->getRange();
4495 // All clear; add the attribute.
4497 D->addAttr(::new (S.Context)
4498 CFAuditedTransferAttr(A.getRange(), S.Context,
4499 A.getAttributeSpellingListIndex()));
4501 D->addAttr(::new (S.Context)
4502 CFUnknownTransferAttr(A.getRange(), S.Context,
4503 A.getAttributeSpellingListIndex()));
4507 static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
4508 const AttributeList &Attr) {
4509 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4510 if (!RD || RD->isUnion()) {
4511 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4512 << Attr.getRange() << Attr.getName() << ExpectedStruct;
4515 IdentifierInfo *ParmName = Attr.getParameterName();
4517 // In Objective-C, verify that the type names an Objective-C type.
4518 // We don't want to check this outside of ObjC because people sometimes
4519 // do crazy C declarations of Objective-C types.
4520 if (ParmName && S.getLangOpts().ObjC1) {
4521 // Check for an existing type with this name.
4522 LookupResult R(S, DeclarationName(ParmName), Attr.getParameterLoc(),
4523 Sema::LookupOrdinaryName);
4524 if (S.LookupName(R, Sc)) {
4525 NamedDecl *Target = R.getFoundDecl();
4526 if (Target && !isa<ObjCInterfaceDecl>(Target)) {
4527 S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
4528 S.Diag(Target->getLocStart(), diag::note_declared_at);
4533 D->addAttr(::new (S.Context)
4534 NSBridgedAttr(Attr.getRange(), S.Context, ParmName,
4535 Attr.getAttributeSpellingListIndex()));
4538 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4539 const AttributeList &Attr) {
4540 if (hasDeclarator(D)) return;
4542 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4543 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4546 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4547 const AttributeList &Attr) {
4548 if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
4549 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4550 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4554 ValueDecl *vd = cast<ValueDecl>(D);
4555 QualType type = vd->getType();
4557 if (!type->isDependentType() &&
4558 !type->isObjCLifetimeType()) {
4559 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4564 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4566 // If we have no lifetime yet, check the lifetime we're presumably
4568 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4569 lifetime = type->getObjCARCImplicitLifetime();
4572 case Qualifiers::OCL_None:
4573 assert(type->isDependentType() &&
4574 "didn't infer lifetime for non-dependent type?");
4577 case Qualifiers::OCL_Weak: // meaningful
4578 case Qualifiers::OCL_Strong: // meaningful
4581 case Qualifiers::OCL_ExplicitNone:
4582 case Qualifiers::OCL_Autoreleasing:
4583 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4584 << (lifetime == Qualifiers::OCL_Autoreleasing);
4588 D->addAttr(::new (S.Context)
4589 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4590 Attr.getAttributeSpellingListIndex()));
4593 //===----------------------------------------------------------------------===//
4594 // Microsoft specific attribute handlers.
4595 //===----------------------------------------------------------------------===//
4597 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4598 if (S.LangOpts.MicrosoftExt || S.LangOpts.Borland) {
4599 // check the attribute arguments.
4600 if (!checkAttributeNumArgs(S, Attr, 1))
4603 Expr *Arg = Attr.getArg(0);
4604 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
4605 if (!Str || !Str->isAscii()) {
4606 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
4611 StringRef StrRef = Str->getString();
4613 bool IsCurly = StrRef.size() > 1 && StrRef.front() == '{' &&
4614 StrRef.back() == '}';
4616 // Validate GUID length.
4617 if (IsCurly && StrRef.size() != 38) {
4618 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4621 if (!IsCurly && StrRef.size() != 36) {
4622 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4626 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4627 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
4628 StringRef::iterator I = StrRef.begin();
4629 if (IsCurly) // Skip the optional '{'
4632 for (int i = 0; i < 36; ++i) {
4633 if (i == 8 || i == 13 || i == 18 || i == 23) {
4635 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4638 } else if (!isHexDigit(*I)) {
4639 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4645 D->addAttr(::new (S.Context)
4646 UuidAttr(Attr.getRange(), S.Context, Str->getString(),
4647 Attr.getAttributeSpellingListIndex()));
4649 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "uuid";
4652 static void handleInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4653 if (!S.LangOpts.MicrosoftExt) {
4654 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4658 AttributeList::Kind Kind = Attr.getKind();
4659 if (Kind == AttributeList::AT_SingleInheritance)
4662 SingleInheritanceAttr(Attr.getRange(), S.Context,
4663 Attr.getAttributeSpellingListIndex()));
4664 else if (Kind == AttributeList::AT_MultipleInheritance)
4667 MultipleInheritanceAttr(Attr.getRange(), S.Context,
4668 Attr.getAttributeSpellingListIndex()));
4669 else if (Kind == AttributeList::AT_VirtualInheritance)
4672 VirtualInheritanceAttr(Attr.getRange(), S.Context,
4673 Attr.getAttributeSpellingListIndex()));
4676 static void handlePortabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4677 if (S.LangOpts.MicrosoftExt) {
4678 AttributeList::Kind Kind = Attr.getKind();
4679 if (Kind == AttributeList::AT_Ptr32)
4681 ::new (S.Context) Ptr32Attr(Attr.getRange(), S.Context,
4682 Attr.getAttributeSpellingListIndex()));
4683 else if (Kind == AttributeList::AT_Ptr64)
4685 ::new (S.Context) Ptr64Attr(Attr.getRange(), S.Context,
4686 Attr.getAttributeSpellingListIndex()));
4687 else if (Kind == AttributeList::AT_Win64)
4689 ::new (S.Context) Win64Attr(Attr.getRange(), S.Context,
4690 Attr.getAttributeSpellingListIndex()));
4692 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4695 static void handleForceInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4696 if (S.LangOpts.MicrosoftExt)
4697 D->addAttr(::new (S.Context)
4698 ForceInlineAttr(Attr.getRange(), S.Context,
4699 Attr.getAttributeSpellingListIndex()));
4701 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4704 //===----------------------------------------------------------------------===//
4705 // Top Level Sema Entry Points
4706 //===----------------------------------------------------------------------===//
4708 static void ProcessNonInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4709 const AttributeList &Attr) {
4710 switch (Attr.getKind()) {
4711 case AttributeList::AT_CUDADevice: handleDeviceAttr (S, D, Attr); break;
4712 case AttributeList::AT_CUDAHost: handleHostAttr (S, D, Attr); break;
4713 case AttributeList::AT_Overloadable:handleOverloadableAttr(S, D, Attr); break;
4719 static void ProcessInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4720 const AttributeList &Attr) {
4721 switch (Attr.getKind()) {
4722 case AttributeList::AT_IBAction: handleIBAction(S, D, Attr); break;
4723 case AttributeList::AT_IBOutlet: handleIBOutlet(S, D, Attr); break;
4724 case AttributeList::AT_IBOutletCollection:
4725 handleIBOutletCollection(S, D, Attr); break;
4726 case AttributeList::AT_AddressSpace:
4727 case AttributeList::AT_ObjCGC:
4728 case AttributeList::AT_VectorSize:
4729 case AttributeList::AT_NeonVectorType:
4730 case AttributeList::AT_NeonPolyVectorType:
4731 // Ignore these, these are type attributes, handled by
4732 // ProcessTypeAttributes.
4734 case AttributeList::AT_CUDADevice:
4735 case AttributeList::AT_CUDAHost:
4736 case AttributeList::AT_Overloadable:
4737 // Ignore, this is a non-inheritable attribute, handled
4738 // by ProcessNonInheritableDeclAttr.
4740 case AttributeList::AT_Alias: handleAliasAttr (S, D, Attr); break;
4741 case AttributeList::AT_Aligned: handleAlignedAttr (S, D, Attr); break;
4742 case AttributeList::AT_AllocSize: handleAllocSizeAttr (S, D, Attr); break;
4743 case AttributeList::AT_AlwaysInline:
4744 handleAlwaysInlineAttr (S, D, Attr); break;
4745 case AttributeList::AT_AnalyzerNoReturn:
4746 handleAnalyzerNoReturnAttr (S, D, Attr); break;
4747 case AttributeList::AT_TLSModel: handleTLSModelAttr (S, D, Attr); break;
4748 case AttributeList::AT_Annotate: handleAnnotateAttr (S, D, Attr); break;
4749 case AttributeList::AT_Availability:handleAvailabilityAttr(S, D, Attr); break;
4750 case AttributeList::AT_CarriesDependency:
4751 handleDependencyAttr(S, scope, D, Attr);
4753 case AttributeList::AT_Common: handleCommonAttr (S, D, Attr); break;
4754 case AttributeList::AT_CUDAConstant:handleConstantAttr (S, D, Attr); break;
4755 case AttributeList::AT_Constructor: handleConstructorAttr (S, D, Attr); break;
4756 case AttributeList::AT_CXX11NoReturn:
4757 handleCXX11NoReturnAttr(S, D, Attr);
4759 case AttributeList::AT_Deprecated:
4760 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr, "deprecated");
4762 case AttributeList::AT_Destructor: handleDestructorAttr (S, D, Attr); break;
4763 case AttributeList::AT_ExtVectorType:
4764 handleExtVectorTypeAttr(S, scope, D, Attr);
4766 case AttributeList::AT_MinSize:
4767 handleMinSizeAttr(S, D, Attr);
4769 case AttributeList::AT_Format: handleFormatAttr (S, D, Attr); break;
4770 case AttributeList::AT_FormatArg: handleFormatArgAttr (S, D, Attr); break;
4771 case AttributeList::AT_CUDAGlobal: handleGlobalAttr (S, D, Attr); break;
4772 case AttributeList::AT_GNUInline: handleGNUInlineAttr (S, D, Attr); break;
4773 case AttributeList::AT_CUDALaunchBounds:
4774 handleLaunchBoundsAttr(S, D, Attr);
4776 case AttributeList::AT_Mode: handleModeAttr (S, D, Attr); break;
4777 case AttributeList::AT_Malloc: handleMallocAttr (S, D, Attr); break;
4778 case AttributeList::AT_MayAlias: handleMayAliasAttr (S, D, Attr); break;
4779 case AttributeList::AT_NoCommon: handleNoCommonAttr (S, D, Attr); break;
4780 case AttributeList::AT_NonNull: handleNonNullAttr (S, D, Attr); break;
4781 case AttributeList::AT_ownership_returns:
4782 case AttributeList::AT_ownership_takes:
4783 case AttributeList::AT_ownership_holds:
4784 handleOwnershipAttr (S, D, Attr); break;
4785 case AttributeList::AT_Cold: handleColdAttr (S, D, Attr); break;
4786 case AttributeList::AT_Hot: handleHotAttr (S, D, Attr); break;
4787 case AttributeList::AT_Naked: handleNakedAttr (S, D, Attr); break;
4788 case AttributeList::AT_NoReturn: handleNoReturnAttr (S, D, Attr); break;
4789 case AttributeList::AT_NoThrow: handleNothrowAttr (S, D, Attr); break;
4790 case AttributeList::AT_CUDAShared: handleSharedAttr (S, D, Attr); break;
4791 case AttributeList::AT_VecReturn: handleVecReturnAttr (S, D, Attr); break;
4793 case AttributeList::AT_ObjCOwnership:
4794 handleObjCOwnershipAttr(S, D, Attr); break;
4795 case AttributeList::AT_ObjCPreciseLifetime:
4796 handleObjCPreciseLifetimeAttr(S, D, Attr); break;
4798 case AttributeList::AT_ObjCReturnsInnerPointer:
4799 handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
4801 case AttributeList::AT_ObjCRequiresSuper:
4802 handleObjCRequiresSuperAttr(S, D, Attr); break;
4804 case AttributeList::AT_NSBridged:
4805 handleNSBridgedAttr(S, scope, D, Attr); break;
4807 case AttributeList::AT_CFAuditedTransfer:
4808 case AttributeList::AT_CFUnknownTransfer:
4809 handleCFTransferAttr(S, D, Attr); break;
4811 // Checker-specific.
4812 case AttributeList::AT_CFConsumed:
4813 case AttributeList::AT_NSConsumed: handleNSConsumedAttr (S, D, Attr); break;
4814 case AttributeList::AT_NSConsumesSelf:
4815 handleNSConsumesSelfAttr(S, D, Attr); break;
4817 case AttributeList::AT_NSReturnsAutoreleased:
4818 case AttributeList::AT_NSReturnsNotRetained:
4819 case AttributeList::AT_CFReturnsNotRetained:
4820 case AttributeList::AT_NSReturnsRetained:
4821 case AttributeList::AT_CFReturnsRetained:
4822 handleNSReturnsRetainedAttr(S, D, Attr); break;
4824 case AttributeList::AT_WorkGroupSizeHint:
4825 case AttributeList::AT_ReqdWorkGroupSize:
4826 handleWorkGroupSize(S, D, Attr); break;
4828 case AttributeList::AT_VecTypeHint:
4829 handleVecTypeHint(S, D, Attr); break;
4831 case AttributeList::AT_Endian:
4832 handleEndianAttr(S, D, Attr);
4835 case AttributeList::AT_InitPriority:
4836 handleInitPriorityAttr(S, D, Attr); break;
4838 case AttributeList::AT_Packed: handlePackedAttr (S, D, Attr); break;
4839 case AttributeList::AT_Section: handleSectionAttr (S, D, Attr); break;
4840 case AttributeList::AT_Unavailable:
4841 handleAttrWithMessage<UnavailableAttr>(S, D, Attr, "unavailable");
4843 case AttributeList::AT_ArcWeakrefUnavailable:
4844 handleArcWeakrefUnavailableAttr (S, D, Attr);
4846 case AttributeList::AT_ObjCRootClass:
4847 handleObjCRootClassAttr(S, D, Attr);
4849 case AttributeList::AT_ObjCRequiresPropertyDefs:
4850 handleObjCRequiresPropertyDefsAttr (S, D, Attr);
4852 case AttributeList::AT_Unused: handleUnusedAttr (S, D, Attr); break;
4853 case AttributeList::AT_ReturnsTwice:
4854 handleReturnsTwiceAttr(S, D, Attr);
4856 case AttributeList::AT_Used: handleUsedAttr (S, D, Attr); break;
4857 case AttributeList::AT_Visibility:
4858 handleVisibilityAttr(S, D, Attr, false);
4860 case AttributeList::AT_TypeVisibility:
4861 handleVisibilityAttr(S, D, Attr, true);
4863 case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr);
4865 case AttributeList::AT_Weak: handleWeakAttr (S, D, Attr); break;
4866 case AttributeList::AT_WeakRef: handleWeakRefAttr (S, D, Attr); break;
4867 case AttributeList::AT_WeakImport: handleWeakImportAttr (S, D, Attr); break;
4868 case AttributeList::AT_TransparentUnion:
4869 handleTransparentUnionAttr(S, D, Attr);
4871 case AttributeList::AT_ObjCException:
4872 handleObjCExceptionAttr(S, D, Attr);
4874 case AttributeList::AT_ObjCMethodFamily:
4875 handleObjCMethodFamilyAttr(S, D, Attr);
4877 case AttributeList::AT_ObjCNSObject:handleObjCNSObject (S, D, Attr); break;
4878 case AttributeList::AT_Blocks: handleBlocksAttr (S, D, Attr); break;
4879 case AttributeList::AT_Sentinel: handleSentinelAttr (S, D, Attr); break;
4880 case AttributeList::AT_Const: handleConstAttr (S, D, Attr); break;
4881 case AttributeList::AT_Pure: handlePureAttr (S, D, Attr); break;
4882 case AttributeList::AT_Cleanup: handleCleanupAttr (S, D, Attr); break;
4883 case AttributeList::AT_NoDebug: handleNoDebugAttr (S, D, Attr); break;
4884 case AttributeList::AT_NoInline: handleNoInlineAttr (S, D, Attr); break;
4885 case AttributeList::AT_Regparm: handleRegparmAttr (S, D, Attr); break;
4886 case AttributeList::IgnoredAttribute:
4889 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4890 handleNoInstrumentFunctionAttr(S, D, Attr);
4892 case AttributeList::AT_StdCall:
4893 case AttributeList::AT_CDecl:
4894 case AttributeList::AT_FastCall:
4895 case AttributeList::AT_ThisCall:
4896 case AttributeList::AT_Pascal:
4897 case AttributeList::AT_MSABI:
4898 case AttributeList::AT_SysVABI:
4899 case AttributeList::AT_Pcs:
4900 case AttributeList::AT_PnaclCall:
4901 case AttributeList::AT_IntelOclBicc:
4902 handleCallConvAttr(S, D, Attr);
4904 case AttributeList::AT_OpenCLKernel:
4905 handleOpenCLKernelAttr(S, D, Attr);
4907 case AttributeList::AT_OpenCLImageAccess:
4908 handleOpenCLImageAccessAttr(S, D, Attr);
4911 // Microsoft attributes:
4912 case AttributeList::AT_MsProperty: break;
4913 case AttributeList::AT_MsStruct:
4914 handleMsStructAttr(S, D, Attr);
4916 case AttributeList::AT_Uuid:
4917 handleUuidAttr(S, D, Attr);
4919 case AttributeList::AT_SingleInheritance:
4920 case AttributeList::AT_MultipleInheritance:
4921 case AttributeList::AT_VirtualInheritance:
4922 handleInheritanceAttr(S, D, Attr);
4924 case AttributeList::AT_Win64:
4925 case AttributeList::AT_Ptr32:
4926 case AttributeList::AT_Ptr64:
4927 handlePortabilityAttr(S, D, Attr);
4929 case AttributeList::AT_ForceInline:
4930 handleForceInlineAttr(S, D, Attr);
4933 // Thread safety attributes:
4934 case AttributeList::AT_GuardedVar:
4935 handleGuardedVarAttr(S, D, Attr);
4937 case AttributeList::AT_PtGuardedVar:
4938 handlePtGuardedVarAttr(S, D, Attr);
4940 case AttributeList::AT_ScopedLockable:
4941 handleScopedLockableAttr(S, D, Attr);
4943 case AttributeList::AT_NoSanitizeAddress:
4944 handleNoSanitizeAddressAttr(S, D, Attr);
4946 case AttributeList::AT_NoThreadSafetyAnalysis:
4947 handleNoThreadSafetyAnalysis(S, D, Attr);
4949 case AttributeList::AT_NoSanitizeThread:
4950 handleNoSanitizeThread(S, D, Attr);
4952 case AttributeList::AT_NoSanitizeMemory:
4953 handleNoSanitizeMemory(S, D, Attr);
4955 case AttributeList::AT_Lockable:
4956 handleLockableAttr(S, D, Attr);
4958 case AttributeList::AT_GuardedBy:
4959 handleGuardedByAttr(S, D, Attr);
4961 case AttributeList::AT_PtGuardedBy:
4962 handlePtGuardedByAttr(S, D, Attr);
4964 case AttributeList::AT_ExclusiveLockFunction:
4965 handleExclusiveLockFunctionAttr(S, D, Attr);
4967 case AttributeList::AT_ExclusiveLocksRequired:
4968 handleExclusiveLocksRequiredAttr(S, D, Attr);
4970 case AttributeList::AT_ExclusiveTrylockFunction:
4971 handleExclusiveTrylockFunctionAttr(S, D, Attr);
4973 case AttributeList::AT_LockReturned:
4974 handleLockReturnedAttr(S, D, Attr);
4976 case AttributeList::AT_LocksExcluded:
4977 handleLocksExcludedAttr(S, D, Attr);
4979 case AttributeList::AT_SharedLockFunction:
4980 handleSharedLockFunctionAttr(S, D, Attr);
4982 case AttributeList::AT_SharedLocksRequired:
4983 handleSharedLocksRequiredAttr(S, D, Attr);
4985 case AttributeList::AT_SharedTrylockFunction:
4986 handleSharedTrylockFunctionAttr(S, D, Attr);
4988 case AttributeList::AT_UnlockFunction:
4989 handleUnlockFunAttr(S, D, Attr);
4991 case AttributeList::AT_AcquiredBefore:
4992 handleAcquiredBeforeAttr(S, D, Attr);
4994 case AttributeList::AT_AcquiredAfter:
4995 handleAcquiredAfterAttr(S, D, Attr);
4998 // Type safety attributes.
4999 case AttributeList::AT_ArgumentWithTypeTag:
5000 handleArgumentWithTypeTagAttr(S, D, Attr);
5002 case AttributeList::AT_TypeTagForDatatype:
5003 handleTypeTagForDatatypeAttr(S, D, Attr);
5007 // Ask target about the attribute.
5008 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
5009 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
5010 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ?
5011 diag::warn_unhandled_ms_attribute_ignored :
5012 diag::warn_unknown_attribute_ignored) << Attr.getName();
5017 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5018 /// the attribute applies to decls. If the attribute is a type attribute, just
5019 /// silently ignore it if a GNU attribute.
5020 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5021 const AttributeList &Attr,
5022 bool NonInheritable, bool Inheritable,
5023 bool IncludeCXX11Attributes) {
5024 if (Attr.isInvalid())
5027 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5029 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5033 ProcessNonInheritableDeclAttr(S, scope, D, Attr);
5036 ProcessInheritableDeclAttr(S, scope, D, Attr);
5039 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5040 /// attribute list to the specified decl, ignoring any type attributes.
5041 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5042 const AttributeList *AttrList,
5043 bool NonInheritable, bool Inheritable,
5044 bool IncludeCXX11Attributes) {
5045 for (const AttributeList* l = AttrList; l; l = l->getNext())
5046 ProcessDeclAttribute(*this, S, D, *l, NonInheritable, Inheritable,
5047 IncludeCXX11Attributes);
5050 // static int a9 __attribute__((weakref));
5051 // but that looks really pointless. We reject it.
5052 if (Inheritable && D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5053 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
5054 cast<NamedDecl>(D)->getNameAsString();
5055 D->dropAttr<WeakRefAttr>();
5060 // Annotation attributes are the only attributes allowed after an access
5062 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5063 const AttributeList *AttrList) {
5064 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5065 if (l->getKind() == AttributeList::AT_Annotate) {
5066 handleAnnotateAttr(*this, ASDecl, *l);
5068 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5076 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5077 /// contains any decl attributes that we should warn about.
5078 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5079 for ( ; A; A = A->getNext()) {
5080 // Only warn if the attribute is an unignored, non-type attribute.
5081 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5082 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5084 if (A->getKind() == AttributeList::UnknownAttribute) {
5085 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5086 << A->getName() << A->getRange();
5088 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5089 << A->getName() << A->getRange();
5094 /// checkUnusedDeclAttributes - Given a declarator which is not being
5095 /// used to build a declaration, complain about any decl attributes
5096 /// which might be lying around on it.
5097 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5098 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5099 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5100 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5101 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5104 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5105 /// \#pragma weak needs a non-definition decl and source may not have one.
5106 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5107 SourceLocation Loc) {
5108 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5109 NamedDecl *NewD = 0;
5110 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5111 FunctionDecl *NewFD;
5112 // FIXME: Missing call to CheckFunctionDeclaration().
5114 // FIXME: Is the qualifier info correct?
5115 // FIXME: Is the DeclContext correct?
5116 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5117 Loc, Loc, DeclarationName(II),
5118 FD->getType(), FD->getTypeSourceInfo(),
5119 SC_None, false/*isInlineSpecified*/,
5121 false/*isConstexprSpecified*/);
5124 if (FD->getQualifier())
5125 NewFD->setQualifierInfo(FD->getQualifierLoc());
5127 // Fake up parameter variables; they are declared as if this were
5129 QualType FDTy = FD->getType();
5130 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5131 SmallVector<ParmVarDecl*, 16> Params;
5132 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5133 AE = FT->arg_type_end(); AI != AE; ++AI) {
5134 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
5135 Param->setScopeInfo(0, Params.size());
5136 Params.push_back(Param);
5138 NewFD->setParams(Params);
5140 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5141 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5142 VD->getInnerLocStart(), VD->getLocation(), II,
5143 VD->getType(), VD->getTypeSourceInfo(),
5144 VD->getStorageClass());
5145 if (VD->getQualifier()) {
5146 VarDecl *NewVD = cast<VarDecl>(NewD);
5147 NewVD->setQualifierInfo(VD->getQualifierLoc());
5153 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5154 /// applied to it, possibly with an alias.
5155 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5156 if (W.getUsed()) return; // only do this once
5158 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5159 IdentifierInfo *NDId = ND->getIdentifier();
5160 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5161 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
5163 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
5164 WeakTopLevelDecl.push_back(NewD);
5165 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5166 // to insert Decl at TU scope, sorry.
5167 DeclContext *SavedContext = CurContext;
5168 CurContext = Context.getTranslationUnitDecl();
5169 PushOnScopeChains(NewD, S);
5170 CurContext = SavedContext;
5171 } else { // just add weak to existing
5172 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
5176 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5177 // It's valid to "forward-declare" #pragma weak, in which case we
5179 LoadExternalWeakUndeclaredIdentifiers();
5180 if (!WeakUndeclaredIdentifiers.empty()) {
5181 NamedDecl *ND = NULL;
5182 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5183 if (VD->isExternC())
5185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5186 if (FD->isExternC())
5189 if (IdentifierInfo *Id = ND->getIdentifier()) {
5190 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
5191 = WeakUndeclaredIdentifiers.find(Id);
5192 if (I != WeakUndeclaredIdentifiers.end()) {
5193 WeakInfo W = I->second;
5194 DeclApplyPragmaWeak(S, ND, W);
5195 WeakUndeclaredIdentifiers[Id] = W;
5202 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5203 /// it, apply them to D. This is a bit tricky because PD can have attributes
5204 /// specified in many different places, and we need to find and apply them all.
5205 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
5206 bool NonInheritable, bool Inheritable) {
5207 // Apply decl attributes from the DeclSpec if present.
5208 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5209 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
5211 // Walk the declarator structure, applying decl attributes that were in a type
5212 // position to the decl itself. This handles cases like:
5213 // int *__attr__(x)** D;
5214 // when X is a decl attribute.
5215 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5216 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5217 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable,
5218 /*IncludeCXX11Attributes=*/false);
5220 // Finally, apply any attributes on the decl itself.
5221 if (const AttributeList *Attrs = PD.getAttributes())
5222 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
5225 /// Is the given declaration allowed to use a forbidden type?
5226 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5227 // Private ivars are always okay. Unfortunately, people don't
5228 // always properly make their ivars private, even in system headers.
5229 // Plus we need to make fields okay, too.
5230 // Function declarations in sys headers will be marked unavailable.
5231 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5232 !isa<FunctionDecl>(decl))
5235 // Require it to be declared in a system header.
5236 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5239 /// Handle a delayed forbidden-type diagnostic.
5240 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5242 if (decl && isForbiddenTypeAllowed(S, decl)) {
5243 decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
5244 "this system declaration uses an unsupported type"));
5247 if (S.getLangOpts().ObjCAutoRefCount)
5248 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5249 // FIXME: we may want to suppress diagnostics for all
5250 // kind of forbidden type messages on unavailable functions.
5251 if (FD->hasAttr<UnavailableAttr>() &&
5252 diag.getForbiddenTypeDiagnostic() ==
5253 diag::err_arc_array_param_no_ownership) {
5254 diag.Triggered = true;
5259 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5260 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5261 diag.Triggered = true;
5264 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5265 assert(DelayedDiagnostics.getCurrentPool());
5266 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5267 DelayedDiagnostics.popWithoutEmitting(state);
5269 // When delaying diagnostics to run in the context of a parsed
5270 // declaration, we only want to actually emit anything if parsing
5274 // We emit all the active diagnostics in this pool or any of its
5275 // parents. In general, we'll get one pool for the decl spec
5276 // and a child pool for each declarator; in a decl group like:
5277 // deprecated_typedef foo, *bar, baz();
5278 // only the declarator pops will be passed decls. This is correct;
5279 // we really do need to consider delayed diagnostics from the decl spec
5280 // for each of the different declarations.
5281 const DelayedDiagnosticPool *pool = &poppedPool;
5283 for (DelayedDiagnosticPool::pool_iterator
5284 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5285 // This const_cast is a bit lame. Really, Triggered should be mutable.
5286 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5290 switch (diag.Kind) {
5291 case DelayedDiagnostic::Deprecation:
5292 // Don't bother giving deprecation diagnostics if the decl is invalid.
5293 if (!decl->isInvalidDecl())
5294 HandleDelayedDeprecationCheck(diag, decl);
5297 case DelayedDiagnostic::Access:
5298 HandleDelayedAccessCheck(diag, decl);
5301 case DelayedDiagnostic::ForbiddenType:
5302 handleDelayedForbiddenType(*this, diag, decl);
5306 } while ((pool = pool->getParent()));
5309 /// Given a set of delayed diagnostics, re-emit them as if they had
5310 /// been delayed in the current context instead of in the given pool.
5311 /// Essentially, this just moves them to the current pool.
5312 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5313 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5314 assert(curPool && "re-emitting in undelayed context not supported");
5315 curPool->steal(pool);
5318 static bool isDeclDeprecated(Decl *D) {
5320 if (D->isDeprecated())
5322 // A category implicitly has the availability of the interface.
5323 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5324 return CatD->getClassInterface()->isDeprecated();
5325 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5330 DoEmitDeprecationWarning(Sema &S, const NamedDecl *D, StringRef Message,
5332 const ObjCInterfaceDecl *UnknownObjCClass,
5333 const ObjCPropertyDecl *ObjCPropery) {
5334 DeclarationName Name = D->getDeclName();
5335 if (!Message.empty()) {
5336 S.Diag(Loc, diag::warn_deprecated_message) << Name << Message;
5337 S.Diag(D->getLocation(),
5338 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5339 : diag::note_previous_decl) << Name;
5341 S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5342 << ObjCPropery->getDeclName() << 0;
5343 } else if (!UnknownObjCClass) {
5344 S.Diag(Loc, diag::warn_deprecated) << D->getDeclName();
5345 S.Diag(D->getLocation(),
5346 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5347 : diag::note_previous_decl) << Name;
5349 S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5350 << ObjCPropery->getDeclName() << 0;
5352 S.Diag(Loc, diag::warn_deprecated_fwdclass_message) << Name;
5353 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5357 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
5359 if (isDeclDeprecated(Ctx))
5362 DD.Triggered = true;
5363 DoEmitDeprecationWarning(*this, DD.getDeprecationDecl(),
5364 DD.getDeprecationMessage(), DD.Loc,
5365 DD.getUnknownObjCClass(),
5366 DD.getObjCProperty());
5369 void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
5371 const ObjCInterfaceDecl *UnknownObjCClass,
5372 const ObjCPropertyDecl *ObjCProperty) {
5373 // Delay if we're currently parsing a declaration.
5374 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
5375 DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,
5382 // Otherwise, don't warn if our current context is deprecated.
5383 if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
5385 DoEmitDeprecationWarning(*this, D, Message, Loc, UnknownObjCClass, ObjCProperty);