1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements decl-related attribute processing.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetBuiltins.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 std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation>
229 getAttrLoc(const AttrInfo &AL) {
230 return AL.getLocation();
232 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
234 /// If Expr is a valid integer constant, get the value of the integer
235 /// expression and return success or failure. May output an error.
237 /// Negative argument is implicitly converted to unsigned, unless
238 /// \p StrictlyUnsigned is true.
239 template <typename AttrInfo>
240 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
241 uint32_t &Val, unsigned Idx = UINT_MAX,
242 bool StrictlyUnsigned = false) {
244 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
245 !Expr->isIntegerConstantExpr(I, S.Context)) {
247 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
248 << &AI << Idx << AANT_ArgumentIntegerConstant
249 << Expr->getSourceRange();
251 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
252 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
257 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
258 << I.toString(10, false) << 32 << /* Unsigned */ 1;
262 if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
263 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
264 << &AI << /*non-negative*/ 1;
268 Val = (uint32_t)I.getZExtValue();
272 /// Wrapper around checkUInt32Argument, with an extra check to be sure
273 /// that the result will fit into a regular (signed) int. All args have the same
274 /// purpose as they do in checkUInt32Argument.
275 template <typename AttrInfo>
276 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
277 int &Val, unsigned Idx = UINT_MAX) {
279 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
282 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
283 llvm::APSInt I(32); // for toString
285 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
286 << I.toString(10, false) << 32 << /* Unsigned */ 0;
294 /// Diagnose mutually exclusive attributes when present on a given
295 /// declaration. Returns true if diagnosed.
296 template <typename AttrTy>
297 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
298 if (const auto *A = D->getAttr<AttrTy>()) {
299 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
300 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
306 template <typename AttrTy>
307 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
308 if (const auto *A = D->getAttr<AttrTy>()) {
309 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
311 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
317 /// Check if IdxExpr is a valid parameter index for a function or
318 /// instance method D. May output an error.
320 /// \returns true if IdxExpr is a valid index.
321 template <typename AttrInfo>
322 static bool checkFunctionOrMethodParameterIndex(
323 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
324 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
325 assert(isFunctionOrMethodOrBlock(D));
327 // In C++ the implicit 'this' function parameter also counts.
328 // Parameters are counted from one.
329 bool HP = hasFunctionProto(D);
330 bool HasImplicitThisParam = isInstanceMethod(D);
331 bool IV = HP && isFunctionOrMethodVariadic(D);
333 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
336 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
337 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
338 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
339 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
340 << IdxExpr->getSourceRange();
344 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
345 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
346 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
347 << &AI << AttrArgNum << IdxExpr->getSourceRange();
350 if (HasImplicitThisParam && !CanIndexImplicitThis) {
351 if (IdxSource == 1) {
352 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
353 << &AI << IdxExpr->getSourceRange();
358 Idx = ParamIdx(IdxSource, D);
362 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
363 /// If not emit an error and return false. If the argument is an identifier it
364 /// will emit an error with a fixit hint and treat it as if it was a string
366 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368 SourceLocation *ArgLocation) {
369 // Look for identifiers. If we have one emit a hint to fix it to a literal.
370 if (AL.isArgIdent(ArgNum)) {
371 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
372 Diag(Loc->Loc, diag::err_attribute_argument_type)
373 << AL << AANT_ArgumentString
374 << FixItHint::CreateInsertion(Loc->Loc, "\"")
375 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
376 Str = Loc->Ident->getName();
378 *ArgLocation = Loc->Loc;
382 // Now check for an actual string literal.
383 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
384 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386 *ArgLocation = ArgExpr->getBeginLoc();
388 if (!Literal || !Literal->isAscii()) {
389 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
390 << AL << AANT_ArgumentString;
394 Str = Literal->getString();
398 /// Applies the given attribute to the Decl without performing any
399 /// additional semantic checking.
400 template <typename AttrType>
401 static void handleSimpleAttribute(Sema &S, Decl *D,
402 const AttributeCommonInfo &CI) {
403 D->addAttr(::new (S.Context) AttrType(S.Context, CI));
406 template <typename... DiagnosticArgs>
407 static const Sema::SemaDiagnosticBuilder&
408 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
412 template <typename T, typename... DiagnosticArgs>
413 static const Sema::SemaDiagnosticBuilder&
414 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
415 DiagnosticArgs &&... ExtraArgs) {
416 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
417 std::forward<DiagnosticArgs>(ExtraArgs)...);
420 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
421 /// {@code PassesCheck} is true.
422 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
423 /// specified in {@code ExtraArgs}.
424 template <typename AttrType, typename... DiagnosticArgs>
425 static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
426 const AttributeCommonInfo &CI,
427 bool PassesCheck, unsigned DiagID,
428 DiagnosticArgs &&... ExtraArgs) {
430 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
431 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
434 handleSimpleAttribute<AttrType>(S, D, CI);
437 template <typename AttrType>
438 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
439 const ParsedAttr &AL) {
440 handleSimpleAttribute<AttrType>(S, D, AL);
443 /// Applies the given attribute to the Decl so long as the Decl doesn't
444 /// already have one of the given incompatible attributes.
445 template <typename AttrType, typename IncompatibleAttrType,
446 typename... IncompatibleAttrTypes>
447 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
448 const ParsedAttr &AL) {
449 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
451 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
455 /// Check if the passed-in expression is of type int or bool.
456 static bool isIntOrBool(Expr *Exp) {
457 QualType QT = Exp->getType();
458 return QT->isBooleanType() || QT->isIntegerType();
462 // Check to see if the type is a smart pointer of some kind. We assume
463 // it's a smart pointer if it defines both operator-> and operator*.
464 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
465 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
466 OverloadedOperatorKind Op) {
467 DeclContextLookupResult Result =
468 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
469 return !Result.empty();
472 const RecordDecl *Record = RT->getDecl();
473 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
474 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
475 if (foundStarOperator && foundArrowOperator)
478 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
482 for (auto BaseSpecifier : CXXRecord->bases()) {
483 if (!foundStarOperator)
484 foundStarOperator = IsOverloadedOperatorPresent(
485 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
486 if (!foundArrowOperator)
487 foundArrowOperator = IsOverloadedOperatorPresent(
488 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
491 if (foundStarOperator && foundArrowOperator)
497 /// Check if passed in Decl is a pointer type.
498 /// Note that this function may produce an error message.
499 /// \return true if the Decl is a pointer type; false otherwise
500 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
501 const ParsedAttr &AL) {
502 const auto *VD = cast<ValueDecl>(D);
503 QualType QT = VD->getType();
504 if (QT->isAnyPointerType())
507 if (const auto *RT = QT->getAs<RecordType>()) {
508 // If it's an incomplete type, it could be a smart pointer; skip it.
509 // (We don't want to force template instantiation if we can avoid it,
510 // since that would alter the order in which templates are instantiated.)
511 if (RT->isIncompleteType())
514 if (threadSafetyCheckIsSmartPointer(S, RT))
518 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
522 /// Checks that the passed in QualType either is of RecordType or points
523 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
524 static const RecordType *getRecordType(QualType QT) {
525 if (const auto *RT = QT->getAs<RecordType>())
528 // Now check if we point to record type.
529 if (const auto *PT = QT->getAs<PointerType>())
530 return PT->getPointeeType()->getAs<RecordType>();
535 template <typename AttrType>
536 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
537 // Check if the record itself has the attribute.
538 if (RD->hasAttr<AttrType>())
541 // Else check if any base classes have the attribute.
542 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
543 CXXBasePaths BPaths(false, false);
544 if (CRD->lookupInBases(
545 [](const CXXBaseSpecifier *BS, CXXBasePath &) {
546 const auto &Ty = *BS->getType();
547 // If it's type-dependent, we assume it could have the attribute.
548 if (Ty.isDependentType())
550 return Ty.castAs<RecordType>()->getDecl()->hasAttr<AttrType>();
558 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
559 const RecordType *RT = getRecordType(Ty);
564 // Don't check for the capability if the class hasn't been defined yet.
565 if (RT->isIncompleteType())
568 // Allow smart pointers to be used as capability objects.
569 // FIXME -- Check the type that the smart pointer points to.
570 if (threadSafetyCheckIsSmartPointer(S, RT))
573 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
576 static bool checkTypedefTypeForCapability(QualType Ty) {
577 const auto *TD = Ty->getAs<TypedefType>();
581 TypedefNameDecl *TN = TD->getDecl();
585 return TN->hasAttr<CapabilityAttr>();
588 static bool typeHasCapability(Sema &S, QualType Ty) {
589 if (checkTypedefTypeForCapability(Ty))
592 if (checkRecordTypeForCapability(S, Ty))
598 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
599 // Capability expressions are simple expressions involving the boolean logic
600 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
601 // a DeclRefExpr is found, its type should be checked to determine whether it
602 // is a capability or not.
604 if (const auto *E = dyn_cast<CastExpr>(Ex))
605 return isCapabilityExpr(S, E->getSubExpr());
606 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
607 return isCapabilityExpr(S, E->getSubExpr());
608 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
609 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
610 E->getOpcode() == UO_Deref)
611 return isCapabilityExpr(S, E->getSubExpr());
613 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
614 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
615 return isCapabilityExpr(S, E->getLHS()) &&
616 isCapabilityExpr(S, E->getRHS());
620 return typeHasCapability(S, Ex->getType());
623 /// Checks that all attribute arguments, starting from Sidx, resolve to
624 /// a capability object.
625 /// \param Sidx The attribute argument index to start checking with.
626 /// \param ParamIdxOk Whether an argument can be indexing into a function
628 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
629 const ParsedAttr &AL,
630 SmallVectorImpl<Expr *> &Args,
632 bool ParamIdxOk = false) {
633 if (Sidx == AL.getNumArgs()) {
634 // If we don't have any capability arguments, the attribute implicitly
635 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
636 // a non-static method, and that the class is a (scoped) capability.
637 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
638 if (MD && !MD->isStatic()) {
639 const CXXRecordDecl *RD = MD->getParent();
640 // FIXME -- need to check this again on template instantiation
641 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
642 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
644 diag::warn_thread_attribute_not_on_capability_member)
645 << AL << MD->getParent();
647 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
652 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
653 Expr *ArgExp = AL.getArgAsExpr(Idx);
655 if (ArgExp->isTypeDependent()) {
656 // FIXME -- need to check this again on template instantiation
657 Args.push_back(ArgExp);
661 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
662 if (StrLit->getLength() == 0 ||
663 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
664 // Pass empty strings to the analyzer without warnings.
665 // Treat "*" as the universal lock.
666 Args.push_back(ArgExp);
670 // We allow constant strings to be used as a placeholder for expressions
671 // that are not valid C++ syntax, but warn that they are ignored.
672 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
673 Args.push_back(ArgExp);
677 QualType ArgTy = ArgExp->getType();
679 // A pointer to member expression of the form &MyClass::mu is treated
680 // specially -- we need to look at the type of the member.
681 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
682 if (UOp->getOpcode() == UO_AddrOf)
683 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
684 if (DRE->getDecl()->isCXXInstanceMember())
685 ArgTy = DRE->getDecl()->getType();
687 // First see if we can just cast to record type, or pointer to record type.
688 const RecordType *RT = getRecordType(ArgTy);
690 // Now check if we index into a record type function param.
691 if(!RT && ParamIdxOk) {
692 const auto *FD = dyn_cast<FunctionDecl>(D);
693 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
695 unsigned int NumParams = FD->getNumParams();
696 llvm::APInt ArgValue = IL->getValue();
697 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
698 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
699 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
701 diag::err_attribute_argument_out_of_bounds_extra_info)
702 << AL << Idx + 1 << NumParams;
705 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
709 // If the type does not have a capability, see if the components of the
710 // expression have capabilities. This allows for writing C code where the
711 // capability may be on the type, and the expression is a capability
712 // boolean logic expression. Eg) requires_capability(A || B && !C)
713 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
714 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
717 Args.push_back(ArgExp);
721 //===----------------------------------------------------------------------===//
722 // Attribute Implementations
723 //===----------------------------------------------------------------------===//
725 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
726 if (!threadSafetyCheckIsPointer(S, D, AL))
729 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
732 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
734 SmallVector<Expr *, 1> Args;
735 // check that all arguments are lockable objects
736 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
737 unsigned Size = Args.size();
746 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
748 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
751 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
754 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
756 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
759 if (!threadSafetyCheckIsPointer(S, D, AL))
762 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
765 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
766 SmallVectorImpl<Expr *> &Args) {
767 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
770 // Check that this attribute only applies to lockable types.
771 QualType QT = cast<ValueDecl>(D)->getType();
772 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
773 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
777 // Check that all arguments are lockable objects.
778 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
785 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
786 SmallVector<Expr *, 1> Args;
787 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
790 Expr **StartArg = &Args[0];
791 D->addAttr(::new (S.Context)
792 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
795 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
796 SmallVector<Expr *, 1> Args;
797 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
800 Expr **StartArg = &Args[0];
801 D->addAttr(::new (S.Context)
802 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
805 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
806 SmallVectorImpl<Expr *> &Args) {
807 // zero or more arguments ok
808 // check that all arguments are lockable objects
809 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
814 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
815 SmallVector<Expr *, 1> Args;
816 if (!checkLockFunAttrCommon(S, D, AL, Args))
819 unsigned Size = Args.size();
820 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
821 D->addAttr(::new (S.Context)
822 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
825 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
826 const ParsedAttr &AL) {
827 SmallVector<Expr *, 1> Args;
828 if (!checkLockFunAttrCommon(S, D, AL, Args))
831 unsigned Size = Args.size();
832 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
833 D->addAttr(::new (S.Context)
834 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
837 /// Checks to be sure that the given parameter number is in bounds, and
838 /// is an integral type. Will emit appropriate diagnostics if this returns
841 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
842 template <typename AttrInfo>
843 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
844 const AttrInfo &AI, unsigned AttrArgNo) {
845 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
846 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
848 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
852 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
853 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
854 SourceLocation SrcLoc = AttrArg->getBeginLoc();
855 S.Diag(SrcLoc, diag::err_attribute_integers_only)
856 << AI << Param->getSourceRange();
862 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
863 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
864 !checkAttributeAtMostNumArgs(S, AL, 2))
867 const auto *FD = cast<FunctionDecl>(D);
868 if (!FD->getReturnType()->isPointerType()) {
869 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
873 const Expr *SizeExpr = AL.getArgAsExpr(0);
875 // Parameter indices are 1-indexed, hence Index=1
876 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
878 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
880 ParamIdx SizeArgNo(SizeArgNoVal, D);
882 ParamIdx NumberArgNo;
883 if (AL.getNumArgs() == 2) {
884 const Expr *NumberExpr = AL.getArgAsExpr(1);
886 // Parameter indices are 1-based, hence Index=2
887 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
889 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
891 NumberArgNo = ParamIdx(Val, D);
894 D->addAttr(::new (S.Context)
895 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
898 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
899 SmallVectorImpl<Expr *> &Args) {
900 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
903 if (!isIntOrBool(AL.getArgAsExpr(0))) {
904 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
905 << AL << 1 << AANT_ArgumentIntOrBool;
909 // check that all arguments are lockable objects
910 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
915 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
916 const ParsedAttr &AL) {
917 SmallVector<Expr*, 2> Args;
918 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
921 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
922 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
925 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
926 const ParsedAttr &AL) {
927 SmallVector<Expr*, 2> Args;
928 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
931 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
932 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
935 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
936 // check that the argument is lockable object
937 SmallVector<Expr*, 1> Args;
938 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
939 unsigned Size = Args.size();
943 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
946 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
947 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
950 // check that all arguments are lockable objects
951 SmallVector<Expr*, 1> Args;
952 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
953 unsigned Size = Args.size();
956 Expr **StartArg = &Args[0];
958 D->addAttr(::new (S.Context)
959 LocksExcludedAttr(S.Context, AL, StartArg, Size));
962 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
963 Expr *&Cond, StringRef &Msg) {
964 Cond = AL.getArgAsExpr(0);
965 if (!Cond->isTypeDependent()) {
966 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
967 if (Converted.isInvalid())
969 Cond = Converted.get();
972 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
976 Msg = "<no message provided>";
978 SmallVector<PartialDiagnosticAt, 8> Diags;
979 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
980 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
982 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
983 for (const PartialDiagnosticAt &PDiag : Diags)
984 S.Diag(PDiag.first, PDiag.second);
990 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
991 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
995 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
996 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
1000 /// Determines if a given Expr references any of the given function's
1001 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1002 class ArgumentDependenceChecker
1003 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1005 const CXXRecordDecl *ClassType;
1007 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1011 ArgumentDependenceChecker(const FunctionDecl *FD) {
1013 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1014 ClassType = MD->getParent();
1016 ClassType = nullptr;
1018 Parms.insert(FD->param_begin(), FD->param_end());
1021 bool referencesArgs(Expr *E) {
1027 bool VisitCXXThisExpr(CXXThisExpr *E) {
1028 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1029 "`this` doesn't refer to the enclosing class?");
1034 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1035 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1036 if (Parms.count(PVD)) {
1045 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1046 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1050 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1053 StringRef DiagTypeStr;
1054 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1057 DiagnoseIfAttr::DiagnosticType DiagType;
1058 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1059 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1060 diag::err_diagnose_if_invalid_diagnostic_type);
1064 bool ArgDependent = false;
1065 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1066 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1067 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1068 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1071 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1072 static constexpr const StringRef kWildcard = "*";
1074 llvm::SmallVector<StringRef, 16> Names;
1075 bool HasWildcard = false;
1077 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1078 if (Name == kWildcard)
1080 Names.push_back(Name);
1083 // Add previously defined attributes.
1084 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1085 for (StringRef BuiltinName : NBA->builtinNames())
1086 AddBuiltinName(BuiltinName);
1088 // Add current attributes.
1089 if (AL.getNumArgs() == 0)
1090 AddBuiltinName(kWildcard);
1092 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1093 StringRef BuiltinName;
1094 SourceLocation LiteralLoc;
1095 if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1098 if (Builtin::Context::isBuiltinFunc(BuiltinName))
1099 AddBuiltinName(BuiltinName);
1101 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1102 << BuiltinName << AL;
1105 // Repeating the same attribute is fine.
1107 Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1109 // Empty no_builtin must be on its own.
1110 if (HasWildcard && Names.size() > 1)
1111 S.Diag(D->getLocation(),
1112 diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1115 if (D->hasAttr<NoBuiltinAttr>())
1116 D->dropAttr<NoBuiltinAttr>();
1117 D->addAttr(::new (S.Context)
1118 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1121 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1122 if (D->hasAttr<PassObjectSizeAttr>()) {
1123 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1127 Expr *E = AL.getArgAsExpr(0);
1129 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1132 // pass_object_size's argument is passed in as the second argument of
1133 // __builtin_object_size. So, it has the same constraints as that second
1134 // argument; namely, it must be in the range [0, 3].
1136 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1137 << AL << 0 << 3 << E->getSourceRange();
1141 // pass_object_size is only supported on constant pointer parameters; as a
1142 // kindness to users, we allow the parameter to be non-const for declarations.
1143 // At this point, we have no clue if `D` belongs to a function declaration or
1144 // definition, so we defer the constness check until later.
1145 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1146 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1150 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1153 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1154 ConsumableAttr::ConsumedState DefaultState;
1156 if (AL.isArgIdent(0)) {
1157 IdentifierLoc *IL = AL.getArgAsIdent(0);
1158 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1160 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1165 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1166 << AL << AANT_ArgumentIdentifier;
1170 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1173 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1174 const ParsedAttr &AL) {
1175 QualType ThisType = MD->getThisType()->getPointeeType();
1177 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1178 if (!RD->hasAttr<ConsumableAttr>()) {
1179 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1188 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1189 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1192 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1195 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1196 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1197 CallableWhenAttr::ConsumedState CallableState;
1199 StringRef StateString;
1201 if (AL.isArgIdent(ArgIndex)) {
1202 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1203 StateString = Ident->Ident->getName();
1206 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1210 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1212 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1216 States.push_back(CallableState);
1219 D->addAttr(::new (S.Context)
1220 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1223 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1224 ParamTypestateAttr::ConsumedState ParamState;
1226 if (AL.isArgIdent(0)) {
1227 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1228 StringRef StateString = Ident->Ident->getName();
1230 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1232 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1233 << AL << StateString;
1237 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1238 << AL << AANT_ArgumentIdentifier;
1242 // FIXME: This check is currently being done in the analysis. It can be
1243 // enabled here only after the parser propagates attributes at
1244 // template specialization definition, not declaration.
1245 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1246 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1248 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1249 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1250 // ReturnType.getAsString();
1254 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1257 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1258 ReturnTypestateAttr::ConsumedState ReturnState;
1260 if (AL.isArgIdent(0)) {
1261 IdentifierLoc *IL = AL.getArgAsIdent(0);
1262 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1264 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1269 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1270 << AL << AANT_ArgumentIdentifier;
1274 // FIXME: This check is currently being done in the analysis. It can be
1275 // enabled here only after the parser propagates attributes at
1276 // template specialization definition, not declaration.
1277 //QualType ReturnType;
1279 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1280 // ReturnType = Param->getType();
1282 //} else if (const CXXConstructorDecl *Constructor =
1283 // dyn_cast<CXXConstructorDecl>(D)) {
1284 // ReturnType = Constructor->getThisType()->getPointeeType();
1288 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1291 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1293 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1294 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1295 // ReturnType.getAsString();
1299 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1302 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1303 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1306 SetTypestateAttr::ConsumedState NewState;
1307 if (AL.isArgIdent(0)) {
1308 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1309 StringRef Param = Ident->Ident->getName();
1310 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1311 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1316 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1317 << AL << AANT_ArgumentIdentifier;
1321 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1324 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1325 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1328 TestTypestateAttr::ConsumedState TestState;
1329 if (AL.isArgIdent(0)) {
1330 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1331 StringRef Param = Ident->Ident->getName();
1332 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1333 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1338 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1339 << AL << AANT_ArgumentIdentifier;
1343 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1346 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1347 // Remember this typedef decl, we will need it later for diagnostics.
1348 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1351 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1352 if (auto *TD = dyn_cast<TagDecl>(D))
1353 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
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(S.Context, AL));
1368 // Report warning about changed offset in the newer compiler versions.
1369 if (BitfieldByteAligned)
1370 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1372 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1376 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1379 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1380 // The IBOutlet/IBOutletCollection attributes only apply to instance
1381 // variables or properties of Objective-C classes. The outlet must also
1382 // have an object reference type.
1383 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1384 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1385 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1386 << AL << VD->getType() << 0;
1390 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1391 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1392 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1393 << AL << PD->getType() << 1;
1398 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1405 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1406 if (!checkIBOutletCommon(S, D, AL))
1409 D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1412 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1414 // The iboutletcollection attribute can have zero or one arguments.
1415 if (AL.getNumArgs() > 1) {
1416 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1420 if (!checkIBOutletCommon(S, D, AL))
1425 if (AL.hasParsedType())
1426 PT = AL.getTypeArg();
1428 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1429 S.getScopeForContext(D->getDeclContext()->getParent()));
1431 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1436 TypeSourceInfo *QTLoc = nullptr;
1437 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1439 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1441 // Diagnose use of non-object type in iboutletcollection attribute.
1442 // FIXME. Gnu attribute extension ignores use of builtin types in
1443 // attributes. So, __attribute__((iboutletcollection(char))) will be
1444 // treated as __attribute__((iboutletcollection())).
1445 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1447 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1448 : diag::err_iboutletcollection_type) << QT;
1452 D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1455 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1457 if (T->isReferenceType())
1460 T = T.getNonReferenceType();
1463 // The nonnull attribute, and other similar attributes, can be applied to a
1464 // transparent union that contains a pointer type.
1465 if (const RecordType *UT = T->getAsUnionType()) {
1466 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1467 RecordDecl *UD = UT->getDecl();
1468 for (const auto *I : UD->fields()) {
1469 QualType QT = I->getType();
1470 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1476 return T->isAnyPointerType() || T->isBlockPointerType();
1479 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1480 SourceRange AttrParmRange,
1481 SourceRange TypeRange,
1482 bool isReturnValue = false) {
1483 if (!S.isValidPointerAttrType(T)) {
1485 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1486 << AL << AttrParmRange << TypeRange;
1488 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1489 << AL << AttrParmRange << TypeRange << 0;
1495 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1496 SmallVector<ParamIdx, 8> NonNullArgs;
1497 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1498 Expr *Ex = AL.getArgAsExpr(I);
1500 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1503 // Is the function argument a pointer type?
1504 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1505 !attrNonNullArgCheck(
1506 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1507 Ex->getSourceRange(),
1508 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1511 NonNullArgs.push_back(Idx);
1514 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1515 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1516 // check if the attribute came from a macro expansion or a template
1518 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1519 !S.inTemplateInstantiation()) {
1520 bool AnyPointers = isFunctionOrMethodVariadic(D);
1521 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1522 I != E && !AnyPointers; ++I) {
1523 QualType T = getFunctionOrMethodParamType(D, I);
1524 if (T->isDependentType() || S.isValidPointerAttrType(T))
1529 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1532 ParamIdx *Start = NonNullArgs.data();
1533 unsigned Size = NonNullArgs.size();
1534 llvm::array_pod_sort(Start, Start + Size);
1535 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1538 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1539 const ParsedAttr &AL) {
1540 if (AL.getNumArgs() > 0) {
1541 if (D->getFunctionType()) {
1542 handleNonNullAttr(S, D, AL);
1544 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1545 << D->getSourceRange();
1550 // Is the argument a pointer type?
1551 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1552 D->getSourceRange()))
1555 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1558 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1559 QualType ResultType = getFunctionOrMethodResultType(D);
1560 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1561 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1562 /* isReturnValue */ true))
1565 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1568 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1569 if (D->isInvalidDecl())
1572 // noescape only applies to pointer types.
1573 QualType T = cast<ParmVarDecl>(D)->getType();
1574 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1575 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1576 << AL << AL.getRange() << 0;
1580 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1583 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1584 Expr *E = AL.getArgAsExpr(0),
1585 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1586 S.AddAssumeAlignedAttr(D, AL, E, OE);
1589 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1590 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1593 void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1595 QualType ResultType = getFunctionOrMethodResultType(D);
1596 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1598 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1599 SourceLocation AttrLoc = TmpAttr.getLocation();
1601 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1602 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1603 << &TmpAttr << TmpAttr.getRange() << SR;
1607 if (!E->isValueDependent()) {
1609 if (!E->isIntegerConstantExpr(I, Context)) {
1611 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1612 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1613 << E->getSourceRange();
1615 Diag(AttrLoc, diag::err_attribute_argument_type)
1616 << &TmpAttr << AANT_ArgumentIntegerConstant
1617 << E->getSourceRange();
1621 if (!I.isPowerOf2()) {
1622 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1623 << E->getSourceRange();
1627 if (I > Sema::MaximumAlignment)
1628 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1629 << CI.getRange() << Sema::MaximumAlignment;
1633 if (!OE->isValueDependent()) {
1635 if (!OE->isIntegerConstantExpr(I, Context)) {
1636 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1637 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1638 << OE->getSourceRange();
1644 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1647 void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1649 QualType ResultType = getFunctionOrMethodResultType(D);
1651 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1652 SourceLocation AttrLoc = CI.getLoc();
1654 if (!ResultType->isDependentType() &&
1655 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1656 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1657 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1662 const auto *FuncDecl = cast<FunctionDecl>(D);
1663 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1664 /*AttrArgNum=*/1, ParamExpr, Idx))
1667 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1668 if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1669 !Ty->isAlignValT()) {
1670 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1672 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1676 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1679 /// Normalize the attribute, __foo__ becomes foo.
1680 /// Returns true if normalization was applied.
1681 static bool normalizeName(StringRef &AttrName) {
1682 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1683 AttrName.endswith("__")) {
1684 AttrName = AttrName.drop_front(2).drop_back(2);
1690 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1691 // This attribute must be applied to a function declaration. The first
1692 // argument to the attribute must be an identifier, the name of the resource,
1693 // for example: malloc. The following arguments must be argument indexes, the
1694 // arguments must be of integer type for Returns, otherwise of pointer type.
1695 // The difference between Holds and Takes is that a pointer may still be used
1696 // after being held. free() should be __attribute((ownership_takes)), whereas
1697 // a list append function may well be __attribute((ownership_holds)).
1699 if (!AL.isArgIdent(0)) {
1700 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1701 << AL << 1 << AANT_ArgumentIdentifier;
1705 // Figure out our Kind.
1706 OwnershipAttr::OwnershipKind K =
1707 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1711 case OwnershipAttr::Takes:
1712 case OwnershipAttr::Holds:
1713 if (AL.getNumArgs() < 2) {
1714 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1718 case OwnershipAttr::Returns:
1719 if (AL.getNumArgs() > 2) {
1720 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1726 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1728 StringRef ModuleName = Module->getName();
1729 if (normalizeName(ModuleName)) {
1730 Module = &S.PP.getIdentifierTable().get(ModuleName);
1733 SmallVector<ParamIdx, 8> OwnershipArgs;
1734 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1735 Expr *Ex = AL.getArgAsExpr(i);
1737 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1740 // Is the function argument a pointer type?
1741 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1742 int Err = -1; // No error
1744 case OwnershipAttr::Takes:
1745 case OwnershipAttr::Holds:
1746 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1749 case OwnershipAttr::Returns:
1750 if (!T->isIntegerType())
1755 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1756 << Ex->getSourceRange();
1760 // Check we don't have a conflict with another ownership attribute.
1761 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1762 // Cannot have two ownership attributes of different kinds for the same
1764 if (I->getOwnKind() != K && I->args_end() !=
1765 std::find(I->args_begin(), I->args_end(), Idx)) {
1766 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1768 } else if (K == OwnershipAttr::Returns &&
1769 I->getOwnKind() == OwnershipAttr::Returns) {
1770 // A returns attribute conflicts with any other returns attribute using
1771 // a different index.
1772 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1773 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1774 << I->args_begin()->getSourceIndex();
1776 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1777 << Idx.getSourceIndex() << Ex->getSourceRange();
1782 OwnershipArgs.push_back(Idx);
1785 ParamIdx *Start = OwnershipArgs.data();
1786 unsigned Size = OwnershipArgs.size();
1787 llvm::array_pod_sort(Start, Start + Size);
1788 D->addAttr(::new (S.Context)
1789 OwnershipAttr(S.Context, AL, Module, Start, Size));
1792 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1793 // Check the attribute arguments.
1794 if (AL.getNumArgs() > 1) {
1795 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1801 // static int a __attribute__((weakref ("v2")));
1802 // static int b() __attribute__((weakref ("f3")));
1804 // and ignores the attributes of
1806 // static int a __attribute__((weakref ("v2")));
1809 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1810 if (!Ctx->isFileContext()) {
1811 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1812 << cast<NamedDecl>(D);
1816 // The GCC manual says
1818 // At present, a declaration to which `weakref' is attached can only
1823 // Without a TARGET,
1824 // given as an argument to `weakref' or to `alias', `weakref' is
1825 // equivalent to `weak'.
1827 // gcc 4.4.1 will accept
1828 // int a7 __attribute__((weakref));
1830 // int a7 __attribute__((weak));
1831 // This looks like a bug in gcc. We reject that for now. We should revisit
1832 // it if this behaviour is actually used.
1835 // static ((alias ("y"), weakref)).
1836 // Should we? How to check that weakref is before or after alias?
1838 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1839 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1840 // StringRef parameter it was given anyway.
1842 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1843 // GCC will accept anything as the argument of weakref. Should we
1844 // check for an existing decl?
1845 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1847 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1850 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1852 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1855 // Aliases should be on declarations, not definitions.
1856 const auto *FD = cast<FunctionDecl>(D);
1857 if (FD->isThisDeclarationADefinition()) {
1858 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1862 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1865 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1867 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1870 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1871 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1874 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1875 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1878 // Aliases should be on declarations, not definitions.
1879 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1880 if (FD->isThisDeclarationADefinition()) {
1881 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1885 const auto *VD = cast<VarDecl>(D);
1886 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1887 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1892 // Mark target used to prevent unneeded-internal-declaration warnings.
1893 if (!S.LangOpts.CPlusPlus) {
1894 // FIXME: demangle Str for C++, as the attribute refers to the mangled
1895 // linkage name, not the pre-mangled identifier.
1896 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1897 LookupResult LR(S, target, Sema::LookupOrdinaryName);
1898 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1899 for (NamedDecl *ND : LR)
1900 ND->markUsed(S.Context);
1903 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1906 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1908 SourceLocation LiteralLoc;
1909 // Check that it is a string.
1910 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1913 // Check that the value.
1914 if (Model != "global-dynamic" && Model != "local-dynamic"
1915 && Model != "initial-exec" && Model != "local-exec") {
1916 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1920 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1923 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1924 QualType ResultType = getFunctionOrMethodResultType(D);
1925 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1926 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1930 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1931 << AL << getFunctionOrMethodResultSourceRange(D);
1934 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1935 FunctionDecl *FD = cast<FunctionDecl>(D);
1937 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1938 if (MD->getParent()->isLambda()) {
1939 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1944 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1947 SmallVector<IdentifierInfo *, 8> CPUs;
1948 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1949 if (!AL.isArgIdent(ArgNo)) {
1950 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1951 << AL << AANT_ArgumentIdentifier;
1955 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1956 StringRef CPUName = CPUArg->Ident->getName().trim();
1958 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1959 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1960 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1964 const TargetInfo &Target = S.Context.getTargetInfo();
1965 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1966 return Target.CPUSpecificManglingCharacter(CPUName) ==
1967 Target.CPUSpecificManglingCharacter(Cur->getName());
1969 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1972 CPUs.push_back(CPUArg->Ident);
1975 FD->setIsMultiVersion(true);
1976 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1977 D->addAttr(::new (S.Context)
1978 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1980 D->addAttr(::new (S.Context)
1981 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1984 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1985 if (S.LangOpts.CPlusPlus) {
1986 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
1987 << AL << AttributeLangSupport::Cpp;
1991 if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
1995 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1996 if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
1997 S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2001 const auto *FD = cast<FunctionDecl>(D);
2002 if (!FD->isExternallyVisible()) {
2003 S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2007 D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2010 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2011 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2014 if (AL.isDeclspecAttribute()) {
2015 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2016 const auto &Arch = Triple.getArch();
2017 if (Arch != llvm::Triple::x86 &&
2018 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2019 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2020 << AL << Triple.getArchName();
2025 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2028 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2029 if (hasDeclarator(D)) return;
2031 if (!isa<ObjCMethodDecl>(D)) {
2032 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2033 << Attrs << ExpectedFunctionOrMethod;
2037 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2040 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2041 if (!S.getLangOpts().CFProtectionBranch)
2042 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2044 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2047 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2048 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2056 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2057 // Check whether the attribute is valid on the current target.
2058 if (!AL.existsInTarget(Context.getTargetInfo())) {
2059 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2067 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2069 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2070 // because 'analyzer_noreturn' does not impact the type.
2071 if (!isFunctionOrMethodOrBlock(D)) {
2072 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2073 if (!VD || (!VD->getType()->isBlockPointerType() &&
2074 !VD->getType()->isFunctionPointerType())) {
2075 S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2076 ? diag::err_attribute_wrong_decl_type
2077 : diag::warn_attribute_wrong_decl_type)
2078 << AL << ExpectedFunctionMethodOrBlock;
2083 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2086 // PS3 PPU-specific.
2087 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2089 Returning a Vector Class in Registers
2091 According to the PPU ABI specifications, a class with a single member of
2092 vector type is returned in memory when used as the return value of a
2094 This results in inefficient code when implementing vector classes. To return
2095 the value in a single vector register, add the vecreturn attribute to the
2096 class definition. This attribute is also applicable to struct types.
2102 __vector float xyzw;
2103 } __attribute__((vecreturn));
2105 Vector Add(Vector lhs, Vector rhs)
2108 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2109 return result; // This will be returned in a register
2112 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2113 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2117 const auto *R = cast<RecordDecl>(D);
2120 if (!isa<CXXRecordDecl>(R)) {
2121 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2125 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2126 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2130 for (const auto *I : R->fields()) {
2131 if ((count == 1) || !I->getType()->isVectorType()) {
2132 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2138 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2141 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2142 const ParsedAttr &AL) {
2143 if (isa<ParmVarDecl>(D)) {
2144 // [[carries_dependency]] can only be applied to a parameter if it is a
2145 // parameter of a function declaration or lambda.
2146 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2148 diag::err_carries_dependency_param_not_function_decl);
2153 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2156 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2157 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2159 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2160 // about using it as an extension.
2161 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2162 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2164 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2167 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2168 uint32_t priority = ConstructorAttr::DefaultPriority;
2169 if (AL.getNumArgs() &&
2170 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2173 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2176 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2177 uint32_t priority = DestructorAttr::DefaultPriority;
2178 if (AL.getNumArgs() &&
2179 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2182 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2185 template <typename AttrTy>
2186 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2187 // Handle the case where the attribute has a text message.
2189 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2192 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2195 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2196 const ParsedAttr &AL) {
2197 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2198 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2199 << AL << AL.getRange();
2203 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2206 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2207 IdentifierInfo *Platform,
2208 VersionTuple Introduced,
2209 VersionTuple Deprecated,
2210 VersionTuple Obsoleted) {
2211 StringRef PlatformName
2212 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2213 if (PlatformName.empty())
2214 PlatformName = Platform->getName();
2216 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2217 // of these steps are needed).
2218 if (!Introduced.empty() && !Deprecated.empty() &&
2219 !(Introduced <= Deprecated)) {
2220 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2221 << 1 << PlatformName << Deprecated.getAsString()
2222 << 0 << Introduced.getAsString();
2226 if (!Introduced.empty() && !Obsoleted.empty() &&
2227 !(Introduced <= Obsoleted)) {
2228 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2229 << 2 << PlatformName << Obsoleted.getAsString()
2230 << 0 << Introduced.getAsString();
2234 if (!Deprecated.empty() && !Obsoleted.empty() &&
2235 !(Deprecated <= Obsoleted)) {
2236 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2237 << 2 << PlatformName << Obsoleted.getAsString()
2238 << 1 << Deprecated.getAsString();
2245 /// Check whether the two versions match.
2247 /// If either version tuple is empty, then they are assumed to match. If
2248 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2249 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2250 bool BeforeIsOkay) {
2251 if (X.empty() || Y.empty())
2257 if (BeforeIsOkay && X < Y)
2263 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2264 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2265 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2266 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2267 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2269 VersionTuple MergedIntroduced = Introduced;
2270 VersionTuple MergedDeprecated = Deprecated;
2271 VersionTuple MergedObsoleted = Obsoleted;
2272 bool FoundAny = false;
2273 bool OverrideOrImpl = false;
2276 case AMK_Redeclaration:
2277 OverrideOrImpl = false;
2281 case AMK_ProtocolImplementation:
2282 OverrideOrImpl = true;
2286 if (D->hasAttrs()) {
2287 AttrVec &Attrs = D->getAttrs();
2288 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2289 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2295 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2296 if (OldPlatform != Platform) {
2301 // If there is an existing availability attribute for this platform that
2302 // has a lower priority use the existing one and discard the new
2304 if (OldAA->getPriority() < Priority)
2307 // If there is an existing attribute for this platform that has a higher
2308 // priority than the new attribute then erase the old one and continue
2309 // processing the attributes.
2310 if (OldAA->getPriority() > Priority) {
2311 Attrs.erase(Attrs.begin() + i);
2317 VersionTuple OldIntroduced = OldAA->getIntroduced();
2318 VersionTuple OldDeprecated = OldAA->getDeprecated();
2319 VersionTuple OldObsoleted = OldAA->getObsoleted();
2320 bool OldIsUnavailable = OldAA->getUnavailable();
2322 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2323 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2324 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2325 !(OldIsUnavailable == IsUnavailable ||
2326 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2327 if (OverrideOrImpl) {
2329 VersionTuple FirstVersion;
2330 VersionTuple SecondVersion;
2331 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2333 FirstVersion = OldIntroduced;
2334 SecondVersion = Introduced;
2335 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2337 FirstVersion = Deprecated;
2338 SecondVersion = OldDeprecated;
2339 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2341 FirstVersion = Obsoleted;
2342 SecondVersion = OldObsoleted;
2346 Diag(OldAA->getLocation(),
2347 diag::warn_mismatched_availability_override_unavail)
2348 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2349 << (AMK == AMK_Override);
2351 Diag(OldAA->getLocation(),
2352 diag::warn_mismatched_availability_override)
2354 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2355 << FirstVersion.getAsString() << SecondVersion.getAsString()
2356 << (AMK == AMK_Override);
2358 if (AMK == AMK_Override)
2359 Diag(CI.getLoc(), diag::note_overridden_method);
2361 Diag(CI.getLoc(), diag::note_protocol_method);
2363 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2364 Diag(CI.getLoc(), diag::note_previous_attribute);
2367 Attrs.erase(Attrs.begin() + i);
2372 VersionTuple MergedIntroduced2 = MergedIntroduced;
2373 VersionTuple MergedDeprecated2 = MergedDeprecated;
2374 VersionTuple MergedObsoleted2 = MergedObsoleted;
2376 if (MergedIntroduced2.empty())
2377 MergedIntroduced2 = OldIntroduced;
2378 if (MergedDeprecated2.empty())
2379 MergedDeprecated2 = OldDeprecated;
2380 if (MergedObsoleted2.empty())
2381 MergedObsoleted2 = OldObsoleted;
2383 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2384 MergedIntroduced2, MergedDeprecated2,
2385 MergedObsoleted2)) {
2386 Attrs.erase(Attrs.begin() + i);
2391 MergedIntroduced = MergedIntroduced2;
2392 MergedDeprecated = MergedDeprecated2;
2393 MergedObsoleted = MergedObsoleted2;
2399 MergedIntroduced == Introduced &&
2400 MergedDeprecated == Deprecated &&
2401 MergedObsoleted == Obsoleted)
2404 // Only create a new attribute if !OverrideOrImpl, but we want to do
2406 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2407 MergedDeprecated, MergedObsoleted) &&
2409 auto *Avail = ::new (Context) AvailabilityAttr(
2410 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2411 Message, IsStrict, Replacement, Priority);
2412 Avail->setImplicit(Implicit);
2418 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2419 if (!checkAttributeNumArgs(S, AL, 1))
2421 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2423 IdentifierInfo *II = Platform->Ident;
2424 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2425 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2428 auto *ND = dyn_cast<NamedDecl>(D);
2429 if (!ND) // We warned about this already, so just return.
2432 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2433 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2434 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2435 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2436 bool IsStrict = AL.getStrictLoc().isValid();
2438 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2439 Str = SE->getString();
2440 StringRef Replacement;
2441 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2442 Replacement = SE->getString();
2444 if (II->isStr("swift")) {
2445 if (Introduced.isValid() || Obsoleted.isValid() ||
2446 (!IsUnavailable && !Deprecated.isValid())) {
2448 diag::warn_availability_swift_unavailable_deprecated_only);
2453 int PriorityModifier = AL.isPragmaClangAttribute()
2454 ? Sema::AP_PragmaClangAttribute
2455 : Sema::AP_Explicit;
2456 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2457 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2458 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2459 Sema::AMK_None, PriorityModifier);
2461 D->addAttr(NewAttr);
2463 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2464 // matches before the start of the watchOS platform.
2465 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2466 IdentifierInfo *NewII = nullptr;
2467 if (II->getName() == "ios")
2468 NewII = &S.Context.Idents.get("watchos");
2469 else if (II->getName() == "ios_app_extension")
2470 NewII = &S.Context.Idents.get("watchos_app_extension");
2473 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2474 if (Version.empty())
2476 auto Major = Version.getMajor();
2477 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2478 if (NewMajor >= 2) {
2479 if (Version.getMinor().hasValue()) {
2480 if (Version.getSubminor().hasValue())
2481 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2482 Version.getSubminor().getValue());
2484 return VersionTuple(NewMajor, Version.getMinor().getValue());
2486 return VersionTuple(NewMajor);
2489 return VersionTuple(2, 0);
2492 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2493 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2494 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2496 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2497 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2498 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2500 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2502 D->addAttr(NewAttr);
2504 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2505 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2506 // matches before the start of the tvOS platform.
2507 IdentifierInfo *NewII = nullptr;
2508 if (II->getName() == "ios")
2509 NewII = &S.Context.Idents.get("tvos");
2510 else if (II->getName() == "ios_app_extension")
2511 NewII = &S.Context.Idents.get("tvos_app_extension");
2514 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2515 ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2516 Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2517 Replacement, Sema::AMK_None,
2518 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2520 D->addAttr(NewAttr);
2525 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2526 const ParsedAttr &AL) {
2527 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2529 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2530 "Invalid number of arguments in an external_source_symbol attribute");
2533 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2534 Language = SE->getString();
2535 StringRef DefinedIn;
2536 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2537 DefinedIn = SE->getString();
2538 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2540 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2541 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2545 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2546 typename T::VisibilityType value) {
2547 T *existingAttr = D->getAttr<T>();
2549 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2550 if (existingValue == value)
2552 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2553 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2556 return ::new (S.Context) T(S.Context, CI, value);
2559 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2560 const AttributeCommonInfo &CI,
2561 VisibilityAttr::VisibilityType Vis) {
2562 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2565 TypeVisibilityAttr *
2566 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2567 TypeVisibilityAttr::VisibilityType Vis) {
2568 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2571 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2572 bool isTypeVisibility) {
2573 // Visibility attributes don't mean anything on a typedef.
2574 if (isa<TypedefNameDecl>(D)) {
2575 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2579 // 'type_visibility' can only go on a type or namespace.
2580 if (isTypeVisibility &&
2581 !(isa<TagDecl>(D) ||
2582 isa<ObjCInterfaceDecl>(D) ||
2583 isa<NamespaceDecl>(D))) {
2584 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2585 << AL << ExpectedTypeOrNamespace;
2589 // Check that the argument is a string literal.
2591 SourceLocation LiteralLoc;
2592 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2595 VisibilityAttr::VisibilityType type;
2596 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2597 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2602 // Complain about attempts to use protected visibility on targets
2603 // (like Darwin) that don't support it.
2604 if (type == VisibilityAttr::Protected &&
2605 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2606 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2607 type = VisibilityAttr::Default;
2611 if (isTypeVisibility) {
2612 newAttr = S.mergeTypeVisibilityAttr(
2613 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2615 newAttr = S.mergeVisibilityAttr(D, AL, type);
2618 D->addAttr(newAttr);
2621 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2622 // objc_direct cannot be set on methods declared in the context of a protocol
2623 if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2624 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2628 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2629 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2631 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2635 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2636 const ParsedAttr &AL) {
2637 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2638 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2640 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2644 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2645 const auto *M = cast<ObjCMethodDecl>(D);
2646 if (!AL.isArgIdent(0)) {
2647 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2648 << AL << 1 << AANT_ArgumentIdentifier;
2652 IdentifierLoc *IL = AL.getArgAsIdent(0);
2653 ObjCMethodFamilyAttr::FamilyKind F;
2654 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2655 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2659 if (F == ObjCMethodFamilyAttr::OMF_init &&
2660 !M->getReturnType()->isObjCObjectPointerType()) {
2661 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2662 << M->getReturnType();
2663 // Ignore the attribute.
2667 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2670 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2671 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2672 QualType T = TD->getUnderlyingType();
2673 if (!T->isCARCBridgableType()) {
2674 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2678 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2679 QualType T = PD->getType();
2680 if (!T->isCARCBridgableType()) {
2681 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2686 // It is okay to include this attribute on properties, e.g.:
2688 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2690 // In this case it follows tradition and suppresses an error in the above
2692 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2694 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2697 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2698 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2699 QualType T = TD->getUnderlyingType();
2700 if (!T->isObjCObjectPointerType()) {
2701 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2705 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2708 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2711 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2712 if (!AL.isArgIdent(0)) {
2713 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2714 << AL << 1 << AANT_ArgumentIdentifier;
2718 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2719 BlocksAttr::BlockType type;
2720 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2721 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2725 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2728 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2729 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2730 if (AL.getNumArgs() > 0) {
2731 Expr *E = AL.getArgAsExpr(0);
2732 llvm::APSInt Idx(32);
2733 if (E->isTypeDependent() || E->isValueDependent() ||
2734 !E->isIntegerConstantExpr(Idx, S.Context)) {
2735 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2736 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2740 if (Idx.isSigned() && Idx.isNegative()) {
2741 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2742 << E->getSourceRange();
2746 sentinel = Idx.getZExtValue();
2749 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2750 if (AL.getNumArgs() > 1) {
2751 Expr *E = AL.getArgAsExpr(1);
2752 llvm::APSInt Idx(32);
2753 if (E->isTypeDependent() || E->isValueDependent() ||
2754 !E->isIntegerConstantExpr(Idx, S.Context)) {
2755 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2756 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2759 nullPos = Idx.getZExtValue();
2761 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2762 // FIXME: This error message could be improved, it would be nice
2763 // to say what the bounds actually are.
2764 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2765 << E->getSourceRange();
2770 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2771 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2772 if (isa<FunctionNoProtoType>(FT)) {
2773 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2777 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2778 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2781 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2782 if (!MD->isVariadic()) {
2783 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2786 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2787 if (!BD->isVariadic()) {
2788 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2791 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2792 QualType Ty = V->getType();
2793 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2794 const FunctionType *FT = Ty->isFunctionPointerType()
2795 ? D->getFunctionType()
2796 : Ty->castAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2797 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2798 int m = Ty->isFunctionPointerType() ? 0 : 1;
2799 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2803 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2804 << AL << ExpectedFunctionMethodOrBlock;
2808 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2809 << AL << ExpectedFunctionMethodOrBlock;
2812 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2815 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2816 if (D->getFunctionType() &&
2817 D->getFunctionType()->getReturnType()->isVoidType() &&
2818 !isa<CXXConstructorDecl>(D)) {
2819 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2822 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2823 if (MD->getReturnType()->isVoidType()) {
2824 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2829 if ((AL.isCXX11Attribute() || AL.isC2xAttribute()) && !AL.getScopeName()) {
2830 // The standard attribute cannot be applied to variable declarations such
2831 // as a function pointer.
2832 if (isa<VarDecl>(D))
2833 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2834 << AL << "functions, classes, or enumerations";
2836 // If this is spelled as the standard C++17 attribute, but not in C++17,
2837 // warn about using it as an extension. If there are attribute arguments,
2838 // then claim it's a C++2a extension instead.
2839 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2840 // extension warning for C2x mode.
2841 const LangOptions &LO = S.getLangOpts();
2842 if (AL.getNumArgs() == 1) {
2843 if (LO.CPlusPlus && !LO.CPlusPlus20)
2844 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2846 // Since this this is spelled [[nodiscard]], get the optional string
2847 // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2849 // FIXME: C2x should support this feature as well, even as an extension.
2850 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2852 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2853 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2856 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2859 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2860 // weak_import only applies to variable & function declarations.
2862 if (!D->canBeWeakImported(isDef)) {
2864 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2866 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2867 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2868 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2869 // Nothing to warn about here.
2871 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2872 << AL << ExpectedVariableOrFunction;
2877 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2880 // Handles reqd_work_group_size and work_group_size_hint.
2881 template <typename WorkGroupAttr>
2882 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2884 for (unsigned i = 0; i < 3; ++i) {
2885 const Expr *E = AL.getArgAsExpr(i);
2886 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2887 /*StrictlyUnsigned=*/true))
2889 if (WGSize[i] == 0) {
2890 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2891 << AL << E->getSourceRange();
2896 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2897 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2898 Existing->getYDim() == WGSize[1] &&
2899 Existing->getZDim() == WGSize[2]))
2900 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2902 D->addAttr(::new (S.Context)
2903 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2906 // Handles intel_reqd_sub_group_size.
2907 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2909 const Expr *E = AL.getArgAsExpr(0);
2910 if (!checkUInt32Argument(S, AL, E, SGSize))
2913 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2914 << AL << E->getSourceRange();
2918 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2919 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2920 if (Existing && Existing->getSubGroupSize() != SGSize)
2921 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2923 D->addAttr(::new (S.Context)
2924 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
2927 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2928 if (!AL.hasParsedType()) {
2929 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2933 TypeSourceInfo *ParmTSI = nullptr;
2934 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2935 assert(ParmTSI && "no type source info for attribute argument");
2937 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2938 (ParmType->isBooleanType() ||
2939 !ParmType->isIntegralType(S.getASTContext()))) {
2940 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
2944 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2945 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2946 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2951 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
2954 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2956 // Explicit or partial specializations do not inherit
2957 // the section attribute from the primary template.
2958 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2959 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
2960 FD->isFunctionTemplateSpecialization())
2963 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2964 if (ExistingAttr->getName() == Name)
2966 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2968 Diag(CI.getLoc(), diag::note_previous_attribute);
2971 return ::new (Context) SectionAttr(Context, CI, Name);
2974 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2975 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2976 if (!Error.empty()) {
2977 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2984 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2985 // Make sure that there is a string literal as the sections's single
2988 SourceLocation LiteralLoc;
2989 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2992 if (!S.checkSectionName(LiteralLoc, Str))
2995 // If the target wants to validate the section specifier, make it happen.
2996 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2997 if (!Error.empty()) {
2998 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3003 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3005 D->addAttr(NewAttr);
3008 // This is used for `__declspec(code_seg("segname"))` on a decl.
3009 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3010 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3011 StringRef CodeSegName) {
3013 S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3014 if (!Error.empty()) {
3015 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3016 << Error << 0 /*'code-seg'*/;
3023 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3025 // Explicit or partial specializations do not inherit
3026 // the code_seg attribute from the primary template.
3027 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3028 if (FD->isFunctionTemplateSpecialization())
3031 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3032 if (ExistingAttr->getName() == Name)
3034 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3036 Diag(CI.getLoc(), diag::note_previous_attribute);
3039 return ::new (Context) CodeSegAttr(Context, CI, Name);
3042 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3044 SourceLocation LiteralLoc;
3045 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3047 if (!checkCodeSegName(S, LiteralLoc, Str))
3049 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3050 if (!ExistingAttr->isImplicit()) {
3052 ExistingAttr->getName() == Str
3053 ? diag::warn_duplicate_codeseg_attribute
3054 : diag::err_conflicting_codeseg_attribute);
3057 D->dropAttr<CodeSegAttr>();
3059 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3063 // Check for things we'd like to warn about. Multiversioning issues are
3064 // handled later in the process, once we know how many exist.
3065 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3066 enum FirstParam { Unsupported, Duplicate };
3067 enum SecondParam { None, Architecture };
3068 for (auto Str : {"tune=", "fpmath="})
3069 if (AttrStr.find(Str) != StringRef::npos)
3070 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3071 << Unsupported << None << Str;
3073 ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3075 if (!ParsedAttrs.Architecture.empty() &&
3076 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3077 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3078 << Unsupported << Architecture << ParsedAttrs.Architecture;
3080 if (ParsedAttrs.DuplicateArchitecture)
3081 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3082 << Duplicate << None << "arch=";
3084 for (const auto &Feature : ParsedAttrs.Features) {
3085 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3086 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3087 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3088 << Unsupported << None << CurFeature;
3091 TargetInfo::BranchProtectionInfo BPI;
3093 if (!ParsedAttrs.BranchProtection.empty() &&
3094 !Context.getTargetInfo().validateBranchProtection(
3095 ParsedAttrs.BranchProtection, BPI, Error)) {
3097 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3098 << Unsupported << None << "branch-protection";
3100 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3107 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3109 SourceLocation LiteralLoc;
3110 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3111 S.checkTargetAttr(LiteralLoc, Str))
3114 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3115 D->addAttr(NewAttr);
3118 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3119 Expr *E = AL.getArgAsExpr(0);
3121 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3126 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3127 if (Existing && Existing->getVectorWidth() != VecWidth) {
3128 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3132 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3135 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3136 Expr *E = AL.getArgAsExpr(0);
3137 SourceLocation Loc = E->getExprLoc();
3138 FunctionDecl *FD = nullptr;
3139 DeclarationNameInfo NI;
3141 // gcc only allows for simple identifiers. Since we support more than gcc, we
3142 // will warn the user.
3143 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3144 if (DRE->hasQualifier())
3145 S.Diag(Loc, diag::warn_cleanup_ext);
3146 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3147 NI = DRE->getNameInfo();
3149 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3153 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3154 if (ULE->hasExplicitTemplateArgs())
3155 S.Diag(Loc, diag::warn_cleanup_ext);
3156 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3157 NI = ULE->getNameInfo();
3159 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3161 if (ULE->getType() == S.Context.OverloadTy)
3162 S.NoteAllOverloadCandidates(ULE);
3166 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3170 if (FD->getNumParams() != 1) {
3171 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3176 // We're currently more strict than GCC about what function types we accept.
3177 // If this ever proves to be a problem it should be easy to fix.
3178 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3179 QualType ParamTy = FD->getParamDecl(0)->getType();
3180 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3181 ParamTy, Ty) != Sema::Compatible) {
3182 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3183 << NI.getName() << ParamTy << Ty;
3187 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3190 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3191 const ParsedAttr &AL) {
3192 if (!AL.isArgIdent(0)) {
3193 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3194 << AL << 0 << AANT_ArgumentIdentifier;
3198 EnumExtensibilityAttr::Kind ExtensibilityKind;
3199 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3200 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3201 ExtensibilityKind)) {
3202 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3206 D->addAttr(::new (S.Context)
3207 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3210 /// Handle __attribute__((format_arg((idx)))) attribute based on
3211 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3212 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3213 Expr *IdxExpr = AL.getArgAsExpr(0);
3215 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3218 // Make sure the format string is really a string.
3219 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3221 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3222 if (NotNSStringTy &&
3223 !isCFStringType(Ty, S.Context) &&
3224 (!Ty->isPointerType() ||
3225 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3226 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3227 << "a string type" << IdxExpr->getSourceRange()
3228 << getFunctionOrMethodParamRange(D, 0);
3231 Ty = getFunctionOrMethodResultType(D);
3232 if (!isNSStringType(Ty, S.Context) &&
3233 !isCFStringType(Ty, S.Context) &&
3234 (!Ty->isPointerType() ||
3235 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3236 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3237 << (NotNSStringTy ? "string type" : "NSString")
3238 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3242 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3245 enum FormatAttrKind {
3254 /// getFormatAttrKind - Map from format attribute names to supported format
3256 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3257 return llvm::StringSwitch<FormatAttrKind>(Format)
3258 // Check for formats that get handled specially.
3259 .Case("NSString", NSStringFormat)
3260 .Case("CFString", CFStringFormat)
3261 .Case("strftime", StrftimeFormat)
3263 // Otherwise, check for supported formats.
3264 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3265 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3266 .Case("kprintf", SupportedFormat) // OpenBSD.
3267 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3268 .Case("os_trace", SupportedFormat)
3269 .Case("os_log", SupportedFormat)
3271 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3272 .Default(InvalidFormat);
3275 /// Handle __attribute__((init_priority(priority))) attributes based on
3276 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3277 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3278 if (!S.getLangOpts().CPlusPlus) {
3279 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3283 if (S.getCurFunctionOrMethodDecl()) {
3284 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3288 QualType T = cast<VarDecl>(D)->getType();
3289 if (S.Context.getAsArrayType(T))
3290 T = S.Context.getBaseElementType(T);
3291 if (!T->getAs<RecordType>()) {
3292 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3297 Expr *E = AL.getArgAsExpr(0);
3298 uint32_t prioritynum;
3299 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3304 // Only perform the priority check if the attribute is outside of a system
3305 // header. Values <= 100 are reserved for the implementation, and libc++
3306 // benefits from being able to specify values in that range.
3307 if ((prioritynum < 101 || prioritynum > 65535) &&
3308 !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3309 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3310 << E->getSourceRange() << AL << 101 << 65535;
3314 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3317 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3318 IdentifierInfo *Format, int FormatIdx,
3320 // Check whether we already have an equivalent format attribute.
3321 for (auto *F : D->specific_attrs<FormatAttr>()) {
3322 if (F->getType() == Format &&
3323 F->getFormatIdx() == FormatIdx &&
3324 F->getFirstArg() == FirstArg) {
3325 // If we don't have a valid location for this attribute, adopt the
3327 if (F->getLocation().isInvalid())
3328 F->setRange(CI.getRange());
3333 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3336 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3337 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3338 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3339 if (!AL.isArgIdent(0)) {
3340 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3341 << AL << 1 << AANT_ArgumentIdentifier;
3345 // In C++ the implicit 'this' function parameter also counts, and they are
3346 // counted from one.
3347 bool HasImplicitThisParam = isInstanceMethod(D);
3348 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3350 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3351 StringRef Format = II->getName();
3353 if (normalizeName(Format)) {
3354 // If we've modified the string name, we need a new identifier for it.
3355 II = &S.Context.Idents.get(Format);
3358 // Check for supported formats.
3359 FormatAttrKind Kind = getFormatAttrKind(Format);
3361 if (Kind == IgnoredFormat)
3364 if (Kind == InvalidFormat) {
3365 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3366 << AL << II->getName();
3370 // checks for the 2nd argument
3371 Expr *IdxExpr = AL.getArgAsExpr(1);
3373 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3376 if (Idx < 1 || Idx > NumArgs) {
3377 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3378 << AL << 2 << IdxExpr->getSourceRange();
3382 // FIXME: Do we need to bounds check?
3383 unsigned ArgIdx = Idx - 1;
3385 if (HasImplicitThisParam) {
3388 diag::err_format_attribute_implicit_this_format_string)
3389 << IdxExpr->getSourceRange();
3395 // make sure the format string is really a string
3396 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3398 if (Kind == CFStringFormat) {
3399 if (!isCFStringType(Ty, S.Context)) {
3400 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3401 << "a CFString" << IdxExpr->getSourceRange()
3402 << getFunctionOrMethodParamRange(D, ArgIdx);
3405 } else if (Kind == NSStringFormat) {
3406 // FIXME: do we need to check if the type is NSString*? What are the
3408 if (!isNSStringType(Ty, S.Context)) {
3409 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3410 << "an NSString" << IdxExpr->getSourceRange()
3411 << getFunctionOrMethodParamRange(D, ArgIdx);
3414 } else if (!Ty->isPointerType() ||
3415 !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3416 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3417 << "a string type" << IdxExpr->getSourceRange()
3418 << getFunctionOrMethodParamRange(D, ArgIdx);
3422 // check the 3rd argument
3423 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3425 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3428 // check if the function is variadic if the 3rd argument non-zero
3429 if (FirstArg != 0) {
3430 if (isFunctionOrMethodVariadic(D)) {
3431 ++NumArgs; // +1 for ...
3433 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3438 // strftime requires FirstArg to be 0 because it doesn't read from any
3439 // variable the input is just the current time + the format string.
3440 if (Kind == StrftimeFormat) {
3441 if (FirstArg != 0) {
3442 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3443 << FirstArgExpr->getSourceRange();
3446 // if 0 it disables parameter checking (to use with e.g. va_list)
3447 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3448 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3449 << AL << 3 << FirstArgExpr->getSourceRange();
3453 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3455 D->addAttr(NewAttr);
3458 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3459 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3460 // The index that identifies the callback callee is mandatory.
3461 if (AL.getNumArgs() == 0) {
3462 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3467 bool HasImplicitThisParam = isInstanceMethod(D);
3468 int32_t NumArgs = getFunctionOrMethodNumParams(D);
3470 FunctionDecl *FD = D->getAsFunction();
3471 assert(FD && "Expected a function declaration!");
3473 llvm::StringMap<int> NameIdxMapping;
3474 NameIdxMapping["__"] = -1;
3476 NameIdxMapping["this"] = 0;
3479 for (const ParmVarDecl *PVD : FD->parameters())
3480 NameIdxMapping[PVD->getName()] = Idx++;
3482 auto UnknownName = NameIdxMapping.end();
3484 SmallVector<int, 8> EncodingIndices;
3485 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3489 if (AL.isArgIdent(I)) {
3490 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3491 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3492 if (It == UnknownName) {
3493 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3494 << IdLoc->Ident << IdLoc->Loc;
3498 SR = SourceRange(IdLoc->Loc);
3499 ArgIdx = It->second;
3500 } else if (AL.isArgExpr(I)) {
3501 Expr *IdxExpr = AL.getArgAsExpr(I);
3503 // If the expression is not parseable as an int32_t we have a problem.
3504 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3506 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3507 << AL << (I + 1) << IdxExpr->getSourceRange();
3511 // Check oob, excluding the special values, 0 and -1.
3512 if (ArgIdx < -1 || ArgIdx > NumArgs) {
3513 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3514 << AL << (I + 1) << IdxExpr->getSourceRange();
3518 SR = IdxExpr->getSourceRange();
3520 llvm_unreachable("Unexpected ParsedAttr argument type!");
3523 if (ArgIdx == 0 && !HasImplicitThisParam) {
3524 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3529 // Adjust for the case we do not have an implicit "this" parameter. In this
3530 // case we decrease all positive values by 1 to get LLVM argument indices.
3531 if (!HasImplicitThisParam && ArgIdx > 0)
3534 EncodingIndices.push_back(ArgIdx);
3537 int CalleeIdx = EncodingIndices.front();
3538 // Check if the callee index is proper, thus not "this" and not "unknown".
3539 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3540 // is false and positive if "HasImplicitThisParam" is true.
3541 if (CalleeIdx < (int)HasImplicitThisParam) {
3542 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3547 // Get the callee type, note the index adjustment as the AST doesn't contain
3548 // the this type (which the callee cannot reference anyway!).
3549 const Type *CalleeType =
3550 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3552 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3553 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3558 const Type *CalleeFnType =
3559 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3561 // TODO: Check the type of the callee arguments.
3563 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3564 if (!CalleeFnProtoType) {
3565 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3570 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3571 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3572 << AL << (unsigned)(EncodingIndices.size() - 1);
3576 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3577 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3578 << AL << (unsigned)(EncodingIndices.size() - 1);
3582 if (CalleeFnProtoType->isVariadic()) {
3583 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3587 // Do not allow multiple callback attributes.
3588 if (D->hasAttr<CallbackAttr>()) {
3589 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3593 D->addAttr(::new (S.Context) CallbackAttr(
3594 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3597 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3598 // Try to find the underlying union declaration.
3599 RecordDecl *RD = nullptr;
3600 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3601 if (TD && TD->getUnderlyingType()->isUnionType())
3602 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3604 RD = dyn_cast<RecordDecl>(D);
3606 if (!RD || !RD->isUnion()) {
3607 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3612 if (!RD->isCompleteDefinition()) {
3613 if (!RD->isBeingDefined())
3615 diag::warn_transparent_union_attribute_not_definition);
3619 RecordDecl::field_iterator Field = RD->field_begin(),
3620 FieldEnd = RD->field_end();
3621 if (Field == FieldEnd) {
3622 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3626 FieldDecl *FirstField = *Field;
3627 QualType FirstType = FirstField->getType();
3628 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3629 S.Diag(FirstField->getLocation(),
3630 diag::warn_transparent_union_attribute_floating)
3631 << FirstType->isVectorType() << FirstType;
3635 if (FirstType->isIncompleteType())
3637 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3638 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3639 for (; Field != FieldEnd; ++Field) {
3640 QualType FieldType = Field->getType();
3641 if (FieldType->isIncompleteType())
3643 // FIXME: this isn't fully correct; we also need to test whether the
3644 // members of the union would all have the same calling convention as the
3645 // first member of the union. Checking just the size and alignment isn't
3646 // sufficient (consider structs passed on the stack instead of in registers
3648 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3649 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3650 // Warn if we drop the attribute.
3651 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3652 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3653 : S.Context.getTypeAlign(FieldType);
3654 S.Diag(Field->getLocation(),
3655 diag::warn_transparent_union_attribute_field_size_align)
3656 << isSize << Field->getDeclName() << FieldBits;
3657 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3658 S.Diag(FirstField->getLocation(),
3659 diag::note_transparent_union_first_field_size_align)
3660 << isSize << FirstBits;
3665 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3668 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3669 // Make sure that there is a string literal as the annotation's single
3672 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3675 // Don't duplicate annotations that are already set.
3676 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3677 if (I->getAnnotation() == Str)
3681 D->addAttr(::new (S.Context) AnnotateAttr(S.Context, AL, Str));
3684 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3685 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3688 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3689 AlignValueAttr TmpAttr(Context, CI, E);
3690 SourceLocation AttrLoc = CI.getLoc();
3693 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3694 T = TD->getUnderlyingType();
3695 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3698 llvm_unreachable("Unknown decl type for align_value");
3700 if (!T->isDependentType() && !T->isAnyPointerType() &&
3701 !T->isReferenceType() && !T->isMemberPointerType()) {
3702 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3703 << &TmpAttr << T << D->getSourceRange();
3707 if (!E->isValueDependent()) {
3708 llvm::APSInt Alignment;
3710 = VerifyIntegerConstantExpression(E, &Alignment,
3711 diag::err_align_value_attribute_argument_not_int,
3712 /*AllowFold*/ false);
3713 if (ICE.isInvalid())
3716 if (!Alignment.isPowerOf2()) {
3717 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3718 << E->getSourceRange();
3722 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3726 // Save dependent expressions in the AST to be instantiated.
3727 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3730 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3731 // check the attribute arguments.
3732 if (AL.getNumArgs() > 1) {
3733 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3737 if (AL.getNumArgs() == 0) {
3738 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3742 Expr *E = AL.getArgAsExpr(0);
3743 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3744 S.Diag(AL.getEllipsisLoc(),
3745 diag::err_pack_expansion_without_parameter_packs);
3749 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3752 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3755 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3756 bool IsPackExpansion) {
3757 AlignedAttr TmpAttr(Context, CI, true, E);
3758 SourceLocation AttrLoc = CI.getLoc();
3760 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3761 if (TmpAttr.isAlignas()) {
3762 // C++11 [dcl.align]p1:
3763 // An alignment-specifier may be applied to a variable or to a class
3764 // data member, but it shall not be applied to a bit-field, a function
3765 // parameter, the formal parameter of a catch clause, or a variable
3766 // declared with the register storage class specifier. An
3767 // alignment-specifier may also be applied to the declaration of a class
3768 // or enumeration type.
3770 // An alignment attribute shall not be specified in a declaration of
3771 // a typedef, or a bit-field, or a function, or a parameter, or an
3772 // object declared with the register storage-class specifier.
3774 if (isa<ParmVarDecl>(D)) {
3776 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3777 if (VD->getStorageClass() == SC_Register)
3779 if (VD->isExceptionVariable())
3781 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3782 if (FD->isBitField())
3784 } else if (!isa<TagDecl>(D)) {
3785 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3786 << (TmpAttr.isC11() ? ExpectedVariableOrField
3787 : ExpectedVariableFieldOrTag);
3790 if (DiagKind != -1) {
3791 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3792 << &TmpAttr << DiagKind;
3797 if (E->isValueDependent()) {
3798 // We can't support a dependent alignment on a non-dependent type,
3799 // because we have no way to model that a type is "alignment-dependent"
3800 // but not dependent in any other way.
3801 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3802 if (!TND->getUnderlyingType()->isDependentType()) {
3803 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3804 << E->getSourceRange();
3809 // Save dependent expressions in the AST to be instantiated.
3810 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
3811 AA->setPackExpansion(IsPackExpansion);
3816 // FIXME: Cache the number on the AL object?
3817 llvm::APSInt Alignment;
3819 = VerifyIntegerConstantExpression(E, &Alignment,
3820 diag::err_aligned_attribute_argument_not_int,
3821 /*AllowFold*/ false);
3822 if (ICE.isInvalid())
3825 uint64_t AlignVal = Alignment.getZExtValue();
3827 // C++11 [dcl.align]p2:
3828 // -- if the constant expression evaluates to zero, the alignment
3829 // specifier shall have no effect
3831 // An alignment specification of zero has no effect.
3832 if (!(TmpAttr.isAlignas() && !Alignment)) {
3833 if (!llvm::isPowerOf2_64(AlignVal)) {
3834 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3835 << E->getSourceRange();
3840 unsigned MaximumAlignment = Sema::MaximumAlignment;
3841 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
3842 MaximumAlignment = std::min(MaximumAlignment, 8192u);
3843 if (AlignVal > MaximumAlignment) {
3844 Diag(AttrLoc, diag::err_attribute_aligned_too_great)
3845 << MaximumAlignment << E->getSourceRange();
3849 if (Context.getTargetInfo().isTLSSupported()) {
3850 unsigned MaxTLSAlign =
3851 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3853 const auto *VD = dyn_cast<VarDecl>(D);
3854 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3855 VD->getTLSKind() != VarDecl::TLS_None) {
3856 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3857 << (unsigned)AlignVal << VD << MaxTLSAlign;
3862 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
3863 AA->setPackExpansion(IsPackExpansion);
3867 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
3868 TypeSourceInfo *TS, bool IsPackExpansion) {
3869 // FIXME: Cache the number on the AL object if non-dependent?
3870 // FIXME: Perform checking of type validity
3871 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
3872 AA->setPackExpansion(IsPackExpansion);
3876 void Sema::CheckAlignasUnderalignment(Decl *D) {
3877 assert(D->hasAttrs() && "no attributes on decl");
3879 QualType UnderlyingTy, DiagTy;
3880 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3881 UnderlyingTy = DiagTy = VD->getType();
3883 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3884 if (const auto *ED = dyn_cast<EnumDecl>(D))
3885 UnderlyingTy = ED->getIntegerType();
3887 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3890 // C++11 [dcl.align]p5, C11 6.7.5/4:
3891 // The combined effect of all alignment attributes in a declaration shall
3892 // not specify an alignment that is less strict than the alignment that
3893 // would otherwise be required for the entity being declared.
3894 AlignedAttr *AlignasAttr = nullptr;
3895 AlignedAttr *LastAlignedAttr = nullptr;
3897 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3898 if (I->isAlignmentDependent())
3902 Align = std::max(Align, I->getAlignment(Context));
3903 LastAlignedAttr = I;
3906 if (Align && DiagTy->isSizelessType()) {
3907 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
3908 << LastAlignedAttr << DiagTy;
3909 } else if (AlignasAttr && Align) {
3910 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3911 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3912 if (NaturalAlign > RequestedAlign)
3913 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3914 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3918 bool Sema::checkMSInheritanceAttrOnDefinition(
3919 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3920 MSInheritanceModel ExplicitModel) {
3921 assert(RD->hasDefinition() && "RD has no definition!");
3923 // We may not have seen base specifiers or any virtual methods yet. We will
3924 // have to wait until the record is defined to catch any mismatches.
3925 if (!RD->getDefinition()->isCompleteDefinition())
3928 // The unspecified model never matches what a definition could need.
3929 if (ExplicitModel == MSInheritanceModel::Unspecified)
3933 if (RD->calculateInheritanceModel() == ExplicitModel)
3936 if (RD->calculateInheritanceModel() <= ExplicitModel)
3940 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3941 << 0 /*definition*/;
3942 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
3946 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3948 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3949 bool &IntegerMode, bool &ComplexMode,
3950 bool &ExplicitIEEE) {
3952 ComplexMode = false;
3953 switch (Str.size()) {
3971 case 'K': // KFmode - IEEE quad precision (__float128)
3972 ExplicitIEEE = true;
3973 DestWidth = Str[1] == 'I' ? 0 : 128;
3976 ExplicitIEEE = false;
3980 if (Str[1] == 'F') {
3981 IntegerMode = false;
3982 } else if (Str[1] == 'C') {
3983 IntegerMode = false;
3985 } else if (Str[1] != 'I') {
3990 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3991 // pointer on PIC16 and other embedded platforms.
3993 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3994 else if (Str == "byte")
3995 DestWidth = S.Context.getTargetInfo().getCharWidth();
3998 if (Str == "pointer")
3999 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4002 if (Str == "unwind_word")
4003 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4008 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4011 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4012 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4013 /// HImode, not an intermediate pointer.
4014 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4015 // This attribute isn't documented, but glibc uses it. It changes
4016 // the width of an int or unsigned int to the specified size.
4017 if (!AL.isArgIdent(0)) {
4018 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4019 << AL << AANT_ArgumentIdentifier;
4023 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4025 S.AddModeAttr(D, AL, Name);
4028 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4029 IdentifierInfo *Name, bool InInstantiation) {
4030 StringRef Str = Name->getName();
4032 SourceLocation AttrLoc = CI.getLoc();
4034 unsigned DestWidth = 0;
4035 bool IntegerMode = true;
4036 bool ComplexMode = false;
4037 bool ExplicitIEEE = false;
4038 llvm::APInt VectorSize(64, 0);
4039 if (Str.size() >= 4 && Str[0] == 'V') {
4040 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4041 size_t StrSize = Str.size();
4042 size_t VectorStringLength = 0;
4043 while ((VectorStringLength + 1) < StrSize &&
4044 isdigit(Str[VectorStringLength + 1]))
4045 ++VectorStringLength;
4046 if (VectorStringLength &&
4047 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4048 VectorSize.isPowerOf2()) {
4049 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4050 IntegerMode, ComplexMode, ExplicitIEEE);
4051 // Avoid duplicate warning from template instantiation.
4052 if (!InInstantiation)
4053 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4060 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4063 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4064 // and friends, at least with glibc.
4065 // FIXME: Make sure floating-point mappings are accurate
4066 // FIXME: Support XF and TF types
4068 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4073 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4074 OldTy = TD->getUnderlyingType();
4075 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4076 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4077 // Try to get type from enum declaration, default to int.
4078 OldTy = ED->getIntegerType();
4080 OldTy = Context.IntTy;
4082 OldTy = cast<ValueDecl>(D)->getType();
4084 if (OldTy->isDependentType()) {
4085 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4089 // Base type can also be a vector type (see PR17453).
4090 // Distinguish between base type and base element type.
4091 QualType OldElemTy = OldTy;
4092 if (const auto *VT = OldTy->getAs<VectorType>())
4093 OldElemTy = VT->getElementType();
4095 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4096 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4097 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4098 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4099 VectorSize.getBoolValue()) {
4100 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4103 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4104 !OldElemTy->isExtIntType()) ||
4105 OldElemTy->getAs<EnumType>();
4107 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4108 !IntegralOrAnyEnumType)
4109 Diag(AttrLoc, diag::err_mode_not_primitive);
4110 else if (IntegerMode) {
4111 if (!IntegralOrAnyEnumType)
4112 Diag(AttrLoc, diag::err_mode_wrong_type);
4113 } else if (ComplexMode) {
4114 if (!OldElemTy->isComplexType())
4115 Diag(AttrLoc, diag::err_mode_wrong_type);
4117 if (!OldElemTy->isFloatingType())
4118 Diag(AttrLoc, diag::err_mode_wrong_type);
4124 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4125 OldElemTy->isSignedIntegerType());
4127 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE);
4129 if (NewElemTy.isNull()) {
4130 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4135 NewElemTy = Context.getComplexType(NewElemTy);
4138 QualType NewTy = NewElemTy;
4139 if (VectorSize.getBoolValue()) {
4140 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4141 VectorType::GenericVector);
4142 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4143 // Complex machine mode does not support base vector types.
4145 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4148 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4149 OldVT->getNumElements() /
4150 Context.getTypeSize(NewElemTy);
4152 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4155 if (NewTy.isNull()) {
4156 Diag(AttrLoc, diag::err_mode_wrong_type);
4160 // Install the new type.
4161 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4162 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4163 else if (auto *ED = dyn_cast<EnumDecl>(D))
4164 ED->setIntegerType(NewTy);
4166 cast<ValueDecl>(D)->setType(NewTy);
4168 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4171 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4172 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4175 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4176 const AttributeCommonInfo &CI,
4177 const IdentifierInfo *Ident) {
4178 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4179 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4180 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4184 if (D->hasAttr<AlwaysInlineAttr>())
4187 return ::new (Context) AlwaysInlineAttr(Context, CI);
4190 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4191 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4194 return ::new (Context) CommonAttr(Context, AL);
4197 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4198 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4201 return ::new (Context) CommonAttr(Context, AL);
4204 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4205 const ParsedAttr &AL) {
4206 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4207 // Attribute applies to Var but not any subclass of it (like ParmVar,
4208 // ImplicitParm or VarTemplateSpecialization).
4209 if (VD->getKind() != Decl::Var) {
4210 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4211 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4212 : ExpectedVariableOrFunction);
4215 // Attribute does not apply to non-static local variables.
4216 if (VD->hasLocalStorage()) {
4217 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4222 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4225 return ::new (Context) InternalLinkageAttr(Context, AL);
4227 InternalLinkageAttr *
4228 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4229 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4230 // Attribute applies to Var but not any subclass of it (like ParmVar,
4231 // ImplicitParm or VarTemplateSpecialization).
4232 if (VD->getKind() != Decl::Var) {
4233 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4234 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4235 : ExpectedVariableOrFunction);
4238 // Attribute does not apply to non-static local variables.
4239 if (VD->hasLocalStorage()) {
4240 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4245 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4248 return ::new (Context) InternalLinkageAttr(Context, AL);
4251 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4252 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4253 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4254 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4258 if (D->hasAttr<MinSizeAttr>())
4261 return ::new (Context) MinSizeAttr(Context, CI);
4264 NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4265 Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4266 if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4269 return ::new (Context) NoSpeculativeLoadHardeningAttr(Context, AL);
4272 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4273 const AttributeCommonInfo &CI) {
4274 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4275 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4276 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4277 D->dropAttr<AlwaysInlineAttr>();
4279 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4280 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4281 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4282 D->dropAttr<MinSizeAttr>();
4285 if (D->hasAttr<OptimizeNoneAttr>())
4288 return ::new (Context) OptimizeNoneAttr(Context, CI);
4291 SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4292 Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4293 if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4296 return ::new (Context) SpeculativeLoadHardeningAttr(Context, AL);
4299 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4300 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4303 if (AlwaysInlineAttr *Inline =
4304 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4308 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4309 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4310 D->addAttr(MinSize);
4313 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4314 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4315 D->addAttr(Optnone);
4318 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4319 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4321 const auto *VD = cast<VarDecl>(D);
4322 if (!VD->hasGlobalStorage()) {
4323 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4326 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4329 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4330 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4332 const auto *VD = cast<VarDecl>(D);
4333 // extern __shared__ is only allowed on arrays with no length (e.g.
4335 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4336 !isa<IncompleteArrayType>(VD->getType())) {
4337 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4340 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4341 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4342 << S.CurrentCUDATarget())
4344 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4347 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4348 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4349 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4352 const auto *FD = cast<FunctionDecl>(D);
4353 if (!FD->getReturnType()->isVoidType() &&
4354 !FD->getReturnType()->getAs<AutoType>() &&
4355 !FD->getReturnType()->isInstantiationDependentType()) {
4356 SourceRange RTRange = FD->getReturnTypeSourceRange();
4357 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4359 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4363 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4364 if (Method->isInstance()) {
4365 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4369 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4371 // Only warn for "inline" when compiling for host, to cut down on noise.
4372 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4373 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4375 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4376 // In host compilation the kernel is emitted as a stub function, which is
4377 // a helper function for launching the kernel. The instructions in the helper
4378 // function has nothing to do with the source code of the kernel. Do not emit
4379 // debug info for the stub function to avoid confusing the debugger.
4380 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4381 D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4384 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4385 const auto *Fn = cast<FunctionDecl>(D);
4386 if (!Fn->isInlineSpecified()) {
4387 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4391 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4392 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4394 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4397 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4398 if (hasDeclarator(D)) return;
4400 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4401 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4403 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4406 if (!isa<ObjCMethodDecl>(D)) {
4407 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4408 << AL << ExpectedFunctionOrMethod;
4412 switch (AL.getKind()) {
4413 case ParsedAttr::AT_FastCall:
4414 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4416 case ParsedAttr::AT_StdCall:
4417 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4419 case ParsedAttr::AT_ThisCall:
4420 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4422 case ParsedAttr::AT_CDecl:
4423 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4425 case ParsedAttr::AT_Pascal:
4426 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4428 case ParsedAttr::AT_SwiftCall:
4429 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4431 case ParsedAttr::AT_VectorCall:
4432 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4434 case ParsedAttr::AT_MSABI:
4435 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4437 case ParsedAttr::AT_SysVABI:
4438 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4440 case ParsedAttr::AT_RegCall:
4441 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4443 case ParsedAttr::AT_Pcs: {
4444 PcsAttr::PCSType PCS;
4447 PCS = PcsAttr::AAPCS;
4450 PCS = PcsAttr::AAPCS_VFP;
4453 llvm_unreachable("unexpected calling convention in pcs attribute");
4456 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4459 case ParsedAttr::AT_AArch64VectorPcs:
4460 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4462 case ParsedAttr::AT_IntelOclBicc:
4463 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4465 case ParsedAttr::AT_PreserveMost:
4466 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4468 case ParsedAttr::AT_PreserveAll:
4469 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4472 llvm_unreachable("unexpected attribute kind");
4476 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4477 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4480 std::vector<StringRef> DiagnosticIdentifiers;
4481 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4484 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4487 // FIXME: Warn if the rule name is unknown. This is tricky because only
4488 // clang-tidy knows about available rules.
4489 DiagnosticIdentifiers.push_back(RuleName);
4491 D->addAttr(::new (S.Context)
4492 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4493 DiagnosticIdentifiers.size()));
4496 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4497 TypeSourceInfo *DerefTypeLoc = nullptr;
4499 if (AL.hasParsedType()) {
4500 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4502 unsigned SelectIdx = ~0U;
4503 if (ParmType->isReferenceType())
4505 else if (ParmType->isArrayType())
4508 if (SelectIdx != ~0U) {
4509 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4515 // To check if earlier decl attributes do not conflict the newly parsed ones
4516 // we always add (and check) the attribute to the cannonical decl.
4517 D = D->getCanonicalDecl();
4518 if (AL.getKind() == ParsedAttr::AT_Owner) {
4519 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4521 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4522 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4523 ? OAttr->getDerefType().getTypePtr()
4525 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4526 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4528 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4532 for (Decl *Redecl : D->redecls()) {
4533 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4536 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4538 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4539 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4540 ? PAttr->getDerefType().getTypePtr()
4542 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4543 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4545 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4549 for (Decl *Redecl : D->redecls()) {
4550 Redecl->addAttr(::new (S.Context)
4551 PointerAttr(S.Context, AL, DerefTypeLoc));
4556 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4557 const FunctionDecl *FD) {
4558 if (Attrs.isInvalid())
4561 if (Attrs.hasProcessingCache()) {
4562 CC = (CallingConv) Attrs.getProcessingCache();
4566 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4567 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4572 // TODO: diagnose uses of these conventions on the wrong target.
4573 switch (Attrs.getKind()) {
4574 case ParsedAttr::AT_CDecl:
4577 case ParsedAttr::AT_FastCall:
4578 CC = CC_X86FastCall;
4580 case ParsedAttr::AT_StdCall:
4583 case ParsedAttr::AT_ThisCall:
4584 CC = CC_X86ThisCall;
4586 case ParsedAttr::AT_Pascal:
4589 case ParsedAttr::AT_SwiftCall:
4592 case ParsedAttr::AT_VectorCall:
4593 CC = CC_X86VectorCall;
4595 case ParsedAttr::AT_AArch64VectorPcs:
4596 CC = CC_AArch64VectorCall;
4598 case ParsedAttr::AT_RegCall:
4601 case ParsedAttr::AT_MSABI:
4602 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4605 case ParsedAttr::AT_SysVABI:
4606 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4609 case ParsedAttr::AT_Pcs: {
4611 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4615 if (StrRef == "aapcs") {
4618 } else if (StrRef == "aapcs-vfp") {
4624 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4627 case ParsedAttr::AT_IntelOclBicc:
4628 CC = CC_IntelOclBicc;
4630 case ParsedAttr::AT_PreserveMost:
4631 CC = CC_PreserveMost;
4633 case ParsedAttr::AT_PreserveAll:
4634 CC = CC_PreserveAll;
4636 default: llvm_unreachable("unexpected attribute kind");
4639 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4640 const TargetInfo &TI = Context.getTargetInfo();
4641 // CUDA functions may have host and/or device attributes which indicate
4642 // their targeted execution environment, therefore the calling convention
4643 // of functions in CUDA should be checked against the target deduced based
4644 // on their host/device attributes.
4645 if (LangOpts.CUDA) {
4646 auto *Aux = Context.getAuxTargetInfo();
4647 auto CudaTarget = IdentifyCUDATarget(FD);
4648 bool CheckHost = false, CheckDevice = false;
4649 switch (CudaTarget) {
4650 case CFT_HostDevice:
4661 case CFT_InvalidTarget:
4662 llvm_unreachable("unexpected cuda target");
4664 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4665 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4666 if (CheckHost && HostTI)
4667 A = HostTI->checkCallingConvention(CC);
4668 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4669 A = DeviceTI->checkCallingConvention(CC);
4671 A = TI.checkCallingConvention(CC);
4675 case TargetInfo::CCCR_OK:
4678 case TargetInfo::CCCR_Ignore:
4679 // Treat an ignored convention as if it was an explicit C calling convention
4680 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4681 // that command line flags that change the default convention to
4682 // __vectorcall don't affect declarations marked __stdcall.
4686 case TargetInfo::CCCR_Error:
4687 Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4688 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4691 case TargetInfo::CCCR_Warning: {
4692 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4693 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4695 // This convention is not valid for the target. Use the default function or
4696 // method calling convention.
4697 bool IsCXXMethod = false, IsVariadic = false;
4699 IsCXXMethod = FD->isCXXInstanceMember();
4700 IsVariadic = FD->isVariadic();
4702 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4707 Attrs.setProcessingCache((unsigned) CC);
4711 /// Pointer-like types in the default address space.
4712 static bool isValidSwiftContextType(QualType Ty) {
4713 if (!Ty->hasPointerRepresentation())
4714 return Ty->isDependentType();
4715 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4718 /// Pointers and references in the default address space.
4719 static bool isValidSwiftIndirectResultType(QualType Ty) {
4720 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4721 Ty = PtrType->getPointeeType();
4722 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4723 Ty = RefType->getPointeeType();
4725 return Ty->isDependentType();
4727 return Ty.getAddressSpace() == LangAS::Default;
4730 /// Pointers and references to pointers in the default address space.
4731 static bool isValidSwiftErrorResultType(QualType Ty) {
4732 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4733 Ty = PtrType->getPointeeType();
4734 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4735 Ty = RefType->getPointeeType();
4737 return Ty->isDependentType();
4739 if (!Ty.getQualifiers().empty())
4741 return isValidSwiftContextType(Ty);
4744 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
4747 QualType type = cast<ParmVarDecl>(D)->getType();
4749 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4750 if (existingAttr->getABI() != abi) {
4751 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4752 << getParameterABISpelling(abi) << existingAttr;
4753 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4759 case ParameterABI::Ordinary:
4760 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4762 case ParameterABI::SwiftContext:
4763 if (!isValidSwiftContextType(type)) {
4764 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4765 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
4767 D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
4770 case ParameterABI::SwiftErrorResult:
4771 if (!isValidSwiftErrorResultType(type)) {
4772 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4773 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
4775 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
4778 case ParameterABI::SwiftIndirectResult:
4779 if (!isValidSwiftIndirectResultType(type)) {
4780 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4781 << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
4783 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
4786 llvm_unreachable("bad parameter ABI attribute");
4789 /// Checks a regparm attribute, returning true if it is ill-formed and
4790 /// otherwise setting numParams to the appropriate value.
4791 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4795 if (!checkAttributeNumArgs(*this, AL, 1)) {
4801 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4802 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4807 if (Context.getTargetInfo().getRegParmMax() == 0) {
4808 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4809 << NumParamsExpr->getSourceRange();
4815 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4816 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4817 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4825 // Checks whether an argument of launch_bounds attribute is
4826 // acceptable, performs implicit conversion to Rvalue, and returns
4827 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4828 // and may output an error.
4829 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4830 const CUDALaunchBoundsAttr &AL,
4831 const unsigned Idx) {
4832 if (S.DiagnoseUnexpandedParameterPack(E))
4835 // Accept template arguments for now as they depend on something else.
4836 // We'll get to check them when they eventually get instantiated.
4837 if (E->isValueDependent())
4841 if (!E->isIntegerConstantExpr(I, S.Context)) {
4842 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4843 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4846 // Make sure we can fit it in 32 bits.
4847 if (!I.isIntN(32)) {
4848 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4849 << 32 << /* Unsigned */ 1;
4853 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4854 << &AL << Idx << E->getSourceRange();
4856 // We may need to perform implicit conversion of the argument.
4857 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4858 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4859 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4860 assert(!ValArg.isInvalid() &&
4861 "Unexpected PerformCopyInitialization() failure.");
4863 return ValArg.getAs<Expr>();
4866 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
4867 Expr *MaxThreads, Expr *MinBlocks) {
4868 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
4869 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4870 if (MaxThreads == nullptr)
4874 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4875 if (MinBlocks == nullptr)
4879 D->addAttr(::new (Context)
4880 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
4883 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4884 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4885 !checkAttributeAtMostNumArgs(S, AL, 2))
4888 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
4889 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
4892 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4893 const ParsedAttr &AL) {
4894 if (!AL.isArgIdent(0)) {
4895 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4896 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4900 ParamIdx ArgumentIdx;
4901 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4905 ParamIdx TypeTagIdx;
4906 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4910 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
4912 // Ensure that buffer has a pointer type.
4913 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4914 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4915 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4916 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4919 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4920 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
4924 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4925 const ParsedAttr &AL) {
4926 if (!AL.isArgIdent(0)) {
4927 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4928 << AL << 1 << AANT_ArgumentIdentifier;
4932 if (!checkAttributeNumArgs(S, AL, 1))
4935 if (!isa<VarDecl>(D)) {
4936 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4937 << AL << ExpectedVariable;
4941 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4942 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4943 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4944 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4946 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
4947 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
4948 AL.getMustBeNull()));
4951 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4954 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4956 true /* CanIndexImplicitThis */))
4959 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4960 D->addAttr(::new (S.Context)
4961 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
4964 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
4965 const ParsedAttr &AL) {
4966 uint32_t Count = 0, Offset = 0;
4967 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
4969 if (AL.getNumArgs() == 2) {
4970 Expr *Arg = AL.getArgAsExpr(1);
4971 if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
4973 if (Count < Offset) {
4974 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
4975 << &AL << 0 << Count << Arg->getBeginLoc();
4979 D->addAttr(::new (S.Context)
4980 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
4984 struct IntrinToName {
4989 } // unnamed namespace
4991 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
4992 ArrayRef<IntrinToName> Map,
4993 const char *IntrinNames) {
4994 if (AliasName.startswith("__arm_"))
4995 AliasName = AliasName.substr(6);
4996 const IntrinToName *It = std::lower_bound(
4997 Map.begin(), Map.end(), BuiltinID,
4998 [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
4999 if (It == Map.end() || It->Id != BuiltinID)
5001 StringRef FullName(&IntrinNames[It->FullName]);
5002 if (AliasName == FullName)
5004 if (It->ShortName == -1)
5006 StringRef ShortName(&IntrinNames[It->ShortName]);
5007 return AliasName == ShortName;
5010 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5011 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5012 // The included file defines:
5013 // - ArrayRef<IntrinToName> Map
5014 // - const char IntrinNames[]
5015 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5018 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5019 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5020 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5023 static bool ArmSveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5024 switch (BuiltinID) {
5027 #define GET_SVE_BUILTINS
5028 #define BUILTIN(name, types, attr) case SVE::BI##name:
5029 #include "clang/Basic/arm_sve_builtins.inc"
5034 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5035 if (!AL.isArgIdent(0)) {
5036 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5037 << AL << 1 << AANT_ArgumentIdentifier;
5041 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5042 unsigned BuiltinID = Ident->getBuiltinID();
5043 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5045 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5046 if ((IsAArch64 && !ArmSveAliasValid(BuiltinID, AliasName)) ||
5047 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5048 !ArmCdeAliasValid(BuiltinID, AliasName))) {
5049 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5053 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5056 //===----------------------------------------------------------------------===//
5057 // Checker-specific attribute handlers.
5058 //===----------------------------------------------------------------------===//
5059 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5060 return QT->isDependentType() || QT->isObjCRetainableType();
5063 static bool isValidSubjectOfNSAttribute(QualType QT) {
5064 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5065 QT->isObjCNSObjectType();
5068 static bool isValidSubjectOfCFAttribute(QualType QT) {
5069 return QT->isDependentType() || QT->isPointerType() ||
5070 isValidSubjectOfNSAttribute(QT);
5073 static bool isValidSubjectOfOSAttribute(QualType QT) {
5074 if (QT->isDependentType())
5076 QualType PT = QT->getPointeeType();
5077 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5080 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5081 RetainOwnershipKind K,
5082 bool IsTemplateInstantiation) {
5083 ValueDecl *VD = cast<ValueDecl>(D);
5085 case RetainOwnershipKind::OS:
5086 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5087 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5088 diag::warn_ns_attribute_wrong_parameter_type,
5089 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5091 case RetainOwnershipKind::NS:
5092 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5093 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5095 // These attributes are normally just advisory, but in ARC, ns_consumed
5096 // is significant. Allow non-dependent code to contain inappropriate
5097 // attributes even in ARC, but require template instantiations to be
5098 // set up correctly.
5099 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5100 ? diag::err_ns_attribute_wrong_parameter_type
5101 : diag::warn_ns_attribute_wrong_parameter_type),
5102 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5104 case RetainOwnershipKind::CF:
5105 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5106 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5107 diag::warn_ns_attribute_wrong_parameter_type,
5108 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5113 static Sema::RetainOwnershipKind
5114 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5115 switch (AL.getKind()) {
5116 case ParsedAttr::AT_CFConsumed:
5117 case ParsedAttr::AT_CFReturnsRetained:
5118 case ParsedAttr::AT_CFReturnsNotRetained:
5119 return Sema::RetainOwnershipKind::CF;
5120 case ParsedAttr::AT_OSConsumesThis:
5121 case ParsedAttr::AT_OSConsumed:
5122 case ParsedAttr::AT_OSReturnsRetained:
5123 case ParsedAttr::AT_OSReturnsNotRetained:
5124 case ParsedAttr::AT_OSReturnsRetainedOnZero:
5125 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5126 return Sema::RetainOwnershipKind::OS;
5127 case ParsedAttr::AT_NSConsumesSelf:
5128 case ParsedAttr::AT_NSConsumed:
5129 case ParsedAttr::AT_NSReturnsRetained:
5130 case ParsedAttr::AT_NSReturnsNotRetained:
5131 case ParsedAttr::AT_NSReturnsAutoreleased:
5132 return Sema::RetainOwnershipKind::NS;
5134 llvm_unreachable("Wrong argument supplied");
5138 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5139 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5142 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5143 << "'ns_returns_retained'" << 0 << 0;
5147 /// \return whether the parameter is a pointer to OSObject pointer.
5148 static bool isValidOSObjectOutParameter(const Decl *D) {
5149 const auto *PVD = dyn_cast<ParmVarDecl>(D);
5152 QualType QT = PVD->getType();
5153 QualType PT = QT->getPointeeType();
5154 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5157 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5158 const ParsedAttr &AL) {
5159 QualType ReturnType;
5160 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5162 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5163 ReturnType = MD->getReturnType();
5164 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5165 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5166 return; // ignore: was handled as a type attribute
5167 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5168 ReturnType = PD->getType();
5169 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5170 ReturnType = FD->getReturnType();
5171 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5172 // Attributes on parameters are used for out-parameters,
5173 // passed as pointers-to-pointers.
5174 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5175 ? /*pointer-to-CF-pointer*/2
5176 : /*pointer-to-OSObject-pointer*/3;
5177 ReturnType = Param->getType()->getPointeeType();
5178 if (ReturnType.isNull()) {
5179 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5180 << AL << DiagID << AL.getRange();
5183 } else if (AL.isUsedAsTypeAttr()) {
5186 AttributeDeclKind ExpectedDeclKind;
5187 switch (AL.getKind()) {
5188 default: llvm_unreachable("invalid ownership attribute");
5189 case ParsedAttr::AT_NSReturnsRetained:
5190 case ParsedAttr::AT_NSReturnsAutoreleased:
5191 case ParsedAttr::AT_NSReturnsNotRetained:
5192 ExpectedDeclKind = ExpectedFunctionOrMethod;
5195 case ParsedAttr::AT_OSReturnsRetained:
5196 case ParsedAttr::AT_OSReturnsNotRetained:
5197 case ParsedAttr::AT_CFReturnsRetained:
5198 case ParsedAttr::AT_CFReturnsNotRetained:
5199 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5202 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5203 << AL.getRange() << AL << ExpectedDeclKind;
5209 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5210 switch (AL.getKind()) {
5211 default: llvm_unreachable("invalid ownership attribute");
5212 case ParsedAttr::AT_NSReturnsRetained:
5213 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5217 case ParsedAttr::AT_NSReturnsAutoreleased:
5218 case ParsedAttr::AT_NSReturnsNotRetained:
5219 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5223 case ParsedAttr::AT_CFReturnsRetained:
5224 case ParsedAttr::AT_CFReturnsNotRetained:
5225 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5229 case ParsedAttr::AT_OSReturnsRetained:
5230 case ParsedAttr::AT_OSReturnsNotRetained:
5231 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5233 ParmDiagID = 3; // Pointer-to-OSObject-pointer
5238 if (AL.isUsedAsTypeAttr())
5241 if (isa<ParmVarDecl>(D)) {
5242 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5243 << AL << ParmDiagID << AL.getRange();
5245 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5250 } SubjectKind = Function;
5251 if (isa<ObjCMethodDecl>(D))
5252 SubjectKind = Method;
5253 else if (isa<ObjCPropertyDecl>(D))
5254 SubjectKind = Property;
5255 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5256 << AL << SubjectKind << Cf << AL.getRange();
5261 switch (AL.getKind()) {
5263 llvm_unreachable("invalid ownership attribute");
5264 case ParsedAttr::AT_NSReturnsAutoreleased:
5265 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5267 case ParsedAttr::AT_CFReturnsNotRetained:
5268 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5270 case ParsedAttr::AT_NSReturnsNotRetained:
5271 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5273 case ParsedAttr::AT_CFReturnsRetained:
5274 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5276 case ParsedAttr::AT_NSReturnsRetained:
5277 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5279 case ParsedAttr::AT_OSReturnsRetained:
5280 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5282 case ParsedAttr::AT_OSReturnsNotRetained:
5283 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5288 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5289 const ParsedAttr &Attrs) {
5290 const int EP_ObjCMethod = 1;
5291 const int EP_ObjCProperty = 2;
5293 SourceLocation loc = Attrs.getLoc();
5294 QualType resultType;
5295 if (isa<ObjCMethodDecl>(D))
5296 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5298 resultType = cast<ObjCPropertyDecl>(D)->getType();
5300 if (!resultType->isReferenceType() &&
5301 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5302 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5303 << SourceRange(loc) << Attrs
5304 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5305 << /*non-retainable pointer*/ 2;
5307 // Drop the attribute.
5311 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5314 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5315 const ParsedAttr &Attrs) {
5316 const auto *Method = cast<ObjCMethodDecl>(D);
5318 const DeclContext *DC = Method->getDeclContext();
5319 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5320 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5322 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5325 if (Method->getMethodFamily() == OMF_dealloc) {
5326 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5331 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5334 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5335 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5338 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5342 // Typedefs only allow objc_bridge(id) and have some additional checking.
5343 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5344 if (!Parm->Ident->isStr("id")) {
5345 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5349 // Only allow 'cv void *'.
5350 QualType T = TD->getUnderlyingType();
5351 if (!T->isVoidPointerType()) {
5352 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5357 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5360 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5361 const ParsedAttr &AL) {
5362 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5365 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5369 D->addAttr(::new (S.Context)
5370 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5373 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5374 const ParsedAttr &AL) {
5375 IdentifierInfo *RelatedClass =
5376 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5377 if (!RelatedClass) {
5378 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5381 IdentifierInfo *ClassMethod =
5382 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5383 IdentifierInfo *InstanceMethod =
5384 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5385 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5386 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5389 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5390 const ParsedAttr &AL) {
5391 DeclContext *Ctx = D->getDeclContext();
5393 // This attribute can only be applied to methods in interfaces or class
5395 if (!isa<ObjCInterfaceDecl>(Ctx) &&
5396 !(isa<ObjCCategoryDecl>(Ctx) &&
5397 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5398 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5402 ObjCInterfaceDecl *IFace;
5403 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5404 IFace = CatDecl->getClassInterface();
5406 IFace = cast<ObjCInterfaceDecl>(Ctx);
5411 IFace->setHasDesignatedInitializers();
5412 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5415 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5416 StringRef MetaDataName;
5417 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5419 D->addAttr(::new (S.Context)
5420 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5423 // When a user wants to use objc_boxable with a union or struct
5424 // but they don't have access to the declaration (legacy/third-party code)
5425 // then they can 'enable' this feature with a typedef:
5426 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5427 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5428 bool notify = false;
5430 auto *RD = dyn_cast<RecordDecl>(D);
5431 if (RD && RD->getDefinition()) {
5432 RD = RD->getDefinition();
5437 ObjCBoxableAttr *BoxableAttr =
5438 ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5439 RD->addAttr(BoxableAttr);
5441 // we need to notify ASTReader/ASTWriter about
5442 // modification of existing declaration
5443 if (ASTMutationListener *L = S.getASTMutationListener())
5444 L->AddedAttributeToRecord(BoxableAttr, RD);
5449 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5450 if (hasDeclarator(D)) return;
5452 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5453 << AL.getRange() << AL << ExpectedVariable;
5456 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5457 const ParsedAttr &AL) {
5458 const auto *VD = cast<ValueDecl>(D);
5459 QualType QT = VD->getType();
5461 if (!QT->isDependentType() &&
5462 !QT->isObjCLifetimeType()) {
5463 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5468 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5470 // If we have no lifetime yet, check the lifetime we're presumably
5472 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5473 Lifetime = QT->getObjCARCImplicitLifetime();
5476 case Qualifiers::OCL_None:
5477 assert(QT->isDependentType() &&
5478 "didn't infer lifetime for non-dependent type?");
5481 case Qualifiers::OCL_Weak: // meaningful
5482 case Qualifiers::OCL_Strong: // meaningful
5485 case Qualifiers::OCL_ExplicitNone:
5486 case Qualifiers::OCL_Autoreleasing:
5487 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5488 << (Lifetime == Qualifiers::OCL_Autoreleasing);
5492 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5495 //===----------------------------------------------------------------------===//
5496 // Microsoft specific attribute handlers.
5497 //===----------------------------------------------------------------------===//
5499 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5500 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
5501 if (const auto *UA = D->getAttr<UuidAttr>()) {
5502 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
5504 if (!UA->getGuid().empty()) {
5505 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5506 Diag(CI.getLoc(), diag::note_previous_uuid);
5507 D->dropAttr<UuidAttr>();
5511 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
5514 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5515 if (!S.LangOpts.CPlusPlus) {
5516 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5517 << AL << AttributeLangSupport::C;
5521 StringRef OrigStrRef;
5522 SourceLocation LiteralLoc;
5523 if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
5526 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5527 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5528 StringRef StrRef = OrigStrRef;
5529 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5530 StrRef = StrRef.drop_front().drop_back();
5532 // Validate GUID length.
5533 if (StrRef.size() != 36) {
5534 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5538 for (unsigned i = 0; i < 36; ++i) {
5539 if (i == 8 || i == 13 || i == 18 || i == 23) {
5540 if (StrRef[i] != '-') {
5541 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5544 } else if (!isHexDigit(StrRef[i])) {
5545 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5550 // Convert to our parsed format and canonicalize.
5551 MSGuidDecl::Parts Parsed;
5552 StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
5553 StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
5554 StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
5555 for (unsigned i = 0; i != 8; ++i)
5556 StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
5557 .getAsInteger(16, Parsed.Part4And5[i]);
5558 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
5560 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5561 // the only thing in the [] list, the [] too), and add an insertion of
5562 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5563 // separating attributes nor of the [ and the ] are in the AST.
5564 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5566 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5567 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5569 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
5574 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5575 if (!S.LangOpts.CPlusPlus) {
5576 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5577 << AL << AttributeLangSupport::C;
5580 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5581 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
5584 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5588 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5589 const auto *VD = cast<VarDecl>(D);
5590 if (!S.Context.getTargetInfo().isTLSSupported()) {
5591 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5594 if (VD->getTSCSpec() != TSCS_unspecified) {
5595 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5598 if (VD->hasLocalStorage()) {
5599 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5602 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
5605 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5606 SmallVector<StringRef, 4> Tags;
5607 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5609 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5611 Tags.push_back(Tag);
5614 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5615 if (!NS->isInline()) {
5616 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5619 if (NS->isAnonymousNamespace()) {
5620 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5623 if (AL.getNumArgs() == 0)
5624 Tags.push_back(NS->getName());
5625 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5628 // Store tags sorted and without duplicates.
5630 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5632 D->addAttr(::new (S.Context)
5633 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
5636 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5637 // Check the attribute arguments.
5638 if (AL.getNumArgs() > 1) {
5639 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5644 SourceLocation ArgLoc;
5646 if (AL.getNumArgs() == 0)
5648 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5651 ARMInterruptAttr::InterruptType Kind;
5652 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5653 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5658 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
5661 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5662 // MSP430 'interrupt' attribute is applied to
5663 // a function with no parameters and void return type.
5664 if (!isFunctionOrMethod(D)) {
5665 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5666 << "'interrupt'" << ExpectedFunctionOrMethod;
5670 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5671 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5672 << /*MSP430*/ 1 << 0;
5676 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5677 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5678 << /*MSP430*/ 1 << 1;
5682 // The attribute takes one integer argument.
5683 if (!checkAttributeNumArgs(S, AL, 1))
5686 if (!AL.isArgExpr(0)) {
5687 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5688 << AL << AANT_ArgumentIntegerConstant;
5692 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5693 llvm::APSInt NumParams(32);
5694 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5695 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5696 << AL << AANT_ArgumentIntegerConstant
5697 << NumParamsExpr->getSourceRange();
5700 // The argument should be in range 0..63.
5701 unsigned Num = NumParams.getLimitedValue(255);
5703 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5704 << AL << (int)NumParams.getSExtValue()
5705 << NumParamsExpr->getSourceRange();
5709 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
5710 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5713 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5714 // Only one optional argument permitted.
5715 if (AL.getNumArgs() > 1) {
5716 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5721 SourceLocation ArgLoc;
5723 if (AL.getNumArgs() == 0)
5725 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5728 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5729 // a) Must be a function.
5730 // b) Must have no parameters.
5731 // c) Must have the 'void' return type.
5732 // d) Cannot have the 'mips16' attribute, as that instruction set
5733 // lacks the 'eret' instruction.
5734 // e) The attribute itself must either have no argument or one of the
5735 // valid interrupt types, see [MipsInterruptDocs].
5737 if (!isFunctionOrMethod(D)) {
5738 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5739 << "'interrupt'" << ExpectedFunctionOrMethod;
5743 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5744 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5749 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5750 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5755 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5758 MipsInterruptAttr::InterruptType Kind;
5759 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5760 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5761 << AL << "'" + std::string(Str) + "'";
5765 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
5768 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5769 // Semantic checks for a function with the 'interrupt' attribute.
5770 // a) Must be a function.
5771 // b) Must have the 'void' return type.
5772 // c) Must take 1 or 2 arguments.
5773 // d) The 1st argument must be a pointer.
5774 // e) The 2nd argument (if any) must be an unsigned integer.
5775 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5776 CXXMethodDecl::isStaticOverloadedOperator(
5777 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5778 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5779 << AL << ExpectedFunctionWithProtoType;
5782 // Interrupt handler must have void return type.
5783 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5784 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5785 diag::err_anyx86_interrupt_attribute)
5786 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5792 // Interrupt handler must have 1 or 2 parameters.
5793 unsigned NumParams = getFunctionOrMethodNumParams(D);
5794 if (NumParams < 1 || NumParams > 2) {
5795 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5796 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5802 // The first argument must be a pointer.
5803 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5804 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5805 diag::err_anyx86_interrupt_attribute)
5806 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5812 // The second argument, if present, must be an unsigned integer.
5814 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5817 if (NumParams == 2 &&
5818 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5819 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5820 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5821 diag::err_anyx86_interrupt_attribute)
5822 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5825 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5828 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
5829 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5832 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5833 if (!isFunctionOrMethod(D)) {
5834 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5835 << "'interrupt'" << ExpectedFunction;
5839 if (!checkAttributeNumArgs(S, AL, 0))
5842 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5845 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5846 if (!isFunctionOrMethod(D)) {
5847 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5848 << "'signal'" << ExpectedFunction;
5852 if (!checkAttributeNumArgs(S, AL, 0))
5855 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5858 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
5859 // Add preserve_access_index attribute to all fields and inner records.
5860 for (auto D : RD->decls()) {
5861 if (D->hasAttr<BPFPreserveAccessIndexAttr>())
5864 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
5865 if (auto *Rec = dyn_cast<RecordDecl>(D))
5866 handleBPFPreserveAIRecord(S, Rec);
5870 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
5871 const ParsedAttr &AL) {
5872 auto *Rec = cast<RecordDecl>(D);
5873 handleBPFPreserveAIRecord(S, Rec);
5874 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
5877 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5878 if (!isFunctionOrMethod(D)) {
5879 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5880 << "'export_name'" << ExpectedFunction;
5884 auto *FD = cast<FunctionDecl>(D);
5885 if (FD->isThisDeclarationADefinition()) {
5886 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5891 SourceLocation ArgLoc;
5892 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5895 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
5896 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5899 WebAssemblyImportModuleAttr *
5900 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
5901 auto *FD = cast<FunctionDecl>(D);
5903 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
5904 if (ExistingAttr->getImportModule() == AL.getImportModule())
5906 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
5907 << ExistingAttr->getImportModule() << AL.getImportModule();
5908 Diag(AL.getLoc(), diag::note_previous_attribute);
5911 if (FD->hasBody()) {
5912 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
5915 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
5916 AL.getImportModule());
5919 WebAssemblyImportNameAttr *
5920 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
5921 auto *FD = cast<FunctionDecl>(D);
5923 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
5924 if (ExistingAttr->getImportName() == AL.getImportName())
5926 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
5927 << ExistingAttr->getImportName() << AL.getImportName();
5928 Diag(AL.getLoc(), diag::note_previous_attribute);
5931 if (FD->hasBody()) {
5932 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
5935 return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
5936 AL.getImportName());
5940 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5941 auto *FD = cast<FunctionDecl>(D);
5944 SourceLocation ArgLoc;
5945 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5947 if (FD->hasBody()) {
5948 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
5952 FD->addAttr(::new (S.Context)
5953 WebAssemblyImportModuleAttr(S.Context, AL, Str));
5957 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5958 auto *FD = cast<FunctionDecl>(D);
5961 SourceLocation ArgLoc;
5962 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5964 if (FD->hasBody()) {
5965 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
5969 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
5972 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5973 const ParsedAttr &AL) {
5974 // Warn about repeated attributes.
5975 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5976 S.Diag(AL.getRange().getBegin(),
5977 diag::warn_riscv_repeated_interrupt_attribute);
5978 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5982 // Check the attribute argument. Argument is optional.
5983 if (!checkAttributeAtMostNumArgs(S, AL, 1))
5987 SourceLocation ArgLoc;
5989 // 'machine'is the default interrupt mode.
5990 if (AL.getNumArgs() == 0)
5992 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5995 // Semantic checks for a function with the 'interrupt' attribute:
5996 // - Must be a function.
5997 // - Must have no parameters.
5998 // - Must have the 'void' return type.
5999 // - The attribute itself must either have no argument or one of the
6000 // valid interrupt types, see [RISCVInterruptDocs].
6002 if (D->getFunctionType() == nullptr) {
6003 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6004 << "'interrupt'" << ExpectedFunction;
6008 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6009 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6010 << /*RISC-V*/ 2 << 0;
6014 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6015 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6016 << /*RISC-V*/ 2 << 1;
6020 RISCVInterruptAttr::InterruptType Kind;
6021 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6022 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6027 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
6030 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6031 // Dispatch the interrupt attribute based on the current target.
6032 switch (S.Context.getTargetInfo().getTriple().getArch()) {
6033 case llvm::Triple::msp430:
6034 handleMSP430InterruptAttr(S, D, AL);
6036 case llvm::Triple::mipsel:
6037 case llvm::Triple::mips:
6038 handleMipsInterruptAttr(S, D, AL);
6040 case llvm::Triple::x86:
6041 case llvm::Triple::x86_64:
6042 handleAnyX86InterruptAttr(S, D, AL);
6044 case llvm::Triple::avr:
6045 handleAVRInterruptAttr(S, D, AL);
6047 case llvm::Triple::riscv32:
6048 case llvm::Triple::riscv64:
6049 handleRISCVInterruptAttr(S, D, AL);
6052 handleARMInterruptAttr(S, D, AL);
6058 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
6059 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
6060 // Accept template arguments for now as they depend on something else.
6061 // We'll get to check them when they eventually get instantiated.
6062 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
6066 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
6070 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
6073 if (Min == 0 && Max != 0) {
6074 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6079 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6087 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
6088 const AttributeCommonInfo &CI,
6089 Expr *MinExpr, Expr *MaxExpr) {
6090 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
6092 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
6095 D->addAttr(::new (Context)
6096 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
6099 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
6100 const ParsedAttr &AL) {
6101 Expr *MinExpr = AL.getArgAsExpr(0);
6102 Expr *MaxExpr = AL.getArgAsExpr(1);
6104 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
6107 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
6109 const AMDGPUWavesPerEUAttr &Attr) {
6110 if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
6111 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
6114 // Accept template arguments for now as they depend on something else.
6115 // We'll get to check them when they eventually get instantiated.
6116 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
6120 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
6124 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
6127 if (Min == 0 && Max != 0) {
6128 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6132 if (Max != 0 && Min > Max) {
6133 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6141 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
6142 Expr *MinExpr, Expr *MaxExpr) {
6143 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
6145 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
6148 D->addAttr(::new (Context)
6149 AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
6152 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6153 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
6154 !checkAttributeAtMostNumArgs(S, AL, 2))
6157 Expr *MinExpr = AL.getArgAsExpr(0);
6158 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
6160 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
6163 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6164 uint32_t NumSGPR = 0;
6165 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
6166 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
6169 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
6172 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6173 uint32_t NumVGPR = 0;
6174 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
6175 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
6178 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
6181 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
6182 const ParsedAttr &AL) {
6183 // If we try to apply it to a function pointer, don't warn, but don't
6184 // do anything, either. It doesn't matter anyway, because there's nothing
6185 // special about calling a force_align_arg_pointer function.
6186 const auto *VD = dyn_cast<ValueDecl>(D);
6187 if (VD && VD->getType()->isFunctionPointerType())
6189 // Also don't warn on function pointer typedefs.
6190 const auto *TD = dyn_cast<TypedefNameDecl>(D);
6191 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
6192 TD->getUnderlyingType()->isFunctionType()))
6194 // Attribute can only be applied to function types.
6195 if (!isa<FunctionDecl>(D)) {
6196 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6197 << AL << ExpectedFunction;
6201 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
6204 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
6206 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6207 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
6210 // TODO: Investigate what happens with the next major version of MSVC.
6211 if (Version != LangOptions::MSVC2015 / 100) {
6212 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6213 << AL << Version << VersionExpr->getSourceRange();
6217 // The attribute expects a "major" version number like 19, but new versions of
6218 // MSVC have moved to updating the "minor", or less significant numbers, so we
6219 // have to multiply by 100 now.
6222 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
6225 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
6226 const AttributeCommonInfo &CI) {
6227 if (D->hasAttr<DLLExportAttr>()) {
6228 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
6232 if (D->hasAttr<DLLImportAttr>())
6235 return ::new (Context) DLLImportAttr(Context, CI);
6238 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
6239 const AttributeCommonInfo &CI) {
6240 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
6241 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
6242 D->dropAttr<DLLImportAttr>();
6245 if (D->hasAttr<DLLExportAttr>())
6248 return ::new (Context) DLLExportAttr(Context, CI);
6251 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6252 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
6253 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6254 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
6258 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6259 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
6260 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6261 // MinGW doesn't allow dllimport on inline functions.
6262 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
6268 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
6269 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6270 MD->getParent()->isLambda()) {
6271 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
6276 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
6277 ? (Attr *)S.mergeDLLExportAttr(D, A)
6278 : (Attr *)S.mergeDLLImportAttr(D, A);
6280 D->addAttr(NewAttr);
6284 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
6286 MSInheritanceModel Model) {
6287 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
6288 if (IA->getInheritanceModel() == Model)
6290 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
6291 << 1 /*previous declaration*/;
6292 Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
6293 D->dropAttr<MSInheritanceAttr>();
6296 auto *RD = cast<CXXRecordDecl>(D);
6297 if (RD->hasDefinition()) {
6298 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
6303 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
6304 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
6305 << 1 /*partial specialization*/;
6308 if (RD->getDescribedClassTemplate()) {
6309 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
6310 << 0 /*primary template*/;
6315 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
6318 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6319 // The capability attributes take a single string parameter for the name of
6320 // the capability they represent. The lockable attribute does not take any
6321 // parameters. However, semantically, both attributes represent the same
6322 // concept, and so they use the same semantic attribute. Eventually, the
6323 // lockable attribute will be removed.
6325 // For backward compatibility, any capability which has no specified string
6326 // literal will be considered a "mutex."
6327 StringRef N("mutex");
6328 SourceLocation LiteralLoc;
6329 if (AL.getKind() == ParsedAttr::AT_Capability &&
6330 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
6333 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
6336 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6337 SmallVector<Expr*, 1> Args;
6338 if (!checkLockFunAttrCommon(S, D, AL, Args))
6341 D->addAttr(::new (S.Context)
6342 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
6345 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
6346 const ParsedAttr &AL) {
6347 SmallVector<Expr*, 1> Args;
6348 if (!checkLockFunAttrCommon(S, D, AL, Args))
6351 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
6355 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
6356 const ParsedAttr &AL) {
6357 SmallVector<Expr*, 2> Args;
6358 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
6361 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
6362 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
6365 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6366 const ParsedAttr &AL) {
6367 // Check that all arguments are lockable objects.
6368 SmallVector<Expr *, 1> Args;
6369 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6371 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
6375 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6376 const ParsedAttr &AL) {
6377 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6380 // check that all arguments are lockable objects
6381 SmallVector<Expr*, 1> Args;
6382 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6386 RequiresCapabilityAttr *RCA = ::new (S.Context)
6387 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
6392 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6393 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6394 if (NSD->isAnonymousNamespace()) {
6395 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6396 // Do not want to attach the attribute to the namespace because that will
6397 // cause confusing diagnostic reports for uses of declarations within the
6403 // Handle the cases where the attribute has a text message.
6404 StringRef Str, Replacement;
6405 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6406 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6409 // Only support a single optional message for Declspec and CXX11.
6410 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6411 checkAttributeAtMostNumArgs(S, AL, 1);
6412 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6413 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6416 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6417 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6419 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
6422 static bool isGlobalVar(const Decl *D) {
6423 if (const auto *S = dyn_cast<VarDecl>(D))
6424 return S->hasGlobalStorage();
6428 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6429 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6432 std::vector<StringRef> Sanitizers;
6434 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6435 StringRef SanitizerName;
6436 SourceLocation LiteralLoc;
6438 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6441 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
6443 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6444 else if (isGlobalVar(D) && SanitizerName != "address")
6445 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6446 << AL << ExpectedFunctionOrMethod;
6447 Sanitizers.push_back(SanitizerName);
6450 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
6451 Sanitizers.size()));
6454 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6455 const ParsedAttr &AL) {
6456 StringRef AttrName = AL.getAttrName()->getName();
6457 normalizeName(AttrName);
6458 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6459 .Case("no_address_safety_analysis", "address")
6460 .Case("no_sanitize_address", "address")
6461 .Case("no_sanitize_thread", "thread")
6462 .Case("no_sanitize_memory", "memory");
6463 if (isGlobalVar(D) && SanitizerName != "address")
6464 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6465 << AL << ExpectedFunction;
6467 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
6468 // NoSanitizeAttr object; but we need to calculate the correct spelling list
6469 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
6470 // has the same spellings as the index for NoSanitizeAttr. We don't have a
6471 // general way to "translate" between the two, so this hack attempts to work
6472 // around the issue with hard-coded indicies. This is critical for calling
6473 // getSpelling() or prettyPrint() on the resulting semantic attribute object
6474 // without failing assertions.
6475 unsigned TranslatedSpellingIndex = 0;
6476 if (AL.isC2xAttribute() || AL.isCXX11Attribute())
6477 TranslatedSpellingIndex = 1;
6479 AttributeCommonInfo Info = AL;
6480 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
6481 D->addAttr(::new (S.Context)
6482 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
6485 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6486 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6487 D->addAttr(Internal);
6490 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6491 if (S.LangOpts.OpenCLVersion != 200)
6492 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6493 << AL << "2.0" << 0;
6495 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6499 /// Handles semantic checking for features that are common to all attributes,
6500 /// such as checking whether a parameter was properly specified, or the correct
6501 /// number of arguments were passed, etc.
6502 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6503 const ParsedAttr &AL) {
6504 // Several attributes carry different semantics than the parsing requires, so
6505 // those are opted out of the common argument checks.
6507 // We also bail on unknown and ignored attributes because those are handled
6508 // as part of the target-specific handling logic.
6509 if (AL.getKind() == ParsedAttr::UnknownAttribute)
6511 // Check whether the attribute requires specific language extensions to be
6513 if (!AL.diagnoseLangOpts(S))
6515 // Check whether the attribute appertains to the given subject.
6516 if (!AL.diagnoseAppertainsTo(S, D))
6518 if (AL.hasCustomParsing())
6521 if (AL.getMinArgs() == AL.getMaxArgs()) {
6522 // If there are no optional arguments, then checking for the argument count
6524 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6527 // There are optional arguments, so checking is slightly more involved.
6528 if (AL.getMinArgs() &&
6529 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6531 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6532 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6536 if (S.CheckAttrTarget(AL))
6542 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6543 if (D->isInvalidDecl())
6546 // Check if there is only one access qualifier.
6547 if (D->hasAttr<OpenCLAccessAttr>()) {
6548 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6549 AL.getSemanticSpelling()) {
6550 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6551 << AL.getAttrName()->getName() << AL.getRange();
6553 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6554 << D->getSourceRange();
6555 D->setInvalidDecl(true);
6560 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6561 // image object can be read and written.
6562 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6563 // object. Using the read_write (or __read_write) qualifier with the pipe
6564 // qualifier is a compilation error.
6565 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6566 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6567 if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
6568 if ((!S.getLangOpts().OpenCLCPlusPlus &&
6569 S.getLangOpts().OpenCLVersion < 200) ||
6570 DeclTy->isPipeType()) {
6571 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6572 << AL << PDecl->getType() << DeclTy->isImageType();
6573 D->setInvalidDecl(true);
6579 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
6582 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6583 // The 'sycl_kernel' attribute applies only to function templates.
6584 const auto *FD = cast<FunctionDecl>(D);
6585 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
6586 assert(FT && "Function template is expected");
6588 // Function template must have at least two template parameters.
6589 const TemplateParameterList *TL = FT->getTemplateParameters();
6590 if (TL->size() < 2) {
6591 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
6595 // Template parameters must be typenames.
6596 for (unsigned I = 0; I < 2; ++I) {
6597 const NamedDecl *TParam = TL->getParam(I);
6598 if (isa<NonTypeTemplateParmDecl>(TParam)) {
6599 S.Diag(FT->getLocation(),
6600 diag::warn_sycl_kernel_invalid_template_param_type);
6605 // Function must have at least one argument.
6606 if (getFunctionOrMethodNumParams(D) != 1) {
6607 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
6611 // Function must return void.
6612 QualType RetTy = getFunctionOrMethodResultType(D);
6613 if (!RetTy->isVoidType()) {
6614 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
6618 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
6621 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6622 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6623 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6624 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6628 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6629 handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6631 handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6634 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6635 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6636 "uninitialized is only valid on automatic duration variables");
6637 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
6640 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6641 bool DiagnoseFailure) {
6642 QualType Ty = VD->getType();
6643 if (!Ty->isObjCRetainableType()) {
6644 if (DiagnoseFailure) {
6645 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6651 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6653 // Sema::inferObjCARCLifetime must run after processing decl attributes
6654 // (because __block lowers to an attribute), so if the lifetime hasn't been
6655 // explicitly specified, infer it locally now.
6656 if (LifetimeQual == Qualifiers::OCL_None)
6657 LifetimeQual = Ty->getObjCARCImplicitLifetime();
6659 // The attributes only really makes sense for __strong variables; ignore any
6660 // attempts to annotate a parameter with any other lifetime qualifier.
6661 if (LifetimeQual != Qualifiers::OCL_Strong) {
6662 if (DiagnoseFailure) {
6663 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6669 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6670 // to ensure that the variable is 'const' so that we can error on
6671 // modification, which can otherwise over-release.
6672 VD->setType(Ty.withConst());
6673 VD->setARCPseudoStrong(true);
6677 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6678 const ParsedAttr &AL) {
6679 if (auto *VD = dyn_cast<VarDecl>(D)) {
6680 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6681 if (!VD->hasLocalStorage()) {
6682 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6687 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6690 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6694 // If D is a function-like declaration (method, block, or function), then we
6695 // make every parameter psuedo-strong.
6696 unsigned NumParams =
6697 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
6698 for (unsigned I = 0; I != NumParams; ++I) {
6699 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6700 QualType Ty = PVD->getType();
6702 // If a user wrote a parameter with __strong explicitly, then assume they
6703 // want "real" strong semantics for that parameter. This works because if
6704 // the parameter was written with __strong, then the strong qualifier will
6706 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6707 Qualifiers::OCL_Strong)
6710 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6712 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6715 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6716 // Check that the return type is a `typedef int kern_return_t` or a typedef
6717 // around it, because otherwise MIG convention checks make no sense.
6718 // BlockDecl doesn't store a return type, so it's annoying to check,
6719 // so let's skip it for now.
6720 if (!isa<BlockDecl>(D)) {
6721 QualType T = getFunctionOrMethodResultType(D);
6722 bool IsKernReturnT = false;
6723 while (const auto *TT = T->getAs<TypedefType>()) {
6724 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
6727 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
6728 S.Diag(D->getBeginLoc(),
6729 diag::warn_mig_server_routine_does_not_return_kern_return_t);
6734 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
6737 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6738 // Warn if the return type is not a pointer or reference type.
6739 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6740 QualType RetTy = FD->getReturnType();
6741 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
6742 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
6743 << AL.getRange() << RetTy;
6748 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
6751 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6752 if (AL.isUsedAsTypeAttr())
6754 // Warn if the parameter is definitely not an output parameter.
6755 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
6756 if (PVD->getType()->isIntegerType()) {
6757 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
6763 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
6765 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
6768 template<typename Attr>
6769 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6771 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
6773 D->addAttr(Attr::Create(S.Context, Argument, AL));
6776 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6777 // The guard attribute takes a single identifier argument.
6779 if (!AL.isArgIdent(0)) {
6780 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6781 << AL << AANT_ArgumentIdentifier;
6785 CFGuardAttr::GuardArg Arg;
6786 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6787 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
6788 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6792 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
6795 //===----------------------------------------------------------------------===//
6796 // Top Level Sema Entry Points
6797 //===----------------------------------------------------------------------===//
6799 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6800 /// the attribute applies to decls. If the attribute is a type attribute, just
6801 /// silently ignore it if a GNU attribute.
6802 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6803 const ParsedAttr &AL,
6804 bool IncludeCXX11Attributes) {
6805 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6808 // Ignore C++11 attributes on declarator chunks: they appertain to the type
6810 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6813 // Unknown attributes are automatically warned on. Target-specific attributes
6814 // which do not apply to the current target architecture are treated as
6815 // though they were unknown attributes.
6816 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6817 !AL.existsInTarget(S.Context.getTargetInfo())) {
6819 AL.isDeclspecAttribute()
6820 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6821 : (unsigned)diag::warn_unknown_attribute_ignored)
6826 if (handleCommonAttributeFeatures(S, D, AL))
6829 switch (AL.getKind()) {
6831 if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
6833 if (!AL.isStmtAttr()) {
6834 // Type attributes are handled elsewhere; silently move on.
6835 assert(AL.isTypeAttr() && "Non-type attribute not handled");
6838 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6839 << AL << D->getLocation();
6841 case ParsedAttr::AT_Interrupt:
6842 handleInterruptAttr(S, D, AL);
6844 case ParsedAttr::AT_X86ForceAlignArgPointer:
6845 handleX86ForceAlignArgPointerAttr(S, D, AL);
6847 case ParsedAttr::AT_DLLExport:
6848 case ParsedAttr::AT_DLLImport:
6849 handleDLLAttr(S, D, AL);
6851 case ParsedAttr::AT_Mips16:
6852 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6853 MipsInterruptAttr>(S, D, AL);
6855 case ParsedAttr::AT_MicroMips:
6856 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6858 case ParsedAttr::AT_MipsLongCall:
6859 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6862 case ParsedAttr::AT_MipsShortCall:
6863 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6866 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6867 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6869 case ParsedAttr::AT_AMDGPUWavesPerEU:
6870 handleAMDGPUWavesPerEUAttr(S, D, AL);
6872 case ParsedAttr::AT_AMDGPUNumSGPR:
6873 handleAMDGPUNumSGPRAttr(S, D, AL);
6875 case ParsedAttr::AT_AMDGPUNumVGPR:
6876 handleAMDGPUNumVGPRAttr(S, D, AL);
6878 case ParsedAttr::AT_AVRSignal:
6879 handleAVRSignalAttr(S, D, AL);
6881 case ParsedAttr::AT_BPFPreserveAccessIndex:
6882 handleBPFPreserveAccessIndexAttr(S, D, AL);
6884 case ParsedAttr::AT_WebAssemblyExportName:
6885 handleWebAssemblyExportNameAttr(S, D, AL);
6887 case ParsedAttr::AT_WebAssemblyImportModule:
6888 handleWebAssemblyImportModuleAttr(S, D, AL);
6890 case ParsedAttr::AT_WebAssemblyImportName:
6891 handleWebAssemblyImportNameAttr(S, D, AL);
6893 case ParsedAttr::AT_IBOutlet:
6894 handleIBOutlet(S, D, AL);
6896 case ParsedAttr::AT_IBOutletCollection:
6897 handleIBOutletCollection(S, D, AL);
6899 case ParsedAttr::AT_IFunc:
6900 handleIFuncAttr(S, D, AL);
6902 case ParsedAttr::AT_Alias:
6903 handleAliasAttr(S, D, AL);
6905 case ParsedAttr::AT_Aligned:
6906 handleAlignedAttr(S, D, AL);
6908 case ParsedAttr::AT_AlignValue:
6909 handleAlignValueAttr(S, D, AL);
6911 case ParsedAttr::AT_AllocSize:
6912 handleAllocSizeAttr(S, D, AL);
6914 case ParsedAttr::AT_AlwaysInline:
6915 handleAlwaysInlineAttr(S, D, AL);
6917 case ParsedAttr::AT_AnalyzerNoReturn:
6918 handleAnalyzerNoReturnAttr(S, D, AL);
6920 case ParsedAttr::AT_TLSModel:
6921 handleTLSModelAttr(S, D, AL);
6923 case ParsedAttr::AT_Annotate:
6924 handleAnnotateAttr(S, D, AL);
6926 case ParsedAttr::AT_Availability:
6927 handleAvailabilityAttr(S, D, AL);
6929 case ParsedAttr::AT_CarriesDependency:
6930 handleDependencyAttr(S, scope, D, AL);
6932 case ParsedAttr::AT_CPUDispatch:
6933 case ParsedAttr::AT_CPUSpecific:
6934 handleCPUSpecificAttr(S, D, AL);
6936 case ParsedAttr::AT_Common:
6937 handleCommonAttr(S, D, AL);
6939 case ParsedAttr::AT_CUDAConstant:
6940 handleConstantAttr(S, D, AL);
6942 case ParsedAttr::AT_PassObjectSize:
6943 handlePassObjectSizeAttr(S, D, AL);
6945 case ParsedAttr::AT_Constructor:
6946 if (S.Context.getTargetInfo().getTriple().isOSAIX())
6947 llvm::report_fatal_error(
6948 "'constructor' attribute is not yet supported on AIX");
6950 handleConstructorAttr(S, D, AL);
6952 case ParsedAttr::AT_Deprecated:
6953 handleDeprecatedAttr(S, D, AL);
6955 case ParsedAttr::AT_Destructor:
6956 if (S.Context.getTargetInfo().getTriple().isOSAIX())
6957 llvm::report_fatal_error("'destructor' attribute is not yet supported on AIX");
6959 handleDestructorAttr(S, D, AL);
6961 case ParsedAttr::AT_EnableIf:
6962 handleEnableIfAttr(S, D, AL);
6964 case ParsedAttr::AT_DiagnoseIf:
6965 handleDiagnoseIfAttr(S, D, AL);
6967 case ParsedAttr::AT_NoBuiltin:
6968 handleNoBuiltinAttr(S, D, AL);
6970 case ParsedAttr::AT_ExtVectorType:
6971 handleExtVectorTypeAttr(S, D, AL);
6973 case ParsedAttr::AT_ExternalSourceSymbol:
6974 handleExternalSourceSymbolAttr(S, D, AL);
6976 case ParsedAttr::AT_MinSize:
6977 handleMinSizeAttr(S, D, AL);
6979 case ParsedAttr::AT_OptimizeNone:
6980 handleOptimizeNoneAttr(S, D, AL);
6982 case ParsedAttr::AT_EnumExtensibility:
6983 handleEnumExtensibilityAttr(S, D, AL);
6985 case ParsedAttr::AT_SYCLKernel:
6986 handleSYCLKernelAttr(S, D, AL);
6988 case ParsedAttr::AT_Format:
6989 handleFormatAttr(S, D, AL);
6991 case ParsedAttr::AT_FormatArg:
6992 handleFormatArgAttr(S, D, AL);
6994 case ParsedAttr::AT_Callback:
6995 handleCallbackAttr(S, D, AL);
6997 case ParsedAttr::AT_CUDAGlobal:
6998 handleGlobalAttr(S, D, AL);
7000 case ParsedAttr::AT_CUDADevice:
7001 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
7004 case ParsedAttr::AT_CUDAHost:
7005 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
7007 case ParsedAttr::AT_CUDADeviceBuiltinSurfaceType:
7008 handleSimpleAttributeWithExclusions<CUDADeviceBuiltinSurfaceTypeAttr,
7009 CUDADeviceBuiltinTextureTypeAttr>(S, D,
7012 case ParsedAttr::AT_CUDADeviceBuiltinTextureType:
7013 handleSimpleAttributeWithExclusions<CUDADeviceBuiltinTextureTypeAttr,
7014 CUDADeviceBuiltinSurfaceTypeAttr>(S, D,
7017 case ParsedAttr::AT_GNUInline:
7018 handleGNUInlineAttr(S, D, AL);
7020 case ParsedAttr::AT_CUDALaunchBounds:
7021 handleLaunchBoundsAttr(S, D, AL);
7023 case ParsedAttr::AT_Restrict:
7024 handleRestrictAttr(S, D, AL);
7026 case ParsedAttr::AT_Mode:
7027 handleModeAttr(S, D, AL);
7029 case ParsedAttr::AT_NonNull:
7030 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
7031 handleNonNullAttrParameter(S, PVD, AL);
7033 handleNonNullAttr(S, D, AL);
7035 case ParsedAttr::AT_ReturnsNonNull:
7036 handleReturnsNonNullAttr(S, D, AL);
7038 case ParsedAttr::AT_NoEscape:
7039 handleNoEscapeAttr(S, D, AL);
7041 case ParsedAttr::AT_AssumeAligned:
7042 handleAssumeAlignedAttr(S, D, AL);
7044 case ParsedAttr::AT_AllocAlign:
7045 handleAllocAlignAttr(S, D, AL);
7047 case ParsedAttr::AT_Ownership:
7048 handleOwnershipAttr(S, D, AL);
7050 case ParsedAttr::AT_Cold:
7051 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
7053 case ParsedAttr::AT_Hot:
7054 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
7056 case ParsedAttr::AT_Naked:
7057 handleNakedAttr(S, D, AL);
7059 case ParsedAttr::AT_NoReturn:
7060 handleNoReturnAttr(S, D, AL);
7062 case ParsedAttr::AT_AnyX86NoCfCheck:
7063 handleNoCfCheckAttr(S, D, AL);
7065 case ParsedAttr::AT_NoThrow:
7066 if (!AL.isUsedAsTypeAttr())
7067 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
7069 case ParsedAttr::AT_CUDAShared:
7070 handleSharedAttr(S, D, AL);
7072 case ParsedAttr::AT_VecReturn:
7073 handleVecReturnAttr(S, D, AL);
7075 case ParsedAttr::AT_ObjCOwnership:
7076 handleObjCOwnershipAttr(S, D, AL);
7078 case ParsedAttr::AT_ObjCPreciseLifetime:
7079 handleObjCPreciseLifetimeAttr(S, D, AL);
7081 case ParsedAttr::AT_ObjCReturnsInnerPointer:
7082 handleObjCReturnsInnerPointerAttr(S, D, AL);
7084 case ParsedAttr::AT_ObjCRequiresSuper:
7085 handleObjCRequiresSuperAttr(S, D, AL);
7087 case ParsedAttr::AT_ObjCBridge:
7088 handleObjCBridgeAttr(S, D, AL);
7090 case ParsedAttr::AT_ObjCBridgeMutable:
7091 handleObjCBridgeMutableAttr(S, D, AL);
7093 case ParsedAttr::AT_ObjCBridgeRelated:
7094 handleObjCBridgeRelatedAttr(S, D, AL);
7096 case ParsedAttr::AT_ObjCDesignatedInitializer:
7097 handleObjCDesignatedInitializer(S, D, AL);
7099 case ParsedAttr::AT_ObjCRuntimeName:
7100 handleObjCRuntimeName(S, D, AL);
7102 case ParsedAttr::AT_ObjCBoxable:
7103 handleObjCBoxable(S, D, AL);
7105 case ParsedAttr::AT_CFAuditedTransfer:
7106 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
7107 CFUnknownTransferAttr>(S, D, AL);
7109 case ParsedAttr::AT_CFUnknownTransfer:
7110 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
7111 CFAuditedTransferAttr>(S, D, AL);
7113 case ParsedAttr::AT_CFConsumed:
7114 case ParsedAttr::AT_NSConsumed:
7115 case ParsedAttr::AT_OSConsumed:
7116 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
7117 /*IsTemplateInstantiation=*/false);
7119 case ParsedAttr::AT_OSReturnsRetainedOnZero:
7120 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
7121 S, D, AL, isValidOSObjectOutParameter(D),
7122 diag::warn_ns_attribute_wrong_parameter_type,
7123 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
7125 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
7126 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
7127 S, D, AL, isValidOSObjectOutParameter(D),
7128 diag::warn_ns_attribute_wrong_parameter_type,
7129 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
7131 case ParsedAttr::AT_NSReturnsAutoreleased:
7132 case ParsedAttr::AT_NSReturnsNotRetained:
7133 case ParsedAttr::AT_NSReturnsRetained:
7134 case ParsedAttr::AT_CFReturnsNotRetained:
7135 case ParsedAttr::AT_CFReturnsRetained:
7136 case ParsedAttr::AT_OSReturnsNotRetained:
7137 case ParsedAttr::AT_OSReturnsRetained:
7138 handleXReturnsXRetainedAttr(S, D, AL);
7140 case ParsedAttr::AT_WorkGroupSizeHint:
7141 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
7143 case ParsedAttr::AT_ReqdWorkGroupSize:
7144 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
7146 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
7147 handleSubGroupSize(S, D, AL);
7149 case ParsedAttr::AT_VecTypeHint:
7150 handleVecTypeHint(S, D, AL);
7152 case ParsedAttr::AT_InitPriority:
7153 if (S.Context.getTargetInfo().getTriple().isOSAIX())
7154 llvm::report_fatal_error(
7155 "'init_priority' attribute is not yet supported on AIX");
7157 handleInitPriorityAttr(S, D, AL);
7159 case ParsedAttr::AT_Packed:
7160 handlePackedAttr(S, D, AL);
7162 case ParsedAttr::AT_Section:
7163 handleSectionAttr(S, D, AL);
7165 case ParsedAttr::AT_SpeculativeLoadHardening:
7166 handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
7167 NoSpeculativeLoadHardeningAttr>(S, D,
7170 case ParsedAttr::AT_NoSpeculativeLoadHardening:
7171 handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
7172 SpeculativeLoadHardeningAttr>(S, D, AL);
7174 case ParsedAttr::AT_CodeSeg:
7175 handleCodeSegAttr(S, D, AL);
7177 case ParsedAttr::AT_Target:
7178 handleTargetAttr(S, D, AL);
7180 case ParsedAttr::AT_MinVectorWidth:
7181 handleMinVectorWidthAttr(S, D, AL);
7183 case ParsedAttr::AT_Unavailable:
7184 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
7186 case ParsedAttr::AT_ObjCDirect:
7187 handleObjCDirectAttr(S, D, AL);
7189 case ParsedAttr::AT_ObjCDirectMembers:
7190 handleObjCDirectMembersAttr(S, D, AL);
7191 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
7193 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
7194 handleObjCSuppresProtocolAttr(S, D, AL);
7196 case ParsedAttr::AT_Unused:
7197 handleUnusedAttr(S, D, AL);
7199 case ParsedAttr::AT_NotTailCalled:
7200 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
7203 case ParsedAttr::AT_DisableTailCalls:
7204 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
7207 case ParsedAttr::AT_Visibility:
7208 handleVisibilityAttr(S, D, AL, false);
7210 case ParsedAttr::AT_TypeVisibility:
7211 handleVisibilityAttr(S, D, AL, true);
7213 case ParsedAttr::AT_WarnUnusedResult:
7214 handleWarnUnusedResult(S, D, AL);
7216 case ParsedAttr::AT_WeakRef:
7217 handleWeakRefAttr(S, D, AL);
7219 case ParsedAttr::AT_WeakImport:
7220 handleWeakImportAttr(S, D, AL);
7222 case ParsedAttr::AT_TransparentUnion:
7223 handleTransparentUnionAttr(S, D, AL);
7225 case ParsedAttr::AT_ObjCMethodFamily:
7226 handleObjCMethodFamilyAttr(S, D, AL);
7228 case ParsedAttr::AT_ObjCNSObject:
7229 handleObjCNSObject(S, D, AL);
7231 case ParsedAttr::AT_ObjCIndependentClass:
7232 handleObjCIndependentClass(S, D, AL);
7234 case ParsedAttr::AT_Blocks:
7235 handleBlocksAttr(S, D, AL);
7237 case ParsedAttr::AT_Sentinel:
7238 handleSentinelAttr(S, D, AL);
7240 case ParsedAttr::AT_Cleanup:
7241 handleCleanupAttr(S, D, AL);
7243 case ParsedAttr::AT_NoDebug:
7244 handleNoDebugAttr(S, D, AL);
7246 case ParsedAttr::AT_CmseNSEntry:
7247 handleCmseNSEntryAttr(S, D, AL);
7249 case ParsedAttr::AT_StdCall:
7250 case ParsedAttr::AT_CDecl:
7251 case ParsedAttr::AT_FastCall:
7252 case ParsedAttr::AT_ThisCall:
7253 case ParsedAttr::AT_Pascal:
7254 case ParsedAttr::AT_RegCall:
7255 case ParsedAttr::AT_SwiftCall:
7256 case ParsedAttr::AT_VectorCall:
7257 case ParsedAttr::AT_MSABI:
7258 case ParsedAttr::AT_SysVABI:
7259 case ParsedAttr::AT_Pcs:
7260 case ParsedAttr::AT_IntelOclBicc:
7261 case ParsedAttr::AT_PreserveMost:
7262 case ParsedAttr::AT_PreserveAll:
7263 case ParsedAttr::AT_AArch64VectorPcs:
7264 handleCallConvAttr(S, D, AL);
7266 case ParsedAttr::AT_Suppress:
7267 handleSuppressAttr(S, D, AL);
7269 case ParsedAttr::AT_Owner:
7270 case ParsedAttr::AT_Pointer:
7271 handleLifetimeCategoryAttr(S, D, AL);
7273 case ParsedAttr::AT_OpenCLAccess:
7274 handleOpenCLAccessAttr(S, D, AL);
7276 case ParsedAttr::AT_OpenCLNoSVM:
7277 handleOpenCLNoSVMAttr(S, D, AL);
7279 case ParsedAttr::AT_SwiftContext:
7280 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
7282 case ParsedAttr::AT_SwiftErrorResult:
7283 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
7285 case ParsedAttr::AT_SwiftIndirectResult:
7286 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
7288 case ParsedAttr::AT_InternalLinkage:
7289 handleInternalLinkageAttr(S, D, AL);
7292 // Microsoft attributes:
7293 case ParsedAttr::AT_LayoutVersion:
7294 handleLayoutVersion(S, D, AL);
7296 case ParsedAttr::AT_Uuid:
7297 handleUuidAttr(S, D, AL);
7299 case ParsedAttr::AT_MSInheritance:
7300 handleMSInheritanceAttr(S, D, AL);
7302 case ParsedAttr::AT_Thread:
7303 handleDeclspecThreadAttr(S, D, AL);
7306 case ParsedAttr::AT_AbiTag:
7307 handleAbiTagAttr(S, D, AL);
7309 case ParsedAttr::AT_CFGuard:
7310 handleCFGuardAttr(S, D, AL);
7313 // Thread safety attributes:
7314 case ParsedAttr::AT_AssertExclusiveLock:
7315 handleAssertExclusiveLockAttr(S, D, AL);
7317 case ParsedAttr::AT_AssertSharedLock:
7318 handleAssertSharedLockAttr(S, D, AL);
7320 case ParsedAttr::AT_PtGuardedVar:
7321 handlePtGuardedVarAttr(S, D, AL);
7323 case ParsedAttr::AT_NoSanitize:
7324 handleNoSanitizeAttr(S, D, AL);
7326 case ParsedAttr::AT_NoSanitizeSpecific:
7327 handleNoSanitizeSpecificAttr(S, D, AL);
7329 case ParsedAttr::AT_GuardedBy:
7330 handleGuardedByAttr(S, D, AL);
7332 case ParsedAttr::AT_PtGuardedBy:
7333 handlePtGuardedByAttr(S, D, AL);
7335 case ParsedAttr::AT_ExclusiveTrylockFunction:
7336 handleExclusiveTrylockFunctionAttr(S, D, AL);
7338 case ParsedAttr::AT_LockReturned:
7339 handleLockReturnedAttr(S, D, AL);
7341 case ParsedAttr::AT_LocksExcluded:
7342 handleLocksExcludedAttr(S, D, AL);
7344 case ParsedAttr::AT_SharedTrylockFunction:
7345 handleSharedTrylockFunctionAttr(S, D, AL);
7347 case ParsedAttr::AT_AcquiredBefore:
7348 handleAcquiredBeforeAttr(S, D, AL);
7350 case ParsedAttr::AT_AcquiredAfter:
7351 handleAcquiredAfterAttr(S, D, AL);
7354 // Capability analysis attributes.
7355 case ParsedAttr::AT_Capability:
7356 case ParsedAttr::AT_Lockable:
7357 handleCapabilityAttr(S, D, AL);
7359 case ParsedAttr::AT_RequiresCapability:
7360 handleRequiresCapabilityAttr(S, D, AL);
7363 case ParsedAttr::AT_AssertCapability:
7364 handleAssertCapabilityAttr(S, D, AL);
7366 case ParsedAttr::AT_AcquireCapability:
7367 handleAcquireCapabilityAttr(S, D, AL);
7369 case ParsedAttr::AT_ReleaseCapability:
7370 handleReleaseCapabilityAttr(S, D, AL);
7372 case ParsedAttr::AT_TryAcquireCapability:
7373 handleTryAcquireCapabilityAttr(S, D, AL);
7376 // Consumed analysis attributes.
7377 case ParsedAttr::AT_Consumable:
7378 handleConsumableAttr(S, D, AL);
7380 case ParsedAttr::AT_CallableWhen:
7381 handleCallableWhenAttr(S, D, AL);
7383 case ParsedAttr::AT_ParamTypestate:
7384 handleParamTypestateAttr(S, D, AL);
7386 case ParsedAttr::AT_ReturnTypestate:
7387 handleReturnTypestateAttr(S, D, AL);
7389 case ParsedAttr::AT_SetTypestate:
7390 handleSetTypestateAttr(S, D, AL);
7392 case ParsedAttr::AT_TestTypestate:
7393 handleTestTypestateAttr(S, D, AL);
7396 // Type safety attributes.
7397 case ParsedAttr::AT_ArgumentWithTypeTag:
7398 handleArgumentWithTypeTagAttr(S, D, AL);
7400 case ParsedAttr::AT_TypeTagForDatatype:
7401 handleTypeTagForDatatypeAttr(S, D, AL);
7405 case ParsedAttr::AT_XRayLogArgs:
7406 handleXRayLogArgsAttr(S, D, AL);
7409 case ParsedAttr::AT_PatchableFunctionEntry:
7410 handlePatchableFunctionEntryAttr(S, D, AL);
7413 case ParsedAttr::AT_AlwaysDestroy:
7414 case ParsedAttr::AT_NoDestroy:
7415 handleDestroyAttr(S, D, AL);
7418 case ParsedAttr::AT_Uninitialized:
7419 handleUninitializedAttr(S, D, AL);
7422 case ParsedAttr::AT_LoaderUninitialized:
7423 handleSimpleAttribute<LoaderUninitializedAttr>(S, D, AL);
7426 case ParsedAttr::AT_ObjCExternallyRetained:
7427 handleObjCExternallyRetainedAttr(S, D, AL);
7430 case ParsedAttr::AT_MIGServerRoutine:
7431 handleMIGServerRoutineAttr(S, D, AL);
7434 case ParsedAttr::AT_MSAllocator:
7435 handleMSAllocatorAttr(S, D, AL);
7438 case ParsedAttr::AT_ArmBuiltinAlias:
7439 handleArmBuiltinAliasAttr(S, D, AL);
7442 case ParsedAttr::AT_AcquireHandle:
7443 handleAcquireHandleAttr(S, D, AL);
7446 case ParsedAttr::AT_ReleaseHandle:
7447 handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
7450 case ParsedAttr::AT_UseHandle:
7451 handleHandleAttr<UseHandleAttr>(S, D, AL);
7456 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7457 /// attribute list to the specified decl, ignoring any type attributes.
7458 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7459 const ParsedAttributesView &AttrList,
7460 bool IncludeCXX11Attributes) {
7461 if (AttrList.empty())
7464 for (const ParsedAttr &AL : AttrList)
7465 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7467 // FIXME: We should be able to handle these cases in TableGen.
7469 // static int a9 __attribute__((weakref));
7470 // but that looks really pointless. We reject it.
7471 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7472 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7473 << cast<NamedDecl>(D);
7474 D->dropAttr<WeakRefAttr>();
7478 // FIXME: We should be able to handle this in TableGen as well. It would be
7479 // good to have a way to specify "these attributes must appear as a group",
7480 // for these. Additionally, it would be good to have a way to specify "these
7481 // attribute must never appear as a group" for attributes like cold and hot.
7482 if (!D->hasAttr<OpenCLKernelAttr>()) {
7483 // These attributes cannot be applied to a non-kernel function.
7484 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7485 // FIXME: This emits a different error message than
7486 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7487 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7488 D->setInvalidDecl();
7489 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7490 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7491 D->setInvalidDecl();
7492 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7493 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7494 D->setInvalidDecl();
7495 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7496 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7497 D->setInvalidDecl();
7498 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7499 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7500 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7501 << A << ExpectedKernelFunction;
7502 D->setInvalidDecl();
7503 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7504 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7505 << A << ExpectedKernelFunction;
7506 D->setInvalidDecl();
7507 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7508 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7509 << A << ExpectedKernelFunction;
7510 D->setInvalidDecl();
7511 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7512 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7513 << A << ExpectedKernelFunction;
7514 D->setInvalidDecl();
7519 // Do this check after processing D's attributes because the attribute
7520 // objc_method_family can change whether the given method is in the init
7521 // family, and it can be applied after objc_designated_initializer. This is a
7522 // bit of a hack, but we need it to be compatible with versions of clang that
7523 // processed the attribute list in the wrong order.
7524 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7525 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7526 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7527 D->dropAttr<ObjCDesignatedInitializerAttr>();
7531 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
7533 void Sema::ProcessDeclAttributeDelayed(Decl *D,
7534 const ParsedAttributesView &AttrList) {
7535 for (const ParsedAttr &AL : AttrList)
7536 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7537 handleTransparentUnionAttr(*this, D, AL);
7541 // For BPFPreserveAccessIndexAttr, we want to populate the attributes
7542 // to fields and inner records as well.
7543 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
7544 handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
7547 // Annotation attributes are the only attributes allowed after an access
7549 bool Sema::ProcessAccessDeclAttributeList(
7550 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7551 for (const ParsedAttr &AL : AttrList) {
7552 if (AL.getKind() == ParsedAttr::AT_Annotate) {
7553 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7555 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7562 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7563 /// contains any decl attributes that we should warn about.
7564 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7565 for (const ParsedAttr &AL : A) {
7566 // Only warn if the attribute is an unignored, non-type attribute.
7567 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7569 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7572 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7573 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7574 << AL << AL.getRange();
7576 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7582 /// checkUnusedDeclAttributes - Given a declarator which is not being
7583 /// used to build a declaration, complain about any decl attributes
7584 /// which might be lying around on it.
7585 void Sema::checkUnusedDeclAttributes(Declarator &D) {
7586 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7587 ::checkUnusedDeclAttributes(*this, D.getAttributes());
7588 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7589 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7592 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7593 /// \#pragma weak needs a non-definition decl and source may not have one.
7594 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7595 SourceLocation Loc) {
7596 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7597 NamedDecl *NewD = nullptr;
7598 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7599 FunctionDecl *NewFD;
7600 // FIXME: Missing call to CheckFunctionDeclaration().
7602 // FIXME: Is the qualifier info correct?
7603 // FIXME: Is the DeclContext correct?
7604 NewFD = FunctionDecl::Create(
7605 FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
7606 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
7607 false /*isInlineSpecified*/, FD->hasPrototype(), CSK_unspecified,
7608 FD->getTrailingRequiresClause());
7611 if (FD->getQualifier())
7612 NewFD->setQualifierInfo(FD->getQualifierLoc());
7614 // Fake up parameter variables; they are declared as if this were
7616 QualType FDTy = FD->getType();
7617 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7618 SmallVector<ParmVarDecl*, 16> Params;
7619 for (const auto &AI : FT->param_types()) {
7620 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7621 Param->setScopeInfo(0, Params.size());
7622 Params.push_back(Param);
7624 NewFD->setParams(Params);
7626 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7627 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7628 VD->getInnerLocStart(), VD->getLocation(), II,
7629 VD->getType(), VD->getTypeSourceInfo(),
7630 VD->getStorageClass());
7631 if (VD->getQualifier())
7632 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7637 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7638 /// applied to it, possibly with an alias.
7639 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7640 if (W.getUsed()) return; // only do this once
7642 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7643 IdentifierInfo *NDId = ND->getIdentifier();
7644 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7646 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
7647 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7648 AttributeCommonInfo::AS_Pragma));
7649 WeakTopLevelDecl.push_back(NewD);
7650 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7651 // to insert Decl at TU scope, sorry.
7652 DeclContext *SavedContext = CurContext;
7653 CurContext = Context.getTranslationUnitDecl();
7654 NewD->setDeclContext(CurContext);
7655 NewD->setLexicalDeclContext(CurContext);
7656 PushOnScopeChains(NewD, S);
7657 CurContext = SavedContext;
7658 } else { // just add weak to existing
7659 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7660 AttributeCommonInfo::AS_Pragma));
7664 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7665 // It's valid to "forward-declare" #pragma weak, in which case we
7667 LoadExternalWeakUndeclaredIdentifiers();
7668 if (!WeakUndeclaredIdentifiers.empty()) {
7669 NamedDecl *ND = nullptr;
7670 if (auto *VD = dyn_cast<VarDecl>(D))
7671 if (VD->isExternC())
7673 if (auto *FD = dyn_cast<FunctionDecl>(D))
7674 if (FD->isExternC())
7677 if (IdentifierInfo *Id = ND->getIdentifier()) {
7678 auto I = WeakUndeclaredIdentifiers.find(Id);
7679 if (I != WeakUndeclaredIdentifiers.end()) {
7680 WeakInfo W = I->second;
7681 DeclApplyPragmaWeak(S, ND, W);
7682 WeakUndeclaredIdentifiers[Id] = W;
7689 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7690 /// it, apply them to D. This is a bit tricky because PD can have attributes
7691 /// specified in many different places, and we need to find and apply them all.
7692 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7693 // Apply decl attributes from the DeclSpec if present.
7694 if (!PD.getDeclSpec().getAttributes().empty())
7695 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7697 // Walk the declarator structure, applying decl attributes that were in a type
7698 // position to the decl itself. This handles cases like:
7699 // int *__attr__(x)** D;
7700 // when X is a decl attribute.
7701 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7702 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7703 /*IncludeCXX11Attributes=*/false);
7705 // Finally, apply any attributes on the decl itself.
7706 ProcessDeclAttributeList(S, D, PD.getAttributes());
7708 // Apply additional attributes specified by '#pragma clang attribute'.
7709 AddPragmaAttributes(S, D);
7712 /// Is the given declaration allowed to use a forbidden type?
7713 /// If so, it'll still be annotated with an attribute that makes it
7714 /// illegal to actually use.
7715 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7716 const DelayedDiagnostic &diag,
7717 UnavailableAttr::ImplicitReason &reason) {
7718 // Private ivars are always okay. Unfortunately, people don't
7719 // always properly make their ivars private, even in system headers.
7720 // Plus we need to make fields okay, too.
7721 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7722 !isa<FunctionDecl>(D))
7725 // Silently accept unsupported uses of __weak in both user and system
7726 // declarations when it's been disabled, for ease of integration with
7727 // -fno-objc-arc files. We do have to take some care against attempts
7728 // to define such things; for now, we've only done that for ivars
7730 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7731 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7732 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7733 reason = UnavailableAttr::IR_ForbiddenWeak;
7738 // Allow all sorts of things in system headers.
7739 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7740 // Currently, all the failures dealt with this way are due to ARC
7742 reason = UnavailableAttr::IR_ARCForbiddenType;
7749 /// Handle a delayed forbidden-type diagnostic.
7750 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7752 auto Reason = UnavailableAttr::IR_None;
7753 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7754 assert(Reason && "didn't set reason?");
7755 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7758 if (S.getLangOpts().ObjCAutoRefCount)
7759 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7760 // FIXME: we may want to suppress diagnostics for all
7761 // kind of forbidden type messages on unavailable functions.
7762 if (FD->hasAttr<UnavailableAttr>() &&
7763 DD.getForbiddenTypeDiagnostic() ==
7764 diag::err_arc_array_param_no_ownership) {
7765 DD.Triggered = true;
7770 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7771 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7772 DD.Triggered = true;
7776 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7777 assert(DelayedDiagnostics.getCurrentPool());
7778 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7779 DelayedDiagnostics.popWithoutEmitting(state);
7781 // When delaying diagnostics to run in the context of a parsed
7782 // declaration, we only want to actually emit anything if parsing
7786 // We emit all the active diagnostics in this pool or any of its
7787 // parents. In general, we'll get one pool for the decl spec
7788 // and a child pool for each declarator; in a decl group like:
7789 // deprecated_typedef foo, *bar, baz();
7790 // only the declarator pops will be passed decls. This is correct;
7791 // we really do need to consider delayed diagnostics from the decl spec
7792 // for each of the different declarations.
7793 const DelayedDiagnosticPool *pool = &poppedPool;
7795 bool AnyAccessFailures = false;
7796 for (DelayedDiagnosticPool::pool_iterator
7797 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7798 // This const_cast is a bit lame. Really, Triggered should be mutable.
7799 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7803 switch (diag.Kind) {
7804 case DelayedDiagnostic::Availability:
7805 // Don't bother giving deprecation/unavailable diagnostics if
7806 // the decl is invalid.
7807 if (!decl->isInvalidDecl())
7808 handleDelayedAvailabilityCheck(diag, decl);
7811 case DelayedDiagnostic::Access:
7812 // Only produce one access control diagnostic for a structured binding
7813 // declaration: we don't need to tell the user that all the fields are
7814 // inaccessible one at a time.
7815 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
7817 HandleDelayedAccessCheck(diag, decl);
7819 AnyAccessFailures = true;
7822 case DelayedDiagnostic::ForbiddenType:
7823 handleDelayedForbiddenType(*this, diag, decl);
7827 } while ((pool = pool->getParent()));
7830 /// Given a set of delayed diagnostics, re-emit them as if they had
7831 /// been delayed in the current context instead of in the given pool.
7832 /// Essentially, this just moves them to the current pool.
7833 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7834 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7835 assert(curPool && "re-emitting in undelayed context not supported");
7836 curPool->steal(pool);