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/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/MathExtras.h"
39 using namespace clang;
42 namespace AttributeLangSupport {
48 } // end namespace AttributeLangSupport
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// isFunctionOrMethod - Return true if the given decl has function
55 /// type (function or function-typed variable) or an Objective-C
57 static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
61 /// \brief Return true if the given decl has function type (function or
62 /// function-typed variable) or an Objective-C method or a block.
63 static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
67 /// Return true if the given decl has a declarator that should have
68 /// been processed by Sema::GetTypeForDeclarator.
69 static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
75 /// hasFunctionProto - Return true if the given decl has a argument
76 /// information. This decl should have already passed
77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78 static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
84 /// getFunctionOrMethodNumParams - Return number of function or method
85 /// parameters. It is an error to call this on a K&R function (use
86 /// hasFunctionProto first).
87 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
95 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
96 if (const FunctionType *FnTy = D->getFunctionType())
97 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
98 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
99 return BD->getParamDecl(Idx)->getType();
101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
104 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
108 return MD->parameters()[Idx]->getSourceRange();
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
114 static QualType getFunctionOrMethodResultType(const Decl *D) {
115 if (const FunctionType *FnTy = D->getFunctionType())
116 return cast<FunctionType>(FnTy)->getReturnType();
117 return cast<ObjCMethodDecl>(D)->getReturnType();
120 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
128 static bool isFunctionOrMethodVariadic(const Decl *D) {
129 if (const FunctionType *FnTy = D->getFunctionType()) {
130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
131 return proto->isVariadic();
133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
136 return cast<ObjCMethodDecl>(D)->isVariadic();
139 static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
141 return MethodDecl->isInstance();
145 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
154 IdentifierInfo* ClsName = Cls->getIdentifier();
156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
161 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
162 const PointerType *PT = T->getAs<PointerType>();
166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
170 const RecordDecl *RD = RT->getDecl();
171 if (RD->getTagKind() != TTK_Struct)
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
177 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
182 template <typename Compare>
183 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
194 /// \brief Check if the attribute has exactly as many args as Num. May
196 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
203 /// \brief Check if the attribute has at least as many args as Num. May
205 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
212 /// \brief Check if the attribute has at most as many args as Num. May
214 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
221 /// \brief A helper function to provide Attribute Location for the Attr types
222 /// AND the AttributeList.
223 template <typename AttrInfo>
224 static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
225 SourceLocation>::type
226 getAttrLoc(const AttrInfo &Attr) {
227 return Attr.getLocation();
229 static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
230 return Attr.getLoc();
233 /// \brief A helper function to provide Attribute Name for the Attr types
234 /// AND the AttributeList.
235 template <typename AttrInfo>
236 static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
237 const AttrInfo *>::type
238 getAttrName(const AttrInfo &Attr) {
241 static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
242 return Attr.getName();
245 /// \brief If Expr is a valid integer constant, get the value of the integer
246 /// expression and return success or failure. May output an error.
247 template<typename AttrInfo>
248 static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX) {
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
256 << Expr->getSourceRange();
258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
260 << Expr->getSourceRange();
265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
270 Val = (uint32_t)I.getZExtValue();
274 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
275 /// that the result will fit into a regular (signed) int. All args have the same
276 /// purpose as they do in checkUInt32Argument.
277 template<typename AttrInfo>
278 static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX) {
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
285 llvm::APSInt I(32); // for toString
287 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
288 << I.toString(10, false) << 32 << /* Unsigned */ 0;
296 /// \brief Diagnose mutually exclusive attributes when present on a given
297 /// declaration. Returns true if diagnosed.
298 template <typename AttrTy>
299 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
301 if (AttrTy *A = D->getAttr<AttrTy>()) {
302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
310 /// \brief Check if IdxExpr is a valid parameter index for a function or
311 /// instance method D. May output an error.
313 /// \returns true if IdxExpr is a valid index.
314 template <typename AttrInfo>
315 static bool checkFunctionOrMethodParameterIndex(
316 Sema &S, const Decl *D, const AttrInfo& Attr,
317 unsigned AttrArgNum, const Expr *IdxExpr, uint64_t &Idx) {
318 assert(isFunctionOrMethodOrBlock(D));
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
333 << IdxExpr->getSourceRange();
337 Idx = IdxInt.getLimitedValue();
338 if (Idx < 1 || (!IV && Idx > NumParams)) {
339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
343 Idx--; // Convert to zero-based.
344 if (HasImplicitThisParam) {
346 S.Diag(getAttrLoc(Attr),
347 diag::err_attribute_invalid_implicit_this_argument)
348 << getAttrName(Attr) << IdxExpr->getSourceRange();
357 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
358 /// If not emit an error and return false. If the argument is an identifier it
359 /// will emit an error with a fixit hint and treat it as if it was a string
361 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
363 SourceLocation *ArgLocation) {
364 // Look for identifiers. If we have one emit a hint to fix it to a literal.
365 if (Attr.isArgIdent(ArgNum)) {
366 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
367 Diag(Loc->Loc, diag::err_attribute_argument_type)
368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
371 Str = Loc->Ident->getName();
373 *ArgLocation = Loc->Loc;
377 // Now check for an actual string literal.
378 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
379 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
381 *ArgLocation = ArgExpr->getLocStart();
383 if (!Literal || !Literal->isAscii()) {
384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
385 << Attr.getName() << AANT_ArgumentString;
389 Str = Literal->getString();
393 /// \brief Applies the given attribute to the Decl without performing any
394 /// additional semantic checking.
395 template <typename AttrType>
396 static void handleSimpleAttribute(Sema &S, Decl *D,
397 const AttributeList &Attr) {
398 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
399 Attr.getAttributeSpellingListIndex()));
402 template <typename AttrType>
403 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
404 const AttributeList &Attr) {
405 handleSimpleAttribute<AttrType>(S, D, Attr);
408 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
409 /// already have one of the given incompatible attributes.
410 template <typename AttrType, typename IncompatibleAttrType,
411 typename... IncompatibleAttrTypes>
412 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
413 const AttributeList &Attr) {
414 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
417 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
421 /// \brief Check if the passed-in expression is of type int or bool.
422 static bool isIntOrBool(Expr *Exp) {
423 QualType QT = Exp->getType();
424 return QT->isBooleanType() || QT->isIntegerType();
428 // Check to see if the type is a smart pointer of some kind. We assume
429 // it's a smart pointer if it defines both operator-> and operator*.
430 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
444 /// \brief Check if passed in Decl is a pointer type.
445 /// Note that this function may produce an error message.
446 /// \return true if the Decl is a pointer type; false otherwise
447 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
449 const ValueDecl *vd = cast<ValueDecl>(D);
450 QualType QT = vd->getType();
451 if (QT->isAnyPointerType())
454 if (const RecordType *RT = QT->getAs<RecordType>()) {
455 // If it's an incomplete type, it could be a smart pointer; skip it.
456 // (We don't want to force template instantiation if we can avoid it,
457 // since that would alter the order in which templates are instantiated.)
458 if (RT->isIncompleteType())
461 if (threadSafetyCheckIsSmartPointer(S, RT))
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
466 << Attr.getName() << QT;
470 /// \brief Checks that the passed in QualType either is of RecordType or points
471 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
472 static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
483 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
484 const RecordType *RT = getRecordType(Ty);
489 // Don't check for the capability if the class hasn't been defined yet.
490 if (RT->isIncompleteType())
493 // Allow smart pointers to be used as capability objects.
494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
498 // Check if the record itself has a capability.
499 RecordDecl *RD = RT->getDecl();
500 if (RD->hasAttr<CapabilityAttr>())
503 // Else check if any base classes have a capability.
504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
508 return Type->getDecl()->hasAttr<CapabilityAttr>();
515 static bool checkTypedefTypeForCapability(QualType Ty) {
516 const auto *TD = Ty->getAs<TypedefType>();
520 TypedefNameDecl *TN = TD->getDecl();
524 return TN->hasAttr<CapabilityAttr>();
527 static bool typeHasCapability(Sema &S, QualType Ty) {
528 if (checkTypedefTypeForCapability(Ty))
531 if (checkRecordTypeForCapability(S, Ty))
537 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
538 // Capability expressions are simple expressions involving the boolean logic
539 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
540 // a DeclRefExpr is found, its type should be checked to determine whether it
541 // is a capability or not.
543 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
544 return typeHasCapability(S, E->getType());
545 else if (const auto *E = dyn_cast<CastExpr>(Ex))
546 return isCapabilityExpr(S, E->getSubExpr());
547 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
548 return isCapabilityExpr(S, E->getSubExpr());
549 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
550 if (E->getOpcode() == UO_LNot)
551 return isCapabilityExpr(S, E->getSubExpr());
553 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
554 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
555 return isCapabilityExpr(S, E->getLHS()) &&
556 isCapabilityExpr(S, E->getRHS());
563 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
564 /// a capability object.
565 /// \param Sidx The attribute argument index to start checking with.
566 /// \param ParamIdxOk Whether an argument can be indexing into a function
568 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
569 const AttributeList &Attr,
570 SmallVectorImpl<Expr *> &Args,
572 bool ParamIdxOk = false) {
573 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
574 Expr *ArgExp = Attr.getArgAsExpr(Idx);
576 if (ArgExp->isTypeDependent()) {
577 // FIXME -- need to check this again on template instantiation
578 Args.push_back(ArgExp);
582 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
583 if (StrLit->getLength() == 0 ||
584 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
585 // Pass empty strings to the analyzer without warnings.
586 // Treat "*" as the universal lock.
587 Args.push_back(ArgExp);
591 // We allow constant strings to be used as a placeholder for expressions
592 // that are not valid C++ syntax, but warn that they are ignored.
593 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
595 Args.push_back(ArgExp);
599 QualType ArgTy = ArgExp->getType();
601 // A pointer to member expression of the form &MyClass::mu is treated
602 // specially -- we need to look at the type of the member.
603 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
604 if (UOp->getOpcode() == UO_AddrOf)
605 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
606 if (DRE->getDecl()->isCXXInstanceMember())
607 ArgTy = DRE->getDecl()->getType();
609 // First see if we can just cast to record type, or pointer to record type.
610 const RecordType *RT = getRecordType(ArgTy);
612 // Now check if we index into a record type function param.
613 if(!RT && ParamIdxOk) {
614 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
615 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
617 unsigned int NumParams = FD->getNumParams();
618 llvm::APInt ArgValue = IL->getValue();
619 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
620 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
621 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
622 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
623 << Attr.getName() << Idx + 1 << NumParams;
626 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
630 // If the type does not have a capability, see if the components of the
631 // expression have capabilities. This allows for writing C code where the
632 // capability may be on the type, and the expression is a capability
633 // boolean logic expression. Eg) requires_capability(A || B && !C)
634 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
636 << Attr.getName() << ArgTy;
638 Args.push_back(ArgExp);
642 //===----------------------------------------------------------------------===//
643 // Attribute Implementations
644 //===----------------------------------------------------------------------===//
646 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
647 const AttributeList &Attr) {
648 if (!threadSafetyCheckIsPointer(S, D, Attr))
651 D->addAttr(::new (S.Context)
652 PtGuardedVarAttr(Attr.getRange(), S.Context,
653 Attr.getAttributeSpellingListIndex()));
656 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
657 const AttributeList &Attr,
659 SmallVector<Expr*, 1> Args;
660 // check that all arguments are lockable objects
661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
662 unsigned Size = Args.size();
671 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
673 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
676 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
677 Attr.getAttributeSpellingListIndex()));
680 static void handlePtGuardedByAttr(Sema &S, Decl *D,
681 const AttributeList &Attr) {
683 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
686 if (!threadSafetyCheckIsPointer(S, D, Attr))
689 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
691 Attr.getAttributeSpellingListIndex()));
694 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
695 const AttributeList &Attr,
696 SmallVectorImpl<Expr *> &Args) {
697 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
700 // Check that this attribute only applies to lockable types.
701 QualType QT = cast<ValueDecl>(D)->getType();
702 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
703 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
708 // Check that all arguments are lockable objects.
709 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
716 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
717 const AttributeList &Attr) {
718 SmallVector<Expr*, 1> Args;
719 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
722 Expr **StartArg = &Args[0];
723 D->addAttr(::new (S.Context)
724 AcquiredAfterAttr(Attr.getRange(), S.Context,
725 StartArg, Args.size(),
726 Attr.getAttributeSpellingListIndex()));
729 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
735 Expr **StartArg = &Args[0];
736 D->addAttr(::new (S.Context)
737 AcquiredBeforeAttr(Attr.getRange(), S.Context,
738 StartArg, Args.size(),
739 Attr.getAttributeSpellingListIndex()));
742 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
743 const AttributeList &Attr,
744 SmallVectorImpl<Expr *> &Args) {
745 // zero or more arguments ok
746 // check that all arguments are lockable objects
747 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
752 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
753 const AttributeList &Attr) {
754 SmallVector<Expr*, 1> Args;
755 if (!checkLockFunAttrCommon(S, D, Attr, Args))
758 unsigned Size = Args.size();
759 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
760 D->addAttr(::new (S.Context)
761 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
762 Attr.getAttributeSpellingListIndex()));
765 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
766 const AttributeList &Attr) {
767 SmallVector<Expr*, 1> Args;
768 if (!checkLockFunAttrCommon(S, D, Attr, Args))
771 unsigned Size = Args.size();
772 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
773 D->addAttr(::new (S.Context)
774 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
776 Attr.getAttributeSpellingListIndex()));
779 /// \brief Checks to be sure that the given parameter number is in bounds, and is
780 /// an integral type. Will emit appropriate diagnostics if this returns
783 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
784 /// to actually retrieve the argument, so it's base-0.
785 template <typename AttrInfo>
786 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
787 const AttrInfo &Attr, Expr *AttrArg,
788 unsigned FuncParamNo, unsigned AttrArgNo,
789 bool AllowDependentType = false) {
791 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
795 const ParmVarDecl *Param = FD->getParamDecl(Idx);
796 if (AllowDependentType && Param->getType()->isDependentType())
798 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
799 SourceLocation SrcLoc = AttrArg->getLocStart();
800 S.Diag(SrcLoc, diag::err_attribute_integers_only)
801 << getAttrName(Attr) << Param->getSourceRange();
807 /// \brief Checks to be sure that the given parameter number is in bounds, and is
808 /// an integral type. Will emit appropriate diagnostics if this returns false.
810 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
811 /// to actually retrieve the argument, so it's base-0.
812 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
813 const AttributeList &Attr,
814 unsigned FuncParamNo, unsigned AttrArgNo,
815 bool AllowDependentType = false) {
816 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
817 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
818 FuncParamNo, AttrArgNo, AllowDependentType);
821 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
823 !checkAttributeAtMostNumArgs(S, Attr, 2))
826 const auto *FD = cast<FunctionDecl>(D);
827 if (!FD->getReturnType()->isPointerType()) {
828 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
833 const Expr *SizeExpr = Attr.getArgAsExpr(0);
835 // Parameter indices are 1-indexed, hence Index=1
836 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
839 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
842 // Args are 1-indexed, so 0 implies that the arg was not present
844 if (Attr.getNumArgs() == 2) {
845 const Expr *NumberExpr = Attr.getArgAsExpr(1);
846 // Parameter indices are 1-based, hence Index=2
847 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
851 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
855 D->addAttr(::new (S.Context) AllocSizeAttr(
856 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
857 Attr.getAttributeSpellingListIndex()));
860 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
861 const AttributeList &Attr,
862 SmallVectorImpl<Expr *> &Args) {
863 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
866 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
867 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
868 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
872 // check that all arguments are lockable objects
873 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
878 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
879 const AttributeList &Attr) {
880 SmallVector<Expr*, 2> Args;
881 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
884 D->addAttr(::new (S.Context)
885 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
886 Attr.getArgAsExpr(0),
887 Args.data(), Args.size(),
888 Attr.getAttributeSpellingListIndex()));
891 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
892 const AttributeList &Attr) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
897 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
898 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
899 Args.size(), Attr.getAttributeSpellingListIndex()));
902 static void handleLockReturnedAttr(Sema &S, Decl *D,
903 const AttributeList &Attr) {
904 // check that the argument is lockable object
905 SmallVector<Expr*, 1> Args;
906 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
907 unsigned Size = Args.size();
911 D->addAttr(::new (S.Context)
912 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
913 Attr.getAttributeSpellingListIndex()));
916 static void handleLocksExcludedAttr(Sema &S, Decl *D,
917 const AttributeList &Attr) {
918 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
921 // check that all arguments are lockable objects
922 SmallVector<Expr*, 1> Args;
923 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
924 unsigned Size = Args.size();
927 Expr **StartArg = &Args[0];
929 D->addAttr(::new (S.Context)
930 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
931 Attr.getAttributeSpellingListIndex()));
934 static bool checkFunctionConditionAttr(Sema &S, Decl *D,
935 const AttributeList &Attr,
936 Expr *&Cond, StringRef &Msg) {
937 Cond = Attr.getArgAsExpr(0);
938 if (!Cond->isTypeDependent()) {
939 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
940 if (Converted.isInvalid())
942 Cond = Converted.get();
945 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
949 Msg = "<no message provided>";
951 SmallVector<PartialDiagnosticAt, 8> Diags;
952 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
953 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
955 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
957 for (const PartialDiagnosticAt &PDiag : Diags)
958 S.Diag(PDiag.first, PDiag.second);
964 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
965 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
969 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
970 D->addAttr(::new (S.Context)
971 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
972 Attr.getAttributeSpellingListIndex()));
976 /// Determines if a given Expr references any of the given function's
977 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
978 class ArgumentDependenceChecker
979 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
981 const CXXRecordDecl *ClassType;
983 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
987 ArgumentDependenceChecker(const FunctionDecl *FD) {
989 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
990 ClassType = MD->getParent();
994 Parms.insert(FD->param_begin(), FD->param_end());
997 bool referencesArgs(Expr *E) {
1003 bool VisitCXXThisExpr(CXXThisExpr *E) {
1004 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1005 "`this` doesn't refer to the enclosing class?");
1010 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1011 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1012 if (Parms.count(PVD)) {
1021 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1022 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1026 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1029 StringRef DiagTypeStr;
1030 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1033 DiagnoseIfAttr::DiagnosticType DiagType;
1034 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1035 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1036 diag::err_diagnose_if_invalid_diagnostic_type);
1040 bool ArgDependent = false;
1041 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1042 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1043 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1044 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D),
1045 Attr.getAttributeSpellingListIndex()));
1048 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1049 const AttributeList &Attr) {
1050 if (D->hasAttr<PassObjectSizeAttr>()) {
1051 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1056 Expr *E = Attr.getArgAsExpr(0);
1058 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1061 // pass_object_size's argument is passed in as the second argument of
1062 // __builtin_object_size. So, it has the same constraints as that second
1063 // argument; namely, it must be in the range [0, 3].
1065 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1066 << Attr.getName() << 0 << 3 << E->getSourceRange();
1070 // pass_object_size is only supported on constant pointer parameters; as a
1071 // kindness to users, we allow the parameter to be non-const for declarations.
1072 // At this point, we have no clue if `D` belongs to a function declaration or
1073 // definition, so we defer the constness check until later.
1074 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1075 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1076 << Attr.getName() << 1;
1080 D->addAttr(::new (S.Context)
1081 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1082 Attr.getAttributeSpellingListIndex()));
1085 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1086 ConsumableAttr::ConsumedState DefaultState;
1088 if (Attr.isArgIdent(0)) {
1089 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1090 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1092 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1093 << Attr.getName() << IL->Ident;
1097 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1098 << Attr.getName() << AANT_ArgumentIdentifier;
1102 D->addAttr(::new (S.Context)
1103 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1104 Attr.getAttributeSpellingListIndex()));
1107 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1108 const AttributeList &Attr) {
1109 ASTContext &CurrContext = S.getASTContext();
1110 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1112 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1113 if (!RD->hasAttr<ConsumableAttr>()) {
1114 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1115 RD->getNameAsString();
1124 static void handleCallableWhenAttr(Sema &S, Decl *D,
1125 const AttributeList &Attr) {
1126 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1129 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1132 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1133 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1134 CallableWhenAttr::ConsumedState CallableState;
1136 StringRef StateString;
1138 if (Attr.isArgIdent(ArgIndex)) {
1139 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1140 StateString = Ident->Ident->getName();
1143 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1147 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1149 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1150 << Attr.getName() << StateString;
1154 States.push_back(CallableState);
1157 D->addAttr(::new (S.Context)
1158 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1159 States.size(), Attr.getAttributeSpellingListIndex()));
1162 static void handleParamTypestateAttr(Sema &S, Decl *D,
1163 const AttributeList &Attr) {
1164 ParamTypestateAttr::ConsumedState ParamState;
1166 if (Attr.isArgIdent(0)) {
1167 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1168 StringRef StateString = Ident->Ident->getName();
1170 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1172 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1173 << Attr.getName() << StateString;
1177 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1178 Attr.getName() << AANT_ArgumentIdentifier;
1182 // FIXME: This check is currently being done in the analysis. It can be
1183 // enabled here only after the parser propagates attributes at
1184 // template specialization definition, not declaration.
1185 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1186 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1188 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1189 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1190 // ReturnType.getAsString();
1194 D->addAttr(::new (S.Context)
1195 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1196 Attr.getAttributeSpellingListIndex()));
1199 static void handleReturnTypestateAttr(Sema &S, Decl *D,
1200 const AttributeList &Attr) {
1201 ReturnTypestateAttr::ConsumedState ReturnState;
1203 if (Attr.isArgIdent(0)) {
1204 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1205 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1207 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1208 << Attr.getName() << IL->Ident;
1212 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1213 Attr.getName() << AANT_ArgumentIdentifier;
1217 // FIXME: This check is currently being done in the analysis. It can be
1218 // enabled here only after the parser propagates attributes at
1219 // template specialization definition, not declaration.
1220 //QualType ReturnType;
1222 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1223 // ReturnType = Param->getType();
1225 //} else if (const CXXConstructorDecl *Constructor =
1226 // dyn_cast<CXXConstructorDecl>(D)) {
1227 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1231 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1234 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1236 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1237 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1238 // ReturnType.getAsString();
1242 D->addAttr(::new (S.Context)
1243 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1244 Attr.getAttributeSpellingListIndex()));
1247 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1248 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1251 SetTypestateAttr::ConsumedState NewState;
1252 if (Attr.isArgIdent(0)) {
1253 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1254 StringRef Param = Ident->Ident->getName();
1255 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1256 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1257 << Attr.getName() << Param;
1261 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1262 Attr.getName() << AANT_ArgumentIdentifier;
1266 D->addAttr(::new (S.Context)
1267 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1268 Attr.getAttributeSpellingListIndex()));
1271 static void handleTestTypestateAttr(Sema &S, Decl *D,
1272 const AttributeList &Attr) {
1273 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1276 TestTypestateAttr::ConsumedState TestState;
1277 if (Attr.isArgIdent(0)) {
1278 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1279 StringRef Param = Ident->Ident->getName();
1280 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1281 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1282 << Attr.getName() << Param;
1286 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1287 Attr.getName() << AANT_ArgumentIdentifier;
1291 D->addAttr(::new (S.Context)
1292 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1293 Attr.getAttributeSpellingListIndex()));
1296 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1297 const AttributeList &Attr) {
1298 // Remember this typedef decl, we will need it later for diagnostics.
1299 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1302 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1303 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1304 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1305 Attr.getAttributeSpellingListIndex()));
1306 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1307 // Report warning about changed offset in the newer compiler versions.
1308 if (!FD->getType()->isDependentType() &&
1309 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1310 S.Context.getTypeAlign(FD->getType()) <= 8)
1311 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1313 FD->addAttr(::new (S.Context) PackedAttr(
1314 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1316 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1319 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1320 // The IBOutlet/IBOutletCollection attributes only apply to instance
1321 // variables or properties of Objective-C classes. The outlet must also
1322 // have an object reference type.
1323 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1324 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1325 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1326 << Attr.getName() << VD->getType() << 0;
1330 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1331 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1332 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1333 << Attr.getName() << PD->getType() << 1;
1338 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1345 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1346 if (!checkIBOutletCommon(S, D, Attr))
1349 D->addAttr(::new (S.Context)
1350 IBOutletAttr(Attr.getRange(), S.Context,
1351 Attr.getAttributeSpellingListIndex()));
1354 static void handleIBOutletCollection(Sema &S, Decl *D,
1355 const AttributeList &Attr) {
1357 // The iboutletcollection attribute can have zero or one arguments.
1358 if (Attr.getNumArgs() > 1) {
1359 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1360 << Attr.getName() << 1;
1364 if (!checkIBOutletCommon(S, D, Attr))
1369 if (Attr.hasParsedType())
1370 PT = Attr.getTypeArg();
1372 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1373 S.getScopeForContext(D->getDeclContext()->getParent()));
1375 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1380 TypeSourceInfo *QTLoc = nullptr;
1381 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1383 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1385 // Diagnose use of non-object type in iboutletcollection attribute.
1386 // FIXME. Gnu attribute extension ignores use of builtin types in
1387 // attributes. So, __attribute__((iboutletcollection(char))) will be
1388 // treated as __attribute__((iboutletcollection())).
1389 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1390 S.Diag(Attr.getLoc(),
1391 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1392 : diag::err_iboutletcollection_type) << QT;
1396 D->addAttr(::new (S.Context)
1397 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1398 Attr.getAttributeSpellingListIndex()));
1401 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1403 if (T->isReferenceType())
1406 T = T.getNonReferenceType();
1409 // The nonnull attribute, and other similar attributes, can be applied to a
1410 // transparent union that contains a pointer type.
1411 if (const RecordType *UT = T->getAsUnionType()) {
1412 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1413 RecordDecl *UD = UT->getDecl();
1414 for (const auto *I : UD->fields()) {
1415 QualType QT = I->getType();
1416 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1422 return T->isAnyPointerType() || T->isBlockPointerType();
1425 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1426 SourceRange AttrParmRange,
1427 SourceRange TypeRange,
1428 bool isReturnValue = false) {
1429 if (!S.isValidPointerAttrType(T)) {
1431 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1432 << Attr.getName() << AttrParmRange << TypeRange;
1434 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1435 << Attr.getName() << AttrParmRange << TypeRange << 0;
1441 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1442 SmallVector<unsigned, 8> NonNullArgs;
1443 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1444 Expr *Ex = Attr.getArgAsExpr(I);
1446 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1449 // Is the function argument a pointer type?
1450 if (Idx < getFunctionOrMethodNumParams(D) &&
1451 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1452 Ex->getSourceRange(),
1453 getFunctionOrMethodParamRange(D, Idx)))
1456 NonNullArgs.push_back(Idx);
1459 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1460 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1461 // check if the attribute came from a macro expansion or a template
1463 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1464 !S.inTemplateInstantiation()) {
1465 bool AnyPointers = isFunctionOrMethodVariadic(D);
1466 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1467 I != E && !AnyPointers; ++I) {
1468 QualType T = getFunctionOrMethodParamType(D, I);
1469 if (T->isDependentType() || S.isValidPointerAttrType(T))
1474 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1477 unsigned *Start = NonNullArgs.data();
1478 unsigned Size = NonNullArgs.size();
1479 llvm::array_pod_sort(Start, Start + Size);
1480 D->addAttr(::new (S.Context)
1481 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1482 Attr.getAttributeSpellingListIndex()));
1485 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1486 const AttributeList &Attr) {
1487 if (Attr.getNumArgs() > 0) {
1488 if (D->getFunctionType()) {
1489 handleNonNullAttr(S, D, Attr);
1491 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1492 << D->getSourceRange();
1497 // Is the argument a pointer type?
1498 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1499 D->getSourceRange()))
1502 D->addAttr(::new (S.Context)
1503 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1504 Attr.getAttributeSpellingListIndex()));
1507 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1508 const AttributeList &Attr) {
1509 QualType ResultType = getFunctionOrMethodResultType(D);
1510 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1511 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1512 /* isReturnValue */ true))
1515 D->addAttr(::new (S.Context)
1516 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1517 Attr.getAttributeSpellingListIndex()));
1520 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1521 const AttributeList &Attr) {
1522 Expr *E = Attr.getArgAsExpr(0),
1523 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1524 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1525 Attr.getAttributeSpellingListIndex());
1528 static void handleAllocAlignAttr(Sema &S, Decl *D,
1529 const AttributeList &Attr) {
1530 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1531 Attr.getAttributeSpellingListIndex());
1534 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1535 Expr *OE, unsigned SpellingListIndex) {
1536 QualType ResultType = getFunctionOrMethodResultType(D);
1537 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1539 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1540 SourceLocation AttrLoc = AttrRange.getBegin();
1542 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1543 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1544 << &TmpAttr << AttrRange << SR;
1548 if (!E->isValueDependent()) {
1550 if (!E->isIntegerConstantExpr(I, Context)) {
1552 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1553 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1554 << E->getSourceRange();
1556 Diag(AttrLoc, diag::err_attribute_argument_type)
1557 << &TmpAttr << AANT_ArgumentIntegerConstant
1558 << E->getSourceRange();
1562 if (!I.isPowerOf2()) {
1563 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1564 << E->getSourceRange();
1570 if (!OE->isValueDependent()) {
1572 if (!OE->isIntegerConstantExpr(I, Context)) {
1573 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1574 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1575 << OE->getSourceRange();
1581 D->addAttr(::new (Context)
1582 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1585 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1586 unsigned SpellingListIndex) {
1587 QualType ResultType = getFunctionOrMethodResultType(D);
1589 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1590 SourceLocation AttrLoc = AttrRange.getBegin();
1592 if (!ResultType->isDependentType() &&
1593 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1594 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1595 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1600 const auto *FuncDecl = cast<FunctionDecl>(D);
1601 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1602 /*AttrArgNo=*/1, ParamExpr,
1606 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1607 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1608 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1609 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1613 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1614 // because that has corrected for the implicit this parameter, and is zero-
1615 // based. The attribute expects what the user wrote explicitly.
1617 ParamExpr->EvaluateAsInt(Val, Context);
1619 D->addAttr(::new (Context) AllocAlignAttr(
1620 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1623 /// Normalize the attribute, __foo__ becomes foo.
1624 /// Returns true if normalization was applied.
1625 static bool normalizeName(StringRef &AttrName) {
1626 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1627 AttrName.endswith("__")) {
1628 AttrName = AttrName.drop_front(2).drop_back(2);
1634 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1635 // This attribute must be applied to a function declaration. The first
1636 // argument to the attribute must be an identifier, the name of the resource,
1637 // for example: malloc. The following arguments must be argument indexes, the
1638 // arguments must be of integer type for Returns, otherwise of pointer type.
1639 // The difference between Holds and Takes is that a pointer may still be used
1640 // after being held. free() should be __attribute((ownership_takes)), whereas
1641 // a list append function may well be __attribute((ownership_holds)).
1643 if (!AL.isArgIdent(0)) {
1644 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1645 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1649 // Figure out our Kind.
1650 OwnershipAttr::OwnershipKind K =
1651 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1652 AL.getAttributeSpellingListIndex()).getOwnKind();
1656 case OwnershipAttr::Takes:
1657 case OwnershipAttr::Holds:
1658 if (AL.getNumArgs() < 2) {
1659 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1660 << AL.getName() << 2;
1664 case OwnershipAttr::Returns:
1665 if (AL.getNumArgs() > 2) {
1666 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1667 << AL.getName() << 1;
1673 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1675 StringRef ModuleName = Module->getName();
1676 if (normalizeName(ModuleName)) {
1677 Module = &S.PP.getIdentifierTable().get(ModuleName);
1680 SmallVector<unsigned, 8> OwnershipArgs;
1681 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1682 Expr *Ex = AL.getArgAsExpr(i);
1684 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1687 // Is the function argument a pointer type?
1688 QualType T = getFunctionOrMethodParamType(D, Idx);
1689 int Err = -1; // No error
1691 case OwnershipAttr::Takes:
1692 case OwnershipAttr::Holds:
1693 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1696 case OwnershipAttr::Returns:
1697 if (!T->isIntegerType())
1702 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1703 << Ex->getSourceRange();
1707 // Check we don't have a conflict with another ownership attribute.
1708 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1709 // Cannot have two ownership attributes of different kinds for the same
1711 if (I->getOwnKind() != K && I->args_end() !=
1712 std::find(I->args_begin(), I->args_end(), Idx)) {
1713 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1714 << AL.getName() << I;
1716 } else if (K == OwnershipAttr::Returns &&
1717 I->getOwnKind() == OwnershipAttr::Returns) {
1718 // A returns attribute conflicts with any other returns attribute using
1719 // a different index. Note, diagnostic reporting is 1-based, but stored
1720 // argument indexes are 0-based.
1721 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1722 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1723 << *(I->args_begin()) + 1;
1725 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1726 << (unsigned)Idx + 1 << Ex->getSourceRange();
1731 OwnershipArgs.push_back(Idx);
1734 unsigned* start = OwnershipArgs.data();
1735 unsigned size = OwnershipArgs.size();
1736 llvm::array_pod_sort(start, start + size);
1738 D->addAttr(::new (S.Context)
1739 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1740 AL.getAttributeSpellingListIndex()));
1743 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1744 // Check the attribute arguments.
1745 if (Attr.getNumArgs() > 1) {
1746 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1747 << Attr.getName() << 1;
1751 NamedDecl *nd = cast<NamedDecl>(D);
1755 // static int a __attribute__((weakref ("v2")));
1756 // static int b() __attribute__((weakref ("f3")));
1758 // and ignores the attributes of
1760 // static int a __attribute__((weakref ("v2")));
1763 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1764 if (!Ctx->isFileContext()) {
1765 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1770 // The GCC manual says
1772 // At present, a declaration to which `weakref' is attached can only
1777 // Without a TARGET,
1778 // given as an argument to `weakref' or to `alias', `weakref' is
1779 // equivalent to `weak'.
1781 // gcc 4.4.1 will accept
1782 // int a7 __attribute__((weakref));
1784 // int a7 __attribute__((weak));
1785 // This looks like a bug in gcc. We reject that for now. We should revisit
1786 // it if this behaviour is actually used.
1789 // static ((alias ("y"), weakref)).
1790 // Should we? How to check that weakref is before or after alias?
1792 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1793 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1794 // StringRef parameter it was given anyway.
1796 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1797 // GCC will accept anything as the argument of weakref. Should we
1798 // check for an existing decl?
1799 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1800 Attr.getAttributeSpellingListIndex()));
1802 D->addAttr(::new (S.Context)
1803 WeakRefAttr(Attr.getRange(), S.Context,
1804 Attr.getAttributeSpellingListIndex()));
1807 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1809 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1812 // Aliases should be on declarations, not definitions.
1813 const auto *FD = cast<FunctionDecl>(D);
1814 if (FD->isThisDeclarationADefinition()) {
1815 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1818 // FIXME: it should be handled as a target specific attribute.
1819 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1820 llvm::Triple::ELF) {
1821 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1825 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1826 Attr.getAttributeSpellingListIndex()));
1829 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1831 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1834 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1835 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1838 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1839 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1842 // Aliases should be on declarations, not definitions.
1843 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1844 if (FD->isThisDeclarationADefinition()) {
1845 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1849 const auto *VD = cast<VarDecl>(D);
1850 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1851 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1856 // FIXME: check if target symbol exists in current file
1858 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1859 Attr.getAttributeSpellingListIndex()));
1862 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1863 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1866 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1867 Attr.getAttributeSpellingListIndex()));
1870 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1871 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1874 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1875 Attr.getAttributeSpellingListIndex()));
1878 static void handleTLSModelAttr(Sema &S, Decl *D,
1879 const AttributeList &Attr) {
1881 SourceLocation LiteralLoc;
1882 // Check that it is a string.
1883 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1886 // Check that the value.
1887 if (Model != "global-dynamic" && Model != "local-dynamic"
1888 && Model != "initial-exec" && Model != "local-exec") {
1889 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1893 D->addAttr(::new (S.Context)
1894 TLSModelAttr(Attr.getRange(), S.Context, Model,
1895 Attr.getAttributeSpellingListIndex()));
1898 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1899 QualType ResultType = getFunctionOrMethodResultType(D);
1900 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1901 D->addAttr(::new (S.Context) RestrictAttr(
1902 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1906 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1907 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1910 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1911 if (S.LangOpts.CPlusPlus) {
1912 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1913 << Attr.getName() << AttributeLangSupport::Cpp;
1917 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1918 Attr.getAttributeSpellingListIndex()))
1922 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1923 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1927 if (Attr.isDeclspecAttribute()) {
1928 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1929 const auto &Arch = Triple.getArch();
1930 if (Arch != llvm::Triple::x86 &&
1931 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1932 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1933 << Attr.getName() << Triple.getArchName();
1938 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1939 Attr.getAttributeSpellingListIndex()));
1942 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1943 if (hasDeclarator(D)) return;
1945 if (S.CheckNoReturnAttr(attr))
1948 if (!isa<ObjCMethodDecl>(D)) {
1949 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1950 << attr.getName() << ExpectedFunctionOrMethod;
1954 D->addAttr(::new (S.Context) NoReturnAttr(
1955 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
1958 static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D,
1959 const AttributeList &Attr) {
1960 if (S.CheckNoCallerSavedRegsAttr(Attr))
1963 D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr(
1964 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1967 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1968 if (!checkAttributeNumArgs(*this, attr, 0)) {
1976 bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &Attr) {
1977 // Check whether the attribute is valid on the current target.
1978 if (!Attr.existsInTarget(Context.getTargetInfo())) {
1979 Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName();
1984 if (!checkAttributeNumArgs(*this, Attr, 0)) {
1992 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1993 const AttributeList &Attr) {
1995 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1996 // because 'analyzer_noreturn' does not impact the type.
1997 if (!isFunctionOrMethodOrBlock(D)) {
1998 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1999 if (!VD || (!VD->getType()->isBlockPointerType() &&
2000 !VD->getType()->isFunctionPointerType())) {
2001 S.Diag(Attr.getLoc(),
2002 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
2003 : diag::warn_attribute_wrong_decl_type)
2004 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2009 D->addAttr(::new (S.Context)
2010 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2011 Attr.getAttributeSpellingListIndex()));
2014 // PS3 PPU-specific.
2015 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2017 Returning a Vector Class in Registers
2019 According to the PPU ABI specifications, a class with a single member of
2020 vector type is returned in memory when used as the return value of a function.
2021 This results in inefficient code when implementing vector classes. To return
2022 the value in a single vector register, add the vecreturn attribute to the
2023 class definition. This attribute is also applicable to struct types.
2029 __vector float xyzw;
2030 } __attribute__((vecreturn));
2032 Vector Add(Vector lhs, Vector rhs)
2035 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2036 return result; // This will be returned in a register
2039 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2040 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
2044 RecordDecl *record = cast<RecordDecl>(D);
2047 if (!isa<CXXRecordDecl>(record)) {
2048 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2052 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2053 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2057 for (const auto *I : record->fields()) {
2058 if ((count == 1) || !I->getType()->isVectorType()) {
2059 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2065 D->addAttr(::new (S.Context)
2066 VecReturnAttr(Attr.getRange(), S.Context,
2067 Attr.getAttributeSpellingListIndex()));
2070 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2071 const AttributeList &Attr) {
2072 if (isa<ParmVarDecl>(D)) {
2073 // [[carries_dependency]] can only be applied to a parameter if it is a
2074 // parameter of a function declaration or lambda.
2075 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2076 S.Diag(Attr.getLoc(),
2077 diag::err_carries_dependency_param_not_function_decl);
2082 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2083 Attr.getRange(), S.Context,
2084 Attr.getAttributeSpellingListIndex()));
2087 static void handleNotTailCalledAttr(Sema &S, Decl *D,
2088 const AttributeList &Attr) {
2089 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2093 D->addAttr(::new (S.Context) NotTailCalledAttr(
2094 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2097 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2098 const AttributeList &Attr) {
2099 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2103 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2104 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2107 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2108 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2109 if (VD->hasLocalStorage()) {
2110 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2113 } else if (!isFunctionOrMethod(D)) {
2114 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2115 << Attr.getName() << ExpectedVariableOrFunction;
2119 D->addAttr(::new (S.Context)
2120 UsedAttr(Attr.getRange(), S.Context,
2121 Attr.getAttributeSpellingListIndex()));
2124 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2125 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2127 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2128 // The C++1z spelling of this attribute cannot be applied to a static data
2129 // member per [dcl.attr.unused]p2.
2130 if (cast<VarDecl>(D)->isStaticDataMember()) {
2131 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2132 << Attr.getName() << ExpectedForMaybeUnused;
2137 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2138 // about using it as an extension.
2139 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2140 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2142 D->addAttr(::new (S.Context) UnusedAttr(
2143 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2146 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2147 uint32_t priority = ConstructorAttr::DefaultPriority;
2148 if (Attr.getNumArgs() &&
2149 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2152 D->addAttr(::new (S.Context)
2153 ConstructorAttr(Attr.getRange(), S.Context, priority,
2154 Attr.getAttributeSpellingListIndex()));
2157 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2158 uint32_t priority = DestructorAttr::DefaultPriority;
2159 if (Attr.getNumArgs() &&
2160 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2163 D->addAttr(::new (S.Context)
2164 DestructorAttr(Attr.getRange(), S.Context, priority,
2165 Attr.getAttributeSpellingListIndex()));
2168 template <typename AttrTy>
2169 static void handleAttrWithMessage(Sema &S, Decl *D,
2170 const AttributeList &Attr) {
2171 // Handle the case where the attribute has a text message.
2173 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2176 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2177 Attr.getAttributeSpellingListIndex()));
2180 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2181 const AttributeList &Attr) {
2182 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2183 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2184 << Attr.getName() << Attr.getRange();
2188 D->addAttr(::new (S.Context)
2189 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2190 Attr.getAttributeSpellingListIndex()));
2193 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2194 IdentifierInfo *Platform,
2195 VersionTuple Introduced,
2196 VersionTuple Deprecated,
2197 VersionTuple Obsoleted) {
2198 StringRef PlatformName
2199 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2200 if (PlatformName.empty())
2201 PlatformName = Platform->getName();
2203 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2204 // of these steps are needed).
2205 if (!Introduced.empty() && !Deprecated.empty() &&
2206 !(Introduced <= Deprecated)) {
2207 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2208 << 1 << PlatformName << Deprecated.getAsString()
2209 << 0 << Introduced.getAsString();
2213 if (!Introduced.empty() && !Obsoleted.empty() &&
2214 !(Introduced <= Obsoleted)) {
2215 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2216 << 2 << PlatformName << Obsoleted.getAsString()
2217 << 0 << Introduced.getAsString();
2221 if (!Deprecated.empty() && !Obsoleted.empty() &&
2222 !(Deprecated <= Obsoleted)) {
2223 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2224 << 2 << PlatformName << Obsoleted.getAsString()
2225 << 1 << Deprecated.getAsString();
2232 /// \brief Check whether the two versions match.
2234 /// If either version tuple is empty, then they are assumed to match. If
2235 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2236 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2237 bool BeforeIsOkay) {
2238 if (X.empty() || Y.empty())
2244 if (BeforeIsOkay && X < Y)
2250 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2251 IdentifierInfo *Platform,
2253 VersionTuple Introduced,
2254 VersionTuple Deprecated,
2255 VersionTuple Obsoleted,
2259 StringRef Replacement,
2260 AvailabilityMergeKind AMK,
2261 unsigned AttrSpellingListIndex) {
2262 VersionTuple MergedIntroduced = Introduced;
2263 VersionTuple MergedDeprecated = Deprecated;
2264 VersionTuple MergedObsoleted = Obsoleted;
2265 bool FoundAny = false;
2266 bool OverrideOrImpl = false;
2269 case AMK_Redeclaration:
2270 OverrideOrImpl = false;
2274 case AMK_ProtocolImplementation:
2275 OverrideOrImpl = true;
2279 if (D->hasAttrs()) {
2280 AttrVec &Attrs = D->getAttrs();
2281 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2282 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2288 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2289 if (OldPlatform != Platform) {
2294 // If there is an existing availability attribute for this platform that
2295 // is explicit and the new one is implicit use the explicit one and
2296 // discard the new implicit attribute.
2297 if (!OldAA->isImplicit() && Implicit) {
2301 // If there is an existing attribute for this platform that is implicit
2302 // and the new attribute is explicit then erase the old one and
2303 // continue processing the attributes.
2304 if (!Implicit && OldAA->isImplicit()) {
2305 Attrs.erase(Attrs.begin() + i);
2311 VersionTuple OldIntroduced = OldAA->getIntroduced();
2312 VersionTuple OldDeprecated = OldAA->getDeprecated();
2313 VersionTuple OldObsoleted = OldAA->getObsoleted();
2314 bool OldIsUnavailable = OldAA->getUnavailable();
2316 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2317 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2318 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2319 !(OldIsUnavailable == IsUnavailable ||
2320 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2321 if (OverrideOrImpl) {
2323 VersionTuple FirstVersion;
2324 VersionTuple SecondVersion;
2325 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2327 FirstVersion = OldIntroduced;
2328 SecondVersion = Introduced;
2329 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2331 FirstVersion = Deprecated;
2332 SecondVersion = OldDeprecated;
2333 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2335 FirstVersion = Obsoleted;
2336 SecondVersion = OldObsoleted;
2340 Diag(OldAA->getLocation(),
2341 diag::warn_mismatched_availability_override_unavail)
2342 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2343 << (AMK == AMK_Override);
2345 Diag(OldAA->getLocation(),
2346 diag::warn_mismatched_availability_override)
2348 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2349 << FirstVersion.getAsString() << SecondVersion.getAsString()
2350 << (AMK == AMK_Override);
2352 if (AMK == AMK_Override)
2353 Diag(Range.getBegin(), diag::note_overridden_method);
2355 Diag(Range.getBegin(), diag::note_protocol_method);
2357 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2358 Diag(Range.getBegin(), diag::note_previous_attribute);
2361 Attrs.erase(Attrs.begin() + i);
2366 VersionTuple MergedIntroduced2 = MergedIntroduced;
2367 VersionTuple MergedDeprecated2 = MergedDeprecated;
2368 VersionTuple MergedObsoleted2 = MergedObsoleted;
2370 if (MergedIntroduced2.empty())
2371 MergedIntroduced2 = OldIntroduced;
2372 if (MergedDeprecated2.empty())
2373 MergedDeprecated2 = OldDeprecated;
2374 if (MergedObsoleted2.empty())
2375 MergedObsoleted2 = OldObsoleted;
2377 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2378 MergedIntroduced2, MergedDeprecated2,
2379 MergedObsoleted2)) {
2380 Attrs.erase(Attrs.begin() + i);
2385 MergedIntroduced = MergedIntroduced2;
2386 MergedDeprecated = MergedDeprecated2;
2387 MergedObsoleted = MergedObsoleted2;
2393 MergedIntroduced == Introduced &&
2394 MergedDeprecated == Deprecated &&
2395 MergedObsoleted == Obsoleted)
2398 // Only create a new attribute if !OverrideOrImpl, but we want to do
2400 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2401 MergedDeprecated, MergedObsoleted) &&
2403 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2404 Introduced, Deprecated,
2405 Obsoleted, IsUnavailable, Message,
2406 IsStrict, Replacement,
2407 AttrSpellingListIndex);
2408 Avail->setImplicit(Implicit);
2414 static void handleAvailabilityAttr(Sema &S, Decl *D,
2415 const AttributeList &Attr) {
2416 if (!checkAttributeNumArgs(S, Attr, 1))
2418 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2419 unsigned Index = Attr.getAttributeSpellingListIndex();
2421 IdentifierInfo *II = Platform->Ident;
2422 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2423 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2426 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2427 if (!ND) // We warned about this already, so just return.
2430 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2431 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2432 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2433 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2434 bool IsStrict = Attr.getStrictLoc().isValid();
2436 if (const StringLiteral *SE =
2437 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2438 Str = SE->getString();
2439 StringRef Replacement;
2440 if (const StringLiteral *SE =
2441 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2442 Replacement = SE->getString();
2444 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2450 IsStrict, Replacement,
2454 D->addAttr(NewAttr);
2456 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2457 // matches before the start of the watchOS platform.
2458 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2459 IdentifierInfo *NewII = nullptr;
2460 if (II->getName() == "ios")
2461 NewII = &S.Context.Idents.get("watchos");
2462 else if (II->getName() == "ios_app_extension")
2463 NewII = &S.Context.Idents.get("watchos_app_extension");
2466 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2467 if (Version.empty())
2469 auto Major = Version.getMajor();
2470 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2471 if (NewMajor >= 2) {
2472 if (Version.getMinor().hasValue()) {
2473 if (Version.getSubminor().hasValue())
2474 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2475 Version.getSubminor().getValue());
2477 return VersionTuple(NewMajor, Version.getMinor().getValue());
2481 return VersionTuple(2, 0);
2484 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2485 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2486 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2488 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2501 D->addAttr(NewAttr);
2503 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2504 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2505 // matches before the start of the tvOS platform.
2506 IdentifierInfo *NewII = nullptr;
2507 if (II->getName() == "ios")
2508 NewII = &S.Context.Idents.get("tvos");
2509 else if (II->getName() == "ios_app_extension")
2510 NewII = &S.Context.Idents.get("tvos_app_extension");
2513 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2526 D->addAttr(NewAttr);
2531 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2532 const AttributeList &Attr) {
2533 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2535 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2536 "Invalid number of arguments in an external_source_symbol attribute");
2539 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2540 Language = SE->getString();
2541 StringRef DefinedIn;
2542 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2543 DefinedIn = SE->getString();
2544 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2546 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2547 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2548 Attr.getAttributeSpellingListIndex()));
2552 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2553 typename T::VisibilityType value,
2554 unsigned attrSpellingListIndex) {
2555 T *existingAttr = D->getAttr<T>();
2557 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2558 if (existingValue == value)
2560 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2561 S.Diag(range.getBegin(), diag::note_previous_attribute);
2564 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2567 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2568 VisibilityAttr::VisibilityType Vis,
2569 unsigned AttrSpellingListIndex) {
2570 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2571 AttrSpellingListIndex);
2574 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2575 TypeVisibilityAttr::VisibilityType Vis,
2576 unsigned AttrSpellingListIndex) {
2577 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2578 AttrSpellingListIndex);
2581 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2582 bool isTypeVisibility) {
2583 // Visibility attributes don't mean anything on a typedef.
2584 if (isa<TypedefNameDecl>(D)) {
2585 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2590 // 'type_visibility' can only go on a type or namespace.
2591 if (isTypeVisibility &&
2592 !(isa<TagDecl>(D) ||
2593 isa<ObjCInterfaceDecl>(D) ||
2594 isa<NamespaceDecl>(D))) {
2595 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2596 << Attr.getName() << ExpectedTypeOrNamespace;
2600 // Check that the argument is a string literal.
2602 SourceLocation LiteralLoc;
2603 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2606 VisibilityAttr::VisibilityType type;
2607 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2608 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2609 << Attr.getName() << TypeStr;
2613 // Complain about attempts to use protected visibility on targets
2614 // (like Darwin) that don't support it.
2615 if (type == VisibilityAttr::Protected &&
2616 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2617 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2618 type = VisibilityAttr::Default;
2621 unsigned Index = Attr.getAttributeSpellingListIndex();
2622 clang::Attr *newAttr;
2623 if (isTypeVisibility) {
2624 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2625 (TypeVisibilityAttr::VisibilityType) type,
2628 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2631 D->addAttr(newAttr);
2634 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2635 const AttributeList &Attr) {
2636 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2637 if (!Attr.isArgIdent(0)) {
2638 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2639 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2643 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2644 ObjCMethodFamilyAttr::FamilyKind F;
2645 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2646 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2651 if (F == ObjCMethodFamilyAttr::OMF_init &&
2652 !method->getReturnType()->isObjCObjectPointerType()) {
2653 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2654 << method->getReturnType();
2655 // Ignore the attribute.
2659 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2661 Attr.getAttributeSpellingListIndex()));
2664 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2665 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2666 QualType T = TD->getUnderlyingType();
2667 if (!T->isCARCBridgableType()) {
2668 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2672 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2673 QualType T = PD->getType();
2674 if (!T->isCARCBridgableType()) {
2675 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2680 // It is okay to include this attribute on properties, e.g.:
2682 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2684 // In this case it follows tradition and suppresses an error in the above
2686 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2688 D->addAttr(::new (S.Context)
2689 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2690 Attr.getAttributeSpellingListIndex()));
2693 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2694 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2695 QualType T = TD->getUnderlyingType();
2696 if (!T->isObjCObjectPointerType()) {
2697 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2701 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2704 D->addAttr(::new (S.Context)
2705 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2706 Attr.getAttributeSpellingListIndex()));
2709 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2710 if (!Attr.isArgIdent(0)) {
2711 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2712 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2716 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2717 BlocksAttr::BlockType type;
2718 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2719 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2720 << Attr.getName() << II;
2724 D->addAttr(::new (S.Context)
2725 BlocksAttr(Attr.getRange(), S.Context, type,
2726 Attr.getAttributeSpellingListIndex()));
2729 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2730 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2731 if (Attr.getNumArgs() > 0) {
2732 Expr *E = Attr.getArgAsExpr(0);
2733 llvm::APSInt Idx(32);
2734 if (E->isTypeDependent() || E->isValueDependent() ||
2735 !E->isIntegerConstantExpr(Idx, S.Context)) {
2736 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2737 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2738 << E->getSourceRange();
2742 if (Idx.isSigned() && Idx.isNegative()) {
2743 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2744 << E->getSourceRange();
2748 sentinel = Idx.getZExtValue();
2751 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2752 if (Attr.getNumArgs() > 1) {
2753 Expr *E = Attr.getArgAsExpr(1);
2754 llvm::APSInt Idx(32);
2755 if (E->isTypeDependent() || E->isValueDependent() ||
2756 !E->isIntegerConstantExpr(Idx, S.Context)) {
2757 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2758 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2759 << E->getSourceRange();
2762 nullPos = Idx.getZExtValue();
2764 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2765 // FIXME: This error message could be improved, it would be nice
2766 // to say what the bounds actually are.
2767 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2768 << E->getSourceRange();
2773 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2774 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2775 if (isa<FunctionNoProtoType>(FT)) {
2776 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2780 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2781 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2784 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2785 if (!MD->isVariadic()) {
2786 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2789 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2790 if (!BD->isVariadic()) {
2791 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2794 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2795 QualType Ty = V->getType();
2796 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2797 const FunctionType *FT = Ty->isFunctionPointerType()
2798 ? D->getFunctionType()
2799 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2800 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2801 int m = Ty->isFunctionPointerType() ? 0 : 1;
2802 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2806 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2807 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2811 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2812 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2815 D->addAttr(::new (S.Context)
2816 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2817 Attr.getAttributeSpellingListIndex()));
2820 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2821 if (D->getFunctionType() &&
2822 D->getFunctionType()->getReturnType()->isVoidType()) {
2823 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2824 << Attr.getName() << 0;
2827 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2828 if (MD->getReturnType()->isVoidType()) {
2829 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2830 << Attr.getName() << 1;
2834 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2835 // about using it as an extension.
2836 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2837 !Attr.getScopeName())
2838 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2840 D->addAttr(::new (S.Context)
2841 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2842 Attr.getAttributeSpellingListIndex()));
2845 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2846 // weak_import only applies to variable & function declarations.
2848 if (!D->canBeWeakImported(isDef)) {
2850 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2852 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2853 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2854 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2855 // Nothing to warn about here.
2857 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2858 << Attr.getName() << ExpectedVariableOrFunction;
2863 D->addAttr(::new (S.Context)
2864 WeakImportAttr(Attr.getRange(), S.Context,
2865 Attr.getAttributeSpellingListIndex()));
2868 // Handles reqd_work_group_size and work_group_size_hint.
2869 template <typename WorkGroupAttr>
2870 static void handleWorkGroupSize(Sema &S, Decl *D,
2871 const AttributeList &Attr) {
2873 for (unsigned i = 0; i < 3; ++i) {
2874 const Expr *E = Attr.getArgAsExpr(i);
2875 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2877 if (WGSize[i] == 0) {
2878 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2879 << Attr.getName() << E->getSourceRange();
2884 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2885 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2886 Existing->getYDim() == WGSize[1] &&
2887 Existing->getZDim() == WGSize[2]))
2888 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2890 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2891 WGSize[0], WGSize[1], WGSize[2],
2892 Attr.getAttributeSpellingListIndex()));
2895 // Handles intel_reqd_sub_group_size.
2896 static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) {
2898 const Expr *E = Attr.getArgAsExpr(0);
2899 if (!checkUInt32Argument(S, Attr, E, SGSize))
2902 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2903 << Attr.getName() << E->getSourceRange();
2907 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2908 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2909 if (Existing && Existing->getSubGroupSize() != SGSize)
2910 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2912 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2913 Attr.getRange(), S.Context, SGSize,
2914 Attr.getAttributeSpellingListIndex()));
2917 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2918 if (!Attr.hasParsedType()) {
2919 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2920 << Attr.getName() << 1;
2924 TypeSourceInfo *ParmTSI = nullptr;
2925 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2926 assert(ParmTSI && "no type source info for attribute argument");
2928 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2929 (ParmType->isBooleanType() ||
2930 !ParmType->isIntegralType(S.getASTContext()))) {
2931 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2936 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2937 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2938 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2943 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2945 Attr.getAttributeSpellingListIndex()));
2948 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2950 unsigned AttrSpellingListIndex) {
2951 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2952 if (ExistingAttr->getName() == Name)
2954 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2955 Diag(Range.getBegin(), diag::note_previous_attribute);
2958 return ::new (Context) SectionAttr(Range, Context, Name,
2959 AttrSpellingListIndex);
2962 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2963 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2964 if (!Error.empty()) {
2965 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2971 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2972 // Make sure that there is a string literal as the sections's single
2975 SourceLocation LiteralLoc;
2976 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2979 if (!S.checkSectionName(LiteralLoc, Str))
2982 // If the target wants to validate the section specifier, make it happen.
2983 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2984 if (!Error.empty()) {
2985 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2990 unsigned Index = Attr.getAttributeSpellingListIndex();
2991 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2993 D->addAttr(NewAttr);
2996 // Check for things we'd like to warn about, no errors or validation for now.
2997 // TODO: Validation should use a backend target library that specifies
2998 // the allowable subtarget features and cpus. We could use something like a
2999 // TargetCodeGenInfo hook here to do validation.
3000 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3001 for (auto Str : {"tune=", "fpmath="})
3002 if (AttrStr.find(Str) != StringRef::npos)
3003 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
3006 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3008 SourceLocation LiteralLoc;
3009 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
3011 S.checkTargetAttr(LiteralLoc, Str);
3012 unsigned Index = Attr.getAttributeSpellingListIndex();
3013 TargetAttr *NewAttr =
3014 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
3015 D->addAttr(NewAttr);
3018 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3019 VarDecl *VD = cast<VarDecl>(D);
3020 if (!VD->hasLocalStorage()) {
3021 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3025 Expr *E = Attr.getArgAsExpr(0);
3026 SourceLocation Loc = E->getExprLoc();
3027 FunctionDecl *FD = nullptr;
3028 DeclarationNameInfo NI;
3030 // gcc only allows for simple identifiers. Since we support more than gcc, we
3031 // will warn the user.
3032 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3033 if (DRE->hasQualifier())
3034 S.Diag(Loc, diag::warn_cleanup_ext);
3035 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3036 NI = DRE->getNameInfo();
3038 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3042 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3043 if (ULE->hasExplicitTemplateArgs())
3044 S.Diag(Loc, diag::warn_cleanup_ext);
3045 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3046 NI = ULE->getNameInfo();
3048 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3050 if (ULE->getType() == S.Context.OverloadTy)
3051 S.NoteAllOverloadCandidates(ULE);
3055 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3059 if (FD->getNumParams() != 1) {
3060 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3065 // We're currently more strict than GCC about what function types we accept.
3066 // If this ever proves to be a problem it should be easy to fix.
3067 QualType Ty = S.Context.getPointerType(VD->getType());
3068 QualType ParamTy = FD->getParamDecl(0)->getType();
3069 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3070 ParamTy, Ty) != Sema::Compatible) {
3071 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3072 << NI.getName() << ParamTy << Ty;
3076 D->addAttr(::new (S.Context)
3077 CleanupAttr(Attr.getRange(), S.Context, FD,
3078 Attr.getAttributeSpellingListIndex()));
3081 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3082 const AttributeList &Attr) {
3083 if (!Attr.isArgIdent(0)) {
3084 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3085 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3089 EnumExtensibilityAttr::Kind ExtensibilityKind;
3090 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3091 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3092 ExtensibilityKind)) {
3093 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3094 << Attr.getName() << II;
3098 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3099 Attr.getRange(), S.Context, ExtensibilityKind,
3100 Attr.getAttributeSpellingListIndex()));
3103 /// Handle __attribute__((format_arg((idx)))) attribute based on
3104 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3105 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3106 Expr *IdxExpr = Attr.getArgAsExpr(0);
3108 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3111 // Make sure the format string is really a string.
3112 QualType Ty = getFunctionOrMethodParamType(D, Idx);
3114 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3115 if (NotNSStringTy &&
3116 !isCFStringType(Ty, S.Context) &&
3117 (!Ty->isPointerType() ||
3118 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3119 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3120 << "a string type" << IdxExpr->getSourceRange()
3121 << getFunctionOrMethodParamRange(D, 0);
3124 Ty = getFunctionOrMethodResultType(D);
3125 if (!isNSStringType(Ty, S.Context) &&
3126 !isCFStringType(Ty, S.Context) &&
3127 (!Ty->isPointerType() ||
3128 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3129 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3130 << (NotNSStringTy ? "string type" : "NSString")
3131 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3135 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3136 // because that has corrected for the implicit this parameter, and is zero-
3137 // based. The attribute expects what the user wrote explicitly.
3139 IdxExpr->EvaluateAsInt(Val, S.Context);
3141 D->addAttr(::new (S.Context)
3142 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3143 Attr.getAttributeSpellingListIndex()));
3146 enum FormatAttrKind {
3155 /// getFormatAttrKind - Map from format attribute names to supported format
3157 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3158 return llvm::StringSwitch<FormatAttrKind>(Format)
3159 // Check for formats that get handled specially.
3160 .Case("NSString", NSStringFormat)
3161 .Case("CFString", CFStringFormat)
3162 .Case("strftime", StrftimeFormat)
3164 // Otherwise, check for supported formats.
3165 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3166 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3167 .Case("kprintf", SupportedFormat) // OpenBSD.
3168 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3169 .Case("os_trace", SupportedFormat)
3170 .Case("os_log", SupportedFormat)
3172 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3173 .Default(InvalidFormat);
3176 /// Handle __attribute__((init_priority(priority))) attributes based on
3177 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3178 static void handleInitPriorityAttr(Sema &S, Decl *D,
3179 const AttributeList &Attr) {
3180 if (!S.getLangOpts().CPlusPlus) {
3181 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3185 if (S.getCurFunctionOrMethodDecl()) {
3186 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3190 QualType T = cast<VarDecl>(D)->getType();
3191 if (S.Context.getAsArrayType(T))
3192 T = S.Context.getBaseElementType(T);
3193 if (!T->getAs<RecordType>()) {
3194 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3199 Expr *E = Attr.getArgAsExpr(0);
3200 uint32_t prioritynum;
3201 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3206 if (prioritynum < 101 || prioritynum > 65535) {
3207 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3208 << E->getSourceRange() << Attr.getName() << 101 << 65535;
3212 D->addAttr(::new (S.Context)
3213 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3214 Attr.getAttributeSpellingListIndex()));
3217 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3218 IdentifierInfo *Format, int FormatIdx,
3220 unsigned AttrSpellingListIndex) {
3221 // Check whether we already have an equivalent format attribute.
3222 for (auto *F : D->specific_attrs<FormatAttr>()) {
3223 if (F->getType() == Format &&
3224 F->getFormatIdx() == FormatIdx &&
3225 F->getFirstArg() == FirstArg) {
3226 // If we don't have a valid location for this attribute, adopt the
3228 if (F->getLocation().isInvalid())
3234 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3235 FirstArg, AttrSpellingListIndex);
3238 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3239 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3240 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3241 if (!Attr.isArgIdent(0)) {
3242 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3243 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3247 // In C++ the implicit 'this' function parameter also counts, and they are
3248 // counted from one.
3249 bool HasImplicitThisParam = isInstanceMethod(D);
3250 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3252 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3253 StringRef Format = II->getName();
3255 if (normalizeName(Format)) {
3256 // If we've modified the string name, we need a new identifier for it.
3257 II = &S.Context.Idents.get(Format);
3260 // Check for supported formats.
3261 FormatAttrKind Kind = getFormatAttrKind(Format);
3263 if (Kind == IgnoredFormat)
3266 if (Kind == InvalidFormat) {
3267 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3268 << Attr.getName() << II->getName();
3272 // checks for the 2nd argument
3273 Expr *IdxExpr = Attr.getArgAsExpr(1);
3275 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3278 if (Idx < 1 || Idx > NumArgs) {
3279 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3280 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3284 // FIXME: Do we need to bounds check?
3285 unsigned ArgIdx = Idx - 1;
3287 if (HasImplicitThisParam) {
3289 S.Diag(Attr.getLoc(),
3290 diag::err_format_attribute_implicit_this_format_string)
3291 << IdxExpr->getSourceRange();
3297 // make sure the format string is really a string
3298 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3300 if (Kind == CFStringFormat) {
3301 if (!isCFStringType(Ty, S.Context)) {
3302 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3303 << "a CFString" << IdxExpr->getSourceRange()
3304 << getFunctionOrMethodParamRange(D, ArgIdx);
3307 } else if (Kind == NSStringFormat) {
3308 // FIXME: do we need to check if the type is NSString*? What are the
3310 if (!isNSStringType(Ty, S.Context)) {
3311 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3312 << "an NSString" << IdxExpr->getSourceRange()
3313 << getFunctionOrMethodParamRange(D, ArgIdx);
3316 } else if (!Ty->isPointerType() ||
3317 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3318 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3319 << "a string type" << IdxExpr->getSourceRange()
3320 << getFunctionOrMethodParamRange(D, ArgIdx);
3324 // check the 3rd argument
3325 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3327 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3330 // check if the function is variadic if the 3rd argument non-zero
3331 if (FirstArg != 0) {
3332 if (isFunctionOrMethodVariadic(D)) {
3333 ++NumArgs; // +1 for ...
3335 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3340 // strftime requires FirstArg to be 0 because it doesn't read from any
3341 // variable the input is just the current time + the format string.
3342 if (Kind == StrftimeFormat) {
3343 if (FirstArg != 0) {
3344 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3345 << FirstArgExpr->getSourceRange();
3348 // if 0 it disables parameter checking (to use with e.g. va_list)
3349 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3350 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3351 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3355 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3357 Attr.getAttributeSpellingListIndex());
3359 D->addAttr(NewAttr);
3362 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3363 const AttributeList &Attr) {
3364 // Try to find the underlying union declaration.
3365 RecordDecl *RD = nullptr;
3366 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3367 if (TD && TD->getUnderlyingType()->isUnionType())
3368 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3370 RD = dyn_cast<RecordDecl>(D);
3372 if (!RD || !RD->isUnion()) {
3373 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3374 << Attr.getName() << ExpectedUnion;
3378 if (!RD->isCompleteDefinition()) {
3379 if (!RD->isBeingDefined())
3380 S.Diag(Attr.getLoc(),
3381 diag::warn_transparent_union_attribute_not_definition);
3385 RecordDecl::field_iterator Field = RD->field_begin(),
3386 FieldEnd = RD->field_end();
3387 if (Field == FieldEnd) {
3388 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3392 FieldDecl *FirstField = *Field;
3393 QualType FirstType = FirstField->getType();
3394 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3395 S.Diag(FirstField->getLocation(),
3396 diag::warn_transparent_union_attribute_floating)
3397 << FirstType->isVectorType() << FirstType;
3401 if (FirstType->isIncompleteType())
3403 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3404 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3405 for (; Field != FieldEnd; ++Field) {
3406 QualType FieldType = Field->getType();
3407 if (FieldType->isIncompleteType())
3409 // FIXME: this isn't fully correct; we also need to test whether the
3410 // members of the union would all have the same calling convention as the
3411 // first member of the union. Checking just the size and alignment isn't
3412 // sufficient (consider structs passed on the stack instead of in registers
3414 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3415 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3416 // Warn if we drop the attribute.
3417 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3418 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3419 : S.Context.getTypeAlign(FieldType);
3420 S.Diag(Field->getLocation(),
3421 diag::warn_transparent_union_attribute_field_size_align)
3422 << isSize << Field->getDeclName() << FieldBits;
3423 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3424 S.Diag(FirstField->getLocation(),
3425 diag::note_transparent_union_first_field_size_align)
3426 << isSize << FirstBits;
3431 RD->addAttr(::new (S.Context)
3432 TransparentUnionAttr(Attr.getRange(), S.Context,
3433 Attr.getAttributeSpellingListIndex()));
3436 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3437 // Make sure that there is a string literal as the annotation's single
3440 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3443 // Don't duplicate annotations that are already set.
3444 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3445 if (I->getAnnotation() == Str)
3449 D->addAttr(::new (S.Context)
3450 AnnotateAttr(Attr.getRange(), S.Context, Str,
3451 Attr.getAttributeSpellingListIndex()));
3454 static void handleAlignValueAttr(Sema &S, Decl *D,
3455 const AttributeList &Attr) {
3456 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3457 Attr.getAttributeSpellingListIndex());
3460 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3461 unsigned SpellingListIndex) {
3462 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3463 SourceLocation AttrLoc = AttrRange.getBegin();
3466 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3467 T = TD->getUnderlyingType();
3468 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3471 llvm_unreachable("Unknown decl type for align_value");
3473 if (!T->isDependentType() && !T->isAnyPointerType() &&
3474 !T->isReferenceType() && !T->isMemberPointerType()) {
3475 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3476 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3480 if (!E->isValueDependent()) {
3481 llvm::APSInt Alignment;
3483 = VerifyIntegerConstantExpression(E, &Alignment,
3484 diag::err_align_value_attribute_argument_not_int,
3485 /*AllowFold*/ false);
3486 if (ICE.isInvalid())
3489 if (!Alignment.isPowerOf2()) {
3490 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3491 << E->getSourceRange();
3495 D->addAttr(::new (Context)
3496 AlignValueAttr(AttrRange, Context, ICE.get(),
3497 SpellingListIndex));
3501 // Save dependent expressions in the AST to be instantiated.
3502 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3505 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3506 // check the attribute arguments.
3507 if (Attr.getNumArgs() > 1) {
3508 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3509 << Attr.getName() << 1;
3513 if (Attr.getNumArgs() == 0) {
3514 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3515 true, nullptr, Attr.getAttributeSpellingListIndex()));
3519 Expr *E = Attr.getArgAsExpr(0);
3520 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3521 S.Diag(Attr.getEllipsisLoc(),
3522 diag::err_pack_expansion_without_parameter_packs);
3526 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3529 if (E->isValueDependent()) {
3530 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3531 if (!TND->getUnderlyingType()->isDependentType()) {
3532 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3533 << E->getSourceRange();
3539 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3540 Attr.isPackExpansion());
3543 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3544 unsigned SpellingListIndex, bool IsPackExpansion) {
3545 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3546 SourceLocation AttrLoc = AttrRange.getBegin();
3548 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3549 if (TmpAttr.isAlignas()) {
3550 // C++11 [dcl.align]p1:
3551 // An alignment-specifier may be applied to a variable or to a class
3552 // data member, but it shall not be applied to a bit-field, a function
3553 // parameter, the formal parameter of a catch clause, or a variable
3554 // declared with the register storage class specifier. An
3555 // alignment-specifier may also be applied to the declaration of a class
3556 // or enumeration type.
3558 // An alignment attribute shall not be specified in a declaration of
3559 // a typedef, or a bit-field, or a function, or a parameter, or an
3560 // object declared with the register storage-class specifier.
3562 if (isa<ParmVarDecl>(D)) {
3564 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3565 if (VD->getStorageClass() == SC_Register)
3567 if (VD->isExceptionVariable())
3569 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3570 if (FD->isBitField())
3572 } else if (!isa<TagDecl>(D)) {
3573 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3574 << (TmpAttr.isC11() ? ExpectedVariableOrField
3575 : ExpectedVariableFieldOrTag);
3578 if (DiagKind != -1) {
3579 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3580 << &TmpAttr << DiagKind;
3585 if (E->isTypeDependent() || E->isValueDependent()) {
3586 // Save dependent expressions in the AST to be instantiated.
3587 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3588 AA->setPackExpansion(IsPackExpansion);
3593 // FIXME: Cache the number on the Attr object?
3594 llvm::APSInt Alignment;
3596 = VerifyIntegerConstantExpression(E, &Alignment,
3597 diag::err_aligned_attribute_argument_not_int,
3598 /*AllowFold*/ false);
3599 if (ICE.isInvalid())
3602 uint64_t AlignVal = Alignment.getZExtValue();
3604 // C++11 [dcl.align]p2:
3605 // -- if the constant expression evaluates to zero, the alignment
3606 // specifier shall have no effect
3608 // An alignment specification of zero has no effect.
3609 if (!(TmpAttr.isAlignas() && !Alignment)) {
3610 if (!llvm::isPowerOf2_64(AlignVal)) {
3611 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3612 << E->getSourceRange();
3617 // Alignment calculations can wrap around if it's greater than 2**28.
3618 unsigned MaxValidAlignment =
3619 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3621 if (AlignVal > MaxValidAlignment) {
3622 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3623 << E->getSourceRange();
3627 if (Context.getTargetInfo().isTLSSupported()) {
3628 unsigned MaxTLSAlign =
3629 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3631 auto *VD = dyn_cast<VarDecl>(D);
3632 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3633 VD->getTLSKind() != VarDecl::TLS_None) {
3634 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3635 << (unsigned)AlignVal << VD << MaxTLSAlign;
3640 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3641 ICE.get(), SpellingListIndex);
3642 AA->setPackExpansion(IsPackExpansion);
3646 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3647 unsigned SpellingListIndex, bool IsPackExpansion) {
3648 // FIXME: Cache the number on the Attr object if non-dependent?
3649 // FIXME: Perform checking of type validity
3650 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3652 AA->setPackExpansion(IsPackExpansion);
3656 void Sema::CheckAlignasUnderalignment(Decl *D) {
3657 assert(D->hasAttrs() && "no attributes on decl");
3659 QualType UnderlyingTy, DiagTy;
3660 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3661 UnderlyingTy = DiagTy = VD->getType();
3663 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3664 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3665 UnderlyingTy = ED->getIntegerType();
3667 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3670 // C++11 [dcl.align]p5, C11 6.7.5/4:
3671 // The combined effect of all alignment attributes in a declaration shall
3672 // not specify an alignment that is less strict than the alignment that
3673 // would otherwise be required for the entity being declared.
3674 AlignedAttr *AlignasAttr = nullptr;
3676 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3677 if (I->isAlignmentDependent())
3681 Align = std::max(Align, I->getAlignment(Context));
3684 if (AlignasAttr && Align) {
3685 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3686 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3687 if (NaturalAlign > RequestedAlign)
3688 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3689 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3693 bool Sema::checkMSInheritanceAttrOnDefinition(
3694 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3695 MSInheritanceAttr::Spelling SemanticSpelling) {
3696 assert(RD->hasDefinition() && "RD has no definition!");
3698 // We may not have seen base specifiers or any virtual methods yet. We will
3699 // have to wait until the record is defined to catch any mismatches.
3700 if (!RD->getDefinition()->isCompleteDefinition())
3703 // The unspecified model never matches what a definition could need.
3704 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3708 if (RD->calculateInheritanceModel() == SemanticSpelling)
3711 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3715 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3716 << 0 /*definition*/;
3717 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3718 << RD->getNameAsString();
3722 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3724 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3725 bool &IntegerMode, bool &ComplexMode) {
3727 ComplexMode = false;
3728 switch (Str.size()) {
3750 if (Str[1] == 'F') {
3751 IntegerMode = false;
3752 } else if (Str[1] == 'C') {
3753 IntegerMode = false;
3755 } else if (Str[1] != 'I') {
3760 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3761 // pointer on PIC16 and other embedded platforms.
3763 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3764 else if (Str == "byte")
3765 DestWidth = S.Context.getTargetInfo().getCharWidth();
3768 if (Str == "pointer")
3769 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3772 if (Str == "unwind_word")
3773 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3778 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3781 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3782 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3783 /// HImode, not an intermediate pointer.
3784 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3785 // This attribute isn't documented, but glibc uses it. It changes
3786 // the width of an int or unsigned int to the specified size.
3787 if (!Attr.isArgIdent(0)) {
3788 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3789 << AANT_ArgumentIdentifier;
3793 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3795 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3798 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3799 unsigned SpellingListIndex, bool InInstantiation) {
3800 StringRef Str = Name->getName();
3802 SourceLocation AttrLoc = AttrRange.getBegin();
3804 unsigned DestWidth = 0;
3805 bool IntegerMode = true;
3806 bool ComplexMode = false;
3807 llvm::APInt VectorSize(64, 0);
3808 if (Str.size() >= 4 && Str[0] == 'V') {
3809 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3810 size_t StrSize = Str.size();
3811 size_t VectorStringLength = 0;
3812 while ((VectorStringLength + 1) < StrSize &&
3813 isdigit(Str[VectorStringLength + 1]))
3814 ++VectorStringLength;
3815 if (VectorStringLength &&
3816 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3817 VectorSize.isPowerOf2()) {
3818 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3819 IntegerMode, ComplexMode);
3820 // Avoid duplicate warning from template instantiation.
3821 if (!InInstantiation)
3822 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3829 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3831 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3832 // and friends, at least with glibc.
3833 // FIXME: Make sure floating-point mappings are accurate
3834 // FIXME: Support XF and TF types
3836 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3841 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3842 OldTy = TD->getUnderlyingType();
3843 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3844 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3845 // Try to get type from enum declaration, default to int.
3846 OldTy = ED->getIntegerType();
3848 OldTy = Context.IntTy;
3850 OldTy = cast<ValueDecl>(D)->getType();
3852 if (OldTy->isDependentType()) {
3853 D->addAttr(::new (Context)
3854 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3858 // Base type can also be a vector type (see PR17453).
3859 // Distinguish between base type and base element type.
3860 QualType OldElemTy = OldTy;
3861 if (const VectorType *VT = OldTy->getAs<VectorType>())
3862 OldElemTy = VT->getElementType();
3864 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3865 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3866 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3867 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3868 VectorSize.getBoolValue()) {
3869 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3872 bool IntegralOrAnyEnumType =
3873 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3875 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3876 !IntegralOrAnyEnumType)
3877 Diag(AttrLoc, diag::err_mode_not_primitive);
3878 else if (IntegerMode) {
3879 if (!IntegralOrAnyEnumType)
3880 Diag(AttrLoc, diag::err_mode_wrong_type);
3881 } else if (ComplexMode) {
3882 if (!OldElemTy->isComplexType())
3883 Diag(AttrLoc, diag::err_mode_wrong_type);
3885 if (!OldElemTy->isFloatingType())
3886 Diag(AttrLoc, diag::err_mode_wrong_type);
3892 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3893 OldElemTy->isSignedIntegerType());
3895 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3897 if (NewElemTy.isNull()) {
3898 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3903 NewElemTy = Context.getComplexType(NewElemTy);
3906 QualType NewTy = NewElemTy;
3907 if (VectorSize.getBoolValue()) {
3908 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3909 VectorType::GenericVector);
3910 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3911 // Complex machine mode does not support base vector types.
3913 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3916 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3917 OldVT->getNumElements() /
3918 Context.getTypeSize(NewElemTy);
3920 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3923 if (NewTy.isNull()) {
3924 Diag(AttrLoc, diag::err_mode_wrong_type);
3928 // Install the new type.
3929 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3930 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3931 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3932 ED->setIntegerType(NewTy);
3934 cast<ValueDecl>(D)->setType(NewTy);
3936 D->addAttr(::new (Context)
3937 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3940 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3941 D->addAttr(::new (S.Context)
3942 NoDebugAttr(Attr.getRange(), S.Context,
3943 Attr.getAttributeSpellingListIndex()));
3946 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3947 IdentifierInfo *Ident,
3948 unsigned AttrSpellingListIndex) {
3949 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3950 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3951 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3955 if (D->hasAttr<AlwaysInlineAttr>())
3958 return ::new (Context) AlwaysInlineAttr(Range, Context,
3959 AttrSpellingListIndex);
3962 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3963 IdentifierInfo *Ident,
3964 unsigned AttrSpellingListIndex) {
3965 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3968 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3971 InternalLinkageAttr *
3972 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3973 IdentifierInfo *Ident,
3974 unsigned AttrSpellingListIndex) {
3975 if (auto VD = dyn_cast<VarDecl>(D)) {
3976 // Attribute applies to Var but not any subclass of it (like ParmVar,
3977 // ImplicitParm or VarTemplateSpecialization).
3978 if (VD->getKind() != Decl::Var) {
3979 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3980 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3981 : ExpectedVariableOrFunction);
3984 // Attribute does not apply to non-static local variables.
3985 if (VD->hasLocalStorage()) {
3986 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3991 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3994 return ::new (Context)
3995 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3998 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3999 unsigned AttrSpellingListIndex) {
4000 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4001 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4002 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4006 if (D->hasAttr<MinSizeAttr>())
4009 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4012 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4013 unsigned AttrSpellingListIndex) {
4014 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4015 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4016 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4017 D->dropAttr<AlwaysInlineAttr>();
4019 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4020 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4021 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4022 D->dropAttr<MinSizeAttr>();
4025 if (D->hasAttr<OptimizeNoneAttr>())
4028 return ::new (Context) OptimizeNoneAttr(Range, Context,
4029 AttrSpellingListIndex);
4032 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4033 const AttributeList &Attr) {
4034 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
4038 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4039 D, Attr.getRange(), Attr.getName(),
4040 Attr.getAttributeSpellingListIndex()))
4044 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4045 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4046 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4047 D->addAttr(MinSize);
4050 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4051 const AttributeList &Attr) {
4052 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4053 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4054 D->addAttr(Optnone);
4057 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4058 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4061 auto *VD = cast<VarDecl>(D);
4062 if (!VD->hasGlobalStorage()) {
4063 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4066 D->addAttr(::new (S.Context) CUDAConstantAttr(
4067 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4070 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4071 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4074 auto *VD = cast<VarDecl>(D);
4075 // extern __shared__ is only allowed on arrays with no length (e.g.
4077 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
4078 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4081 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4082 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4083 << S.CurrentCUDATarget())
4085 D->addAttr(::new (S.Context) CUDASharedAttr(
4086 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4089 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4090 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4092 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4096 FunctionDecl *FD = cast<FunctionDecl>(D);
4097 if (!FD->getReturnType()->isVoidType()) {
4098 SourceRange RTRange = FD->getReturnTypeSourceRange();
4099 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4101 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4105 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4106 if (Method->isInstance()) {
4107 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4111 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4113 // Only warn for "inline" when compiling for host, to cut down on noise.
4114 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4115 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4117 D->addAttr(::new (S.Context)
4118 CUDAGlobalAttr(Attr.getRange(), S.Context,
4119 Attr.getAttributeSpellingListIndex()));
4122 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4123 FunctionDecl *Fn = cast<FunctionDecl>(D);
4124 if (!Fn->isInlineSpecified()) {
4125 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4129 D->addAttr(::new (S.Context)
4130 GNUInlineAttr(Attr.getRange(), S.Context,
4131 Attr.getAttributeSpellingListIndex()));
4134 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4135 if (hasDeclarator(D)) return;
4137 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4138 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4140 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4143 if (!isa<ObjCMethodDecl>(D)) {
4144 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4145 << Attr.getName() << ExpectedFunctionOrMethod;
4149 switch (Attr.getKind()) {
4150 case AttributeList::AT_FastCall:
4151 D->addAttr(::new (S.Context)
4152 FastCallAttr(Attr.getRange(), S.Context,
4153 Attr.getAttributeSpellingListIndex()));
4155 case AttributeList::AT_StdCall:
4156 D->addAttr(::new (S.Context)
4157 StdCallAttr(Attr.getRange(), S.Context,
4158 Attr.getAttributeSpellingListIndex()));
4160 case AttributeList::AT_ThisCall:
4161 D->addAttr(::new (S.Context)
4162 ThisCallAttr(Attr.getRange(), S.Context,
4163 Attr.getAttributeSpellingListIndex()));
4165 case AttributeList::AT_CDecl:
4166 D->addAttr(::new (S.Context)
4167 CDeclAttr(Attr.getRange(), S.Context,
4168 Attr.getAttributeSpellingListIndex()));
4170 case AttributeList::AT_Pascal:
4171 D->addAttr(::new (S.Context)
4172 PascalAttr(Attr.getRange(), S.Context,
4173 Attr.getAttributeSpellingListIndex()));
4175 case AttributeList::AT_SwiftCall:
4176 D->addAttr(::new (S.Context)
4177 SwiftCallAttr(Attr.getRange(), S.Context,
4178 Attr.getAttributeSpellingListIndex()));
4180 case AttributeList::AT_VectorCall:
4181 D->addAttr(::new (S.Context)
4182 VectorCallAttr(Attr.getRange(), S.Context,
4183 Attr.getAttributeSpellingListIndex()));
4185 case AttributeList::AT_MSABI:
4186 D->addAttr(::new (S.Context)
4187 MSABIAttr(Attr.getRange(), S.Context,
4188 Attr.getAttributeSpellingListIndex()));
4190 case AttributeList::AT_SysVABI:
4191 D->addAttr(::new (S.Context)
4192 SysVABIAttr(Attr.getRange(), S.Context,
4193 Attr.getAttributeSpellingListIndex()));
4195 case AttributeList::AT_RegCall:
4196 D->addAttr(::new (S.Context) RegCallAttr(
4197 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4199 case AttributeList::AT_Pcs: {
4200 PcsAttr::PCSType PCS;
4203 PCS = PcsAttr::AAPCS;
4206 PCS = PcsAttr::AAPCS_VFP;
4209 llvm_unreachable("unexpected calling convention in pcs attribute");
4212 D->addAttr(::new (S.Context)
4213 PcsAttr(Attr.getRange(), S.Context, PCS,
4214 Attr.getAttributeSpellingListIndex()));
4217 case AttributeList::AT_IntelOclBicc:
4218 D->addAttr(::new (S.Context)
4219 IntelOclBiccAttr(Attr.getRange(), S.Context,
4220 Attr.getAttributeSpellingListIndex()));
4222 case AttributeList::AT_PreserveMost:
4223 D->addAttr(::new (S.Context) PreserveMostAttr(
4224 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4226 case AttributeList::AT_PreserveAll:
4227 D->addAttr(::new (S.Context) PreserveAllAttr(
4228 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4231 llvm_unreachable("unexpected attribute kind");
4235 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4236 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4239 std::vector<StringRef> DiagnosticIdentifiers;
4240 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4243 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4246 // FIXME: Warn if the rule name is unknown. This is tricky because only
4247 // clang-tidy knows about available rules.
4248 DiagnosticIdentifiers.push_back(RuleName);
4250 D->addAttr(::new (S.Context) SuppressAttr(
4251 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4252 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4255 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4256 const FunctionDecl *FD) {
4257 if (attr.isInvalid())
4260 if (attr.hasProcessingCache()) {
4261 CC = (CallingConv) attr.getProcessingCache();
4265 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4266 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
4271 // TODO: diagnose uses of these conventions on the wrong target.
4272 switch (attr.getKind()) {
4273 case AttributeList::AT_CDecl: CC = CC_C; break;
4274 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4275 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4276 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4277 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4278 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4279 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4280 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4281 case AttributeList::AT_MSABI:
4282 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4285 case AttributeList::AT_SysVABI:
4286 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4289 case AttributeList::AT_Pcs: {
4291 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4295 if (StrRef == "aapcs") {
4298 } else if (StrRef == "aapcs-vfp") {
4304 Diag(attr.getLoc(), diag::err_invalid_pcs);
4307 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4308 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4309 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4310 default: llvm_unreachable("unexpected attribute kind");
4313 const TargetInfo &TI = Context.getTargetInfo();
4314 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4315 if (A != TargetInfo::CCCR_OK) {
4316 if (A == TargetInfo::CCCR_Warning)
4317 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4319 // This convention is not valid for the target. Use the default function or
4320 // method calling convention.
4321 bool IsCXXMethod = false, IsVariadic = false;
4323 IsCXXMethod = FD->isCXXInstanceMember();
4324 IsVariadic = FD->isVariadic();
4326 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4329 attr.setProcessingCache((unsigned) CC);
4333 /// Pointer-like types in the default address space.
4334 static bool isValidSwiftContextType(QualType type) {
4335 if (!type->hasPointerRepresentation())
4336 return type->isDependentType();
4337 return type->getPointeeType().getAddressSpace() == 0;
4340 /// Pointers and references in the default address space.
4341 static bool isValidSwiftIndirectResultType(QualType type) {
4342 if (auto ptrType = type->getAs<PointerType>()) {
4343 type = ptrType->getPointeeType();
4344 } else if (auto refType = type->getAs<ReferenceType>()) {
4345 type = refType->getPointeeType();
4347 return type->isDependentType();
4349 return type.getAddressSpace() == 0;
4352 /// Pointers and references to pointers in the default address space.
4353 static bool isValidSwiftErrorResultType(QualType type) {
4354 if (auto ptrType = type->getAs<PointerType>()) {
4355 type = ptrType->getPointeeType();
4356 } else if (auto refType = type->getAs<ReferenceType>()) {
4357 type = refType->getPointeeType();
4359 return type->isDependentType();
4361 if (!type.getQualifiers().empty())
4363 return isValidSwiftContextType(type);
4366 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4368 S.AddParameterABIAttr(attr.getRange(), D, abi,
4369 attr.getAttributeSpellingListIndex());
4372 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4373 unsigned spellingIndex) {
4375 QualType type = cast<ParmVarDecl>(D)->getType();
4377 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4378 if (existingAttr->getABI() != abi) {
4379 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4380 << getParameterABISpelling(abi) << existingAttr;
4381 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4387 case ParameterABI::Ordinary:
4388 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4390 case ParameterABI::SwiftContext:
4391 if (!isValidSwiftContextType(type)) {
4392 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4393 << getParameterABISpelling(abi)
4394 << /*pointer to pointer */ 0 << type;
4396 D->addAttr(::new (Context)
4397 SwiftContextAttr(range, Context, spellingIndex));
4400 case ParameterABI::SwiftErrorResult:
4401 if (!isValidSwiftErrorResultType(type)) {
4402 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4403 << getParameterABISpelling(abi)
4404 << /*pointer to pointer */ 1 << type;
4406 D->addAttr(::new (Context)
4407 SwiftErrorResultAttr(range, Context, spellingIndex));
4410 case ParameterABI::SwiftIndirectResult:
4411 if (!isValidSwiftIndirectResultType(type)) {
4412 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4413 << getParameterABISpelling(abi)
4414 << /*pointer*/ 0 << type;
4416 D->addAttr(::new (Context)
4417 SwiftIndirectResultAttr(range, Context, spellingIndex));
4420 llvm_unreachable("bad parameter ABI attribute");
4423 /// Checks a regparm attribute, returning true if it is ill-formed and
4424 /// otherwise setting numParams to the appropriate value.
4425 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4426 if (Attr.isInvalid())
4429 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4435 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4436 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4441 if (Context.getTargetInfo().getRegParmMax() == 0) {
4442 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4443 << NumParamsExpr->getSourceRange();
4449 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4450 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4451 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4459 // Checks whether an argument of launch_bounds attribute is
4460 // acceptable, performs implicit conversion to Rvalue, and returns
4461 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4462 // and may output an error.
4463 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4464 const CUDALaunchBoundsAttr &Attr,
4465 const unsigned Idx) {
4466 if (S.DiagnoseUnexpandedParameterPack(E))
4469 // Accept template arguments for now as they depend on something else.
4470 // We'll get to check them when they eventually get instantiated.
4471 if (E->isValueDependent())
4475 if (!E->isIntegerConstantExpr(I, S.Context)) {
4476 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4477 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4480 // Make sure we can fit it in 32 bits.
4481 if (!I.isIntN(32)) {
4482 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4483 << 32 << /* Unsigned */ 1;
4487 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4488 << &Attr << Idx << E->getSourceRange();
4490 // We may need to perform implicit conversion of the argument.
4491 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4492 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4493 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4494 assert(!ValArg.isInvalid() &&
4495 "Unexpected PerformCopyInitialization() failure.");
4497 return ValArg.getAs<Expr>();
4500 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4501 Expr *MinBlocks, unsigned SpellingListIndex) {
4502 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4504 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4505 if (MaxThreads == nullptr)
4509 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4510 if (MinBlocks == nullptr)
4514 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4515 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4518 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4519 const AttributeList &Attr) {
4520 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4521 !checkAttributeAtMostNumArgs(S, Attr, 2))
4524 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4525 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4526 Attr.getAttributeSpellingListIndex());
4529 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4530 const AttributeList &Attr) {
4531 if (!Attr.isArgIdent(0)) {
4532 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4533 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4537 if (!checkAttributeNumArgs(S, Attr, 3))
4540 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4542 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4543 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4544 << Attr.getName() << ExpectedFunctionOrMethod;
4548 uint64_t ArgumentIdx;
4549 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4553 uint64_t TypeTagIdx;
4554 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4558 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4560 // Ensure that buffer has a pointer type.
4561 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4562 if (!BufferTy->isPointerType()) {
4563 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4564 << Attr.getName() << 0;
4568 D->addAttr(::new (S.Context)
4569 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4570 ArgumentIdx, TypeTagIdx, IsPointer,
4571 Attr.getAttributeSpellingListIndex()));
4574 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4575 const AttributeList &Attr) {
4576 if (!Attr.isArgIdent(0)) {
4577 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4578 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4582 if (!checkAttributeNumArgs(S, Attr, 1))
4585 if (!isa<VarDecl>(D)) {
4586 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4587 << Attr.getName() << ExpectedVariable;
4591 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4592 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4593 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4594 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4596 D->addAttr(::new (S.Context)
4597 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4599 Attr.getLayoutCompatible(),
4600 Attr.getMustBeNull(),
4601 Attr.getAttributeSpellingListIndex()));
4604 static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4605 const AttributeList &Attr) {
4607 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4611 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4612 D->addAttr(::new (S.Context)
4613 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4614 Attr.getAttributeSpellingListIndex()));
4617 //===----------------------------------------------------------------------===//
4618 // Checker-specific attribute handlers.
4619 //===----------------------------------------------------------------------===//
4621 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4622 return type->isDependentType() ||
4623 type->isObjCRetainableType();
4626 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4627 return type->isDependentType() ||
4628 type->isObjCObjectPointerType() ||
4629 S.Context.isObjCNSObjectType(type);
4632 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4633 return type->isDependentType() ||
4634 type->isPointerType() ||
4635 isValidSubjectOfNSAttribute(S, type);
4638 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4639 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4640 Attr.getKind() == AttributeList::AT_NSConsumed,
4641 /*template instantiation*/ false);
4644 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4645 unsigned spellingIndex, bool isNSConsumed,
4646 bool isTemplateInstantiation) {
4647 ParmVarDecl *param = cast<ParmVarDecl>(D);
4651 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4653 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4657 // These attributes are normally just advisory, but in ARC, ns_consumed
4658 // is significant. Allow non-dependent code to contain inappropriate
4659 // attributes even in ARC, but require template instantiations to be
4660 // set up correctly.
4661 Diag(D->getLocStart(),
4662 (isTemplateInstantiation && isNSConsumed &&
4663 getLangOpts().ObjCAutoRefCount
4664 ? diag::err_ns_attribute_wrong_parameter_type
4665 : diag::warn_ns_attribute_wrong_parameter_type))
4667 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4668 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4673 param->addAttr(::new (Context)
4674 NSConsumedAttr(attrRange, Context, spellingIndex));
4676 param->addAttr(::new (Context)
4677 CFConsumedAttr(attrRange, Context, spellingIndex));
4680 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4681 const AttributeList &Attr) {
4682 QualType returnType;
4684 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4685 returnType = MD->getReturnType();
4686 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4687 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4688 return; // ignore: was handled as a type attribute
4689 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4690 returnType = PD->getType();
4691 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4692 returnType = FD->getReturnType();
4693 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4694 returnType = Param->getType()->getPointeeType();
4695 if (returnType.isNull()) {
4696 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4697 << Attr.getName() << /*pointer-to-CF*/2
4702 AttributeDeclKind ExpectedDeclKind;
4703 switch (Attr.getKind()) {
4704 default: llvm_unreachable("invalid ownership attribute");
4705 case AttributeList::AT_NSReturnsRetained:
4706 case AttributeList::AT_NSReturnsAutoreleased:
4707 case AttributeList::AT_NSReturnsNotRetained:
4708 ExpectedDeclKind = ExpectedFunctionOrMethod;
4711 case AttributeList::AT_CFReturnsRetained:
4712 case AttributeList::AT_CFReturnsNotRetained:
4713 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4716 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4717 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4723 switch (Attr.getKind()) {
4724 default: llvm_unreachable("invalid ownership attribute");
4725 case AttributeList::AT_NSReturnsRetained:
4726 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4730 case AttributeList::AT_NSReturnsAutoreleased:
4731 case AttributeList::AT_NSReturnsNotRetained:
4732 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4736 case AttributeList::AT_CFReturnsRetained:
4737 case AttributeList::AT_CFReturnsNotRetained:
4738 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4744 if (isa<ParmVarDecl>(D)) {
4745 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4746 << Attr.getName() << /*pointer-to-CF*/2
4749 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4754 } SubjectKind = Function;
4755 if (isa<ObjCMethodDecl>(D))
4756 SubjectKind = Method;
4757 else if (isa<ObjCPropertyDecl>(D))
4758 SubjectKind = Property;
4759 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4760 << Attr.getName() << SubjectKind << cf
4766 switch (Attr.getKind()) {
4768 llvm_unreachable("invalid ownership attribute");
4769 case AttributeList::AT_NSReturnsAutoreleased:
4770 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4771 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4773 case AttributeList::AT_CFReturnsNotRetained:
4774 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4775 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4777 case AttributeList::AT_NSReturnsNotRetained:
4778 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4779 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4781 case AttributeList::AT_CFReturnsRetained:
4782 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4783 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4785 case AttributeList::AT_NSReturnsRetained:
4786 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4787 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4792 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4793 const AttributeList &attr) {
4794 const int EP_ObjCMethod = 1;
4795 const int EP_ObjCProperty = 2;
4797 SourceLocation loc = attr.getLoc();
4798 QualType resultType;
4799 if (isa<ObjCMethodDecl>(D))
4800 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4802 resultType = cast<ObjCPropertyDecl>(D)->getType();
4804 if (!resultType->isReferenceType() &&
4805 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4806 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4809 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4810 << /*non-retainable pointer*/ 2;
4812 // Drop the attribute.
4816 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4817 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4820 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4821 const AttributeList &attr) {
4822 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4824 DeclContext *DC = method->getDeclContext();
4825 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4826 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4827 << attr.getName() << 0;
4828 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4831 if (method->getMethodFamily() == OMF_dealloc) {
4832 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4833 << attr.getName() << 1;
4837 method->addAttr(::new (S.Context)
4838 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4839 attr.getAttributeSpellingListIndex()));
4842 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4843 const AttributeList &Attr) {
4844 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4848 D->addAttr(::new (S.Context)
4849 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4850 Attr.getAttributeSpellingListIndex()));
4853 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4854 const AttributeList &Attr) {
4855 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4859 D->addAttr(::new (S.Context)
4860 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4861 Attr.getAttributeSpellingListIndex()));
4864 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4865 const AttributeList &Attr) {
4866 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4869 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4873 // Typedefs only allow objc_bridge(id) and have some additional checking.
4874 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4875 if (!Parm->Ident->isStr("id")) {
4876 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4881 // Only allow 'cv void *'.
4882 QualType T = TD->getUnderlyingType();
4883 if (!T->isVoidPointerType()) {
4884 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4889 D->addAttr(::new (S.Context)
4890 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4891 Attr.getAttributeSpellingListIndex()));
4894 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4895 const AttributeList &Attr) {
4896 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4899 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4903 D->addAttr(::new (S.Context)
4904 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4905 Attr.getAttributeSpellingListIndex()));
4908 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4909 const AttributeList &Attr) {
4910 IdentifierInfo *RelatedClass =
4911 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4912 if (!RelatedClass) {
4913 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4916 IdentifierInfo *ClassMethod =
4917 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4918 IdentifierInfo *InstanceMethod =
4919 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4920 D->addAttr(::new (S.Context)
4921 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4922 ClassMethod, InstanceMethod,
4923 Attr.getAttributeSpellingListIndex()));
4926 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4927 const AttributeList &Attr) {
4928 ObjCInterfaceDecl *IFace;
4929 if (ObjCCategoryDecl *CatDecl =
4930 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4931 IFace = CatDecl->getClassInterface();
4933 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4938 IFace->setHasDesignatedInitializers();
4939 D->addAttr(::new (S.Context)
4940 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4941 Attr.getAttributeSpellingListIndex()));
4944 static void handleObjCRuntimeName(Sema &S, Decl *D,
4945 const AttributeList &Attr) {
4946 StringRef MetaDataName;
4947 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4949 D->addAttr(::new (S.Context)
4950 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4952 Attr.getAttributeSpellingListIndex()));
4955 // When a user wants to use objc_boxable with a union or struct
4956 // but they don't have access to the declaration (legacy/third-party code)
4957 // then they can 'enable' this feature with a typedef:
4958 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4959 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4960 bool notify = false;
4962 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4963 if (RD && RD->getDefinition()) {
4964 RD = RD->getDefinition();
4969 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4970 ObjCBoxableAttr(Attr.getRange(), S.Context,
4971 Attr.getAttributeSpellingListIndex());
4972 RD->addAttr(BoxableAttr);
4974 // we need to notify ASTReader/ASTWriter about
4975 // modification of existing declaration
4976 if (ASTMutationListener *L = S.getASTMutationListener())
4977 L->AddedAttributeToRecord(BoxableAttr, RD);
4982 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4983 const AttributeList &Attr) {
4984 if (hasDeclarator(D)) return;
4986 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4987 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4990 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4991 const AttributeList &Attr) {
4992 ValueDecl *vd = cast<ValueDecl>(D);
4993 QualType type = vd->getType();
4995 if (!type->isDependentType() &&
4996 !type->isObjCLifetimeType()) {
4997 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5002 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5004 // If we have no lifetime yet, check the lifetime we're presumably
5006 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
5007 lifetime = type->getObjCARCImplicitLifetime();
5010 case Qualifiers::OCL_None:
5011 assert(type->isDependentType() &&
5012 "didn't infer lifetime for non-dependent type?");
5015 case Qualifiers::OCL_Weak: // meaningful
5016 case Qualifiers::OCL_Strong: // meaningful
5019 case Qualifiers::OCL_ExplicitNone:
5020 case Qualifiers::OCL_Autoreleasing:
5021 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5022 << (lifetime == Qualifiers::OCL_Autoreleasing);
5026 D->addAttr(::new (S.Context)
5027 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5028 Attr.getAttributeSpellingListIndex()));
5031 //===----------------------------------------------------------------------===//
5032 // Microsoft specific attribute handlers.
5033 //===----------------------------------------------------------------------===//
5035 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5036 unsigned AttrSpellingListIndex, StringRef Uuid) {
5037 if (const auto *UA = D->getAttr<UuidAttr>()) {
5038 if (UA->getGuid().equals_lower(Uuid))
5040 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5041 Diag(Range.getBegin(), diag::note_previous_uuid);
5042 D->dropAttr<UuidAttr>();
5045 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5048 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5049 if (!S.LangOpts.CPlusPlus) {
5050 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5051 << Attr.getName() << AttributeLangSupport::C;
5056 SourceLocation LiteralLoc;
5057 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5060 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5061 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5062 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5063 StrRef = StrRef.drop_front().drop_back();
5065 // Validate GUID length.
5066 if (StrRef.size() != 36) {
5067 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5071 for (unsigned i = 0; i < 36; ++i) {
5072 if (i == 8 || i == 13 || i == 18 || i == 23) {
5073 if (StrRef[i] != '-') {
5074 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5077 } else if (!isHexDigit(StrRef[i])) {
5078 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5083 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5084 // the only thing in the [] list, the [] too), and add an insertion of
5085 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5086 // separating attributes nor of the [ and the ] are in the AST.
5087 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5089 if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5090 S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5092 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5093 Attr.getAttributeSpellingListIndex(), StrRef);
5098 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5099 if (!S.LangOpts.CPlusPlus) {
5100 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5101 << Attr.getName() << AttributeLangSupport::C;
5104 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5105 D, Attr.getRange(), /*BestCase=*/true,
5106 Attr.getAttributeSpellingListIndex(),
5107 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5110 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5114 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5115 const AttributeList &Attr) {
5116 VarDecl *VD = cast<VarDecl>(D);
5117 if (!S.Context.getTargetInfo().isTLSSupported()) {
5118 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5121 if (VD->getTSCSpec() != TSCS_unspecified) {
5122 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5125 if (VD->hasLocalStorage()) {
5126 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5129 VD->addAttr(::new (S.Context) ThreadAttr(
5130 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5133 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5134 SmallVector<StringRef, 4> Tags;
5135 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5137 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5139 Tags.push_back(Tag);
5142 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5143 if (!NS->isInline()) {
5144 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5147 if (NS->isAnonymousNamespace()) {
5148 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5151 if (Attr.getNumArgs() == 0)
5152 Tags.push_back(NS->getName());
5153 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5156 // Store tags sorted and without duplicates.
5157 std::sort(Tags.begin(), Tags.end());
5158 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5160 D->addAttr(::new (S.Context)
5161 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5162 Attr.getAttributeSpellingListIndex()));
5165 static void handleARMInterruptAttr(Sema &S, Decl *D,
5166 const AttributeList &Attr) {
5167 // Check the attribute arguments.
5168 if (Attr.getNumArgs() > 1) {
5169 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5170 << Attr.getName() << 1;
5175 SourceLocation ArgLoc;
5177 if (Attr.getNumArgs() == 0)
5179 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5182 ARMInterruptAttr::InterruptType Kind;
5183 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5184 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5185 << Attr.getName() << Str << ArgLoc;
5189 unsigned Index = Attr.getAttributeSpellingListIndex();
5190 D->addAttr(::new (S.Context)
5191 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5194 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5195 const AttributeList &Attr) {
5196 if (!checkAttributeNumArgs(S, Attr, 1))
5199 if (!Attr.isArgExpr(0)) {
5200 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5201 << AANT_ArgumentIntegerConstant;
5205 // FIXME: Check for decl - it should be void ()(void).
5207 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5208 llvm::APSInt NumParams(32);
5209 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5210 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5211 << Attr.getName() << AANT_ArgumentIntegerConstant
5212 << NumParamsExpr->getSourceRange();
5216 unsigned Num = NumParams.getLimitedValue(255);
5217 if ((Num & 1) || Num > 30) {
5218 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5219 << Attr.getName() << (int)NumParams.getSExtValue()
5220 << NumParamsExpr->getSourceRange();
5224 D->addAttr(::new (S.Context)
5225 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5226 Attr.getAttributeSpellingListIndex()));
5227 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5230 static void handleMipsInterruptAttr(Sema &S, Decl *D,
5231 const AttributeList &Attr) {
5232 // Only one optional argument permitted.
5233 if (Attr.getNumArgs() > 1) {
5234 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5235 << Attr.getName() << 1;
5240 SourceLocation ArgLoc;
5242 if (Attr.getNumArgs() == 0)
5244 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5247 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5248 // a) Must be a function.
5249 // b) Must have no parameters.
5250 // c) Must have the 'void' return type.
5251 // d) Cannot have the 'mips16' attribute, as that instruction set
5252 // lacks the 'eret' instruction.
5253 // e) The attribute itself must either have no argument or one of the
5254 // valid interrupt types, see [MipsInterruptDocs].
5256 if (!isFunctionOrMethod(D)) {
5257 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5258 << "'interrupt'" << ExpectedFunctionOrMethod;
5262 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5263 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5268 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5269 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5274 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5278 MipsInterruptAttr::InterruptType Kind;
5279 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5280 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5281 << Attr.getName() << "'" + std::string(Str) + "'";
5285 D->addAttr(::new (S.Context) MipsInterruptAttr(
5286 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5289 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5290 const AttributeList &Attr) {
5291 // Semantic checks for a function with the 'interrupt' attribute.
5292 // a) Must be a function.
5293 // b) Must have the 'void' return type.
5294 // c) Must take 1 or 2 arguments.
5295 // d) The 1st argument must be a pointer.
5296 // e) The 2nd argument (if any) must be an unsigned integer.
5297 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5298 CXXMethodDecl::isStaticOverloadedOperator(
5299 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5300 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5301 << Attr.getName() << ExpectedFunctionWithProtoType;
5304 // Interrupt handler must have void return type.
5305 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5306 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5307 diag::err_anyx86_interrupt_attribute)
5308 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5314 // Interrupt handler must have 1 or 2 parameters.
5315 unsigned NumParams = getFunctionOrMethodNumParams(D);
5316 if (NumParams < 1 || NumParams > 2) {
5317 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5318 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5324 // The first argument must be a pointer.
5325 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5326 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5327 diag::err_anyx86_interrupt_attribute)
5328 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5334 // The second argument, if present, must be an unsigned integer.
5336 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5339 if (NumParams == 2 &&
5340 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5341 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5342 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5343 diag::err_anyx86_interrupt_attribute)
5344 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5347 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5350 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5351 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5352 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5355 static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5356 if (!isFunctionOrMethod(D)) {
5357 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5358 << "'interrupt'" << ExpectedFunction;
5362 if (!checkAttributeNumArgs(S, Attr, 0))
5365 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5368 static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5369 if (!isFunctionOrMethod(D)) {
5370 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5371 << "'signal'" << ExpectedFunction;
5375 if (!checkAttributeNumArgs(S, Attr, 0))
5378 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5381 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5382 // Dispatch the interrupt attribute based on the current target.
5383 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5384 case llvm::Triple::msp430:
5385 handleMSP430InterruptAttr(S, D, Attr);
5387 case llvm::Triple::mipsel:
5388 case llvm::Triple::mips:
5389 handleMipsInterruptAttr(S, D, Attr);
5391 case llvm::Triple::x86:
5392 case llvm::Triple::x86_64:
5393 handleAnyX86InterruptAttr(S, D, Attr);
5395 case llvm::Triple::avr:
5396 handleAVRInterruptAttr(S, D, Attr);
5399 handleARMInterruptAttr(S, D, Attr);
5404 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5405 const AttributeList &Attr) {
5407 Expr *MinExpr = Attr.getArgAsExpr(0);
5408 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5412 Expr *MaxExpr = Attr.getArgAsExpr(1);
5413 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5416 if (Min == 0 && Max != 0) {
5417 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5418 << Attr.getName() << 0;
5422 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5423 << Attr.getName() << 1;
5427 D->addAttr(::new (S.Context)
5428 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5429 Attr.getAttributeSpellingListIndex()));
5432 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5433 const AttributeList &Attr) {
5435 Expr *MinExpr = Attr.getArgAsExpr(0);
5436 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5440 if (Attr.getNumArgs() == 2) {
5441 Expr *MaxExpr = Attr.getArgAsExpr(1);
5442 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5446 if (Min == 0 && Max != 0) {
5447 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5448 << Attr.getName() << 0;
5451 if (Max != 0 && Min > Max) {
5452 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5453 << Attr.getName() << 1;
5457 D->addAttr(::new (S.Context)
5458 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5459 Attr.getAttributeSpellingListIndex()));
5462 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5463 const AttributeList &Attr) {
5464 uint32_t NumSGPR = 0;
5465 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5466 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5469 D->addAttr(::new (S.Context)
5470 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5471 Attr.getAttributeSpellingListIndex()));
5474 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5475 const AttributeList &Attr) {
5476 uint32_t NumVGPR = 0;
5477 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5478 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5481 D->addAttr(::new (S.Context)
5482 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5483 Attr.getAttributeSpellingListIndex()));
5486 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5487 const AttributeList& Attr) {
5488 // If we try to apply it to a function pointer, don't warn, but don't
5489 // do anything, either. It doesn't matter anyway, because there's nothing
5490 // special about calling a force_align_arg_pointer function.
5491 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5492 if (VD && VD->getType()->isFunctionPointerType())
5494 // Also don't warn on function pointer typedefs.
5495 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5496 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5497 TD->getUnderlyingType()->isFunctionType()))
5499 // Attribute can only be applied to function types.
5500 if (!isa<FunctionDecl>(D)) {
5501 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5502 << Attr.getName() << /* function */0;
5506 D->addAttr(::new (S.Context)
5507 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5508 Attr.getAttributeSpellingListIndex()));
5511 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5513 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5514 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5517 // TODO: Investigate what happens with the next major version of MSVC.
5518 if (Version != LangOptions::MSVC2015) {
5519 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5520 << Attr.getName() << Version << VersionExpr->getSourceRange();
5524 D->addAttr(::new (S.Context)
5525 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5526 Attr.getAttributeSpellingListIndex()));
5529 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5530 unsigned AttrSpellingListIndex) {
5531 if (D->hasAttr<DLLExportAttr>()) {
5532 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5536 if (D->hasAttr<DLLImportAttr>())
5539 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5542 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5543 unsigned AttrSpellingListIndex) {
5544 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5545 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5546 D->dropAttr<DLLImportAttr>();
5549 if (D->hasAttr<DLLExportAttr>())
5552 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5555 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5556 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5557 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5558 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5563 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5564 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5565 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5566 // MinGW doesn't allow dllimport on inline functions.
5567 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5573 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5574 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5575 MD->getParent()->isLambda()) {
5576 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5581 unsigned Index = A.getAttributeSpellingListIndex();
5582 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5583 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5584 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5586 D->addAttr(NewAttr);
5590 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5591 unsigned AttrSpellingListIndex,
5592 MSInheritanceAttr::Spelling SemanticSpelling) {
5593 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5594 if (IA->getSemanticSpelling() == SemanticSpelling)
5596 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5597 << 1 /*previous declaration*/;
5598 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5599 D->dropAttr<MSInheritanceAttr>();
5602 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5603 if (RD->hasDefinition()) {
5604 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5605 SemanticSpelling)) {
5609 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5610 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5611 << 1 /*partial specialization*/;
5614 if (RD->getDescribedClassTemplate()) {
5615 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5616 << 0 /*primary template*/;
5621 return ::new (Context)
5622 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5625 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5626 // The capability attributes take a single string parameter for the name of
5627 // the capability they represent. The lockable attribute does not take any
5628 // parameters. However, semantically, both attributes represent the same
5629 // concept, and so they use the same semantic attribute. Eventually, the
5630 // lockable attribute will be removed.
5632 // For backward compatibility, any capability which has no specified string
5633 // literal will be considered a "mutex."
5634 StringRef N("mutex");
5635 SourceLocation LiteralLoc;
5636 if (Attr.getKind() == AttributeList::AT_Capability &&
5637 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5640 // Currently, there are only two names allowed for a capability: role and
5641 // mutex (case insensitive). Diagnose other capability names.
5642 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5643 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5645 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5646 Attr.getAttributeSpellingListIndex()));
5649 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5650 const AttributeList &Attr) {
5651 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5652 Attr.getArgAsExpr(0),
5653 Attr.getAttributeSpellingListIndex()));
5656 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5657 const AttributeList &Attr) {
5658 SmallVector<Expr*, 1> Args;
5659 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5662 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5664 Args.data(), Args.size(),
5665 Attr.getAttributeSpellingListIndex()));
5668 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5669 const AttributeList &Attr) {
5670 SmallVector<Expr*, 2> Args;
5671 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5674 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5676 Attr.getArgAsExpr(0),
5679 Attr.getAttributeSpellingListIndex()));
5682 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5683 const AttributeList &Attr) {
5684 // Check that all arguments are lockable objects.
5685 SmallVector<Expr *, 1> Args;
5686 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5688 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5689 Attr.getRange(), S.Context, Args.data(), Args.size(),
5690 Attr.getAttributeSpellingListIndex()));
5693 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5694 const AttributeList &Attr) {
5695 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5698 // check that all arguments are lockable objects
5699 SmallVector<Expr*, 1> Args;
5700 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5704 RequiresCapabilityAttr *RCA = ::new (S.Context)
5705 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5706 Args.size(), Attr.getAttributeSpellingListIndex());
5711 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5712 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5713 if (NSD->isAnonymousNamespace()) {
5714 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5715 // Do not want to attach the attribute to the namespace because that will
5716 // cause confusing diagnostic reports for uses of declarations within the
5722 // Handle the cases where the attribute has a text message.
5723 StringRef Str, Replacement;
5724 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5725 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5728 // Only support a single optional message for Declspec and CXX11.
5729 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5730 checkAttributeAtMostNumArgs(S, Attr, 1);
5731 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5732 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5735 if (!S.getLangOpts().CPlusPlus14)
5736 if (Attr.isCXX11Attribute() &&
5737 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5738 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5740 D->addAttr(::new (S.Context)
5741 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5742 Attr.getAttributeSpellingListIndex()));
5745 static bool isGlobalVar(const Decl *D) {
5746 if (const auto *S = dyn_cast<VarDecl>(D))
5747 return S->hasGlobalStorage();
5751 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5752 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5755 std::vector<StringRef> Sanitizers;
5757 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5758 StringRef SanitizerName;
5759 SourceLocation LiteralLoc;
5761 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5764 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5765 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5766 else if (isGlobalVar(D) && SanitizerName != "address")
5767 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5768 << Attr.getName() << ExpectedFunctionOrMethod;
5769 Sanitizers.push_back(SanitizerName);
5772 D->addAttr(::new (S.Context) NoSanitizeAttr(
5773 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5774 Attr.getAttributeSpellingListIndex()));
5777 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5778 const AttributeList &Attr) {
5779 StringRef AttrName = Attr.getName()->getName();
5780 normalizeName(AttrName);
5781 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5782 .Case("no_address_safety_analysis", "address")
5783 .Case("no_sanitize_address", "address")
5784 .Case("no_sanitize_thread", "thread")
5785 .Case("no_sanitize_memory", "memory");
5786 if (isGlobalVar(D) && SanitizerName != "address")
5787 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5788 << Attr.getName() << ExpectedFunction;
5789 D->addAttr(::new (S.Context)
5790 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5791 Attr.getAttributeSpellingListIndex()));
5794 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5795 const AttributeList &Attr) {
5796 if (InternalLinkageAttr *Internal =
5797 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5798 Attr.getAttributeSpellingListIndex()))
5799 D->addAttr(Internal);
5802 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5803 if (S.LangOpts.OpenCLVersion != 200)
5804 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5805 << Attr.getName() << "2.0" << 0;
5807 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5808 << Attr.getName() << "2.0";
5811 /// Handles semantic checking for features that are common to all attributes,
5812 /// such as checking whether a parameter was properly specified, or the correct
5813 /// number of arguments were passed, etc.
5814 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5815 const AttributeList &Attr) {
5816 // Several attributes carry different semantics than the parsing requires, so
5817 // those are opted out of the common argument checks.
5819 // We also bail on unknown and ignored attributes because those are handled
5820 // as part of the target-specific handling logic.
5821 if (Attr.getKind() == AttributeList::UnknownAttribute)
5823 // Check whether the attribute requires specific language extensions to be
5825 if (!Attr.diagnoseLangOpts(S))
5827 // Check whether the attribute appertains to the given subject.
5828 if (!Attr.diagnoseAppertainsTo(S, D))
5830 if (Attr.hasCustomParsing())
5833 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5834 // If there are no optional arguments, then checking for the argument count
5836 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5839 // There are optional arguments, so checking is slightly more involved.
5840 if (Attr.getMinArgs() &&
5841 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5843 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5844 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5851 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5852 const AttributeList &Attr) {
5853 if (D->isInvalidDecl())
5856 // Check if there is only one access qualifier.
5857 if (D->hasAttr<OpenCLAccessAttr>()) {
5858 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5859 << D->getSourceRange();
5860 D->setInvalidDecl(true);
5864 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5865 // image object can be read and written.
5866 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5867 // object. Using the read_write (or __read_write) qualifier with the pipe
5868 // qualifier is a compilation error.
5869 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5870 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5871 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5872 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5873 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5874 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5875 D->setInvalidDecl(true);
5881 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5882 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5885 //===----------------------------------------------------------------------===//
5886 // Top Level Sema Entry Points
5887 //===----------------------------------------------------------------------===//
5889 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5890 /// the attribute applies to decls. If the attribute is a type attribute, just
5891 /// silently ignore it if a GNU attribute.
5892 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5893 const AttributeList &Attr,
5894 bool IncludeCXX11Attributes) {
5895 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5898 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5900 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5903 // Unknown attributes are automatically warned on. Target-specific attributes
5904 // which do not apply to the current target architecture are treated as
5905 // though they were unknown attributes.
5906 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5907 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5908 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5909 ? diag::warn_unhandled_ms_attribute_ignored
5910 : diag::warn_unknown_attribute_ignored)
5915 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5918 switch (Attr.getKind()) {
5920 if (!Attr.isStmtAttr()) {
5921 // Type attributes are handled elsewhere; silently move on.
5922 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5925 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5926 << Attr.getName() << D->getLocation();
5928 case AttributeList::AT_Interrupt:
5929 handleInterruptAttr(S, D, Attr);
5931 case AttributeList::AT_X86ForceAlignArgPointer:
5932 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5934 case AttributeList::AT_DLLExport:
5935 case AttributeList::AT_DLLImport:
5936 handleDLLAttr(S, D, Attr);
5938 case AttributeList::AT_Mips16:
5939 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
5940 MipsInterruptAttr>(S, D, Attr);
5942 case AttributeList::AT_NoMips16:
5943 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5945 case AttributeList::AT_MicroMips:
5946 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, Attr);
5948 case AttributeList::AT_NoMicroMips:
5949 handleSimpleAttribute<NoMicroMipsAttr>(S, D, Attr);
5951 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5952 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5954 case AttributeList::AT_AMDGPUWavesPerEU:
5955 handleAMDGPUWavesPerEUAttr(S, D, Attr);
5957 case AttributeList::AT_AMDGPUNumSGPR:
5958 handleAMDGPUNumSGPRAttr(S, D, Attr);
5960 case AttributeList::AT_AMDGPUNumVGPR:
5961 handleAMDGPUNumVGPRAttr(S, D, Attr);
5963 case AttributeList::AT_AVRSignal:
5964 handleAVRSignalAttr(S, D, Attr);
5966 case AttributeList::AT_IBAction:
5967 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5969 case AttributeList::AT_IBOutlet:
5970 handleIBOutlet(S, D, Attr);
5972 case AttributeList::AT_IBOutletCollection:
5973 handleIBOutletCollection(S, D, Attr);
5975 case AttributeList::AT_IFunc:
5976 handleIFuncAttr(S, D, Attr);
5978 case AttributeList::AT_Alias:
5979 handleAliasAttr(S, D, Attr);
5981 case AttributeList::AT_Aligned:
5982 handleAlignedAttr(S, D, Attr);
5984 case AttributeList::AT_AlignValue:
5985 handleAlignValueAttr(S, D, Attr);
5987 case AttributeList::AT_AllocSize:
5988 handleAllocSizeAttr(S, D, Attr);
5990 case AttributeList::AT_AlwaysInline:
5991 handleAlwaysInlineAttr(S, D, Attr);
5993 case AttributeList::AT_AnalyzerNoReturn:
5994 handleAnalyzerNoReturnAttr(S, D, Attr);
5996 case AttributeList::AT_TLSModel:
5997 handleTLSModelAttr(S, D, Attr);
5999 case AttributeList::AT_Annotate:
6000 handleAnnotateAttr(S, D, Attr);
6002 case AttributeList::AT_Availability:
6003 handleAvailabilityAttr(S, D, Attr);
6005 case AttributeList::AT_CarriesDependency:
6006 handleDependencyAttr(S, scope, D, Attr);
6008 case AttributeList::AT_Common:
6009 handleCommonAttr(S, D, Attr);
6011 case AttributeList::AT_CUDAConstant:
6012 handleConstantAttr(S, D, Attr);
6014 case AttributeList::AT_PassObjectSize:
6015 handlePassObjectSizeAttr(S, D, Attr);
6017 case AttributeList::AT_Constructor:
6018 handleConstructorAttr(S, D, Attr);
6020 case AttributeList::AT_CXX11NoReturn:
6021 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
6023 case AttributeList::AT_Deprecated:
6024 handleDeprecatedAttr(S, D, Attr);
6026 case AttributeList::AT_Destructor:
6027 handleDestructorAttr(S, D, Attr);
6029 case AttributeList::AT_EnableIf:
6030 handleEnableIfAttr(S, D, Attr);
6032 case AttributeList::AT_DiagnoseIf:
6033 handleDiagnoseIfAttr(S, D, Attr);
6035 case AttributeList::AT_ExtVectorType:
6036 handleExtVectorTypeAttr(S, scope, D, Attr);
6038 case AttributeList::AT_ExternalSourceSymbol:
6039 handleExternalSourceSymbolAttr(S, D, Attr);
6041 case AttributeList::AT_MinSize:
6042 handleMinSizeAttr(S, D, Attr);
6044 case AttributeList::AT_OptimizeNone:
6045 handleOptimizeNoneAttr(S, D, Attr);
6047 case AttributeList::AT_FlagEnum:
6048 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
6050 case AttributeList::AT_EnumExtensibility:
6051 handleEnumExtensibilityAttr(S, D, Attr);
6053 case AttributeList::AT_Flatten:
6054 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6056 case AttributeList::AT_Format:
6057 handleFormatAttr(S, D, Attr);
6059 case AttributeList::AT_FormatArg:
6060 handleFormatArgAttr(S, D, Attr);
6062 case AttributeList::AT_CUDAGlobal:
6063 handleGlobalAttr(S, D, Attr);
6065 case AttributeList::AT_CUDADevice:
6066 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6069 case AttributeList::AT_CUDAHost:
6070 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6073 case AttributeList::AT_GNUInline:
6074 handleGNUInlineAttr(S, D, Attr);
6076 case AttributeList::AT_CUDALaunchBounds:
6077 handleLaunchBoundsAttr(S, D, Attr);
6079 case AttributeList::AT_Restrict:
6080 handleRestrictAttr(S, D, Attr);
6082 case AttributeList::AT_MayAlias:
6083 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6085 case AttributeList::AT_Mode:
6086 handleModeAttr(S, D, Attr);
6088 case AttributeList::AT_NoAlias:
6089 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6091 case AttributeList::AT_NoCommon:
6092 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6094 case AttributeList::AT_NoSplitStack:
6095 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6097 case AttributeList::AT_NonNull:
6098 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6099 handleNonNullAttrParameter(S, PVD, Attr);
6101 handleNonNullAttr(S, D, Attr);
6103 case AttributeList::AT_ReturnsNonNull:
6104 handleReturnsNonNullAttr(S, D, Attr);
6106 case AttributeList::AT_AssumeAligned:
6107 handleAssumeAlignedAttr(S, D, Attr);
6109 case AttributeList::AT_AllocAlign:
6110 handleAllocAlignAttr(S, D, Attr);
6112 case AttributeList::AT_Overloadable:
6113 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6115 case AttributeList::AT_Ownership:
6116 handleOwnershipAttr(S, D, Attr);
6118 case AttributeList::AT_Cold:
6119 handleColdAttr(S, D, Attr);
6121 case AttributeList::AT_Hot:
6122 handleHotAttr(S, D, Attr);
6124 case AttributeList::AT_Naked:
6125 handleNakedAttr(S, D, Attr);
6127 case AttributeList::AT_NoReturn:
6128 handleNoReturnAttr(S, D, Attr);
6130 case AttributeList::AT_NoThrow:
6131 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6133 case AttributeList::AT_CUDAShared:
6134 handleSharedAttr(S, D, Attr);
6136 case AttributeList::AT_VecReturn:
6137 handleVecReturnAttr(S, D, Attr);
6139 case AttributeList::AT_ObjCOwnership:
6140 handleObjCOwnershipAttr(S, D, Attr);
6142 case AttributeList::AT_ObjCPreciseLifetime:
6143 handleObjCPreciseLifetimeAttr(S, D, Attr);
6145 case AttributeList::AT_ObjCReturnsInnerPointer:
6146 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6148 case AttributeList::AT_ObjCRequiresSuper:
6149 handleObjCRequiresSuperAttr(S, D, Attr);
6151 case AttributeList::AT_ObjCBridge:
6152 handleObjCBridgeAttr(S, scope, D, Attr);
6154 case AttributeList::AT_ObjCBridgeMutable:
6155 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6157 case AttributeList::AT_ObjCBridgeRelated:
6158 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6160 case AttributeList::AT_ObjCDesignatedInitializer:
6161 handleObjCDesignatedInitializer(S, D, Attr);
6163 case AttributeList::AT_ObjCRuntimeName:
6164 handleObjCRuntimeName(S, D, Attr);
6166 case AttributeList::AT_ObjCRuntimeVisible:
6167 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6169 case AttributeList::AT_ObjCBoxable:
6170 handleObjCBoxable(S, D, Attr);
6172 case AttributeList::AT_CFAuditedTransfer:
6173 handleCFAuditedTransferAttr(S, D, Attr);
6175 case AttributeList::AT_CFUnknownTransfer:
6176 handleCFUnknownTransferAttr(S, D, Attr);
6178 case AttributeList::AT_CFConsumed:
6179 case AttributeList::AT_NSConsumed:
6180 handleNSConsumedAttr(S, D, Attr);
6182 case AttributeList::AT_NSConsumesSelf:
6183 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6185 case AttributeList::AT_NSReturnsAutoreleased:
6186 case AttributeList::AT_NSReturnsNotRetained:
6187 case AttributeList::AT_CFReturnsNotRetained:
6188 case AttributeList::AT_NSReturnsRetained:
6189 case AttributeList::AT_CFReturnsRetained:
6190 handleNSReturnsRetainedAttr(S, D, Attr);
6192 case AttributeList::AT_WorkGroupSizeHint:
6193 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6195 case AttributeList::AT_ReqdWorkGroupSize:
6196 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6198 case AttributeList::AT_OpenCLIntelReqdSubGroupSize:
6199 handleSubGroupSize(S, D, Attr);
6201 case AttributeList::AT_VecTypeHint:
6202 handleVecTypeHint(S, D, Attr);
6204 case AttributeList::AT_RequireConstantInit:
6205 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6207 case AttributeList::AT_InitPriority:
6208 handleInitPriorityAttr(S, D, Attr);
6210 case AttributeList::AT_Packed:
6211 handlePackedAttr(S, D, Attr);
6213 case AttributeList::AT_Section:
6214 handleSectionAttr(S, D, Attr);
6216 case AttributeList::AT_Target:
6217 handleTargetAttr(S, D, Attr);
6219 case AttributeList::AT_Unavailable:
6220 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
6222 case AttributeList::AT_ArcWeakrefUnavailable:
6223 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6225 case AttributeList::AT_ObjCRootClass:
6226 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6228 case AttributeList::AT_ObjCSubclassingRestricted:
6229 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6231 case AttributeList::AT_ObjCExplicitProtocolImpl:
6232 handleObjCSuppresProtocolAttr(S, D, Attr);
6234 case AttributeList::AT_ObjCRequiresPropertyDefs:
6235 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6237 case AttributeList::AT_Unused:
6238 handleUnusedAttr(S, D, Attr);
6240 case AttributeList::AT_ReturnsTwice:
6241 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6243 case AttributeList::AT_NotTailCalled:
6244 handleNotTailCalledAttr(S, D, Attr);
6246 case AttributeList::AT_DisableTailCalls:
6247 handleDisableTailCallsAttr(S, D, Attr);
6249 case AttributeList::AT_Used:
6250 handleUsedAttr(S, D, Attr);
6252 case AttributeList::AT_Visibility:
6253 handleVisibilityAttr(S, D, Attr, false);
6255 case AttributeList::AT_TypeVisibility:
6256 handleVisibilityAttr(S, D, Attr, true);
6258 case AttributeList::AT_WarnUnused:
6259 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6261 case AttributeList::AT_WarnUnusedResult:
6262 handleWarnUnusedResult(S, D, Attr);
6264 case AttributeList::AT_Weak:
6265 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6267 case AttributeList::AT_WeakRef:
6268 handleWeakRefAttr(S, D, Attr);
6270 case AttributeList::AT_WeakImport:
6271 handleWeakImportAttr(S, D, Attr);
6273 case AttributeList::AT_TransparentUnion:
6274 handleTransparentUnionAttr(S, D, Attr);
6276 case AttributeList::AT_ObjCException:
6277 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6279 case AttributeList::AT_ObjCMethodFamily:
6280 handleObjCMethodFamilyAttr(S, D, Attr);
6282 case AttributeList::AT_ObjCNSObject:
6283 handleObjCNSObject(S, D, Attr);
6285 case AttributeList::AT_ObjCIndependentClass:
6286 handleObjCIndependentClass(S, D, Attr);
6288 case AttributeList::AT_Blocks:
6289 handleBlocksAttr(S, D, Attr);
6291 case AttributeList::AT_Sentinel:
6292 handleSentinelAttr(S, D, Attr);
6294 case AttributeList::AT_Const:
6295 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6297 case AttributeList::AT_Pure:
6298 handleSimpleAttribute<PureAttr>(S, D, Attr);
6300 case AttributeList::AT_Cleanup:
6301 handleCleanupAttr(S, D, Attr);
6303 case AttributeList::AT_NoDebug:
6304 handleNoDebugAttr(S, D, Attr);
6306 case AttributeList::AT_NoDuplicate:
6307 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6309 case AttributeList::AT_Convergent:
6310 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6312 case AttributeList::AT_NoInline:
6313 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6315 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6316 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6318 case AttributeList::AT_StdCall:
6319 case AttributeList::AT_CDecl:
6320 case AttributeList::AT_FastCall:
6321 case AttributeList::AT_ThisCall:
6322 case AttributeList::AT_Pascal:
6323 case AttributeList::AT_RegCall:
6324 case AttributeList::AT_SwiftCall:
6325 case AttributeList::AT_VectorCall:
6326 case AttributeList::AT_MSABI:
6327 case AttributeList::AT_SysVABI:
6328 case AttributeList::AT_Pcs:
6329 case AttributeList::AT_IntelOclBicc:
6330 case AttributeList::AT_PreserveMost:
6331 case AttributeList::AT_PreserveAll:
6332 handleCallConvAttr(S, D, Attr);
6334 case AttributeList::AT_Suppress:
6335 handleSuppressAttr(S, D, Attr);
6337 case AttributeList::AT_OpenCLKernel:
6338 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6340 case AttributeList::AT_OpenCLAccess:
6341 handleOpenCLAccessAttr(S, D, Attr);
6343 case AttributeList::AT_OpenCLNoSVM:
6344 handleOpenCLNoSVMAttr(S, D, Attr);
6346 case AttributeList::AT_SwiftContext:
6347 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6349 case AttributeList::AT_SwiftErrorResult:
6350 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6352 case AttributeList::AT_SwiftIndirectResult:
6353 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6355 case AttributeList::AT_InternalLinkage:
6356 handleInternalLinkageAttr(S, D, Attr);
6358 case AttributeList::AT_LTOVisibilityPublic:
6359 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6362 // Microsoft attributes:
6363 case AttributeList::AT_EmptyBases:
6364 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6366 case AttributeList::AT_LayoutVersion:
6367 handleLayoutVersion(S, D, Attr);
6369 case AttributeList::AT_MSNoVTable:
6370 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6372 case AttributeList::AT_MSStruct:
6373 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6375 case AttributeList::AT_Uuid:
6376 handleUuidAttr(S, D, Attr);
6378 case AttributeList::AT_MSInheritance:
6379 handleMSInheritanceAttr(S, D, Attr);
6381 case AttributeList::AT_SelectAny:
6382 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6384 case AttributeList::AT_Thread:
6385 handleDeclspecThreadAttr(S, D, Attr);
6388 case AttributeList::AT_AbiTag:
6389 handleAbiTagAttr(S, D, Attr);
6392 // Thread safety attributes:
6393 case AttributeList::AT_AssertExclusiveLock:
6394 handleAssertExclusiveLockAttr(S, D, Attr);
6396 case AttributeList::AT_AssertSharedLock:
6397 handleAssertSharedLockAttr(S, D, Attr);
6399 case AttributeList::AT_GuardedVar:
6400 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6402 case AttributeList::AT_PtGuardedVar:
6403 handlePtGuardedVarAttr(S, D, Attr);
6405 case AttributeList::AT_ScopedLockable:
6406 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6408 case AttributeList::AT_NoSanitize:
6409 handleNoSanitizeAttr(S, D, Attr);
6411 case AttributeList::AT_NoSanitizeSpecific:
6412 handleNoSanitizeSpecificAttr(S, D, Attr);
6414 case AttributeList::AT_NoThreadSafetyAnalysis:
6415 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6417 case AttributeList::AT_GuardedBy:
6418 handleGuardedByAttr(S, D, Attr);
6420 case AttributeList::AT_PtGuardedBy:
6421 handlePtGuardedByAttr(S, D, Attr);
6423 case AttributeList::AT_ExclusiveTrylockFunction:
6424 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6426 case AttributeList::AT_LockReturned:
6427 handleLockReturnedAttr(S, D, Attr);
6429 case AttributeList::AT_LocksExcluded:
6430 handleLocksExcludedAttr(S, D, Attr);
6432 case AttributeList::AT_SharedTrylockFunction:
6433 handleSharedTrylockFunctionAttr(S, D, Attr);
6435 case AttributeList::AT_AcquiredBefore:
6436 handleAcquiredBeforeAttr(S, D, Attr);
6438 case AttributeList::AT_AcquiredAfter:
6439 handleAcquiredAfterAttr(S, D, Attr);
6442 // Capability analysis attributes.
6443 case AttributeList::AT_Capability:
6444 case AttributeList::AT_Lockable:
6445 handleCapabilityAttr(S, D, Attr);
6447 case AttributeList::AT_RequiresCapability:
6448 handleRequiresCapabilityAttr(S, D, Attr);
6451 case AttributeList::AT_AssertCapability:
6452 handleAssertCapabilityAttr(S, D, Attr);
6454 case AttributeList::AT_AcquireCapability:
6455 handleAcquireCapabilityAttr(S, D, Attr);
6457 case AttributeList::AT_ReleaseCapability:
6458 handleReleaseCapabilityAttr(S, D, Attr);
6460 case AttributeList::AT_TryAcquireCapability:
6461 handleTryAcquireCapabilityAttr(S, D, Attr);
6464 // Consumed analysis attributes.
6465 case AttributeList::AT_Consumable:
6466 handleConsumableAttr(S, D, Attr);
6468 case AttributeList::AT_ConsumableAutoCast:
6469 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6471 case AttributeList::AT_ConsumableSetOnRead:
6472 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6474 case AttributeList::AT_CallableWhen:
6475 handleCallableWhenAttr(S, D, Attr);
6477 case AttributeList::AT_ParamTypestate:
6478 handleParamTypestateAttr(S, D, Attr);
6480 case AttributeList::AT_ReturnTypestate:
6481 handleReturnTypestateAttr(S, D, Attr);
6483 case AttributeList::AT_SetTypestate:
6484 handleSetTypestateAttr(S, D, Attr);
6486 case AttributeList::AT_TestTypestate:
6487 handleTestTypestateAttr(S, D, Attr);
6490 // Type safety attributes.
6491 case AttributeList::AT_ArgumentWithTypeTag:
6492 handleArgumentWithTypeTagAttr(S, D, Attr);
6494 case AttributeList::AT_TypeTagForDatatype:
6495 handleTypeTagForDatatypeAttr(S, D, Attr);
6497 case AttributeList::AT_AnyX86NoCallerSavedRegisters:
6498 handleNoCallerSavedRegsAttr(S, D, Attr);
6500 case AttributeList::AT_RenderScriptKernel:
6501 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6504 case AttributeList::AT_XRayInstrument:
6505 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6507 case AttributeList::AT_XRayLogArgs:
6508 handleXRayLogArgsAttr(S, D, Attr);
6513 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6514 /// attribute list to the specified decl, ignoring any type attributes.
6515 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6516 const AttributeList *AttrList,
6517 bool IncludeCXX11Attributes) {
6518 for (const AttributeList* l = AttrList; l; l = l->getNext())
6519 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6521 // FIXME: We should be able to handle these cases in TableGen.
6523 // static int a9 __attribute__((weakref));
6524 // but that looks really pointless. We reject it.
6525 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6526 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6527 << cast<NamedDecl>(D);
6528 D->dropAttr<WeakRefAttr>();
6532 // FIXME: We should be able to handle this in TableGen as well. It would be
6533 // good to have a way to specify "these attributes must appear as a group",
6534 // for these. Additionally, it would be good to have a way to specify "these
6535 // attribute must never appear as a group" for attributes like cold and hot.
6536 if (!D->hasAttr<OpenCLKernelAttr>()) {
6537 // These attributes cannot be applied to a non-kernel function.
6538 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6539 // FIXME: This emits a different error message than
6540 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6541 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6542 D->setInvalidDecl();
6543 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6544 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6545 D->setInvalidDecl();
6546 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6547 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6548 D->setInvalidDecl();
6549 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6550 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6551 << A << ExpectedKernelFunction;
6552 D->setInvalidDecl();
6553 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6554 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6555 << A << ExpectedKernelFunction;
6556 D->setInvalidDecl();
6557 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6558 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6559 << A << ExpectedKernelFunction;
6560 D->setInvalidDecl();
6561 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6562 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6563 << A << ExpectedKernelFunction;
6564 D->setInvalidDecl();
6565 } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6566 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6567 D->setInvalidDecl();
6572 // Helper for delayed proccessing TransparentUnion attribute.
6573 void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6574 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6575 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6576 handleTransparentUnionAttr(*this, D, *Attr);
6581 // Annotation attributes are the only attributes allowed after an access
6583 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6584 const AttributeList *AttrList) {
6585 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6586 if (l->getKind() == AttributeList::AT_Annotate) {
6587 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6589 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6597 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6598 /// contains any decl attributes that we should warn about.
6599 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6600 for ( ; A; A = A->getNext()) {
6601 // Only warn if the attribute is an unignored, non-type attribute.
6602 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6603 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6605 if (A->getKind() == AttributeList::UnknownAttribute) {
6606 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6607 << A->getName() << A->getRange();
6609 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6610 << A->getName() << A->getRange();
6615 /// checkUnusedDeclAttributes - Given a declarator which is not being
6616 /// used to build a declaration, complain about any decl attributes
6617 /// which might be lying around on it.
6618 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6619 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6620 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6621 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6622 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6625 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6626 /// \#pragma weak needs a non-definition decl and source may not have one.
6627 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6628 SourceLocation Loc) {
6629 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6630 NamedDecl *NewD = nullptr;
6631 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6632 FunctionDecl *NewFD;
6633 // FIXME: Missing call to CheckFunctionDeclaration().
6635 // FIXME: Is the qualifier info correct?
6636 // FIXME: Is the DeclContext correct?
6637 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6638 Loc, Loc, DeclarationName(II),
6639 FD->getType(), FD->getTypeSourceInfo(),
6640 SC_None, false/*isInlineSpecified*/,
6642 false/*isConstexprSpecified*/);
6645 if (FD->getQualifier())
6646 NewFD->setQualifierInfo(FD->getQualifierLoc());
6648 // Fake up parameter variables; they are declared as if this were
6650 QualType FDTy = FD->getType();
6651 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6652 SmallVector<ParmVarDecl*, 16> Params;
6653 for (const auto &AI : FT->param_types()) {
6654 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6655 Param->setScopeInfo(0, Params.size());
6656 Params.push_back(Param);
6658 NewFD->setParams(Params);
6660 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6661 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6662 VD->getInnerLocStart(), VD->getLocation(), II,
6663 VD->getType(), VD->getTypeSourceInfo(),
6664 VD->getStorageClass());
6665 if (VD->getQualifier()) {
6666 VarDecl *NewVD = cast<VarDecl>(NewD);
6667 NewVD->setQualifierInfo(VD->getQualifierLoc());
6673 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6674 /// applied to it, possibly with an alias.
6675 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6676 if (W.getUsed()) return; // only do this once
6678 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6679 IdentifierInfo *NDId = ND->getIdentifier();
6680 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6681 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6683 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6684 WeakTopLevelDecl.push_back(NewD);
6685 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6686 // to insert Decl at TU scope, sorry.
6687 DeclContext *SavedContext = CurContext;
6688 CurContext = Context.getTranslationUnitDecl();
6689 NewD->setDeclContext(CurContext);
6690 NewD->setLexicalDeclContext(CurContext);
6691 PushOnScopeChains(NewD, S);
6692 CurContext = SavedContext;
6693 } else { // just add weak to existing
6694 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6698 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6699 // It's valid to "forward-declare" #pragma weak, in which case we
6701 LoadExternalWeakUndeclaredIdentifiers();
6702 if (!WeakUndeclaredIdentifiers.empty()) {
6703 NamedDecl *ND = nullptr;
6704 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6705 if (VD->isExternC())
6707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6708 if (FD->isExternC())
6711 if (IdentifierInfo *Id = ND->getIdentifier()) {
6712 auto I = WeakUndeclaredIdentifiers.find(Id);
6713 if (I != WeakUndeclaredIdentifiers.end()) {
6714 WeakInfo W = I->second;
6715 DeclApplyPragmaWeak(S, ND, W);
6716 WeakUndeclaredIdentifiers[Id] = W;
6723 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6724 /// it, apply them to D. This is a bit tricky because PD can have attributes
6725 /// specified in many different places, and we need to find and apply them all.
6726 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6727 // Apply decl attributes from the DeclSpec if present.
6728 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6729 ProcessDeclAttributeList(S, D, Attrs);
6731 // Walk the declarator structure, applying decl attributes that were in a type
6732 // position to the decl itself. This handles cases like:
6733 // int *__attr__(x)** D;
6734 // when X is a decl attribute.
6735 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6736 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6737 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6739 // Finally, apply any attributes on the decl itself.
6740 if (const AttributeList *Attrs = PD.getAttributes())
6741 ProcessDeclAttributeList(S, D, Attrs);
6743 // Apply additional attributes specified by '#pragma clang attribute'.
6744 AddPragmaAttributes(S, D);
6747 /// Is the given declaration allowed to use a forbidden type?
6748 /// If so, it'll still be annotated with an attribute that makes it
6749 /// illegal to actually use.
6750 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6751 const DelayedDiagnostic &diag,
6752 UnavailableAttr::ImplicitReason &reason) {
6753 // Private ivars are always okay. Unfortunately, people don't
6754 // always properly make their ivars private, even in system headers.
6755 // Plus we need to make fields okay, too.
6756 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6757 !isa<FunctionDecl>(decl))
6760 // Silently accept unsupported uses of __weak in both user and system
6761 // declarations when it's been disabled, for ease of integration with
6762 // -fno-objc-arc files. We do have to take some care against attempts
6763 // to define such things; for now, we've only done that for ivars
6765 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6766 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6767 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6768 reason = UnavailableAttr::IR_ForbiddenWeak;
6773 // Allow all sorts of things in system headers.
6774 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6775 // Currently, all the failures dealt with this way are due to ARC
6777 reason = UnavailableAttr::IR_ARCForbiddenType;
6784 /// Handle a delayed forbidden-type diagnostic.
6785 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6787 auto reason = UnavailableAttr::IR_None;
6788 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6789 assert(reason && "didn't set reason?");
6790 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6794 if (S.getLangOpts().ObjCAutoRefCount)
6795 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6796 // FIXME: we may want to suppress diagnostics for all
6797 // kind of forbidden type messages on unavailable functions.
6798 if (FD->hasAttr<UnavailableAttr>() &&
6799 diag.getForbiddenTypeDiagnostic() ==
6800 diag::err_arc_array_param_no_ownership) {
6801 diag.Triggered = true;
6806 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6807 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6808 diag.Triggered = true;
6811 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6813 // Check each AvailabilityAttr to find the one for this platform.
6814 for (const auto *A : D->attrs()) {
6815 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6816 // FIXME: this is copied from CheckAvailability. We should try to
6819 // Check if this is an App Extension "platform", and if so chop off
6820 // the suffix for matching with the actual platform.
6821 StringRef ActualPlatform = Avail->getPlatform()->getName();
6822 StringRef RealizedPlatform = ActualPlatform;
6823 if (Context.getLangOpts().AppExt) {
6824 size_t suffix = RealizedPlatform.rfind("_app_extension");
6825 if (suffix != StringRef::npos)
6826 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6829 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6831 // Match the platform name.
6832 if (RealizedPlatform == TargetPlatform)
6839 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6840 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6841 /// in a deprecated context, but not the other way around.
6842 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6843 VersionTuple DeclVersion,
6845 assert(K != AR_Available && "Expected an unavailable declaration here!");
6847 // Checks if we should emit the availability diagnostic in the context of C.
6848 auto CheckContext = [&](const Decl *C) {
6849 if (K == AR_NotYetIntroduced) {
6850 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6851 if (AA->getIntroduced() >= DeclVersion)
6853 } else if (K == AR_Deprecated)
6854 if (C->isDeprecated())
6857 if (C->isUnavailable())
6862 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6863 // on nested declarations in an @interface having the availability of the
6864 // interface when they really shouldn't: they are members of the enclosing
6865 // context, and can referenced from there.
6866 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6867 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6868 if (CheckContext(OrigCtx))
6871 // An implementation implicitly has the availability of the interface.
6872 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6873 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6874 if (CheckContext(Interface))
6877 // A category implicitly has the availability of the interface.
6878 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6879 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6880 if (CheckContext(Interface))
6885 if (CheckContext(Ctx))
6888 // An implementation implicitly has the availability of the interface.
6889 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6890 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6891 if (CheckContext(Interface))
6894 // A category implicitly has the availability of the interface.
6895 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6896 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6897 if (CheckContext(Interface))
6899 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6904 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6905 Decl *Ctx, const NamedDecl *D,
6906 StringRef Message, SourceLocation Loc,
6907 const ObjCInterfaceDecl *UnknownObjCClass,
6908 const ObjCPropertyDecl *ObjCProperty,
6909 bool ObjCPropertyAccess) {
6910 // Diagnostics for deprecated or unavailable.
6911 unsigned diag, diag_message, diag_fwdclass_message;
6912 unsigned diag_available_here = diag::note_availability_specified_here;
6913 SourceLocation NoteLocation = D->getLocation();
6915 // Matches 'diag::note_property_attribute' options.
6916 unsigned property_note_select;
6918 // Matches diag::note_availability_specified_here.
6919 unsigned available_here_select_kind;
6921 VersionTuple DeclVersion;
6922 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6923 DeclVersion = AA->getIntroduced();
6925 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6930 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6931 : diag::warn_property_method_deprecated;
6932 diag_message = diag::warn_deprecated_message;
6933 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6934 property_note_select = /* deprecated */ 0;
6935 available_here_select_kind = /* deprecated */ 2;
6936 if (const auto *attr = D->getAttr<DeprecatedAttr>())
6937 NoteLocation = attr->getLocation();
6940 case AR_Unavailable:
6941 diag = !ObjCPropertyAccess ? diag::err_unavailable
6942 : diag::err_property_method_unavailable;
6943 diag_message = diag::err_unavailable_message;
6944 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6945 property_note_select = /* unavailable */ 1;
6946 available_here_select_kind = /* unavailable */ 0;
6948 if (auto attr = D->getAttr<UnavailableAttr>()) {
6949 if (attr->isImplicit() && attr->getImplicitReason()) {
6950 // Most of these failures are due to extra restrictions in ARC;
6951 // reflect that in the primary diagnostic when applicable.
6952 auto flagARCError = [&] {
6953 if (S.getLangOpts().ObjCAutoRefCount &&
6954 S.getSourceManager().isInSystemHeader(D->getLocation()))
6955 diag = diag::err_unavailable_in_arc;
6958 switch (attr->getImplicitReason()) {
6959 case UnavailableAttr::IR_None: break;
6961 case UnavailableAttr::IR_ARCForbiddenType:
6963 diag_available_here = diag::note_arc_forbidden_type;
6966 case UnavailableAttr::IR_ForbiddenWeak:
6967 if (S.getLangOpts().ObjCWeakRuntime)
6968 diag_available_here = diag::note_arc_weak_disabled;
6970 diag_available_here = diag::note_arc_weak_no_runtime;
6973 case UnavailableAttr::IR_ARCForbiddenConversion:
6975 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6978 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6980 diag_available_here = diag::note_arc_init_returns_unrelated;
6983 case UnavailableAttr::IR_ARCFieldWithOwnership:
6985 diag_available_here = diag::note_arc_field_with_ownership;
6992 case AR_NotYetIntroduced:
6993 diag = diag::warn_partial_availability;
6994 diag_message = diag::warn_partial_message;
6995 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6996 property_note_select = /* partial */ 2;
6997 available_here_select_kind = /* partial */ 3;
7001 llvm_unreachable("Warning for availability of available declaration?");
7004 CharSourceRange UseRange;
7005 StringRef Replacement;
7006 if (K == AR_Deprecated) {
7007 if (auto attr = D->getAttr<DeprecatedAttr>())
7008 Replacement = attr->getReplacement();
7009 if (auto attr = getAttrForPlatform(S.Context, D))
7010 Replacement = attr->getReplacement();
7012 if (!Replacement.empty())
7014 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7017 if (!Message.empty()) {
7018 S.Diag(Loc, diag_message) << D << Message
7019 << (UseRange.isValid() ?
7020 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7022 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7023 << ObjCProperty->getDeclName() << property_note_select;
7024 } else if (!UnknownObjCClass) {
7025 S.Diag(Loc, diag) << D
7026 << (UseRange.isValid() ?
7027 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7029 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7030 << ObjCProperty->getDeclName() << property_note_select;
7032 S.Diag(Loc, diag_fwdclass_message) << D
7033 << (UseRange.isValid() ?
7034 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7035 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7038 // The declaration can have multiple availability attributes, we are looking
7040 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
7041 if (A && A->isInherited()) {
7042 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
7043 Redecl = Redecl->getPreviousDecl()) {
7044 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
7046 if (AForRedecl && !AForRedecl->isInherited()) {
7047 // If D is a declaration with inherited attributes, the note should
7048 // point to the declaration with actual attributes.
7049 S.Diag(Redecl->getLocation(), diag_available_here) << D
7050 << available_here_select_kind;
7056 S.Diag(NoteLocation, diag_available_here)
7057 << D << available_here_select_kind;
7059 if (K == AR_NotYetIntroduced)
7060 S.Diag(Loc, diag::note_partial_availability_silence) << D;
7063 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7065 assert(DD.Kind == DelayedDiagnostic::Availability &&
7066 "Expected an availability diagnostic here");
7068 DD.Triggered = true;
7069 DoEmitAvailabilityWarning(
7070 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
7071 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
7072 DD.getObjCProperty(), false);
7075 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7076 assert(DelayedDiagnostics.getCurrentPool());
7077 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7078 DelayedDiagnostics.popWithoutEmitting(state);
7080 // When delaying diagnostics to run in the context of a parsed
7081 // declaration, we only want to actually emit anything if parsing
7085 // We emit all the active diagnostics in this pool or any of its
7086 // parents. In general, we'll get one pool for the decl spec
7087 // and a child pool for each declarator; in a decl group like:
7088 // deprecated_typedef foo, *bar, baz();
7089 // only the declarator pops will be passed decls. This is correct;
7090 // we really do need to consider delayed diagnostics from the decl spec
7091 // for each of the different declarations.
7092 const DelayedDiagnosticPool *pool = &poppedPool;
7094 for (DelayedDiagnosticPool::pool_iterator
7095 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7096 // This const_cast is a bit lame. Really, Triggered should be mutable.
7097 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7101 switch (diag.Kind) {
7102 case DelayedDiagnostic::Availability:
7103 // Don't bother giving deprecation/unavailable diagnostics if
7104 // the decl is invalid.
7105 if (!decl->isInvalidDecl())
7106 handleDelayedAvailabilityCheck(*this, diag, decl);
7109 case DelayedDiagnostic::Access:
7110 HandleDelayedAccessCheck(diag, decl);
7113 case DelayedDiagnostic::ForbiddenType:
7114 handleDelayedForbiddenType(*this, diag, decl);
7118 } while ((pool = pool->getParent()));
7121 /// Given a set of delayed diagnostics, re-emit them as if they had
7122 /// been delayed in the current context instead of in the given pool.
7123 /// Essentially, this just moves them to the current pool.
7124 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7125 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7126 assert(curPool && "re-emitting in undelayed context not supported");
7127 curPool->steal(pool);
7130 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
7131 NamedDecl *D, StringRef Message,
7133 const ObjCInterfaceDecl *UnknownObjCClass,
7134 const ObjCPropertyDecl *ObjCProperty,
7135 bool ObjCPropertyAccess) {
7136 // Delay if we're currently parsing a declaration.
7137 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
7138 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
7139 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
7140 ObjCPropertyAccess));
7144 Decl *Ctx = cast<Decl>(getCurLexicalContext());
7145 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
7146 ObjCProperty, ObjCPropertyAccess);
7151 /// Returns true if the given statement can be a body-like child of \p Parent.
7152 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7153 switch (Parent->getStmtClass()) {
7154 case Stmt::IfStmtClass:
7155 return cast<IfStmt>(Parent)->getThen() == S ||
7156 cast<IfStmt>(Parent)->getElse() == S;
7157 case Stmt::WhileStmtClass:
7158 return cast<WhileStmt>(Parent)->getBody() == S;
7159 case Stmt::DoStmtClass:
7160 return cast<DoStmt>(Parent)->getBody() == S;
7161 case Stmt::ForStmtClass:
7162 return cast<ForStmt>(Parent)->getBody() == S;
7163 case Stmt::CXXForRangeStmtClass:
7164 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7165 case Stmt::ObjCForCollectionStmtClass:
7166 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7167 case Stmt::CaseStmtClass:
7168 case Stmt::DefaultStmtClass:
7169 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7175 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7179 bool VisitStmt(Stmt *S) { return S != Target; }
7181 /// Returns true if the given statement is present in the given declaration.
7182 static bool isContained(const Stmt *Target, const Decl *D) {
7183 StmtUSEFinder Visitor;
7184 Visitor.Target = Target;
7185 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7189 /// Traverses the AST and finds the last statement that used a given
7191 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7195 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7196 if (DRE->getDecl() == D)
7201 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7202 const CompoundStmt *Scope) {
7203 LastDeclUSEFinder Visitor;
7205 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
7207 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
7214 /// \brief This class implements -Wunguarded-availability.
7216 /// This is done with a traversal of the AST of a function that makes reference
7217 /// to a partially available declaration. Whenever we encounter an \c if of the
7218 /// form: \c if(@available(...)), we use the version from the condition to visit
7219 /// the then statement.
7220 class DiagnoseUnguardedAvailability
7221 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7222 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7227 /// Stack of potentially nested 'if (@available(...))'s.
7228 SmallVector<VersionTuple, 8> AvailabilityStack;
7229 SmallVector<const Stmt *, 16> StmtStack;
7231 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7234 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7235 : SemaRef(SemaRef), Ctx(Ctx) {
7236 AvailabilityStack.push_back(
7237 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
7240 bool TraverseDecl(Decl *D) {
7241 // Avoid visiting nested functions to prevent duplicate warnings.
7242 if (!D || isa<FunctionDecl>(D))
7244 return Base::TraverseDecl(D);
7247 bool TraverseStmt(Stmt *S) {
7250 StmtStack.push_back(S);
7251 bool Result = Base::TraverseStmt(S);
7252 StmtStack.pop_back();
7256 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7258 bool TraverseIfStmt(IfStmt *If);
7260 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
7262 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
7263 if (PRE->isClassReceiver())
7264 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
7268 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7269 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7270 DiagnoseDeclAvailability(
7271 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7275 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7276 DiagnoseDeclAvailability(DRE->getDecl(),
7277 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7281 bool VisitMemberExpr(MemberExpr *ME) {
7282 DiagnoseDeclAvailability(ME->getMemberDecl(),
7283 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7287 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
7288 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use)
7289 << (!SemaRef.getLangOpts().ObjC1);
7293 bool VisitTypeLoc(TypeLoc Ty);
7296 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7297 NamedDecl *D, SourceRange Range) {
7299 VersionTuple ContextVersion = AvailabilityStack.back();
7300 if (AvailabilityResult Result =
7301 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
7302 // All other diagnostic kinds have already been handled in
7303 // DiagnoseAvailabilityOfDecl.
7304 if (Result != AR_NotYetIntroduced)
7307 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7308 VersionTuple Introduced = AA->getIntroduced();
7310 if (ContextVersion >= Introduced)
7313 // If the context of this function is less available than D, we should not
7314 // emit a diagnostic.
7315 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7318 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7320 << AvailabilityAttr::getPrettyPlatformName(
7321 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7322 << Introduced.getAsString();
7324 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7325 << D << /* partial */ 3;
7328 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7330 << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0
7331 : /*__builtin_available*/ 1);
7333 // Find the statement which should be enclosed in the if @available check.
7334 if (StmtStack.empty())
7336 const Stmt *StmtOfUse = StmtStack.back();
7337 const CompoundStmt *Scope = nullptr;
7338 for (const Stmt *S : llvm::reverse(StmtStack)) {
7339 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7343 if (isBodyLikeChildStmt(StmtOfUse, S)) {
7344 // The declaration won't be seen outside of the statement, so we don't
7345 // have to wrap the uses of any declared variables in if (@available).
7346 // Therefore we can avoid setting Scope here.
7351 const Stmt *LastStmtOfUse = nullptr;
7352 if (isa<DeclStmt>(StmtOfUse) && Scope) {
7353 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
7354 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
7355 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
7361 const SourceManager &SM = SemaRef.getSourceManager();
7362 SourceLocation IfInsertionLoc =
7363 SM.getExpansionLoc(StmtOfUse->getLocStart());
7364 SourceLocation StmtEndLoc =
7365 SM.getExpansionRange(
7366 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd())
7368 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
7371 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
7372 const char *ExtraIndentation = " ";
7373 std::string FixItString;
7374 llvm::raw_string_ostream FixItOS(FixItString);
7375 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available"
7376 : "__builtin_available")
7378 << AvailabilityAttr::getPlatformNameSourceSpelling(
7379 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7380 << " " << Introduced.getAsString() << ", *)) {\n"
7381 << Indentation << ExtraIndentation;
7382 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
7383 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
7384 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
7385 /*SkipTrailingWhitespaceAndNewLine=*/false);
7386 if (ElseInsertionLoc.isInvalid())
7388 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
7389 FixItOS.str().clear();
7391 << Indentation << "} else {\n"
7392 << Indentation << ExtraIndentation
7393 << "// Fallback on earlier versions\n"
7394 << Indentation << "}";
7395 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
7399 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7400 const Type *TyPtr = Ty.getTypePtr();
7401 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7403 if (Range.isInvalid())
7406 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7407 TagDecl *TD = TT->getDecl();
7408 DiagnoseDeclAvailability(TD, Range);
7410 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7411 TypedefNameDecl *D = TD->getDecl();
7412 DiagnoseDeclAvailability(D, Range);
7414 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7415 if (NamedDecl *D = ObjCO->getInterface())
7416 DiagnoseDeclAvailability(D, Range);
7422 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7423 VersionTuple CondVersion;
7424 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7425 CondVersion = E->getVersion();
7427 // If we're using the '*' case here or if this check is redundant, then we
7428 // use the enclosing version to check both branches.
7429 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7430 return Base::TraverseStmt(If->getThen()) &&
7431 Base::TraverseStmt(If->getElse());
7433 // This isn't an availability checking 'if', we can just continue.
7434 return Base::TraverseIfStmt(If);
7437 AvailabilityStack.push_back(CondVersion);
7438 bool ShouldContinue = TraverseStmt(If->getThen());
7439 AvailabilityStack.pop_back();
7441 return ShouldContinue && TraverseStmt(If->getElse());
7444 } // end anonymous namespace
7446 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7447 Stmt *Body = nullptr;
7449 if (auto *FD = D->getAsFunction()) {
7450 // FIXME: We only examine the pattern decl for availability violations now,
7451 // but we should also examine instantiated templates.
7452 if (FD->isTemplateInstantiation())
7455 Body = FD->getBody();
7456 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7457 Body = MD->getBody();
7458 else if (auto *BD = dyn_cast<BlockDecl>(D))
7459 Body = BD->getBody();
7461 assert(Body && "Need a body here!");
7463 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);