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/DeclCXX.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/DelayedDiagnostic.h"
25 #include "clang/Sema/Lookup.h"
26 #include "llvm/ADT/StringExtras.h"
27 using namespace clang;
30 /// These constants match the enumerated choices of
31 /// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
32 enum AttributeDeclKind {
35 ExpectedVariableOrFunction,
36 ExpectedFunctionOrMethod,
38 ExpectedParameterOrMethod,
39 ExpectedFunctionMethodOrBlock,
40 ExpectedClassOrVirtualMethod,
41 ExpectedFunctionMethodOrParameter,
43 ExpectedVirtualMethod,
47 ExpectedVariableFunctionOrLabel,
48 ExpectedFieldOrGlobalVar
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static const FunctionType *getFunctionType(const Decl *D,
56 bool blocksToo = true) {
58 if (const ValueDecl *decl = dyn_cast<ValueDecl>(D))
60 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(D))
62 else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(D))
63 Ty = decl->getUnderlyingType();
67 if (Ty->isFunctionPointerType())
68 Ty = Ty->getAs<PointerType>()->getPointeeType();
69 else if (blocksToo && Ty->isBlockPointerType())
70 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
72 return Ty->getAs<FunctionType>();
75 // FIXME: We should provide an abstraction around a method or function
76 // to provide the following bits of information.
78 /// isFunction - Return true if the given decl has function
79 /// type (function or function-typed variable).
80 static bool isFunction(const Decl *D) {
81 return getFunctionType(D, false) != NULL;
84 /// isFunctionOrMethod - Return true if the given decl has function
85 /// type (function or function-typed variable) or an Objective-C
87 static bool isFunctionOrMethod(const Decl *D) {
88 return isFunction(D)|| isa<ObjCMethodDecl>(D);
91 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
92 /// type (function or function-typed variable) or an Objective-C
93 /// method or a block.
94 static bool isFunctionOrMethodOrBlock(const Decl *D) {
95 if (isFunctionOrMethod(D))
97 // check for block is more involved.
98 if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
99 QualType Ty = V->getType();
100 return Ty->isBlockPointerType();
102 return isa<BlockDecl>(D);
105 /// Return true if the given decl has a declarator that should have
106 /// been processed by Sema::GetTypeForDeclarator.
107 static bool hasDeclarator(const Decl *D) {
108 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
109 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
110 isa<ObjCPropertyDecl>(D);
113 /// hasFunctionProto - Return true if the given decl has a argument
114 /// information. This decl should have already passed
115 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
116 static bool hasFunctionProto(const Decl *D) {
117 if (const FunctionType *FnTy = getFunctionType(D))
118 return isa<FunctionProtoType>(FnTy);
120 assert(isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D));
125 /// getFunctionOrMethodNumArgs - Return number of function or method
126 /// arguments. It is an error to call this on a K&R function (use
127 /// hasFunctionProto first).
128 static unsigned getFunctionOrMethodNumArgs(const Decl *D) {
129 if (const FunctionType *FnTy = getFunctionType(D))
130 return cast<FunctionProtoType>(FnTy)->getNumArgs();
131 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
132 return BD->getNumParams();
133 return cast<ObjCMethodDecl>(D)->param_size();
136 static QualType getFunctionOrMethodArgType(const Decl *D, unsigned Idx) {
137 if (const FunctionType *FnTy = getFunctionType(D))
138 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
139 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
140 return BD->getParamDecl(Idx)->getType();
142 return cast<ObjCMethodDecl>(D)->param_begin()[Idx]->getType();
145 static QualType getFunctionOrMethodResultType(const Decl *D) {
146 if (const FunctionType *FnTy = getFunctionType(D))
147 return cast<FunctionProtoType>(FnTy)->getResultType();
148 return cast<ObjCMethodDecl>(D)->getResultType();
151 static bool isFunctionOrMethodVariadic(const Decl *D) {
152 if (const FunctionType *FnTy = getFunctionType(D)) {
153 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
154 return proto->isVariadic();
155 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
156 return BD->isVariadic();
158 return cast<ObjCMethodDecl>(D)->isVariadic();
162 static bool isInstanceMethod(const Decl *D) {
163 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
164 return MethodDecl->isInstance();
168 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
169 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
173 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
177 IdentifierInfo* ClsName = Cls->getIdentifier();
179 // FIXME: Should we walk the chain of classes?
180 return ClsName == &Ctx.Idents.get("NSString") ||
181 ClsName == &Ctx.Idents.get("NSMutableString");
184 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
185 const PointerType *PT = T->getAs<PointerType>();
189 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
193 const RecordDecl *RD = RT->getDecl();
194 if (RD->getTagKind() != TTK_Struct)
197 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
200 /// \brief Check if the attribute has exactly as many args as Num. May
202 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
204 if (Attr.getNumArgs() != Num) {
205 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Num;
213 /// \brief Check if the attribute has at least as many args as Num. May
215 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
217 if (Attr.getNumArgs() < Num) {
218 S.Diag(Attr.getLoc(), diag::err_attribute_too_few_arguments) << Num;
226 /// \brief Check if passed in Decl is a field or potentially shared global var
227 /// \return true if the Decl is a field or potentially shared global variable
229 static bool mayBeSharedVariable(const Decl *D) {
230 if (isa<FieldDecl>(D))
232 if (const VarDecl *vd = dyn_cast<VarDecl>(D))
233 return (vd->hasGlobalStorage() && !(vd->isThreadSpecified()));
238 /// \brief Check if the passed-in expression is of type int or bool.
239 static bool isIntOrBool(Expr *Exp) {
240 QualType QT = Exp->getType();
241 return QT->isBooleanType() || QT->isIntegerType();
245 /// \brief Check if passed in Decl is a pointer type.
246 /// Note that this function may produce an error message.
247 /// \return true if the Decl is a pointer type; false otherwise
249 static bool checkIsPointer(Sema &S, const Decl *D, const AttributeList &Attr) {
250 if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) {
251 QualType QT = vd->getType();
252 if (QT->isAnyPointerType())
254 S.Diag(Attr.getLoc(), diag::warn_pointer_attribute_wrong_type)
255 << Attr.getName()->getName() << QT;
257 S.Diag(Attr.getLoc(), diag::err_attribute_can_be_applied_only_to_value_decl)
263 /// \brief Checks that the passed in QualType either is of RecordType or points
264 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
265 static const RecordType *getRecordType(QualType QT) {
266 if (const RecordType *RT = QT->getAs<RecordType>())
269 // Now check if we point to record type.
270 if (const PointerType *PT = QT->getAs<PointerType>())
271 return PT->getPointeeType()->getAs<RecordType>();
276 /// \brief Thread Safety Analysis: Checks that the passed in RecordType
277 /// resolves to a lockable object. May flag an error.
278 static bool checkForLockableRecord(Sema &S, Decl *D, const AttributeList &Attr,
279 const RecordType *RT) {
280 // Flag error if could not get record type for this argument.
282 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_class)
286 // Flag error if the type is not lockable.
287 if (!RT->getDecl()->getAttr<LockableAttr>()) {
288 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_lockable)
295 /// \brief Thread Safety Analysis: Checks that all attribute arguments, starting
296 /// from Sidx, resolve to a lockable object. May flag an error.
297 /// \param Sidx The attribute argument index to start checking with.
298 /// \param ParamIdxOk Whether an argument can be indexing into a function
300 static bool checkAttrArgsAreLockableObjs(Sema &S, Decl *D,
301 const AttributeList &Attr,
302 SmallVectorImpl<Expr*> &Args,
304 bool ParamIdxOk = false) {
305 for(unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
306 Expr *ArgExp = Attr.getArg(Idx);
308 if (ArgExp->isTypeDependent()) {
309 // FIXME -- need to processs this again on template instantiation
310 Args.push_back(ArgExp);
314 QualType ArgTy = ArgExp->getType();
316 // First see if we can just cast to record type, or point to record type.
317 const RecordType *RT = getRecordType(ArgTy);
319 // Now check if we index into a record type function param.
320 if(!RT && ParamIdxOk) {
321 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
322 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
324 unsigned int NumParams = FD->getNumParams();
325 llvm::APInt ArgValue = IL->getValue();
326 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
327 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
328 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
329 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
330 << Attr.getName() << Idx + 1 << NumParams;
333 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
334 RT = getRecordType(ArgTy);
338 if (!checkForLockableRecord(S, D, Attr, RT))
341 Args.push_back(ArgExp);
346 //===----------------------------------------------------------------------===//
347 // Attribute Implementations
348 //===----------------------------------------------------------------------===//
350 // FIXME: All this manual attribute parsing code is gross. At the
351 // least add some helper functions to check most argument patterns (#
352 // and types of args).
354 static void handleGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr,
355 bool pointer = false) {
356 assert(!Attr.isInvalid());
358 if (!checkAttributeNumArgs(S, Attr, 0))
361 // D must be either a member field or global (potentially shared) variable.
362 if (!mayBeSharedVariable(D)) {
363 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
364 << Attr.getName() << ExpectedFieldOrGlobalVar;
368 if (pointer && !checkIsPointer(S, D, Attr))
372 D->addAttr(::new (S.Context) PtGuardedVarAttr(Attr.getRange(), S.Context));
374 D->addAttr(::new (S.Context) GuardedVarAttr(Attr.getRange(), S.Context));
377 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr,
378 bool pointer = false) {
379 assert(!Attr.isInvalid());
381 if (!checkAttributeNumArgs(S, Attr, 1))
384 Expr *Arg = Attr.getArg(0);
386 // D must be either a member field or global (potentially shared) variable.
387 if (!mayBeSharedVariable(D)) {
388 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
389 << Attr.getName() << ExpectedFieldOrGlobalVar;
393 if (pointer && !checkIsPointer(S, D, Attr))
396 if (Arg->isTypeDependent())
397 // FIXME: handle attributes with dependent types
400 // check that the argument is lockable object
401 if (!checkForLockableRecord(S, D, Attr, getRecordType(Arg->getType())))
405 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
408 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg));
412 static void handleLockableAttr(Sema &S, Decl *D, const AttributeList &Attr,
413 bool scoped = false) {
414 assert(!Attr.isInvalid());
416 if (!checkAttributeNumArgs(S, Attr, 0))
419 // FIXME: Lockable structs for C code.
420 if (!isa<CXXRecordDecl>(D)) {
421 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
422 << Attr.getName() << ExpectedClass;
427 D->addAttr(::new (S.Context) ScopedLockableAttr(Attr.getRange(), S.Context));
429 D->addAttr(::new (S.Context) LockableAttr(Attr.getRange(), S.Context));
432 static void handleNoThreadSafetyAttr(Sema &S, Decl *D,
433 const AttributeList &Attr) {
434 assert(!Attr.isInvalid());
436 if (!checkAttributeNumArgs(S, Attr, 0))
439 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
440 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
441 << Attr.getName() << ExpectedFunctionOrMethod;
445 D->addAttr(::new (S.Context) NoThreadSafetyAnalysisAttr(Attr.getRange(),
449 static void handleAcquireOrderAttr(Sema &S, Decl *D, const AttributeList &Attr,
451 assert(!Attr.isInvalid());
453 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
456 // D must be either a member field or global (potentially shared) variable.
457 ValueDecl *VD = dyn_cast<ValueDecl>(D);
458 if (!VD || !mayBeSharedVariable(D)) {
459 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
460 << Attr.getName() << ExpectedFieldOrGlobalVar;
464 // Check that this attribute only applies to lockable types
465 QualType QT = VD->getType();
466 if (!QT->isDependentType()) {
467 const RecordType *RT = getRecordType(QT);
468 if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
469 S.Diag(Attr.getLoc(), diag::err_attribute_decl_not_lockable)
475 SmallVector<Expr*, 1> Args;
476 // check that all arguments are lockable objects
477 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args))
480 unsigned Size = Args.size();
481 assert(Size == Attr.getNumArgs());
482 Expr **StartArg = Size == 0 ? 0 : &Args[0];
485 D->addAttr(::new (S.Context) AcquiredBeforeAttr(Attr.getRange(), S.Context,
488 D->addAttr(::new (S.Context) AcquiredAfterAttr(Attr.getRange(), S.Context,
492 static void handleLockFunAttr(Sema &S, Decl *D, const AttributeList &Attr,
493 bool exclusive = false) {
494 assert(!Attr.isInvalid());
496 // zero or more arguments ok
498 // check that the attribute is applied to a function
499 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
500 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
501 << Attr.getName() << ExpectedFunctionOrMethod;
505 // check that all arguments are lockable objects
506 SmallVector<Expr*, 1> Args;
507 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true))
510 unsigned Size = Args.size();
511 assert(Size == Attr.getNumArgs());
512 Expr **StartArg = Size == 0 ? 0 : &Args[0];
515 D->addAttr(::new (S.Context) ExclusiveLockFunctionAttr(Attr.getRange(),
519 D->addAttr(::new (S.Context) SharedLockFunctionAttr(Attr.getRange(),
524 static void handleTrylockFunAttr(Sema &S, Decl *D, const AttributeList &Attr,
525 bool exclusive = false) {
526 assert(!Attr.isInvalid());
528 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
532 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
533 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
534 << Attr.getName() << ExpectedFunctionOrMethod;
538 if (!isIntOrBool(Attr.getArg(0))) {
539 S.Diag(Attr.getLoc(), diag::err_attribute_first_argument_not_int_or_bool)
544 SmallVector<Expr*, 2> Args;
545 // check that all arguments are lockable objects
546 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args, 1))
549 unsigned Size = Args.size();
550 Expr **StartArg = Size == 0 ? 0 : &Args[0];
553 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(Attr.getRange(),
558 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(Attr.getRange(),
564 static void handleLocksRequiredAttr(Sema &S, Decl *D, const AttributeList &Attr,
565 bool exclusive = false) {
566 assert(!Attr.isInvalid());
568 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
571 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
572 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
573 << Attr.getName() << ExpectedFunctionOrMethod;
577 // check that all arguments are lockable objects
578 SmallVector<Expr*, 1> Args;
579 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args))
582 unsigned Size = Args.size();
583 assert(Size == Attr.getNumArgs());
584 Expr **StartArg = Size == 0 ? 0 : &Args[0];
587 D->addAttr(::new (S.Context) ExclusiveLocksRequiredAttr(Attr.getRange(),
591 D->addAttr(::new (S.Context) SharedLocksRequiredAttr(Attr.getRange(),
596 static void handleUnlockFunAttr(Sema &S, Decl *D,
597 const AttributeList &Attr) {
598 assert(!Attr.isInvalid());
600 // zero or more arguments ok
602 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
603 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
604 << Attr.getName() << ExpectedFunctionOrMethod;
608 // check that all arguments are lockable objects
609 SmallVector<Expr*, 1> Args;
610 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true))
613 unsigned Size = Args.size();
614 assert(Size == Attr.getNumArgs());
615 Expr **StartArg = Size == 0 ? 0 : &Args[0];
617 D->addAttr(::new (S.Context) UnlockFunctionAttr(Attr.getRange(), S.Context,
621 static void handleLockReturnedAttr(Sema &S, Decl *D,
622 const AttributeList &Attr) {
623 assert(!Attr.isInvalid());
625 if (!checkAttributeNumArgs(S, Attr, 1))
627 Expr *Arg = Attr.getArg(0);
629 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
630 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
631 << Attr.getName() << ExpectedFunctionOrMethod;
635 if (Arg->isTypeDependent())
638 // check that the argument is lockable object
639 if (!checkForLockableRecord(S, D, Attr, getRecordType(Arg->getType())))
642 D->addAttr(::new (S.Context) LockReturnedAttr(Attr.getRange(), S.Context, Arg));
645 static void handleLocksExcludedAttr(Sema &S, Decl *D,
646 const AttributeList &Attr) {
647 assert(!Attr.isInvalid());
649 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
652 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
653 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
654 << Attr.getName() << ExpectedFunctionOrMethod;
658 // check that all arguments are lockable objects
659 SmallVector<Expr*, 1> Args;
660 if (!checkAttrArgsAreLockableObjs(S, D, Attr, Args))
663 unsigned Size = Args.size();
664 assert(Size == Attr.getNumArgs());
665 Expr **StartArg = Size == 0 ? 0 : &Args[0];
667 D->addAttr(::new (S.Context) LocksExcludedAttr(Attr.getRange(), S.Context,
672 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
673 const AttributeList &Attr) {
674 TypedefNameDecl *tDecl = dyn_cast<TypedefNameDecl>(D);
676 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
680 QualType curType = tDecl->getUnderlyingType();
684 // Special case where the argument is a template id.
685 if (Attr.getParameterName()) {
688 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
690 ExprResult Size = S.ActOnIdExpression(scope, SS, id, false, false);
691 if (Size.isInvalid())
694 sizeExpr = Size.get();
696 // check the attribute arguments.
697 if (!checkAttributeNumArgs(S, Attr, 1))
700 sizeExpr = Attr.getArg(0);
703 // Instantiate/Install the vector type, and let Sema build the type for us.
704 // This will run the reguired checks.
705 QualType T = S.BuildExtVectorType(curType, sizeExpr, Attr.getLoc());
707 // FIXME: preserve the old source info.
708 tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
710 // Remember this typedef decl, we will need it later for diagnostics.
711 S.ExtVectorDecls.push_back(tDecl);
715 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
716 // check the attribute arguments.
717 if (!checkAttributeNumArgs(S, Attr, 0))
720 if (TagDecl *TD = dyn_cast<TagDecl>(D))
721 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
722 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
723 // If the alignment is less than or equal to 8 bits, the packed attribute
725 if (!FD->getType()->isIncompleteType() &&
726 S.Context.getTypeAlign(FD->getType()) <= 8)
727 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
728 << Attr.getName() << FD->getType();
730 FD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
732 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
735 static void handleMsStructAttr(Sema &S, Decl *D, const AttributeList &Attr) {
736 if (TagDecl *TD = dyn_cast<TagDecl>(D))
737 TD->addAttr(::new (S.Context) MsStructAttr(Attr.getRange(), S.Context));
739 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
742 static void handleIBAction(Sema &S, Decl *D, const AttributeList &Attr) {
743 // check the attribute arguments.
744 if (!checkAttributeNumArgs(S, Attr, 0))
747 // The IBAction attributes only apply to instance methods.
748 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
749 if (MD->isInstanceMethod()) {
750 D->addAttr(::new (S.Context) IBActionAttr(Attr.getRange(), S.Context));
754 S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
757 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
758 // The IBOutlet/IBOutletCollection attributes only apply to instance
759 // variables or properties of Objective-C classes. The outlet must also
760 // have an object reference type.
761 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
762 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
763 S.Diag(Attr.getLoc(), diag::err_iboutlet_object_type)
764 << Attr.getName() << VD->getType() << 0;
768 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
769 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
770 S.Diag(Attr.getLoc(), diag::err_iboutlet_object_type)
771 << Attr.getName() << PD->getType() << 1;
776 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
783 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
784 // check the attribute arguments.
785 if (!checkAttributeNumArgs(S, Attr, 0))
788 if (!checkIBOutletCommon(S, D, Attr))
791 D->addAttr(::new (S.Context) IBOutletAttr(Attr.getRange(), S.Context));
794 static void handleIBOutletCollection(Sema &S, Decl *D,
795 const AttributeList &Attr) {
797 // The iboutletcollection attribute can have zero or one arguments.
798 if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
799 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
803 if (!checkIBOutletCommon(S, D, Attr))
806 IdentifierInfo *II = Attr.getParameterName();
808 II = &S.Context.Idents.get("id");
810 ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
811 S.getScopeForContext(D->getDeclContext()->getParent()));
813 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
816 QualType QT = TypeRep.get();
817 // Diagnose use of non-object type in iboutletcollection attribute.
818 // FIXME. Gnu attribute extension ignores use of builtin types in
819 // attributes. So, __attribute__((iboutletcollection(char))) will be
820 // treated as __attribute__((iboutletcollection())).
821 if (!QT->isObjCIdType() && !QT->isObjCClassType() &&
822 !QT->isObjCObjectType()) {
823 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
826 D->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getRange(),S.Context,
827 QT, Attr.getParameterLoc()));
830 static void possibleTransparentUnionPointerType(QualType &T) {
831 if (const RecordType *UT = T->getAsUnionType())
832 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
833 RecordDecl *UD = UT->getDecl();
834 for (RecordDecl::field_iterator it = UD->field_begin(),
835 itend = UD->field_end(); it != itend; ++it) {
836 QualType QT = it->getType();
837 if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
845 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
846 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
848 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
849 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
850 << Attr.getName() << ExpectedFunction;
854 // In C++ the implicit 'this' function parameter also counts, and they are
856 bool HasImplicitThisParam = isInstanceMethod(D);
857 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
859 // The nonnull attribute only applies to pointers.
860 SmallVector<unsigned, 10> NonNullArgs;
862 for (AttributeList::arg_iterator I=Attr.arg_begin(),
863 E=Attr.arg_end(); I!=E; ++I) {
866 // The argument must be an integer constant expression.
868 llvm::APSInt ArgNum(32);
869 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
870 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
871 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
872 << "nonnull" << Ex->getSourceRange();
876 unsigned x = (unsigned) ArgNum.getZExtValue();
878 if (x < 1 || x > NumArgs) {
879 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
880 << "nonnull" << I.getArgNum() << Ex->getSourceRange();
885 if (HasImplicitThisParam) {
887 S.Diag(Attr.getLoc(),
888 diag::err_attribute_invalid_implicit_this_argument)
889 << "nonnull" << Ex->getSourceRange();
895 // Is the function argument a pointer type?
896 QualType T = getFunctionOrMethodArgType(D, x).getNonReferenceType();
897 possibleTransparentUnionPointerType(T);
899 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
900 // FIXME: Should also highlight argument in decl.
901 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
902 << "nonnull" << Ex->getSourceRange();
906 NonNullArgs.push_back(x);
909 // If no arguments were specified to __attribute__((nonnull)) then all pointer
910 // arguments have a nonnull attribute.
911 if (NonNullArgs.empty()) {
912 for (unsigned I = 0, E = getFunctionOrMethodNumArgs(D); I != E; ++I) {
913 QualType T = getFunctionOrMethodArgType(D, I).getNonReferenceType();
914 possibleTransparentUnionPointerType(T);
915 if (T->isAnyPointerType() || T->isBlockPointerType())
916 NonNullArgs.push_back(I);
919 // No pointer arguments?
920 if (NonNullArgs.empty()) {
921 // Warn the trivial case only if attribute is not coming from a
922 // macro instantiation.
923 if (Attr.getLoc().isFileID())
924 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
929 unsigned* start = &NonNullArgs[0];
930 unsigned size = NonNullArgs.size();
931 llvm::array_pod_sort(start, start + size);
932 D->addAttr(::new (S.Context) NonNullAttr(Attr.getRange(), S.Context, start,
936 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
937 // This attribute must be applied to a function declaration.
938 // The first argument to the attribute must be a string,
939 // the name of the resource, for example "malloc".
940 // The following arguments must be argument indexes, the arguments must be
941 // of integer type for Returns, otherwise of pointer type.
942 // The difference between Holds and Takes is that a pointer may still be used
943 // after being held. free() should be __attribute((ownership_takes)), whereas
944 // a list append function may well be __attribute((ownership_holds)).
946 if (!AL.getParameterName()) {
947 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
948 << AL.getName()->getName() << 1;
951 // Figure out our Kind, and check arguments while we're at it.
952 OwnershipAttr::OwnershipKind K;
953 switch (AL.getKind()) {
954 case AttributeList::AT_ownership_takes:
955 K = OwnershipAttr::Takes;
956 if (AL.getNumArgs() < 1) {
957 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
961 case AttributeList::AT_ownership_holds:
962 K = OwnershipAttr::Holds;
963 if (AL.getNumArgs() < 1) {
964 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
968 case AttributeList::AT_ownership_returns:
969 K = OwnershipAttr::Returns;
970 if (AL.getNumArgs() > 1) {
971 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
972 << AL.getNumArgs() + 1;
977 // This should never happen given how we are called.
978 llvm_unreachable("Unknown ownership attribute");
981 if (!isFunction(D) || !hasFunctionProto(D)) {
982 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
983 << AL.getName() << ExpectedFunction;
987 // In C++ the implicit 'this' function parameter also counts, and they are
989 bool HasImplicitThisParam = isInstanceMethod(D);
990 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
992 StringRef Module = AL.getParameterName()->getName();
994 // Normalize the argument, __foo__ becomes foo.
995 if (Module.startswith("__") && Module.endswith("__"))
996 Module = Module.substr(2, Module.size() - 4);
998 SmallVector<unsigned, 10> OwnershipArgs;
1000 for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
1004 llvm::APSInt ArgNum(32);
1005 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1006 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1007 S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
1008 << AL.getName()->getName() << IdxExpr->getSourceRange();
1012 unsigned x = (unsigned) ArgNum.getZExtValue();
1014 if (x > NumArgs || x < 1) {
1015 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
1016 << AL.getName()->getName() << x << IdxExpr->getSourceRange();
1020 if (HasImplicitThisParam) {
1022 S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1023 << "ownership" << IdxExpr->getSourceRange();
1030 case OwnershipAttr::Takes:
1031 case OwnershipAttr::Holds: {
1032 // Is the function argument a pointer type?
1033 QualType T = getFunctionOrMethodArgType(D, x);
1034 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1035 // FIXME: Should also highlight argument in decl.
1036 S.Diag(AL.getLoc(), diag::err_ownership_type)
1037 << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
1039 << IdxExpr->getSourceRange();
1044 case OwnershipAttr::Returns: {
1045 if (AL.getNumArgs() > 1) {
1046 // Is the function argument an integer type?
1047 Expr *IdxExpr = AL.getArg(0);
1048 llvm::APSInt ArgNum(32);
1049 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
1050 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
1051 S.Diag(AL.getLoc(), diag::err_ownership_type)
1052 << "ownership_returns" << "integer"
1053 << IdxExpr->getSourceRange();
1060 llvm_unreachable("Unknown ownership attribute");
1063 // Check we don't have a conflict with another ownership attribute.
1064 for (specific_attr_iterator<OwnershipAttr>
1065 i = D->specific_attr_begin<OwnershipAttr>(),
1066 e = D->specific_attr_end<OwnershipAttr>();
1068 if ((*i)->getOwnKind() != K) {
1069 for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
1072 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1073 << AL.getName()->getName() << "ownership_*";
1078 OwnershipArgs.push_back(x);
1081 unsigned* start = OwnershipArgs.data();
1082 unsigned size = OwnershipArgs.size();
1083 llvm::array_pod_sort(start, start + size);
1085 if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
1086 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
1090 D->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, K, Module,
1094 /// Whether this declaration has internal linkage for the purposes of
1095 /// things that want to complain about things not have internal linkage.
1096 static bool hasEffectivelyInternalLinkage(NamedDecl *D) {
1097 switch (D->getLinkage()) {
1099 case InternalLinkage:
1102 // Template instantiations that go from external to unique-external
1103 // shouldn't get diagnosed.
1104 case UniqueExternalLinkage:
1107 case ExternalLinkage:
1110 llvm_unreachable("unknown linkage kind!");
1114 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1115 // Check the attribute arguments.
1116 if (Attr.getNumArgs() > 1) {
1117 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1121 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1122 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1123 << Attr.getName() << ExpectedVariableOrFunction;
1127 NamedDecl *nd = cast<NamedDecl>(D);
1131 // static int a __attribute__((weakref ("v2")));
1132 // static int b() __attribute__((weakref ("f3")));
1134 // and ignores the attributes of
1136 // static int a __attribute__((weakref ("v2")));
1139 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1140 if (!Ctx->isFileContext()) {
1141 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
1142 nd->getNameAsString();
1146 // The GCC manual says
1148 // At present, a declaration to which `weakref' is attached can only
1153 // Without a TARGET,
1154 // given as an argument to `weakref' or to `alias', `weakref' is
1155 // equivalent to `weak'.
1157 // gcc 4.4.1 will accept
1158 // int a7 __attribute__((weakref));
1160 // int a7 __attribute__((weak));
1161 // This looks like a bug in gcc. We reject that for now. We should revisit
1162 // it if this behaviour is actually used.
1164 if (!hasEffectivelyInternalLinkage(nd)) {
1165 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static);
1170 // static ((alias ("y"), weakref)).
1171 // Should we? How to check that weakref is before or after alias?
1173 if (Attr.getNumArgs() == 1) {
1174 Expr *Arg = Attr.getArg(0);
1175 Arg = Arg->IgnoreParenCasts();
1176 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1178 if (!Str || !Str->isAscii()) {
1179 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1183 // GCC will accept anything as the argument of weakref. Should we
1184 // check for an existing decl?
1185 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1189 D->addAttr(::new (S.Context) WeakRefAttr(Attr.getRange(), S.Context));
1192 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1193 // check the attribute arguments.
1194 if (Attr.getNumArgs() != 1) {
1195 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1199 Expr *Arg = Attr.getArg(0);
1200 Arg = Arg->IgnoreParenCasts();
1201 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1203 if (!Str || !Str->isAscii()) {
1204 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1209 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1210 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1214 // FIXME: check if target symbol exists in current file
1216 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context,
1220 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1221 // Check the attribute arguments.
1222 if (!checkAttributeNumArgs(S, Attr, 0))
1225 if (!isa<FunctionDecl>(D)) {
1226 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1227 << Attr.getName() << ExpectedFunction;
1231 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context));
1234 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
1235 const AttributeList &Attr) {
1236 // Check the attribute arguments.
1237 if (Attr.hasParameterOrArguments()) {
1238 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1242 if (!isa<FunctionDecl>(D)) {
1243 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1244 << Attr.getName() << ExpectedFunction;
1248 D->addAttr(::new (S.Context) AlwaysInlineAttr(Attr.getRange(), S.Context));
1251 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1252 // Check the attribute arguments.
1253 if (Attr.hasParameterOrArguments()) {
1254 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1259 QualType RetTy = FD->getResultType();
1260 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1261 D->addAttr(::new (S.Context) MallocAttr(Attr.getRange(), S.Context));
1266 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1269 static void handleMayAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1270 // check the attribute arguments.
1271 if (!checkAttributeNumArgs(S, Attr, 0))
1274 D->addAttr(::new (S.Context) MayAliasAttr(Attr.getRange(), S.Context));
1277 static void handleNoCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1278 assert(!Attr.isInvalid());
1279 if (isa<VarDecl>(D))
1280 D->addAttr(::new (S.Context) NoCommonAttr(Attr.getRange(), S.Context));
1282 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1283 << Attr.getName() << ExpectedVariable;
1286 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1287 assert(!Attr.isInvalid());
1288 if (isa<VarDecl>(D))
1289 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context));
1291 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1292 << Attr.getName() << ExpectedVariable;
1295 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1296 if (hasDeclarator(D)) return;
1298 if (S.CheckNoReturnAttr(attr)) return;
1300 if (!isa<ObjCMethodDecl>(D)) {
1301 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1302 << attr.getName() << ExpectedFunctionOrMethod;
1306 D->addAttr(::new (S.Context) NoReturnAttr(attr.getRange(), S.Context));
1309 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1310 if (attr.hasParameterOrArguments()) {
1311 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1319 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1320 const AttributeList &Attr) {
1322 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1323 // because 'analyzer_noreturn' does not impact the type.
1325 if(!checkAttributeNumArgs(S, Attr, 0))
1328 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1329 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1330 if (VD == 0 || (!VD->getType()->isBlockPointerType()
1331 && !VD->getType()->isFunctionPointerType())) {
1332 S.Diag(Attr.getLoc(),
1333 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1334 : diag::warn_attribute_wrong_decl_type)
1335 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1340 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getRange(), S.Context));
1343 // PS3 PPU-specific.
1344 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1346 Returning a Vector Class in Registers
1348 According to the PPU ABI specifications, a class with a single member of
1349 vector type is returned in memory when used as the return value of a function.
1350 This results in inefficient code when implementing vector classes. To return
1351 the value in a single vector register, add the vecreturn attribute to the
1352 class definition. This attribute is also applicable to struct types.
1358 __vector float xyzw;
1359 } __attribute__((vecreturn));
1361 Vector Add(Vector lhs, Vector rhs)
1364 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1365 return result; // This will be returned in a register
1368 if (!isa<RecordDecl>(D)) {
1369 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1370 << Attr.getName() << ExpectedClass;
1374 if (D->getAttr<VecReturnAttr>()) {
1375 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
1379 RecordDecl *record = cast<RecordDecl>(D);
1382 if (!isa<CXXRecordDecl>(record)) {
1383 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1387 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1388 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1392 for (RecordDecl::field_iterator iter = record->field_begin();
1393 iter != record->field_end(); iter++) {
1394 if ((count == 1) || !iter->getType()->isVectorType()) {
1395 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1401 D->addAttr(::new (S.Context) VecReturnAttr(Attr.getRange(), S.Context));
1404 static void handleDependencyAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1405 if (!isFunctionOrMethod(D) && !isa<ParmVarDecl>(D)) {
1406 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1407 << Attr.getName() << ExpectedFunctionMethodOrParameter;
1410 // FIXME: Actually store the attribute on the declaration
1413 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1414 // check the attribute arguments.
1415 if (Attr.hasParameterOrArguments()) {
1416 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1420 if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isFunctionOrMethod(D) &&
1421 !isa<TypeDecl>(D) && !isa<LabelDecl>(D)) {
1422 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1423 << Attr.getName() << ExpectedVariableFunctionOrLabel;
1427 D->addAttr(::new (S.Context) UnusedAttr(Attr.getRange(), S.Context));
1430 static void handleReturnsTwiceAttr(Sema &S, Decl *D,
1431 const AttributeList &Attr) {
1432 // check the attribute arguments.
1433 if (Attr.hasParameterOrArguments()) {
1434 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1438 if (!isa<FunctionDecl>(D)) {
1439 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1440 << Attr.getName() << ExpectedFunction;
1444 D->addAttr(::new (S.Context) ReturnsTwiceAttr(Attr.getRange(), S.Context));
1447 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1448 // check the attribute arguments.
1449 if (Attr.hasParameterOrArguments()) {
1450 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1455 if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
1456 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
1459 } else if (!isFunctionOrMethod(D)) {
1460 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1461 << Attr.getName() << ExpectedVariableOrFunction;
1465 D->addAttr(::new (S.Context) UsedAttr(Attr.getRange(), S.Context));
1468 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1469 // check the attribute arguments.
1470 if (Attr.getNumArgs() > 1) {
1471 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1475 int priority = 65535; // FIXME: Do not hardcode such constants.
1476 if (Attr.getNumArgs() > 0) {
1477 Expr *E = Attr.getArg(0);
1478 llvm::APSInt Idx(32);
1479 if (E->isTypeDependent() || E->isValueDependent() ||
1480 !E->isIntegerConstantExpr(Idx, S.Context)) {
1481 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1482 << "constructor" << 1 << E->getSourceRange();
1485 priority = Idx.getZExtValue();
1488 if (!isa<FunctionDecl>(D)) {
1489 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1490 << Attr.getName() << ExpectedFunction;
1494 D->addAttr(::new (S.Context) ConstructorAttr(Attr.getRange(), S.Context,
1498 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1499 // check the attribute arguments.
1500 if (Attr.getNumArgs() > 1) {
1501 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1505 int priority = 65535; // FIXME: Do not hardcode such constants.
1506 if (Attr.getNumArgs() > 0) {
1507 Expr *E = Attr.getArg(0);
1508 llvm::APSInt Idx(32);
1509 if (E->isTypeDependent() || E->isValueDependent() ||
1510 !E->isIntegerConstantExpr(Idx, S.Context)) {
1511 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1512 << "destructor" << 1 << E->getSourceRange();
1515 priority = Idx.getZExtValue();
1518 if (!isa<FunctionDecl>(D)) {
1519 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1520 << Attr.getName() << ExpectedFunction;
1524 D->addAttr(::new (S.Context) DestructorAttr(Attr.getRange(), S.Context,
1528 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1529 unsigned NumArgs = Attr.getNumArgs();
1531 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1535 // Handle the case where deprecated attribute has a text message.
1538 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
1540 S.Diag(Attr.getArg(0)->getLocStart(), diag::err_attribute_not_string)
1544 Str = SE->getString();
1547 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str));
1550 static void handleUnavailableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1551 unsigned NumArgs = Attr.getNumArgs();
1553 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1557 // Handle the case where unavailable attribute has a text message.
1560 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
1562 S.Diag(Attr.getArg(0)->getLocStart(),
1563 diag::err_attribute_not_string) << "unavailable";
1566 Str = SE->getString();
1568 D->addAttr(::new (S.Context) UnavailableAttr(Attr.getRange(), S.Context, Str));
1571 static void handleArcWeakrefUnavailableAttr(Sema &S, Decl *D,
1572 const AttributeList &Attr) {
1573 unsigned NumArgs = Attr.getNumArgs();
1575 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
1579 D->addAttr(::new (S.Context) ArcWeakrefUnavailableAttr(
1580 Attr.getRange(), S.Context));
1583 static void handleAvailabilityAttr(Sema &S, Decl *D,
1584 const AttributeList &Attr) {
1585 IdentifierInfo *Platform = Attr.getParameterName();
1586 SourceLocation PlatformLoc = Attr.getParameterLoc();
1588 StringRef PlatformName
1589 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1590 if (PlatformName.empty()) {
1591 S.Diag(PlatformLoc, diag::warn_availability_unknown_platform)
1594 PlatformName = Platform->getName();
1597 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1598 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1599 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1600 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1602 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1603 // of these steps are needed).
1604 if (Introduced.isValid() && Deprecated.isValid() &&
1605 !(Introduced.Version <= Deprecated.Version)) {
1606 S.Diag(Introduced.KeywordLoc, diag::warn_availability_version_ordering)
1607 << 1 << PlatformName << Deprecated.Version.getAsString()
1608 << 0 << Introduced.Version.getAsString();
1612 if (Introduced.isValid() && Obsoleted.isValid() &&
1613 !(Introduced.Version <= Obsoleted.Version)) {
1614 S.Diag(Introduced.KeywordLoc, diag::warn_availability_version_ordering)
1615 << 2 << PlatformName << Obsoleted.Version.getAsString()
1616 << 0 << Introduced.Version.getAsString();
1620 if (Deprecated.isValid() && Obsoleted.isValid() &&
1621 !(Deprecated.Version <= Obsoleted.Version)) {
1622 S.Diag(Deprecated.KeywordLoc, diag::warn_availability_version_ordering)
1623 << 2 << PlatformName << Obsoleted.Version.getAsString()
1624 << 1 << Deprecated.Version.getAsString();
1628 D->addAttr(::new (S.Context) AvailabilityAttr(Attr.getRange(), S.Context,
1636 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1637 // check the attribute arguments.
1638 if(!checkAttributeNumArgs(S, Attr, 1))
1641 Expr *Arg = Attr.getArg(0);
1642 Arg = Arg->IgnoreParenCasts();
1643 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1645 if (!Str || !Str->isAscii()) {
1646 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1647 << "visibility" << 1;
1651 StringRef TypeStr = Str->getString();
1652 VisibilityAttr::VisibilityType type;
1654 if (TypeStr == "default")
1655 type = VisibilityAttr::Default;
1656 else if (TypeStr == "hidden")
1657 type = VisibilityAttr::Hidden;
1658 else if (TypeStr == "internal")
1659 type = VisibilityAttr::Hidden; // FIXME
1660 else if (TypeStr == "protected")
1661 type = VisibilityAttr::Protected;
1663 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
1667 D->addAttr(::new (S.Context) VisibilityAttr(Attr.getRange(), S.Context, type));
1670 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
1671 const AttributeList &Attr) {
1672 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
1674 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1679 if (Attr.getNumArgs() != 0 || !Attr.getParameterName()) {
1680 if (!Attr.getParameterName() && Attr.getNumArgs() == 1) {
1681 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1682 << "objc_method_family" << 1;
1684 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1690 StringRef param = Attr.getParameterName()->getName();
1691 ObjCMethodFamilyAttr::FamilyKind family;
1692 if (param == "none")
1693 family = ObjCMethodFamilyAttr::OMF_None;
1694 else if (param == "alloc")
1695 family = ObjCMethodFamilyAttr::OMF_alloc;
1696 else if (param == "copy")
1697 family = ObjCMethodFamilyAttr::OMF_copy;
1698 else if (param == "init")
1699 family = ObjCMethodFamilyAttr::OMF_init;
1700 else if (param == "mutableCopy")
1701 family = ObjCMethodFamilyAttr::OMF_mutableCopy;
1702 else if (param == "new")
1703 family = ObjCMethodFamilyAttr::OMF_new;
1705 // Just warn and ignore it. This is future-proof against new
1706 // families being used in system headers.
1707 S.Diag(Attr.getParameterLoc(), diag::warn_unknown_method_family);
1711 if (family == ObjCMethodFamilyAttr::OMF_init &&
1712 !method->getResultType()->isObjCObjectPointerType()) {
1713 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
1714 << method->getResultType();
1715 // Ignore the attribute.
1719 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
1720 S.Context, family));
1723 static void handleObjCExceptionAttr(Sema &S, Decl *D,
1724 const AttributeList &Attr) {
1725 if (!checkAttributeNumArgs(S, Attr, 0))
1728 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
1730 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
1734 D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getRange(), S.Context));
1737 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
1738 if (Attr.getNumArgs() != 0) {
1739 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1742 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1743 QualType T = TD->getUnderlyingType();
1744 if (!T->isPointerType() ||
1745 !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
1746 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
1750 D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getRange(), S.Context));
1754 handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1755 if (Attr.getNumArgs() != 0) {
1756 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1760 if (!isa<FunctionDecl>(D)) {
1761 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
1765 D->addAttr(::new (S.Context) OverloadableAttr(Attr.getRange(), S.Context));
1768 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1769 if (!Attr.getParameterName()) {
1770 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1775 if (Attr.getNumArgs() != 0) {
1776 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1780 BlocksAttr::BlockType type;
1781 if (Attr.getParameterName()->isStr("byref"))
1782 type = BlocksAttr::ByRef;
1784 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1785 << "blocks" << Attr.getParameterName();
1789 D->addAttr(::new (S.Context) BlocksAttr(Attr.getRange(), S.Context, type));
1792 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1793 // check the attribute arguments.
1794 if (Attr.getNumArgs() > 2) {
1795 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
1799 unsigned sentinel = 0;
1800 if (Attr.getNumArgs() > 0) {
1801 Expr *E = Attr.getArg(0);
1802 llvm::APSInt Idx(32);
1803 if (E->isTypeDependent() || E->isValueDependent() ||
1804 !E->isIntegerConstantExpr(Idx, S.Context)) {
1805 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1806 << "sentinel" << 1 << E->getSourceRange();
1810 if (Idx.isSigned() && Idx.isNegative()) {
1811 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
1812 << E->getSourceRange();
1816 sentinel = Idx.getZExtValue();
1819 unsigned nullPos = 0;
1820 if (Attr.getNumArgs() > 1) {
1821 Expr *E = Attr.getArg(1);
1822 llvm::APSInt Idx(32);
1823 if (E->isTypeDependent() || E->isValueDependent() ||
1824 !E->isIntegerConstantExpr(Idx, S.Context)) {
1825 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1826 << "sentinel" << 2 << E->getSourceRange();
1829 nullPos = Idx.getZExtValue();
1831 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
1832 // FIXME: This error message could be improved, it would be nice
1833 // to say what the bounds actually are.
1834 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
1835 << E->getSourceRange();
1840 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1841 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
1842 if (isa<FunctionNoProtoType>(FT)) {
1843 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
1847 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1848 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1851 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1852 if (!MD->isVariadic()) {
1853 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1856 } else if (isa<BlockDecl>(D)) {
1857 // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
1860 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
1861 QualType Ty = V->getType();
1862 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
1863 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
1864 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
1865 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1866 int m = Ty->isFunctionPointerType() ? 0 : 1;
1867 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
1871 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1872 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1876 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1877 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1880 D->addAttr(::new (S.Context) SentinelAttr(Attr.getRange(), S.Context, sentinel,
1884 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
1885 // check the attribute arguments.
1886 if (!checkAttributeNumArgs(S, Attr, 0))
1889 if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
1890 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1891 << Attr.getName() << ExpectedFunctionOrMethod;
1895 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
1896 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1897 << Attr.getName() << 0;
1900 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1901 if (MD->getResultType()->isVoidType()) {
1902 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1903 << Attr.getName() << 1;
1907 D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getRange(), S.Context));
1910 static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1911 // check the attribute arguments.
1912 if (Attr.hasParameterOrArguments()) {
1913 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1917 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1918 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1919 << Attr.getName() << ExpectedVariableOrFunction;
1923 NamedDecl *nd = cast<NamedDecl>(D);
1925 // 'weak' only applies to declarations with external linkage.
1926 if (hasEffectivelyInternalLinkage(nd)) {
1927 S.Diag(Attr.getLoc(), diag::err_attribute_weak_static);
1931 nd->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
1934 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1935 // check the attribute arguments.
1936 if (!checkAttributeNumArgs(S, Attr, 0))
1940 // weak_import only applies to variable & function declarations.
1942 if (!D->canBeWeakImported(isDef)) {
1944 S.Diag(Attr.getLoc(),
1945 diag::warn_attribute_weak_import_invalid_on_definition)
1946 << "weak_import" << 2 /*variable and function*/;
1947 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
1948 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
1949 isa<ObjCInterfaceDecl>(D))) {
1950 // Nothing to warn about here.
1952 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1953 << Attr.getName() << ExpectedVariableOrFunction;
1958 D->addAttr(::new (S.Context) WeakImportAttr(Attr.getRange(), S.Context));
1961 static void handleReqdWorkGroupSize(Sema &S, Decl *D,
1962 const AttributeList &Attr) {
1963 // Attribute has 3 arguments.
1964 if (!checkAttributeNumArgs(S, Attr, 3))
1968 for (unsigned i = 0; i < 3; ++i) {
1969 Expr *E = Attr.getArg(i);
1970 llvm::APSInt ArgNum(32);
1971 if (E->isTypeDependent() || E->isValueDependent() ||
1972 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
1973 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1974 << "reqd_work_group_size" << E->getSourceRange();
1977 WGSize[i] = (unsigned) ArgNum.getZExtValue();
1979 D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
1980 WGSize[0], WGSize[1],
1984 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1985 // Attribute has no arguments.
1986 if (!checkAttributeNumArgs(S, Attr, 1))
1989 // Make sure that there is a string literal as the sections's single
1991 Expr *ArgExpr = Attr.getArg(0);
1992 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1994 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
1998 // If the target wants to validate the section specifier, make it happen.
1999 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(SE->getString());
2000 if (!Error.empty()) {
2001 S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
2006 // This attribute cannot be applied to local variables.
2007 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2008 S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
2012 D->addAttr(::new (S.Context) SectionAttr(Attr.getRange(), S.Context,
2017 static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2018 // check the attribute arguments.
2019 if (Attr.hasParameterOrArguments()) {
2020 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2024 if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2025 if (Existing->getLocation().isInvalid())
2026 Existing->setRange(Attr.getRange());
2028 D->addAttr(::new (S.Context) NoThrowAttr(Attr.getRange(), S.Context));
2032 static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2033 // check the attribute arguments.
2034 if (Attr.hasParameterOrArguments()) {
2035 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2039 if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2040 if (Existing->getLocation().isInvalid())
2041 Existing->setRange(Attr.getRange());
2043 D->addAttr(::new (S.Context) ConstAttr(Attr.getRange(), S.Context));
2047 static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2048 // check the attribute arguments.
2049 if (!checkAttributeNumArgs(S, Attr, 0))
2052 D->addAttr(::new (S.Context) PureAttr(Attr.getRange(), S.Context));
2055 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2056 if (!Attr.getParameterName()) {
2057 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2061 if (Attr.getNumArgs() != 0) {
2062 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2066 VarDecl *VD = dyn_cast<VarDecl>(D);
2068 if (!VD || !VD->hasLocalStorage()) {
2069 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
2073 // Look up the function
2074 // FIXME: Lookup probably isn't looking in the right place
2075 NamedDecl *CleanupDecl
2076 = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
2077 Attr.getParameterLoc(), Sema::LookupOrdinaryName);
2079 S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
2080 Attr.getParameterName();
2084 FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
2086 S.Diag(Attr.getParameterLoc(),
2087 diag::err_attribute_cleanup_arg_not_function)
2088 << Attr.getParameterName();
2092 if (FD->getNumParams() != 1) {
2093 S.Diag(Attr.getParameterLoc(),
2094 diag::err_attribute_cleanup_func_must_take_one_arg)
2095 << Attr.getParameterName();
2099 // We're currently more strict than GCC about what function types we accept.
2100 // If this ever proves to be a problem it should be easy to fix.
2101 QualType Ty = S.Context.getPointerType(VD->getType());
2102 QualType ParamTy = FD->getParamDecl(0)->getType();
2103 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2104 ParamTy, Ty) != Sema::Compatible) {
2105 S.Diag(Attr.getParameterLoc(),
2106 diag::err_attribute_cleanup_func_arg_incompatible_type) <<
2107 Attr.getParameterName() << ParamTy << Ty;
2111 D->addAttr(::new (S.Context) CleanupAttr(Attr.getRange(), S.Context, FD));
2112 S.MarkDeclarationReferenced(Attr.getParameterLoc(), FD);
2115 /// Handle __attribute__((format_arg((idx)))) attribute based on
2116 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2117 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2118 if (!checkAttributeNumArgs(S, Attr, 1))
2121 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2122 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2123 << Attr.getName() << ExpectedFunction;
2127 // In C++ the implicit 'this' function parameter also counts, and they are
2128 // counted from one.
2129 bool HasImplicitThisParam = isInstanceMethod(D);
2130 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2131 unsigned FirstIdx = 1;
2133 // checks for the 2nd argument
2134 Expr *IdxExpr = Attr.getArg(0);
2135 llvm::APSInt Idx(32);
2136 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2137 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2138 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2139 << "format" << 2 << IdxExpr->getSourceRange();
2143 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2144 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2145 << "format" << 2 << IdxExpr->getSourceRange();
2149 unsigned ArgIdx = Idx.getZExtValue() - 1;
2151 if (HasImplicitThisParam) {
2153 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
2154 << "format_arg" << IdxExpr->getSourceRange();
2160 // make sure the format string is really a string
2161 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2163 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2164 if (not_nsstring_type &&
2165 !isCFStringType(Ty, S.Context) &&
2166 (!Ty->isPointerType() ||
2167 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2168 // FIXME: Should highlight the actual expression that has the wrong type.
2169 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2170 << (not_nsstring_type ? "a string type" : "an NSString")
2171 << IdxExpr->getSourceRange();
2174 Ty = getFunctionOrMethodResultType(D);
2175 if (!isNSStringType(Ty, S.Context) &&
2176 !isCFStringType(Ty, S.Context) &&
2177 (!Ty->isPointerType() ||
2178 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2179 // FIXME: Should highlight the actual expression that has the wrong type.
2180 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2181 << (not_nsstring_type ? "string type" : "NSString")
2182 << IdxExpr->getSourceRange();
2186 D->addAttr(::new (S.Context) FormatArgAttr(Attr.getRange(), S.Context,
2187 Idx.getZExtValue()));
2190 enum FormatAttrKind {
2199 /// getFormatAttrKind - Map from format attribute names to supported format
2201 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2202 // Check for formats that get handled specially.
2203 if (Format == "NSString")
2204 return NSStringFormat;
2205 if (Format == "CFString")
2206 return CFStringFormat;
2207 if (Format == "strftime")
2208 return StrftimeFormat;
2210 // Otherwise, check for supported formats.
2211 if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
2212 Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
2213 Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
2214 Format == "zcmn_err" ||
2215 Format == "kprintf") // OpenBSD.
2216 return SupportedFormat;
2218 if (Format == "gcc_diag" || Format == "gcc_cdiag" ||
2219 Format == "gcc_cxxdiag" || Format == "gcc_tdiag")
2220 return IgnoredFormat;
2222 return InvalidFormat;
2225 /// Handle __attribute__((init_priority(priority))) attributes based on
2226 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2227 static void handleInitPriorityAttr(Sema &S, Decl *D,
2228 const AttributeList &Attr) {
2229 if (!S.getLangOptions().CPlusPlus) {
2230 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2234 if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
2235 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2239 QualType T = dyn_cast<VarDecl>(D)->getType();
2240 if (S.Context.getAsArrayType(T))
2241 T = S.Context.getBaseElementType(T);
2242 if (!T->getAs<RecordType>()) {
2243 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2248 if (Attr.getNumArgs() != 1) {
2249 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2253 Expr *priorityExpr = Attr.getArg(0);
2255 llvm::APSInt priority(32);
2256 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
2257 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
2258 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2259 << "init_priority" << priorityExpr->getSourceRange();
2263 unsigned prioritynum = priority.getZExtValue();
2264 if (prioritynum < 101 || prioritynum > 65535) {
2265 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2266 << priorityExpr->getSourceRange();
2270 D->addAttr(::new (S.Context) InitPriorityAttr(Attr.getRange(), S.Context,
2274 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2275 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2276 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2278 if (!Attr.getParameterName()) {
2279 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2284 if (Attr.getNumArgs() != 2) {
2285 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
2289 if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
2290 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2291 << Attr.getName() << ExpectedFunction;
2295 // In C++ the implicit 'this' function parameter also counts, and they are
2296 // counted from one.
2297 bool HasImplicitThisParam = isInstanceMethod(D);
2298 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2299 unsigned FirstIdx = 1;
2301 StringRef Format = Attr.getParameterName()->getName();
2303 // Normalize the argument, __foo__ becomes foo.
2304 if (Format.startswith("__") && Format.endswith("__"))
2305 Format = Format.substr(2, Format.size() - 4);
2307 // Check for supported formats.
2308 FormatAttrKind Kind = getFormatAttrKind(Format);
2310 if (Kind == IgnoredFormat)
2313 if (Kind == InvalidFormat) {
2314 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2315 << "format" << Attr.getParameterName()->getName();
2319 // checks for the 2nd argument
2320 Expr *IdxExpr = Attr.getArg(0);
2321 llvm::APSInt Idx(32);
2322 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2323 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2324 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2325 << "format" << 2 << IdxExpr->getSourceRange();
2329 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2330 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2331 << "format" << 2 << IdxExpr->getSourceRange();
2335 // FIXME: Do we need to bounds check?
2336 unsigned ArgIdx = Idx.getZExtValue() - 1;
2338 if (HasImplicitThisParam) {
2340 S.Diag(Attr.getLoc(),
2341 diag::err_format_attribute_implicit_this_format_string)
2342 << IdxExpr->getSourceRange();
2348 // make sure the format string is really a string
2349 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2351 if (Kind == CFStringFormat) {
2352 if (!isCFStringType(Ty, S.Context)) {
2353 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2354 << "a CFString" << IdxExpr->getSourceRange();
2357 } else if (Kind == NSStringFormat) {
2358 // FIXME: do we need to check if the type is NSString*? What are the
2360 if (!isNSStringType(Ty, S.Context)) {
2361 // FIXME: Should highlight the actual expression that has the wrong type.
2362 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2363 << "an NSString" << IdxExpr->getSourceRange();
2366 } else if (!Ty->isPointerType() ||
2367 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2368 // FIXME: Should highlight the actual expression that has the wrong type.
2369 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2370 << "a string type" << IdxExpr->getSourceRange();
2374 // check the 3rd argument
2375 Expr *FirstArgExpr = Attr.getArg(1);
2376 llvm::APSInt FirstArg(32);
2377 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
2378 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
2379 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2380 << "format" << 3 << FirstArgExpr->getSourceRange();
2384 // check if the function is variadic if the 3rd argument non-zero
2385 if (FirstArg != 0) {
2386 if (isFunctionOrMethodVariadic(D)) {
2387 ++NumArgs; // +1 for ...
2389 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2394 // strftime requires FirstArg to be 0 because it doesn't read from any
2395 // variable the input is just the current time + the format string.
2396 if (Kind == StrftimeFormat) {
2397 if (FirstArg != 0) {
2398 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2399 << FirstArgExpr->getSourceRange();
2402 // if 0 it disables parameter checking (to use with e.g. va_list)
2403 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2404 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2405 << "format" << 3 << FirstArgExpr->getSourceRange();
2409 // Check whether we already have an equivalent format attribute.
2410 for (specific_attr_iterator<FormatAttr>
2411 i = D->specific_attr_begin<FormatAttr>(),
2412 e = D->specific_attr_end<FormatAttr>();
2415 if (f->getType() == Format &&
2416 f->getFormatIdx() == (int)Idx.getZExtValue() &&
2417 f->getFirstArg() == (int)FirstArg.getZExtValue()) {
2418 // If we don't have a valid location for this attribute, adopt the
2420 if (f->getLocation().isInvalid())
2421 f->setRange(Attr.getRange());
2426 D->addAttr(::new (S.Context) FormatAttr(Attr.getRange(), S.Context, Format,
2428 FirstArg.getZExtValue()));
2431 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2432 const AttributeList &Attr) {
2433 // check the attribute arguments.
2434 if (!checkAttributeNumArgs(S, Attr, 0))
2438 // Try to find the underlying union declaration.
2440 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2441 if (TD && TD->getUnderlyingType()->isUnionType())
2442 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2444 RD = dyn_cast<RecordDecl>(D);
2446 if (!RD || !RD->isUnion()) {
2447 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2448 << Attr.getName() << ExpectedUnion;
2452 if (!RD->isCompleteDefinition()) {
2453 S.Diag(Attr.getLoc(),
2454 diag::warn_transparent_union_attribute_not_definition);
2458 RecordDecl::field_iterator Field = RD->field_begin(),
2459 FieldEnd = RD->field_end();
2460 if (Field == FieldEnd) {
2461 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2465 FieldDecl *FirstField = *Field;
2466 QualType FirstType = FirstField->getType();
2467 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2468 S.Diag(FirstField->getLocation(),
2469 diag::warn_transparent_union_attribute_floating)
2470 << FirstType->isVectorType() << FirstType;
2474 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2475 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2476 for (; Field != FieldEnd; ++Field) {
2477 QualType FieldType = Field->getType();
2478 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2479 S.Context.getTypeAlign(FieldType) != FirstAlign) {
2480 // Warn if we drop the attribute.
2481 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2482 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2483 : S.Context.getTypeAlign(FieldType);
2484 S.Diag(Field->getLocation(),
2485 diag::warn_transparent_union_attribute_field_size_align)
2486 << isSize << Field->getDeclName() << FieldBits;
2487 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2488 S.Diag(FirstField->getLocation(),
2489 diag::note_transparent_union_first_field_size_align)
2490 << isSize << FirstBits;
2495 RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getRange(), S.Context));
2498 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2499 // check the attribute arguments.
2500 if (!checkAttributeNumArgs(S, Attr, 1))
2503 Expr *ArgExpr = Attr.getArg(0);
2504 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
2506 // Make sure that there is a string literal as the annotation's single
2509 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
2513 // Don't duplicate annotations that are already set.
2514 for (specific_attr_iterator<AnnotateAttr>
2515 i = D->specific_attr_begin<AnnotateAttr>(),
2516 e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
2517 if ((*i)->getAnnotation() == SE->getString())
2520 D->addAttr(::new (S.Context) AnnotateAttr(Attr.getRange(), S.Context,
2524 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2525 // check the attribute arguments.
2526 if (Attr.getNumArgs() > 1) {
2527 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2531 //FIXME: The C++0x version of this attribute has more limited applicabilty
2532 // than GNU's, and should error out when it is used to specify a
2533 // weaker alignment, rather than being silently ignored.
2535 if (Attr.getNumArgs() == 0) {
2536 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, true, 0));
2540 S.AddAlignedAttr(Attr.getRange(), D, Attr.getArg(0));
2543 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E) {
2544 if (E->isTypeDependent() || E->isValueDependent()) {
2545 // Save dependent expressions in the AST to be instantiated.
2546 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E));
2550 SourceLocation AttrLoc = AttrRange.getBegin();
2551 // FIXME: Cache the number on the Attr object?
2552 llvm::APSInt Alignment(32);
2553 if (!E->isIntegerConstantExpr(Alignment, Context)) {
2554 Diag(AttrLoc, diag::err_attribute_argument_not_int)
2555 << "aligned" << E->getSourceRange();
2558 if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2559 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
2560 << E->getSourceRange();
2564 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E));
2567 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS) {
2568 // FIXME: Cache the number on the Attr object if non-dependent?
2569 // FIXME: Perform checking of type validity
2570 D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, false, TS));
2574 /// handleModeAttr - This attribute modifies the width of a decl with primitive
2577 /// Despite what would be logical, the mode attribute is a decl attribute, not a
2578 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
2579 /// HImode, not an intermediate pointer.
2580 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2581 // This attribute isn't documented, but glibc uses it. It changes
2582 // the width of an int or unsigned int to the specified size.
2584 // Check that there aren't any arguments
2585 if (!checkAttributeNumArgs(S, Attr, 0))
2589 IdentifierInfo *Name = Attr.getParameterName();
2591 S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
2595 StringRef Str = Attr.getParameterName()->getName();
2597 // Normalize the attribute name, __foo__ becomes foo.
2598 if (Str.startswith("__") && Str.endswith("__"))
2599 Str = Str.substr(2, Str.size() - 4);
2601 unsigned DestWidth = 0;
2602 bool IntegerMode = true;
2603 bool ComplexMode = false;
2604 switch (Str.size()) {
2607 case 'Q': DestWidth = 8; break;
2608 case 'H': DestWidth = 16; break;
2609 case 'S': DestWidth = 32; break;
2610 case 'D': DestWidth = 64; break;
2611 case 'X': DestWidth = 96; break;
2612 case 'T': DestWidth = 128; break;
2614 if (Str[1] == 'F') {
2615 IntegerMode = false;
2616 } else if (Str[1] == 'C') {
2617 IntegerMode = false;
2619 } else if (Str[1] != 'I') {
2624 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
2625 // pointer on PIC16 and other embedded platforms.
2627 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2628 else if (Str == "byte")
2629 DestWidth = S.Context.getTargetInfo().getCharWidth();
2632 if (Str == "pointer")
2633 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2638 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2639 OldTy = TD->getUnderlyingType();
2640 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2641 OldTy = VD->getType();
2643 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
2644 << "mode" << Attr.getRange();
2648 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
2649 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
2650 else if (IntegerMode) {
2651 if (!OldTy->isIntegralOrEnumerationType())
2652 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2653 } else if (ComplexMode) {
2654 if (!OldTy->isComplexType())
2655 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2657 if (!OldTy->isFloatingType())
2658 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2661 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
2662 // and friends, at least with glibc.
2663 // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
2664 // width on unusual platforms.
2665 // FIXME: Make sure floating-point mappings are accurate
2666 // FIXME: Support XF and TF types
2668 switch (DestWidth) {
2670 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
2673 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2677 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2680 if (OldTy->isSignedIntegerType())
2681 NewTy = S.Context.SignedCharTy;
2683 NewTy = S.Context.UnsignedCharTy;
2687 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2690 if (OldTy->isSignedIntegerType())
2691 NewTy = S.Context.ShortTy;
2693 NewTy = S.Context.UnsignedShortTy;
2697 NewTy = S.Context.FloatTy;
2698 else if (OldTy->isSignedIntegerType())
2699 NewTy = S.Context.IntTy;
2701 NewTy = S.Context.UnsignedIntTy;
2705 NewTy = S.Context.DoubleTy;
2706 else if (OldTy->isSignedIntegerType())
2707 if (S.Context.getTargetInfo().getLongWidth() == 64)
2708 NewTy = S.Context.LongTy;
2710 NewTy = S.Context.LongLongTy;
2712 if (S.Context.getTargetInfo().getLongWidth() == 64)
2713 NewTy = S.Context.UnsignedLongTy;
2715 NewTy = S.Context.UnsignedLongLongTy;
2718 NewTy = S.Context.LongDoubleTy;
2722 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2725 if (OldTy->isSignedIntegerType())
2726 NewTy = S.Context.Int128Ty;
2728 NewTy = S.Context.UnsignedInt128Ty;
2733 NewTy = S.Context.getComplexType(NewTy);
2736 // Install the new type.
2737 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2738 // FIXME: preserve existing source info.
2739 TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
2741 cast<ValueDecl>(D)->setType(NewTy);
2744 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2745 // check the attribute arguments.
2746 if (!checkAttributeNumArgs(S, Attr, 0))
2749 if (!isFunctionOrMethod(D)) {
2750 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2751 << Attr.getName() << ExpectedFunction;
2755 D->addAttr(::new (S.Context) NoDebugAttr(Attr.getRange(), S.Context));
2758 static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2759 // check the attribute arguments.
2760 if (!checkAttributeNumArgs(S, Attr, 0))
2764 if (!isa<FunctionDecl>(D)) {
2765 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2766 << Attr.getName() << ExpectedFunction;
2770 D->addAttr(::new (S.Context) NoInlineAttr(Attr.getRange(), S.Context));
2773 static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
2774 const AttributeList &Attr) {
2775 // check the attribute arguments.
2776 if (!checkAttributeNumArgs(S, Attr, 0))
2780 if (!isa<FunctionDecl>(D)) {
2781 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2782 << Attr.getName() << ExpectedFunction;
2786 D->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getRange(),
2790 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2791 if (S.LangOpts.CUDA) {
2792 // check the attribute arguments.
2793 if (Attr.hasParameterOrArguments()) {
2794 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2798 if (!isa<VarDecl>(D)) {
2799 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2800 << Attr.getName() << ExpectedVariable;
2804 D->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getRange(), S.Context));
2806 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
2810 static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2811 if (S.LangOpts.CUDA) {
2812 // check the attribute arguments.
2813 if (Attr.getNumArgs() != 0) {
2814 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2818 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
2819 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2820 << Attr.getName() << ExpectedVariableOrFunction;
2824 D->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getRange(), S.Context));
2826 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
2830 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2831 if (S.LangOpts.CUDA) {
2832 // check the attribute arguments.
2833 if (!checkAttributeNumArgs(S, Attr, 0))
2836 if (!isa<FunctionDecl>(D)) {
2837 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2838 << Attr.getName() << ExpectedFunction;
2842 FunctionDecl *FD = cast<FunctionDecl>(D);
2843 if (!FD->getResultType()->isVoidType()) {
2844 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
2845 if (FunctionTypeLoc* FTL = dyn_cast<FunctionTypeLoc>(&TL)) {
2846 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
2848 << FixItHint::CreateReplacement(FTL->getResultLoc().getSourceRange(),
2851 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
2857 D->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getRange(), S.Context));
2859 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
2863 static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2864 if (S.LangOpts.CUDA) {
2865 // check the attribute arguments.
2866 if (!checkAttributeNumArgs(S, Attr, 0))
2870 if (!isa<FunctionDecl>(D)) {
2871 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2872 << Attr.getName() << ExpectedFunction;
2876 D->addAttr(::new (S.Context) CUDAHostAttr(Attr.getRange(), S.Context));
2878 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
2882 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2883 if (S.LangOpts.CUDA) {
2884 // check the attribute arguments.
2885 if (!checkAttributeNumArgs(S, Attr, 0))
2889 if (!isa<VarDecl>(D)) {
2890 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2891 << Attr.getName() << ExpectedVariable;
2895 D->addAttr(::new (S.Context) CUDASharedAttr(Attr.getRange(), S.Context));
2897 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
2901 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2902 // check the attribute arguments.
2903 if (!checkAttributeNumArgs(S, Attr, 0))
2906 FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
2908 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2909 << Attr.getName() << ExpectedFunction;
2913 if (!Fn->isInlineSpecified()) {
2914 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
2918 D->addAttr(::new (S.Context) GNUInlineAttr(Attr.getRange(), S.Context));
2921 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2922 if (hasDeclarator(D)) return;
2924 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
2925 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
2927 if (S.CheckCallingConvAttr(Attr, CC))
2930 if (!isa<ObjCMethodDecl>(D)) {
2931 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2932 << Attr.getName() << ExpectedFunctionOrMethod;
2936 switch (Attr.getKind()) {
2937 case AttributeList::AT_fastcall:
2938 D->addAttr(::new (S.Context) FastCallAttr(Attr.getRange(), S.Context));
2940 case AttributeList::AT_stdcall:
2941 D->addAttr(::new (S.Context) StdCallAttr(Attr.getRange(), S.Context));
2943 case AttributeList::AT_thiscall:
2944 D->addAttr(::new (S.Context) ThisCallAttr(Attr.getRange(), S.Context));
2946 case AttributeList::AT_cdecl:
2947 D->addAttr(::new (S.Context) CDeclAttr(Attr.getRange(), S.Context));
2949 case AttributeList::AT_pascal:
2950 D->addAttr(::new (S.Context) PascalAttr(Attr.getRange(), S.Context));
2952 case AttributeList::AT_pcs: {
2953 Expr *Arg = Attr.getArg(0);
2954 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2955 if (!Str || !Str->isAscii()) {
2956 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2962 StringRef StrRef = Str->getString();
2963 PcsAttr::PCSType PCS;
2964 if (StrRef == "aapcs")
2965 PCS = PcsAttr::AAPCS;
2966 else if (StrRef == "aapcs-vfp")
2967 PCS = PcsAttr::AAPCS_VFP;
2969 S.Diag(Attr.getLoc(), diag::err_invalid_pcs);
2974 D->addAttr(::new (S.Context) PcsAttr(Attr.getRange(), S.Context, PCS));
2977 llvm_unreachable("unexpected attribute kind");
2982 static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
2983 assert(!Attr.isInvalid());
2984 D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
2987 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC) {
2988 if (attr.isInvalid())
2991 if ((attr.getNumArgs() != 0 &&
2992 !(attr.getKind() == AttributeList::AT_pcs && attr.getNumArgs() == 1)) ||
2993 attr.getParameterName()) {
2994 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2999 // TODO: diagnose uses of these conventions on the wrong target. Or, better
3000 // move to TargetAttributesSema one day.
3001 switch (attr.getKind()) {
3002 case AttributeList::AT_cdecl: CC = CC_C; break;
3003 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
3004 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
3005 case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break;
3006 case AttributeList::AT_pascal: CC = CC_X86Pascal; break;
3007 case AttributeList::AT_pcs: {
3008 Expr *Arg = attr.getArg(0);
3009 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3010 if (!Str || !Str->isAscii()) {
3011 Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3017 StringRef StrRef = Str->getString();
3018 if (StrRef == "aapcs") {
3021 } else if (StrRef == "aapcs-vfp") {
3027 default: llvm_unreachable("unexpected attribute kind"); return true;
3033 static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3034 if (hasDeclarator(D)) return;
3037 if (S.CheckRegparmAttr(Attr, numParams))
3040 if (!isa<ObjCMethodDecl>(D)) {
3041 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3042 << Attr.getName() << ExpectedFunctionOrMethod;
3046 D->addAttr(::new (S.Context) RegparmAttr(Attr.getRange(), S.Context, numParams));
3049 /// Checks a regparm attribute, returning true if it is ill-formed and
3050 /// otherwise setting numParams to the appropriate value.
3051 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3052 if (Attr.isInvalid())
3055 if (Attr.getNumArgs() != 1) {
3056 Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3061 Expr *NumParamsExpr = Attr.getArg(0);
3062 llvm::APSInt NumParams(32);
3063 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
3064 !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
3065 Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3066 << "regparm" << NumParamsExpr->getSourceRange();
3071 if (Context.getTargetInfo().getRegParmMax() == 0) {
3072 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3073 << NumParamsExpr->getSourceRange();
3078 numParams = NumParams.getZExtValue();
3079 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3080 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3081 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3089 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
3090 if (S.LangOpts.CUDA) {
3091 // check the attribute arguments.
3092 if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
3093 // FIXME: 0 is not okay.
3094 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
3098 if (!isFunctionOrMethod(D)) {
3099 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3100 << Attr.getName() << ExpectedFunctionOrMethod;
3104 Expr *MaxThreadsExpr = Attr.getArg(0);
3105 llvm::APSInt MaxThreads(32);
3106 if (MaxThreadsExpr->isTypeDependent() ||
3107 MaxThreadsExpr->isValueDependent() ||
3108 !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
3109 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3110 << "launch_bounds" << 1 << MaxThreadsExpr->getSourceRange();
3114 llvm::APSInt MinBlocks(32);
3115 if (Attr.getNumArgs() > 1) {
3116 Expr *MinBlocksExpr = Attr.getArg(1);
3117 if (MinBlocksExpr->isTypeDependent() ||
3118 MinBlocksExpr->isValueDependent() ||
3119 !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
3120 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3121 << "launch_bounds" << 2 << MinBlocksExpr->getSourceRange();
3126 D->addAttr(::new (S.Context) CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3127 MaxThreads.getZExtValue(),
3128 MinBlocks.getZExtValue()));
3130 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
3134 //===----------------------------------------------------------------------===//
3135 // Checker-specific attribute handlers.
3136 //===----------------------------------------------------------------------===//
3138 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3139 return type->isDependentType() ||
3140 type->isObjCObjectPointerType() ||
3141 S.Context.isObjCNSObjectType(type);
3143 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3144 return type->isDependentType() ||
3145 type->isPointerType() ||
3146 isValidSubjectOfNSAttribute(S, type);
3149 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3150 ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
3152 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3153 << Attr.getRange() << Attr.getName() << ExpectedParameter;
3158 if (Attr.getKind() == AttributeList::AT_ns_consumed) {
3159 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3162 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3167 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3168 << Attr.getRange() << Attr.getName() << cf;
3173 param->addAttr(::new (S.Context) CFConsumedAttr(Attr.getRange(), S.Context));
3175 param->addAttr(::new (S.Context) NSConsumedAttr(Attr.getRange(), S.Context));
3178 static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
3179 const AttributeList &Attr) {
3180 if (!isa<ObjCMethodDecl>(D)) {
3181 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3182 << Attr.getRange() << Attr.getName() << ExpectedMethod;
3186 D->addAttr(::new (S.Context) NSConsumesSelfAttr(Attr.getRange(), S.Context));
3189 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3190 const AttributeList &Attr) {
3192 QualType returnType;
3194 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3195 returnType = MD->getResultType();
3196 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3197 returnType = PD->getType();
3198 else if (S.getLangOptions().ObjCAutoRefCount && hasDeclarator(D) &&
3199 (Attr.getKind() == AttributeList::AT_ns_returns_retained))
3200 return; // ignore: was handled as a type attribute
3201 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3202 returnType = FD->getResultType();
3204 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3205 << Attr.getRange() << Attr.getName()
3206 << ExpectedFunctionOrMethod;
3212 switch (Attr.getKind()) {
3213 default: llvm_unreachable("invalid ownership attribute"); return;
3214 case AttributeList::AT_ns_returns_autoreleased:
3215 case AttributeList::AT_ns_returns_retained:
3216 case AttributeList::AT_ns_returns_not_retained:
3217 typeOK = isValidSubjectOfNSAttribute(S, returnType);
3221 case AttributeList::AT_cf_returns_retained:
3222 case AttributeList::AT_cf_returns_not_retained:
3223 typeOK = isValidSubjectOfCFAttribute(S, returnType);
3229 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3230 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3234 switch (Attr.getKind()) {
3236 llvm_unreachable("invalid ownership attribute");
3237 case AttributeList::AT_ns_returns_autoreleased:
3238 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(Attr.getRange(),
3241 case AttributeList::AT_cf_returns_not_retained:
3242 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getRange(),
3245 case AttributeList::AT_ns_returns_not_retained:
3246 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getRange(),
3249 case AttributeList::AT_cf_returns_retained:
3250 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getRange(),
3253 case AttributeList::AT_ns_returns_retained:
3254 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getRange(),
3260 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3261 const AttributeList &attr) {
3262 SourceLocation loc = attr.getLoc();
3264 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
3266 if (!isa<ObjCMethodDecl>(method)) {
3267 S.Diag(method->getLocStart(), diag::err_attribute_wrong_decl_type)
3268 << SourceRange(loc, loc) << attr.getName() << 13 /* methods */;
3272 // Check that the method returns a normal pointer.
3273 QualType resultType = method->getResultType();
3275 if (!resultType->isReferenceType() &&
3276 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3277 S.Diag(method->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3279 << attr.getName() << /*method*/ 1 << /*non-retainable pointer*/ 2;
3281 // Drop the attribute.
3286 ::new (S.Context) ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context));
3289 /// Handle cf_audited_transfer and cf_unknown_transfer.
3290 static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
3291 if (!isa<FunctionDecl>(D)) {
3292 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3293 << A.getRange() << A.getName() << 0 /*function*/;
3297 bool IsAudited = (A.getKind() == AttributeList::AT_cf_audited_transfer);
3299 // Check whether there's a conflicting attribute already present.
3302 Existing = D->getAttr<CFUnknownTransferAttr>();
3304 Existing = D->getAttr<CFAuditedTransferAttr>();
3307 S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
3309 << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
3310 << A.getRange() << Existing->getRange();
3314 // All clear; add the attribute.
3317 ::new (S.Context) CFAuditedTransferAttr(A.getRange(), S.Context));
3320 ::new (S.Context) CFUnknownTransferAttr(A.getRange(), S.Context));
3324 static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
3325 const AttributeList &Attr) {
3326 RecordDecl *RD = dyn_cast<RecordDecl>(D);
3327 if (!RD || RD->isUnion()) {
3328 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3329 << Attr.getRange() << Attr.getName() << 14 /*struct */;
3332 IdentifierInfo *ParmName = Attr.getParameterName();
3334 // In Objective-C, verify that the type names an Objective-C type.
3335 // We don't want to check this outside of ObjC because people sometimes
3336 // do crazy C declarations of Objective-C types.
3337 if (ParmName && S.getLangOptions().ObjC1) {
3338 // Check for an existing type with this name.
3339 LookupResult R(S, DeclarationName(ParmName), Attr.getParameterLoc(),
3340 Sema::LookupOrdinaryName);
3341 if (S.LookupName(R, Sc)) {
3342 NamedDecl *Target = R.getFoundDecl();
3343 if (Target && !isa<ObjCInterfaceDecl>(Target)) {
3344 S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
3345 S.Diag(Target->getLocStart(), diag::note_declared_at);
3350 D->addAttr(::new (S.Context) NSBridgedAttr(Attr.getRange(), S.Context,
3354 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3355 const AttributeList &Attr) {
3356 if (hasDeclarator(D)) return;
3358 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3359 << Attr.getRange() << Attr.getName() << 12 /* variable */;
3362 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3363 const AttributeList &Attr) {
3364 if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
3365 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3366 << Attr.getRange() << Attr.getName() << 12 /* variable */;
3370 ValueDecl *vd = cast<ValueDecl>(D);
3371 QualType type = vd->getType();
3373 if (!type->isDependentType() &&
3374 !type->isObjCLifetimeType()) {
3375 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3380 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3382 // If we have no lifetime yet, check the lifetime we're presumably
3384 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3385 lifetime = type->getObjCARCImplicitLifetime();
3388 case Qualifiers::OCL_None:
3389 assert(type->isDependentType() &&
3390 "didn't infer lifetime for non-dependent type?");
3393 case Qualifiers::OCL_Weak: // meaningful
3394 case Qualifiers::OCL_Strong: // meaningful
3397 case Qualifiers::OCL_ExplicitNone:
3398 case Qualifiers::OCL_Autoreleasing:
3399 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3400 << (lifetime == Qualifiers::OCL_Autoreleasing);
3404 D->addAttr(::new (S.Context)
3405 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context));
3408 static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
3409 return Attr.getKind() == AttributeList::AT_dllimport ||
3410 Attr.getKind() == AttributeList::AT_dllexport ||
3411 Attr.getKind() == AttributeList::AT_uuid;
3414 //===----------------------------------------------------------------------===//
3415 // Microsoft specific attribute handlers.
3416 //===----------------------------------------------------------------------===//
3418 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3419 if (S.LangOpts.MicrosoftExt || S.LangOpts.Borland) {
3420 // check the attribute arguments.
3421 if (!checkAttributeNumArgs(S, Attr, 1))
3424 Expr *Arg = Attr.getArg(0);
3425 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3426 if (!Str || !Str->isAscii()) {
3427 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
3432 StringRef StrRef = Str->getString();
3434 bool IsCurly = StrRef.size() > 1 && StrRef.front() == '{' &&
3435 StrRef.back() == '}';
3437 // Validate GUID length.
3438 if (IsCurly && StrRef.size() != 38) {
3439 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
3442 if (!IsCurly && StrRef.size() != 36) {
3443 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
3447 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
3448 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
3449 StringRef::iterator I = StrRef.begin();
3450 if (IsCurly) // Skip the optional '{'
3453 for (int i = 0; i < 36; ++i) {
3454 if (i == 8 || i == 13 || i == 18 || i == 23) {
3456 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
3459 } else if (!isxdigit(*I)) {
3460 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
3466 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context,
3469 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "uuid";
3472 //===----------------------------------------------------------------------===//
3473 // Top Level Sema Entry Points
3474 //===----------------------------------------------------------------------===//
3476 static void ProcessNonInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
3477 const AttributeList &Attr) {
3478 switch (Attr.getKind()) {
3479 case AttributeList::AT_device: handleDeviceAttr (S, D, Attr); break;
3480 case AttributeList::AT_host: handleHostAttr (S, D, Attr); break;
3481 case AttributeList::AT_overloadable:handleOverloadableAttr(S, D, Attr); break;
3487 static void ProcessInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
3488 const AttributeList &Attr) {
3489 switch (Attr.getKind()) {
3490 case AttributeList::AT_IBAction: handleIBAction(S, D, Attr); break;
3491 case AttributeList::AT_IBOutlet: handleIBOutlet(S, D, Attr); break;
3492 case AttributeList::AT_IBOutletCollection:
3493 handleIBOutletCollection(S, D, Attr); break;
3494 case AttributeList::AT_address_space:
3495 case AttributeList::AT_opencl_image_access:
3496 case AttributeList::AT_objc_gc:
3497 case AttributeList::AT_vector_size:
3498 case AttributeList::AT_neon_vector_type:
3499 case AttributeList::AT_neon_polyvector_type:
3500 // Ignore these, these are type attributes, handled by
3501 // ProcessTypeAttributes.
3503 case AttributeList::AT_device:
3504 case AttributeList::AT_host:
3505 case AttributeList::AT_overloadable:
3506 // Ignore, this is a non-inheritable attribute, handled
3507 // by ProcessNonInheritableDeclAttr.
3509 case AttributeList::AT_alias: handleAliasAttr (S, D, Attr); break;
3510 case AttributeList::AT_aligned: handleAlignedAttr (S, D, Attr); break;
3511 case AttributeList::AT_always_inline:
3512 handleAlwaysInlineAttr (S, D, Attr); break;
3513 case AttributeList::AT_analyzer_noreturn:
3514 handleAnalyzerNoReturnAttr (S, D, Attr); break;
3515 case AttributeList::AT_annotate: handleAnnotateAttr (S, D, Attr); break;
3516 case AttributeList::AT_availability:handleAvailabilityAttr(S, D, Attr); break;
3517 case AttributeList::AT_carries_dependency:
3518 handleDependencyAttr (S, D, Attr); break;
3519 case AttributeList::AT_common: handleCommonAttr (S, D, Attr); break;
3520 case AttributeList::AT_constant: handleConstantAttr (S, D, Attr); break;
3521 case AttributeList::AT_constructor: handleConstructorAttr (S, D, Attr); break;
3522 case AttributeList::AT_deprecated: handleDeprecatedAttr (S, D, Attr); break;
3523 case AttributeList::AT_destructor: handleDestructorAttr (S, D, Attr); break;
3524 case AttributeList::AT_ext_vector_type:
3525 handleExtVectorTypeAttr(S, scope, D, Attr);
3527 case AttributeList::AT_format: handleFormatAttr (S, D, Attr); break;
3528 case AttributeList::AT_format_arg: handleFormatArgAttr (S, D, Attr); break;
3529 case AttributeList::AT_global: handleGlobalAttr (S, D, Attr); break;
3530 case AttributeList::AT_gnu_inline: handleGNUInlineAttr (S, D, Attr); break;
3531 case AttributeList::AT_launch_bounds:
3532 handleLaunchBoundsAttr(S, D, Attr);
3534 case AttributeList::AT_mode: handleModeAttr (S, D, Attr); break;
3535 case AttributeList::AT_malloc: handleMallocAttr (S, D, Attr); break;
3536 case AttributeList::AT_may_alias: handleMayAliasAttr (S, D, Attr); break;
3537 case AttributeList::AT_nocommon: handleNoCommonAttr (S, D, Attr); break;
3538 case AttributeList::AT_nonnull: handleNonNullAttr (S, D, Attr); break;
3539 case AttributeList::AT_ownership_returns:
3540 case AttributeList::AT_ownership_takes:
3541 case AttributeList::AT_ownership_holds:
3542 handleOwnershipAttr (S, D, Attr); break;
3543 case AttributeList::AT_naked: handleNakedAttr (S, D, Attr); break;
3544 case AttributeList::AT_noreturn: handleNoReturnAttr (S, D, Attr); break;
3545 case AttributeList::AT_nothrow: handleNothrowAttr (S, D, Attr); break;
3546 case AttributeList::AT_shared: handleSharedAttr (S, D, Attr); break;
3547 case AttributeList::AT_vecreturn: handleVecReturnAttr (S, D, Attr); break;
3549 case AttributeList::AT_objc_ownership:
3550 handleObjCOwnershipAttr(S, D, Attr); break;
3551 case AttributeList::AT_objc_precise_lifetime:
3552 handleObjCPreciseLifetimeAttr(S, D, Attr); break;
3554 case AttributeList::AT_objc_returns_inner_pointer:
3555 handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
3557 case AttributeList::AT_ns_bridged:
3558 handleNSBridgedAttr(S, scope, D, Attr); break;
3560 case AttributeList::AT_cf_audited_transfer:
3561 case AttributeList::AT_cf_unknown_transfer:
3562 handleCFTransferAttr(S, D, Attr); break;
3564 // Checker-specific.
3565 case AttributeList::AT_cf_consumed:
3566 case AttributeList::AT_ns_consumed: handleNSConsumedAttr (S, D, Attr); break;
3567 case AttributeList::AT_ns_consumes_self:
3568 handleNSConsumesSelfAttr(S, D, Attr); break;
3570 case AttributeList::AT_ns_returns_autoreleased:
3571 case AttributeList::AT_ns_returns_not_retained:
3572 case AttributeList::AT_cf_returns_not_retained:
3573 case AttributeList::AT_ns_returns_retained:
3574 case AttributeList::AT_cf_returns_retained:
3575 handleNSReturnsRetainedAttr(S, D, Attr); break;
3577 case AttributeList::AT_reqd_wg_size:
3578 handleReqdWorkGroupSize(S, D, Attr); break;
3580 case AttributeList::AT_init_priority:
3581 handleInitPriorityAttr(S, D, Attr); break;
3583 case AttributeList::AT_packed: handlePackedAttr (S, D, Attr); break;
3584 case AttributeList::AT_MsStruct: handleMsStructAttr (S, D, Attr); break;
3585 case AttributeList::AT_section: handleSectionAttr (S, D, Attr); break;
3586 case AttributeList::AT_unavailable: handleUnavailableAttr (S, D, Attr); break;
3587 case AttributeList::AT_arc_weakref_unavailable:
3588 handleArcWeakrefUnavailableAttr (S, D, Attr);
3590 case AttributeList::AT_unused: handleUnusedAttr (S, D, Attr); break;
3591 case AttributeList::AT_returns_twice:
3592 handleReturnsTwiceAttr(S, D, Attr);
3594 case AttributeList::AT_used: handleUsedAttr (S, D, Attr); break;
3595 case AttributeList::AT_visibility: handleVisibilityAttr (S, D, Attr); break;
3596 case AttributeList::AT_warn_unused_result: handleWarnUnusedResult(S, D, Attr);
3598 case AttributeList::AT_weak: handleWeakAttr (S, D, Attr); break;
3599 case AttributeList::AT_weakref: handleWeakRefAttr (S, D, Attr); break;
3600 case AttributeList::AT_weak_import: handleWeakImportAttr (S, D, Attr); break;
3601 case AttributeList::AT_transparent_union:
3602 handleTransparentUnionAttr(S, D, Attr);
3604 case AttributeList::AT_objc_exception:
3605 handleObjCExceptionAttr(S, D, Attr);
3607 case AttributeList::AT_objc_method_family:
3608 handleObjCMethodFamilyAttr(S, D, Attr);
3610 case AttributeList::AT_nsobject: handleObjCNSObject (S, D, Attr); break;
3611 case AttributeList::AT_blocks: handleBlocksAttr (S, D, Attr); break;
3612 case AttributeList::AT_sentinel: handleSentinelAttr (S, D, Attr); break;
3613 case AttributeList::AT_const: handleConstAttr (S, D, Attr); break;
3614 case AttributeList::AT_pure: handlePureAttr (S, D, Attr); break;
3615 case AttributeList::AT_cleanup: handleCleanupAttr (S, D, Attr); break;
3616 case AttributeList::AT_nodebug: handleNoDebugAttr (S, D, Attr); break;
3617 case AttributeList::AT_noinline: handleNoInlineAttr (S, D, Attr); break;
3618 case AttributeList::AT_regparm: handleRegparmAttr (S, D, Attr); break;
3619 case AttributeList::IgnoredAttribute:
3622 case AttributeList::AT_no_instrument_function: // Interacts with -pg.
3623 handleNoInstrumentFunctionAttr(S, D, Attr);
3625 case AttributeList::AT_stdcall:
3626 case AttributeList::AT_cdecl:
3627 case AttributeList::AT_fastcall:
3628 case AttributeList::AT_thiscall:
3629 case AttributeList::AT_pascal:
3630 case AttributeList::AT_pcs:
3631 handleCallConvAttr(S, D, Attr);
3633 case AttributeList::AT_opencl_kernel_function:
3634 handleOpenCLKernelAttr(S, D, Attr);
3636 case AttributeList::AT_uuid:
3637 handleUuidAttr(S, D, Attr);
3640 // Thread safety attributes:
3641 case AttributeList::AT_guarded_var:
3642 handleGuardedVarAttr(S, D, Attr);
3644 case AttributeList::AT_pt_guarded_var:
3645 handleGuardedVarAttr(S, D, Attr, /*pointer = */true);
3647 case AttributeList::AT_scoped_lockable:
3648 handleLockableAttr(S, D, Attr, /*scoped = */true);
3650 case AttributeList::AT_no_thread_safety_analysis:
3651 handleNoThreadSafetyAttr(S, D, Attr);
3653 case AttributeList::AT_lockable:
3654 handleLockableAttr(S, D, Attr);
3656 case AttributeList::AT_guarded_by:
3657 handleGuardedByAttr(S, D, Attr);
3659 case AttributeList::AT_pt_guarded_by:
3660 handleGuardedByAttr(S, D, Attr, /*pointer = */true);
3662 case AttributeList::AT_exclusive_lock_function:
3663 handleLockFunAttr(S, D, Attr, /*exclusive = */true);
3665 case AttributeList::AT_exclusive_locks_required:
3666 handleLocksRequiredAttr(S, D, Attr, /*exclusive = */true);
3668 case AttributeList::AT_exclusive_trylock_function:
3669 handleTrylockFunAttr(S, D, Attr, /*exclusive = */true);
3671 case AttributeList::AT_lock_returned:
3672 handleLockReturnedAttr(S, D, Attr);
3674 case AttributeList::AT_locks_excluded:
3675 handleLocksExcludedAttr(S, D, Attr);
3677 case AttributeList::AT_shared_lock_function:
3678 handleLockFunAttr(S, D, Attr);
3680 case AttributeList::AT_shared_locks_required:
3681 handleLocksRequiredAttr(S, D, Attr);
3683 case AttributeList::AT_shared_trylock_function:
3684 handleTrylockFunAttr(S, D, Attr);
3686 case AttributeList::AT_unlock_function:
3687 handleUnlockFunAttr(S, D, Attr);
3689 case AttributeList::AT_acquired_before:
3690 handleAcquireOrderAttr(S, D, Attr, /*before = */true);
3692 case AttributeList::AT_acquired_after:
3693 handleAcquireOrderAttr(S, D, Attr, /*before = */false);
3697 // Ask target about the attribute.
3698 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
3699 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
3700 S.Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored)
3706 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
3707 /// the attribute applies to decls. If the attribute is a type attribute, just
3708 /// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
3709 /// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
3710 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
3711 const AttributeList &Attr,
3712 bool NonInheritable, bool Inheritable) {
3713 if (Attr.isInvalid())
3716 if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
3717 // FIXME: Try to deal with other __declspec attributes!
3721 ProcessNonInheritableDeclAttr(S, scope, D, Attr);
3724 ProcessInheritableDeclAttr(S, scope, D, Attr);
3727 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
3728 /// attribute list to the specified decl, ignoring any type attributes.
3729 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
3730 const AttributeList *AttrList,
3731 bool NonInheritable, bool Inheritable) {
3732 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
3733 ProcessDeclAttribute(*this, S, D, *l, NonInheritable, Inheritable);
3737 // static int a9 __attribute__((weakref));
3738 // but that looks really pointless. We reject it.
3739 if (Inheritable && D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
3740 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
3741 dyn_cast<NamedDecl>(D)->getNameAsString();
3746 // Annotation attributes are the only attributes allowed after an access
3748 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3749 const AttributeList *AttrList) {
3750 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
3751 if (l->getKind() == AttributeList::AT_annotate) {
3752 handleAnnotateAttr(*this, ASDecl, *l);
3754 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
3762 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
3763 /// contains any decl attributes that we should warn about.
3764 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
3765 for ( ; A; A = A->getNext()) {
3766 // Only warn if the attribute is an unignored, non-type attribute.
3767 if (A->isUsedAsTypeAttr()) continue;
3768 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
3770 if (A->getKind() == AttributeList::UnknownAttribute) {
3771 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
3772 << A->getName() << A->getRange();
3774 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
3775 << A->getName() << A->getRange();
3780 /// checkUnusedDeclAttributes - Given a declarator which is not being
3781 /// used to build a declaration, complain about any decl attributes
3782 /// which might be lying around on it.
3783 void Sema::checkUnusedDeclAttributes(Declarator &D) {
3784 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
3785 ::checkUnusedDeclAttributes(*this, D.getAttributes());
3786 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
3787 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
3790 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
3791 /// #pragma weak needs a non-definition decl and source may not have one
3792 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
3793 SourceLocation Loc) {
3794 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
3795 NamedDecl *NewD = 0;
3796 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3797 FunctionDecl *NewFD;
3798 // FIXME: Missing call to CheckFunctionDeclaration().
3800 // FIXME: Is the qualifier info correct?
3801 // FIXME: Is the DeclContext correct?
3802 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
3803 Loc, Loc, DeclarationName(II),
3804 FD->getType(), FD->getTypeSourceInfo(),
3806 false/*isInlineSpecified*/,
3808 false/*isConstexprSpecified*/);
3811 if (FD->getQualifier())
3812 NewFD->setQualifierInfo(FD->getQualifierLoc());
3814 // Fake up parameter variables; they are declared as if this were
3816 QualType FDTy = FD->getType();
3817 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
3818 SmallVector<ParmVarDecl*, 16> Params;
3819 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3820 AE = FT->arg_type_end(); AI != AE; ++AI) {
3821 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
3822 Param->setScopeInfo(0, Params.size());
3823 Params.push_back(Param);
3825 NewFD->setParams(Params);
3827 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
3828 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
3829 VD->getInnerLocStart(), VD->getLocation(), II,
3830 VD->getType(), VD->getTypeSourceInfo(),
3831 VD->getStorageClass(),
3832 VD->getStorageClassAsWritten());
3833 if (VD->getQualifier()) {
3834 VarDecl *NewVD = cast<VarDecl>(NewD);
3835 NewVD->setQualifierInfo(VD->getQualifierLoc());
3841 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
3842 /// applied to it, possibly with an alias.
3843 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
3844 if (W.getUsed()) return; // only do this once
3846 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
3847 IdentifierInfo *NDId = ND->getIdentifier();
3848 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
3849 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
3851 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
3852 WeakTopLevelDecl.push_back(NewD);
3853 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
3854 // to insert Decl at TU scope, sorry.
3855 DeclContext *SavedContext = CurContext;
3856 CurContext = Context.getTranslationUnitDecl();
3857 PushOnScopeChains(NewD, S);
3858 CurContext = SavedContext;
3859 } else { // just add weak to existing
3860 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
3864 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
3865 /// it, apply them to D. This is a bit tricky because PD can have attributes
3866 /// specified in many different places, and we need to find and apply them all.
3867 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
3868 bool NonInheritable, bool Inheritable) {
3869 // It's valid to "forward-declare" #pragma weak, in which case we
3872 LoadExternalWeakUndeclaredIdentifiers();
3873 if (!WeakUndeclaredIdentifiers.empty()) {
3874 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
3875 if (IdentifierInfo *Id = ND->getIdentifier()) {
3876 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
3877 = WeakUndeclaredIdentifiers.find(Id);
3878 if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
3879 WeakInfo W = I->second;
3880 DeclApplyPragmaWeak(S, ND, W);
3881 WeakUndeclaredIdentifiers[Id] = W;
3888 // Apply decl attributes from the DeclSpec if present.
3889 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
3890 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3892 // Walk the declarator structure, applying decl attributes that were in a type
3893 // position to the decl itself. This handles cases like:
3894 // int *__attr__(x)** D;
3895 // when X is a decl attribute.
3896 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
3897 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
3898 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3900 // Finally, apply any attributes on the decl itself.
3901 if (const AttributeList *Attrs = PD.getAttributes())
3902 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3905 /// Is the given declaration allowed to use a forbidden type?
3906 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
3907 // Private ivars are always okay. Unfortunately, people don't
3908 // always properly make their ivars private, even in system headers.
3909 // Plus we need to make fields okay, too.
3910 // Function declarations in sys headers will be marked unavailable.
3911 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
3912 !isa<FunctionDecl>(decl))
3915 // Require it to be declared in a system header.
3916 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
3919 /// Handle a delayed forbidden-type diagnostic.
3920 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
3922 if (decl && isForbiddenTypeAllowed(S, decl)) {
3923 decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
3924 "this system declaration uses an unsupported type"));
3927 if (S.getLangOptions().ObjCAutoRefCount)
3928 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
3929 // FIXME. we may want to supress diagnostics for all
3930 // kind of forbidden type messages on unavailable functions.
3931 if (FD->hasAttr<UnavailableAttr>() &&
3932 diag.getForbiddenTypeDiagnostic() ==
3933 diag::err_arc_array_param_no_ownership) {
3934 diag.Triggered = true;
3939 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
3940 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
3941 diag.Triggered = true;
3944 // This duplicates a vector push_back but hides the need to know the
3945 // size of the type.
3946 void Sema::DelayedDiagnostics::add(const DelayedDiagnostic &diag) {
3947 assert(StackSize <= StackCapacity);
3949 // Grow the stack if necessary.
3950 if (StackSize == StackCapacity) {
3951 unsigned newCapacity = 2 * StackCapacity + 2;
3952 char *newBuffer = new char[newCapacity * sizeof(DelayedDiagnostic)];
3953 const char *oldBuffer = (const char*) Stack;
3956 memcpy(newBuffer, oldBuffer, StackCapacity * sizeof(DelayedDiagnostic));
3959 Stack = reinterpret_cast<sema::DelayedDiagnostic*>(newBuffer);
3960 StackCapacity = newCapacity;
3963 assert(StackSize < StackCapacity);
3964 new (&Stack[StackSize++]) DelayedDiagnostic(diag);
3967 void Sema::DelayedDiagnostics::popParsingDecl(Sema &S, ParsingDeclState state,
3969 DelayedDiagnostics &DD = S.DelayedDiagnostics;
3971 // Check the invariants.
3972 assert(DD.StackSize >= state.SavedStackSize);
3973 assert(state.SavedStackSize >= DD.ActiveStackBase);
3974 assert(DD.ParsingDepth > 0);
3976 // Drop the parsing depth.
3979 // If there are no active diagnostics, we're done.
3980 if (DD.StackSize == DD.ActiveStackBase)
3983 // We only want to actually emit delayed diagnostics when we
3984 // successfully parsed a decl.
3985 if (decl && !decl->isInvalidDecl()) {
3986 // We emit all the active diagnostics, not just those starting
3987 // from the saved state. The idea is this: we get one push for a
3988 // decl spec and another for each declarator; in a decl group like:
3989 // deprecated_typedef foo, *bar, baz();
3990 // only the declarator pops will be passed decls. This is correct;
3991 // we really do need to consider delayed diagnostics from the decl spec
3992 // for each of the different declarations.
3993 for (unsigned i = DD.ActiveStackBase, e = DD.StackSize; i != e; ++i) {
3994 DelayedDiagnostic &diag = DD.Stack[i];
3998 switch (diag.Kind) {
3999 case DelayedDiagnostic::Deprecation:
4000 S.HandleDelayedDeprecationCheck(diag, decl);
4003 case DelayedDiagnostic::Access:
4004 S.HandleDelayedAccessCheck(diag, decl);
4007 case DelayedDiagnostic::ForbiddenType:
4008 handleDelayedForbiddenType(S, diag, decl);
4014 // Destroy all the delayed diagnostics we're about to pop off.
4015 for (unsigned i = state.SavedStackSize, e = DD.StackSize; i != e; ++i)
4016 DD.Stack[i].Destroy();
4018 DD.StackSize = state.SavedStackSize;
4021 static bool isDeclDeprecated(Decl *D) {
4023 if (D->isDeprecated())
4025 // A category implicitly has the availability of the interface.
4026 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4027 return CatD->getClassInterface()->isDeprecated();
4028 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4032 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
4034 if (isDeclDeprecated(Ctx))
4037 DD.Triggered = true;
4038 if (!DD.getDeprecationMessage().empty())
4039 Diag(DD.Loc, diag::warn_deprecated_message)
4040 << DD.getDeprecationDecl()->getDeclName()
4041 << DD.getDeprecationMessage();
4043 Diag(DD.Loc, diag::warn_deprecated)
4044 << DD.getDeprecationDecl()->getDeclName();
4047 void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
4049 const ObjCInterfaceDecl *UnknownObjCClass) {
4050 // Delay if we're currently parsing a declaration.
4051 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
4052 DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D, Message));
4056 // Otherwise, don't warn if our current context is deprecated.
4057 if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
4059 if (!Message.empty())
4060 Diag(Loc, diag::warn_deprecated_message) << D->getDeclName()
4063 if (!UnknownObjCClass)
4064 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
4066 Diag(Loc, diag::warn_deprecated_fwdclass_message) << D->getDeclName();
4067 Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);