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/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/MathExtras.h"
40 using namespace clang;
43 namespace AttributeLangSupport {
49 } // end namespace AttributeLangSupport
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 /// isFunctionOrMethod - Return true if the given decl has function
56 /// type (function or function-typed variable) or an Objective-C
58 static bool isFunctionOrMethod(const Decl *D) {
59 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
62 /// Return true if the given decl has function type (function or
63 /// function-typed variable) or an Objective-C method or a block.
64 static bool isFunctionOrMethodOrBlock(const Decl *D) {
65 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
68 /// Return true if the given decl has a declarator that should have
69 /// been processed by Sema::GetTypeForDeclarator.
70 static bool hasDeclarator(const Decl *D) {
71 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
72 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
73 isa<ObjCPropertyDecl>(D);
76 /// hasFunctionProto - Return true if the given decl has a argument
77 /// information. This decl should have already passed
78 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
79 static bool hasFunctionProto(const Decl *D) {
80 if (const FunctionType *FnTy = D->getFunctionType())
81 return isa<FunctionProtoType>(FnTy);
82 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
85 /// getFunctionOrMethodNumParams - Return number of function or method
86 /// parameters. It is an error to call this on a K&R function (use
87 /// hasFunctionProto first).
88 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
89 if (const FunctionType *FnTy = D->getFunctionType())
90 return cast<FunctionProtoType>(FnTy)->getNumParams();
91 if (const auto *BD = dyn_cast<BlockDecl>(D))
92 return BD->getNumParams();
93 return cast<ObjCMethodDecl>(D)->param_size();
96 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
98 if (const auto *FD = dyn_cast<FunctionDecl>(D))
99 return FD->getParamDecl(Idx);
100 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
101 return MD->getParamDecl(Idx);
102 if (const auto *BD = dyn_cast<BlockDecl>(D))
103 return BD->getParamDecl(Idx);
107 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
108 if (const FunctionType *FnTy = D->getFunctionType())
109 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
110 if (const auto *BD = dyn_cast<BlockDecl>(D))
111 return BD->getParamDecl(Idx)->getType();
113 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
116 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
117 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
118 return PVD->getSourceRange();
119 return SourceRange();
122 static QualType getFunctionOrMethodResultType(const Decl *D) {
123 if (const FunctionType *FnTy = D->getFunctionType())
124 return FnTy->getReturnType();
125 return cast<ObjCMethodDecl>(D)->getReturnType();
128 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
129 if (const auto *FD = dyn_cast<FunctionDecl>(D))
130 return FD->getReturnTypeSourceRange();
131 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
132 return MD->getReturnTypeSourceRange();
133 return SourceRange();
136 static bool isFunctionOrMethodVariadic(const Decl *D) {
137 if (const FunctionType *FnTy = D->getFunctionType())
138 return cast<FunctionProtoType>(FnTy)->isVariadic();
139 if (const auto *BD = dyn_cast<BlockDecl>(D))
140 return BD->isVariadic();
141 return cast<ObjCMethodDecl>(D)->isVariadic();
144 static bool isInstanceMethod(const Decl *D) {
145 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
146 return MethodDecl->isInstance();
150 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
151 const auto *PT = T->getAs<ObjCObjectPointerType>();
155 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
159 IdentifierInfo* ClsName = Cls->getIdentifier();
161 // FIXME: Should we walk the chain of classes?
162 return ClsName == &Ctx.Idents.get("NSString") ||
163 ClsName == &Ctx.Idents.get("NSMutableString");
166 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
167 const auto *PT = T->getAs<PointerType>();
171 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
175 const RecordDecl *RD = RT->getDecl();
176 if (RD->getTagKind() != TTK_Struct)
179 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
182 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
183 // FIXME: Include the type in the argument list.
184 return AL.getNumArgs() + AL.hasParsedType();
187 template <typename Compare>
188 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
189 unsigned Num, unsigned Diag,
191 if (Comp(getNumAttributeArgs(AL), Num)) {
192 S.Diag(AL.getLoc(), Diag) << AL << Num;
199 /// Check if the attribute has exactly as many args as Num. May
201 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
202 return checkAttributeNumArgsImpl(S, AL, Num,
203 diag::err_attribute_wrong_number_arguments,
204 std::not_equal_to<unsigned>());
207 /// Check if the attribute has at least as many args as Num. May
209 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
211 return checkAttributeNumArgsImpl(S, AL, Num,
212 diag::err_attribute_too_few_arguments,
213 std::less<unsigned>());
216 /// Check if the attribute has at most as many args as Num. May
218 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
220 return checkAttributeNumArgsImpl(S, AL, Num,
221 diag::err_attribute_too_many_arguments,
222 std::greater<unsigned>());
225 /// A helper function to provide Attribute Location for the Attr types
226 /// AND the ParsedAttr.
227 template <typename AttrInfo>
228 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
229 SourceLocation>::type
230 getAttrLoc(const AttrInfo &AL) {
231 return AL.getLocation();
233 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
235 /// If Expr is a valid integer constant, get the value of the integer
236 /// expression and return success or failure. May output an error.
238 /// Negative argument is implicitly converted to unsigned, unless
239 /// \p StrictlyUnsigned is true.
240 template <typename AttrInfo>
241 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
242 uint32_t &Val, unsigned Idx = UINT_MAX,
243 bool StrictlyUnsigned = false) {
245 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
246 !Expr->isIntegerConstantExpr(I, S.Context)) {
248 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
249 << AI << Idx << AANT_ArgumentIntegerConstant
250 << Expr->getSourceRange();
252 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
253 << AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
258 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
259 << I.toString(10, false) << 32 << /* Unsigned */ 1;
263 if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
264 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
265 << AI << /*non-negative*/ 1;
269 Val = (uint32_t)I.getZExtValue();
273 /// Wrapper around checkUInt32Argument, with an extra check to be sure
274 /// that the result will fit into a regular (signed) int. All args have the same
275 /// purpose as they do in checkUInt32Argument.
276 template <typename AttrInfo>
277 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
278 int &Val, unsigned Idx = UINT_MAX) {
280 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
283 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
284 llvm::APSInt I(32); // for toString
286 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
287 << I.toString(10, false) << 32 << /* Unsigned */ 0;
295 /// Diagnose mutually exclusive attributes when present on a given
296 /// declaration. Returns true if diagnosed.
297 template <typename AttrTy>
298 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
299 if (const auto *A = D->getAttr<AttrTy>()) {
300 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
301 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
307 template <typename AttrTy>
308 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
309 if (const auto *A = D->getAttr<AttrTy>()) {
310 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
312 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
318 /// Check if IdxExpr is a valid parameter index for a function or
319 /// instance method D. May output an error.
321 /// \returns true if IdxExpr is a valid index.
322 template <typename AttrInfo>
323 static bool checkFunctionOrMethodParameterIndex(
324 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
325 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
326 assert(isFunctionOrMethodOrBlock(D));
328 // In C++ the implicit 'this' function parameter also counts.
329 // Parameters are counted from one.
330 bool HP = hasFunctionProto(D);
331 bool HasImplicitThisParam = isInstanceMethod(D);
332 bool IV = HP && isFunctionOrMethodVariadic(D);
334 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
337 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
338 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
339 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
340 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
341 << IdxExpr->getSourceRange();
345 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
346 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
347 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
348 << &AI << AttrArgNum << IdxExpr->getSourceRange();
351 if (HasImplicitThisParam && !CanIndexImplicitThis) {
352 if (IdxSource == 1) {
353 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
354 << &AI << IdxExpr->getSourceRange();
359 Idx = ParamIdx(IdxSource, D);
363 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364 /// If not emit an error and return false. If the argument is an identifier it
365 /// will emit an error with a fixit hint and treat it as if it was a string
367 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
369 SourceLocation *ArgLocation) {
370 // Look for identifiers. If we have one emit a hint to fix it to a literal.
371 if (AL.isArgIdent(ArgNum)) {
372 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
373 Diag(Loc->Loc, diag::err_attribute_argument_type)
374 << AL << AANT_ArgumentString
375 << FixItHint::CreateInsertion(Loc->Loc, "\"")
376 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377 Str = Loc->Ident->getName();
379 *ArgLocation = Loc->Loc;
383 // Now check for an actual string literal.
384 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
385 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
387 *ArgLocation = ArgExpr->getBeginLoc();
389 if (!Literal || !Literal->isAscii()) {
390 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391 << AL << AANT_ArgumentString;
395 Str = Literal->getString();
399 /// Applies the given attribute to the Decl without performing any
400 /// additional semantic checking.
401 template <typename AttrType>
402 static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR,
403 unsigned SpellingIndex) {
404 D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
407 template <typename AttrType>
408 static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
409 handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
410 AL.getAttributeSpellingListIndex());
414 template <typename... DiagnosticArgs>
415 static const Sema::SemaDiagnosticBuilder&
416 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
420 template <typename T, typename... DiagnosticArgs>
421 static const Sema::SemaDiagnosticBuilder&
422 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
423 DiagnosticArgs &&... ExtraArgs) {
424 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
425 std::forward<DiagnosticArgs>(ExtraArgs)...);
428 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
429 /// {@code PassesCheck} is true.
430 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
431 /// specified in {@code ExtraArgs}.
432 template <typename AttrType, typename... DiagnosticArgs>
434 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
435 unsigned SpellingIndex,
437 unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
439 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
440 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
443 handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
446 template <typename AttrType, typename... DiagnosticArgs>
448 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
451 DiagnosticArgs&&... ExtraArgs) {
452 return handleSimpleAttributeOrDiagnose<AttrType>(
453 S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
454 DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
457 template <typename AttrType>
458 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
459 const ParsedAttr &AL) {
460 handleSimpleAttribute<AttrType>(S, D, AL);
463 /// Applies the given attribute to the Decl so long as the Decl doesn't
464 /// already have one of the given incompatible attributes.
465 template <typename AttrType, typename IncompatibleAttrType,
466 typename... IncompatibleAttrTypes>
467 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
468 const ParsedAttr &AL) {
469 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
471 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
475 /// Check if the passed-in expression is of type int or bool.
476 static bool isIntOrBool(Expr *Exp) {
477 QualType QT = Exp->getType();
478 return QT->isBooleanType() || QT->isIntegerType();
482 // Check to see if the type is a smart pointer of some kind. We assume
483 // it's a smart pointer if it defines both operator-> and operator*.
484 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
485 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
486 OverloadedOperatorKind Op) {
487 DeclContextLookupResult Result =
488 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
489 return !Result.empty();
492 const RecordDecl *Record = RT->getDecl();
493 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
494 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
495 if (foundStarOperator && foundArrowOperator)
498 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
502 for (auto BaseSpecifier : CXXRecord->bases()) {
503 if (!foundStarOperator)
504 foundStarOperator = IsOverloadedOperatorPresent(
505 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
506 if (!foundArrowOperator)
507 foundArrowOperator = IsOverloadedOperatorPresent(
508 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
511 if (foundStarOperator && foundArrowOperator)
517 /// Check if passed in Decl is a pointer type.
518 /// Note that this function may produce an error message.
519 /// \return true if the Decl is a pointer type; false otherwise
520 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
521 const ParsedAttr &AL) {
522 const auto *VD = cast<ValueDecl>(D);
523 QualType QT = VD->getType();
524 if (QT->isAnyPointerType())
527 if (const auto *RT = QT->getAs<RecordType>()) {
528 // If it's an incomplete type, it could be a smart pointer; skip it.
529 // (We don't want to force template instantiation if we can avoid it,
530 // since that would alter the order in which templates are instantiated.)
531 if (RT->isIncompleteType())
534 if (threadSafetyCheckIsSmartPointer(S, RT))
538 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
542 /// Checks that the passed in QualType either is of RecordType or points
543 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
544 static const RecordType *getRecordType(QualType QT) {
545 if (const auto *RT = QT->getAs<RecordType>())
548 // Now check if we point to record type.
549 if (const auto *PT = QT->getAs<PointerType>())
550 return PT->getPointeeType()->getAs<RecordType>();
555 template <typename AttrType>
556 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
557 // Check if the record itself has the attribute.
558 if (RD->hasAttr<AttrType>())
561 // Else check if any base classes have the attribute.
562 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
563 CXXBasePaths BPaths(false, false);
564 if (CRD->lookupInBases(
565 [](const CXXBaseSpecifier *BS, CXXBasePath &) {
566 const auto &Ty = *BS->getType();
567 // If it's type-dependent, we assume it could have the attribute.
568 if (Ty.isDependentType())
570 return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
578 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
579 const RecordType *RT = getRecordType(Ty);
584 // Don't check for the capability if the class hasn't been defined yet.
585 if (RT->isIncompleteType())
588 // Allow smart pointers to be used as capability objects.
589 // FIXME -- Check the type that the smart pointer points to.
590 if (threadSafetyCheckIsSmartPointer(S, RT))
593 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
596 static bool checkTypedefTypeForCapability(QualType Ty) {
597 const auto *TD = Ty->getAs<TypedefType>();
601 TypedefNameDecl *TN = TD->getDecl();
605 return TN->hasAttr<CapabilityAttr>();
608 static bool typeHasCapability(Sema &S, QualType Ty) {
609 if (checkTypedefTypeForCapability(Ty))
612 if (checkRecordTypeForCapability(S, Ty))
618 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
619 // Capability expressions are simple expressions involving the boolean logic
620 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
621 // a DeclRefExpr is found, its type should be checked to determine whether it
622 // is a capability or not.
624 if (const auto *E = dyn_cast<CastExpr>(Ex))
625 return isCapabilityExpr(S, E->getSubExpr());
626 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
627 return isCapabilityExpr(S, E->getSubExpr());
628 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
629 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
630 E->getOpcode() == UO_Deref)
631 return isCapabilityExpr(S, E->getSubExpr());
633 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
634 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
635 return isCapabilityExpr(S, E->getLHS()) &&
636 isCapabilityExpr(S, E->getRHS());
640 return typeHasCapability(S, Ex->getType());
643 /// Checks that all attribute arguments, starting from Sidx, resolve to
644 /// a capability object.
645 /// \param Sidx The attribute argument index to start checking with.
646 /// \param ParamIdxOk Whether an argument can be indexing into a function
648 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
649 const ParsedAttr &AL,
650 SmallVectorImpl<Expr *> &Args,
652 bool ParamIdxOk = false) {
653 if (Sidx == AL.getNumArgs()) {
654 // If we don't have any capability arguments, the attribute implicitly
655 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
656 // a non-static method, and that the class is a (scoped) capability.
657 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
658 if (MD && !MD->isStatic()) {
659 const CXXRecordDecl *RD = MD->getParent();
660 // FIXME -- need to check this again on template instantiation
661 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
662 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
664 diag::warn_thread_attribute_not_on_capability_member)
665 << AL << MD->getParent();
667 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
672 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
673 Expr *ArgExp = AL.getArgAsExpr(Idx);
675 if (ArgExp->isTypeDependent()) {
676 // FIXME -- need to check this again on template instantiation
677 Args.push_back(ArgExp);
681 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
682 if (StrLit->getLength() == 0 ||
683 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
684 // Pass empty strings to the analyzer without warnings.
685 // Treat "*" as the universal lock.
686 Args.push_back(ArgExp);
690 // We allow constant strings to be used as a placeholder for expressions
691 // that are not valid C++ syntax, but warn that they are ignored.
692 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
693 Args.push_back(ArgExp);
697 QualType ArgTy = ArgExp->getType();
699 // A pointer to member expression of the form &MyClass::mu is treated
700 // specially -- we need to look at the type of the member.
701 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
702 if (UOp->getOpcode() == UO_AddrOf)
703 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
704 if (DRE->getDecl()->isCXXInstanceMember())
705 ArgTy = DRE->getDecl()->getType();
707 // First see if we can just cast to record type, or pointer to record type.
708 const RecordType *RT = getRecordType(ArgTy);
710 // Now check if we index into a record type function param.
711 if(!RT && ParamIdxOk) {
712 const auto *FD = dyn_cast<FunctionDecl>(D);
713 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
715 unsigned int NumParams = FD->getNumParams();
716 llvm::APInt ArgValue = IL->getValue();
717 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
718 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
719 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
720 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
721 << AL << Idx + 1 << NumParams;
724 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
728 // If the type does not have a capability, see if the components of the
729 // expression have capabilities. This allows for writing C code where the
730 // capability may be on the type, and the expression is a capability
731 // boolean logic expression. Eg) requires_capability(A || B && !C)
732 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
733 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
736 Args.push_back(ArgExp);
740 //===----------------------------------------------------------------------===//
741 // Attribute Implementations
742 //===----------------------------------------------------------------------===//
744 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
745 if (!threadSafetyCheckIsPointer(S, D, AL))
748 D->addAttr(::new (S.Context)
749 PtGuardedVarAttr(AL.getRange(), S.Context,
750 AL.getAttributeSpellingListIndex()));
753 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
755 SmallVector<Expr *, 1> Args;
756 // check that all arguments are lockable objects
757 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
758 unsigned Size = Args.size();
767 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
769 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
772 D->addAttr(::new (S.Context) GuardedByAttr(
773 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
776 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
778 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
781 if (!threadSafetyCheckIsPointer(S, D, AL))
784 D->addAttr(::new (S.Context) PtGuardedByAttr(
785 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
788 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
789 SmallVectorImpl<Expr *> &Args) {
790 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
793 // Check that this attribute only applies to lockable types.
794 QualType QT = cast<ValueDecl>(D)->getType();
795 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
796 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
800 // Check that all arguments are lockable objects.
801 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
808 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
809 SmallVector<Expr *, 1> Args;
810 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
813 Expr **StartArg = &Args[0];
814 D->addAttr(::new (S.Context) AcquiredAfterAttr(
815 AL.getRange(), S.Context, StartArg, Args.size(),
816 AL.getAttributeSpellingListIndex()));
819 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
820 SmallVector<Expr *, 1> Args;
821 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
824 Expr **StartArg = &Args[0];
825 D->addAttr(::new (S.Context) AcquiredBeforeAttr(
826 AL.getRange(), S.Context, StartArg, Args.size(),
827 AL.getAttributeSpellingListIndex()));
830 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
831 SmallVectorImpl<Expr *> &Args) {
832 // zero or more arguments ok
833 // check that all arguments are lockable objects
834 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
839 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
840 SmallVector<Expr *, 1> Args;
841 if (!checkLockFunAttrCommon(S, D, AL, Args))
844 unsigned Size = Args.size();
845 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
846 D->addAttr(::new (S.Context)
847 AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
848 AL.getAttributeSpellingListIndex()));
851 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
852 const ParsedAttr &AL) {
853 SmallVector<Expr *, 1> Args;
854 if (!checkLockFunAttrCommon(S, D, AL, Args))
857 unsigned Size = Args.size();
858 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
859 D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
860 AL.getRange(), S.Context, StartArg, Size,
861 AL.getAttributeSpellingListIndex()));
864 /// Checks to be sure that the given parameter number is in bounds, and
865 /// is an integral type. Will emit appropriate diagnostics if this returns
868 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
869 template <typename AttrInfo>
870 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
871 const AttrInfo &AI, unsigned AttrArgNo) {
872 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
873 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
875 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
879 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
880 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
881 SourceLocation SrcLoc = AttrArg->getBeginLoc();
882 S.Diag(SrcLoc, diag::err_attribute_integers_only)
883 << AI << Param->getSourceRange();
889 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
890 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
891 !checkAttributeAtMostNumArgs(S, AL, 2))
894 const auto *FD = cast<FunctionDecl>(D);
895 if (!FD->getReturnType()->isPointerType()) {
896 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
900 const Expr *SizeExpr = AL.getArgAsExpr(0);
902 // Parameter indices are 1-indexed, hence Index=1
903 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1))
905 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
907 ParamIdx SizeArgNo(SizeArgNoVal, D);
909 ParamIdx NumberArgNo;
910 if (AL.getNumArgs() == 2) {
911 const Expr *NumberExpr = AL.getArgAsExpr(1);
913 // Parameter indices are 1-based, hence Index=2
914 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2))
916 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
918 NumberArgNo = ParamIdx(Val, D);
921 D->addAttr(::new (S.Context)
922 AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
923 AL.getAttributeSpellingListIndex()));
926 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
927 SmallVectorImpl<Expr *> &Args) {
928 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
931 if (!isIntOrBool(AL.getArgAsExpr(0))) {
932 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
933 << AL << 1 << AANT_ArgumentIntOrBool;
937 // check that all arguments are lockable objects
938 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
943 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
944 const ParsedAttr &AL) {
945 SmallVector<Expr*, 2> Args;
946 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
949 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
950 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
951 AL.getAttributeSpellingListIndex()));
954 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
955 const ParsedAttr &AL) {
956 SmallVector<Expr*, 2> Args;
957 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
960 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
961 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
962 Args.size(), AL.getAttributeSpellingListIndex()));
965 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
966 // check that the argument is lockable object
967 SmallVector<Expr*, 1> Args;
968 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
969 unsigned Size = Args.size();
973 D->addAttr(::new (S.Context)
974 LockReturnedAttr(AL.getRange(), S.Context, Args[0],
975 AL.getAttributeSpellingListIndex()));
978 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
979 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
982 // check that all arguments are lockable objects
983 SmallVector<Expr*, 1> Args;
984 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
985 unsigned Size = Args.size();
988 Expr **StartArg = &Args[0];
990 D->addAttr(::new (S.Context)
991 LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
992 AL.getAttributeSpellingListIndex()));
995 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
996 Expr *&Cond, StringRef &Msg) {
997 Cond = AL.getArgAsExpr(0);
998 if (!Cond->isTypeDependent()) {
999 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
1000 if (Converted.isInvalid())
1002 Cond = Converted.get();
1005 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
1009 Msg = "<no message provided>";
1011 SmallVector<PartialDiagnosticAt, 8> Diags;
1012 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
1013 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
1015 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
1016 for (const PartialDiagnosticAt &PDiag : Diags)
1017 S.Diag(PDiag.first, PDiag.second);
1023 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1024 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
1028 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1029 D->addAttr(::new (S.Context)
1030 EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
1031 AL.getAttributeSpellingListIndex()));
1035 /// Determines if a given Expr references any of the given function's
1036 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1037 class ArgumentDependenceChecker
1038 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1040 const CXXRecordDecl *ClassType;
1042 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1046 ArgumentDependenceChecker(const FunctionDecl *FD) {
1048 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1049 ClassType = MD->getParent();
1051 ClassType = nullptr;
1053 Parms.insert(FD->param_begin(), FD->param_end());
1056 bool referencesArgs(Expr *E) {
1062 bool VisitCXXThisExpr(CXXThisExpr *E) {
1063 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1064 "`this` doesn't refer to the enclosing class?");
1069 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1070 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1071 if (Parms.count(PVD)) {
1080 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1081 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1085 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1088 StringRef DiagTypeStr;
1089 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1092 DiagnoseIfAttr::DiagnosticType DiagType;
1093 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1094 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1095 diag::err_diagnose_if_invalid_diagnostic_type);
1099 bool ArgDependent = false;
1100 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1101 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1102 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1103 AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
1104 cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
1107 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108 if (D->hasAttr<PassObjectSizeAttr>()) {
1109 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1113 Expr *E = AL.getArgAsExpr(0);
1115 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1118 // pass_object_size's argument is passed in as the second argument of
1119 // __builtin_object_size. So, it has the same constraints as that second
1120 // argument; namely, it must be in the range [0, 3].
1122 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_outof_range)
1123 << AL << 0 << 3 << E->getSourceRange();
1127 // pass_object_size is only supported on constant pointer parameters; as a
1128 // kindness to users, we allow the parameter to be non-const for declarations.
1129 // At this point, we have no clue if `D` belongs to a function declaration or
1130 // definition, so we defer the constness check until later.
1131 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1132 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1136 D->addAttr(::new (S.Context) PassObjectSizeAttr(
1137 AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
1140 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1141 ConsumableAttr::ConsumedState DefaultState;
1143 if (AL.isArgIdent(0)) {
1144 IdentifierLoc *IL = AL.getArgAsIdent(0);
1145 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1147 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1152 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1153 << AL << AANT_ArgumentIdentifier;
1157 D->addAttr(::new (S.Context)
1158 ConsumableAttr(AL.getRange(), S.Context, DefaultState,
1159 AL.getAttributeSpellingListIndex()));
1162 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1163 const ParsedAttr &AL) {
1164 QualType ThisType = MD->getThisType()->getPointeeType();
1166 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1167 if (!RD->hasAttr<ConsumableAttr>()) {
1168 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1169 RD->getNameAsString();
1178 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1179 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1182 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1185 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1186 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1187 CallableWhenAttr::ConsumedState CallableState;
1189 StringRef StateString;
1191 if (AL.isArgIdent(ArgIndex)) {
1192 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1193 StateString = Ident->Ident->getName();
1196 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1200 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1202 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1206 States.push_back(CallableState);
1209 D->addAttr(::new (S.Context)
1210 CallableWhenAttr(AL.getRange(), S.Context, States.data(),
1211 States.size(), AL.getAttributeSpellingListIndex()));
1214 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1215 ParamTypestateAttr::ConsumedState ParamState;
1217 if (AL.isArgIdent(0)) {
1218 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1219 StringRef StateString = Ident->Ident->getName();
1221 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1223 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1224 << AL << StateString;
1228 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1229 << AL << AANT_ArgumentIdentifier;
1233 // FIXME: This check is currently being done in the analysis. It can be
1234 // enabled here only after the parser propagates attributes at
1235 // template specialization definition, not declaration.
1236 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1237 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1239 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1240 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1241 // ReturnType.getAsString();
1245 D->addAttr(::new (S.Context)
1246 ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
1247 AL.getAttributeSpellingListIndex()));
1250 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 ReturnTypestateAttr::ConsumedState ReturnState;
1253 if (AL.isArgIdent(0)) {
1254 IdentifierLoc *IL = AL.getArgAsIdent(0);
1255 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1257 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1262 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1263 << AL << AANT_ArgumentIdentifier;
1267 // FIXME: This check is currently being done in the analysis. It can be
1268 // enabled here only after the parser propagates attributes at
1269 // template specialization definition, not declaration.
1270 //QualType ReturnType;
1272 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1273 // ReturnType = Param->getType();
1275 //} else if (const CXXConstructorDecl *Constructor =
1276 // dyn_cast<CXXConstructorDecl>(D)) {
1277 // ReturnType = Constructor->getThisType()->getPointeeType();
1281 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1284 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1286 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1287 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1288 // ReturnType.getAsString();
1292 D->addAttr(::new (S.Context)
1293 ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
1294 AL.getAttributeSpellingListIndex()));
1297 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1301 SetTypestateAttr::ConsumedState NewState;
1302 if (AL.isArgIdent(0)) {
1303 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1304 StringRef Param = Ident->Ident->getName();
1305 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1306 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1311 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1312 << AL << AANT_ArgumentIdentifier;
1316 D->addAttr(::new (S.Context)
1317 SetTypestateAttr(AL.getRange(), S.Context, NewState,
1318 AL.getAttributeSpellingListIndex()));
1321 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1322 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1325 TestTypestateAttr::ConsumedState TestState;
1326 if (AL.isArgIdent(0)) {
1327 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1328 StringRef Param = Ident->Ident->getName();
1329 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1330 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1335 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1336 << AL << AANT_ArgumentIdentifier;
1340 D->addAttr(::new (S.Context)
1341 TestTypestateAttr(AL.getRange(), S.Context, TestState,
1342 AL.getAttributeSpellingListIndex()));
1345 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1346 // Remember this typedef decl, we will need it later for diagnostics.
1347 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1350 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1351 if (auto *TD = dyn_cast<TagDecl>(D))
1352 TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
1353 AL.getAttributeSpellingListIndex()));
1354 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1355 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1356 !FD->getType()->isIncompleteType() &&
1358 S.Context.getTypeAlign(FD->getType()) <= 8);
1360 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1361 if (BitfieldByteAligned)
1362 // The PS4 target needs to maintain ABI backwards compatibility.
1363 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1364 << AL << FD->getType();
1366 FD->addAttr(::new (S.Context) PackedAttr(
1367 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1369 // Report warning about changed offset in the newer compiler versions.
1370 if (BitfieldByteAligned)
1371 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1373 FD->addAttr(::new (S.Context) PackedAttr(
1374 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1378 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1381 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1382 // The IBOutlet/IBOutletCollection attributes only apply to instance
1383 // variables or properties of Objective-C classes. The outlet must also
1384 // have an object reference type.
1385 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1386 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1387 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1388 << AL << VD->getType() << 0;
1392 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1393 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1394 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1395 << AL << PD->getType() << 1;
1400 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1407 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1408 if (!checkIBOutletCommon(S, D, AL))
1411 D->addAttr(::new (S.Context)
1412 IBOutletAttr(AL.getRange(), S.Context,
1413 AL.getAttributeSpellingListIndex()));
1416 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1418 // The iboutletcollection attribute can have zero or one arguments.
1419 if (AL.getNumArgs() > 1) {
1420 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1424 if (!checkIBOutletCommon(S, D, AL))
1429 if (AL.hasParsedType())
1430 PT = AL.getTypeArg();
1432 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1433 S.getScopeForContext(D->getDeclContext()->getParent()));
1435 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1440 TypeSourceInfo *QTLoc = nullptr;
1441 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1443 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1445 // Diagnose use of non-object type in iboutletcollection attribute.
1446 // FIXME. Gnu attribute extension ignores use of builtin types in
1447 // attributes. So, __attribute__((iboutletcollection(char))) will be
1448 // treated as __attribute__((iboutletcollection())).
1449 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1451 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1452 : diag::err_iboutletcollection_type) << QT;
1456 D->addAttr(::new (S.Context)
1457 IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
1458 AL.getAttributeSpellingListIndex()));
1461 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1463 if (T->isReferenceType())
1466 T = T.getNonReferenceType();
1469 // The nonnull attribute, and other similar attributes, can be applied to a
1470 // transparent union that contains a pointer type.
1471 if (const RecordType *UT = T->getAsUnionType()) {
1472 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1473 RecordDecl *UD = UT->getDecl();
1474 for (const auto *I : UD->fields()) {
1475 QualType QT = I->getType();
1476 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1482 return T->isAnyPointerType() || T->isBlockPointerType();
1485 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1486 SourceRange AttrParmRange,
1487 SourceRange TypeRange,
1488 bool isReturnValue = false) {
1489 if (!S.isValidPointerAttrType(T)) {
1491 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1492 << AL << AttrParmRange << TypeRange;
1494 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1495 << AL << AttrParmRange << TypeRange << 0;
1501 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1502 SmallVector<ParamIdx, 8> NonNullArgs;
1503 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1504 Expr *Ex = AL.getArgAsExpr(I);
1506 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1509 // Is the function argument a pointer type?
1510 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1511 !attrNonNullArgCheck(
1512 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1513 Ex->getSourceRange(),
1514 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1517 NonNullArgs.push_back(Idx);
1520 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1521 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1522 // check if the attribute came from a macro expansion or a template
1524 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1525 !S.inTemplateInstantiation()) {
1526 bool AnyPointers = isFunctionOrMethodVariadic(D);
1527 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1528 I != E && !AnyPointers; ++I) {
1529 QualType T = getFunctionOrMethodParamType(D, I);
1530 if (T->isDependentType() || S.isValidPointerAttrType(T))
1535 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1538 ParamIdx *Start = NonNullArgs.data();
1539 unsigned Size = NonNullArgs.size();
1540 llvm::array_pod_sort(Start, Start + Size);
1541 D->addAttr(::new (S.Context)
1542 NonNullAttr(AL.getRange(), S.Context, Start, Size,
1543 AL.getAttributeSpellingListIndex()));
1546 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1547 const ParsedAttr &AL) {
1548 if (AL.getNumArgs() > 0) {
1549 if (D->getFunctionType()) {
1550 handleNonNullAttr(S, D, AL);
1552 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1553 << D->getSourceRange();
1558 // Is the argument a pointer type?
1559 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1560 D->getSourceRange()))
1563 D->addAttr(::new (S.Context)
1564 NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
1565 AL.getAttributeSpellingListIndex()));
1568 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1569 QualType ResultType = getFunctionOrMethodResultType(D);
1570 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1571 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1572 /* isReturnValue */ true))
1575 D->addAttr(::new (S.Context)
1576 ReturnsNonNullAttr(AL.getRange(), S.Context,
1577 AL.getAttributeSpellingListIndex()));
1580 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1581 if (D->isInvalidDecl())
1584 // noescape only applies to pointer types.
1585 QualType T = cast<ParmVarDecl>(D)->getType();
1586 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1587 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588 << AL << AL.getRange() << 0;
1592 D->addAttr(::new (S.Context) NoEscapeAttr(
1593 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1596 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1597 Expr *E = AL.getArgAsExpr(0),
1598 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1599 S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
1600 AL.getAttributeSpellingListIndex());
1603 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1604 S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
1605 AL.getAttributeSpellingListIndex());
1608 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1609 Expr *OE, unsigned SpellingListIndex) {
1610 QualType ResultType = getFunctionOrMethodResultType(D);
1611 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1613 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1614 SourceLocation AttrLoc = AttrRange.getBegin();
1616 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1617 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1618 << &TmpAttr << AttrRange << SR;
1622 if (!E->isValueDependent()) {
1624 if (!E->isIntegerConstantExpr(I, Context)) {
1626 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1627 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1628 << E->getSourceRange();
1630 Diag(AttrLoc, diag::err_attribute_argument_type)
1631 << &TmpAttr << AANT_ArgumentIntegerConstant
1632 << E->getSourceRange();
1636 if (!I.isPowerOf2()) {
1637 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1638 << E->getSourceRange();
1644 if (!OE->isValueDependent()) {
1646 if (!OE->isIntegerConstantExpr(I, Context)) {
1647 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1648 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1649 << OE->getSourceRange();
1655 D->addAttr(::new (Context)
1656 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1659 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1660 unsigned SpellingListIndex) {
1661 QualType ResultType = getFunctionOrMethodResultType(D);
1663 AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
1664 SourceLocation AttrLoc = AttrRange.getBegin();
1666 if (!ResultType->isDependentType() &&
1667 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1668 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1669 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1674 const auto *FuncDecl = cast<FunctionDecl>(D);
1675 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1676 /*AttrArgNo=*/1, ParamExpr, Idx))
1679 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1680 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1681 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1683 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1687 D->addAttr(::new (Context)
1688 AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
1691 /// Normalize the attribute, __foo__ becomes foo.
1692 /// Returns true if normalization was applied.
1693 static bool normalizeName(StringRef &AttrName) {
1694 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1695 AttrName.endswith("__")) {
1696 AttrName = AttrName.drop_front(2).drop_back(2);
1702 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1703 // This attribute must be applied to a function declaration. The first
1704 // argument to the attribute must be an identifier, the name of the resource,
1705 // for example: malloc. The following arguments must be argument indexes, the
1706 // arguments must be of integer type for Returns, otherwise of pointer type.
1707 // The difference between Holds and Takes is that a pointer may still be used
1708 // after being held. free() should be __attribute((ownership_takes)), whereas
1709 // a list append function may well be __attribute((ownership_holds)).
1711 if (!AL.isArgIdent(0)) {
1712 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1713 << AL << 1 << AANT_ArgumentIdentifier;
1717 // Figure out our Kind.
1718 OwnershipAttr::OwnershipKind K =
1719 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1720 AL.getAttributeSpellingListIndex()).getOwnKind();
1724 case OwnershipAttr::Takes:
1725 case OwnershipAttr::Holds:
1726 if (AL.getNumArgs() < 2) {
1727 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1731 case OwnershipAttr::Returns:
1732 if (AL.getNumArgs() > 2) {
1733 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1739 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1741 StringRef ModuleName = Module->getName();
1742 if (normalizeName(ModuleName)) {
1743 Module = &S.PP.getIdentifierTable().get(ModuleName);
1746 SmallVector<ParamIdx, 8> OwnershipArgs;
1747 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1748 Expr *Ex = AL.getArgAsExpr(i);
1750 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1753 // Is the function argument a pointer type?
1754 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1755 int Err = -1; // No error
1757 case OwnershipAttr::Takes:
1758 case OwnershipAttr::Holds:
1759 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1762 case OwnershipAttr::Returns:
1763 if (!T->isIntegerType())
1768 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1769 << Ex->getSourceRange();
1773 // Check we don't have a conflict with another ownership attribute.
1774 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1775 // Cannot have two ownership attributes of different kinds for the same
1777 if (I->getOwnKind() != K && I->args_end() !=
1778 std::find(I->args_begin(), I->args_end(), Idx)) {
1779 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1781 } else if (K == OwnershipAttr::Returns &&
1782 I->getOwnKind() == OwnershipAttr::Returns) {
1783 // A returns attribute conflicts with any other returns attribute using
1784 // a different index.
1785 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1786 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1787 << I->args_begin()->getSourceIndex();
1789 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1790 << Idx.getSourceIndex() << Ex->getSourceRange();
1795 OwnershipArgs.push_back(Idx);
1798 ParamIdx *Start = OwnershipArgs.data();
1799 unsigned Size = OwnershipArgs.size();
1800 llvm::array_pod_sort(Start, Start + Size);
1801 D->addAttr(::new (S.Context)
1802 OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
1803 AL.getAttributeSpellingListIndex()));
1806 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1807 // Check the attribute arguments.
1808 if (AL.getNumArgs() > 1) {
1809 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1815 // static int a __attribute__((weakref ("v2")));
1816 // static int b() __attribute__((weakref ("f3")));
1818 // and ignores the attributes of
1820 // static int a __attribute__((weakref ("v2")));
1823 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1824 if (!Ctx->isFileContext()) {
1825 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1826 << cast<NamedDecl>(D);
1830 // The GCC manual says
1832 // At present, a declaration to which `weakref' is attached can only
1837 // Without a TARGET,
1838 // given as an argument to `weakref' or to `alias', `weakref' is
1839 // equivalent to `weak'.
1841 // gcc 4.4.1 will accept
1842 // int a7 __attribute__((weakref));
1844 // int a7 __attribute__((weak));
1845 // This looks like a bug in gcc. We reject that for now. We should revisit
1846 // it if this behaviour is actually used.
1849 // static ((alias ("y"), weakref)).
1850 // Should we? How to check that weakref is before or after alias?
1852 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1853 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1854 // StringRef parameter it was given anyway.
1856 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1857 // GCC will accept anything as the argument of weakref. Should we
1858 // check for an existing decl?
1859 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1860 AL.getAttributeSpellingListIndex()));
1862 D->addAttr(::new (S.Context)
1863 WeakRefAttr(AL.getRange(), S.Context,
1864 AL.getAttributeSpellingListIndex()));
1867 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1869 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1872 // Aliases should be on declarations, not definitions.
1873 const auto *FD = cast<FunctionDecl>(D);
1874 if (FD->isThisDeclarationADefinition()) {
1875 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1879 D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
1880 AL.getAttributeSpellingListIndex()));
1883 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1885 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1888 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1889 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1892 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1893 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1896 // Aliases should be on declarations, not definitions.
1897 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (FD->isThisDeclarationADefinition()) {
1899 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1903 const auto *VD = cast<VarDecl>(D);
1904 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1905 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1910 // Mark target used to prevent unneeded-internal-declaration warnings.
1911 if (!S.LangOpts.CPlusPlus) {
1912 // FIXME: demangle Str for C++, as the attribute refers to the mangled
1913 // linkage name, not the pre-mangled identifier.
1914 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1915 LookupResult LR(S, target, Sema::LookupOrdinaryName);
1916 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1917 for (NamedDecl *ND : LR)
1918 ND->markUsed(S.Context);
1921 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1922 AL.getAttributeSpellingListIndex()));
1925 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1927 SourceLocation LiteralLoc;
1928 // Check that it is a string.
1929 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1932 // Check that the value.
1933 if (Model != "global-dynamic" && Model != "local-dynamic"
1934 && Model != "initial-exec" && Model != "local-exec") {
1935 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1939 D->addAttr(::new (S.Context)
1940 TLSModelAttr(AL.getRange(), S.Context, Model,
1941 AL.getAttributeSpellingListIndex()));
1944 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1945 QualType ResultType = getFunctionOrMethodResultType(D);
1946 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1947 D->addAttr(::new (S.Context) RestrictAttr(
1948 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1952 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1953 << AL << getFunctionOrMethodResultSourceRange(D);
1956 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1957 FunctionDecl *FD = cast<FunctionDecl>(D);
1959 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1960 if (MD->getParent()->isLambda()) {
1961 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1966 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1969 SmallVector<IdentifierInfo *, 8> CPUs;
1970 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1971 if (!AL.isArgIdent(ArgNo)) {
1972 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1973 << AL << AANT_ArgumentIdentifier;
1977 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1978 StringRef CPUName = CPUArg->Ident->getName().trim();
1980 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1981 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1982 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1986 const TargetInfo &Target = S.Context.getTargetInfo();
1987 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1988 return Target.CPUSpecificManglingCharacter(CPUName) ==
1989 Target.CPUSpecificManglingCharacter(Cur->getName());
1991 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1994 CPUs.push_back(CPUArg->Ident);
1997 FD->setIsMultiVersion(true);
1998 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1999 D->addAttr(::new (S.Context) CPUSpecificAttr(
2000 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2001 AL.getAttributeSpellingListIndex()));
2003 D->addAttr(::new (S.Context) CPUDispatchAttr(
2004 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2005 AL.getAttributeSpellingListIndex()));
2008 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2009 if (S.LangOpts.CPlusPlus) {
2010 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2011 << AL << AttributeLangSupport::Cpp;
2015 if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
2019 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2020 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2023 if (AL.isDeclspecAttribute()) {
2024 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2025 const auto &Arch = Triple.getArch();
2026 if (Arch != llvm::Triple::x86 &&
2027 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2028 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2029 << AL << Triple.getArchName();
2034 D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
2035 AL.getAttributeSpellingListIndex()));
2038 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2039 if (hasDeclarator(D)) return;
2041 if (!isa<ObjCMethodDecl>(D)) {
2042 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2043 << Attrs << ExpectedFunctionOrMethod;
2047 D->addAttr(::new (S.Context) NoReturnAttr(
2048 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
2051 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2052 if (!S.getLangOpts().CFProtectionBranch)
2053 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2055 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2058 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2059 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2067 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2068 // Check whether the attribute is valid on the current target.
2069 if (!AL.existsInTarget(Context.getTargetInfo())) {
2070 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2078 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2080 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2081 // because 'analyzer_noreturn' does not impact the type.
2082 if (!isFunctionOrMethodOrBlock(D)) {
2083 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2084 if (!VD || (!VD->getType()->isBlockPointerType() &&
2085 !VD->getType()->isFunctionPointerType())) {
2086 S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2087 ? diag::err_attribute_wrong_decl_type
2088 : diag::warn_attribute_wrong_decl_type)
2089 << AL << ExpectedFunctionMethodOrBlock;
2094 D->addAttr(::new (S.Context)
2095 AnalyzerNoReturnAttr(AL.getRange(), S.Context,
2096 AL.getAttributeSpellingListIndex()));
2099 // PS3 PPU-specific.
2100 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2102 Returning a Vector Class in Registers
2104 According to the PPU ABI specifications, a class with a single member of
2105 vector type is returned in memory when used as the return value of a
2107 This results in inefficient code when implementing vector classes. To return
2108 the value in a single vector register, add the vecreturn attribute to the
2109 class definition. This attribute is also applicable to struct types.
2115 __vector float xyzw;
2116 } __attribute__((vecreturn));
2118 Vector Add(Vector lhs, Vector rhs)
2121 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2122 return result; // This will be returned in a register
2125 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2126 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2130 const auto *R = cast<RecordDecl>(D);
2133 if (!isa<CXXRecordDecl>(R)) {
2134 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2138 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2139 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2143 for (const auto *I : R->fields()) {
2144 if ((count == 1) || !I->getType()->isVectorType()) {
2145 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2151 D->addAttr(::new (S.Context) VecReturnAttr(
2152 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2155 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2156 const ParsedAttr &AL) {
2157 if (isa<ParmVarDecl>(D)) {
2158 // [[carries_dependency]] can only be applied to a parameter if it is a
2159 // parameter of a function declaration or lambda.
2160 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2162 diag::err_carries_dependency_param_not_function_decl);
2167 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2168 AL.getRange(), S.Context,
2169 AL.getAttributeSpellingListIndex()));
2172 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2173 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2175 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2176 // about using it as an extension.
2177 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2178 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2180 D->addAttr(::new (S.Context) UnusedAttr(
2181 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2184 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2185 uint32_t priority = ConstructorAttr::DefaultPriority;
2186 if (AL.getNumArgs() &&
2187 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2190 D->addAttr(::new (S.Context)
2191 ConstructorAttr(AL.getRange(), S.Context, priority,
2192 AL.getAttributeSpellingListIndex()));
2195 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2196 uint32_t priority = DestructorAttr::DefaultPriority;
2197 if (AL.getNumArgs() &&
2198 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2201 D->addAttr(::new (S.Context)
2202 DestructorAttr(AL.getRange(), S.Context, priority,
2203 AL.getAttributeSpellingListIndex()));
2206 template <typename AttrTy>
2207 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2208 // Handle the case where the attribute has a text message.
2210 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2213 D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
2214 AL.getAttributeSpellingListIndex()));
2217 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2218 const ParsedAttr &AL) {
2219 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2220 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2221 << AL << AL.getRange();
2225 D->addAttr(::new (S.Context)
2226 ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
2227 AL.getAttributeSpellingListIndex()));
2230 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2231 IdentifierInfo *Platform,
2232 VersionTuple Introduced,
2233 VersionTuple Deprecated,
2234 VersionTuple Obsoleted) {
2235 StringRef PlatformName
2236 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2237 if (PlatformName.empty())
2238 PlatformName = Platform->getName();
2240 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2241 // of these steps are needed).
2242 if (!Introduced.empty() && !Deprecated.empty() &&
2243 !(Introduced <= Deprecated)) {
2244 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2245 << 1 << PlatformName << Deprecated.getAsString()
2246 << 0 << Introduced.getAsString();
2250 if (!Introduced.empty() && !Obsoleted.empty() &&
2251 !(Introduced <= Obsoleted)) {
2252 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2253 << 2 << PlatformName << Obsoleted.getAsString()
2254 << 0 << Introduced.getAsString();
2258 if (!Deprecated.empty() && !Obsoleted.empty() &&
2259 !(Deprecated <= Obsoleted)) {
2260 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2261 << 2 << PlatformName << Obsoleted.getAsString()
2262 << 1 << Deprecated.getAsString();
2269 /// Check whether the two versions match.
2271 /// If either version tuple is empty, then they are assumed to match. If
2272 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2273 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2274 bool BeforeIsOkay) {
2275 if (X.empty() || Y.empty())
2281 if (BeforeIsOkay && X < Y)
2287 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2288 IdentifierInfo *Platform,
2290 VersionTuple Introduced,
2291 VersionTuple Deprecated,
2292 VersionTuple Obsoleted,
2296 StringRef Replacement,
2297 AvailabilityMergeKind AMK,
2298 unsigned AttrSpellingListIndex) {
2299 VersionTuple MergedIntroduced = Introduced;
2300 VersionTuple MergedDeprecated = Deprecated;
2301 VersionTuple MergedObsoleted = Obsoleted;
2302 bool FoundAny = false;
2303 bool OverrideOrImpl = false;
2306 case AMK_Redeclaration:
2307 OverrideOrImpl = false;
2311 case AMK_ProtocolImplementation:
2312 OverrideOrImpl = true;
2316 if (D->hasAttrs()) {
2317 AttrVec &Attrs = D->getAttrs();
2318 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2319 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2325 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2326 if (OldPlatform != Platform) {
2331 // If there is an existing availability attribute for this platform that
2332 // is explicit and the new one is implicit use the explicit one and
2333 // discard the new implicit attribute.
2334 if (!OldAA->isImplicit() && Implicit) {
2338 // If there is an existing attribute for this platform that is implicit
2339 // and the new attribute is explicit then erase the old one and
2340 // continue processing the attributes.
2341 if (!Implicit && OldAA->isImplicit()) {
2342 Attrs.erase(Attrs.begin() + i);
2348 VersionTuple OldIntroduced = OldAA->getIntroduced();
2349 VersionTuple OldDeprecated = OldAA->getDeprecated();
2350 VersionTuple OldObsoleted = OldAA->getObsoleted();
2351 bool OldIsUnavailable = OldAA->getUnavailable();
2353 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2354 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2355 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2356 !(OldIsUnavailable == IsUnavailable ||
2357 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2358 if (OverrideOrImpl) {
2360 VersionTuple FirstVersion;
2361 VersionTuple SecondVersion;
2362 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2364 FirstVersion = OldIntroduced;
2365 SecondVersion = Introduced;
2366 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2368 FirstVersion = Deprecated;
2369 SecondVersion = OldDeprecated;
2370 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2372 FirstVersion = Obsoleted;
2373 SecondVersion = OldObsoleted;
2377 Diag(OldAA->getLocation(),
2378 diag::warn_mismatched_availability_override_unavail)
2379 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2380 << (AMK == AMK_Override);
2382 Diag(OldAA->getLocation(),
2383 diag::warn_mismatched_availability_override)
2385 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2386 << FirstVersion.getAsString() << SecondVersion.getAsString()
2387 << (AMK == AMK_Override);
2389 if (AMK == AMK_Override)
2390 Diag(Range.getBegin(), diag::note_overridden_method);
2392 Diag(Range.getBegin(), diag::note_protocol_method);
2394 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2395 Diag(Range.getBegin(), diag::note_previous_attribute);
2398 Attrs.erase(Attrs.begin() + i);
2403 VersionTuple MergedIntroduced2 = MergedIntroduced;
2404 VersionTuple MergedDeprecated2 = MergedDeprecated;
2405 VersionTuple MergedObsoleted2 = MergedObsoleted;
2407 if (MergedIntroduced2.empty())
2408 MergedIntroduced2 = OldIntroduced;
2409 if (MergedDeprecated2.empty())
2410 MergedDeprecated2 = OldDeprecated;
2411 if (MergedObsoleted2.empty())
2412 MergedObsoleted2 = OldObsoleted;
2414 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2415 MergedIntroduced2, MergedDeprecated2,
2416 MergedObsoleted2)) {
2417 Attrs.erase(Attrs.begin() + i);
2422 MergedIntroduced = MergedIntroduced2;
2423 MergedDeprecated = MergedDeprecated2;
2424 MergedObsoleted = MergedObsoleted2;
2430 MergedIntroduced == Introduced &&
2431 MergedDeprecated == Deprecated &&
2432 MergedObsoleted == Obsoleted)
2435 // Only create a new attribute if !OverrideOrImpl, but we want to do
2437 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2438 MergedDeprecated, MergedObsoleted) &&
2440 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2441 Introduced, Deprecated,
2442 Obsoleted, IsUnavailable, Message,
2443 IsStrict, Replacement,
2444 AttrSpellingListIndex);
2445 Avail->setImplicit(Implicit);
2451 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2452 if (!checkAttributeNumArgs(S, AL, 1))
2454 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2455 unsigned Index = AL.getAttributeSpellingListIndex();
2457 IdentifierInfo *II = Platform->Ident;
2458 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2459 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2462 auto *ND = dyn_cast<NamedDecl>(D);
2463 if (!ND) // We warned about this already, so just return.
2466 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2467 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2468 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2469 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2470 bool IsStrict = AL.getStrictLoc().isValid();
2472 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2473 Str = SE->getString();
2474 StringRef Replacement;
2475 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2476 Replacement = SE->getString();
2478 if (II->isStr("swift")) {
2479 if (Introduced.isValid() || Obsoleted.isValid() ||
2480 (!IsUnavailable && !Deprecated.isValid())) {
2482 diag::warn_availability_swift_unavailable_deprecated_only);
2487 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II,
2493 IsStrict, Replacement,
2497 D->addAttr(NewAttr);
2499 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2500 // matches before the start of the watchOS platform.
2501 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2502 IdentifierInfo *NewII = nullptr;
2503 if (II->getName() == "ios")
2504 NewII = &S.Context.Idents.get("watchos");
2505 else if (II->getName() == "ios_app_extension")
2506 NewII = &S.Context.Idents.get("watchos_app_extension");
2509 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2510 if (Version.empty())
2512 auto Major = Version.getMajor();
2513 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2514 if (NewMajor >= 2) {
2515 if (Version.getMinor().hasValue()) {
2516 if (Version.getSubminor().hasValue())
2517 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2518 Version.getSubminor().getValue());
2520 return VersionTuple(NewMajor, Version.getMinor().getValue());
2524 return VersionTuple(2, 0);
2527 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2528 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2529 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2531 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2544 D->addAttr(NewAttr);
2546 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2547 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2548 // matches before the start of the tvOS platform.
2549 IdentifierInfo *NewII = nullptr;
2550 if (II->getName() == "ios")
2551 NewII = &S.Context.Idents.get("tvos");
2552 else if (II->getName() == "ios_app_extension")
2553 NewII = &S.Context.Idents.get("tvos_app_extension");
2556 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2569 D->addAttr(NewAttr);
2574 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2575 const ParsedAttr &AL) {
2576 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2578 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2579 "Invalid number of arguments in an external_source_symbol attribute");
2582 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2583 Language = SE->getString();
2584 StringRef DefinedIn;
2585 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2586 DefinedIn = SE->getString();
2587 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2589 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2590 AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2591 AL.getAttributeSpellingListIndex()));
2595 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2596 typename T::VisibilityType value,
2597 unsigned attrSpellingListIndex) {
2598 T *existingAttr = D->getAttr<T>();
2600 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2601 if (existingValue == value)
2603 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2604 S.Diag(range.getBegin(), diag::note_previous_attribute);
2607 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2610 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2611 VisibilityAttr::VisibilityType Vis,
2612 unsigned AttrSpellingListIndex) {
2613 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2614 AttrSpellingListIndex);
2617 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2618 TypeVisibilityAttr::VisibilityType Vis,
2619 unsigned AttrSpellingListIndex) {
2620 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2621 AttrSpellingListIndex);
2624 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2625 bool isTypeVisibility) {
2626 // Visibility attributes don't mean anything on a typedef.
2627 if (isa<TypedefNameDecl>(D)) {
2628 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2632 // 'type_visibility' can only go on a type or namespace.
2633 if (isTypeVisibility &&
2634 !(isa<TagDecl>(D) ||
2635 isa<ObjCInterfaceDecl>(D) ||
2636 isa<NamespaceDecl>(D))) {
2637 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2638 << AL << ExpectedTypeOrNamespace;
2642 // Check that the argument is a string literal.
2644 SourceLocation LiteralLoc;
2645 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2648 VisibilityAttr::VisibilityType type;
2649 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2650 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2655 // Complain about attempts to use protected visibility on targets
2656 // (like Darwin) that don't support it.
2657 if (type == VisibilityAttr::Protected &&
2658 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2659 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2660 type = VisibilityAttr::Default;
2663 unsigned Index = AL.getAttributeSpellingListIndex();
2665 if (isTypeVisibility) {
2666 newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2667 (TypeVisibilityAttr::VisibilityType) type,
2670 newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2673 D->addAttr(newAttr);
2676 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2677 const auto *M = cast<ObjCMethodDecl>(D);
2678 if (!AL.isArgIdent(0)) {
2679 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2680 << AL << 1 << AANT_ArgumentIdentifier;
2684 IdentifierLoc *IL = AL.getArgAsIdent(0);
2685 ObjCMethodFamilyAttr::FamilyKind F;
2686 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2687 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2691 if (F == ObjCMethodFamilyAttr::OMF_init &&
2692 !M->getReturnType()->isObjCObjectPointerType()) {
2693 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2694 << M->getReturnType();
2695 // Ignore the attribute.
2699 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2700 AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2703 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2704 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2705 QualType T = TD->getUnderlyingType();
2706 if (!T->isCARCBridgableType()) {
2707 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2711 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2712 QualType T = PD->getType();
2713 if (!T->isCARCBridgableType()) {
2714 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2719 // It is okay to include this attribute on properties, e.g.:
2721 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2723 // In this case it follows tradition and suppresses an error in the above
2725 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2727 D->addAttr(::new (S.Context)
2728 ObjCNSObjectAttr(AL.getRange(), S.Context,
2729 AL.getAttributeSpellingListIndex()));
2732 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2733 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2734 QualType T = TD->getUnderlyingType();
2735 if (!T->isObjCObjectPointerType()) {
2736 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2740 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2743 D->addAttr(::new (S.Context)
2744 ObjCIndependentClassAttr(AL.getRange(), S.Context,
2745 AL.getAttributeSpellingListIndex()));
2748 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2749 if (!AL.isArgIdent(0)) {
2750 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2751 << AL << 1 << AANT_ArgumentIdentifier;
2755 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2756 BlocksAttr::BlockType type;
2757 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2758 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2762 D->addAttr(::new (S.Context)
2763 BlocksAttr(AL.getRange(), S.Context, type,
2764 AL.getAttributeSpellingListIndex()));
2767 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2768 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2769 if (AL.getNumArgs() > 0) {
2770 Expr *E = AL.getArgAsExpr(0);
2771 llvm::APSInt Idx(32);
2772 if (E->isTypeDependent() || E->isValueDependent() ||
2773 !E->isIntegerConstantExpr(Idx, S.Context)) {
2774 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2775 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2779 if (Idx.isSigned() && Idx.isNegative()) {
2780 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2781 << E->getSourceRange();
2785 sentinel = Idx.getZExtValue();
2788 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2789 if (AL.getNumArgs() > 1) {
2790 Expr *E = AL.getArgAsExpr(1);
2791 llvm::APSInt Idx(32);
2792 if (E->isTypeDependent() || E->isValueDependent() ||
2793 !E->isIntegerConstantExpr(Idx, S.Context)) {
2794 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2795 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2798 nullPos = Idx.getZExtValue();
2800 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2801 // FIXME: This error message could be improved, it would be nice
2802 // to say what the bounds actually are.
2803 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2804 << E->getSourceRange();
2809 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2810 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2811 if (isa<FunctionNoProtoType>(FT)) {
2812 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2816 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2817 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2820 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2821 if (!MD->isVariadic()) {
2822 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2825 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2826 if (!BD->isVariadic()) {
2827 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2830 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2831 QualType Ty = V->getType();
2832 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2833 const FunctionType *FT = Ty->isFunctionPointerType()
2834 ? D->getFunctionType()
2835 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2836 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2837 int m = Ty->isFunctionPointerType() ? 0 : 1;
2838 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2842 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2843 << AL << ExpectedFunctionMethodOrBlock;
2847 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2848 << AL << ExpectedFunctionMethodOrBlock;
2851 D->addAttr(::new (S.Context)
2852 SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2853 AL.getAttributeSpellingListIndex()));
2856 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2857 if (D->getFunctionType() &&
2858 D->getFunctionType()->getReturnType()->isVoidType()) {
2859 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2862 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2863 if (MD->getReturnType()->isVoidType()) {
2864 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2868 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2869 // about using it as an extension.
2870 if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
2872 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2874 D->addAttr(::new (S.Context)
2875 WarnUnusedResultAttr(AL.getRange(), S.Context,
2876 AL.getAttributeSpellingListIndex()));
2879 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2880 // weak_import only applies to variable & function declarations.
2882 if (!D->canBeWeakImported(isDef)) {
2884 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2886 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2887 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2888 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2889 // Nothing to warn about here.
2891 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2892 << AL << ExpectedVariableOrFunction;
2897 D->addAttr(::new (S.Context)
2898 WeakImportAttr(AL.getRange(), S.Context,
2899 AL.getAttributeSpellingListIndex()));
2902 // Handles reqd_work_group_size and work_group_size_hint.
2903 template <typename WorkGroupAttr>
2904 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2906 for (unsigned i = 0; i < 3; ++i) {
2907 const Expr *E = AL.getArgAsExpr(i);
2908 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2909 /*StrictlyUnsigned=*/true))
2911 if (WGSize[i] == 0) {
2912 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2913 << AL << E->getSourceRange();
2918 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2919 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2920 Existing->getYDim() == WGSize[1] &&
2921 Existing->getZDim() == WGSize[2]))
2922 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2924 D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2925 WGSize[0], WGSize[1], WGSize[2],
2926 AL.getAttributeSpellingListIndex()));
2929 // Handles intel_reqd_sub_group_size.
2930 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2932 const Expr *E = AL.getArgAsExpr(0);
2933 if (!checkUInt32Argument(S, AL, E, SGSize))
2936 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2937 << AL << E->getSourceRange();
2941 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2942 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2943 if (Existing && Existing->getSubGroupSize() != SGSize)
2944 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2946 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2947 AL.getRange(), S.Context, SGSize,
2948 AL.getAttributeSpellingListIndex()));
2951 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2952 if (!AL.hasParsedType()) {
2953 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2957 TypeSourceInfo *ParmTSI = nullptr;
2958 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2959 assert(ParmTSI && "no type source info for attribute argument");
2961 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2962 (ParmType->isBooleanType() ||
2963 !ParmType->isIntegralType(S.getASTContext()))) {
2964 S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2969 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2970 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2971 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2976 D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2978 AL.getAttributeSpellingListIndex()));
2981 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2983 unsigned AttrSpellingListIndex) {
2984 // Explicit or partial specializations do not inherit
2985 // the section attribute from the primary template.
2986 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2987 if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2988 FD->isFunctionTemplateSpecialization())
2991 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2992 if (ExistingAttr->getName() == Name)
2994 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2996 Diag(Range.getBegin(), diag::note_previous_attribute);
2999 return ::new (Context) SectionAttr(Range, Context, Name,
3000 AttrSpellingListIndex);
3003 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3004 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
3005 if (!Error.empty()) {
3006 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3013 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3014 // Make sure that there is a string literal as the sections's single
3017 SourceLocation LiteralLoc;
3018 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3021 if (!S.checkSectionName(LiteralLoc, Str))
3024 // If the target wants to validate the section specifier, make it happen.
3025 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3026 if (!Error.empty()) {
3027 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3032 unsigned Index = AL.getAttributeSpellingListIndex();
3033 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
3035 D->addAttr(NewAttr);
3038 static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) {
3039 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3040 if (!Error.empty()) {
3041 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3042 << 0 /*'code-seg'*/;
3048 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
3050 unsigned AttrSpellingListIndex) {
3051 // Explicit or partial specializations do not inherit
3052 // the code_seg attribute from the primary template.
3053 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3054 if (FD->isFunctionTemplateSpecialization())
3057 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3058 if (ExistingAttr->getName() == Name)
3060 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3062 Diag(Range.getBegin(), diag::note_previous_attribute);
3065 return ::new (Context) CodeSegAttr(Range, Context, Name,
3066 AttrSpellingListIndex);
3069 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3071 SourceLocation LiteralLoc;
3072 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3074 if (!checkCodeSegName(S, LiteralLoc, Str))
3076 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3077 if (!ExistingAttr->isImplicit()) {
3079 ExistingAttr->getName() == Str
3080 ? diag::warn_duplicate_codeseg_attribute
3081 : diag::err_conflicting_codeseg_attribute);
3084 D->dropAttr<CodeSegAttr>();
3086 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
3087 AL.getAttributeSpellingListIndex()))
3091 // Check for things we'd like to warn about. Multiversioning issues are
3092 // handled later in the process, once we know how many exist.
3093 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3094 enum FirstParam { Unsupported, Duplicate };
3095 enum SecondParam { None, Architecture };
3096 for (auto Str : {"tune=", "fpmath="})
3097 if (AttrStr.find(Str) != StringRef::npos)
3098 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3099 << Unsupported << None << Str;
3101 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3103 if (!ParsedAttrs.Architecture.empty() &&
3104 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3105 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3106 << Unsupported << Architecture << ParsedAttrs.Architecture;
3108 if (ParsedAttrs.DuplicateArchitecture)
3109 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3110 << Duplicate << None << "arch=";
3112 for (const auto &Feature : ParsedAttrs.Features) {
3113 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3114 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3115 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3116 << Unsupported << None << CurFeature;
3122 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3124 SourceLocation LiteralLoc;
3125 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3126 S.checkTargetAttr(LiteralLoc, Str))
3129 unsigned Index = AL.getAttributeSpellingListIndex();
3130 TargetAttr *NewAttr =
3131 ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
3132 D->addAttr(NewAttr);
3135 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3136 Expr *E = AL.getArgAsExpr(0);
3138 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3143 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3144 if (Existing && Existing->getVectorWidth() != VecWidth) {
3145 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3149 D->addAttr(::new (S.Context)
3150 MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
3151 AL.getAttributeSpellingListIndex()));
3154 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3155 Expr *E = AL.getArgAsExpr(0);
3156 SourceLocation Loc = E->getExprLoc();
3157 FunctionDecl *FD = nullptr;
3158 DeclarationNameInfo NI;
3160 // gcc only allows for simple identifiers. Since we support more than gcc, we
3161 // will warn the user.
3162 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3163 if (DRE->hasQualifier())
3164 S.Diag(Loc, diag::warn_cleanup_ext);
3165 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3166 NI = DRE->getNameInfo();
3168 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3172 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3173 if (ULE->hasExplicitTemplateArgs())
3174 S.Diag(Loc, diag::warn_cleanup_ext);
3175 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3176 NI = ULE->getNameInfo();
3178 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3180 if (ULE->getType() == S.Context.OverloadTy)
3181 S.NoteAllOverloadCandidates(ULE);
3185 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3189 if (FD->getNumParams() != 1) {
3190 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3195 // We're currently more strict than GCC about what function types we accept.
3196 // If this ever proves to be a problem it should be easy to fix.
3197 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3198 QualType ParamTy = FD->getParamDecl(0)->getType();
3199 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3200 ParamTy, Ty) != Sema::Compatible) {
3201 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3202 << NI.getName() << ParamTy << Ty;
3206 D->addAttr(::new (S.Context)
3207 CleanupAttr(AL.getRange(), S.Context, FD,
3208 AL.getAttributeSpellingListIndex()));
3211 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3212 const ParsedAttr &AL) {
3213 if (!AL.isArgIdent(0)) {
3214 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3215 << AL << 0 << AANT_ArgumentIdentifier;
3219 EnumExtensibilityAttr::Kind ExtensibilityKind;
3220 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3221 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3222 ExtensibilityKind)) {
3223 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3227 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3228 AL.getRange(), S.Context, ExtensibilityKind,
3229 AL.getAttributeSpellingListIndex()));
3232 /// Handle __attribute__((format_arg((idx)))) attribute based on
3233 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3234 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3235 Expr *IdxExpr = AL.getArgAsExpr(0);
3237 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3240 // Make sure the format string is really a string.
3241 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3243 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3244 if (NotNSStringTy &&
3245 !isCFStringType(Ty, S.Context) &&
3246 (!Ty->isPointerType() ||
3247 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3248 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3249 << "a string type" << IdxExpr->getSourceRange()
3250 << getFunctionOrMethodParamRange(D, 0);
3253 Ty = getFunctionOrMethodResultType(D);
3254 if (!isNSStringType(Ty, S.Context) &&
3255 !isCFStringType(Ty, S.Context) &&
3256 (!Ty->isPointerType() ||
3257 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3258 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3259 << (NotNSStringTy ? "string type" : "NSString")
3260 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3264 D->addAttr(::new (S.Context) FormatArgAttr(
3265 AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3268 enum FormatAttrKind {
3277 /// getFormatAttrKind - Map from format attribute names to supported format
3279 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3280 return llvm::StringSwitch<FormatAttrKind>(Format)
3281 // Check for formats that get handled specially.
3282 .Case("NSString", NSStringFormat)
3283 .Case("CFString", CFStringFormat)
3284 .Case("strftime", StrftimeFormat)
3286 // Otherwise, check for supported formats.
3287 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3288 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3289 .Case("kprintf", SupportedFormat) // OpenBSD.
3290 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3291 .Case("os_trace", SupportedFormat)
3292 .Case("os_log", SupportedFormat)
3294 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3295 .Default(InvalidFormat);
3298 /// Handle __attribute__((init_priority(priority))) attributes based on
3299 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3300 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3301 if (!S.getLangOpts().CPlusPlus) {
3302 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3306 if (S.getCurFunctionOrMethodDecl()) {
3307 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3311 QualType T = cast<VarDecl>(D)->getType();
3312 if (S.Context.getAsArrayType(T))
3313 T = S.Context.getBaseElementType(T);
3314 if (!T->getAs<RecordType>()) {
3315 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3320 Expr *E = AL.getArgAsExpr(0);
3321 uint32_t prioritynum;
3322 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3327 if (prioritynum < 101 || prioritynum > 65535) {
3328 S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range)
3329 << E->getSourceRange() << AL << 101 << 65535;
3333 D->addAttr(::new (S.Context)
3334 InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3335 AL.getAttributeSpellingListIndex()));
3338 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3339 IdentifierInfo *Format, int FormatIdx,
3341 unsigned AttrSpellingListIndex) {
3342 // Check whether we already have an equivalent format attribute.
3343 for (auto *F : D->specific_attrs<FormatAttr>()) {
3344 if (F->getType() == Format &&
3345 F->getFormatIdx() == FormatIdx &&
3346 F->getFirstArg() == FirstArg) {
3347 // If we don't have a valid location for this attribute, adopt the
3349 if (F->getLocation().isInvalid())
3355 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3356 FirstArg, AttrSpellingListIndex);
3359 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3360 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3361 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3362 if (!AL.isArgIdent(0)) {
3363 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3364 << AL << 1 << AANT_ArgumentIdentifier;
3368 // In C++ the implicit 'this' function parameter also counts, and they are
3369 // counted from one.
3370 bool HasImplicitThisParam = isInstanceMethod(D);
3371 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3373 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3374 StringRef Format = II->getName();
3376 if (normalizeName(Format)) {
3377 // If we've modified the string name, we need a new identifier for it.
3378 II = &S.Context.Idents.get(Format);
3381 // Check for supported formats.
3382 FormatAttrKind Kind = getFormatAttrKind(Format);
3384 if (Kind == IgnoredFormat)
3387 if (Kind == InvalidFormat) {
3388 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3389 << AL << II->getName();
3393 // checks for the 2nd argument
3394 Expr *IdxExpr = AL.getArgAsExpr(1);
3396 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3399 if (Idx < 1 || Idx > NumArgs) {
3400 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3401 << AL << 2 << IdxExpr->getSourceRange();
3405 // FIXME: Do we need to bounds check?
3406 unsigned ArgIdx = Idx - 1;
3408 if (HasImplicitThisParam) {
3411 diag::err_format_attribute_implicit_this_format_string)
3412 << IdxExpr->getSourceRange();
3418 // make sure the format string is really a string
3419 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3421 if (Kind == CFStringFormat) {
3422 if (!isCFStringType(Ty, S.Context)) {
3423 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3424 << "a CFString" << IdxExpr->getSourceRange()
3425 << getFunctionOrMethodParamRange(D, ArgIdx);
3428 } else if (Kind == NSStringFormat) {
3429 // FIXME: do we need to check if the type is NSString*? What are the
3431 if (!isNSStringType(Ty, S.Context)) {
3432 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3433 << "an NSString" << IdxExpr->getSourceRange()
3434 << getFunctionOrMethodParamRange(D, ArgIdx);
3437 } else if (!Ty->isPointerType() ||
3438 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3439 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3440 << "a string type" << IdxExpr->getSourceRange()
3441 << getFunctionOrMethodParamRange(D, ArgIdx);
3445 // check the 3rd argument
3446 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3448 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3451 // check if the function is variadic if the 3rd argument non-zero
3452 if (FirstArg != 0) {
3453 if (isFunctionOrMethodVariadic(D)) {
3454 ++NumArgs; // +1 for ...
3456 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3461 // strftime requires FirstArg to be 0 because it doesn't read from any
3462 // variable the input is just the current time + the format string.
3463 if (Kind == StrftimeFormat) {
3464 if (FirstArg != 0) {
3465 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3466 << FirstArgExpr->getSourceRange();
3469 // if 0 it disables parameter checking (to use with e.g. va_list)
3470 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3471 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3472 << AL << 3 << FirstArgExpr->getSourceRange();
3476 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3478 AL.getAttributeSpellingListIndex());
3480 D->addAttr(NewAttr);
3483 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3484 // Try to find the underlying union declaration.
3485 RecordDecl *RD = nullptr;
3486 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3487 if (TD && TD->getUnderlyingType()->isUnionType())
3488 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3490 RD = dyn_cast<RecordDecl>(D);
3492 if (!RD || !RD->isUnion()) {
3493 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3498 if (!RD->isCompleteDefinition()) {
3499 if (!RD->isBeingDefined())
3501 diag::warn_transparent_union_attribute_not_definition);
3505 RecordDecl::field_iterator Field = RD->field_begin(),
3506 FieldEnd = RD->field_end();
3507 if (Field == FieldEnd) {
3508 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3512 FieldDecl *FirstField = *Field;
3513 QualType FirstType = FirstField->getType();
3514 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3515 S.Diag(FirstField->getLocation(),
3516 diag::warn_transparent_union_attribute_floating)
3517 << FirstType->isVectorType() << FirstType;
3521 if (FirstType->isIncompleteType())
3523 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3524 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3525 for (; Field != FieldEnd; ++Field) {
3526 QualType FieldType = Field->getType();
3527 if (FieldType->isIncompleteType())
3529 // FIXME: this isn't fully correct; we also need to test whether the
3530 // members of the union would all have the same calling convention as the
3531 // first member of the union. Checking just the size and alignment isn't
3532 // sufficient (consider structs passed on the stack instead of in registers
3534 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3535 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3536 // Warn if we drop the attribute.
3537 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3538 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3539 : S.Context.getTypeAlign(FieldType);
3540 S.Diag(Field->getLocation(),
3541 diag::warn_transparent_union_attribute_field_size_align)
3542 << isSize << Field->getDeclName() << FieldBits;
3543 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3544 S.Diag(FirstField->getLocation(),
3545 diag::note_transparent_union_first_field_size_align)
3546 << isSize << FirstBits;
3551 RD->addAttr(::new (S.Context)
3552 TransparentUnionAttr(AL.getRange(), S.Context,
3553 AL.getAttributeSpellingListIndex()));
3556 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3557 // Make sure that there is a string literal as the annotation's single
3560 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3563 // Don't duplicate annotations that are already set.
3564 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3565 if (I->getAnnotation() == Str)
3569 D->addAttr(::new (S.Context)
3570 AnnotateAttr(AL.getRange(), S.Context, Str,
3571 AL.getAttributeSpellingListIndex()));
3574 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3575 S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3576 AL.getAttributeSpellingListIndex());
3579 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3580 unsigned SpellingListIndex) {
3581 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3582 SourceLocation AttrLoc = AttrRange.getBegin();
3585 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3586 T = TD->getUnderlyingType();
3587 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3590 llvm_unreachable("Unknown decl type for align_value");
3592 if (!T->isDependentType() && !T->isAnyPointerType() &&
3593 !T->isReferenceType() && !T->isMemberPointerType()) {
3594 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3595 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3599 if (!E->isValueDependent()) {
3600 llvm::APSInt Alignment;
3602 = VerifyIntegerConstantExpression(E, &Alignment,
3603 diag::err_align_value_attribute_argument_not_int,
3604 /*AllowFold*/ false);
3605 if (ICE.isInvalid())
3608 if (!Alignment.isPowerOf2()) {
3609 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3610 << E->getSourceRange();
3614 D->addAttr(::new (Context)
3615 AlignValueAttr(AttrRange, Context, ICE.get(),
3616 SpellingListIndex));
3620 // Save dependent expressions in the AST to be instantiated.
3621 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3624 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3625 // check the attribute arguments.
3626 if (AL.getNumArgs() > 1) {
3627 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3631 if (AL.getNumArgs() == 0) {
3632 D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3633 true, nullptr, AL.getAttributeSpellingListIndex()));
3637 Expr *E = AL.getArgAsExpr(0);
3638 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3639 S.Diag(AL.getEllipsisLoc(),
3640 diag::err_pack_expansion_without_parameter_packs);
3644 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3647 S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(),
3648 AL.isPackExpansion());
3651 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3652 unsigned SpellingListIndex, bool IsPackExpansion) {
3653 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3654 SourceLocation AttrLoc = AttrRange.getBegin();
3656 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3657 if (TmpAttr.isAlignas()) {
3658 // C++11 [dcl.align]p1:
3659 // An alignment-specifier may be applied to a variable or to a class
3660 // data member, but it shall not be applied to a bit-field, a function
3661 // parameter, the formal parameter of a catch clause, or a variable
3662 // declared with the register storage class specifier. An
3663 // alignment-specifier may also be applied to the declaration of a class
3664 // or enumeration type.
3666 // An alignment attribute shall not be specified in a declaration of
3667 // a typedef, or a bit-field, or a function, or a parameter, or an
3668 // object declared with the register storage-class specifier.
3670 if (isa<ParmVarDecl>(D)) {
3672 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3673 if (VD->getStorageClass() == SC_Register)
3675 if (VD->isExceptionVariable())
3677 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3678 if (FD->isBitField())
3680 } else if (!isa<TagDecl>(D)) {
3681 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3682 << (TmpAttr.isC11() ? ExpectedVariableOrField
3683 : ExpectedVariableFieldOrTag);
3686 if (DiagKind != -1) {
3687 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3688 << &TmpAttr << DiagKind;
3693 if (E->isValueDependent()) {
3694 // We can't support a dependent alignment on a non-dependent type,
3695 // because we have no way to model that a type is "alignment-dependent"
3696 // but not dependent in any other way.
3697 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3698 if (!TND->getUnderlyingType()->isDependentType()) {
3699 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3700 << E->getSourceRange();
3705 // Save dependent expressions in the AST to be instantiated.
3706 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3707 AA->setPackExpansion(IsPackExpansion);
3712 // FIXME: Cache the number on the AL object?
3713 llvm::APSInt Alignment;
3715 = VerifyIntegerConstantExpression(E, &Alignment,
3716 diag::err_aligned_attribute_argument_not_int,
3717 /*AllowFold*/ false);
3718 if (ICE.isInvalid())
3721 uint64_t AlignVal = Alignment.getZExtValue();
3723 // C++11 [dcl.align]p2:
3724 // -- if the constant expression evaluates to zero, the alignment
3725 // specifier shall have no effect
3727 // An alignment specification of zero has no effect.
3728 if (!(TmpAttr.isAlignas() && !Alignment)) {
3729 if (!llvm::isPowerOf2_64(AlignVal)) {
3730 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3731 << E->getSourceRange();
3736 // Alignment calculations can wrap around if it's greater than 2**28.
3737 unsigned MaxValidAlignment =
3738 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3740 if (AlignVal > MaxValidAlignment) {
3741 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3742 << E->getSourceRange();
3746 if (Context.getTargetInfo().isTLSSupported()) {
3747 unsigned MaxTLSAlign =
3748 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3750 const auto *VD = dyn_cast<VarDecl>(D);
3751 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3752 VD->getTLSKind() != VarDecl::TLS_None) {
3753 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3754 << (unsigned)AlignVal << VD << MaxTLSAlign;
3759 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3760 ICE.get(), SpellingListIndex);
3761 AA->setPackExpansion(IsPackExpansion);
3765 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3766 unsigned SpellingListIndex, bool IsPackExpansion) {
3767 // FIXME: Cache the number on the AL object if non-dependent?
3768 // FIXME: Perform checking of type validity
3769 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3771 AA->setPackExpansion(IsPackExpansion);
3775 void Sema::CheckAlignasUnderalignment(Decl *D) {
3776 assert(D->hasAttrs() && "no attributes on decl");
3778 QualType UnderlyingTy, DiagTy;
3779 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3780 UnderlyingTy = DiagTy = VD->getType();
3782 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3783 if (const auto *ED = dyn_cast<EnumDecl>(D))
3784 UnderlyingTy = ED->getIntegerType();
3786 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3789 // C++11 [dcl.align]p5, C11 6.7.5/4:
3790 // The combined effect of all alignment attributes in a declaration shall
3791 // not specify an alignment that is less strict than the alignment that
3792 // would otherwise be required for the entity being declared.
3793 AlignedAttr *AlignasAttr = nullptr;
3795 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3796 if (I->isAlignmentDependent())
3800 Align = std::max(Align, I->getAlignment(Context));
3803 if (AlignasAttr && Align) {
3804 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3805 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3806 if (NaturalAlign > RequestedAlign)
3807 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3808 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3812 bool Sema::checkMSInheritanceAttrOnDefinition(
3813 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3814 MSInheritanceAttr::Spelling SemanticSpelling) {
3815 assert(RD->hasDefinition() && "RD has no definition!");
3817 // We may not have seen base specifiers or any virtual methods yet. We will
3818 // have to wait until the record is defined to catch any mismatches.
3819 if (!RD->getDefinition()->isCompleteDefinition())
3822 // The unspecified model never matches what a definition could need.
3823 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3827 if (RD->calculateInheritanceModel() == SemanticSpelling)
3830 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3834 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3835 << 0 /*definition*/;
3836 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3837 << RD->getNameAsString();
3841 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3843 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3844 bool &IntegerMode, bool &ComplexMode) {
3846 ComplexMode = false;
3847 switch (Str.size()) {
3869 if (Str[1] == 'F') {
3870 IntegerMode = false;
3871 } else if (Str[1] == 'C') {
3872 IntegerMode = false;
3874 } else if (Str[1] != 'I') {
3879 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3880 // pointer on PIC16 and other embedded platforms.
3882 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3883 else if (Str == "byte")
3884 DestWidth = S.Context.getTargetInfo().getCharWidth();
3887 if (Str == "pointer")
3888 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3891 if (Str == "unwind_word")
3892 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3897 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3900 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3901 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3902 /// HImode, not an intermediate pointer.
3903 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3904 // This attribute isn't documented, but glibc uses it. It changes
3905 // the width of an int or unsigned int to the specified size.
3906 if (!AL.isArgIdent(0)) {
3907 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
3908 << AL << AANT_ArgumentIdentifier;
3912 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3914 S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
3917 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3918 unsigned SpellingListIndex, bool InInstantiation) {
3919 StringRef Str = Name->getName();
3921 SourceLocation AttrLoc = AttrRange.getBegin();
3923 unsigned DestWidth = 0;
3924 bool IntegerMode = true;
3925 bool ComplexMode = false;
3926 llvm::APInt VectorSize(64, 0);
3927 if (Str.size() >= 4 && Str[0] == 'V') {
3928 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3929 size_t StrSize = Str.size();
3930 size_t VectorStringLength = 0;
3931 while ((VectorStringLength + 1) < StrSize &&
3932 isdigit(Str[VectorStringLength + 1]))
3933 ++VectorStringLength;
3934 if (VectorStringLength &&
3935 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3936 VectorSize.isPowerOf2()) {
3937 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3938 IntegerMode, ComplexMode);
3939 // Avoid duplicate warning from template instantiation.
3940 if (!InInstantiation)
3941 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3948 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3950 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3951 // and friends, at least with glibc.
3952 // FIXME: Make sure floating-point mappings are accurate
3953 // FIXME: Support XF and TF types
3955 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3960 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3961 OldTy = TD->getUnderlyingType();
3962 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
3963 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3964 // Try to get type from enum declaration, default to int.
3965 OldTy = ED->getIntegerType();
3967 OldTy = Context.IntTy;
3969 OldTy = cast<ValueDecl>(D)->getType();
3971 if (OldTy->isDependentType()) {
3972 D->addAttr(::new (Context)
3973 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3977 // Base type can also be a vector type (see PR17453).
3978 // Distinguish between base type and base element type.
3979 QualType OldElemTy = OldTy;
3980 if (const auto *VT = OldTy->getAs<VectorType>())
3981 OldElemTy = VT->getElementType();
3983 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3984 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3985 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3986 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3987 VectorSize.getBoolValue()) {
3988 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3991 bool IntegralOrAnyEnumType =
3992 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3994 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3995 !IntegralOrAnyEnumType)
3996 Diag(AttrLoc, diag::err_mode_not_primitive);
3997 else if (IntegerMode) {
3998 if (!IntegralOrAnyEnumType)
3999 Diag(AttrLoc, diag::err_mode_wrong_type);
4000 } else if (ComplexMode) {
4001 if (!OldElemTy->isComplexType())
4002 Diag(AttrLoc, diag::err_mode_wrong_type);
4004 if (!OldElemTy->isFloatingType())
4005 Diag(AttrLoc, diag::err_mode_wrong_type);
4011 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4012 OldElemTy->isSignedIntegerType());
4014 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4016 if (NewElemTy.isNull()) {
4017 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4022 NewElemTy = Context.getComplexType(NewElemTy);
4025 QualType NewTy = NewElemTy;
4026 if (VectorSize.getBoolValue()) {
4027 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4028 VectorType::GenericVector);
4029 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4030 // Complex machine mode does not support base vector types.
4032 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4035 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4036 OldVT->getNumElements() /
4037 Context.getTypeSize(NewElemTy);
4039 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4042 if (NewTy.isNull()) {
4043 Diag(AttrLoc, diag::err_mode_wrong_type);
4047 // Install the new type.
4048 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4049 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4050 else if (auto *ED = dyn_cast<EnumDecl>(D))
4051 ED->setIntegerType(NewTy);
4053 cast<ValueDecl>(D)->setType(NewTy);
4055 D->addAttr(::new (Context)
4056 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4059 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4060 D->addAttr(::new (S.Context)
4061 NoDebugAttr(AL.getRange(), S.Context,
4062 AL.getAttributeSpellingListIndex()));
4065 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
4066 IdentifierInfo *Ident,
4067 unsigned AttrSpellingListIndex) {
4068 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4069 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
4070 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4074 if (D->hasAttr<AlwaysInlineAttr>())
4077 return ::new (Context) AlwaysInlineAttr(Range, Context,
4078 AttrSpellingListIndex);
4081 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4082 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4085 return ::new (Context)
4086 CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4089 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4090 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4093 return ::new (Context)
4094 CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4097 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4098 const ParsedAttr &AL) {
4099 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4100 // Attribute applies to Var but not any subclass of it (like ParmVar,
4101 // ImplicitParm or VarTemplateSpecialization).
4102 if (VD->getKind() != Decl::Var) {
4103 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4104 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4105 : ExpectedVariableOrFunction);
4108 // Attribute does not apply to non-static local variables.
4109 if (VD->hasLocalStorage()) {
4110 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4115 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4118 return ::new (Context) InternalLinkageAttr(
4119 AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4121 InternalLinkageAttr *
4122 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4123 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4124 // Attribute applies to Var but not any subclass of it (like ParmVar,
4125 // ImplicitParm or VarTemplateSpecialization).
4126 if (VD->getKind() != Decl::Var) {
4127 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4128 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4129 : ExpectedVariableOrFunction);
4132 // Attribute does not apply to non-static local variables.
4133 if (VD->hasLocalStorage()) {
4134 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4139 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4142 return ::new (Context)
4143 InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4146 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4147 unsigned AttrSpellingListIndex) {
4148 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4149 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4150 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4154 if (D->hasAttr<MinSizeAttr>())
4157 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4160 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4161 unsigned AttrSpellingListIndex) {
4162 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4163 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4164 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4165 D->dropAttr<AlwaysInlineAttr>();
4167 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4168 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4169 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4170 D->dropAttr<MinSizeAttr>();
4173 if (D->hasAttr<OptimizeNoneAttr>())
4176 return ::new (Context) OptimizeNoneAttr(Range, Context,
4177 AttrSpellingListIndex);
4180 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4181 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4184 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4185 D, AL.getRange(), AL.getName(),
4186 AL.getAttributeSpellingListIndex()))
4190 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4191 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4192 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4193 D->addAttr(MinSize);
4196 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4197 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4198 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4199 D->addAttr(Optnone);
4202 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4203 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4205 const auto *VD = cast<VarDecl>(D);
4206 if (!VD->hasGlobalStorage()) {
4207 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4210 D->addAttr(::new (S.Context) CUDAConstantAttr(
4211 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4214 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4215 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4217 const auto *VD = cast<VarDecl>(D);
4218 // extern __shared__ is only allowed on arrays with no length (e.g.
4220 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4221 !isa<IncompleteArrayType>(VD->getType())) {
4222 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4225 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4226 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4227 << S.CurrentCUDATarget())
4229 D->addAttr(::new (S.Context) CUDASharedAttr(
4230 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4233 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4234 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4235 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4238 const auto *FD = cast<FunctionDecl>(D);
4239 if (!FD->getReturnType()->isVoidType()) {
4240 SourceRange RTRange = FD->getReturnTypeSourceRange();
4241 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4243 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4247 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4248 if (Method->isInstance()) {
4249 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4253 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4255 // Only warn for "inline" when compiling for host, to cut down on noise.
4256 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4257 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4259 D->addAttr(::new (S.Context)
4260 CUDAGlobalAttr(AL.getRange(), S.Context,
4261 AL.getAttributeSpellingListIndex()));
4264 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4265 const auto *Fn = cast<FunctionDecl>(D);
4266 if (!Fn->isInlineSpecified()) {
4267 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4271 D->addAttr(::new (S.Context)
4272 GNUInlineAttr(AL.getRange(), S.Context,
4273 AL.getAttributeSpellingListIndex()));
4276 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4277 if (hasDeclarator(D)) return;
4279 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4280 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4282 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4285 if (!isa<ObjCMethodDecl>(D)) {
4286 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4287 << AL << ExpectedFunctionOrMethod;
4291 switch (AL.getKind()) {
4292 case ParsedAttr::AT_FastCall:
4293 D->addAttr(::new (S.Context)
4294 FastCallAttr(AL.getRange(), S.Context,
4295 AL.getAttributeSpellingListIndex()));
4297 case ParsedAttr::AT_StdCall:
4298 D->addAttr(::new (S.Context)
4299 StdCallAttr(AL.getRange(), S.Context,
4300 AL.getAttributeSpellingListIndex()));
4302 case ParsedAttr::AT_ThisCall:
4303 D->addAttr(::new (S.Context)
4304 ThisCallAttr(AL.getRange(), S.Context,
4305 AL.getAttributeSpellingListIndex()));
4307 case ParsedAttr::AT_CDecl:
4308 D->addAttr(::new (S.Context)
4309 CDeclAttr(AL.getRange(), S.Context,
4310 AL.getAttributeSpellingListIndex()));
4312 case ParsedAttr::AT_Pascal:
4313 D->addAttr(::new (S.Context)
4314 PascalAttr(AL.getRange(), S.Context,
4315 AL.getAttributeSpellingListIndex()));
4317 case ParsedAttr::AT_SwiftCall:
4318 D->addAttr(::new (S.Context)
4319 SwiftCallAttr(AL.getRange(), S.Context,
4320 AL.getAttributeSpellingListIndex()));
4322 case ParsedAttr::AT_VectorCall:
4323 D->addAttr(::new (S.Context)
4324 VectorCallAttr(AL.getRange(), S.Context,
4325 AL.getAttributeSpellingListIndex()));
4327 case ParsedAttr::AT_MSABI:
4328 D->addAttr(::new (S.Context)
4329 MSABIAttr(AL.getRange(), S.Context,
4330 AL.getAttributeSpellingListIndex()));
4332 case ParsedAttr::AT_SysVABI:
4333 D->addAttr(::new (S.Context)
4334 SysVABIAttr(AL.getRange(), S.Context,
4335 AL.getAttributeSpellingListIndex()));
4337 case ParsedAttr::AT_RegCall:
4338 D->addAttr(::new (S.Context) RegCallAttr(
4339 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4341 case ParsedAttr::AT_Pcs: {
4342 PcsAttr::PCSType PCS;
4345 PCS = PcsAttr::AAPCS;
4348 PCS = PcsAttr::AAPCS_VFP;
4351 llvm_unreachable("unexpected calling convention in pcs attribute");
4354 D->addAttr(::new (S.Context)
4355 PcsAttr(AL.getRange(), S.Context, PCS,
4356 AL.getAttributeSpellingListIndex()));
4359 case ParsedAttr::AT_AArch64VectorPcs:
4360 D->addAttr(::new(S.Context)
4361 AArch64VectorPcsAttr(AL.getRange(), S.Context,
4362 AL.getAttributeSpellingListIndex()));
4364 case ParsedAttr::AT_IntelOclBicc:
4365 D->addAttr(::new (S.Context)
4366 IntelOclBiccAttr(AL.getRange(), S.Context,
4367 AL.getAttributeSpellingListIndex()));
4369 case ParsedAttr::AT_PreserveMost:
4370 D->addAttr(::new (S.Context) PreserveMostAttr(
4371 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4373 case ParsedAttr::AT_PreserveAll:
4374 D->addAttr(::new (S.Context) PreserveAllAttr(
4375 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4378 llvm_unreachable("unexpected attribute kind");
4382 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4383 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4386 std::vector<StringRef> DiagnosticIdentifiers;
4387 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4390 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4393 // FIXME: Warn if the rule name is unknown. This is tricky because only
4394 // clang-tidy knows about available rules.
4395 DiagnosticIdentifiers.push_back(RuleName);
4397 D->addAttr(::new (S.Context) SuppressAttr(
4398 AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4399 DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4402 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4403 const FunctionDecl *FD) {
4404 if (Attrs.isInvalid())
4407 if (Attrs.hasProcessingCache()) {
4408 CC = (CallingConv) Attrs.getProcessingCache();
4412 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4413 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4418 // TODO: diagnose uses of these conventions on the wrong target.
4419 switch (Attrs.getKind()) {
4420 case ParsedAttr::AT_CDecl:
4423 case ParsedAttr::AT_FastCall:
4424 CC = CC_X86FastCall;
4426 case ParsedAttr::AT_StdCall:
4429 case ParsedAttr::AT_ThisCall:
4430 CC = CC_X86ThisCall;
4432 case ParsedAttr::AT_Pascal:
4435 case ParsedAttr::AT_SwiftCall:
4438 case ParsedAttr::AT_VectorCall:
4439 CC = CC_X86VectorCall;
4441 case ParsedAttr::AT_AArch64VectorPcs:
4442 CC = CC_AArch64VectorCall;
4444 case ParsedAttr::AT_RegCall:
4447 case ParsedAttr::AT_MSABI:
4448 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4451 case ParsedAttr::AT_SysVABI:
4452 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4455 case ParsedAttr::AT_Pcs: {
4457 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4461 if (StrRef == "aapcs") {
4464 } else if (StrRef == "aapcs-vfp") {
4470 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4473 case ParsedAttr::AT_IntelOclBicc:
4474 CC = CC_IntelOclBicc;
4476 case ParsedAttr::AT_PreserveMost:
4477 CC = CC_PreserveMost;
4479 case ParsedAttr::AT_PreserveAll:
4480 CC = CC_PreserveAll;
4482 default: llvm_unreachable("unexpected attribute kind");
4485 const TargetInfo &TI = Context.getTargetInfo();
4486 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4487 if (A != TargetInfo::CCCR_OK) {
4488 if (A == TargetInfo::CCCR_Warning)
4489 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs;
4491 // This convention is not valid for the target. Use the default function or
4492 // method calling convention.
4493 bool IsCXXMethod = false, IsVariadic = false;
4495 IsCXXMethod = FD->isCXXInstanceMember();
4496 IsVariadic = FD->isVariadic();
4498 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4501 Attrs.setProcessingCache((unsigned) CC);
4505 /// Pointer-like types in the default address space.
4506 static bool isValidSwiftContextType(QualType Ty) {
4507 if (!Ty->hasPointerRepresentation())
4508 return Ty->isDependentType();
4509 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4512 /// Pointers and references in the default address space.
4513 static bool isValidSwiftIndirectResultType(QualType Ty) {
4514 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4515 Ty = PtrType->getPointeeType();
4516 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4517 Ty = RefType->getPointeeType();
4519 return Ty->isDependentType();
4521 return Ty.getAddressSpace() == LangAS::Default;
4524 /// Pointers and references to pointers in the default address space.
4525 static bool isValidSwiftErrorResultType(QualType Ty) {
4526 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4527 Ty = PtrType->getPointeeType();
4528 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4529 Ty = RefType->getPointeeType();
4531 return Ty->isDependentType();
4533 if (!Ty.getQualifiers().empty())
4535 return isValidSwiftContextType(Ty);
4538 static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4540 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4541 Attrs.getAttributeSpellingListIndex());
4544 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4545 unsigned spellingIndex) {
4547 QualType type = cast<ParmVarDecl>(D)->getType();
4549 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4550 if (existingAttr->getABI() != abi) {
4551 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4552 << getParameterABISpelling(abi) << existingAttr;
4553 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4559 case ParameterABI::Ordinary:
4560 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4562 case ParameterABI::SwiftContext:
4563 if (!isValidSwiftContextType(type)) {
4564 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4565 << getParameterABISpelling(abi)
4566 << /*pointer to pointer */ 0 << type;
4568 D->addAttr(::new (Context)
4569 SwiftContextAttr(range, Context, spellingIndex));
4572 case ParameterABI::SwiftErrorResult:
4573 if (!isValidSwiftErrorResultType(type)) {
4574 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4575 << getParameterABISpelling(abi)
4576 << /*pointer to pointer */ 1 << type;
4578 D->addAttr(::new (Context)
4579 SwiftErrorResultAttr(range, Context, spellingIndex));
4582 case ParameterABI::SwiftIndirectResult:
4583 if (!isValidSwiftIndirectResultType(type)) {
4584 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4585 << getParameterABISpelling(abi)
4586 << /*pointer*/ 0 << type;
4588 D->addAttr(::new (Context)
4589 SwiftIndirectResultAttr(range, Context, spellingIndex));
4592 llvm_unreachable("bad parameter ABI attribute");
4595 /// Checks a regparm attribute, returning true if it is ill-formed and
4596 /// otherwise setting numParams to the appropriate value.
4597 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4601 if (!checkAttributeNumArgs(*this, AL, 1)) {
4607 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4608 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4613 if (Context.getTargetInfo().getRegParmMax() == 0) {
4614 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4615 << NumParamsExpr->getSourceRange();
4621 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4622 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4623 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4631 // Checks whether an argument of launch_bounds attribute is
4632 // acceptable, performs implicit conversion to Rvalue, and returns
4633 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4634 // and may output an error.
4635 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4636 const CUDALaunchBoundsAttr &AL,
4637 const unsigned Idx) {
4638 if (S.DiagnoseUnexpandedParameterPack(E))
4641 // Accept template arguments for now as they depend on something else.
4642 // We'll get to check them when they eventually get instantiated.
4643 if (E->isValueDependent())
4647 if (!E->isIntegerConstantExpr(I, S.Context)) {
4648 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4649 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4652 // Make sure we can fit it in 32 bits.
4653 if (!I.isIntN(32)) {
4654 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4655 << 32 << /* Unsigned */ 1;
4659 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4660 << &AL << Idx << E->getSourceRange();
4662 // We may need to perform implicit conversion of the argument.
4663 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4664 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4665 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4666 assert(!ValArg.isInvalid() &&
4667 "Unexpected PerformCopyInitialization() failure.");
4669 return ValArg.getAs<Expr>();
4672 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4673 Expr *MinBlocks, unsigned SpellingListIndex) {
4674 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4676 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4677 if (MaxThreads == nullptr)
4681 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4682 if (MinBlocks == nullptr)
4686 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4687 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4690 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4691 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4692 !checkAttributeAtMostNumArgs(S, AL, 2))
4695 S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4696 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4697 AL.getAttributeSpellingListIndex());
4700 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4701 const ParsedAttr &AL) {
4702 if (!AL.isArgIdent(0)) {
4703 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4704 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4708 ParamIdx ArgumentIdx;
4709 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4713 ParamIdx TypeTagIdx;
4714 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4718 bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4720 // Ensure that buffer has a pointer type.
4721 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4722 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4723 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4724 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4727 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4728 AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4729 TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4732 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4733 const ParsedAttr &AL) {
4734 if (!AL.isArgIdent(0)) {
4735 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4736 << AL << 1 << AANT_ArgumentIdentifier;
4740 if (!checkAttributeNumArgs(S, AL, 1))
4743 if (!isa<VarDecl>(D)) {
4744 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4745 << AL << ExpectedVariable;
4749 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4750 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4751 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4752 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4754 D->addAttr(::new (S.Context)
4755 TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4757 AL.getLayoutCompatible(),
4759 AL.getAttributeSpellingListIndex()));
4762 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4765 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4767 true /* CanIndexImplicitThis */))
4770 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4771 D->addAttr(::new (S.Context) XRayLogArgsAttr(
4772 AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4773 AL.getAttributeSpellingListIndex()));
4776 //===----------------------------------------------------------------------===//
4777 // Checker-specific attribute handlers.
4778 //===----------------------------------------------------------------------===//
4779 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4780 return QT->isDependentType() || QT->isObjCRetainableType();
4783 static bool isValidSubjectOfNSAttribute(QualType QT) {
4784 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4785 QT->isObjCNSObjectType();
4788 static bool isValidSubjectOfCFAttribute(QualType QT) {
4789 return QT->isDependentType() || QT->isPointerType() ||
4790 isValidSubjectOfNSAttribute(QT);
4793 static bool isValidSubjectOfOSAttribute(QualType QT) {
4794 if (QT->isDependentType())
4796 QualType PT = QT->getPointeeType();
4797 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
4800 void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
4801 RetainOwnershipKind K,
4802 bool IsTemplateInstantiation) {
4803 ValueDecl *VD = cast<ValueDecl>(D);
4805 case RetainOwnershipKind::OS:
4806 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
4807 *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
4808 diag::warn_ns_attribute_wrong_parameter_type,
4809 /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
4811 case RetainOwnershipKind::NS:
4812 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
4813 *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
4815 // These attributes are normally just advisory, but in ARC, ns_consumed
4816 // is significant. Allow non-dependent code to contain inappropriate
4817 // attributes even in ARC, but require template instantiations to be
4818 // set up correctly.
4819 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
4820 ? diag::err_ns_attribute_wrong_parameter_type
4821 : diag::warn_ns_attribute_wrong_parameter_type),
4822 /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
4824 case RetainOwnershipKind::CF:
4825 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
4826 *this, VD, SR, SpellingIndex,
4827 isValidSubjectOfCFAttribute(VD->getType()),
4828 diag::warn_ns_attribute_wrong_parameter_type,
4829 /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
4834 static Sema::RetainOwnershipKind
4835 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
4836 switch (AL.getKind()) {
4837 case ParsedAttr::AT_CFConsumed:
4838 case ParsedAttr::AT_CFReturnsRetained:
4839 case ParsedAttr::AT_CFReturnsNotRetained:
4840 return Sema::RetainOwnershipKind::CF;
4841 case ParsedAttr::AT_OSConsumesThis:
4842 case ParsedAttr::AT_OSConsumed:
4843 case ParsedAttr::AT_OSReturnsRetained:
4844 case ParsedAttr::AT_OSReturnsNotRetained:
4845 case ParsedAttr::AT_OSReturnsRetainedOnZero:
4846 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
4847 return Sema::RetainOwnershipKind::OS;
4848 case ParsedAttr::AT_NSConsumesSelf:
4849 case ParsedAttr::AT_NSConsumed:
4850 case ParsedAttr::AT_NSReturnsRetained:
4851 case ParsedAttr::AT_NSReturnsNotRetained:
4852 case ParsedAttr::AT_NSReturnsAutoreleased:
4853 return Sema::RetainOwnershipKind::NS;
4855 llvm_unreachable("Wrong argument supplied");
4859 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
4860 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
4863 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
4864 << "'ns_returns_retained'" << 0 << 0;
4868 /// \return whether the parameter is a pointer to OSObject pointer.
4869 static bool isValidOSObjectOutParameter(const Decl *D) {
4870 const auto *PVD = dyn_cast<ParmVarDecl>(D);
4873 QualType QT = PVD->getType();
4874 QualType PT = QT->getPointeeType();
4875 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
4878 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
4879 const ParsedAttr &AL) {
4880 QualType ReturnType;
4881 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
4883 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
4884 ReturnType = MD->getReturnType();
4885 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4886 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
4887 return; // ignore: was handled as a type attribute
4888 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
4889 ReturnType = PD->getType();
4890 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4891 ReturnType = FD->getReturnType();
4892 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
4893 // Attributes on parameters are used for out-parameters,
4894 // passed as pointers-to-pointers.
4895 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
4896 ? /*pointer-to-CF-pointer*/2
4897 : /*pointer-to-OSObject-pointer*/3;
4898 ReturnType = Param->getType()->getPointeeType();
4899 if (ReturnType.isNull()) {
4900 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4901 << AL << DiagID << AL.getRange();
4904 } else if (AL.isUsedAsTypeAttr()) {
4907 AttributeDeclKind ExpectedDeclKind;
4908 switch (AL.getKind()) {
4909 default: llvm_unreachable("invalid ownership attribute");
4910 case ParsedAttr::AT_NSReturnsRetained:
4911 case ParsedAttr::AT_NSReturnsAutoreleased:
4912 case ParsedAttr::AT_NSReturnsNotRetained:
4913 ExpectedDeclKind = ExpectedFunctionOrMethod;
4916 case ParsedAttr::AT_OSReturnsRetained:
4917 case ParsedAttr::AT_OSReturnsNotRetained:
4918 case ParsedAttr::AT_CFReturnsRetained:
4919 case ParsedAttr::AT_CFReturnsNotRetained:
4920 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4923 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
4924 << AL.getRange() << AL << ExpectedDeclKind;
4930 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
4931 switch (AL.getKind()) {
4932 default: llvm_unreachable("invalid ownership attribute");
4933 case ParsedAttr::AT_NSReturnsRetained:
4934 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
4938 case ParsedAttr::AT_NSReturnsAutoreleased:
4939 case ParsedAttr::AT_NSReturnsNotRetained:
4940 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
4944 case ParsedAttr::AT_CFReturnsRetained:
4945 case ParsedAttr::AT_CFReturnsNotRetained:
4946 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
4950 case ParsedAttr::AT_OSReturnsRetained:
4951 case ParsedAttr::AT_OSReturnsNotRetained:
4952 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
4954 ParmDiagID = 3; // Pointer-to-OSObject-pointer
4959 if (AL.isUsedAsTypeAttr())
4962 if (isa<ParmVarDecl>(D)) {
4963 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4964 << AL << ParmDiagID << AL.getRange();
4966 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4971 } SubjectKind = Function;
4972 if (isa<ObjCMethodDecl>(D))
4973 SubjectKind = Method;
4974 else if (isa<ObjCPropertyDecl>(D))
4975 SubjectKind = Property;
4976 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
4977 << AL << SubjectKind << Cf << AL.getRange();
4982 switch (AL.getKind()) {
4984 llvm_unreachable("invalid ownership attribute");
4985 case ParsedAttr::AT_NSReturnsAutoreleased:
4986 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
4988 case ParsedAttr::AT_CFReturnsNotRetained:
4989 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
4991 case ParsedAttr::AT_NSReturnsNotRetained:
4992 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
4994 case ParsedAttr::AT_CFReturnsRetained:
4995 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
4997 case ParsedAttr::AT_NSReturnsRetained:
4998 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5000 case ParsedAttr::AT_OSReturnsRetained:
5001 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5003 case ParsedAttr::AT_OSReturnsNotRetained:
5004 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5009 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5010 const ParsedAttr &Attrs) {
5011 const int EP_ObjCMethod = 1;
5012 const int EP_ObjCProperty = 2;
5014 SourceLocation loc = Attrs.getLoc();
5015 QualType resultType;
5016 if (isa<ObjCMethodDecl>(D))
5017 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5019 resultType = cast<ObjCPropertyDecl>(D)->getType();
5021 if (!resultType->isReferenceType() &&
5022 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5023 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5024 << SourceRange(loc) << Attrs
5025 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5026 << /*non-retainable pointer*/ 2;
5028 // Drop the attribute.
5032 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
5033 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5036 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5037 const ParsedAttr &Attrs) {
5038 const auto *Method = cast<ObjCMethodDecl>(D);
5040 const DeclContext *DC = Method->getDeclContext();
5041 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5042 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5044 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5047 if (Method->getMethodFamily() == OMF_dealloc) {
5048 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5053 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
5054 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5057 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5058 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5061 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5065 // Typedefs only allow objc_bridge(id) and have some additional checking.
5066 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5067 if (!Parm->Ident->isStr("id")) {
5068 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5072 // Only allow 'cv void *'.
5073 QualType T = TD->getUnderlyingType();
5074 if (!T->isVoidPointerType()) {
5075 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5080 D->addAttr(::new (S.Context)
5081 ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
5082 AL.getAttributeSpellingListIndex()));
5085 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5086 const ParsedAttr &AL) {
5087 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5090 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5094 D->addAttr(::new (S.Context)
5095 ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
5096 AL.getAttributeSpellingListIndex()));
5099 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5100 const ParsedAttr &AL) {
5101 IdentifierInfo *RelatedClass =
5102 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5103 if (!RelatedClass) {
5104 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5107 IdentifierInfo *ClassMethod =
5108 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5109 IdentifierInfo *InstanceMethod =
5110 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5111 D->addAttr(::new (S.Context)
5112 ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
5113 ClassMethod, InstanceMethod,
5114 AL.getAttributeSpellingListIndex()));
5117 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5118 const ParsedAttr &AL) {
5119 DeclContext *Ctx = D->getDeclContext();
5121 // This attribute can only be applied to methods in interfaces or class
5123 if (!isa<ObjCInterfaceDecl>(Ctx) &&
5124 !(isa<ObjCCategoryDecl>(Ctx) &&
5125 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5126 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5130 ObjCInterfaceDecl *IFace;
5131 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5132 IFace = CatDecl->getClassInterface();
5134 IFace = cast<ObjCInterfaceDecl>(Ctx);
5139 IFace->setHasDesignatedInitializers();
5140 D->addAttr(::new (S.Context)
5141 ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
5142 AL.getAttributeSpellingListIndex()));
5145 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5146 StringRef MetaDataName;
5147 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5149 D->addAttr(::new (S.Context)
5150 ObjCRuntimeNameAttr(AL.getRange(), S.Context,
5152 AL.getAttributeSpellingListIndex()));
5155 // When a user wants to use objc_boxable with a union or struct
5156 // but they don't have access to the declaration (legacy/third-party code)
5157 // then they can 'enable' this feature with a typedef:
5158 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5159 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5160 bool notify = false;
5162 auto *RD = dyn_cast<RecordDecl>(D);
5163 if (RD && RD->getDefinition()) {
5164 RD = RD->getDefinition();
5169 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5170 ObjCBoxableAttr(AL.getRange(), S.Context,
5171 AL.getAttributeSpellingListIndex());
5172 RD->addAttr(BoxableAttr);
5174 // we need to notify ASTReader/ASTWriter about
5175 // modification of existing declaration
5176 if (ASTMutationListener *L = S.getASTMutationListener())
5177 L->AddedAttributeToRecord(BoxableAttr, RD);
5182 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5183 if (hasDeclarator(D)) return;
5185 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5186 << AL.getRange() << AL << ExpectedVariable;
5189 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5190 const ParsedAttr &AL) {
5191 const auto *VD = cast<ValueDecl>(D);
5192 QualType QT = VD->getType();
5194 if (!QT->isDependentType() &&
5195 !QT->isObjCLifetimeType()) {
5196 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5201 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5203 // If we have no lifetime yet, check the lifetime we're presumably
5205 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5206 Lifetime = QT->getObjCARCImplicitLifetime();
5209 case Qualifiers::OCL_None:
5210 assert(QT->isDependentType() &&
5211 "didn't infer lifetime for non-dependent type?");
5214 case Qualifiers::OCL_Weak: // meaningful
5215 case Qualifiers::OCL_Strong: // meaningful
5218 case Qualifiers::OCL_ExplicitNone:
5219 case Qualifiers::OCL_Autoreleasing:
5220 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5221 << (Lifetime == Qualifiers::OCL_Autoreleasing);
5225 D->addAttr(::new (S.Context)
5226 ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
5227 AL.getAttributeSpellingListIndex()));
5230 //===----------------------------------------------------------------------===//
5231 // Microsoft specific attribute handlers.
5232 //===----------------------------------------------------------------------===//
5234 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5235 unsigned AttrSpellingListIndex, StringRef Uuid) {
5236 if (const auto *UA = D->getAttr<UuidAttr>()) {
5237 if (UA->getGuid().equals_lower(Uuid))
5239 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5240 Diag(Range.getBegin(), diag::note_previous_uuid);
5241 D->dropAttr<UuidAttr>();
5244 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5247 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5248 if (!S.LangOpts.CPlusPlus) {
5249 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5250 << AL << AttributeLangSupport::C;
5255 SourceLocation LiteralLoc;
5256 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5259 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5260 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5261 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5262 StrRef = StrRef.drop_front().drop_back();
5264 // Validate GUID length.
5265 if (StrRef.size() != 36) {
5266 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5270 for (unsigned i = 0; i < 36; ++i) {
5271 if (i == 8 || i == 13 || i == 18 || i == 23) {
5272 if (StrRef[i] != '-') {
5273 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5276 } else if (!isHexDigit(StrRef[i])) {
5277 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5282 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5283 // the only thing in the [] list, the [] too), and add an insertion of
5284 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5285 // separating attributes nor of the [ and the ] are in the AST.
5286 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5288 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5289 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5291 UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5292 AL.getAttributeSpellingListIndex(), StrRef);
5297 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5298 if (!S.LangOpts.CPlusPlus) {
5299 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5300 << AL << AttributeLangSupport::C;
5303 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5304 D, AL.getRange(), /*BestCase=*/true,
5305 AL.getAttributeSpellingListIndex(),
5306 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5309 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5313 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5314 const auto *VD = cast<VarDecl>(D);
5315 if (!S.Context.getTargetInfo().isTLSSupported()) {
5316 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5319 if (VD->getTSCSpec() != TSCS_unspecified) {
5320 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5323 if (VD->hasLocalStorage()) {
5324 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5327 D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5328 AL.getAttributeSpellingListIndex()));
5331 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5332 SmallVector<StringRef, 4> Tags;
5333 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5335 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5337 Tags.push_back(Tag);
5340 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5341 if (!NS->isInline()) {
5342 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5345 if (NS->isAnonymousNamespace()) {
5346 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5349 if (AL.getNumArgs() == 0)
5350 Tags.push_back(NS->getName());
5351 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5354 // Store tags sorted and without duplicates.
5356 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5358 D->addAttr(::new (S.Context)
5359 AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
5360 AL.getAttributeSpellingListIndex()));
5363 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5364 // Check the attribute arguments.
5365 if (AL.getNumArgs() > 1) {
5366 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5371 SourceLocation ArgLoc;
5373 if (AL.getNumArgs() == 0)
5375 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5378 ARMInterruptAttr::InterruptType Kind;
5379 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5380 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5385 unsigned Index = AL.getAttributeSpellingListIndex();
5386 D->addAttr(::new (S.Context)
5387 ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
5390 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5391 // MSP430 'interrupt' attribute is applied to
5392 // a function with no parameters and void return type.
5393 if (!isFunctionOrMethod(D)) {
5394 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5395 << "'interrupt'" << ExpectedFunctionOrMethod;
5399 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5400 S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5405 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5406 S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5411 // The attribute takes one integer argument.
5412 if (!checkAttributeNumArgs(S, AL, 1))
5415 if (!AL.isArgExpr(0)) {
5416 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5417 << AL << AANT_ArgumentIntegerConstant;
5421 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5422 llvm::APSInt NumParams(32);
5423 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5424 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5425 << AL << AANT_ArgumentIntegerConstant
5426 << NumParamsExpr->getSourceRange();
5429 // The argument should be in range 0..63.
5430 unsigned Num = NumParams.getLimitedValue(255);
5432 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5433 << AL << (int)NumParams.getSExtValue()
5434 << NumParamsExpr->getSourceRange();
5438 D->addAttr(::new (S.Context)
5439 MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
5440 AL.getAttributeSpellingListIndex()));
5441 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5444 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5445 // Only one optional argument permitted.
5446 if (AL.getNumArgs() > 1) {
5447 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5452 SourceLocation ArgLoc;
5454 if (AL.getNumArgs() == 0)
5456 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5459 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5460 // a) Must be a function.
5461 // b) Must have no parameters.
5462 // c) Must have the 'void' return type.
5463 // d) Cannot have the 'mips16' attribute, as that instruction set
5464 // lacks the 'eret' instruction.
5465 // e) The attribute itself must either have no argument or one of the
5466 // valid interrupt types, see [MipsInterruptDocs].
5468 if (!isFunctionOrMethod(D)) {
5469 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5470 << "'interrupt'" << ExpectedFunctionOrMethod;
5474 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5475 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5480 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5481 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5486 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5489 MipsInterruptAttr::InterruptType Kind;
5490 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5491 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5492 << AL << "'" + std::string(Str) + "'";
5496 D->addAttr(::new (S.Context) MipsInterruptAttr(
5497 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5500 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5501 // Semantic checks for a function with the 'interrupt' attribute.
5502 // a) Must be a function.
5503 // b) Must have the 'void' return type.
5504 // c) Must take 1 or 2 arguments.
5505 // d) The 1st argument must be a pointer.
5506 // e) The 2nd argument (if any) must be an unsigned integer.
5507 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5508 CXXMethodDecl::isStaticOverloadedOperator(
5509 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5510 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5511 << AL << ExpectedFunctionWithProtoType;
5514 // Interrupt handler must have void return type.
5515 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5516 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5517 diag::err_anyx86_interrupt_attribute)
5518 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5524 // Interrupt handler must have 1 or 2 parameters.
5525 unsigned NumParams = getFunctionOrMethodNumParams(D);
5526 if (NumParams < 1 || NumParams > 2) {
5527 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5528 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5534 // The first argument must be a pointer.
5535 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5536 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5537 diag::err_anyx86_interrupt_attribute)
5538 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5544 // The second argument, if present, must be an unsigned integer.
5546 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5549 if (NumParams == 2 &&
5550 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5551 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5552 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5553 diag::err_anyx86_interrupt_attribute)
5554 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5557 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5560 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5561 AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex()));
5562 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5565 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5566 if (!isFunctionOrMethod(D)) {
5567 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5568 << "'interrupt'" << ExpectedFunction;
5572 if (!checkAttributeNumArgs(S, AL, 0))
5575 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5578 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5579 if (!isFunctionOrMethod(D)) {
5580 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5581 << "'signal'" << ExpectedFunction;
5585 if (!checkAttributeNumArgs(S, AL, 0))
5588 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5591 static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5592 if (!isFunctionOrMethod(D)) {
5593 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5594 << "'import_module'" << ExpectedFunction;
5598 auto *FD = cast<FunctionDecl>(D);
5599 if (FD->isThisDeclarationADefinition()) {
5600 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5605 SourceLocation ArgLoc;
5606 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5609 FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr(
5610 AL.getRange(), S.Context, Str,
5611 AL.getAttributeSpellingListIndex()));
5614 static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5615 if (!isFunctionOrMethod(D)) {
5616 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5617 << "'import_name'" << ExpectedFunction;
5621 auto *FD = cast<FunctionDecl>(D);
5622 if (FD->isThisDeclarationADefinition()) {
5623 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5628 SourceLocation ArgLoc;
5629 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5632 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(
5633 AL.getRange(), S.Context, Str,
5634 AL.getAttributeSpellingListIndex()));
5637 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5638 const ParsedAttr &AL) {
5639 // Warn about repeated attributes.
5640 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5641 S.Diag(AL.getRange().getBegin(),
5642 diag::warn_riscv_repeated_interrupt_attribute);
5643 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5647 // Check the attribute argument. Argument is optional.
5648 if (!checkAttributeAtMostNumArgs(S, AL, 1))
5652 SourceLocation ArgLoc;
5654 // 'machine'is the default interrupt mode.
5655 if (AL.getNumArgs() == 0)
5657 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5660 // Semantic checks for a function with the 'interrupt' attribute:
5661 // - Must be a function.
5662 // - Must have no parameters.
5663 // - Must have the 'void' return type.
5664 // - The attribute itself must either have no argument or one of the
5665 // valid interrupt types, see [RISCVInterruptDocs].
5667 if (D->getFunctionType() == nullptr) {
5668 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5669 << "'interrupt'" << ExpectedFunction;
5673 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5674 S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 0;
5678 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5679 S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 1;
5683 RISCVInterruptAttr::InterruptType Kind;
5684 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5685 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5690 D->addAttr(::new (S.Context) RISCVInterruptAttr(
5691 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5694 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5695 // Dispatch the interrupt attribute based on the current target.
5696 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5697 case llvm::Triple::msp430:
5698 handleMSP430InterruptAttr(S, D, AL);
5700 case llvm::Triple::mipsel:
5701 case llvm::Triple::mips:
5702 handleMipsInterruptAttr(S, D, AL);
5704 case llvm::Triple::x86:
5705 case llvm::Triple::x86_64:
5706 handleAnyX86InterruptAttr(S, D, AL);
5708 case llvm::Triple::avr:
5709 handleAVRInterruptAttr(S, D, AL);
5711 case llvm::Triple::riscv32:
5712 case llvm::Triple::riscv64:
5713 handleRISCVInterruptAttr(S, D, AL);
5716 handleARMInterruptAttr(S, D, AL);
5721 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5722 const ParsedAttr &AL) {
5724 Expr *MinExpr = AL.getArgAsExpr(0);
5725 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5729 Expr *MaxExpr = AL.getArgAsExpr(1);
5730 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5733 if (Min == 0 && Max != 0) {
5734 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5738 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5742 D->addAttr(::new (S.Context)
5743 AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max,
5744 AL.getAttributeSpellingListIndex()));
5747 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5749 Expr *MinExpr = AL.getArgAsExpr(0);
5750 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5754 if (AL.getNumArgs() == 2) {
5755 Expr *MaxExpr = AL.getArgAsExpr(1);
5756 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5760 if (Min == 0 && Max != 0) {
5761 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5764 if (Max != 0 && Min > Max) {
5765 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5769 D->addAttr(::new (S.Context)
5770 AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max,
5771 AL.getAttributeSpellingListIndex()));
5774 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5775 uint32_t NumSGPR = 0;
5776 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
5777 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
5780 D->addAttr(::new (S.Context)
5781 AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
5782 AL.getAttributeSpellingListIndex()));
5785 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5786 uint32_t NumVGPR = 0;
5787 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
5788 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
5791 D->addAttr(::new (S.Context)
5792 AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
5793 AL.getAttributeSpellingListIndex()));
5796 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5797 const ParsedAttr &AL) {
5798 // If we try to apply it to a function pointer, don't warn, but don't
5799 // do anything, either. It doesn't matter anyway, because there's nothing
5800 // special about calling a force_align_arg_pointer function.
5801 const auto *VD = dyn_cast<ValueDecl>(D);
5802 if (VD && VD->getType()->isFunctionPointerType())
5804 // Also don't warn on function pointer typedefs.
5805 const auto *TD = dyn_cast<TypedefNameDecl>(D);
5806 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5807 TD->getUnderlyingType()->isFunctionType()))
5809 // Attribute can only be applied to function types.
5810 if (!isa<FunctionDecl>(D)) {
5811 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5812 << AL << ExpectedFunction;
5816 D->addAttr(::new (S.Context)
5817 X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
5818 AL.getAttributeSpellingListIndex()));
5821 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
5823 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5824 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
5827 // TODO: Investigate what happens with the next major version of MSVC.
5828 if (Version != LangOptions::MSVC2015 / 100) {
5829 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5830 << AL << Version << VersionExpr->getSourceRange();
5834 // The attribute expects a "major" version number like 19, but new versions of
5835 // MSVC have moved to updating the "minor", or less significant numbers, so we
5836 // have to multiply by 100 now.
5839 D->addAttr(::new (S.Context)
5840 LayoutVersionAttr(AL.getRange(), S.Context, Version,
5841 AL.getAttributeSpellingListIndex()));
5844 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5845 unsigned AttrSpellingListIndex) {
5846 if (D->hasAttr<DLLExportAttr>()) {
5847 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5851 if (D->hasAttr<DLLImportAttr>())
5854 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5857 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5858 unsigned AttrSpellingListIndex) {
5859 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5860 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5861 D->dropAttr<DLLImportAttr>();
5864 if (D->hasAttr<DLLExportAttr>())
5867 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5870 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
5871 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5872 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5873 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
5877 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5878 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
5879 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5880 // MinGW doesn't allow dllimport on inline functions.
5881 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5887 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5888 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5889 MD->getParent()->isLambda()) {
5890 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
5895 unsigned Index = A.getAttributeSpellingListIndex();
5896 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
5897 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5898 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5900 D->addAttr(NewAttr);
5904 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5905 unsigned AttrSpellingListIndex,
5906 MSInheritanceAttr::Spelling SemanticSpelling) {
5907 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5908 if (IA->getSemanticSpelling() == SemanticSpelling)
5910 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5911 << 1 /*previous declaration*/;
5912 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5913 D->dropAttr<MSInheritanceAttr>();
5916 auto *RD = cast<CXXRecordDecl>(D);
5917 if (RD->hasDefinition()) {
5918 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5919 SemanticSpelling)) {
5923 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5924 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5925 << 1 /*partial specialization*/;
5928 if (RD->getDescribedClassTemplate()) {
5929 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5930 << 0 /*primary template*/;
5935 return ::new (Context)
5936 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5939 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5940 // The capability attributes take a single string parameter for the name of
5941 // the capability they represent. The lockable attribute does not take any
5942 // parameters. However, semantically, both attributes represent the same
5943 // concept, and so they use the same semantic attribute. Eventually, the
5944 // lockable attribute will be removed.
5946 // For backward compatibility, any capability which has no specified string
5947 // literal will be considered a "mutex."
5948 StringRef N("mutex");
5949 SourceLocation LiteralLoc;
5950 if (AL.getKind() == ParsedAttr::AT_Capability &&
5951 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
5954 // Currently, there are only two names allowed for a capability: role and
5955 // mutex (case insensitive). Diagnose other capability names.
5956 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5957 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5959 D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
5960 AL.getAttributeSpellingListIndex()));
5963 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5964 SmallVector<Expr*, 1> Args;
5965 if (!checkLockFunAttrCommon(S, D, AL, Args))
5968 D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
5969 Args.data(), Args.size(),
5970 AL.getAttributeSpellingListIndex()));
5973 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5974 const ParsedAttr &AL) {
5975 SmallVector<Expr*, 1> Args;
5976 if (!checkLockFunAttrCommon(S, D, AL, Args))
5979 D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
5981 Args.data(), Args.size(),
5982 AL.getAttributeSpellingListIndex()));
5985 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5986 const ParsedAttr &AL) {
5987 SmallVector<Expr*, 2> Args;
5988 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
5991 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
5996 AL.getAttributeSpellingListIndex()));
5999 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6000 const ParsedAttr &AL) {
6001 // Check that all arguments are lockable objects.
6002 SmallVector<Expr *, 1> Args;
6003 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6005 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
6006 AL.getRange(), S.Context, Args.data(), Args.size(),
6007 AL.getAttributeSpellingListIndex()));
6010 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6011 const ParsedAttr &AL) {
6012 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6015 // check that all arguments are lockable objects
6016 SmallVector<Expr*, 1> Args;
6017 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6021 RequiresCapabilityAttr *RCA = ::new (S.Context)
6022 RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
6023 Args.size(), AL.getAttributeSpellingListIndex());
6028 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6029 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6030 if (NSD->isAnonymousNamespace()) {
6031 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6032 // Do not want to attach the attribute to the namespace because that will
6033 // cause confusing diagnostic reports for uses of declarations within the
6039 // Handle the cases where the attribute has a text message.
6040 StringRef Str, Replacement;
6041 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6042 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6045 // Only support a single optional message for Declspec and CXX11.
6046 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6047 checkAttributeAtMostNumArgs(S, AL, 1);
6048 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6049 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6052 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6053 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6055 D->addAttr(::new (S.Context)
6056 DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
6057 AL.getAttributeSpellingListIndex()));
6060 static bool isGlobalVar(const Decl *D) {
6061 if (const auto *S = dyn_cast<VarDecl>(D))
6062 return S->hasGlobalStorage();
6066 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6067 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6070 std::vector<StringRef> Sanitizers;
6072 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6073 StringRef SanitizerName;
6074 SourceLocation LiteralLoc;
6076 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6079 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
6080 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6081 else if (isGlobalVar(D) && SanitizerName != "address")
6082 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6083 << AL << ExpectedFunctionOrMethod;
6084 Sanitizers.push_back(SanitizerName);
6087 D->addAttr(::new (S.Context) NoSanitizeAttr(
6088 AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
6089 AL.getAttributeSpellingListIndex()));
6092 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6093 const ParsedAttr &AL) {
6094 StringRef AttrName = AL.getName()->getName();
6095 normalizeName(AttrName);
6096 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6097 .Case("no_address_safety_analysis", "address")
6098 .Case("no_sanitize_address", "address")
6099 .Case("no_sanitize_thread", "thread")
6100 .Case("no_sanitize_memory", "memory");
6101 if (isGlobalVar(D) && SanitizerName != "address")
6102 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6103 << AL << ExpectedFunction;
6104 D->addAttr(::new (S.Context)
6105 NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1,
6106 AL.getAttributeSpellingListIndex()));
6109 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6110 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6111 D->addAttr(Internal);
6114 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6115 if (S.LangOpts.OpenCLVersion != 200)
6116 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6117 << AL << "2.0" << 0;
6119 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6123 /// Handles semantic checking for features that are common to all attributes,
6124 /// such as checking whether a parameter was properly specified, or the correct
6125 /// number of arguments were passed, etc.
6126 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6127 const ParsedAttr &AL) {
6128 // Several attributes carry different semantics than the parsing requires, so
6129 // those are opted out of the common argument checks.
6131 // We also bail on unknown and ignored attributes because those are handled
6132 // as part of the target-specific handling logic.
6133 if (AL.getKind() == ParsedAttr::UnknownAttribute)
6135 // Check whether the attribute requires specific language extensions to be
6137 if (!AL.diagnoseLangOpts(S))
6139 // Check whether the attribute appertains to the given subject.
6140 if (!AL.diagnoseAppertainsTo(S, D))
6142 if (AL.hasCustomParsing())
6145 if (AL.getMinArgs() == AL.getMaxArgs()) {
6146 // If there are no optional arguments, then checking for the argument count
6148 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6151 // There are optional arguments, so checking is slightly more involved.
6152 if (AL.getMinArgs() &&
6153 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6155 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6156 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6160 if (S.CheckAttrTarget(AL))
6166 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6167 if (D->isInvalidDecl())
6170 // Check if there is only one access qualifier.
6171 if (D->hasAttr<OpenCLAccessAttr>()) {
6172 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6173 AL.getSemanticSpelling()) {
6174 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6175 << AL.getName()->getName() << AL.getRange();
6177 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6178 << D->getSourceRange();
6179 D->setInvalidDecl(true);
6184 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6185 // image object can be read and written.
6186 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6187 // object. Using the read_write (or __read_write) qualifier with the pipe
6188 // qualifier is a compilation error.
6189 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6190 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6191 if (AL.getName()->getName().find("read_write") != StringRef::npos) {
6192 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
6193 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6194 << AL << PDecl->getType() << DeclTy->isImageType();
6195 D->setInvalidDecl(true);
6201 D->addAttr(::new (S.Context) OpenCLAccessAttr(
6202 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
6205 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6206 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6207 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6208 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6212 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6213 handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6215 handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6218 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6219 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6220 "uninitialized is only valid on automatic duration variables");
6221 unsigned Index = AL.getAttributeSpellingListIndex();
6222 D->addAttr(::new (S.Context)
6223 UninitializedAttr(AL.getLoc(), S.Context, Index));
6226 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6227 bool DiagnoseFailure) {
6228 QualType Ty = VD->getType();
6229 if (!Ty->isObjCRetainableType()) {
6230 if (DiagnoseFailure) {
6231 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6237 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6239 // Sema::inferObjCARCLifetime must run after processing decl attributes
6240 // (because __block lowers to an attribute), so if the lifetime hasn't been
6241 // explicitly specified, infer it locally now.
6242 if (LifetimeQual == Qualifiers::OCL_None)
6243 LifetimeQual = Ty->getObjCARCImplicitLifetime();
6245 // The attributes only really makes sense for __strong variables; ignore any
6246 // attempts to annotate a parameter with any other lifetime qualifier.
6247 if (LifetimeQual != Qualifiers::OCL_Strong) {
6248 if (DiagnoseFailure) {
6249 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6255 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6256 // to ensure that the variable is 'const' so that we can error on
6257 // modification, which can otherwise over-release.
6258 VD->setType(Ty.withConst());
6259 VD->setARCPseudoStrong(true);
6263 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6264 const ParsedAttr &AL) {
6265 if (auto *VD = dyn_cast<VarDecl>(D)) {
6266 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6267 if (!VD->hasLocalStorage()) {
6268 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6273 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6276 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6280 // If D is a function-like declaration (method, block, or function), then we
6281 // make every parameter psuedo-strong.
6282 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6283 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6284 QualType Ty = PVD->getType();
6286 // If a user wrote a parameter with __strong explicitly, then assume they
6287 // want "real" strong semantics for that parameter. This works because if
6288 // the parameter was written with __strong, then the strong qualifier will
6290 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6291 Qualifiers::OCL_Strong)
6294 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6296 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6299 //===----------------------------------------------------------------------===//
6300 // Top Level Sema Entry Points
6301 //===----------------------------------------------------------------------===//
6303 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6304 /// the attribute applies to decls. If the attribute is a type attribute, just
6305 /// silently ignore it if a GNU attribute.
6306 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6307 const ParsedAttr &AL,
6308 bool IncludeCXX11Attributes) {
6309 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6312 // Ignore C++11 attributes on declarator chunks: they appertain to the type
6314 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6317 // Unknown attributes are automatically warned on. Target-specific attributes
6318 // which do not apply to the current target architecture are treated as
6319 // though they were unknown attributes.
6320 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6321 !AL.existsInTarget(S.Context.getTargetInfo())) {
6323 AL.isDeclspecAttribute()
6324 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6325 : (unsigned)diag::warn_unknown_attribute_ignored)
6330 if (handleCommonAttributeFeatures(S, D, AL))
6333 switch (AL.getKind()) {
6335 if (!AL.isStmtAttr()) {
6336 // Type attributes are handled elsewhere; silently move on.
6337 assert(AL.isTypeAttr() && "Non-type attribute not handled");
6340 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6341 << AL << D->getLocation();
6343 case ParsedAttr::AT_Interrupt:
6344 handleInterruptAttr(S, D, AL);
6346 case ParsedAttr::AT_X86ForceAlignArgPointer:
6347 handleX86ForceAlignArgPointerAttr(S, D, AL);
6349 case ParsedAttr::AT_DLLExport:
6350 case ParsedAttr::AT_DLLImport:
6351 handleDLLAttr(S, D, AL);
6353 case ParsedAttr::AT_Mips16:
6354 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6355 MipsInterruptAttr>(S, D, AL);
6357 case ParsedAttr::AT_NoMips16:
6358 handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6360 case ParsedAttr::AT_MicroMips:
6361 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6363 case ParsedAttr::AT_NoMicroMips:
6364 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6366 case ParsedAttr::AT_MipsLongCall:
6367 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6370 case ParsedAttr::AT_MipsShortCall:
6371 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6374 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6375 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6377 case ParsedAttr::AT_AMDGPUWavesPerEU:
6378 handleAMDGPUWavesPerEUAttr(S, D, AL);
6380 case ParsedAttr::AT_AMDGPUNumSGPR:
6381 handleAMDGPUNumSGPRAttr(S, D, AL);
6383 case ParsedAttr::AT_AMDGPUNumVGPR:
6384 handleAMDGPUNumVGPRAttr(S, D, AL);
6386 case ParsedAttr::AT_AVRSignal:
6387 handleAVRSignalAttr(S, D, AL);
6389 case ParsedAttr::AT_WebAssemblyImportModule:
6390 handleWebAssemblyImportModuleAttr(S, D, AL);
6392 case ParsedAttr::AT_WebAssemblyImportName:
6393 handleWebAssemblyImportNameAttr(S, D, AL);
6395 case ParsedAttr::AT_IBAction:
6396 handleSimpleAttribute<IBActionAttr>(S, D, AL);
6398 case ParsedAttr::AT_IBOutlet:
6399 handleIBOutlet(S, D, AL);
6401 case ParsedAttr::AT_IBOutletCollection:
6402 handleIBOutletCollection(S, D, AL);
6404 case ParsedAttr::AT_IFunc:
6405 handleIFuncAttr(S, D, AL);
6407 case ParsedAttr::AT_Alias:
6408 handleAliasAttr(S, D, AL);
6410 case ParsedAttr::AT_Aligned:
6411 handleAlignedAttr(S, D, AL);
6413 case ParsedAttr::AT_AlignValue:
6414 handleAlignValueAttr(S, D, AL);
6416 case ParsedAttr::AT_AllocSize:
6417 handleAllocSizeAttr(S, D, AL);
6419 case ParsedAttr::AT_AlwaysInline:
6420 handleAlwaysInlineAttr(S, D, AL);
6422 case ParsedAttr::AT_Artificial:
6423 handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6425 case ParsedAttr::AT_AnalyzerNoReturn:
6426 handleAnalyzerNoReturnAttr(S, D, AL);
6428 case ParsedAttr::AT_TLSModel:
6429 handleTLSModelAttr(S, D, AL);
6431 case ParsedAttr::AT_Annotate:
6432 handleAnnotateAttr(S, D, AL);
6434 case ParsedAttr::AT_Availability:
6435 handleAvailabilityAttr(S, D, AL);
6437 case ParsedAttr::AT_CarriesDependency:
6438 handleDependencyAttr(S, scope, D, AL);
6440 case ParsedAttr::AT_CPUDispatch:
6441 case ParsedAttr::AT_CPUSpecific:
6442 handleCPUSpecificAttr(S, D, AL);
6444 case ParsedAttr::AT_Common:
6445 handleCommonAttr(S, D, AL);
6447 case ParsedAttr::AT_CUDAConstant:
6448 handleConstantAttr(S, D, AL);
6450 case ParsedAttr::AT_PassObjectSize:
6451 handlePassObjectSizeAttr(S, D, AL);
6453 case ParsedAttr::AT_Constructor:
6454 handleConstructorAttr(S, D, AL);
6456 case ParsedAttr::AT_CXX11NoReturn:
6457 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6459 case ParsedAttr::AT_Deprecated:
6460 handleDeprecatedAttr(S, D, AL);
6462 case ParsedAttr::AT_Destructor:
6463 handleDestructorAttr(S, D, AL);
6465 case ParsedAttr::AT_EnableIf:
6466 handleEnableIfAttr(S, D, AL);
6468 case ParsedAttr::AT_DiagnoseIf:
6469 handleDiagnoseIfAttr(S, D, AL);
6471 case ParsedAttr::AT_ExtVectorType:
6472 handleExtVectorTypeAttr(S, D, AL);
6474 case ParsedAttr::AT_ExternalSourceSymbol:
6475 handleExternalSourceSymbolAttr(S, D, AL);
6477 case ParsedAttr::AT_MinSize:
6478 handleMinSizeAttr(S, D, AL);
6480 case ParsedAttr::AT_OptimizeNone:
6481 handleOptimizeNoneAttr(S, D, AL);
6483 case ParsedAttr::AT_FlagEnum:
6484 handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6486 case ParsedAttr::AT_EnumExtensibility:
6487 handleEnumExtensibilityAttr(S, D, AL);
6489 case ParsedAttr::AT_Flatten:
6490 handleSimpleAttribute<FlattenAttr>(S, D, AL);
6492 case ParsedAttr::AT_Format:
6493 handleFormatAttr(S, D, AL);
6495 case ParsedAttr::AT_FormatArg:
6496 handleFormatArgAttr(S, D, AL);
6498 case ParsedAttr::AT_CUDAGlobal:
6499 handleGlobalAttr(S, D, AL);
6501 case ParsedAttr::AT_CUDADevice:
6502 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6505 case ParsedAttr::AT_CUDAHost:
6506 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6508 case ParsedAttr::AT_GNUInline:
6509 handleGNUInlineAttr(S, D, AL);
6511 case ParsedAttr::AT_CUDALaunchBounds:
6512 handleLaunchBoundsAttr(S, D, AL);
6514 case ParsedAttr::AT_Restrict:
6515 handleRestrictAttr(S, D, AL);
6517 case ParsedAttr::AT_LifetimeBound:
6518 handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6520 case ParsedAttr::AT_MayAlias:
6521 handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6523 case ParsedAttr::AT_Mode:
6524 handleModeAttr(S, D, AL);
6526 case ParsedAttr::AT_NoAlias:
6527 handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6529 case ParsedAttr::AT_NoCommon:
6530 handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6532 case ParsedAttr::AT_NoSplitStack:
6533 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6535 case ParsedAttr::AT_NonNull:
6536 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6537 handleNonNullAttrParameter(S, PVD, AL);
6539 handleNonNullAttr(S, D, AL);
6541 case ParsedAttr::AT_ReturnsNonNull:
6542 handleReturnsNonNullAttr(S, D, AL);
6544 case ParsedAttr::AT_NoEscape:
6545 handleNoEscapeAttr(S, D, AL);
6547 case ParsedAttr::AT_AssumeAligned:
6548 handleAssumeAlignedAttr(S, D, AL);
6550 case ParsedAttr::AT_AllocAlign:
6551 handleAllocAlignAttr(S, D, AL);
6553 case ParsedAttr::AT_Overloadable:
6554 handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6556 case ParsedAttr::AT_Ownership:
6557 handleOwnershipAttr(S, D, AL);
6559 case ParsedAttr::AT_Cold:
6560 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6562 case ParsedAttr::AT_Hot:
6563 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6565 case ParsedAttr::AT_Naked:
6566 handleNakedAttr(S, D, AL);
6568 case ParsedAttr::AT_NoReturn:
6569 handleNoReturnAttr(S, D, AL);
6571 case ParsedAttr::AT_AnyX86NoCfCheck:
6572 handleNoCfCheckAttr(S, D, AL);
6574 case ParsedAttr::AT_NoThrow:
6575 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6577 case ParsedAttr::AT_CUDAShared:
6578 handleSharedAttr(S, D, AL);
6580 case ParsedAttr::AT_VecReturn:
6581 handleVecReturnAttr(S, D, AL);
6583 case ParsedAttr::AT_ObjCOwnership:
6584 handleObjCOwnershipAttr(S, D, AL);
6586 case ParsedAttr::AT_ObjCPreciseLifetime:
6587 handleObjCPreciseLifetimeAttr(S, D, AL);
6589 case ParsedAttr::AT_ObjCReturnsInnerPointer:
6590 handleObjCReturnsInnerPointerAttr(S, D, AL);
6592 case ParsedAttr::AT_ObjCRequiresSuper:
6593 handleObjCRequiresSuperAttr(S, D, AL);
6595 case ParsedAttr::AT_ObjCBridge:
6596 handleObjCBridgeAttr(S, D, AL);
6598 case ParsedAttr::AT_ObjCBridgeMutable:
6599 handleObjCBridgeMutableAttr(S, D, AL);
6601 case ParsedAttr::AT_ObjCBridgeRelated:
6602 handleObjCBridgeRelatedAttr(S, D, AL);
6604 case ParsedAttr::AT_ObjCDesignatedInitializer:
6605 handleObjCDesignatedInitializer(S, D, AL);
6607 case ParsedAttr::AT_ObjCRuntimeName:
6608 handleObjCRuntimeName(S, D, AL);
6610 case ParsedAttr::AT_ObjCRuntimeVisible:
6611 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6613 case ParsedAttr::AT_ObjCBoxable:
6614 handleObjCBoxable(S, D, AL);
6616 case ParsedAttr::AT_CFAuditedTransfer:
6617 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6618 CFUnknownTransferAttr>(S, D, AL);
6620 case ParsedAttr::AT_CFUnknownTransfer:
6621 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6622 CFAuditedTransferAttr>(S, D, AL);
6624 case ParsedAttr::AT_CFConsumed:
6625 case ParsedAttr::AT_NSConsumed:
6626 case ParsedAttr::AT_OSConsumed:
6627 S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(),
6628 parsedAttrToRetainOwnershipKind(AL),
6629 /*IsTemplateInstantiation=*/false);
6631 case ParsedAttr::AT_NSConsumesSelf:
6632 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6634 case ParsedAttr::AT_OSConsumesThis:
6635 handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
6637 case ParsedAttr::AT_OSReturnsRetainedOnZero:
6638 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
6639 S, D, AL, isValidOSObjectOutParameter(D),
6640 diag::warn_ns_attribute_wrong_parameter_type,
6641 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
6643 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6644 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
6645 S, D, AL, isValidOSObjectOutParameter(D),
6646 diag::warn_ns_attribute_wrong_parameter_type,
6647 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
6649 case ParsedAttr::AT_NSReturnsAutoreleased:
6650 case ParsedAttr::AT_NSReturnsNotRetained:
6651 case ParsedAttr::AT_NSReturnsRetained:
6652 case ParsedAttr::AT_CFReturnsNotRetained:
6653 case ParsedAttr::AT_CFReturnsRetained:
6654 case ParsedAttr::AT_OSReturnsNotRetained:
6655 case ParsedAttr::AT_OSReturnsRetained:
6656 handleXReturnsXRetainedAttr(S, D, AL);
6658 case ParsedAttr::AT_WorkGroupSizeHint:
6659 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6661 case ParsedAttr::AT_ReqdWorkGroupSize:
6662 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6664 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6665 handleSubGroupSize(S, D, AL);
6667 case ParsedAttr::AT_VecTypeHint:
6668 handleVecTypeHint(S, D, AL);
6670 case ParsedAttr::AT_RequireConstantInit:
6671 handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
6673 case ParsedAttr::AT_InitPriority:
6674 handleInitPriorityAttr(S, D, AL);
6676 case ParsedAttr::AT_Packed:
6677 handlePackedAttr(S, D, AL);
6679 case ParsedAttr::AT_Section:
6680 handleSectionAttr(S, D, AL);
6682 case ParsedAttr::AT_SpeculativeLoadHardening:
6683 handleSimpleAttribute<SpeculativeLoadHardeningAttr>(S, D, AL);
6685 case ParsedAttr::AT_CodeSeg:
6686 handleCodeSegAttr(S, D, AL);
6688 case ParsedAttr::AT_Target:
6689 handleTargetAttr(S, D, AL);
6691 case ParsedAttr::AT_MinVectorWidth:
6692 handleMinVectorWidthAttr(S, D, AL);
6694 case ParsedAttr::AT_Unavailable:
6695 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
6697 case ParsedAttr::AT_ArcWeakrefUnavailable:
6698 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
6700 case ParsedAttr::AT_ObjCRootClass:
6701 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
6703 case ParsedAttr::AT_ObjCSubclassingRestricted:
6704 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
6706 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
6707 handleObjCSuppresProtocolAttr(S, D, AL);
6709 case ParsedAttr::AT_ObjCRequiresPropertyDefs:
6710 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
6712 case ParsedAttr::AT_Unused:
6713 handleUnusedAttr(S, D, AL);
6715 case ParsedAttr::AT_ReturnsTwice:
6716 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
6718 case ParsedAttr::AT_NotTailCalled:
6719 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
6722 case ParsedAttr::AT_DisableTailCalls:
6723 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
6726 case ParsedAttr::AT_Used:
6727 handleSimpleAttribute<UsedAttr>(S, D, AL);
6729 case ParsedAttr::AT_Visibility:
6730 handleVisibilityAttr(S, D, AL, false);
6732 case ParsedAttr::AT_TypeVisibility:
6733 handleVisibilityAttr(S, D, AL, true);
6735 case ParsedAttr::AT_WarnUnused:
6736 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
6738 case ParsedAttr::AT_WarnUnusedResult:
6739 handleWarnUnusedResult(S, D, AL);
6741 case ParsedAttr::AT_Weak:
6742 handleSimpleAttribute<WeakAttr>(S, D, AL);
6744 case ParsedAttr::AT_WeakRef:
6745 handleWeakRefAttr(S, D, AL);
6747 case ParsedAttr::AT_WeakImport:
6748 handleWeakImportAttr(S, D, AL);
6750 case ParsedAttr::AT_TransparentUnion:
6751 handleTransparentUnionAttr(S, D, AL);
6753 case ParsedAttr::AT_ObjCException:
6754 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
6756 case ParsedAttr::AT_ObjCMethodFamily:
6757 handleObjCMethodFamilyAttr(S, D, AL);
6759 case ParsedAttr::AT_ObjCNSObject:
6760 handleObjCNSObject(S, D, AL);
6762 case ParsedAttr::AT_ObjCIndependentClass:
6763 handleObjCIndependentClass(S, D, AL);
6765 case ParsedAttr::AT_Blocks:
6766 handleBlocksAttr(S, D, AL);
6768 case ParsedAttr::AT_Sentinel:
6769 handleSentinelAttr(S, D, AL);
6771 case ParsedAttr::AT_Const:
6772 handleSimpleAttribute<ConstAttr>(S, D, AL);
6774 case ParsedAttr::AT_Pure:
6775 handleSimpleAttribute<PureAttr>(S, D, AL);
6777 case ParsedAttr::AT_Cleanup:
6778 handleCleanupAttr(S, D, AL);
6780 case ParsedAttr::AT_NoDebug:
6781 handleNoDebugAttr(S, D, AL);
6783 case ParsedAttr::AT_NoDuplicate:
6784 handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
6786 case ParsedAttr::AT_Convergent:
6787 handleSimpleAttribute<ConvergentAttr>(S, D, AL);
6789 case ParsedAttr::AT_NoInline:
6790 handleSimpleAttribute<NoInlineAttr>(S, D, AL);
6792 case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
6793 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
6795 case ParsedAttr::AT_NoStackProtector:
6796 // Interacts with -fstack-protector options.
6797 handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
6799 case ParsedAttr::AT_StdCall:
6800 case ParsedAttr::AT_CDecl:
6801 case ParsedAttr::AT_FastCall:
6802 case ParsedAttr::AT_ThisCall:
6803 case ParsedAttr::AT_Pascal:
6804 case ParsedAttr::AT_RegCall:
6805 case ParsedAttr::AT_SwiftCall:
6806 case ParsedAttr::AT_VectorCall:
6807 case ParsedAttr::AT_MSABI:
6808 case ParsedAttr::AT_SysVABI:
6809 case ParsedAttr::AT_Pcs:
6810 case ParsedAttr::AT_IntelOclBicc:
6811 case ParsedAttr::AT_PreserveMost:
6812 case ParsedAttr::AT_PreserveAll:
6813 case ParsedAttr::AT_AArch64VectorPcs:
6814 handleCallConvAttr(S, D, AL);
6816 case ParsedAttr::AT_Suppress:
6817 handleSuppressAttr(S, D, AL);
6819 case ParsedAttr::AT_OpenCLKernel:
6820 handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
6822 case ParsedAttr::AT_OpenCLAccess:
6823 handleOpenCLAccessAttr(S, D, AL);
6825 case ParsedAttr::AT_OpenCLNoSVM:
6826 handleOpenCLNoSVMAttr(S, D, AL);
6828 case ParsedAttr::AT_SwiftContext:
6829 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext);
6831 case ParsedAttr::AT_SwiftErrorResult:
6832 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult);
6834 case ParsedAttr::AT_SwiftIndirectResult:
6835 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult);
6837 case ParsedAttr::AT_InternalLinkage:
6838 handleInternalLinkageAttr(S, D, AL);
6840 case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
6841 handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
6843 case ParsedAttr::AT_LTOVisibilityPublic:
6844 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
6847 // Microsoft attributes:
6848 case ParsedAttr::AT_EmptyBases:
6849 handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
6851 case ParsedAttr::AT_LayoutVersion:
6852 handleLayoutVersion(S, D, AL);
6854 case ParsedAttr::AT_TrivialABI:
6855 handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
6857 case ParsedAttr::AT_MSNoVTable:
6858 handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
6860 case ParsedAttr::AT_MSStruct:
6861 handleSimpleAttribute<MSStructAttr>(S, D, AL);
6863 case ParsedAttr::AT_Uuid:
6864 handleUuidAttr(S, D, AL);
6866 case ParsedAttr::AT_MSInheritance:
6867 handleMSInheritanceAttr(S, D, AL);
6869 case ParsedAttr::AT_SelectAny:
6870 handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
6872 case ParsedAttr::AT_Thread:
6873 handleDeclspecThreadAttr(S, D, AL);
6876 case ParsedAttr::AT_AbiTag:
6877 handleAbiTagAttr(S, D, AL);
6880 // Thread safety attributes:
6881 case ParsedAttr::AT_AssertExclusiveLock:
6882 handleAssertExclusiveLockAttr(S, D, AL);
6884 case ParsedAttr::AT_AssertSharedLock:
6885 handleAssertSharedLockAttr(S, D, AL);
6887 case ParsedAttr::AT_GuardedVar:
6888 handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
6890 case ParsedAttr::AT_PtGuardedVar:
6891 handlePtGuardedVarAttr(S, D, AL);
6893 case ParsedAttr::AT_ScopedLockable:
6894 handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
6896 case ParsedAttr::AT_NoSanitize:
6897 handleNoSanitizeAttr(S, D, AL);
6899 case ParsedAttr::AT_NoSanitizeSpecific:
6900 handleNoSanitizeSpecificAttr(S, D, AL);
6902 case ParsedAttr::AT_NoThreadSafetyAnalysis:
6903 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
6905 case ParsedAttr::AT_GuardedBy:
6906 handleGuardedByAttr(S, D, AL);
6908 case ParsedAttr::AT_PtGuardedBy:
6909 handlePtGuardedByAttr(S, D, AL);
6911 case ParsedAttr::AT_ExclusiveTrylockFunction:
6912 handleExclusiveTrylockFunctionAttr(S, D, AL);
6914 case ParsedAttr::AT_LockReturned:
6915 handleLockReturnedAttr(S, D, AL);
6917 case ParsedAttr::AT_LocksExcluded:
6918 handleLocksExcludedAttr(S, D, AL);
6920 case ParsedAttr::AT_SharedTrylockFunction:
6921 handleSharedTrylockFunctionAttr(S, D, AL);
6923 case ParsedAttr::AT_AcquiredBefore:
6924 handleAcquiredBeforeAttr(S, D, AL);
6926 case ParsedAttr::AT_AcquiredAfter:
6927 handleAcquiredAfterAttr(S, D, AL);
6930 // Capability analysis attributes.
6931 case ParsedAttr::AT_Capability:
6932 case ParsedAttr::AT_Lockable:
6933 handleCapabilityAttr(S, D, AL);
6935 case ParsedAttr::AT_RequiresCapability:
6936 handleRequiresCapabilityAttr(S, D, AL);
6939 case ParsedAttr::AT_AssertCapability:
6940 handleAssertCapabilityAttr(S, D, AL);
6942 case ParsedAttr::AT_AcquireCapability:
6943 handleAcquireCapabilityAttr(S, D, AL);
6945 case ParsedAttr::AT_ReleaseCapability:
6946 handleReleaseCapabilityAttr(S, D, AL);
6948 case ParsedAttr::AT_TryAcquireCapability:
6949 handleTryAcquireCapabilityAttr(S, D, AL);
6952 // Consumed analysis attributes.
6953 case ParsedAttr::AT_Consumable:
6954 handleConsumableAttr(S, D, AL);
6956 case ParsedAttr::AT_ConsumableAutoCast:
6957 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
6959 case ParsedAttr::AT_ConsumableSetOnRead:
6960 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
6962 case ParsedAttr::AT_CallableWhen:
6963 handleCallableWhenAttr(S, D, AL);
6965 case ParsedAttr::AT_ParamTypestate:
6966 handleParamTypestateAttr(S, D, AL);
6968 case ParsedAttr::AT_ReturnTypestate:
6969 handleReturnTypestateAttr(S, D, AL);
6971 case ParsedAttr::AT_SetTypestate:
6972 handleSetTypestateAttr(S, D, AL);
6974 case ParsedAttr::AT_TestTypestate:
6975 handleTestTypestateAttr(S, D, AL);
6978 // Type safety attributes.
6979 case ParsedAttr::AT_ArgumentWithTypeTag:
6980 handleArgumentWithTypeTagAttr(S, D, AL);
6982 case ParsedAttr::AT_TypeTagForDatatype:
6983 handleTypeTagForDatatypeAttr(S, D, AL);
6985 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
6986 handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
6988 case ParsedAttr::AT_RenderScriptKernel:
6989 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
6992 case ParsedAttr::AT_XRayInstrument:
6993 handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
6995 case ParsedAttr::AT_XRayLogArgs:
6996 handleXRayLogArgsAttr(S, D, AL);
6999 // Move semantics attribute.
7000 case ParsedAttr::AT_Reinitializes:
7001 handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7004 case ParsedAttr::AT_AlwaysDestroy:
7005 case ParsedAttr::AT_NoDestroy:
7006 handleDestroyAttr(S, D, AL);
7009 case ParsedAttr::AT_Uninitialized:
7010 handleUninitializedAttr(S, D, AL);
7013 case ParsedAttr::AT_ObjCExternallyRetained:
7014 handleObjCExternallyRetainedAttr(S, D, AL);
7019 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7020 /// attribute list to the specified decl, ignoring any type attributes.
7021 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7022 const ParsedAttributesView &AttrList,
7023 bool IncludeCXX11Attributes) {
7024 if (AttrList.empty())
7027 for (const ParsedAttr &AL : AttrList)
7028 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7030 // FIXME: We should be able to handle these cases in TableGen.
7032 // static int a9 __attribute__((weakref));
7033 // but that looks really pointless. We reject it.
7034 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7035 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7036 << cast<NamedDecl>(D);
7037 D->dropAttr<WeakRefAttr>();
7041 // FIXME: We should be able to handle this in TableGen as well. It would be
7042 // good to have a way to specify "these attributes must appear as a group",
7043 // for these. Additionally, it would be good to have a way to specify "these
7044 // attribute must never appear as a group" for attributes like cold and hot.
7045 if (!D->hasAttr<OpenCLKernelAttr>()) {
7046 // These attributes cannot be applied to a non-kernel function.
7047 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7048 // FIXME: This emits a different error message than
7049 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7050 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7051 D->setInvalidDecl();
7052 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7053 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7054 D->setInvalidDecl();
7055 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7056 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7057 D->setInvalidDecl();
7058 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7059 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7060 D->setInvalidDecl();
7061 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7062 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7063 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7064 << A << ExpectedKernelFunction;
7065 D->setInvalidDecl();
7066 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7067 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7068 << A << ExpectedKernelFunction;
7069 D->setInvalidDecl();
7070 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7071 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7072 << A << ExpectedKernelFunction;
7073 D->setInvalidDecl();
7074 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7075 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7076 << A << ExpectedKernelFunction;
7077 D->setInvalidDecl();
7082 // Do this check after processing D's attributes because the attribute
7083 // objc_method_family can change whether the given method is in the init
7084 // family, and it can be applied after objc_designated_initializer. This is a
7085 // bit of a hack, but we need it to be compatible with versions of clang that
7086 // processed the attribute list in the wrong order.
7087 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7088 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7089 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7090 D->dropAttr<ObjCDesignatedInitializerAttr>();
7094 // Helper for delayed processing TransparentUnion attribute.
7095 void Sema::ProcessDeclAttributeDelayed(Decl *D,
7096 const ParsedAttributesView &AttrList) {
7097 for (const ParsedAttr &AL : AttrList)
7098 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7099 handleTransparentUnionAttr(*this, D, AL);
7104 // Annotation attributes are the only attributes allowed after an access
7106 bool Sema::ProcessAccessDeclAttributeList(
7107 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7108 for (const ParsedAttr &AL : AttrList) {
7109 if (AL.getKind() == ParsedAttr::AT_Annotate) {
7110 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7112 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7119 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7120 /// contains any decl attributes that we should warn about.
7121 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7122 for (const ParsedAttr &AL : A) {
7123 // Only warn if the attribute is an unignored, non-type attribute.
7124 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7126 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7129 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7130 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7131 << AL << AL.getRange();
7133 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7139 /// checkUnusedDeclAttributes - Given a declarator which is not being
7140 /// used to build a declaration, complain about any decl attributes
7141 /// which might be lying around on it.
7142 void Sema::checkUnusedDeclAttributes(Declarator &D) {
7143 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7144 ::checkUnusedDeclAttributes(*this, D.getAttributes());
7145 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7146 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7149 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7150 /// \#pragma weak needs a non-definition decl and source may not have one.
7151 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7152 SourceLocation Loc) {
7153 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7154 NamedDecl *NewD = nullptr;
7155 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7156 FunctionDecl *NewFD;
7157 // FIXME: Missing call to CheckFunctionDeclaration().
7159 // FIXME: Is the qualifier info correct?
7160 // FIXME: Is the DeclContext correct?
7161 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
7162 Loc, Loc, DeclarationName(II),
7163 FD->getType(), FD->getTypeSourceInfo(),
7164 SC_None, false/*isInlineSpecified*/,
7166 false/*isConstexprSpecified*/);
7169 if (FD->getQualifier())
7170 NewFD->setQualifierInfo(FD->getQualifierLoc());
7172 // Fake up parameter variables; they are declared as if this were
7174 QualType FDTy = FD->getType();
7175 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7176 SmallVector<ParmVarDecl*, 16> Params;
7177 for (const auto &AI : FT->param_types()) {
7178 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7179 Param->setScopeInfo(0, Params.size());
7180 Params.push_back(Param);
7182 NewFD->setParams(Params);
7184 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7185 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7186 VD->getInnerLocStart(), VD->getLocation(), II,
7187 VD->getType(), VD->getTypeSourceInfo(),
7188 VD->getStorageClass());
7189 if (VD->getQualifier())
7190 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7195 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7196 /// applied to it, possibly with an alias.
7197 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7198 if (W.getUsed()) return; // only do this once
7200 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7201 IdentifierInfo *NDId = ND->getIdentifier();
7202 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7203 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
7205 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7206 WeakTopLevelDecl.push_back(NewD);
7207 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7208 // to insert Decl at TU scope, sorry.
7209 DeclContext *SavedContext = CurContext;
7210 CurContext = Context.getTranslationUnitDecl();
7211 NewD->setDeclContext(CurContext);
7212 NewD->setLexicalDeclContext(CurContext);
7213 PushOnScopeChains(NewD, S);
7214 CurContext = SavedContext;
7215 } else { // just add weak to existing
7216 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7220 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7221 // It's valid to "forward-declare" #pragma weak, in which case we
7223 LoadExternalWeakUndeclaredIdentifiers();
7224 if (!WeakUndeclaredIdentifiers.empty()) {
7225 NamedDecl *ND = nullptr;
7226 if (auto *VD = dyn_cast<VarDecl>(D))
7227 if (VD->isExternC())
7229 if (auto *FD = dyn_cast<FunctionDecl>(D))
7230 if (FD->isExternC())
7233 if (IdentifierInfo *Id = ND->getIdentifier()) {
7234 auto I = WeakUndeclaredIdentifiers.find(Id);
7235 if (I != WeakUndeclaredIdentifiers.end()) {
7236 WeakInfo W = I->second;
7237 DeclApplyPragmaWeak(S, ND, W);
7238 WeakUndeclaredIdentifiers[Id] = W;
7245 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7246 /// it, apply them to D. This is a bit tricky because PD can have attributes
7247 /// specified in many different places, and we need to find and apply them all.
7248 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7249 // Apply decl attributes from the DeclSpec if present.
7250 if (!PD.getDeclSpec().getAttributes().empty())
7251 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7253 // Walk the declarator structure, applying decl attributes that were in a type
7254 // position to the decl itself. This handles cases like:
7255 // int *__attr__(x)** D;
7256 // when X is a decl attribute.
7257 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7258 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7259 /*IncludeCXX11Attributes=*/false);
7261 // Finally, apply any attributes on the decl itself.
7262 ProcessDeclAttributeList(S, D, PD.getAttributes());
7264 // Apply additional attributes specified by '#pragma clang attribute'.
7265 AddPragmaAttributes(S, D);
7268 /// Is the given declaration allowed to use a forbidden type?
7269 /// If so, it'll still be annotated with an attribute that makes it
7270 /// illegal to actually use.
7271 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7272 const DelayedDiagnostic &diag,
7273 UnavailableAttr::ImplicitReason &reason) {
7274 // Private ivars are always okay. Unfortunately, people don't
7275 // always properly make their ivars private, even in system headers.
7276 // Plus we need to make fields okay, too.
7277 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7278 !isa<FunctionDecl>(D))
7281 // Silently accept unsupported uses of __weak in both user and system
7282 // declarations when it's been disabled, for ease of integration with
7283 // -fno-objc-arc files. We do have to take some care against attempts
7284 // to define such things; for now, we've only done that for ivars
7286 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7287 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7288 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7289 reason = UnavailableAttr::IR_ForbiddenWeak;
7294 // Allow all sorts of things in system headers.
7295 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7296 // Currently, all the failures dealt with this way are due to ARC
7298 reason = UnavailableAttr::IR_ARCForbiddenType;
7305 /// Handle a delayed forbidden-type diagnostic.
7306 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7308 auto Reason = UnavailableAttr::IR_None;
7309 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7310 assert(Reason && "didn't set reason?");
7311 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7314 if (S.getLangOpts().ObjCAutoRefCount)
7315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7316 // FIXME: we may want to suppress diagnostics for all
7317 // kind of forbidden type messages on unavailable functions.
7318 if (FD->hasAttr<UnavailableAttr>() &&
7319 DD.getForbiddenTypeDiagnostic() ==
7320 diag::err_arc_array_param_no_ownership) {
7321 DD.Triggered = true;
7326 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7327 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7328 DD.Triggered = true;
7331 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
7333 // Check each AvailabilityAttr to find the one for this platform.
7334 for (const auto *A : D->attrs()) {
7335 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
7336 // FIXME: this is copied from CheckAvailability. We should try to
7339 // Check if this is an App Extension "platform", and if so chop off
7340 // the suffix for matching with the actual platform.
7341 StringRef ActualPlatform = Avail->getPlatform()->getName();
7342 StringRef RealizedPlatform = ActualPlatform;
7343 if (Context.getLangOpts().AppExt) {
7344 size_t suffix = RealizedPlatform.rfind("_app_extension");
7345 if (suffix != StringRef::npos)
7346 RealizedPlatform = RealizedPlatform.slice(0, suffix);
7349 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
7351 // Match the platform name.
7352 if (RealizedPlatform == TargetPlatform)
7359 /// The diagnostic we should emit for \c D, and the declaration that
7360 /// originated it, or \c AR_Available.
7362 /// \param D The declaration to check.
7363 /// \param Message If non-null, this will be populated with the message from
7364 /// the availability attribute that is selected.
7365 /// \param ClassReceiver If we're checking the the method of a class message
7366 /// send, the class. Otherwise nullptr.
7367 static std::pair<AvailabilityResult, const NamedDecl *>
7368 ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
7369 std::string *Message,
7370 ObjCInterfaceDecl *ClassReceiver) {
7371 AvailabilityResult Result = D->getAvailability(Message);
7373 // For typedefs, if the typedef declaration appears available look
7374 // to the underlying type to see if it is more restrictive.
7375 while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
7376 if (Result == AR_Available) {
7377 if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7379 Result = D->getAvailability(Message);
7386 // Forward class declarations get their attributes from their definition.
7387 if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
7388 if (IDecl->getDefinition()) {
7389 D = IDecl->getDefinition();
7390 Result = D->getAvailability(Message);
7394 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
7395 if (Result == AR_Available) {
7396 const DeclContext *DC = ECD->getDeclContext();
7397 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
7398 Result = TheEnumDecl->getAvailability(Message);
7403 // For +new, infer availability from -init.
7404 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7405 if (S.NSAPIObj && ClassReceiver) {
7406 ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
7407 S.NSAPIObj->getInitSelector());
7408 if (Init && Result == AR_Available && MD->isClassMethod() &&
7409 MD->getSelector() == S.NSAPIObj->getNewSelector() &&
7410 MD->definedInNSObject(S.getASTContext())) {
7411 Result = Init->getAvailability(Message);
7421 /// whether we should emit a diagnostic for \c K and \c DeclVersion in
7422 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
7423 /// in a deprecated context, but not the other way around.
7425 ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
7426 VersionTuple DeclVersion, Decl *Ctx,
7427 const NamedDecl *OffendingDecl) {
7428 assert(K != AR_Available && "Expected an unavailable declaration here!");
7430 // Checks if we should emit the availability diagnostic in the context of C.
7431 auto CheckContext = [&](const Decl *C) {
7432 if (K == AR_NotYetIntroduced) {
7433 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
7434 if (AA->getIntroduced() >= DeclVersion)
7436 } else if (K == AR_Deprecated) {
7437 if (C->isDeprecated())
7439 } else if (K == AR_Unavailable) {
7440 // It is perfectly fine to refer to an 'unavailable' Objective-C method
7441 // when it is referenced from within the @implementation itself. In this
7442 // context, we interpret unavailable as a form of access control.
7443 if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
7444 if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
7445 if (MD->getClassInterface() == Impl->getClassInterface())
7451 if (C->isUnavailable())
7457 if (CheckContext(Ctx))
7460 // An implementation implicitly has the availability of the interface.
7461 // Unless it is "+load" method.
7462 if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
7463 if (MethodD->isClassMethod() &&
7464 MethodD->getSelector().getAsString() == "load")
7467 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7468 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7469 if (CheckContext(Interface))
7472 // A category implicitly has the availability of the interface.
7473 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7474 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7475 if (CheckContext(Interface))
7477 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7483 shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7484 const VersionTuple &DeploymentVersion,
7485 const VersionTuple &DeclVersion) {
7486 const auto &Triple = Context.getTargetInfo().getTriple();
7487 VersionTuple ForceAvailabilityFromVersion;
7488 switch (Triple.getOS()) {
7489 case llvm::Triple::IOS:
7490 case llvm::Triple::TvOS:
7491 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7493 case llvm::Triple::WatchOS:
7494 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7496 case llvm::Triple::Darwin:
7497 case llvm::Triple::MacOSX:
7498 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7501 // New targets should always warn about availability.
7502 return Triple.getVendor() == llvm::Triple::Apple;
7504 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7505 DeclVersion >= ForceAvailabilityFromVersion;
7508 static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7509 for (Decl *Ctx = OrigCtx; Ctx;
7510 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7511 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7512 return cast<NamedDecl>(Ctx);
7513 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7514 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7515 return Imp->getClassInterface();
7520 return dyn_cast<NamedDecl>(OrigCtx);
7525 struct AttributeInsertion {
7530 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7531 return {" ", D->getEndLoc(), ""};
7533 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7534 return {" ", Loc, ""};
7536 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7537 return {"", D->getBeginLoc(), "\n"};
7541 } // end anonymous namespace
7543 /// Tries to parse a string as ObjC method name.
7545 /// \param Name The string to parse. Expected to originate from availability
7546 /// attribute argument.
7547 /// \param SlotNames The vector that will be populated with slot names. In case
7548 /// of unsuccessful parsing can contain invalid data.
7549 /// \returns A number of method parameters if parsing was successful, None
7551 static Optional<unsigned>
7552 tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
7553 const LangOptions &LangOpts) {
7554 // Accept replacements starting with - or + as valid ObjC method names.
7555 if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
7556 Name = Name.drop_front(1);
7559 Name.split(SlotNames, ':');
7561 if (Name.back() == ':') {
7562 // Remove an empty string at the end that doesn't represent any slot.
7563 SlotNames.pop_back();
7564 NumParams = SlotNames.size();
7566 if (SlotNames.size() != 1)
7567 // Not a valid method name, just a colon-separated string.
7571 // Verify all slot names are valid.
7572 bool AllowDollar = LangOpts.DollarIdents;
7573 for (StringRef S : SlotNames) {
7576 if (!isValidIdentifier(S, AllowDollar))
7582 /// Returns a source location in which it's appropriate to insert a new
7583 /// attribute for the given declaration \D.
7584 static Optional<AttributeInsertion>
7585 createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7586 const LangOptions &LangOpts) {
7587 if (isa<ObjCPropertyDecl>(D))
7588 return AttributeInsertion::createInsertionAfter(D);
7589 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7592 return AttributeInsertion::createInsertionAfter(D);
7594 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7595 SourceLocation Loc =
7596 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7597 if (Loc.isInvalid())
7599 // Insert after the 'struct'/whatever keyword.
7600 return AttributeInsertion::createInsertionAfter(Loc);
7602 return AttributeInsertion::createInsertionBefore(D);
7605 /// Actually emit an availability diagnostic for a reference to an unavailable
7608 /// \param Ctx The context that the reference occurred in
7609 /// \param ReferringDecl The exact declaration that was referenced.
7610 /// \param OffendingDecl A related decl to \c ReferringDecl that has an
7611 /// availability attribute corresponding to \c K attached to it. Note that this
7612 /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7613 /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7614 /// and OffendingDecl is the EnumDecl.
7615 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7616 Decl *Ctx, const NamedDecl *ReferringDecl,
7617 const NamedDecl *OffendingDecl,
7619 ArrayRef<SourceLocation> Locs,
7620 const ObjCInterfaceDecl *UnknownObjCClass,
7621 const ObjCPropertyDecl *ObjCProperty,
7622 bool ObjCPropertyAccess) {
7623 // Diagnostics for deprecated or unavailable.
7624 unsigned diag, diag_message, diag_fwdclass_message;
7625 unsigned diag_available_here = diag::note_availability_specified_here;
7626 SourceLocation NoteLocation = OffendingDecl->getLocation();
7628 // Matches 'diag::note_property_attribute' options.
7629 unsigned property_note_select;
7631 // Matches diag::note_availability_specified_here.
7632 unsigned available_here_select_kind;
7634 VersionTuple DeclVersion;
7635 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7636 DeclVersion = AA->getIntroduced();
7638 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
7642 SourceLocation Loc = Locs.front();
7644 // The declaration can have multiple availability attributes, we are looking
7646 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7647 if (A && A->isInherited()) {
7648 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7649 Redecl = Redecl->getPreviousDecl()) {
7650 const AvailabilityAttr *AForRedecl =
7651 getAttrForPlatform(S.Context, Redecl);
7652 if (AForRedecl && !AForRedecl->isInherited()) {
7653 // If D is a declaration with inherited attributes, the note should
7654 // point to the declaration with actual attributes.
7655 NoteLocation = Redecl->getLocation();
7662 case AR_NotYetIntroduced: {
7663 // We would like to emit the diagnostic even if -Wunguarded-availability is
7664 // not specified for deployment targets >= to iOS 11 or equivalent or
7665 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7667 const AvailabilityAttr *AA =
7668 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7669 VersionTuple Introduced = AA->getIntroduced();
7671 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7672 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7674 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7675 : diag::warn_unguarded_availability;
7677 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
7678 S.getASTContext().getTargetInfo().getPlatformName());
7680 S.Diag(Loc, Warning) << OffendingDecl << PlatformName
7681 << Introduced.getAsString();
7683 S.Diag(OffendingDecl->getLocation(),
7684 diag::note_partial_availability_specified_here)
7685 << OffendingDecl << PlatformName << Introduced.getAsString()
7686 << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
7688 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7689 if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
7690 if (TD->getDeclName().isEmpty()) {
7691 S.Diag(TD->getLocation(),
7692 diag::note_decl_unguarded_availability_silence)
7693 << /*Anonymous*/ 1 << TD->getKindName();
7696 auto FixitNoteDiag =
7697 S.Diag(Enclosing->getLocation(),
7698 diag::note_decl_unguarded_availability_silence)
7699 << /*Named*/ 0 << Enclosing;
7700 // Don't offer a fixit for declarations with availability attributes.
7701 if (Enclosing->hasAttr<AvailabilityAttr>())
7703 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7705 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7706 Enclosing, S.getSourceManager(), S.getLangOpts());
7709 std::string PlatformName =
7710 AvailabilityAttr::getPlatformNameSourceSpelling(
7711 S.getASTContext().getTargetInfo().getPlatformName())
7713 std::string Introduced =
7714 OffendingDecl->getVersionIntroduced().getAsString();
7715 FixitNoteDiag << FixItHint::CreateInsertion(
7717 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7718 "(" + Introduced + "))" + Insertion->Suffix)
7724 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7725 : diag::warn_property_method_deprecated;
7726 diag_message = diag::warn_deprecated_message;
7727 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7728 property_note_select = /* deprecated */ 0;
7729 available_here_select_kind = /* deprecated */ 2;
7730 if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
7731 NoteLocation = AL->getLocation();
7734 case AR_Unavailable:
7735 diag = !ObjCPropertyAccess ? diag::err_unavailable
7736 : diag::err_property_method_unavailable;
7737 diag_message = diag::err_unavailable_message;
7738 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7739 property_note_select = /* unavailable */ 1;
7740 available_here_select_kind = /* unavailable */ 0;
7742 if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
7743 if (AL->isImplicit() && AL->getImplicitReason()) {
7744 // Most of these failures are due to extra restrictions in ARC;
7745 // reflect that in the primary diagnostic when applicable.
7746 auto flagARCError = [&] {
7747 if (S.getLangOpts().ObjCAutoRefCount &&
7748 S.getSourceManager().isInSystemHeader(
7749 OffendingDecl->getLocation()))
7750 diag = diag::err_unavailable_in_arc;
7753 switch (AL->getImplicitReason()) {
7754 case UnavailableAttr::IR_None: break;
7756 case UnavailableAttr::IR_ARCForbiddenType:
7758 diag_available_here = diag::note_arc_forbidden_type;
7761 case UnavailableAttr::IR_ForbiddenWeak:
7762 if (S.getLangOpts().ObjCWeakRuntime)
7763 diag_available_here = diag::note_arc_weak_disabled;
7765 diag_available_here = diag::note_arc_weak_no_runtime;
7768 case UnavailableAttr::IR_ARCForbiddenConversion:
7770 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7773 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7775 diag_available_here = diag::note_arc_init_returns_unrelated;
7778 case UnavailableAttr::IR_ARCFieldWithOwnership:
7780 diag_available_here = diag::note_arc_field_with_ownership;
7788 llvm_unreachable("Warning for availability of available declaration?");
7791 SmallVector<FixItHint, 12> FixIts;
7792 if (K == AR_Deprecated) {
7793 StringRef Replacement;
7794 if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
7795 Replacement = AL->getReplacement();
7796 if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
7797 Replacement = AL->getReplacement();
7799 CharSourceRange UseRange;
7800 if (!Replacement.empty())
7802 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7803 if (UseRange.isValid()) {
7804 if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
7805 Selector Sel = MethodDecl->getSelector();
7806 SmallVector<StringRef, 12> SelectorSlotNames;
7807 Optional<unsigned> NumParams = tryParseObjCMethodName(
7808 Replacement, SelectorSlotNames, S.getLangOpts());
7809 if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
7810 assert(SelectorSlotNames.size() == Locs.size());
7811 for (unsigned I = 0; I < Locs.size(); ++I) {
7812 if (!Sel.getNameForSlot(I).empty()) {
7813 CharSourceRange NameRange = CharSourceRange::getCharRange(
7814 Locs[I], S.getLocForEndOfToken(Locs[I]));
7815 FixIts.push_back(FixItHint::CreateReplacement(
7816 NameRange, SelectorSlotNames[I]));
7819 FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
7822 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7824 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7828 if (!Message.empty()) {
7829 S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
7831 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7832 << ObjCProperty->getDeclName() << property_note_select;
7833 } else if (!UnknownObjCClass) {
7834 S.Diag(Loc, diag) << ReferringDecl << FixIts;
7836 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7837 << ObjCProperty->getDeclName() << property_note_select;
7839 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
7840 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7843 S.Diag(NoteLocation, diag_available_here)
7844 << OffendingDecl << available_here_select_kind;
7847 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7849 assert(DD.Kind == DelayedDiagnostic::Availability &&
7850 "Expected an availability diagnostic here");
7852 DD.Triggered = true;
7853 DoEmitAvailabilityWarning(
7854 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7855 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
7856 DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
7857 DD.getObjCProperty(), false);
7860 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7861 assert(DelayedDiagnostics.getCurrentPool());
7862 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7863 DelayedDiagnostics.popWithoutEmitting(state);
7865 // When delaying diagnostics to run in the context of a parsed
7866 // declaration, we only want to actually emit anything if parsing
7870 // We emit all the active diagnostics in this pool or any of its
7871 // parents. In general, we'll get one pool for the decl spec
7872 // and a child pool for each declarator; in a decl group like:
7873 // deprecated_typedef foo, *bar, baz();
7874 // only the declarator pops will be passed decls. This is correct;
7875 // we really do need to consider delayed diagnostics from the decl spec
7876 // for each of the different declarations.
7877 const DelayedDiagnosticPool *pool = &poppedPool;
7879 bool AnyAccessFailures = false;
7880 for (DelayedDiagnosticPool::pool_iterator
7881 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7882 // This const_cast is a bit lame. Really, Triggered should be mutable.
7883 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7887 switch (diag.Kind) {
7888 case DelayedDiagnostic::Availability:
7889 // Don't bother giving deprecation/unavailable diagnostics if
7890 // the decl is invalid.
7891 if (!decl->isInvalidDecl())
7892 handleDelayedAvailabilityCheck(*this, diag, decl);
7895 case DelayedDiagnostic::Access:
7896 // Only produce one access control diagnostic for a structured binding
7897 // declaration: we don't need to tell the user that all the fields are
7898 // inaccessible one at a time.
7899 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
7901 HandleDelayedAccessCheck(diag, decl);
7903 AnyAccessFailures = true;
7906 case DelayedDiagnostic::ForbiddenType:
7907 handleDelayedForbiddenType(*this, diag, decl);
7911 } while ((pool = pool->getParent()));
7914 /// Given a set of delayed diagnostics, re-emit them as if they had
7915 /// been delayed in the current context instead of in the given pool.
7916 /// Essentially, this just moves them to the current pool.
7917 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7918 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7919 assert(curPool && "re-emitting in undelayed context not supported");
7920 curPool->steal(pool);
7923 static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7924 const NamedDecl *ReferringDecl,
7925 const NamedDecl *OffendingDecl,
7927 ArrayRef<SourceLocation> Locs,
7928 const ObjCInterfaceDecl *UnknownObjCClass,
7929 const ObjCPropertyDecl *ObjCProperty,
7930 bool ObjCPropertyAccess) {
7931 // Delay if we're currently parsing a declaration.
7932 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7933 S.DelayedDiagnostics.add(
7934 DelayedDiagnostic::makeAvailability(
7935 AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
7936 ObjCProperty, Message, ObjCPropertyAccess));
7940 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7941 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
7942 Message, Locs, UnknownObjCClass, ObjCProperty,
7943 ObjCPropertyAccess);
7948 /// Returns true if the given statement can be a body-like child of \p Parent.
7949 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7950 switch (Parent->getStmtClass()) {
7951 case Stmt::IfStmtClass:
7952 return cast<IfStmt>(Parent)->getThen() == S ||
7953 cast<IfStmt>(Parent)->getElse() == S;
7954 case Stmt::WhileStmtClass:
7955 return cast<WhileStmt>(Parent)->getBody() == S;
7956 case Stmt::DoStmtClass:
7957 return cast<DoStmt>(Parent)->getBody() == S;
7958 case Stmt::ForStmtClass:
7959 return cast<ForStmt>(Parent)->getBody() == S;
7960 case Stmt::CXXForRangeStmtClass:
7961 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7962 case Stmt::ObjCForCollectionStmtClass:
7963 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7964 case Stmt::CaseStmtClass:
7965 case Stmt::DefaultStmtClass:
7966 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7972 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7976 bool VisitStmt(Stmt *S) { return S != Target; }
7978 /// Returns true if the given statement is present in the given declaration.
7979 static bool isContained(const Stmt *Target, const Decl *D) {
7980 StmtUSEFinder Visitor;
7981 Visitor.Target = Target;
7982 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7986 /// Traverses the AST and finds the last statement that used a given
7988 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7992 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7993 if (DRE->getDecl() == D)
7998 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7999 const CompoundStmt *Scope) {
8000 LastDeclUSEFinder Visitor;
8002 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
8004 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
8011 /// This class implements -Wunguarded-availability.
8013 /// This is done with a traversal of the AST of a function that makes reference
8014 /// to a partially available declaration. Whenever we encounter an \c if of the
8015 /// form: \c if(@available(...)), we use the version from the condition to visit
8016 /// the then statement.
8017 class DiagnoseUnguardedAvailability
8018 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
8019 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
8024 /// Stack of potentially nested 'if (@available(...))'s.
8025 SmallVector<VersionTuple, 8> AvailabilityStack;
8026 SmallVector<const Stmt *, 16> StmtStack;
8028 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
8029 ObjCInterfaceDecl *ClassReceiver = nullptr);
8032 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
8033 : SemaRef(SemaRef), Ctx(Ctx) {
8034 AvailabilityStack.push_back(
8035 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
8038 bool TraverseDecl(Decl *D) {
8039 // Avoid visiting nested functions to prevent duplicate warnings.
8040 if (!D || isa<FunctionDecl>(D))
8042 return Base::TraverseDecl(D);
8045 bool TraverseStmt(Stmt *S) {
8048 StmtStack.push_back(S);
8049 bool Result = Base::TraverseStmt(S);
8050 StmtStack.pop_back();
8054 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
8056 bool TraverseIfStmt(IfStmt *If);
8058 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
8060 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
8061 // to any useful diagnostics.
8062 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
8064 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
8065 if (PRE->isClassReceiver())
8066 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
8070 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
8071 if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
8072 ObjCInterfaceDecl *ID = nullptr;
8073 QualType ReceiverTy = Msg->getClassReceiver();
8074 if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
8075 ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
8077 DiagnoseDeclAvailability(
8078 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
8083 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8084 DiagnoseDeclAvailability(DRE->getDecl(),
8085 SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
8089 bool VisitMemberExpr(MemberExpr *ME) {
8090 DiagnoseDeclAvailability(ME->getMemberDecl(),
8091 SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
8095 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
8096 SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
8097 << (!SemaRef.getLangOpts().ObjC);
8101 bool VisitTypeLoc(TypeLoc Ty);
8104 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
8105 NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
8106 AvailabilityResult Result;
8107 const NamedDecl *OffendingDecl;
8108 std::tie(Result, OffendingDecl) =
8109 ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
8110 if (Result != AR_Available) {
8111 // All other diagnostic kinds have already been handled in
8112 // DiagnoseAvailabilityOfDecl.
8113 if (Result != AR_NotYetIntroduced)
8116 const AvailabilityAttr *AA =
8117 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
8118 VersionTuple Introduced = AA->getIntroduced();
8120 if (AvailabilityStack.back() >= Introduced)
8123 // If the context of this function is less available than D, we should not
8124 // emit a diagnostic.
8125 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
8129 // We would like to emit the diagnostic even if -Wunguarded-availability is
8130 // not specified for deployment targets >= to iOS 11 or equivalent or
8131 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
8134 shouldDiagnoseAvailabilityByDefault(
8136 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
8137 ? diag::warn_unguarded_availability_new
8138 : diag::warn_unguarded_availability;
8140 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8141 SemaRef.getASTContext().getTargetInfo().getPlatformName());
8143 SemaRef.Diag(Range.getBegin(), DiagKind)
8144 << Range << D << PlatformName << Introduced.getAsString();
8146 SemaRef.Diag(OffendingDecl->getLocation(),
8147 diag::note_partial_availability_specified_here)
8148 << OffendingDecl << PlatformName << Introduced.getAsString()
8149 << SemaRef.Context.getTargetInfo()
8150 .getPlatformMinVersion()
8154 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
8156 << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
8157 : /*__builtin_available*/ 1);
8159 // Find the statement which should be enclosed in the if @available check.
8160 if (StmtStack.empty())
8162 const Stmt *StmtOfUse = StmtStack.back();
8163 const CompoundStmt *Scope = nullptr;
8164 for (const Stmt *S : llvm::reverse(StmtStack)) {
8165 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8169 if (isBodyLikeChildStmt(StmtOfUse, S)) {
8170 // The declaration won't be seen outside of the statement, so we don't
8171 // have to wrap the uses of any declared variables in if (@available).
8172 // Therefore we can avoid setting Scope here.
8177 const Stmt *LastStmtOfUse = nullptr;
8178 if (isa<DeclStmt>(StmtOfUse) && Scope) {
8179 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
8180 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
8181 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
8187 const SourceManager &SM = SemaRef.getSourceManager();
8188 SourceLocation IfInsertionLoc =
8189 SM.getExpansionLoc(StmtOfUse->getBeginLoc());
8190 SourceLocation StmtEndLoc =
8191 SM.getExpansionRange(
8192 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
8194 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
8197 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
8198 const char *ExtraIndentation = " ";
8199 std::string FixItString;
8200 llvm::raw_string_ostream FixItOS(FixItString);
8201 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
8202 : "__builtin_available")
8204 << AvailabilityAttr::getPlatformNameSourceSpelling(
8205 SemaRef.getASTContext().getTargetInfo().getPlatformName())
8206 << " " << Introduced.getAsString() << ", *)) {\n"
8207 << Indentation << ExtraIndentation;
8208 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
8209 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
8210 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
8211 /*SkipTrailingWhitespaceAndNewLine=*/false);
8212 if (ElseInsertionLoc.isInvalid())
8214 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
8215 FixItOS.str().clear();
8217 << Indentation << "} else {\n"
8218 << Indentation << ExtraIndentation
8219 << "// Fallback on earlier versions\n"
8220 << Indentation << "}";
8221 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
8225 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
8226 const Type *TyPtr = Ty.getTypePtr();
8227 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
8229 if (Range.isInvalid())
8232 if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
8233 TagDecl *TD = TT->getDecl();
8234 DiagnoseDeclAvailability(TD, Range);
8236 } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
8237 TypedefNameDecl *D = TD->getDecl();
8238 DiagnoseDeclAvailability(D, Range);
8240 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
8241 if (NamedDecl *D = ObjCO->getInterface())
8242 DiagnoseDeclAvailability(D, Range);
8248 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
8249 VersionTuple CondVersion;
8250 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
8251 CondVersion = E->getVersion();
8253 // If we're using the '*' case here or if this check is redundant, then we
8254 // use the enclosing version to check both branches.
8255 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
8256 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
8258 // This isn't an availability checking 'if', we can just continue.
8259 return Base::TraverseIfStmt(If);
8262 AvailabilityStack.push_back(CondVersion);
8263 bool ShouldContinue = TraverseStmt(If->getThen());
8264 AvailabilityStack.pop_back();
8266 return ShouldContinue && TraverseStmt(If->getElse());
8269 } // end anonymous namespace
8271 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
8272 Stmt *Body = nullptr;
8274 if (auto *FD = D->getAsFunction()) {
8275 // FIXME: We only examine the pattern decl for availability violations now,
8276 // but we should also examine instantiated templates.
8277 if (FD->isTemplateInstantiation())
8280 Body = FD->getBody();
8281 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
8282 Body = MD->getBody();
8283 else if (auto *BD = dyn_cast<BlockDecl>(D))
8284 Body = BD->getBody();
8286 assert(Body && "Need a body here!");
8288 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
8291 void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
8292 ArrayRef<SourceLocation> Locs,
8293 const ObjCInterfaceDecl *UnknownObjCClass,
8294 bool ObjCPropertyAccess,
8295 bool AvoidPartialAvailabilityChecks,
8296 ObjCInterfaceDecl *ClassReceiver) {
8297 std::string Message;
8298 AvailabilityResult Result;
8299 const NamedDecl* OffendingDecl;
8300 // See if this declaration is unavailable, deprecated, or partial.
8301 std::tie(Result, OffendingDecl) =
8302 ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
8303 if (Result == AR_Available)
8306 if (Result == AR_NotYetIntroduced) {
8307 if (AvoidPartialAvailabilityChecks)
8310 // We need to know the @available context in the current function to
8311 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
8312 // when we're done parsing the current function.
8313 if (getCurFunctionOrMethodDecl()) {
8314 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
8316 } else if (getCurBlock() || getCurLambda()) {
8317 getCurFunction()->HasPotentialAvailabilityViolations = true;
8322 const ObjCPropertyDecl *ObjCPDecl = nullptr;
8323 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
8324 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
8325 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
8326 if (PDeclResult == Result)
8331 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
8332 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);