[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaDeclAttr.cpp
blobafc9937da0b15cb42853ffcbeec123ee7eaa9f10
1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/Cuda.h"
27 #include "clang/Basic/DarwinSDKInfo.h"
28 #include "clang/Basic/HLSLRuntime.h"
29 #include "clang/Basic/LangOptions.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetBuiltins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedAttr.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/IR/Assumptions.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/Error.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <optional>
52 using namespace clang;
53 using namespace sema;
55 namespace AttributeLangSupport {
56 enum LANG {
58 Cpp,
59 ObjC
61 } // end namespace AttributeLangSupport
63 //===----------------------------------------------------------------------===//
64 // Helper functions
65 //===----------------------------------------------------------------------===//
67 /// isFunctionOrMethod - Return true if the given decl has function
68 /// type (function or function-typed variable) or an Objective-C
69 /// method.
70 static bool isFunctionOrMethod(const Decl *D) {
71 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
74 /// Return true if the given decl has function type (function or
75 /// function-typed variable) or an Objective-C method or a block.
76 static bool isFunctionOrMethodOrBlock(const Decl *D) {
77 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
80 /// Return true if the given decl has a declarator that should have
81 /// been processed by Sema::GetTypeForDeclarator.
82 static bool hasDeclarator(const Decl *D) {
83 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
84 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
85 isa<ObjCPropertyDecl>(D);
88 /// hasFunctionProto - Return true if the given decl has a argument
89 /// information. This decl should have already passed
90 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
91 static bool hasFunctionProto(const Decl *D) {
92 if (const FunctionType *FnTy = D->getFunctionType())
93 return isa<FunctionProtoType>(FnTy);
94 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
97 /// getFunctionOrMethodNumParams - Return number of function or method
98 /// parameters. It is an error to call this on a K&R function (use
99 /// hasFunctionProto first).
100 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
101 if (const FunctionType *FnTy = D->getFunctionType())
102 return cast<FunctionProtoType>(FnTy)->getNumParams();
103 if (const auto *BD = dyn_cast<BlockDecl>(D))
104 return BD->getNumParams();
105 return cast<ObjCMethodDecl>(D)->param_size();
108 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
109 unsigned Idx) {
110 if (const auto *FD = dyn_cast<FunctionDecl>(D))
111 return FD->getParamDecl(Idx);
112 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
113 return MD->getParamDecl(Idx);
114 if (const auto *BD = dyn_cast<BlockDecl>(D))
115 return BD->getParamDecl(Idx);
116 return nullptr;
119 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
120 if (const FunctionType *FnTy = D->getFunctionType())
121 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
122 if (const auto *BD = dyn_cast<BlockDecl>(D))
123 return BD->getParamDecl(Idx)->getType();
125 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
128 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
129 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
130 return PVD->getSourceRange();
131 return SourceRange();
134 static QualType getFunctionOrMethodResultType(const Decl *D) {
135 if (const FunctionType *FnTy = D->getFunctionType())
136 return FnTy->getReturnType();
137 return cast<ObjCMethodDecl>(D)->getReturnType();
140 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
141 if (const auto *FD = dyn_cast<FunctionDecl>(D))
142 return FD->getReturnTypeSourceRange();
143 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
144 return MD->getReturnTypeSourceRange();
145 return SourceRange();
148 static bool isFunctionOrMethodVariadic(const Decl *D) {
149 if (const FunctionType *FnTy = D->getFunctionType())
150 return cast<FunctionProtoType>(FnTy)->isVariadic();
151 if (const auto *BD = dyn_cast<BlockDecl>(D))
152 return BD->isVariadic();
153 return cast<ObjCMethodDecl>(D)->isVariadic();
156 static bool isInstanceMethod(const Decl *D) {
157 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
158 return MethodDecl->isInstance();
159 return false;
162 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
163 bool AllowNSAttributedString = false) {
164 const auto *PT = T->getAs<ObjCObjectPointerType>();
165 if (!PT)
166 return false;
168 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
169 if (!Cls)
170 return false;
172 IdentifierInfo* ClsName = Cls->getIdentifier();
174 if (AllowNSAttributedString &&
175 ClsName == &Ctx.Idents.get("NSAttributedString"))
176 return true;
177 // FIXME: Should we walk the chain of classes?
178 return ClsName == &Ctx.Idents.get("NSString") ||
179 ClsName == &Ctx.Idents.get("NSMutableString");
182 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
183 const auto *PT = T->getAs<PointerType>();
184 if (!PT)
185 return false;
187 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
188 if (!RT)
189 return false;
191 const RecordDecl *RD = RT->getDecl();
192 if (RD->getTagKind() != TTK_Struct)
193 return false;
195 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
198 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
199 // FIXME: Include the type in the argument list.
200 return AL.getNumArgs() + AL.hasParsedType();
203 /// A helper function to provide Attribute Location for the Attr types
204 /// AND the ParsedAttr.
205 template <typename AttrInfo>
206 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
207 getAttrLoc(const AttrInfo &AL) {
208 return AL.getLocation();
210 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
212 /// If Expr is a valid integer constant, get the value of the integer
213 /// expression and return success or failure. May output an error.
215 /// Negative argument is implicitly converted to unsigned, unless
216 /// \p StrictlyUnsigned is true.
217 template <typename AttrInfo>
218 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
219 uint32_t &Val, unsigned Idx = UINT_MAX,
220 bool StrictlyUnsigned = false) {
221 std::optional<llvm::APSInt> I = llvm::APSInt(32);
222 if (Expr->isTypeDependent() ||
223 !(I = Expr->getIntegerConstantExpr(S.Context))) {
224 if (Idx != UINT_MAX)
225 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
226 << &AI << Idx << AANT_ArgumentIntegerConstant
227 << Expr->getSourceRange();
228 else
229 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
230 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
231 return false;
234 if (!I->isIntN(32)) {
235 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
236 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
237 return false;
240 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
241 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
242 << &AI << /*non-negative*/ 1;
243 return false;
246 Val = (uint32_t)I->getZExtValue();
247 return true;
250 /// Wrapper around checkUInt32Argument, with an extra check to be sure
251 /// that the result will fit into a regular (signed) int. All args have the same
252 /// purpose as they do in checkUInt32Argument.
253 template <typename AttrInfo>
254 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
255 int &Val, unsigned Idx = UINT_MAX) {
256 uint32_t UVal;
257 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
258 return false;
260 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
261 llvm::APSInt I(32); // for toString
262 I = UVal;
263 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264 << toString(I, 10, false) << 32 << /* Unsigned */ 0;
265 return false;
268 Val = UVal;
269 return true;
272 /// Diagnose mutually exclusive attributes when present on a given
273 /// declaration. Returns true if diagnosed.
274 template <typename AttrTy>
275 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
276 if (const auto *A = D->getAttr<AttrTy>()) {
277 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
278 << AL << A
279 << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
280 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
281 return true;
283 return false;
286 template <typename AttrTy>
287 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
288 if (const auto *A = D->getAttr<AttrTy>()) {
289 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible)
290 << &AL << A
291 << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
292 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
293 return true;
295 return false;
298 /// Check if IdxExpr is a valid parameter index for a function or
299 /// instance method D. May output an error.
301 /// \returns true if IdxExpr is a valid index.
302 template <typename AttrInfo>
303 static bool checkFunctionOrMethodParameterIndex(
304 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
305 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
306 assert(isFunctionOrMethodOrBlock(D));
308 // In C++ the implicit 'this' function parameter also counts.
309 // Parameters are counted from one.
310 bool HP = hasFunctionProto(D);
311 bool HasImplicitThisParam = isInstanceMethod(D);
312 bool IV = HP && isFunctionOrMethodVariadic(D);
313 unsigned NumParams =
314 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
316 std::optional<llvm::APSInt> IdxInt;
317 if (IdxExpr->isTypeDependent() ||
318 !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
319 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
320 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
321 << IdxExpr->getSourceRange();
322 return false;
325 unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
326 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
327 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
328 << &AI << AttrArgNum << IdxExpr->getSourceRange();
329 return false;
331 if (HasImplicitThisParam && !CanIndexImplicitThis) {
332 if (IdxSource == 1) {
333 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
334 << &AI << IdxExpr->getSourceRange();
335 return false;
339 Idx = ParamIdx(IdxSource, D);
340 return true;
343 /// Check if the argument \p E is a ASCII string literal. If not emit an error
344 /// and return false, otherwise set \p Str to the value of the string literal
345 /// and return true.
346 bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
347 const Expr *E, StringRef &Str,
348 SourceLocation *ArgLocation) {
349 const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts());
350 if (ArgLocation)
351 *ArgLocation = E->getBeginLoc();
353 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
354 Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
355 << CI << AANT_ArgumentString;
356 return false;
359 Str = Literal->getString();
360 return true;
363 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364 /// If not emit an error and return false. If the argument is an identifier it
365 /// will emit an error with a fixit hint and treat it as if it was a string
366 /// literal.
367 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368 StringRef &Str,
369 SourceLocation *ArgLocation) {
370 // Look for identifiers. If we have one emit a hint to fix it to a literal.
371 if (AL.isArgIdent(ArgNum)) {
372 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
373 Diag(Loc->Loc, diag::err_attribute_argument_type)
374 << AL << AANT_ArgumentString
375 << FixItHint::CreateInsertion(Loc->Loc, "\"")
376 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377 Str = Loc->Ident->getName();
378 if (ArgLocation)
379 *ArgLocation = Loc->Loc;
380 return true;
383 // Now check for an actual string literal.
384 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
385 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386 if (ArgLocation)
387 *ArgLocation = ArgExpr->getBeginLoc();
389 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
390 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391 << AL << AANT_ArgumentString;
392 return false;
394 Str = Literal->getString();
395 return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
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) {
409 return 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 @c AttrType to declaration @c D, provided that
421 /// @c PassesCheck is true.
422 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
423 /// specified in @c 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) {
429 if (!PassesCheck) {
430 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
431 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
432 return;
434 handleSimpleAttribute<AttrType>(S, D, CI);
437 /// Check if the passed-in expression is of type int or bool.
438 static bool isIntOrBool(Expr *Exp) {
439 QualType QT = Exp->getType();
440 return QT->isBooleanType() || QT->isIntegerType();
444 // Check to see if the type is a smart pointer of some kind. We assume
445 // it's a smart pointer if it defines both operator-> and operator*.
446 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
447 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
448 OverloadedOperatorKind Op) {
449 DeclContextLookupResult Result =
450 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
451 return !Result.empty();
454 const RecordDecl *Record = RT->getDecl();
455 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
456 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
457 if (foundStarOperator && foundArrowOperator)
458 return true;
460 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
461 if (!CXXRecord)
462 return false;
464 for (const auto &BaseSpecifier : CXXRecord->bases()) {
465 if (!foundStarOperator)
466 foundStarOperator = IsOverloadedOperatorPresent(
467 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
468 if (!foundArrowOperator)
469 foundArrowOperator = IsOverloadedOperatorPresent(
470 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
473 if (foundStarOperator && foundArrowOperator)
474 return true;
476 return false;
479 /// Check if passed in Decl is a pointer type.
480 /// Note that this function may produce an error message.
481 /// \return true if the Decl is a pointer type; false otherwise
482 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
483 const ParsedAttr &AL) {
484 const auto *VD = cast<ValueDecl>(D);
485 QualType QT = VD->getType();
486 if (QT->isAnyPointerType())
487 return true;
489 if (const auto *RT = QT->getAs<RecordType>()) {
490 // If it's an incomplete type, it could be a smart pointer; skip it.
491 // (We don't want to force template instantiation if we can avoid it,
492 // since that would alter the order in which templates are instantiated.)
493 if (RT->isIncompleteType())
494 return true;
496 if (threadSafetyCheckIsSmartPointer(S, RT))
497 return true;
500 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
501 return false;
504 /// Checks that the passed in QualType either is of RecordType or points
505 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
506 static const RecordType *getRecordType(QualType QT) {
507 if (const auto *RT = QT->getAs<RecordType>())
508 return RT;
510 // Now check if we point to record type.
511 if (const auto *PT = QT->getAs<PointerType>())
512 return PT->getPointeeType()->getAs<RecordType>();
514 return nullptr;
517 template <typename AttrType>
518 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
519 // Check if the record itself has the attribute.
520 if (RD->hasAttr<AttrType>())
521 return true;
523 // Else check if any base classes have the attribute.
524 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
525 if (!CRD->forallBases([](const CXXRecordDecl *Base) {
526 return !Base->hasAttr<AttrType>();
528 return true;
530 return false;
533 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
534 const RecordType *RT = getRecordType(Ty);
536 if (!RT)
537 return false;
539 // Don't check for the capability if the class hasn't been defined yet.
540 if (RT->isIncompleteType())
541 return true;
543 // Allow smart pointers to be used as capability objects.
544 // FIXME -- Check the type that the smart pointer points to.
545 if (threadSafetyCheckIsSmartPointer(S, RT))
546 return true;
548 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
551 static bool checkTypedefTypeForCapability(QualType Ty) {
552 const auto *TD = Ty->getAs<TypedefType>();
553 if (!TD)
554 return false;
556 TypedefNameDecl *TN = TD->getDecl();
557 if (!TN)
558 return false;
560 return TN->hasAttr<CapabilityAttr>();
563 static bool typeHasCapability(Sema &S, QualType Ty) {
564 if (checkTypedefTypeForCapability(Ty))
565 return true;
567 if (checkRecordTypeForCapability(S, Ty))
568 return true;
570 return false;
573 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
574 // Capability expressions are simple expressions involving the boolean logic
575 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
576 // a DeclRefExpr is found, its type should be checked to determine whether it
577 // is a capability or not.
579 if (const auto *E = dyn_cast<CastExpr>(Ex))
580 return isCapabilityExpr(S, E->getSubExpr());
581 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
582 return isCapabilityExpr(S, E->getSubExpr());
583 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
584 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
585 E->getOpcode() == UO_Deref)
586 return isCapabilityExpr(S, E->getSubExpr());
587 return false;
588 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
589 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
590 return isCapabilityExpr(S, E->getLHS()) &&
591 isCapabilityExpr(S, E->getRHS());
592 return false;
595 return typeHasCapability(S, Ex->getType());
598 /// Checks that all attribute arguments, starting from Sidx, resolve to
599 /// a capability object.
600 /// \param Sidx The attribute argument index to start checking with.
601 /// \param ParamIdxOk Whether an argument can be indexing into a function
602 /// parameter list.
603 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
604 const ParsedAttr &AL,
605 SmallVectorImpl<Expr *> &Args,
606 unsigned Sidx = 0,
607 bool ParamIdxOk = false) {
608 if (Sidx == AL.getNumArgs()) {
609 // If we don't have any capability arguments, the attribute implicitly
610 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
611 // a non-static method, and that the class is a (scoped) capability.
612 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
613 if (MD && !MD->isStatic()) {
614 const CXXRecordDecl *RD = MD->getParent();
615 // FIXME -- need to check this again on template instantiation
616 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
617 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
618 S.Diag(AL.getLoc(),
619 diag::warn_thread_attribute_not_on_capability_member)
620 << AL << MD->getParent();
621 } else {
622 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
623 << AL;
627 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
628 Expr *ArgExp = AL.getArgAsExpr(Idx);
630 if (ArgExp->isTypeDependent()) {
631 // FIXME -- need to check this again on template instantiation
632 Args.push_back(ArgExp);
633 continue;
636 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
637 if (StrLit->getLength() == 0 ||
638 (StrLit->isOrdinary() && StrLit->getString() == StringRef("*"))) {
639 // Pass empty strings to the analyzer without warnings.
640 // Treat "*" as the universal lock.
641 Args.push_back(ArgExp);
642 continue;
645 // We allow constant strings to be used as a placeholder for expressions
646 // that are not valid C++ syntax, but warn that they are ignored.
647 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
648 Args.push_back(ArgExp);
649 continue;
652 QualType ArgTy = ArgExp->getType();
654 // A pointer to member expression of the form &MyClass::mu is treated
655 // specially -- we need to look at the type of the member.
656 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
657 if (UOp->getOpcode() == UO_AddrOf)
658 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
659 if (DRE->getDecl()->isCXXInstanceMember())
660 ArgTy = DRE->getDecl()->getType();
662 // First see if we can just cast to record type, or pointer to record type.
663 const RecordType *RT = getRecordType(ArgTy);
665 // Now check if we index into a record type function param.
666 if(!RT && ParamIdxOk) {
667 const auto *FD = dyn_cast<FunctionDecl>(D);
668 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
669 if(FD && IL) {
670 unsigned int NumParams = FD->getNumParams();
671 llvm::APInt ArgValue = IL->getValue();
672 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
673 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
674 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
675 S.Diag(AL.getLoc(),
676 diag::err_attribute_argument_out_of_bounds_extra_info)
677 << AL << Idx + 1 << NumParams;
678 continue;
680 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
684 // If the type does not have a capability, see if the components of the
685 // expression have capabilities. This allows for writing C code where the
686 // capability may be on the type, and the expression is a capability
687 // boolean logic expression. Eg) requires_capability(A || B && !C)
688 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
689 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
690 << AL << ArgTy;
692 Args.push_back(ArgExp);
696 //===----------------------------------------------------------------------===//
697 // Attribute Implementations
698 //===----------------------------------------------------------------------===//
700 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
701 if (!threadSafetyCheckIsPointer(S, D, AL))
702 return;
704 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
707 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
708 Expr *&Arg) {
709 SmallVector<Expr *, 1> Args;
710 // check that all arguments are lockable objects
711 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
712 unsigned Size = Args.size();
713 if (Size != 1)
714 return false;
716 Arg = Args[0];
718 return true;
721 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
722 Expr *Arg = nullptr;
723 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
724 return;
726 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
729 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
730 Expr *Arg = nullptr;
731 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
732 return;
734 if (!threadSafetyCheckIsPointer(S, D, AL))
735 return;
737 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
740 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
741 SmallVectorImpl<Expr *> &Args) {
742 if (!AL.checkAtLeastNumArgs(S, 1))
743 return false;
745 // Check that this attribute only applies to lockable types.
746 QualType QT = cast<ValueDecl>(D)->getType();
747 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
748 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
749 return false;
752 // Check that all arguments are lockable objects.
753 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
754 if (Args.empty())
755 return false;
757 return true;
760 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
761 SmallVector<Expr *, 1> Args;
762 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
763 return;
765 Expr **StartArg = &Args[0];
766 D->addAttr(::new (S.Context)
767 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
770 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
771 SmallVector<Expr *, 1> Args;
772 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
773 return;
775 Expr **StartArg = &Args[0];
776 D->addAttr(::new (S.Context)
777 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
780 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
781 SmallVectorImpl<Expr *> &Args) {
782 // zero or more arguments ok
783 // check that all arguments are lockable objects
784 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
786 return true;
789 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
790 SmallVector<Expr *, 1> Args;
791 if (!checkLockFunAttrCommon(S, D, AL, Args))
792 return;
794 unsigned Size = Args.size();
795 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
796 D->addAttr(::new (S.Context)
797 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
800 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
801 const ParsedAttr &AL) {
802 SmallVector<Expr *, 1> Args;
803 if (!checkLockFunAttrCommon(S, D, AL, Args))
804 return;
806 unsigned Size = Args.size();
807 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
808 D->addAttr(::new (S.Context)
809 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
812 /// Checks to be sure that the given parameter number is in bounds, and
813 /// is an integral type. Will emit appropriate diagnostics if this returns
814 /// false.
816 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
817 template <typename AttrInfo>
818 static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
819 unsigned AttrArgNo) {
820 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
821 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
822 ParamIdx Idx;
823 if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
824 Idx))
825 return false;
827 QualType ParamTy = getFunctionOrMethodParamType(D, Idx.getASTIndex());
828 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
829 SourceLocation SrcLoc = AttrArg->getBeginLoc();
830 S.Diag(SrcLoc, diag::err_attribute_integers_only)
831 << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
832 return false;
834 return true;
837 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
838 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
839 return;
841 assert(isFunctionOrMethod(D) && hasFunctionProto(D));
843 QualType RetTy = getFunctionOrMethodResultType(D);
844 if (!RetTy->isPointerType()) {
845 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
846 return;
849 const Expr *SizeExpr = AL.getArgAsExpr(0);
850 int SizeArgNoVal;
851 // Parameter indices are 1-indexed, hence Index=1
852 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
853 return;
854 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
855 return;
856 ParamIdx SizeArgNo(SizeArgNoVal, D);
858 ParamIdx NumberArgNo;
859 if (AL.getNumArgs() == 2) {
860 const Expr *NumberExpr = AL.getArgAsExpr(1);
861 int Val;
862 // Parameter indices are 1-based, hence Index=2
863 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
864 return;
865 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
866 return;
867 NumberArgNo = ParamIdx(Val, D);
870 D->addAttr(::new (S.Context)
871 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
874 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
875 SmallVectorImpl<Expr *> &Args) {
876 if (!AL.checkAtLeastNumArgs(S, 1))
877 return false;
879 if (!isIntOrBool(AL.getArgAsExpr(0))) {
880 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
881 << AL << 1 << AANT_ArgumentIntOrBool;
882 return false;
885 // check that all arguments are lockable objects
886 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
888 return true;
891 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
892 const ParsedAttr &AL) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
895 return;
897 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
898 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
901 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
902 const ParsedAttr &AL) {
903 SmallVector<Expr*, 2> Args;
904 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
905 return;
907 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
908 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
911 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
912 // check that the argument is lockable object
913 SmallVector<Expr*, 1> Args;
914 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
915 unsigned Size = Args.size();
916 if (Size == 0)
917 return;
919 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
922 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
923 if (!AL.checkAtLeastNumArgs(S, 1))
924 return;
926 // check that all arguments are lockable objects
927 SmallVector<Expr*, 1> Args;
928 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
929 unsigned Size = Args.size();
930 if (Size == 0)
931 return;
932 Expr **StartArg = &Args[0];
934 D->addAttr(::new (S.Context)
935 LocksExcludedAttr(S.Context, AL, StartArg, Size));
938 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
939 Expr *&Cond, StringRef &Msg) {
940 Cond = AL.getArgAsExpr(0);
941 if (!Cond->isTypeDependent()) {
942 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
943 if (Converted.isInvalid())
944 return false;
945 Cond = Converted.get();
948 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
949 return false;
951 if (Msg.empty())
952 Msg = "<no message provided>";
954 SmallVector<PartialDiagnosticAt, 8> Diags;
955 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
956 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
957 Diags)) {
958 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
959 for (const PartialDiagnosticAt &PDiag : Diags)
960 S.Diag(PDiag.first, PDiag.second);
961 return false;
963 return true;
966 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
967 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
969 Expr *Cond;
970 StringRef Msg;
971 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
972 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
975 static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
976 StringRef NewUserDiagnostic;
977 if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
978 return;
979 if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
980 D->addAttr(EA);
983 namespace {
984 /// Determines if a given Expr references any of the given function's
985 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
986 class ArgumentDependenceChecker
987 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
988 #ifndef NDEBUG
989 const CXXRecordDecl *ClassType;
990 #endif
991 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
992 bool Result;
994 public:
995 ArgumentDependenceChecker(const FunctionDecl *FD) {
996 #ifndef NDEBUG
997 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
998 ClassType = MD->getParent();
999 else
1000 ClassType = nullptr;
1001 #endif
1002 Parms.insert(FD->param_begin(), FD->param_end());
1005 bool referencesArgs(Expr *E) {
1006 Result = false;
1007 TraverseStmt(E);
1008 return Result;
1011 bool VisitCXXThisExpr(CXXThisExpr *E) {
1012 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1013 "`this` doesn't refer to the enclosing class?");
1014 Result = true;
1015 return false;
1018 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1019 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1020 if (Parms.count(PVD)) {
1021 Result = true;
1022 return false;
1024 return true;
1029 static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
1030 const ParsedAttr &AL) {
1031 const auto *DeclFD = cast<FunctionDecl>(D);
1033 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
1034 if (!MethodDecl->isStatic()) {
1035 S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
1036 return;
1039 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
1040 SourceLocation Loc = [&]() {
1041 auto Union = AL.getArg(Index - 1);
1042 if (Union.is<Expr *>())
1043 return Union.get<Expr *>()->getBeginLoc();
1044 return Union.get<IdentifierLoc *>()->Loc;
1045 }();
1047 S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
1050 FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
1051 if (!AL.isArgExpr(0))
1052 return nullptr;
1053 auto *F = dyn_cast_or_null<DeclRefExpr>(AL.getArgAsExpr(0));
1054 if (!F)
1055 return nullptr;
1056 return dyn_cast_or_null<FunctionDecl>(F->getFoundDecl());
1057 }();
1059 if (!AttrFD || !AttrFD->getBuiltinID(true)) {
1060 DiagnoseType(1, AANT_ArgumentBuiltinFunction);
1061 return;
1064 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
1065 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
1066 << AL << AttrFD << AttrFD->getNumParams();
1067 return;
1070 SmallVector<unsigned, 8> Indices;
1072 for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
1073 if (!AL.isArgExpr(I)) {
1074 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
1075 return;
1078 const Expr *IndexExpr = AL.getArgAsExpr(I);
1079 uint32_t Index;
1081 if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false))
1082 return;
1084 if (Index > DeclFD->getNumParams()) {
1085 S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
1086 << AL << Index << DeclFD << DeclFD->getNumParams();
1087 return;
1090 QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
1091 QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
1093 if (T1.getCanonicalType().getUnqualifiedType() !=
1094 T2.getCanonicalType().getUnqualifiedType()) {
1095 S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
1096 << AL << Index << DeclFD << T2 << I << AttrFD << T1;
1097 return;
1100 Indices.push_back(Index - 1);
1103 D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
1104 S.Context, AL, AttrFD, Indices.data(), Indices.size()));
1107 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1110 Expr *Cond;
1111 StringRef Msg;
1112 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1113 return;
1115 StringRef DiagTypeStr;
1116 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1117 return;
1119 DiagnoseIfAttr::DiagnosticType DiagType;
1120 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1121 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1122 diag::err_diagnose_if_invalid_diagnostic_type);
1123 return;
1126 bool ArgDependent = false;
1127 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1128 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1129 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1130 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1133 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1134 static constexpr const StringRef kWildcard = "*";
1136 llvm::SmallVector<StringRef, 16> Names;
1137 bool HasWildcard = false;
1139 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1140 if (Name == kWildcard)
1141 HasWildcard = true;
1142 Names.push_back(Name);
1145 // Add previously defined attributes.
1146 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1147 for (StringRef BuiltinName : NBA->builtinNames())
1148 AddBuiltinName(BuiltinName);
1150 // Add current attributes.
1151 if (AL.getNumArgs() == 0)
1152 AddBuiltinName(kWildcard);
1153 else
1154 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1155 StringRef BuiltinName;
1156 SourceLocation LiteralLoc;
1157 if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1158 return;
1160 if (Builtin::Context::isBuiltinFunc(BuiltinName))
1161 AddBuiltinName(BuiltinName);
1162 else
1163 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1164 << BuiltinName << AL;
1167 // Repeating the same attribute is fine.
1168 llvm::sort(Names);
1169 Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1171 // Empty no_builtin must be on its own.
1172 if (HasWildcard && Names.size() > 1)
1173 S.Diag(D->getLocation(),
1174 diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1175 << AL;
1177 if (D->hasAttr<NoBuiltinAttr>())
1178 D->dropAttr<NoBuiltinAttr>();
1179 D->addAttr(::new (S.Context)
1180 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1183 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1184 if (D->hasAttr<PassObjectSizeAttr>()) {
1185 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1186 return;
1189 Expr *E = AL.getArgAsExpr(0);
1190 uint32_t Type;
1191 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1192 return;
1194 // pass_object_size's argument is passed in as the second argument of
1195 // __builtin_object_size. So, it has the same constraints as that second
1196 // argument; namely, it must be in the range [0, 3].
1197 if (Type > 3) {
1198 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1199 << AL << 0 << 3 << E->getSourceRange();
1200 return;
1203 // pass_object_size is only supported on constant pointer parameters; as a
1204 // kindness to users, we allow the parameter to be non-const for declarations.
1205 // At this point, we have no clue if `D` belongs to a function declaration or
1206 // definition, so we defer the constness check until later.
1207 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1208 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1209 return;
1212 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1215 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1216 ConsumableAttr::ConsumedState DefaultState;
1218 if (AL.isArgIdent(0)) {
1219 IdentifierLoc *IL = AL.getArgAsIdent(0);
1220 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1221 DefaultState)) {
1222 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1223 << IL->Ident;
1224 return;
1226 } else {
1227 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1228 << AL << AANT_ArgumentIdentifier;
1229 return;
1232 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1235 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1236 const ParsedAttr &AL) {
1237 QualType ThisType = MD->getThisType()->getPointeeType();
1239 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1240 if (!RD->hasAttr<ConsumableAttr>()) {
1241 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1243 return false;
1247 return true;
1250 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 if (!AL.checkAtLeastNumArgs(S, 1))
1252 return;
1254 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1255 return;
1257 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1258 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1259 CallableWhenAttr::ConsumedState CallableState;
1261 StringRef StateString;
1262 SourceLocation Loc;
1263 if (AL.isArgIdent(ArgIndex)) {
1264 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1265 StateString = Ident->Ident->getName();
1266 Loc = Ident->Loc;
1267 } else {
1268 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1269 return;
1272 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1273 CallableState)) {
1274 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1275 return;
1278 States.push_back(CallableState);
1281 D->addAttr(::new (S.Context)
1282 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1285 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1286 ParamTypestateAttr::ConsumedState ParamState;
1288 if (AL.isArgIdent(0)) {
1289 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1290 StringRef StateString = Ident->Ident->getName();
1292 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1293 ParamState)) {
1294 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1295 << AL << StateString;
1296 return;
1298 } else {
1299 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1300 << AL << AANT_ArgumentIdentifier;
1301 return;
1304 // FIXME: This check is currently being done in the analysis. It can be
1305 // enabled here only after the parser propagates attributes at
1306 // template specialization definition, not declaration.
1307 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1308 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1310 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1311 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1312 // ReturnType.getAsString();
1313 // return;
1316 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1319 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1320 ReturnTypestateAttr::ConsumedState ReturnState;
1322 if (AL.isArgIdent(0)) {
1323 IdentifierLoc *IL = AL.getArgAsIdent(0);
1324 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1325 ReturnState)) {
1326 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1327 << IL->Ident;
1328 return;
1330 } else {
1331 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1332 << AL << AANT_ArgumentIdentifier;
1333 return;
1336 // FIXME: This check is currently being done in the analysis. It can be
1337 // enabled here only after the parser propagates attributes at
1338 // template specialization definition, not declaration.
1339 //QualType ReturnType;
1341 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1342 // ReturnType = Param->getType();
1344 //} else if (const CXXConstructorDecl *Constructor =
1345 // dyn_cast<CXXConstructorDecl>(D)) {
1346 // ReturnType = Constructor->getThisType()->getPointeeType();
1348 //} else {
1350 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1353 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1355 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1356 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1357 // ReturnType.getAsString();
1358 // return;
1361 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1364 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1365 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1366 return;
1368 SetTypestateAttr::ConsumedState NewState;
1369 if (AL.isArgIdent(0)) {
1370 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1371 StringRef Param = Ident->Ident->getName();
1372 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1373 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1374 << Param;
1375 return;
1377 } else {
1378 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1379 << AL << AANT_ArgumentIdentifier;
1380 return;
1383 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1386 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1387 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1388 return;
1390 TestTypestateAttr::ConsumedState TestState;
1391 if (AL.isArgIdent(0)) {
1392 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1393 StringRef Param = Ident->Ident->getName();
1394 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1395 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1396 << Param;
1397 return;
1399 } else {
1400 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1401 << AL << AANT_ArgumentIdentifier;
1402 return;
1405 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1408 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1409 // Remember this typedef decl, we will need it later for diagnostics.
1410 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1413 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1414 if (auto *TD = dyn_cast<TagDecl>(D))
1415 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1416 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1417 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1418 !FD->getType()->isIncompleteType() &&
1419 FD->isBitField() &&
1420 S.Context.getTypeAlign(FD->getType()) <= 8);
1422 if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1423 if (BitfieldByteAligned)
1424 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1425 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1426 << AL << FD->getType();
1427 else
1428 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1429 } else {
1430 // Report warning about changed offset in the newer compiler versions.
1431 if (BitfieldByteAligned)
1432 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1434 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1437 } else
1438 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1441 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1442 auto *RD = cast<CXXRecordDecl>(D);
1443 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1444 assert(CTD && "attribute does not appertain to this declaration");
1446 ParsedType PT = AL.getTypeArg();
1447 TypeSourceInfo *TSI = nullptr;
1448 QualType T = S.GetTypeFromParser(PT, &TSI);
1449 if (!TSI)
1450 TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1452 if (!T.hasQualifiers() && T->isTypedefNameType()) {
1453 // Find the template name, if this type names a template specialization.
1454 const TemplateDecl *Template = nullptr;
1455 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1456 T->getAsCXXRecordDecl())) {
1457 Template = CTSD->getSpecializedTemplate();
1458 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1459 while (TST && TST->isTypeAlias())
1460 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1461 if (TST)
1462 Template = TST->getTemplateName().getAsTemplateDecl();
1465 if (Template && declaresSameEntity(Template, CTD)) {
1466 D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1467 return;
1471 S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1472 << T << CTD;
1473 if (const auto *TT = T->getAs<TypedefType>())
1474 S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1475 << TT->getDecl();
1478 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1479 // The IBOutlet/IBOutletCollection attributes only apply to instance
1480 // variables or properties of Objective-C classes. The outlet must also
1481 // have an object reference type.
1482 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1483 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1484 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1485 << AL << VD->getType() << 0;
1486 return false;
1489 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1490 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1491 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1492 << AL << PD->getType() << 1;
1493 return false;
1496 else {
1497 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1498 return false;
1501 return true;
1504 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1505 if (!checkIBOutletCommon(S, D, AL))
1506 return;
1508 D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1511 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1513 // The iboutletcollection attribute can have zero or one arguments.
1514 if (AL.getNumArgs() > 1) {
1515 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1516 return;
1519 if (!checkIBOutletCommon(S, D, AL))
1520 return;
1522 ParsedType PT;
1524 if (AL.hasParsedType())
1525 PT = AL.getTypeArg();
1526 else {
1527 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1528 S.getScopeForContext(D->getDeclContext()->getParent()));
1529 if (!PT) {
1530 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1531 return;
1535 TypeSourceInfo *QTLoc = nullptr;
1536 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1537 if (!QTLoc)
1538 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1540 // Diagnose use of non-object type in iboutletcollection attribute.
1541 // FIXME. Gnu attribute extension ignores use of builtin types in
1542 // attributes. So, __attribute__((iboutletcollection(char))) will be
1543 // treated as __attribute__((iboutletcollection())).
1544 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1545 S.Diag(AL.getLoc(),
1546 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1547 : diag::err_iboutletcollection_type) << QT;
1548 return;
1551 D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1554 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1555 if (RefOkay) {
1556 if (T->isReferenceType())
1557 return true;
1558 } else {
1559 T = T.getNonReferenceType();
1562 // The nonnull attribute, and other similar attributes, can be applied to a
1563 // transparent union that contains a pointer type.
1564 if (const RecordType *UT = T->getAsUnionType()) {
1565 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1566 RecordDecl *UD = UT->getDecl();
1567 for (const auto *I : UD->fields()) {
1568 QualType QT = I->getType();
1569 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1570 return true;
1575 return T->isAnyPointerType() || T->isBlockPointerType();
1578 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1579 SourceRange AttrParmRange,
1580 SourceRange TypeRange,
1581 bool isReturnValue = false) {
1582 if (!S.isValidPointerAttrType(T)) {
1583 if (isReturnValue)
1584 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1585 << AL << AttrParmRange << TypeRange;
1586 else
1587 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588 << AL << AttrParmRange << TypeRange << 0;
1589 return false;
1591 return true;
1594 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1595 SmallVector<ParamIdx, 8> NonNullArgs;
1596 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1597 Expr *Ex = AL.getArgAsExpr(I);
1598 ParamIdx Idx;
1599 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1600 return;
1602 // Is the function argument a pointer type?
1603 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1604 !attrNonNullArgCheck(
1605 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1606 Ex->getSourceRange(),
1607 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1608 continue;
1610 NonNullArgs.push_back(Idx);
1613 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1614 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1615 // check if the attribute came from a macro expansion or a template
1616 // instantiation.
1617 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1618 !S.inTemplateInstantiation()) {
1619 bool AnyPointers = isFunctionOrMethodVariadic(D);
1620 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1621 I != E && !AnyPointers; ++I) {
1622 QualType T = getFunctionOrMethodParamType(D, I);
1623 if (T->isDependentType() || S.isValidPointerAttrType(T))
1624 AnyPointers = true;
1627 if (!AnyPointers)
1628 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1631 ParamIdx *Start = NonNullArgs.data();
1632 unsigned Size = NonNullArgs.size();
1633 llvm::array_pod_sort(Start, Start + Size);
1634 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1637 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1638 const ParsedAttr &AL) {
1639 if (AL.getNumArgs() > 0) {
1640 if (D->getFunctionType()) {
1641 handleNonNullAttr(S, D, AL);
1642 } else {
1643 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1644 << D->getSourceRange();
1646 return;
1649 // Is the argument a pointer type?
1650 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1651 D->getSourceRange()))
1652 return;
1654 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1657 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1658 QualType ResultType = getFunctionOrMethodResultType(D);
1659 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1660 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1661 /* isReturnValue */ true))
1662 return;
1664 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1667 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1668 if (D->isInvalidDecl())
1669 return;
1671 // noescape only applies to pointer types.
1672 QualType T = cast<ParmVarDecl>(D)->getType();
1673 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1674 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1675 << AL << AL.getRange() << 0;
1676 return;
1679 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1682 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1683 Expr *E = AL.getArgAsExpr(0),
1684 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1685 S.AddAssumeAlignedAttr(D, AL, E, OE);
1688 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1689 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1692 void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1693 Expr *OE) {
1694 QualType ResultType = getFunctionOrMethodResultType(D);
1695 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1697 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1698 SourceLocation AttrLoc = TmpAttr.getLocation();
1700 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1701 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1702 << &TmpAttr << TmpAttr.getRange() << SR;
1703 return;
1706 if (!E->isValueDependent()) {
1707 std::optional<llvm::APSInt> I = llvm::APSInt(64);
1708 if (!(I = E->getIntegerConstantExpr(Context))) {
1709 if (OE)
1710 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1711 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1712 << E->getSourceRange();
1713 else
1714 Diag(AttrLoc, diag::err_attribute_argument_type)
1715 << &TmpAttr << AANT_ArgumentIntegerConstant
1716 << E->getSourceRange();
1717 return;
1720 if (!I->isPowerOf2()) {
1721 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1722 << E->getSourceRange();
1723 return;
1726 if (*I > Sema::MaximumAlignment)
1727 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1728 << CI.getRange() << Sema::MaximumAlignment;
1731 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1732 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1733 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1734 << OE->getSourceRange();
1735 return;
1738 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1741 void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1742 Expr *ParamExpr) {
1743 QualType ResultType = getFunctionOrMethodResultType(D);
1745 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1746 SourceLocation AttrLoc = CI.getLoc();
1748 if (!ResultType->isDependentType() &&
1749 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1750 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1751 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1752 return;
1755 ParamIdx Idx;
1756 const auto *FuncDecl = cast<FunctionDecl>(D);
1757 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1758 /*AttrArgNum=*/1, ParamExpr, Idx))
1759 return;
1761 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1762 if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1763 !Ty->isAlignValT()) {
1764 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1765 << &TmpAttr
1766 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1767 return;
1770 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1773 /// Check if \p AssumptionStr is a known assumption and warn if not.
1774 static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
1775 StringRef AssumptionStr) {
1776 if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1777 return;
1779 unsigned BestEditDistance = 3;
1780 StringRef Suggestion;
1781 for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1782 unsigned EditDistance =
1783 AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1784 if (EditDistance < BestEditDistance) {
1785 Suggestion = KnownAssumptionIt.getKey();
1786 BestEditDistance = EditDistance;
1790 if (!Suggestion.empty())
1791 S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1792 << AssumptionStr << Suggestion;
1793 else
1794 S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1797 static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1798 // Handle the case where the attribute has a text message.
1799 StringRef Str;
1800 SourceLocation AttrStrLoc;
1801 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1802 return;
1804 checkAssumptionAttr(S, AttrStrLoc, Str);
1806 D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1809 /// Normalize the attribute, __foo__ becomes foo.
1810 /// Returns true if normalization was applied.
1811 static bool normalizeName(StringRef &AttrName) {
1812 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1813 AttrName.endswith("__")) {
1814 AttrName = AttrName.drop_front(2).drop_back(2);
1815 return true;
1817 return false;
1820 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1821 // This attribute must be applied to a function declaration. The first
1822 // argument to the attribute must be an identifier, the name of the resource,
1823 // for example: malloc. The following arguments must be argument indexes, the
1824 // arguments must be of integer type for Returns, otherwise of pointer type.
1825 // The difference between Holds and Takes is that a pointer may still be used
1826 // after being held. free() should be __attribute((ownership_takes)), whereas
1827 // a list append function may well be __attribute((ownership_holds)).
1829 if (!AL.isArgIdent(0)) {
1830 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1831 << AL << 1 << AANT_ArgumentIdentifier;
1832 return;
1835 // Figure out our Kind.
1836 OwnershipAttr::OwnershipKind K =
1837 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1839 // Check arguments.
1840 switch (K) {
1841 case OwnershipAttr::Takes:
1842 case OwnershipAttr::Holds:
1843 if (AL.getNumArgs() < 2) {
1844 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1845 return;
1847 break;
1848 case OwnershipAttr::Returns:
1849 if (AL.getNumArgs() > 2) {
1850 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1851 return;
1853 break;
1856 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1858 StringRef ModuleName = Module->getName();
1859 if (normalizeName(ModuleName)) {
1860 Module = &S.PP.getIdentifierTable().get(ModuleName);
1863 SmallVector<ParamIdx, 8> OwnershipArgs;
1864 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1865 Expr *Ex = AL.getArgAsExpr(i);
1866 ParamIdx Idx;
1867 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1868 return;
1870 // Is the function argument a pointer type?
1871 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1872 int Err = -1; // No error
1873 switch (K) {
1874 case OwnershipAttr::Takes:
1875 case OwnershipAttr::Holds:
1876 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1877 Err = 0;
1878 break;
1879 case OwnershipAttr::Returns:
1880 if (!T->isIntegerType())
1881 Err = 1;
1882 break;
1884 if (-1 != Err) {
1885 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1886 << Ex->getSourceRange();
1887 return;
1890 // Check we don't have a conflict with another ownership attribute.
1891 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1892 // Cannot have two ownership attributes of different kinds for the same
1893 // index.
1894 if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1895 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1896 << AL << I
1897 << (AL.isRegularKeywordAttribute() ||
1898 I->isRegularKeywordAttribute());
1899 return;
1900 } else if (K == OwnershipAttr::Returns &&
1901 I->getOwnKind() == OwnershipAttr::Returns) {
1902 // A returns attribute conflicts with any other returns attribute using
1903 // a different index.
1904 if (!llvm::is_contained(I->args(), Idx)) {
1905 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1906 << I->args_begin()->getSourceIndex();
1907 if (I->args_size())
1908 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1909 << Idx.getSourceIndex() << Ex->getSourceRange();
1910 return;
1914 OwnershipArgs.push_back(Idx);
1917 ParamIdx *Start = OwnershipArgs.data();
1918 unsigned Size = OwnershipArgs.size();
1919 llvm::array_pod_sort(Start, Start + Size);
1920 D->addAttr(::new (S.Context)
1921 OwnershipAttr(S.Context, AL, Module, Start, Size));
1924 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1925 // Check the attribute arguments.
1926 if (AL.getNumArgs() > 1) {
1927 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1928 return;
1931 // gcc rejects
1932 // class c {
1933 // static int a __attribute__((weakref ("v2")));
1934 // static int b() __attribute__((weakref ("f3")));
1935 // };
1936 // and ignores the attributes of
1937 // void f(void) {
1938 // static int a __attribute__((weakref ("v2")));
1939 // }
1940 // we reject them
1941 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1942 if (!Ctx->isFileContext()) {
1943 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1944 << cast<NamedDecl>(D);
1945 return;
1948 // The GCC manual says
1950 // At present, a declaration to which `weakref' is attached can only
1951 // be `static'.
1953 // It also says
1955 // Without a TARGET,
1956 // given as an argument to `weakref' or to `alias', `weakref' is
1957 // equivalent to `weak'.
1959 // gcc 4.4.1 will accept
1960 // int a7 __attribute__((weakref));
1961 // as
1962 // int a7 __attribute__((weak));
1963 // This looks like a bug in gcc. We reject that for now. We should revisit
1964 // it if this behaviour is actually used.
1966 // GCC rejects
1967 // static ((alias ("y"), weakref)).
1968 // Should we? How to check that weakref is before or after alias?
1970 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1971 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1972 // StringRef parameter it was given anyway.
1973 StringRef Str;
1974 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1975 // GCC will accept anything as the argument of weakref. Should we
1976 // check for an existing decl?
1977 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1979 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1982 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1983 StringRef Str;
1984 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1985 return;
1987 // Aliases should be on declarations, not definitions.
1988 const auto *FD = cast<FunctionDecl>(D);
1989 if (FD->isThisDeclarationADefinition()) {
1990 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1991 return;
1994 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1997 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1998 StringRef Str;
1999 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
2000 return;
2002 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2003 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
2004 return;
2007 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
2008 CudaVersion Version =
2009 ToCudaVersion(S.Context.getTargetInfo().getSDKVersion());
2010 if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
2011 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
2014 // Aliases should be on declarations, not definitions.
2015 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2016 if (FD->isThisDeclarationADefinition()) {
2017 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
2018 return;
2020 } else {
2021 const auto *VD = cast<VarDecl>(D);
2022 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
2023 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
2024 return;
2028 // Mark target used to prevent unneeded-internal-declaration warnings.
2029 if (!S.LangOpts.CPlusPlus) {
2030 // FIXME: demangle Str for C++, as the attribute refers to the mangled
2031 // linkage name, not the pre-mangled identifier.
2032 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
2033 LookupResult LR(S, target, Sema::LookupOrdinaryName);
2034 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
2035 for (NamedDecl *ND : LR)
2036 ND->markUsed(S.Context);
2039 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2042 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2043 StringRef Model;
2044 SourceLocation LiteralLoc;
2045 // Check that it is a string.
2046 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
2047 return;
2049 // Check that the value.
2050 if (Model != "global-dynamic" && Model != "local-dynamic"
2051 && Model != "initial-exec" && Model != "local-exec") {
2052 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
2053 return;
2056 if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
2057 Model != "global-dynamic" && Model != "local-exec") {
2058 S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
2059 return;
2062 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
2065 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2066 QualType ResultType = getFunctionOrMethodResultType(D);
2067 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2068 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2069 return;
2072 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2073 << AL << getFunctionOrMethodResultSourceRange(D);
2076 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2077 // Ensure we don't combine these with themselves, since that causes some
2078 // confusing behavior.
2079 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2080 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2081 return;
2083 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2084 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2085 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2086 return;
2088 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2089 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2090 return;
2092 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2093 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2094 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2095 return;
2099 FunctionDecl *FD = cast<FunctionDecl>(D);
2101 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2102 if (MD->getParent()->isLambda()) {
2103 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2104 return;
2108 if (!AL.checkAtLeastNumArgs(S, 1))
2109 return;
2111 SmallVector<IdentifierInfo *, 8> CPUs;
2112 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2113 if (!AL.isArgIdent(ArgNo)) {
2114 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2115 << AL << AANT_ArgumentIdentifier;
2116 return;
2119 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
2120 StringRef CPUName = CPUArg->Ident->getName().trim();
2122 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
2123 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2124 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2125 return;
2128 const TargetInfo &Target = S.Context.getTargetInfo();
2129 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
2130 return Target.CPUSpecificManglingCharacter(CPUName) ==
2131 Target.CPUSpecificManglingCharacter(Cur->getName());
2132 })) {
2133 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2134 return;
2136 CPUs.push_back(CPUArg->Ident);
2139 FD->setIsMultiVersion(true);
2140 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2141 D->addAttr(::new (S.Context)
2142 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2143 else
2144 D->addAttr(::new (S.Context)
2145 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2148 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2149 if (S.LangOpts.CPlusPlus) {
2150 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2151 << AL << AttributeLangSupport::Cpp;
2152 return;
2155 D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2158 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2159 if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2160 S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2161 return;
2164 const auto *FD = cast<FunctionDecl>(D);
2165 if (!FD->isExternallyVisible()) {
2166 S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2167 return;
2170 D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2173 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2174 if (AL.isDeclspecAttribute()) {
2175 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2176 const auto &Arch = Triple.getArch();
2177 if (Arch != llvm::Triple::x86 &&
2178 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2179 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2180 << AL << Triple.getArchName();
2181 return;
2184 // This form is not allowed to be written on a member function (static or
2185 // nonstatic) when in Microsoft compatibility mode.
2186 if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
2187 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
2188 << AL << AL.isRegularKeywordAttribute() << "non-member functions";
2189 return;
2193 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2196 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2197 if (hasDeclarator(D)) return;
2199 if (!isa<ObjCMethodDecl>(D)) {
2200 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2201 << Attrs << Attrs.isRegularKeywordAttribute()
2202 << ExpectedFunctionOrMethod;
2203 return;
2206 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2209 static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2210 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2211 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2212 // attribute name comes from a macro expansion. We don't want to punish users
2213 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2214 // is defined as a macro which expands to '_Noreturn').
2215 if (!S.getLangOpts().CPlusPlus &&
2216 A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
2217 !(A.getLoc().isMacroID() &&
2218 S.getSourceManager().isInSystemMacro(A.getLoc())))
2219 S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
2221 D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2224 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2225 if (!S.getLangOpts().CFProtectionBranch)
2226 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2227 else
2228 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2231 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2232 if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2233 Attrs.setInvalid();
2234 return true;
2237 return false;
2240 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2241 // Check whether the attribute is valid on the current target.
2242 if (!AL.existsInTarget(Context.getTargetInfo())) {
2243 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
2244 ? diag::err_keyword_not_supported_on_target
2245 : diag::warn_unknown_attribute_ignored)
2246 << AL << AL.getRange();
2247 AL.setInvalid();
2248 return true;
2251 return false;
2254 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2256 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2257 // because 'analyzer_noreturn' does not impact the type.
2258 if (!isFunctionOrMethodOrBlock(D)) {
2259 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2260 if (!VD || (!VD->getType()->isBlockPointerType() &&
2261 !VD->getType()->isFunctionPointerType())) {
2262 S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax()
2263 ? diag::err_attribute_wrong_decl_type
2264 : diag::warn_attribute_wrong_decl_type)
2265 << AL << AL.isRegularKeywordAttribute()
2266 << ExpectedFunctionMethodOrBlock;
2267 return;
2271 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2274 // PS3 PPU-specific.
2275 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2277 Returning a Vector Class in Registers
2279 According to the PPU ABI specifications, a class with a single member of
2280 vector type is returned in memory when used as the return value of a
2281 function.
2282 This results in inefficient code when implementing vector classes. To return
2283 the value in a single vector register, add the vecreturn attribute to the
2284 class definition. This attribute is also applicable to struct types.
2286 Example:
2288 struct Vector
2290 __vector float xyzw;
2291 } __attribute__((vecreturn));
2293 Vector Add(Vector lhs, Vector rhs)
2295 Vector result;
2296 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2297 return result; // This will be returned in a register
2300 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2301 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2302 return;
2305 const auto *R = cast<RecordDecl>(D);
2306 int count = 0;
2308 if (!isa<CXXRecordDecl>(R)) {
2309 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2310 return;
2313 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2314 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2315 return;
2318 for (const auto *I : R->fields()) {
2319 if ((count == 1) || !I->getType()->isVectorType()) {
2320 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2321 return;
2323 count++;
2326 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2329 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2330 const ParsedAttr &AL) {
2331 if (isa<ParmVarDecl>(D)) {
2332 // [[carries_dependency]] can only be applied to a parameter if it is a
2333 // parameter of a function declaration or lambda.
2334 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2335 S.Diag(AL.getLoc(),
2336 diag::err_carries_dependency_param_not_function_decl);
2337 return;
2341 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2344 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2345 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2347 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2348 // about using it as an extension.
2349 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2350 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2352 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2355 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2356 uint32_t priority = ConstructorAttr::DefaultPriority;
2357 if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2358 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2359 return;
2361 if (AL.getNumArgs() &&
2362 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2363 return;
2365 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2368 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2369 uint32_t priority = DestructorAttr::DefaultPriority;
2370 if (AL.getNumArgs() &&
2371 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2372 return;
2374 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2377 template <typename AttrTy>
2378 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2379 // Handle the case where the attribute has a text message.
2380 StringRef Str;
2381 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2382 return;
2384 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2387 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2388 const ParsedAttr &AL) {
2389 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2390 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2391 << AL << AL.getRange();
2392 return;
2395 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2398 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2399 IdentifierInfo *Platform,
2400 VersionTuple Introduced,
2401 VersionTuple Deprecated,
2402 VersionTuple Obsoleted) {
2403 StringRef PlatformName
2404 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2405 if (PlatformName.empty())
2406 PlatformName = Platform->getName();
2408 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2409 // of these steps are needed).
2410 if (!Introduced.empty() && !Deprecated.empty() &&
2411 !(Introduced <= Deprecated)) {
2412 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2413 << 1 << PlatformName << Deprecated.getAsString()
2414 << 0 << Introduced.getAsString();
2415 return true;
2418 if (!Introduced.empty() && !Obsoleted.empty() &&
2419 !(Introduced <= Obsoleted)) {
2420 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2421 << 2 << PlatformName << Obsoleted.getAsString()
2422 << 0 << Introduced.getAsString();
2423 return true;
2426 if (!Deprecated.empty() && !Obsoleted.empty() &&
2427 !(Deprecated <= Obsoleted)) {
2428 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2429 << 2 << PlatformName << Obsoleted.getAsString()
2430 << 1 << Deprecated.getAsString();
2431 return true;
2434 return false;
2437 /// Check whether the two versions match.
2439 /// If either version tuple is empty, then they are assumed to match. If
2440 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2441 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2442 bool BeforeIsOkay) {
2443 if (X.empty() || Y.empty())
2444 return true;
2446 if (X == Y)
2447 return true;
2449 if (BeforeIsOkay && X < Y)
2450 return true;
2452 return false;
2455 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2456 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2457 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2458 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2459 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2460 int Priority) {
2461 VersionTuple MergedIntroduced = Introduced;
2462 VersionTuple MergedDeprecated = Deprecated;
2463 VersionTuple MergedObsoleted = Obsoleted;
2464 bool FoundAny = false;
2465 bool OverrideOrImpl = false;
2466 switch (AMK) {
2467 case AMK_None:
2468 case AMK_Redeclaration:
2469 OverrideOrImpl = false;
2470 break;
2472 case AMK_Override:
2473 case AMK_ProtocolImplementation:
2474 case AMK_OptionalProtocolImplementation:
2475 OverrideOrImpl = true;
2476 break;
2479 if (D->hasAttrs()) {
2480 AttrVec &Attrs = D->getAttrs();
2481 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2482 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2483 if (!OldAA) {
2484 ++i;
2485 continue;
2488 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2489 if (OldPlatform != Platform) {
2490 ++i;
2491 continue;
2494 // If there is an existing availability attribute for this platform that
2495 // has a lower priority use the existing one and discard the new
2496 // attribute.
2497 if (OldAA->getPriority() < Priority)
2498 return nullptr;
2500 // If there is an existing attribute for this platform that has a higher
2501 // priority than the new attribute then erase the old one and continue
2502 // processing the attributes.
2503 if (OldAA->getPriority() > Priority) {
2504 Attrs.erase(Attrs.begin() + i);
2505 --e;
2506 continue;
2509 FoundAny = true;
2510 VersionTuple OldIntroduced = OldAA->getIntroduced();
2511 VersionTuple OldDeprecated = OldAA->getDeprecated();
2512 VersionTuple OldObsoleted = OldAA->getObsoleted();
2513 bool OldIsUnavailable = OldAA->getUnavailable();
2515 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2516 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2517 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2518 !(OldIsUnavailable == IsUnavailable ||
2519 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2520 if (OverrideOrImpl) {
2521 int Which = -1;
2522 VersionTuple FirstVersion;
2523 VersionTuple SecondVersion;
2524 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2525 Which = 0;
2526 FirstVersion = OldIntroduced;
2527 SecondVersion = Introduced;
2528 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2529 Which = 1;
2530 FirstVersion = Deprecated;
2531 SecondVersion = OldDeprecated;
2532 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2533 Which = 2;
2534 FirstVersion = Obsoleted;
2535 SecondVersion = OldObsoleted;
2538 if (Which == -1) {
2539 Diag(OldAA->getLocation(),
2540 diag::warn_mismatched_availability_override_unavail)
2541 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2542 << (AMK == AMK_Override);
2543 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2544 // Allow different 'introduced' / 'obsoleted' availability versions
2545 // on a method that implements an optional protocol requirement. It
2546 // makes less sense to allow this for 'deprecated' as the user can't
2547 // see if the method is 'deprecated' as 'respondsToSelector' will
2548 // still return true when the method is deprecated.
2549 ++i;
2550 continue;
2551 } else {
2552 Diag(OldAA->getLocation(),
2553 diag::warn_mismatched_availability_override)
2554 << Which
2555 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2556 << FirstVersion.getAsString() << SecondVersion.getAsString()
2557 << (AMK == AMK_Override);
2559 if (AMK == AMK_Override)
2560 Diag(CI.getLoc(), diag::note_overridden_method);
2561 else
2562 Diag(CI.getLoc(), diag::note_protocol_method);
2563 } else {
2564 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2565 Diag(CI.getLoc(), diag::note_previous_attribute);
2568 Attrs.erase(Attrs.begin() + i);
2569 --e;
2570 continue;
2573 VersionTuple MergedIntroduced2 = MergedIntroduced;
2574 VersionTuple MergedDeprecated2 = MergedDeprecated;
2575 VersionTuple MergedObsoleted2 = MergedObsoleted;
2577 if (MergedIntroduced2.empty())
2578 MergedIntroduced2 = OldIntroduced;
2579 if (MergedDeprecated2.empty())
2580 MergedDeprecated2 = OldDeprecated;
2581 if (MergedObsoleted2.empty())
2582 MergedObsoleted2 = OldObsoleted;
2584 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2585 MergedIntroduced2, MergedDeprecated2,
2586 MergedObsoleted2)) {
2587 Attrs.erase(Attrs.begin() + i);
2588 --e;
2589 continue;
2592 MergedIntroduced = MergedIntroduced2;
2593 MergedDeprecated = MergedDeprecated2;
2594 MergedObsoleted = MergedObsoleted2;
2595 ++i;
2599 if (FoundAny &&
2600 MergedIntroduced == Introduced &&
2601 MergedDeprecated == Deprecated &&
2602 MergedObsoleted == Obsoleted)
2603 return nullptr;
2605 // Only create a new attribute if !OverrideOrImpl, but we want to do
2606 // the checking.
2607 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2608 MergedDeprecated, MergedObsoleted) &&
2609 !OverrideOrImpl) {
2610 auto *Avail = ::new (Context) AvailabilityAttr(
2611 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2612 Message, IsStrict, Replacement, Priority);
2613 Avail->setImplicit(Implicit);
2614 return Avail;
2616 return nullptr;
2619 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2620 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2621 D)) {
2622 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2623 << AL;
2624 return;
2627 if (!AL.checkExactlyNumArgs(S, 1))
2628 return;
2629 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2631 IdentifierInfo *II = Platform->Ident;
2632 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2633 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2634 << Platform->Ident;
2636 auto *ND = dyn_cast<NamedDecl>(D);
2637 if (!ND) // We warned about this already, so just return.
2638 return;
2640 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2641 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2642 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2643 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2644 bool IsStrict = AL.getStrictLoc().isValid();
2645 StringRef Str;
2646 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2647 Str = SE->getString();
2648 StringRef Replacement;
2649 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2650 Replacement = SE->getString();
2652 if (II->isStr("swift")) {
2653 if (Introduced.isValid() || Obsoleted.isValid() ||
2654 (!IsUnavailable && !Deprecated.isValid())) {
2655 S.Diag(AL.getLoc(),
2656 diag::warn_availability_swift_unavailable_deprecated_only);
2657 return;
2661 if (II->isStr("fuchsia")) {
2662 std::optional<unsigned> Min, Sub;
2663 if ((Min = Introduced.Version.getMinor()) ||
2664 (Sub = Introduced.Version.getSubminor())) {
2665 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2666 return;
2670 int PriorityModifier = AL.isPragmaClangAttribute()
2671 ? Sema::AP_PragmaClangAttribute
2672 : Sema::AP_Explicit;
2673 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2674 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2675 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2676 Sema::AMK_None, PriorityModifier);
2677 if (NewAttr)
2678 D->addAttr(NewAttr);
2680 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2681 // matches before the start of the watchOS platform.
2682 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2683 IdentifierInfo *NewII = nullptr;
2684 if (II->getName() == "ios")
2685 NewII = &S.Context.Idents.get("watchos");
2686 else if (II->getName() == "ios_app_extension")
2687 NewII = &S.Context.Idents.get("watchos_app_extension");
2689 if (NewII) {
2690 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2691 const auto *IOSToWatchOSMapping =
2692 SDKInfo ? SDKInfo->getVersionMapping(
2693 DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
2694 : nullptr;
2696 auto adjustWatchOSVersion =
2697 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2698 if (Version.empty())
2699 return Version;
2700 auto MinimumWatchOSVersion = VersionTuple(2, 0);
2702 if (IOSToWatchOSMapping) {
2703 if (auto MappedVersion = IOSToWatchOSMapping->map(
2704 Version, MinimumWatchOSVersion, std::nullopt)) {
2705 return *MappedVersion;
2709 auto Major = Version.getMajor();
2710 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2711 if (NewMajor >= 2) {
2712 if (Version.getMinor()) {
2713 if (Version.getSubminor())
2714 return VersionTuple(NewMajor, *Version.getMinor(),
2715 *Version.getSubminor());
2716 else
2717 return VersionTuple(NewMajor, *Version.getMinor());
2719 return VersionTuple(NewMajor);
2722 return MinimumWatchOSVersion;
2725 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2726 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2727 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2729 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2730 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2731 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2732 Sema::AMK_None,
2733 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2734 if (NewAttr)
2735 D->addAttr(NewAttr);
2737 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2738 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2739 // matches before the start of the tvOS platform.
2740 IdentifierInfo *NewII = nullptr;
2741 if (II->getName() == "ios")
2742 NewII = &S.Context.Idents.get("tvos");
2743 else if (II->getName() == "ios_app_extension")
2744 NewII = &S.Context.Idents.get("tvos_app_extension");
2746 if (NewII) {
2747 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2748 const auto *IOSToTvOSMapping =
2749 SDKInfo ? SDKInfo->getVersionMapping(
2750 DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
2751 : nullptr;
2753 auto AdjustTvOSVersion =
2754 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2755 if (Version.empty())
2756 return Version;
2758 if (IOSToTvOSMapping) {
2759 if (auto MappedVersion = IOSToTvOSMapping->map(
2760 Version, VersionTuple(0, 0), std::nullopt)) {
2761 return *MappedVersion;
2764 return Version;
2767 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2768 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2769 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2771 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2772 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2773 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2774 Sema::AMK_None,
2775 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2776 if (NewAttr)
2777 D->addAttr(NewAttr);
2779 } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2780 llvm::Triple::IOS &&
2781 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2782 auto GetSDKInfo = [&]() {
2783 return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
2784 "macOS");
2787 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2788 IdentifierInfo *NewII = nullptr;
2789 if (II->getName() == "ios")
2790 NewII = &S.Context.Idents.get("maccatalyst");
2791 else if (II->getName() == "ios_app_extension")
2792 NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2793 if (NewII) {
2794 auto MinMacCatalystVersion = [](const VersionTuple &V) {
2795 if (V.empty())
2796 return V;
2797 if (V.getMajor() < 13 ||
2798 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2799 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2800 return V;
2802 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2803 ND, AL, NewII, true /*Implicit*/,
2804 MinMacCatalystVersion(Introduced.Version),
2805 MinMacCatalystVersion(Deprecated.Version),
2806 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2807 IsStrict, Replacement, Sema::AMK_None,
2808 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2809 if (NewAttr)
2810 D->addAttr(NewAttr);
2811 } else if (II->getName() == "macos" && GetSDKInfo() &&
2812 (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2813 !Obsoleted.Version.empty())) {
2814 if (const auto *MacOStoMacCatalystMapping =
2815 GetSDKInfo()->getVersionMapping(
2816 DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2817 // Infer Mac Catalyst availability from the macOS availability attribute
2818 // if it has versioned availability. Don't infer 'unavailable'. This
2819 // inferred availability has lower priority than the other availability
2820 // attributes that are inferred from 'ios'.
2821 NewII = &S.Context.Idents.get("maccatalyst");
2822 auto RemapMacOSVersion =
2823 [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2824 if (V.empty())
2825 return std::nullopt;
2826 // API_TO_BE_DEPRECATED is 100000.
2827 if (V.getMajor() == 100000)
2828 return VersionTuple(100000);
2829 // The minimum iosmac version is 13.1
2830 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1),
2831 std::nullopt);
2833 std::optional<VersionTuple> NewIntroduced =
2834 RemapMacOSVersion(Introduced.Version),
2835 NewDeprecated =
2836 RemapMacOSVersion(Deprecated.Version),
2837 NewObsoleted =
2838 RemapMacOSVersion(Obsoleted.Version);
2839 if (NewIntroduced || NewDeprecated || NewObsoleted) {
2840 auto VersionOrEmptyVersion =
2841 [](const std::optional<VersionTuple> &V) -> VersionTuple {
2842 return V ? *V : VersionTuple();
2844 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2845 ND, AL, NewII, true /*Implicit*/,
2846 VersionOrEmptyVersion(NewIntroduced),
2847 VersionOrEmptyVersion(NewDeprecated),
2848 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2849 IsStrict, Replacement, Sema::AMK_None,
2850 PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2851 Sema::AP_InferredFromOtherPlatform);
2852 if (NewAttr)
2853 D->addAttr(NewAttr);
2860 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2861 const ParsedAttr &AL) {
2862 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 4))
2863 return;
2865 StringRef Language;
2866 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2867 Language = SE->getString();
2868 StringRef DefinedIn;
2869 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2870 DefinedIn = SE->getString();
2871 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2872 StringRef USR;
2873 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(3)))
2874 USR = SE->getString();
2876 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2877 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
2880 template <class T>
2881 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2882 typename T::VisibilityType value) {
2883 T *existingAttr = D->getAttr<T>();
2884 if (existingAttr) {
2885 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2886 if (existingValue == value)
2887 return nullptr;
2888 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2889 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2890 D->dropAttr<T>();
2892 return ::new (S.Context) T(S.Context, CI, value);
2895 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2896 const AttributeCommonInfo &CI,
2897 VisibilityAttr::VisibilityType Vis) {
2898 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2901 TypeVisibilityAttr *
2902 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2903 TypeVisibilityAttr::VisibilityType Vis) {
2904 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2907 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2908 bool isTypeVisibility) {
2909 // Visibility attributes don't mean anything on a typedef.
2910 if (isa<TypedefNameDecl>(D)) {
2911 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2912 return;
2915 // 'type_visibility' can only go on a type or namespace.
2916 if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
2917 isa<NamespaceDecl>(D))) {
2918 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2919 << AL << AL.isRegularKeywordAttribute() << ExpectedTypeOrNamespace;
2920 return;
2923 // Check that the argument is a string literal.
2924 StringRef TypeStr;
2925 SourceLocation LiteralLoc;
2926 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2927 return;
2929 VisibilityAttr::VisibilityType type;
2930 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2931 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2932 << TypeStr;
2933 return;
2936 // Complain about attempts to use protected visibility on targets
2937 // (like Darwin) that don't support it.
2938 if (type == VisibilityAttr::Protected &&
2939 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2940 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2941 type = VisibilityAttr::Default;
2944 Attr *newAttr;
2945 if (isTypeVisibility) {
2946 newAttr = S.mergeTypeVisibilityAttr(
2947 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2948 } else {
2949 newAttr = S.mergeVisibilityAttr(D, AL, type);
2951 if (newAttr)
2952 D->addAttr(newAttr);
2955 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2956 // objc_direct cannot be set on methods declared in the context of a protocol
2957 if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2958 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2959 return;
2962 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2963 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2964 } else {
2965 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2969 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2970 const ParsedAttr &AL) {
2971 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2972 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2973 } else {
2974 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2978 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2979 const auto *M = cast<ObjCMethodDecl>(D);
2980 if (!AL.isArgIdent(0)) {
2981 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2982 << AL << 1 << AANT_ArgumentIdentifier;
2983 return;
2986 IdentifierLoc *IL = AL.getArgAsIdent(0);
2987 ObjCMethodFamilyAttr::FamilyKind F;
2988 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2989 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2990 return;
2993 if (F == ObjCMethodFamilyAttr::OMF_init &&
2994 !M->getReturnType()->isObjCObjectPointerType()) {
2995 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2996 << M->getReturnType();
2997 // Ignore the attribute.
2998 return;
3001 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
3004 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
3005 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3006 QualType T = TD->getUnderlyingType();
3007 if (!T->isCARCBridgableType()) {
3008 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
3009 return;
3012 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
3013 QualType T = PD->getType();
3014 if (!T->isCARCBridgableType()) {
3015 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
3016 return;
3019 else {
3020 // It is okay to include this attribute on properties, e.g.:
3022 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
3024 // In this case it follows tradition and suppresses an error in the above
3025 // case.
3026 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
3028 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
3031 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
3032 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3033 QualType T = TD->getUnderlyingType();
3034 if (!T->isObjCObjectPointerType()) {
3035 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
3036 return;
3038 } else {
3039 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
3040 return;
3042 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
3045 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3046 if (!AL.isArgIdent(0)) {
3047 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3048 << AL << 1 << AANT_ArgumentIdentifier;
3049 return;
3052 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3053 BlocksAttr::BlockType type;
3054 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
3055 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3056 return;
3059 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
3062 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3063 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3064 if (AL.getNumArgs() > 0) {
3065 Expr *E = AL.getArgAsExpr(0);
3066 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3067 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3068 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3069 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3070 return;
3073 if (Idx->isSigned() && Idx->isNegative()) {
3074 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
3075 << E->getSourceRange();
3076 return;
3079 sentinel = Idx->getZExtValue();
3082 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3083 if (AL.getNumArgs() > 1) {
3084 Expr *E = AL.getArgAsExpr(1);
3085 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3086 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3087 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3088 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3089 return;
3091 nullPos = Idx->getZExtValue();
3093 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3094 // FIXME: This error message could be improved, it would be nice
3095 // to say what the bounds actually are.
3096 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
3097 << E->getSourceRange();
3098 return;
3102 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3103 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3104 if (isa<FunctionNoProtoType>(FT)) {
3105 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
3106 return;
3109 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3110 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3111 return;
3113 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
3114 if (!MD->isVariadic()) {
3115 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3116 return;
3118 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3119 if (!BD->isVariadic()) {
3120 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
3121 return;
3123 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
3124 QualType Ty = V->getType();
3125 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3126 const FunctionType *FT = Ty->isFunctionPointerType()
3127 ? D->getFunctionType()
3128 : Ty->castAs<BlockPointerType>()
3129 ->getPointeeType()
3130 ->castAs<FunctionType>();
3131 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3132 int m = Ty->isFunctionPointerType() ? 0 : 1;
3133 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
3134 return;
3136 } else {
3137 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3138 << AL << AL.isRegularKeywordAttribute()
3139 << ExpectedFunctionMethodOrBlock;
3140 return;
3142 } else {
3143 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3144 << AL << AL.isRegularKeywordAttribute()
3145 << ExpectedFunctionMethodOrBlock;
3146 return;
3148 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3151 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3152 if (D->getFunctionType() &&
3153 D->getFunctionType()->getReturnType()->isVoidType() &&
3154 !isa<CXXConstructorDecl>(D)) {
3155 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
3156 return;
3158 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
3159 if (MD->getReturnType()->isVoidType()) {
3160 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
3161 return;
3164 StringRef Str;
3165 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
3166 // The standard attribute cannot be applied to variable declarations such
3167 // as a function pointer.
3168 if (isa<VarDecl>(D))
3169 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
3170 << AL << AL.isRegularKeywordAttribute()
3171 << "functions, classes, or enumerations";
3173 // If this is spelled as the standard C++17 attribute, but not in C++17,
3174 // warn about using it as an extension. If there are attribute arguments,
3175 // then claim it's a C++20 extension instead.
3176 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3177 // extension warning for C23 mode.
3178 const LangOptions &LO = S.getLangOpts();
3179 if (AL.getNumArgs() == 1) {
3180 if (LO.CPlusPlus && !LO.CPlusPlus20)
3181 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
3183 // Since this is spelled [[nodiscard]], get the optional string
3184 // literal. If in C++ mode, but not in C++20 mode, diagnose as an
3185 // extension.
3186 // FIXME: C23 should support this feature as well, even as an extension.
3187 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
3188 return;
3189 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3190 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
3193 if ((!AL.isGNUAttribute() &&
3194 !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3195 isa<TypedefNameDecl>(D)) {
3196 S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
3197 << AL.isGNUScope();
3198 return;
3201 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3204 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3205 // weak_import only applies to variable & function declarations.
3206 bool isDef = false;
3207 if (!D->canBeWeakImported(isDef)) {
3208 if (isDef)
3209 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
3210 << "weak_import";
3211 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
3212 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3213 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
3214 // Nothing to warn about here.
3215 } else
3216 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3217 << AL << AL.isRegularKeywordAttribute() << ExpectedVariableOrFunction;
3219 return;
3222 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3225 // Handles reqd_work_group_size and work_group_size_hint.
3226 template <typename WorkGroupAttr>
3227 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3228 uint32_t WGSize[3];
3229 for (unsigned i = 0; i < 3; ++i) {
3230 const Expr *E = AL.getArgAsExpr(i);
3231 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3232 /*StrictlyUnsigned=*/true))
3233 return;
3234 if (WGSize[i] == 0) {
3235 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3236 << AL << E->getSourceRange();
3237 return;
3241 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3242 if (Existing && !(Existing->getXDim() == WGSize[0] &&
3243 Existing->getYDim() == WGSize[1] &&
3244 Existing->getZDim() == WGSize[2]))
3245 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3247 D->addAttr(::new (S.Context)
3248 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3251 // Handles intel_reqd_sub_group_size.
3252 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3253 uint32_t SGSize;
3254 const Expr *E = AL.getArgAsExpr(0);
3255 if (!checkUInt32Argument(S, AL, E, SGSize))
3256 return;
3257 if (SGSize == 0) {
3258 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3259 << AL << E->getSourceRange();
3260 return;
3263 OpenCLIntelReqdSubGroupSizeAttr *Existing =
3264 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3265 if (Existing && Existing->getSubGroupSize() != SGSize)
3266 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3268 D->addAttr(::new (S.Context)
3269 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3272 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3273 if (!AL.hasParsedType()) {
3274 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3275 return;
3278 TypeSourceInfo *ParmTSI = nullptr;
3279 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3280 assert(ParmTSI && "no type source info for attribute argument");
3282 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3283 (ParmType->isBooleanType() ||
3284 !ParmType->isIntegralType(S.getASTContext()))) {
3285 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3286 return;
3289 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3290 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3291 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3292 return;
3296 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3299 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3300 StringRef Name) {
3301 // Explicit or partial specializations do not inherit
3302 // the section attribute from the primary template.
3303 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3304 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3305 FD->isFunctionTemplateSpecialization())
3306 return nullptr;
3308 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3309 if (ExistingAttr->getName() == Name)
3310 return nullptr;
3311 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3312 << 1 /*section*/;
3313 Diag(CI.getLoc(), diag::note_previous_attribute);
3314 return nullptr;
3316 return ::new (Context) SectionAttr(Context, CI, Name);
3319 /// Used to implement to perform semantic checking on
3320 /// attribute((section("foo"))) specifiers.
3322 /// In this case, "foo" is passed in to be checked. If the section
3323 /// specifier is invalid, return an Error that indicates the problem.
3325 /// This is a simple quality of implementation feature to catch errors
3326 /// and give good diagnostics in cases when the assembler or code generator
3327 /// would otherwise reject the section specifier.
3328 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3329 if (!Context.getTargetInfo().getTriple().isOSDarwin())
3330 return llvm::Error::success();
3332 // Let MCSectionMachO validate this.
3333 StringRef Segment, Section;
3334 unsigned TAA, StubSize;
3335 bool HasTAA;
3336 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3337 TAA, HasTAA, StubSize);
3340 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3341 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3342 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3343 << toString(std::move(E)) << 1 /*'section'*/;
3344 return false;
3346 return true;
3349 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3350 // Make sure that there is a string literal as the sections's single
3351 // argument.
3352 StringRef Str;
3353 SourceLocation LiteralLoc;
3354 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3355 return;
3357 if (!S.checkSectionName(LiteralLoc, Str))
3358 return;
3360 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3361 if (NewAttr) {
3362 D->addAttr(NewAttr);
3363 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3364 ObjCPropertyDecl>(D))
3365 S.UnifySection(NewAttr->getName(),
3366 ASTContext::PSF_Execute | ASTContext::PSF_Read,
3367 cast<NamedDecl>(D));
3371 // This is used for `__declspec(code_seg("segname"))` on a decl.
3372 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3373 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3374 StringRef CodeSegName) {
3375 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3376 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3377 << toString(std::move(E)) << 0 /*'code-seg'*/;
3378 return false;
3381 return true;
3384 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3385 StringRef Name) {
3386 // Explicit or partial specializations do not inherit
3387 // the code_seg attribute from the primary template.
3388 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3389 if (FD->isFunctionTemplateSpecialization())
3390 return nullptr;
3392 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3393 if (ExistingAttr->getName() == Name)
3394 return nullptr;
3395 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3396 << 0 /*codeseg*/;
3397 Diag(CI.getLoc(), diag::note_previous_attribute);
3398 return nullptr;
3400 return ::new (Context) CodeSegAttr(Context, CI, Name);
3403 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3404 StringRef Str;
3405 SourceLocation LiteralLoc;
3406 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3407 return;
3408 if (!checkCodeSegName(S, LiteralLoc, Str))
3409 return;
3410 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3411 if (!ExistingAttr->isImplicit()) {
3412 S.Diag(AL.getLoc(),
3413 ExistingAttr->getName() == Str
3414 ? diag::warn_duplicate_codeseg_attribute
3415 : diag::err_conflicting_codeseg_attribute);
3416 return;
3418 D->dropAttr<CodeSegAttr>();
3420 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3421 D->addAttr(CSA);
3424 // Check for things we'd like to warn about. Multiversioning issues are
3425 // handled later in the process, once we know how many exist.
3426 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3427 enum FirstParam { Unsupported, Duplicate, Unknown };
3428 enum SecondParam { None, CPU, Tune };
3429 enum ThirdParam { Target, TargetClones };
3430 if (AttrStr.contains("fpmath="))
3431 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3432 << Unsupported << None << "fpmath=" << Target;
3434 // Diagnose use of tune if target doesn't support it.
3435 if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3436 AttrStr.contains("tune="))
3437 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3438 << Unsupported << None << "tune=" << Target;
3440 ParsedTargetAttr ParsedAttrs =
3441 Context.getTargetInfo().parseTargetAttr(AttrStr);
3443 if (!ParsedAttrs.CPU.empty() &&
3444 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
3445 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3446 << Unknown << CPU << ParsedAttrs.CPU << Target;
3448 if (!ParsedAttrs.Tune.empty() &&
3449 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3450 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3451 << Unknown << Tune << ParsedAttrs.Tune << Target;
3453 if (ParsedAttrs.Duplicate != "")
3454 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3455 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3457 for (const auto &Feature : ParsedAttrs.Features) {
3458 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3459 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3460 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3461 << Unsupported << None << CurFeature << Target;
3464 TargetInfo::BranchProtectionInfo BPI;
3465 StringRef DiagMsg;
3466 if (ParsedAttrs.BranchProtection.empty())
3467 return false;
3468 if (!Context.getTargetInfo().validateBranchProtection(
3469 ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
3470 if (DiagMsg.empty())
3471 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3472 << Unsupported << None << "branch-protection" << Target;
3473 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3474 << DiagMsg;
3476 if (!DiagMsg.empty())
3477 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3479 return false;
3482 // Check Target Version attrs
3483 bool Sema::checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &AttrStr,
3484 bool &isDefault) {
3485 enum FirstParam { Unsupported };
3486 enum SecondParam { None };
3487 enum ThirdParam { Target, TargetClones, TargetVersion };
3488 if (AttrStr.trim() == "default")
3489 isDefault = true;
3490 llvm::SmallVector<StringRef, 8> Features;
3491 AttrStr.split(Features, "+");
3492 for (auto &CurFeature : Features) {
3493 CurFeature = CurFeature.trim();
3494 if (CurFeature == "default")
3495 continue;
3496 if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
3497 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3498 << Unsupported << None << CurFeature << TargetVersion;
3500 return false;
3503 static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3504 StringRef Str;
3505 SourceLocation LiteralLoc;
3506 bool isDefault = false;
3507 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3508 S.checkTargetVersionAttr(LiteralLoc, Str, isDefault))
3509 return;
3510 // Do not create default only target_version attribute
3511 if (!isDefault) {
3512 TargetVersionAttr *NewAttr =
3513 ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
3514 D->addAttr(NewAttr);
3518 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3519 StringRef Str;
3520 SourceLocation LiteralLoc;
3521 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3522 S.checkTargetAttr(LiteralLoc, Str))
3523 return;
3525 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3526 D->addAttr(NewAttr);
3529 bool Sema::checkTargetClonesAttrString(
3530 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3531 bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3532 SmallVectorImpl<SmallString<64>> &StringsBuffer) {
3533 enum FirstParam { Unsupported, Duplicate, Unknown };
3534 enum SecondParam { None, CPU, Tune };
3535 enum ThirdParam { Target, TargetClones };
3536 HasCommas = HasCommas || Str.contains(',');
3537 const TargetInfo &TInfo = Context.getTargetInfo();
3538 // Warn on empty at the beginning of a string.
3539 if (Str.size() == 0)
3540 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3541 << Unsupported << None << "" << TargetClones;
3543 std::pair<StringRef, StringRef> Parts = {{}, Str};
3544 while (!Parts.second.empty()) {
3545 Parts = Parts.second.split(',');
3546 StringRef Cur = Parts.first.trim();
3547 SourceLocation CurLoc =
3548 Literal->getLocationOfByte(Cur.data() - Literal->getString().data(),
3549 getSourceManager(), getLangOpts(), TInfo);
3551 bool DefaultIsDupe = false;
3552 bool HasCodeGenImpact = false;
3553 if (Cur.empty())
3554 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3555 << Unsupported << None << "" << TargetClones;
3557 if (TInfo.getTriple().isAArch64()) {
3558 // AArch64 target clones specific
3559 if (Cur == "default") {
3560 DefaultIsDupe = HasDefault;
3561 HasDefault = true;
3562 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3563 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3564 else
3565 StringsBuffer.push_back(Cur);
3566 } else {
3567 std::pair<StringRef, StringRef> CurParts = {{}, Cur};
3568 llvm::SmallVector<StringRef, 8> CurFeatures;
3569 while (!CurParts.second.empty()) {
3570 CurParts = CurParts.second.split('+');
3571 StringRef CurFeature = CurParts.first.trim();
3572 if (!TInfo.validateCpuSupports(CurFeature)) {
3573 Diag(CurLoc, diag::warn_unsupported_target_attribute)
3574 << Unsupported << None << CurFeature << TargetClones;
3575 continue;
3577 if (TInfo.doesFeatureAffectCodeGen(CurFeature))
3578 HasCodeGenImpact = true;
3579 CurFeatures.push_back(CurFeature);
3581 // Canonize TargetClones Attributes
3582 llvm::sort(CurFeatures);
3583 SmallString<64> Res;
3584 for (auto &CurFeat : CurFeatures) {
3585 if (!Res.equals(""))
3586 Res.append("+");
3587 Res.append(CurFeat);
3589 if (llvm::is_contained(StringsBuffer, Res) || DefaultIsDupe)
3590 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3591 else if (!HasCodeGenImpact)
3592 // Ignore features in target_clone attribute that don't impact
3593 // code generation
3594 Diag(CurLoc, diag::warn_target_clone_no_impact_options);
3595 else if (!Res.empty()) {
3596 StringsBuffer.push_back(Res);
3597 HasNotDefault = true;
3600 } else {
3601 // Other targets ( currently X86 )
3602 if (Cur.startswith("arch=")) {
3603 if (!Context.getTargetInfo().isValidCPUName(
3604 Cur.drop_front(sizeof("arch=") - 1)))
3605 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3606 << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3607 << TargetClones;
3608 } else if (Cur == "default") {
3609 DefaultIsDupe = HasDefault;
3610 HasDefault = true;
3611 } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3612 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3613 << Unsupported << None << Cur << TargetClones;
3614 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3615 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3616 // Note: Add even if there are duplicates, since it changes name mangling.
3617 StringsBuffer.push_back(Cur);
3620 if (Str.rtrim().endswith(","))
3621 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3622 << Unsupported << None << "" << TargetClones;
3623 return false;
3626 static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3627 if (S.Context.getTargetInfo().getTriple().isAArch64() &&
3628 !S.Context.getTargetInfo().hasFeature("fmv"))
3629 return;
3631 // Ensure we don't combine these with themselves, since that causes some
3632 // confusing behavior.
3633 if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3634 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3635 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3636 return;
3638 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3639 return;
3641 SmallVector<StringRef, 2> Strings;
3642 SmallVector<SmallString<64>, 2> StringsBuffer;
3643 bool HasCommas = false, HasDefault = false, HasNotDefault = false;
3645 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3646 StringRef CurStr;
3647 SourceLocation LiteralLoc;
3648 if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
3649 S.checkTargetClonesAttrString(
3650 LiteralLoc, CurStr,
3651 cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()),
3652 HasDefault, HasCommas, HasNotDefault, StringsBuffer))
3653 return;
3655 for (auto &SmallStr : StringsBuffer)
3656 Strings.push_back(SmallStr.str());
3658 if (HasCommas && AL.getNumArgs() > 1)
3659 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3661 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
3662 // Add default attribute if there is no one
3663 HasDefault = true;
3664 Strings.push_back("default");
3667 if (!HasDefault) {
3668 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3669 return;
3672 // FIXME: We could probably figure out how to get this to work for lambdas
3673 // someday.
3674 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3675 if (MD->getParent()->isLambda()) {
3676 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3677 << static_cast<unsigned>(MultiVersionKind::TargetClones)
3678 << /*Lambda*/ 9;
3679 return;
3683 // No multiversion if we have default version only.
3684 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
3685 return;
3687 cast<FunctionDecl>(D)->setIsMultiVersion();
3688 TargetClonesAttr *NewAttr = ::new (S.Context)
3689 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3690 D->addAttr(NewAttr);
3693 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3694 Expr *E = AL.getArgAsExpr(0);
3695 uint32_t VecWidth;
3696 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3697 AL.setInvalid();
3698 return;
3701 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3702 if (Existing && Existing->getVectorWidth() != VecWidth) {
3703 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3704 return;
3707 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3710 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3711 Expr *E = AL.getArgAsExpr(0);
3712 SourceLocation Loc = E->getExprLoc();
3713 FunctionDecl *FD = nullptr;
3714 DeclarationNameInfo NI;
3716 // gcc only allows for simple identifiers. Since we support more than gcc, we
3717 // will warn the user.
3718 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3719 if (DRE->hasQualifier())
3720 S.Diag(Loc, diag::warn_cleanup_ext);
3721 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3722 NI = DRE->getNameInfo();
3723 if (!FD) {
3724 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3725 << NI.getName();
3726 return;
3728 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3729 if (ULE->hasExplicitTemplateArgs())
3730 S.Diag(Loc, diag::warn_cleanup_ext);
3731 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3732 NI = ULE->getNameInfo();
3733 if (!FD) {
3734 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3735 << NI.getName();
3736 if (ULE->getType() == S.Context.OverloadTy)
3737 S.NoteAllOverloadCandidates(ULE);
3738 return;
3740 } else {
3741 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3742 return;
3745 if (FD->getNumParams() != 1) {
3746 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3747 << NI.getName();
3748 return;
3751 // We're currently more strict than GCC about what function types we accept.
3752 // If this ever proves to be a problem it should be easy to fix.
3753 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3754 QualType ParamTy = FD->getParamDecl(0)->getType();
3755 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3756 ParamTy, Ty) != Sema::Compatible) {
3757 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3758 << NI.getName() << ParamTy << Ty;
3759 return;
3762 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3765 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3766 const ParsedAttr &AL) {
3767 if (!AL.isArgIdent(0)) {
3768 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3769 << AL << 0 << AANT_ArgumentIdentifier;
3770 return;
3773 EnumExtensibilityAttr::Kind ExtensibilityKind;
3774 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3775 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3776 ExtensibilityKind)) {
3777 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3778 return;
3781 D->addAttr(::new (S.Context)
3782 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3785 /// Handle __attribute__((format_arg((idx)))) attribute based on
3786 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3787 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3788 const Expr *IdxExpr = AL.getArgAsExpr(0);
3789 ParamIdx Idx;
3790 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3791 return;
3793 // Make sure the format string is really a string.
3794 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3796 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3797 if (NotNSStringTy &&
3798 !isCFStringType(Ty, S.Context) &&
3799 (!Ty->isPointerType() ||
3800 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3801 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3802 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3803 return;
3805 Ty = getFunctionOrMethodResultType(D);
3806 // replace instancetype with the class type
3807 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3808 if (Ty->getAs<TypedefType>() == Instancetype)
3809 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3810 if (auto *Interface = OMD->getClassInterface())
3811 Ty = S.Context.getObjCObjectPointerType(
3812 QualType(Interface->getTypeForDecl(), 0));
3813 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3814 !isCFStringType(Ty, S.Context) &&
3815 (!Ty->isPointerType() ||
3816 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3817 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3818 << (NotNSStringTy ? "string type" : "NSString")
3819 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3820 return;
3823 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3826 enum FormatAttrKind {
3827 CFStringFormat,
3828 NSStringFormat,
3829 StrftimeFormat,
3830 SupportedFormat,
3831 IgnoredFormat,
3832 InvalidFormat
3835 /// getFormatAttrKind - Map from format attribute names to supported format
3836 /// types.
3837 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3838 return llvm::StringSwitch<FormatAttrKind>(Format)
3839 // Check for formats that get handled specially.
3840 .Case("NSString", NSStringFormat)
3841 .Case("CFString", CFStringFormat)
3842 .Case("strftime", StrftimeFormat)
3844 // Otherwise, check for supported formats.
3845 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3846 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3847 .Case("kprintf", SupportedFormat) // OpenBSD.
3848 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3849 .Case("os_trace", SupportedFormat)
3850 .Case("os_log", SupportedFormat)
3852 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3853 .Default(InvalidFormat);
3856 /// Handle __attribute__((init_priority(priority))) attributes based on
3857 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3858 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3859 if (!S.getLangOpts().CPlusPlus) {
3860 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3861 return;
3864 if (S.getLangOpts().HLSL) {
3865 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3866 return;
3869 if (S.getCurFunctionOrMethodDecl()) {
3870 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3871 AL.setInvalid();
3872 return;
3874 QualType T = cast<VarDecl>(D)->getType();
3875 if (S.Context.getAsArrayType(T))
3876 T = S.Context.getBaseElementType(T);
3877 if (!T->getAs<RecordType>()) {
3878 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3879 AL.setInvalid();
3880 return;
3883 Expr *E = AL.getArgAsExpr(0);
3884 uint32_t prioritynum;
3885 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3886 AL.setInvalid();
3887 return;
3890 // Only perform the priority check if the attribute is outside of a system
3891 // header. Values <= 100 are reserved for the implementation, and libc++
3892 // benefits from being able to specify values in that range.
3893 if ((prioritynum < 101 || prioritynum > 65535) &&
3894 !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3895 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3896 << E->getSourceRange() << AL << 101 << 65535;
3897 AL.setInvalid();
3898 return;
3900 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3903 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3904 StringRef NewUserDiagnostic) {
3905 if (const auto *EA = D->getAttr<ErrorAttr>()) {
3906 std::string NewAttr = CI.getNormalizedFullName();
3907 assert((NewAttr == "error" || NewAttr == "warning") &&
3908 "unexpected normalized full name");
3909 bool Match = (EA->isError() && NewAttr == "error") ||
3910 (EA->isWarning() && NewAttr == "warning");
3911 if (!Match) {
3912 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3913 << CI << EA
3914 << (CI.isRegularKeywordAttribute() ||
3915 EA->isRegularKeywordAttribute());
3916 Diag(CI.getLoc(), diag::note_conflicting_attribute);
3917 return nullptr;
3919 if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3920 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3921 Diag(EA->getLoc(), diag::note_previous_attribute);
3923 D->dropAttr<ErrorAttr>();
3925 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3928 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3929 IdentifierInfo *Format, int FormatIdx,
3930 int FirstArg) {
3931 // Check whether we already have an equivalent format attribute.
3932 for (auto *F : D->specific_attrs<FormatAttr>()) {
3933 if (F->getType() == Format &&
3934 F->getFormatIdx() == FormatIdx &&
3935 F->getFirstArg() == FirstArg) {
3936 // If we don't have a valid location for this attribute, adopt the
3937 // location.
3938 if (F->getLocation().isInvalid())
3939 F->setRange(CI.getRange());
3940 return nullptr;
3944 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3947 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3948 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3949 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3950 if (!AL.isArgIdent(0)) {
3951 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3952 << AL << 1 << AANT_ArgumentIdentifier;
3953 return;
3956 // In C++ the implicit 'this' function parameter also counts, and they are
3957 // counted from one.
3958 bool HasImplicitThisParam = isInstanceMethod(D);
3959 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3961 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3962 StringRef Format = II->getName();
3964 if (normalizeName(Format)) {
3965 // If we've modified the string name, we need a new identifier for it.
3966 II = &S.Context.Idents.get(Format);
3969 // Check for supported formats.
3970 FormatAttrKind Kind = getFormatAttrKind(Format);
3972 if (Kind == IgnoredFormat)
3973 return;
3975 if (Kind == InvalidFormat) {
3976 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3977 << AL << II->getName();
3978 return;
3981 // checks for the 2nd argument
3982 Expr *IdxExpr = AL.getArgAsExpr(1);
3983 uint32_t Idx;
3984 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3985 return;
3987 if (Idx < 1 || Idx > NumArgs) {
3988 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3989 << AL << 2 << IdxExpr->getSourceRange();
3990 return;
3993 // FIXME: Do we need to bounds check?
3994 unsigned ArgIdx = Idx - 1;
3996 if (HasImplicitThisParam) {
3997 if (ArgIdx == 0) {
3998 S.Diag(AL.getLoc(),
3999 diag::err_format_attribute_implicit_this_format_string)
4000 << IdxExpr->getSourceRange();
4001 return;
4003 ArgIdx--;
4006 // make sure the format string is really a string
4007 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
4009 if (!isNSStringType(Ty, S.Context, true) &&
4010 !isCFStringType(Ty, S.Context) &&
4011 (!Ty->isPointerType() ||
4012 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
4013 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
4014 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
4015 return;
4018 // check the 3rd argument
4019 Expr *FirstArgExpr = AL.getArgAsExpr(2);
4020 uint32_t FirstArg;
4021 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
4022 return;
4024 // FirstArg == 0 is is always valid.
4025 if (FirstArg != 0) {
4026 if (Kind == StrftimeFormat) {
4027 // If the kind is strftime, FirstArg must be 0 because strftime does not
4028 // use any variadic arguments.
4029 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
4030 << FirstArgExpr->getSourceRange()
4031 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
4032 return;
4033 } else if (isFunctionOrMethodVariadic(D)) {
4034 // Else, if the function is variadic, then FirstArg must be 0 or the
4035 // "position" of the ... parameter. It's unusual to use 0 with variadic
4036 // functions, so the fixit proposes the latter.
4037 if (FirstArg != NumArgs + 1) {
4038 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4039 << AL << 3 << FirstArgExpr->getSourceRange()
4040 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(),
4041 std::to_string(NumArgs + 1));
4042 return;
4044 } else {
4045 // Inescapable GCC compatibility diagnostic.
4046 S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
4047 if (FirstArg <= Idx) {
4048 // Else, the function is not variadic, and FirstArg must be 0 or any
4049 // parameter after the format parameter. We don't offer a fixit because
4050 // there are too many possible good values.
4051 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4052 << AL << 3 << FirstArgExpr->getSourceRange();
4053 return;
4058 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
4059 if (NewAttr)
4060 D->addAttr(NewAttr);
4063 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
4064 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4065 // The index that identifies the callback callee is mandatory.
4066 if (AL.getNumArgs() == 0) {
4067 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
4068 << AL.getRange();
4069 return;
4072 bool HasImplicitThisParam = isInstanceMethod(D);
4073 int32_t NumArgs = getFunctionOrMethodNumParams(D);
4075 FunctionDecl *FD = D->getAsFunction();
4076 assert(FD && "Expected a function declaration!");
4078 llvm::StringMap<int> NameIdxMapping;
4079 NameIdxMapping["__"] = -1;
4081 NameIdxMapping["this"] = 0;
4083 int Idx = 1;
4084 for (const ParmVarDecl *PVD : FD->parameters())
4085 NameIdxMapping[PVD->getName()] = Idx++;
4087 auto UnknownName = NameIdxMapping.end();
4089 SmallVector<int, 8> EncodingIndices;
4090 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
4091 SourceRange SR;
4092 int32_t ArgIdx;
4094 if (AL.isArgIdent(I)) {
4095 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
4096 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
4097 if (It == UnknownName) {
4098 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
4099 << IdLoc->Ident << IdLoc->Loc;
4100 return;
4103 SR = SourceRange(IdLoc->Loc);
4104 ArgIdx = It->second;
4105 } else if (AL.isArgExpr(I)) {
4106 Expr *IdxExpr = AL.getArgAsExpr(I);
4108 // If the expression is not parseable as an int32_t we have a problem.
4109 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
4110 false)) {
4111 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4112 << AL << (I + 1) << IdxExpr->getSourceRange();
4113 return;
4116 // Check oob, excluding the special values, 0 and -1.
4117 if (ArgIdx < -1 || ArgIdx > NumArgs) {
4118 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4119 << AL << (I + 1) << IdxExpr->getSourceRange();
4120 return;
4123 SR = IdxExpr->getSourceRange();
4124 } else {
4125 llvm_unreachable("Unexpected ParsedAttr argument type!");
4128 if (ArgIdx == 0 && !HasImplicitThisParam) {
4129 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
4130 << (I + 1) << SR;
4131 return;
4134 // Adjust for the case we do not have an implicit "this" parameter. In this
4135 // case we decrease all positive values by 1 to get LLVM argument indices.
4136 if (!HasImplicitThisParam && ArgIdx > 0)
4137 ArgIdx -= 1;
4139 EncodingIndices.push_back(ArgIdx);
4142 int CalleeIdx = EncodingIndices.front();
4143 // Check if the callee index is proper, thus not "this" and not "unknown".
4144 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4145 // is false and positive if "HasImplicitThisParam" is true.
4146 if (CalleeIdx < (int)HasImplicitThisParam) {
4147 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
4148 << AL.getRange();
4149 return;
4152 // Get the callee type, note the index adjustment as the AST doesn't contain
4153 // the this type (which the callee cannot reference anyway!).
4154 const Type *CalleeType =
4155 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
4156 .getTypePtr();
4157 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
4158 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4159 << AL.getRange();
4160 return;
4163 const Type *CalleeFnType =
4164 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
4166 // TODO: Check the type of the callee arguments.
4168 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
4169 if (!CalleeFnProtoType) {
4170 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4171 << AL.getRange();
4172 return;
4175 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
4176 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4177 << AL << (unsigned)(EncodingIndices.size() - 1);
4178 return;
4181 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
4182 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4183 << AL << (unsigned)(EncodingIndices.size() - 1);
4184 return;
4187 if (CalleeFnProtoType->isVariadic()) {
4188 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
4189 return;
4192 // Do not allow multiple callback attributes.
4193 if (D->hasAttr<CallbackAttr>()) {
4194 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
4195 return;
4198 D->addAttr(::new (S.Context) CallbackAttr(
4199 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
4202 static bool isFunctionLike(const Type &T) {
4203 // Check for explicit function types.
4204 // 'called_once' is only supported in Objective-C and it has
4205 // function pointers and block pointers.
4206 return T.isFunctionPointerType() || T.isBlockPointerType();
4209 /// Handle 'called_once' attribute.
4210 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4211 // 'called_once' only applies to parameters representing functions.
4212 QualType T = cast<ParmVarDecl>(D)->getType();
4214 if (!isFunctionLike(*T)) {
4215 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
4216 return;
4219 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
4222 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4223 // Try to find the underlying union declaration.
4224 RecordDecl *RD = nullptr;
4225 const auto *TD = dyn_cast<TypedefNameDecl>(D);
4226 if (TD && TD->getUnderlyingType()->isUnionType())
4227 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
4228 else
4229 RD = dyn_cast<RecordDecl>(D);
4231 if (!RD || !RD->isUnion()) {
4232 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4233 << AL << AL.isRegularKeywordAttribute() << ExpectedUnion;
4234 return;
4237 if (!RD->isCompleteDefinition()) {
4238 if (!RD->isBeingDefined())
4239 S.Diag(AL.getLoc(),
4240 diag::warn_transparent_union_attribute_not_definition);
4241 return;
4244 RecordDecl::field_iterator Field = RD->field_begin(),
4245 FieldEnd = RD->field_end();
4246 if (Field == FieldEnd) {
4247 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
4248 return;
4251 FieldDecl *FirstField = *Field;
4252 QualType FirstType = FirstField->getType();
4253 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
4254 S.Diag(FirstField->getLocation(),
4255 diag::warn_transparent_union_attribute_floating)
4256 << FirstType->isVectorType() << FirstType;
4257 return;
4260 if (FirstType->isIncompleteType())
4261 return;
4262 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
4263 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
4264 for (; Field != FieldEnd; ++Field) {
4265 QualType FieldType = Field->getType();
4266 if (FieldType->isIncompleteType())
4267 return;
4268 // FIXME: this isn't fully correct; we also need to test whether the
4269 // members of the union would all have the same calling convention as the
4270 // first member of the union. Checking just the size and alignment isn't
4271 // sufficient (consider structs passed on the stack instead of in registers
4272 // as an example).
4273 if (S.Context.getTypeSize(FieldType) != FirstSize ||
4274 S.Context.getTypeAlign(FieldType) > FirstAlign) {
4275 // Warn if we drop the attribute.
4276 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
4277 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
4278 : S.Context.getTypeAlign(FieldType);
4279 S.Diag(Field->getLocation(),
4280 diag::warn_transparent_union_attribute_field_size_align)
4281 << isSize << *Field << FieldBits;
4282 unsigned FirstBits = isSize ? FirstSize : FirstAlign;
4283 S.Diag(FirstField->getLocation(),
4284 diag::note_transparent_union_first_field_size_align)
4285 << isSize << FirstBits;
4286 return;
4290 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
4293 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
4294 StringRef Str, MutableArrayRef<Expr *> Args) {
4295 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
4296 if (ConstantFoldAttrArgs(
4297 CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
4298 D->addAttr(Attr);
4302 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4303 // Make sure that there is a string literal as the annotation's first
4304 // argument.
4305 StringRef Str;
4306 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
4307 return;
4309 llvm::SmallVector<Expr *, 4> Args;
4310 Args.reserve(AL.getNumArgs() - 1);
4311 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
4312 assert(!AL.isArgIdent(Idx));
4313 Args.push_back(AL.getArgAsExpr(Idx));
4316 S.AddAnnotationAttr(D, AL, Str, Args);
4319 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4320 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
4323 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4324 AlignValueAttr TmpAttr(Context, CI, E);
4325 SourceLocation AttrLoc = CI.getLoc();
4327 QualType T;
4328 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4329 T = TD->getUnderlyingType();
4330 else if (const auto *VD = dyn_cast<ValueDecl>(D))
4331 T = VD->getType();
4332 else
4333 llvm_unreachable("Unknown decl type for align_value");
4335 if (!T->isDependentType() && !T->isAnyPointerType() &&
4336 !T->isReferenceType() && !T->isMemberPointerType()) {
4337 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
4338 << &TmpAttr << T << D->getSourceRange();
4339 return;
4342 if (!E->isValueDependent()) {
4343 llvm::APSInt Alignment;
4344 ExprResult ICE = VerifyIntegerConstantExpression(
4345 E, &Alignment, diag::err_align_value_attribute_argument_not_int);
4346 if (ICE.isInvalid())
4347 return;
4349 if (!Alignment.isPowerOf2()) {
4350 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4351 << E->getSourceRange();
4352 return;
4355 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
4356 return;
4359 // Save dependent expressions in the AST to be instantiated.
4360 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
4363 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4364 if (AL.hasParsedType()) {
4365 const ParsedType &TypeArg = AL.getTypeArg();
4366 TypeSourceInfo *TInfo;
4367 (void)S.GetTypeFromParser(
4368 ParsedType::getFromOpaquePtr(TypeArg.getAsOpaquePtr()), &TInfo);
4369 if (AL.isPackExpansion() &&
4370 !TInfo->getType()->containsUnexpandedParameterPack()) {
4371 S.Diag(AL.getEllipsisLoc(),
4372 diag::err_pack_expansion_without_parameter_packs);
4373 return;
4376 if (!AL.isPackExpansion() &&
4377 S.DiagnoseUnexpandedParameterPack(TInfo->getTypeLoc().getBeginLoc(),
4378 TInfo, Sema::UPPC_Expression))
4379 return;
4381 S.AddAlignedAttr(D, AL, TInfo, AL.isPackExpansion());
4382 return;
4385 // check the attribute arguments.
4386 if (AL.getNumArgs() > 1) {
4387 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
4388 return;
4391 if (AL.getNumArgs() == 0) {
4392 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
4393 return;
4396 Expr *E = AL.getArgAsExpr(0);
4397 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
4398 S.Diag(AL.getEllipsisLoc(),
4399 diag::err_pack_expansion_without_parameter_packs);
4400 return;
4403 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
4404 return;
4406 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
4409 /// Perform checking of type validity
4411 /// C++11 [dcl.align]p1:
4412 /// An alignment-specifier may be applied to a variable or to a class
4413 /// data member, but it shall not be applied to a bit-field, a function
4414 /// parameter, the formal parameter of a catch clause, or a variable
4415 /// declared with the register storage class specifier. An
4416 /// alignment-specifier may also be applied to the declaration of a class
4417 /// or enumeration type.
4418 /// CWG 2354:
4419 /// CWG agreed to remove permission for alignas to be applied to
4420 /// enumerations.
4421 /// C11 6.7.5/2:
4422 /// An alignment attribute shall not be specified in a declaration of
4423 /// a typedef, or a bit-field, or a function, or a parameter, or an
4424 /// object declared with the register storage-class specifier.
4425 static bool validateAlignasAppliedType(Sema &S, Decl *D,
4426 const AlignedAttr &Attr,
4427 SourceLocation AttrLoc) {
4428 int DiagKind = -1;
4429 if (isa<ParmVarDecl>(D)) {
4430 DiagKind = 0;
4431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4432 if (VD->getStorageClass() == SC_Register)
4433 DiagKind = 1;
4434 if (VD->isExceptionVariable())
4435 DiagKind = 2;
4436 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4437 if (FD->isBitField())
4438 DiagKind = 3;
4439 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4440 if (ED->getLangOpts().CPlusPlus)
4441 DiagKind = 4;
4442 } else if (!isa<TagDecl>(D)) {
4443 return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
4444 << &Attr << Attr.isRegularKeywordAttribute()
4445 << (Attr.isC11() ? ExpectedVariableOrField
4446 : ExpectedVariableFieldOrTag);
4448 if (DiagKind != -1) {
4449 return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4450 << &Attr << DiagKind;
4452 return false;
4455 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4456 bool IsPackExpansion) {
4457 AlignedAttr TmpAttr(Context, CI, true, E);
4458 SourceLocation AttrLoc = CI.getLoc();
4460 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4461 if (TmpAttr.isAlignas() &&
4462 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4463 return;
4465 if (E->isValueDependent()) {
4466 // We can't support a dependent alignment on a non-dependent type,
4467 // because we have no way to model that a type is "alignment-dependent"
4468 // but not dependent in any other way.
4469 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4470 if (!TND->getUnderlyingType()->isDependentType()) {
4471 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4472 << E->getSourceRange();
4473 return;
4477 // Save dependent expressions in the AST to be instantiated.
4478 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4479 AA->setPackExpansion(IsPackExpansion);
4480 D->addAttr(AA);
4481 return;
4484 // FIXME: Cache the number on the AL object?
4485 llvm::APSInt Alignment;
4486 ExprResult ICE = VerifyIntegerConstantExpression(
4487 E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4488 if (ICE.isInvalid())
4489 return;
4491 uint64_t MaximumAlignment = Sema::MaximumAlignment;
4492 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4493 MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4494 if (Alignment > MaximumAlignment) {
4495 Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4496 << MaximumAlignment << E->getSourceRange();
4497 return;
4500 uint64_t AlignVal = Alignment.getZExtValue();
4501 // C++11 [dcl.align]p2:
4502 // -- if the constant expression evaluates to zero, the alignment
4503 // specifier shall have no effect
4504 // C11 6.7.5p6:
4505 // An alignment specification of zero has no effect.
4506 if (!(TmpAttr.isAlignas() && !Alignment)) {
4507 if (!llvm::isPowerOf2_64(AlignVal)) {
4508 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4509 << E->getSourceRange();
4510 return;
4514 const auto *VD = dyn_cast<VarDecl>(D);
4515 if (VD) {
4516 unsigned MaxTLSAlign =
4517 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4518 .getQuantity();
4519 if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4520 VD->getTLSKind() != VarDecl::TLS_None) {
4521 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4522 << (unsigned)AlignVal << VD << MaxTLSAlign;
4523 return;
4527 // On AIX, an aligned attribute can not decrease the alignment when applied
4528 // to a variable declaration with vector type.
4529 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4530 const Type *Ty = VD->getType().getTypePtr();
4531 if (Ty->isVectorType() && AlignVal < 16) {
4532 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4533 << VD->getType() << 16;
4534 return;
4538 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4539 AA->setPackExpansion(IsPackExpansion);
4540 AA->setCachedAlignmentValue(
4541 static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4542 D->addAttr(AA);
4545 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4546 TypeSourceInfo *TS, bool IsPackExpansion) {
4547 AlignedAttr TmpAttr(Context, CI, false, TS);
4548 SourceLocation AttrLoc = CI.getLoc();
4550 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4551 if (TmpAttr.isAlignas() &&
4552 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4553 return;
4555 if (TS->getType()->isDependentType()) {
4556 // We can't support a dependent alignment on a non-dependent type,
4557 // because we have no way to model that a type is "type-dependent"
4558 // but not dependent in any other way.
4559 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4560 if (!TND->getUnderlyingType()->isDependentType()) {
4561 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4562 << TS->getTypeLoc().getSourceRange();
4563 return;
4567 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4568 AA->setPackExpansion(IsPackExpansion);
4569 D->addAttr(AA);
4570 return;
4573 const auto *VD = dyn_cast<VarDecl>(D);
4574 unsigned AlignVal = TmpAttr.getAlignment(Context);
4575 // On AIX, an aligned attribute can not decrease the alignment when applied
4576 // to a variable declaration with vector type.
4577 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4578 const Type *Ty = VD->getType().getTypePtr();
4579 if (Ty->isVectorType() &&
4580 Context.toCharUnitsFromBits(AlignVal).getQuantity() < 16) {
4581 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4582 << VD->getType() << 16;
4583 return;
4587 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4588 AA->setPackExpansion(IsPackExpansion);
4589 AA->setCachedAlignmentValue(AlignVal);
4590 D->addAttr(AA);
4593 void Sema::CheckAlignasUnderalignment(Decl *D) {
4594 assert(D->hasAttrs() && "no attributes on decl");
4596 QualType UnderlyingTy, DiagTy;
4597 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4598 UnderlyingTy = DiagTy = VD->getType();
4599 } else {
4600 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4601 if (const auto *ED = dyn_cast<EnumDecl>(D))
4602 UnderlyingTy = ED->getIntegerType();
4604 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4605 return;
4607 // C++11 [dcl.align]p5, C11 6.7.5/4:
4608 // The combined effect of all alignment attributes in a declaration shall
4609 // not specify an alignment that is less strict than the alignment that
4610 // would otherwise be required for the entity being declared.
4611 AlignedAttr *AlignasAttr = nullptr;
4612 AlignedAttr *LastAlignedAttr = nullptr;
4613 unsigned Align = 0;
4614 for (auto *I : D->specific_attrs<AlignedAttr>()) {
4615 if (I->isAlignmentDependent())
4616 return;
4617 if (I->isAlignas())
4618 AlignasAttr = I;
4619 Align = std::max(Align, I->getAlignment(Context));
4620 LastAlignedAttr = I;
4623 if (Align && DiagTy->isSizelessType()) {
4624 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4625 << LastAlignedAttr << DiagTy;
4626 } else if (AlignasAttr && Align) {
4627 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4628 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4629 if (NaturalAlign > RequestedAlign)
4630 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4631 << DiagTy << (unsigned)NaturalAlign.getQuantity();
4635 bool Sema::checkMSInheritanceAttrOnDefinition(
4636 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4637 MSInheritanceModel ExplicitModel) {
4638 assert(RD->hasDefinition() && "RD has no definition!");
4640 // We may not have seen base specifiers or any virtual methods yet. We will
4641 // have to wait until the record is defined to catch any mismatches.
4642 if (!RD->getDefinition()->isCompleteDefinition())
4643 return false;
4645 // The unspecified model never matches what a definition could need.
4646 if (ExplicitModel == MSInheritanceModel::Unspecified)
4647 return false;
4649 if (BestCase) {
4650 if (RD->calculateInheritanceModel() == ExplicitModel)
4651 return false;
4652 } else {
4653 if (RD->calculateInheritanceModel() <= ExplicitModel)
4654 return false;
4657 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4658 << 0 /*definition*/;
4659 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4660 return true;
4663 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4664 /// attribute.
4665 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4666 bool &IntegerMode, bool &ComplexMode,
4667 FloatModeKind &ExplicitType) {
4668 IntegerMode = true;
4669 ComplexMode = false;
4670 ExplicitType = FloatModeKind::NoFloat;
4671 switch (Str.size()) {
4672 case 2:
4673 switch (Str[0]) {
4674 case 'Q':
4675 DestWidth = 8;
4676 break;
4677 case 'H':
4678 DestWidth = 16;
4679 break;
4680 case 'S':
4681 DestWidth = 32;
4682 break;
4683 case 'D':
4684 DestWidth = 64;
4685 break;
4686 case 'X':
4687 DestWidth = 96;
4688 break;
4689 case 'K': // KFmode - IEEE quad precision (__float128)
4690 ExplicitType = FloatModeKind::Float128;
4691 DestWidth = Str[1] == 'I' ? 0 : 128;
4692 break;
4693 case 'T':
4694 ExplicitType = FloatModeKind::LongDouble;
4695 DestWidth = 128;
4696 break;
4697 case 'I':
4698 ExplicitType = FloatModeKind::Ibm128;
4699 DestWidth = Str[1] == 'I' ? 0 : 128;
4700 break;
4702 if (Str[1] == 'F') {
4703 IntegerMode = false;
4704 } else if (Str[1] == 'C') {
4705 IntegerMode = false;
4706 ComplexMode = true;
4707 } else if (Str[1] != 'I') {
4708 DestWidth = 0;
4710 break;
4711 case 4:
4712 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4713 // pointer on PIC16 and other embedded platforms.
4714 if (Str == "word")
4715 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4716 else if (Str == "byte")
4717 DestWidth = S.Context.getTargetInfo().getCharWidth();
4718 break;
4719 case 7:
4720 if (Str == "pointer")
4721 DestWidth = S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
4722 break;
4723 case 11:
4724 if (Str == "unwind_word")
4725 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4726 break;
4730 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4731 /// type.
4733 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4734 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4735 /// HImode, not an intermediate pointer.
4736 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4737 // This attribute isn't documented, but glibc uses it. It changes
4738 // the width of an int or unsigned int to the specified size.
4739 if (!AL.isArgIdent(0)) {
4740 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4741 << AL << AANT_ArgumentIdentifier;
4742 return;
4745 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4747 S.AddModeAttr(D, AL, Name);
4750 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4751 IdentifierInfo *Name, bool InInstantiation) {
4752 StringRef Str = Name->getName();
4753 normalizeName(Str);
4754 SourceLocation AttrLoc = CI.getLoc();
4756 unsigned DestWidth = 0;
4757 bool IntegerMode = true;
4758 bool ComplexMode = false;
4759 FloatModeKind ExplicitType = FloatModeKind::NoFloat;
4760 llvm::APInt VectorSize(64, 0);
4761 if (Str.size() >= 4 && Str[0] == 'V') {
4762 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4763 size_t StrSize = Str.size();
4764 size_t VectorStringLength = 0;
4765 while ((VectorStringLength + 1) < StrSize &&
4766 isdigit(Str[VectorStringLength + 1]))
4767 ++VectorStringLength;
4768 if (VectorStringLength &&
4769 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4770 VectorSize.isPowerOf2()) {
4771 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4772 IntegerMode, ComplexMode, ExplicitType);
4773 // Avoid duplicate warning from template instantiation.
4774 if (!InInstantiation)
4775 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4776 } else {
4777 VectorSize = 0;
4781 if (!VectorSize)
4782 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4783 ExplicitType);
4785 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4786 // and friends, at least with glibc.
4787 // FIXME: Make sure floating-point mappings are accurate
4788 // FIXME: Support XF and TF types
4789 if (!DestWidth) {
4790 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4791 return;
4794 QualType OldTy;
4795 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4796 OldTy = TD->getUnderlyingType();
4797 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4798 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4799 // Try to get type from enum declaration, default to int.
4800 OldTy = ED->getIntegerType();
4801 if (OldTy.isNull())
4802 OldTy = Context.IntTy;
4803 } else
4804 OldTy = cast<ValueDecl>(D)->getType();
4806 if (OldTy->isDependentType()) {
4807 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4808 return;
4811 // Base type can also be a vector type (see PR17453).
4812 // Distinguish between base type and base element type.
4813 QualType OldElemTy = OldTy;
4814 if (const auto *VT = OldTy->getAs<VectorType>())
4815 OldElemTy = VT->getElementType();
4817 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4818 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4819 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4820 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4821 VectorSize.getBoolValue()) {
4822 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4823 return;
4825 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4826 !OldElemTy->isBitIntType()) ||
4827 OldElemTy->getAs<EnumType>();
4829 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4830 !IntegralOrAnyEnumType)
4831 Diag(AttrLoc, diag::err_mode_not_primitive);
4832 else if (IntegerMode) {
4833 if (!IntegralOrAnyEnumType)
4834 Diag(AttrLoc, diag::err_mode_wrong_type);
4835 } else if (ComplexMode) {
4836 if (!OldElemTy->isComplexType())
4837 Diag(AttrLoc, diag::err_mode_wrong_type);
4838 } else {
4839 if (!OldElemTy->isFloatingType())
4840 Diag(AttrLoc, diag::err_mode_wrong_type);
4843 QualType NewElemTy;
4845 if (IntegerMode)
4846 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4847 OldElemTy->isSignedIntegerType());
4848 else
4849 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4851 if (NewElemTy.isNull()) {
4852 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4853 return;
4856 if (ComplexMode) {
4857 NewElemTy = Context.getComplexType(NewElemTy);
4860 QualType NewTy = NewElemTy;
4861 if (VectorSize.getBoolValue()) {
4862 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4863 VectorType::GenericVector);
4864 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4865 // Complex machine mode does not support base vector types.
4866 if (ComplexMode) {
4867 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4868 return;
4870 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4871 OldVT->getNumElements() /
4872 Context.getTypeSize(NewElemTy);
4873 NewTy =
4874 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4877 if (NewTy.isNull()) {
4878 Diag(AttrLoc, diag::err_mode_wrong_type);
4879 return;
4882 // Install the new type.
4883 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4884 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4885 else if (auto *ED = dyn_cast<EnumDecl>(D))
4886 ED->setIntegerType(NewTy);
4887 else
4888 cast<ValueDecl>(D)->setType(NewTy);
4890 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4893 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4894 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4897 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4898 const AttributeCommonInfo &CI,
4899 const IdentifierInfo *Ident) {
4900 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4901 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4902 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4903 return nullptr;
4906 if (D->hasAttr<AlwaysInlineAttr>())
4907 return nullptr;
4909 return ::new (Context) AlwaysInlineAttr(Context, CI);
4912 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4913 const ParsedAttr &AL) {
4914 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4915 // Attribute applies to Var but not any subclass of it (like ParmVar,
4916 // ImplicitParm or VarTemplateSpecialization).
4917 if (VD->getKind() != Decl::Var) {
4918 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4919 << AL << AL.isRegularKeywordAttribute()
4920 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4921 : ExpectedVariableOrFunction);
4922 return nullptr;
4924 // Attribute does not apply to non-static local variables.
4925 if (VD->hasLocalStorage()) {
4926 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4927 return nullptr;
4931 return ::new (Context) InternalLinkageAttr(Context, AL);
4933 InternalLinkageAttr *
4934 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4935 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4936 // Attribute applies to Var but not any subclass of it (like ParmVar,
4937 // ImplicitParm or VarTemplateSpecialization).
4938 if (VD->getKind() != Decl::Var) {
4939 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4940 << &AL << AL.isRegularKeywordAttribute()
4941 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4942 : ExpectedVariableOrFunction);
4943 return nullptr;
4945 // Attribute does not apply to non-static local variables.
4946 if (VD->hasLocalStorage()) {
4947 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4948 return nullptr;
4952 return ::new (Context) InternalLinkageAttr(Context, AL);
4955 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4956 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4957 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4958 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4959 return nullptr;
4962 if (D->hasAttr<MinSizeAttr>())
4963 return nullptr;
4965 return ::new (Context) MinSizeAttr(Context, CI);
4968 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4969 StringRef Name) {
4970 if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4971 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4972 Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4973 << PrevSNA << &SNA
4974 << (PrevSNA->isRegularKeywordAttribute() ||
4975 SNA.isRegularKeywordAttribute());
4976 Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4979 D->dropAttr<SwiftNameAttr>();
4981 return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4984 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4985 const AttributeCommonInfo &CI) {
4986 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4987 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4988 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4989 D->dropAttr<AlwaysInlineAttr>();
4991 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4992 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4993 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4994 D->dropAttr<MinSizeAttr>();
4997 if (D->hasAttr<OptimizeNoneAttr>())
4998 return nullptr;
5000 return ::new (Context) OptimizeNoneAttr(Context, CI);
5003 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5004 if (AlwaysInlineAttr *Inline =
5005 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
5006 D->addAttr(Inline);
5009 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5010 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
5011 D->addAttr(MinSize);
5014 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5015 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
5016 D->addAttr(Optnone);
5019 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5020 const auto *VD = cast<VarDecl>(D);
5021 if (VD->hasLocalStorage()) {
5022 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5023 return;
5025 // constexpr variable may already get an implicit constant attr, which should
5026 // be replaced by the explicit constant attr.
5027 if (auto *A = D->getAttr<CUDAConstantAttr>()) {
5028 if (!A->isImplicit())
5029 return;
5030 D->dropAttr<CUDAConstantAttr>();
5032 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
5035 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5036 const auto *VD = cast<VarDecl>(D);
5037 // extern __shared__ is only allowed on arrays with no length (e.g.
5038 // "int x[]").
5039 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
5040 !isa<IncompleteArrayType>(VD->getType())) {
5041 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
5042 return;
5044 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
5045 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
5046 << S.CurrentCUDATarget())
5047 return;
5048 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
5051 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5052 const auto *FD = cast<FunctionDecl>(D);
5053 if (!FD->getReturnType()->isVoidType() &&
5054 !FD->getReturnType()->getAs<AutoType>() &&
5055 !FD->getReturnType()->isInstantiationDependentType()) {
5056 SourceRange RTRange = FD->getReturnTypeSourceRange();
5057 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
5058 << FD->getType()
5059 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
5060 : FixItHint());
5061 return;
5063 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
5064 if (Method->isInstance()) {
5065 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
5066 << Method;
5067 return;
5069 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
5071 // Only warn for "inline" when compiling for host, to cut down on noise.
5072 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
5073 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
5075 if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
5076 D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
5077 else
5078 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
5079 // In host compilation the kernel is emitted as a stub function, which is
5080 // a helper function for launching the kernel. The instructions in the helper
5081 // function has nothing to do with the source code of the kernel. Do not emit
5082 // debug info for the stub function to avoid confusing the debugger.
5083 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
5084 D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
5087 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5088 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5089 if (VD->hasLocalStorage()) {
5090 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5091 return;
5095 if (auto *A = D->getAttr<CUDADeviceAttr>()) {
5096 if (!A->isImplicit())
5097 return;
5098 D->dropAttr<CUDADeviceAttr>();
5100 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
5103 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5104 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5105 if (VD->hasLocalStorage()) {
5106 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5107 return;
5110 if (!D->hasAttr<HIPManagedAttr>())
5111 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
5112 if (!D->hasAttr<CUDADeviceAttr>())
5113 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
5116 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5117 const auto *Fn = cast<FunctionDecl>(D);
5118 if (!Fn->isInlineSpecified()) {
5119 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
5120 return;
5123 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
5124 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
5126 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
5129 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5130 if (hasDeclarator(D)) return;
5132 // Diagnostic is emitted elsewhere: here we store the (valid) AL
5133 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
5134 CallingConv CC;
5135 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
5136 return;
5138 if (!isa<ObjCMethodDecl>(D)) {
5139 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5140 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
5141 return;
5144 switch (AL.getKind()) {
5145 case ParsedAttr::AT_FastCall:
5146 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
5147 return;
5148 case ParsedAttr::AT_StdCall:
5149 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
5150 return;
5151 case ParsedAttr::AT_ThisCall:
5152 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
5153 return;
5154 case ParsedAttr::AT_CDecl:
5155 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
5156 return;
5157 case ParsedAttr::AT_Pascal:
5158 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
5159 return;
5160 case ParsedAttr::AT_SwiftCall:
5161 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
5162 return;
5163 case ParsedAttr::AT_SwiftAsyncCall:
5164 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
5165 return;
5166 case ParsedAttr::AT_VectorCall:
5167 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
5168 return;
5169 case ParsedAttr::AT_MSABI:
5170 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
5171 return;
5172 case ParsedAttr::AT_SysVABI:
5173 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
5174 return;
5175 case ParsedAttr::AT_RegCall:
5176 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
5177 return;
5178 case ParsedAttr::AT_Pcs: {
5179 PcsAttr::PCSType PCS;
5180 switch (CC) {
5181 case CC_AAPCS:
5182 PCS = PcsAttr::AAPCS;
5183 break;
5184 case CC_AAPCS_VFP:
5185 PCS = PcsAttr::AAPCS_VFP;
5186 break;
5187 default:
5188 llvm_unreachable("unexpected calling convention in pcs attribute");
5191 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
5192 return;
5194 case ParsedAttr::AT_AArch64VectorPcs:
5195 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
5196 return;
5197 case ParsedAttr::AT_AArch64SVEPcs:
5198 D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
5199 return;
5200 case ParsedAttr::AT_AMDGPUKernelCall:
5201 D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
5202 return;
5203 case ParsedAttr::AT_IntelOclBicc:
5204 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
5205 return;
5206 case ParsedAttr::AT_PreserveMost:
5207 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
5208 return;
5209 case ParsedAttr::AT_PreserveAll:
5210 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
5211 return;
5212 default:
5213 llvm_unreachable("unexpected attribute kind");
5217 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5218 if (!AL.checkAtLeastNumArgs(S, 1))
5219 return;
5221 std::vector<StringRef> DiagnosticIdentifiers;
5222 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5223 StringRef RuleName;
5225 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
5226 return;
5228 // FIXME: Warn if the rule name is unknown. This is tricky because only
5229 // clang-tidy knows about available rules.
5230 DiagnosticIdentifiers.push_back(RuleName);
5232 D->addAttr(::new (S.Context)
5233 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
5234 DiagnosticIdentifiers.size()));
5237 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5238 TypeSourceInfo *DerefTypeLoc = nullptr;
5239 QualType ParmType;
5240 if (AL.hasParsedType()) {
5241 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
5243 unsigned SelectIdx = ~0U;
5244 if (ParmType->isReferenceType())
5245 SelectIdx = 0;
5246 else if (ParmType->isArrayType())
5247 SelectIdx = 1;
5249 if (SelectIdx != ~0U) {
5250 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
5251 << SelectIdx << AL;
5252 return;
5256 // To check if earlier decl attributes do not conflict the newly parsed ones
5257 // we always add (and check) the attribute to the canonical decl. We need
5258 // to repeat the check for attribute mutual exclusion because we're attaching
5259 // all of the attributes to the canonical declaration rather than the current
5260 // declaration.
5261 D = D->getCanonicalDecl();
5262 if (AL.getKind() == ParsedAttr::AT_Owner) {
5263 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
5264 return;
5265 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
5266 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
5267 ? OAttr->getDerefType().getTypePtr()
5268 : nullptr;
5269 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5270 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5271 << AL << OAttr
5272 << (AL.isRegularKeywordAttribute() ||
5273 OAttr->isRegularKeywordAttribute());
5274 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
5276 return;
5278 for (Decl *Redecl : D->redecls()) {
5279 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
5281 } else {
5282 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
5283 return;
5284 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
5285 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
5286 ? PAttr->getDerefType().getTypePtr()
5287 : nullptr;
5288 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5289 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5290 << AL << PAttr
5291 << (AL.isRegularKeywordAttribute() ||
5292 PAttr->isRegularKeywordAttribute());
5293 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
5295 return;
5297 for (Decl *Redecl : D->redecls()) {
5298 Redecl->addAttr(::new (S.Context)
5299 PointerAttr(S.Context, AL, DerefTypeLoc));
5304 static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5305 if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
5306 return;
5307 if (!D->hasAttr<RandomizeLayoutAttr>())
5308 D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
5311 static void handleNoRandomizeLayoutAttr(Sema &S, Decl *D,
5312 const ParsedAttr &AL) {
5313 if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
5314 return;
5315 if (!D->hasAttr<NoRandomizeLayoutAttr>())
5316 D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
5319 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
5320 const FunctionDecl *FD) {
5321 if (Attrs.isInvalid())
5322 return true;
5324 if (Attrs.hasProcessingCache()) {
5325 CC = (CallingConv) Attrs.getProcessingCache();
5326 return false;
5329 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
5330 if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
5331 Attrs.setInvalid();
5332 return true;
5335 // TODO: diagnose uses of these conventions on the wrong target.
5336 switch (Attrs.getKind()) {
5337 case ParsedAttr::AT_CDecl:
5338 CC = CC_C;
5339 break;
5340 case ParsedAttr::AT_FastCall:
5341 CC = CC_X86FastCall;
5342 break;
5343 case ParsedAttr::AT_StdCall:
5344 CC = CC_X86StdCall;
5345 break;
5346 case ParsedAttr::AT_ThisCall:
5347 CC = CC_X86ThisCall;
5348 break;
5349 case ParsedAttr::AT_Pascal:
5350 CC = CC_X86Pascal;
5351 break;
5352 case ParsedAttr::AT_SwiftCall:
5353 CC = CC_Swift;
5354 break;
5355 case ParsedAttr::AT_SwiftAsyncCall:
5356 CC = CC_SwiftAsync;
5357 break;
5358 case ParsedAttr::AT_VectorCall:
5359 CC = CC_X86VectorCall;
5360 break;
5361 case ParsedAttr::AT_AArch64VectorPcs:
5362 CC = CC_AArch64VectorCall;
5363 break;
5364 case ParsedAttr::AT_AArch64SVEPcs:
5365 CC = CC_AArch64SVEPCS;
5366 break;
5367 case ParsedAttr::AT_AMDGPUKernelCall:
5368 CC = CC_AMDGPUKernelCall;
5369 break;
5370 case ParsedAttr::AT_RegCall:
5371 CC = CC_X86RegCall;
5372 break;
5373 case ParsedAttr::AT_MSABI:
5374 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
5375 CC_Win64;
5376 break;
5377 case ParsedAttr::AT_SysVABI:
5378 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
5379 CC_C;
5380 break;
5381 case ParsedAttr::AT_Pcs: {
5382 StringRef StrRef;
5383 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
5384 Attrs.setInvalid();
5385 return true;
5387 if (StrRef == "aapcs") {
5388 CC = CC_AAPCS;
5389 break;
5390 } else if (StrRef == "aapcs-vfp") {
5391 CC = CC_AAPCS_VFP;
5392 break;
5395 Attrs.setInvalid();
5396 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
5397 return true;
5399 case ParsedAttr::AT_IntelOclBicc:
5400 CC = CC_IntelOclBicc;
5401 break;
5402 case ParsedAttr::AT_PreserveMost:
5403 CC = CC_PreserveMost;
5404 break;
5405 case ParsedAttr::AT_PreserveAll:
5406 CC = CC_PreserveAll;
5407 break;
5408 default: llvm_unreachable("unexpected attribute kind");
5411 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
5412 const TargetInfo &TI = Context.getTargetInfo();
5413 // CUDA functions may have host and/or device attributes which indicate
5414 // their targeted execution environment, therefore the calling convention
5415 // of functions in CUDA should be checked against the target deduced based
5416 // on their host/device attributes.
5417 if (LangOpts.CUDA) {
5418 auto *Aux = Context.getAuxTargetInfo();
5419 auto CudaTarget = IdentifyCUDATarget(FD);
5420 bool CheckHost = false, CheckDevice = false;
5421 switch (CudaTarget) {
5422 case CFT_HostDevice:
5423 CheckHost = true;
5424 CheckDevice = true;
5425 break;
5426 case CFT_Host:
5427 CheckHost = true;
5428 break;
5429 case CFT_Device:
5430 case CFT_Global:
5431 CheckDevice = true;
5432 break;
5433 case CFT_InvalidTarget:
5434 llvm_unreachable("unexpected cuda target");
5436 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
5437 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
5438 if (CheckHost && HostTI)
5439 A = HostTI->checkCallingConvention(CC);
5440 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
5441 A = DeviceTI->checkCallingConvention(CC);
5442 } else {
5443 A = TI.checkCallingConvention(CC);
5446 switch (A) {
5447 case TargetInfo::CCCR_OK:
5448 break;
5450 case TargetInfo::CCCR_Ignore:
5451 // Treat an ignored convention as if it was an explicit C calling convention
5452 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
5453 // that command line flags that change the default convention to
5454 // __vectorcall don't affect declarations marked __stdcall.
5455 CC = CC_C;
5456 break;
5458 case TargetInfo::CCCR_Error:
5459 Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
5460 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5461 break;
5463 case TargetInfo::CCCR_Warning: {
5464 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
5465 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5467 // This convention is not valid for the target. Use the default function or
5468 // method calling convention.
5469 bool IsCXXMethod = false, IsVariadic = false;
5470 if (FD) {
5471 IsCXXMethod = FD->isCXXInstanceMember();
5472 IsVariadic = FD->isVariadic();
5474 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
5475 break;
5479 Attrs.setProcessingCache((unsigned) CC);
5480 return false;
5483 /// Pointer-like types in the default address space.
5484 static bool isValidSwiftContextType(QualType Ty) {
5485 if (!Ty->hasPointerRepresentation())
5486 return Ty->isDependentType();
5487 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
5490 /// Pointers and references in the default address space.
5491 static bool isValidSwiftIndirectResultType(QualType Ty) {
5492 if (const auto *PtrType = Ty->getAs<PointerType>()) {
5493 Ty = PtrType->getPointeeType();
5494 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5495 Ty = RefType->getPointeeType();
5496 } else {
5497 return Ty->isDependentType();
5499 return Ty.getAddressSpace() == LangAS::Default;
5502 /// Pointers and references to pointers in the default address space.
5503 static bool isValidSwiftErrorResultType(QualType Ty) {
5504 if (const auto *PtrType = Ty->getAs<PointerType>()) {
5505 Ty = PtrType->getPointeeType();
5506 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5507 Ty = RefType->getPointeeType();
5508 } else {
5509 return Ty->isDependentType();
5511 if (!Ty.getQualifiers().empty())
5512 return false;
5513 return isValidSwiftContextType(Ty);
5516 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
5517 ParameterABI abi) {
5519 QualType type = cast<ParmVarDecl>(D)->getType();
5521 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5522 if (existingAttr->getABI() != abi) {
5523 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5524 << getParameterABISpelling(abi) << existingAttr
5525 << (CI.isRegularKeywordAttribute() ||
5526 existingAttr->isRegularKeywordAttribute());
5527 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5528 return;
5532 switch (abi) {
5533 case ParameterABI::Ordinary:
5534 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5536 case ParameterABI::SwiftContext:
5537 if (!isValidSwiftContextType(type)) {
5538 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5539 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5541 D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
5542 return;
5544 case ParameterABI::SwiftAsyncContext:
5545 if (!isValidSwiftContextType(type)) {
5546 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5547 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5549 D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5550 return;
5552 case ParameterABI::SwiftErrorResult:
5553 if (!isValidSwiftErrorResultType(type)) {
5554 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5555 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5557 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5558 return;
5560 case ParameterABI::SwiftIndirectResult:
5561 if (!isValidSwiftIndirectResultType(type)) {
5562 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5563 << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5565 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5566 return;
5568 llvm_unreachable("bad parameter ABI attribute");
5571 /// Checks a regparm attribute, returning true if it is ill-formed and
5572 /// otherwise setting numParams to the appropriate value.
5573 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5574 if (AL.isInvalid())
5575 return true;
5577 if (!AL.checkExactlyNumArgs(*this, 1)) {
5578 AL.setInvalid();
5579 return true;
5582 uint32_t NP;
5583 Expr *NumParamsExpr = AL.getArgAsExpr(0);
5584 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
5585 AL.setInvalid();
5586 return true;
5589 if (Context.getTargetInfo().getRegParmMax() == 0) {
5590 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5591 << NumParamsExpr->getSourceRange();
5592 AL.setInvalid();
5593 return true;
5596 numParams = NP;
5597 if (numParams > Context.getTargetInfo().getRegParmMax()) {
5598 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5599 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5600 AL.setInvalid();
5601 return true;
5604 return false;
5607 // Checks whether an argument of launch_bounds attribute is
5608 // acceptable, performs implicit conversion to Rvalue, and returns
5609 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5610 // and may output an error.
5611 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5612 const CUDALaunchBoundsAttr &AL,
5613 const unsigned Idx) {
5614 if (S.DiagnoseUnexpandedParameterPack(E))
5615 return nullptr;
5617 // Accept template arguments for now as they depend on something else.
5618 // We'll get to check them when they eventually get instantiated.
5619 if (E->isValueDependent())
5620 return E;
5622 std::optional<llvm::APSInt> I = llvm::APSInt(64);
5623 if (!(I = E->getIntegerConstantExpr(S.Context))) {
5624 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5625 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5626 return nullptr;
5628 // Make sure we can fit it in 32 bits.
5629 if (!I->isIntN(32)) {
5630 S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5631 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5632 return nullptr;
5634 if (*I < 0)
5635 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5636 << &AL << Idx << E->getSourceRange();
5638 // We may need to perform implicit conversion of the argument.
5639 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5640 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5641 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5642 assert(!ValArg.isInvalid() &&
5643 "Unexpected PerformCopyInitialization() failure.");
5645 return ValArg.getAs<Expr>();
5648 CUDALaunchBoundsAttr *
5649 Sema::CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads,
5650 Expr *MinBlocks) {
5651 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
5652 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5653 if (MaxThreads == nullptr)
5654 return nullptr;
5656 if (MinBlocks) {
5657 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5658 if (MinBlocks == nullptr)
5659 return nullptr;
5662 return ::new (Context)
5663 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks);
5666 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5667 Expr *MaxThreads, Expr *MinBlocks) {
5668 if (auto *Attr = CreateLaunchBoundsAttr(CI, MaxThreads, MinBlocks))
5669 D->addAttr(Attr);
5672 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5673 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
5674 return;
5676 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5677 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
5680 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5681 const ParsedAttr &AL) {
5682 if (!AL.isArgIdent(0)) {
5683 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5684 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5685 return;
5688 ParamIdx ArgumentIdx;
5689 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5690 ArgumentIdx))
5691 return;
5693 ParamIdx TypeTagIdx;
5694 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5695 TypeTagIdx))
5696 return;
5698 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5699 if (IsPointer) {
5700 // Ensure that buffer has a pointer type.
5701 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5702 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5703 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5704 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5707 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5708 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5709 IsPointer));
5712 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5713 const ParsedAttr &AL) {
5714 if (!AL.isArgIdent(0)) {
5715 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5716 << AL << 1 << AANT_ArgumentIdentifier;
5717 return;
5720 if (!AL.checkExactlyNumArgs(S, 1))
5721 return;
5723 if (!isa<VarDecl>(D)) {
5724 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5725 << AL << AL.isRegularKeywordAttribute() << ExpectedVariable;
5726 return;
5729 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5730 TypeSourceInfo *MatchingCTypeLoc = nullptr;
5731 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5732 assert(MatchingCTypeLoc && "no type source info for attribute argument");
5734 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5735 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5736 AL.getMustBeNull()));
5739 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5740 ParamIdx ArgCount;
5742 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5743 ArgCount,
5744 true /* CanIndexImplicitThis */))
5745 return;
5747 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5748 D->addAttr(::new (S.Context)
5749 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5752 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5753 const ParsedAttr &AL) {
5754 uint32_t Count = 0, Offset = 0;
5755 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5756 return;
5757 if (AL.getNumArgs() == 2) {
5758 Expr *Arg = AL.getArgAsExpr(1);
5759 if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5760 return;
5761 if (Count < Offset) {
5762 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5763 << &AL << 0 << Count << Arg->getBeginLoc();
5764 return;
5767 D->addAttr(::new (S.Context)
5768 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5771 namespace {
5772 struct IntrinToName {
5773 uint32_t Id;
5774 int32_t FullName;
5775 int32_t ShortName;
5777 } // unnamed namespace
5779 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5780 ArrayRef<IntrinToName> Map,
5781 const char *IntrinNames) {
5782 if (AliasName.startswith("__arm_"))
5783 AliasName = AliasName.substr(6);
5784 const IntrinToName *It =
5785 llvm::lower_bound(Map, BuiltinID, [](const IntrinToName &L, unsigned Id) {
5786 return L.Id < Id;
5788 if (It == Map.end() || It->Id != BuiltinID)
5789 return false;
5790 StringRef FullName(&IntrinNames[It->FullName]);
5791 if (AliasName == FullName)
5792 return true;
5793 if (It->ShortName == -1)
5794 return false;
5795 StringRef ShortName(&IntrinNames[It->ShortName]);
5796 return AliasName == ShortName;
5799 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5800 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5801 // The included file defines:
5802 // - ArrayRef<IntrinToName> Map
5803 // - const char IntrinNames[]
5804 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5807 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5808 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5809 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5812 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5813 StringRef AliasName) {
5814 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5815 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5816 return BuiltinID >= AArch64::FirstSVEBuiltin &&
5817 BuiltinID <= AArch64::LastSVEBuiltin;
5820 static bool ArmSmeAliasValid(ASTContext &Context, unsigned BuiltinID,
5821 StringRef AliasName) {
5822 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5823 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5824 return BuiltinID >= AArch64::FirstSMEBuiltin &&
5825 BuiltinID <= AArch64::LastSMEBuiltin;
5828 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5829 if (!AL.isArgIdent(0)) {
5830 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5831 << AL << 1 << AANT_ArgumentIdentifier;
5832 return;
5835 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5836 unsigned BuiltinID = Ident->getBuiltinID();
5837 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5839 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5840 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName) &&
5841 !ArmSmeAliasValid(S.Context, BuiltinID, AliasName)) ||
5842 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5843 !ArmCdeAliasValid(BuiltinID, AliasName))) {
5844 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5845 return;
5848 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5851 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
5852 return BuiltinID >= RISCV::FirstRVVBuiltin &&
5853 BuiltinID <= RISCV::LastRVVBuiltin;
5856 static void handleBuiltinAliasAttr(Sema &S, Decl *D,
5857 const ParsedAttr &AL) {
5858 if (!AL.isArgIdent(0)) {
5859 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5860 << AL << 1 << AANT_ArgumentIdentifier;
5861 return;
5864 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5865 unsigned BuiltinID = Ident->getBuiltinID();
5866 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5868 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5869 bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
5870 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
5871 bool IsHLSL = S.Context.getLangOpts().HLSL;
5872 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5873 (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
5874 !ArmCdeAliasValid(BuiltinID, AliasName)) ||
5875 (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
5876 (!IsAArch64 && !IsARM && !IsRISCV && !IsHLSL)) {
5877 S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
5878 return;
5881 D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
5884 //===----------------------------------------------------------------------===//
5885 // Checker-specific attribute handlers.
5886 //===----------------------------------------------------------------------===//
5887 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5888 return QT->isDependentType() || QT->isObjCRetainableType();
5891 static bool isValidSubjectOfNSAttribute(QualType QT) {
5892 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5893 QT->isObjCNSObjectType();
5896 static bool isValidSubjectOfCFAttribute(QualType QT) {
5897 return QT->isDependentType() || QT->isPointerType() ||
5898 isValidSubjectOfNSAttribute(QT);
5901 static bool isValidSubjectOfOSAttribute(QualType QT) {
5902 if (QT->isDependentType())
5903 return true;
5904 QualType PT = QT->getPointeeType();
5905 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5908 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5909 RetainOwnershipKind K,
5910 bool IsTemplateInstantiation) {
5911 ValueDecl *VD = cast<ValueDecl>(D);
5912 switch (K) {
5913 case RetainOwnershipKind::OS:
5914 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5915 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5916 diag::warn_ns_attribute_wrong_parameter_type,
5917 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5918 return;
5919 case RetainOwnershipKind::NS:
5920 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5921 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5923 // These attributes are normally just advisory, but in ARC, ns_consumed
5924 // is significant. Allow non-dependent code to contain inappropriate
5925 // attributes even in ARC, but require template instantiations to be
5926 // set up correctly.
5927 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5928 ? diag::err_ns_attribute_wrong_parameter_type
5929 : diag::warn_ns_attribute_wrong_parameter_type),
5930 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5931 return;
5932 case RetainOwnershipKind::CF:
5933 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5934 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5935 diag::warn_ns_attribute_wrong_parameter_type,
5936 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5937 return;
5941 static Sema::RetainOwnershipKind
5942 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5943 switch (AL.getKind()) {
5944 case ParsedAttr::AT_CFConsumed:
5945 case ParsedAttr::AT_CFReturnsRetained:
5946 case ParsedAttr::AT_CFReturnsNotRetained:
5947 return Sema::RetainOwnershipKind::CF;
5948 case ParsedAttr::AT_OSConsumesThis:
5949 case ParsedAttr::AT_OSConsumed:
5950 case ParsedAttr::AT_OSReturnsRetained:
5951 case ParsedAttr::AT_OSReturnsNotRetained:
5952 case ParsedAttr::AT_OSReturnsRetainedOnZero:
5953 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5954 return Sema::RetainOwnershipKind::OS;
5955 case ParsedAttr::AT_NSConsumesSelf:
5956 case ParsedAttr::AT_NSConsumed:
5957 case ParsedAttr::AT_NSReturnsRetained:
5958 case ParsedAttr::AT_NSReturnsNotRetained:
5959 case ParsedAttr::AT_NSReturnsAutoreleased:
5960 return Sema::RetainOwnershipKind::NS;
5961 default:
5962 llvm_unreachable("Wrong argument supplied");
5966 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5967 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5968 return false;
5970 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5971 << "'ns_returns_retained'" << 0 << 0;
5972 return true;
5975 /// \return whether the parameter is a pointer to OSObject pointer.
5976 static bool isValidOSObjectOutParameter(const Decl *D) {
5977 const auto *PVD = dyn_cast<ParmVarDecl>(D);
5978 if (!PVD)
5979 return false;
5980 QualType QT = PVD->getType();
5981 QualType PT = QT->getPointeeType();
5982 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5985 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5986 const ParsedAttr &AL) {
5987 QualType ReturnType;
5988 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5990 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5991 ReturnType = MD->getReturnType();
5992 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5993 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5994 return; // ignore: was handled as a type attribute
5995 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5996 ReturnType = PD->getType();
5997 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5998 ReturnType = FD->getReturnType();
5999 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
6000 // Attributes on parameters are used for out-parameters,
6001 // passed as pointers-to-pointers.
6002 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
6003 ? /*pointer-to-CF-pointer*/2
6004 : /*pointer-to-OSObject-pointer*/3;
6005 ReturnType = Param->getType()->getPointeeType();
6006 if (ReturnType.isNull()) {
6007 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6008 << AL << DiagID << AL.getRange();
6009 return;
6011 } else if (AL.isUsedAsTypeAttr()) {
6012 return;
6013 } else {
6014 AttributeDeclKind ExpectedDeclKind;
6015 switch (AL.getKind()) {
6016 default: llvm_unreachable("invalid ownership attribute");
6017 case ParsedAttr::AT_NSReturnsRetained:
6018 case ParsedAttr::AT_NSReturnsAutoreleased:
6019 case ParsedAttr::AT_NSReturnsNotRetained:
6020 ExpectedDeclKind = ExpectedFunctionOrMethod;
6021 break;
6023 case ParsedAttr::AT_OSReturnsRetained:
6024 case ParsedAttr::AT_OSReturnsNotRetained:
6025 case ParsedAttr::AT_CFReturnsRetained:
6026 case ParsedAttr::AT_CFReturnsNotRetained:
6027 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
6028 break;
6030 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
6031 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6032 << ExpectedDeclKind;
6033 return;
6036 bool TypeOK;
6037 bool Cf;
6038 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
6039 switch (AL.getKind()) {
6040 default: llvm_unreachable("invalid ownership attribute");
6041 case ParsedAttr::AT_NSReturnsRetained:
6042 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
6043 Cf = false;
6044 break;
6046 case ParsedAttr::AT_NSReturnsAutoreleased:
6047 case ParsedAttr::AT_NSReturnsNotRetained:
6048 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
6049 Cf = false;
6050 break;
6052 case ParsedAttr::AT_CFReturnsRetained:
6053 case ParsedAttr::AT_CFReturnsNotRetained:
6054 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
6055 Cf = true;
6056 break;
6058 case ParsedAttr::AT_OSReturnsRetained:
6059 case ParsedAttr::AT_OSReturnsNotRetained:
6060 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
6061 Cf = true;
6062 ParmDiagID = 3; // Pointer-to-OSObject-pointer
6063 break;
6066 if (!TypeOK) {
6067 if (AL.isUsedAsTypeAttr())
6068 return;
6070 if (isa<ParmVarDecl>(D)) {
6071 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6072 << AL << ParmDiagID << AL.getRange();
6073 } else {
6074 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
6075 enum : unsigned {
6076 Function,
6077 Method,
6078 Property
6079 } SubjectKind = Function;
6080 if (isa<ObjCMethodDecl>(D))
6081 SubjectKind = Method;
6082 else if (isa<ObjCPropertyDecl>(D))
6083 SubjectKind = Property;
6084 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6085 << AL << SubjectKind << Cf << AL.getRange();
6087 return;
6090 switch (AL.getKind()) {
6091 default:
6092 llvm_unreachable("invalid ownership attribute");
6093 case ParsedAttr::AT_NSReturnsAutoreleased:
6094 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
6095 return;
6096 case ParsedAttr::AT_CFReturnsNotRetained:
6097 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
6098 return;
6099 case ParsedAttr::AT_NSReturnsNotRetained:
6100 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
6101 return;
6102 case ParsedAttr::AT_CFReturnsRetained:
6103 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
6104 return;
6105 case ParsedAttr::AT_NSReturnsRetained:
6106 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
6107 return;
6108 case ParsedAttr::AT_OSReturnsRetained:
6109 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
6110 return;
6111 case ParsedAttr::AT_OSReturnsNotRetained:
6112 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
6113 return;
6117 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
6118 const ParsedAttr &Attrs) {
6119 const int EP_ObjCMethod = 1;
6120 const int EP_ObjCProperty = 2;
6122 SourceLocation loc = Attrs.getLoc();
6123 QualType resultType;
6124 if (isa<ObjCMethodDecl>(D))
6125 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
6126 else
6127 resultType = cast<ObjCPropertyDecl>(D)->getType();
6129 if (!resultType->isReferenceType() &&
6130 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
6131 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6132 << SourceRange(loc) << Attrs
6133 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
6134 << /*non-retainable pointer*/ 2;
6136 // Drop the attribute.
6137 return;
6140 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
6143 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
6144 const ParsedAttr &Attrs) {
6145 const auto *Method = cast<ObjCMethodDecl>(D);
6147 const DeclContext *DC = Method->getDeclContext();
6148 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
6149 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6150 << 0;
6151 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
6152 return;
6154 if (Method->getMethodFamily() == OMF_dealloc) {
6155 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6156 << 1;
6157 return;
6160 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
6163 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
6164 auto *E = AL.getArgAsExpr(0);
6165 auto Loc = E ? E->getBeginLoc() : AL.getLoc();
6167 auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
6168 if (!DRE) {
6169 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
6170 return;
6173 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6174 if (!VD) {
6175 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
6176 return;
6179 if (!isNSStringType(VD->getType(), S.Context) &&
6180 !isCFStringType(VD->getType(), S.Context)) {
6181 S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
6182 return;
6185 D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
6188 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6189 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
6191 if (!Parm) {
6192 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6193 return;
6196 // Typedefs only allow objc_bridge(id) and have some additional checking.
6197 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
6198 if (!Parm->Ident->isStr("id")) {
6199 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
6200 return;
6203 // Only allow 'cv void *'.
6204 QualType T = TD->getUnderlyingType();
6205 if (!T->isVoidPointerType()) {
6206 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
6207 return;
6211 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
6214 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
6215 const ParsedAttr &AL) {
6216 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
6218 if (!Parm) {
6219 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6220 return;
6223 D->addAttr(::new (S.Context)
6224 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
6227 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
6228 const ParsedAttr &AL) {
6229 IdentifierInfo *RelatedClass =
6230 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
6231 if (!RelatedClass) {
6232 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6233 return;
6235 IdentifierInfo *ClassMethod =
6236 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
6237 IdentifierInfo *InstanceMethod =
6238 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
6239 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
6240 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
6243 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
6244 const ParsedAttr &AL) {
6245 DeclContext *Ctx = D->getDeclContext();
6247 // This attribute can only be applied to methods in interfaces or class
6248 // extensions.
6249 if (!isa<ObjCInterfaceDecl>(Ctx) &&
6250 !(isa<ObjCCategoryDecl>(Ctx) &&
6251 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
6252 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
6253 return;
6256 ObjCInterfaceDecl *IFace;
6257 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
6258 IFace = CatDecl->getClassInterface();
6259 else
6260 IFace = cast<ObjCInterfaceDecl>(Ctx);
6262 if (!IFace)
6263 return;
6265 IFace->setHasDesignatedInitializers();
6266 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
6269 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
6270 StringRef MetaDataName;
6271 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
6272 return;
6273 D->addAttr(::new (S.Context)
6274 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
6277 // When a user wants to use objc_boxable with a union or struct
6278 // but they don't have access to the declaration (legacy/third-party code)
6279 // then they can 'enable' this feature with a typedef:
6280 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
6281 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
6282 bool notify = false;
6284 auto *RD = dyn_cast<RecordDecl>(D);
6285 if (RD && RD->getDefinition()) {
6286 RD = RD->getDefinition();
6287 notify = true;
6290 if (RD) {
6291 ObjCBoxableAttr *BoxableAttr =
6292 ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
6293 RD->addAttr(BoxableAttr);
6294 if (notify) {
6295 // we need to notify ASTReader/ASTWriter about
6296 // modification of existing declaration
6297 if (ASTMutationListener *L = S.getASTMutationListener())
6298 L->AddedAttributeToRecord(BoxableAttr, RD);
6303 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6304 if (hasDeclarator(D))
6305 return;
6307 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
6308 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6309 << ExpectedVariable;
6312 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
6313 const ParsedAttr &AL) {
6314 const auto *VD = cast<ValueDecl>(D);
6315 QualType QT = VD->getType();
6317 if (!QT->isDependentType() &&
6318 !QT->isObjCLifetimeType()) {
6319 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
6320 << QT;
6321 return;
6324 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
6326 // If we have no lifetime yet, check the lifetime we're presumably
6327 // going to infer.
6328 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
6329 Lifetime = QT->getObjCARCImplicitLifetime();
6331 switch (Lifetime) {
6332 case Qualifiers::OCL_None:
6333 assert(QT->isDependentType() &&
6334 "didn't infer lifetime for non-dependent type?");
6335 break;
6337 case Qualifiers::OCL_Weak: // meaningful
6338 case Qualifiers::OCL_Strong: // meaningful
6339 break;
6341 case Qualifiers::OCL_ExplicitNone:
6342 case Qualifiers::OCL_Autoreleasing:
6343 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
6344 << (Lifetime == Qualifiers::OCL_Autoreleasing);
6345 break;
6348 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
6351 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6352 // Make sure that there is a string literal as the annotation's single
6353 // argument.
6354 StringRef Str;
6355 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
6356 return;
6358 D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
6361 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
6362 // Make sure that there is a string literal as the annotation's single
6363 // argument.
6364 StringRef BT;
6365 if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
6366 return;
6368 // Warn about duplicate attributes if they have different arguments, but drop
6369 // any duplicate attributes regardless.
6370 if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
6371 if (Other->getSwiftType() != BT)
6372 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
6373 return;
6376 D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
6379 static bool isErrorParameter(Sema &S, QualType QT) {
6380 const auto *PT = QT->getAs<PointerType>();
6381 if (!PT)
6382 return false;
6384 QualType Pointee = PT->getPointeeType();
6386 // Check for NSError**.
6387 if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
6388 if (const auto *ID = OPT->getInterfaceDecl())
6389 if (ID->getIdentifier() == S.getNSErrorIdent())
6390 return true;
6392 // Check for CFError**.
6393 if (const auto *PT = Pointee->getAs<PointerType>())
6394 if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
6395 if (S.isCFError(RT->getDecl()))
6396 return true;
6398 return false;
6401 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
6402 auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6403 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6404 if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
6405 return true;
6408 S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
6409 << AL << isa<ObjCMethodDecl>(D);
6410 return false;
6413 auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6414 // - C, ObjC, and block pointers are definitely okay.
6415 // - References are definitely not okay.
6416 // - nullptr_t is weird, but acceptable.
6417 QualType RT = getFunctionOrMethodResultType(D);
6418 if (RT->hasPointerRepresentation() && !RT->isReferenceType())
6419 return true;
6421 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6422 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6423 << /*pointer*/ 1;
6424 return false;
6427 auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6428 QualType RT = getFunctionOrMethodResultType(D);
6429 if (RT->isIntegralType(S.Context))
6430 return true;
6432 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6433 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6434 << /*integral*/ 0;
6435 return false;
6438 if (D->isInvalidDecl())
6439 return;
6441 IdentifierLoc *Loc = AL.getArgAsIdent(0);
6442 SwiftErrorAttr::ConventionKind Convention;
6443 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
6444 Convention)) {
6445 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6446 << AL << Loc->Ident;
6447 return;
6450 switch (Convention) {
6451 case SwiftErrorAttr::None:
6452 // No additional validation required.
6453 break;
6455 case SwiftErrorAttr::NonNullError:
6456 if (!hasErrorParameter(S, D, AL))
6457 return;
6458 break;
6460 case SwiftErrorAttr::NullResult:
6461 if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
6462 return;
6463 break;
6465 case SwiftErrorAttr::NonZeroResult:
6466 case SwiftErrorAttr::ZeroResult:
6467 if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
6468 return;
6469 break;
6472 D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
6475 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
6476 const SwiftAsyncErrorAttr *ErrorAttr,
6477 const SwiftAsyncAttr *AsyncAttr) {
6478 if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
6479 if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
6480 S.Diag(AsyncAttr->getLocation(),
6481 diag::err_swift_async_error_without_swift_async)
6482 << AsyncAttr << isa<ObjCMethodDecl>(D);
6484 return;
6487 const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
6488 D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
6489 // handleSwiftAsyncAttr already verified the type is correct, so no need to
6490 // double-check it here.
6491 const auto *FuncTy = HandlerParam->getType()
6492 ->castAs<BlockPointerType>()
6493 ->getPointeeType()
6494 ->getAs<FunctionProtoType>();
6495 ArrayRef<QualType> BlockParams;
6496 if (FuncTy)
6497 BlockParams = FuncTy->getParamTypes();
6499 switch (ErrorAttr->getConvention()) {
6500 case SwiftAsyncErrorAttr::ZeroArgument:
6501 case SwiftAsyncErrorAttr::NonZeroArgument: {
6502 uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
6503 if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
6504 S.Diag(ErrorAttr->getLocation(),
6505 diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
6506 return;
6508 QualType ErrorParam = BlockParams[ParamIdx - 1];
6509 if (!ErrorParam->isIntegralType(S.Context)) {
6510 StringRef ConvStr =
6511 ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
6512 ? "zero_argument"
6513 : "nonzero_argument";
6514 S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
6515 << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
6516 return;
6518 break;
6520 case SwiftAsyncErrorAttr::NonNullError: {
6521 bool AnyErrorParams = false;
6522 for (QualType Param : BlockParams) {
6523 // Check for NSError *.
6524 if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
6525 if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
6526 if (ID->getIdentifier() == S.getNSErrorIdent()) {
6527 AnyErrorParams = true;
6528 break;
6532 // Check for CFError *.
6533 if (const auto *PtrTy = Param->getAs<PointerType>()) {
6534 if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
6535 if (S.isCFError(RT->getDecl())) {
6536 AnyErrorParams = true;
6537 break;
6543 if (!AnyErrorParams) {
6544 S.Diag(ErrorAttr->getLocation(),
6545 diag::err_swift_async_error_no_error_parameter)
6546 << ErrorAttr << isa<ObjCMethodDecl>(D);
6547 return;
6549 break;
6551 case SwiftAsyncErrorAttr::None:
6552 break;
6556 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
6557 IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
6558 SwiftAsyncErrorAttr::ConventionKind ConvKind;
6559 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
6560 ConvKind)) {
6561 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6562 << AL << IDLoc->Ident;
6563 return;
6566 uint32_t ParamIdx = 0;
6567 switch (ConvKind) {
6568 case SwiftAsyncErrorAttr::ZeroArgument:
6569 case SwiftAsyncErrorAttr::NonZeroArgument: {
6570 if (!AL.checkExactlyNumArgs(S, 2))
6571 return;
6573 Expr *IdxExpr = AL.getArgAsExpr(1);
6574 if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
6575 return;
6576 break;
6578 case SwiftAsyncErrorAttr::NonNullError:
6579 case SwiftAsyncErrorAttr::None: {
6580 if (!AL.checkExactlyNumArgs(S, 1))
6581 return;
6582 break;
6586 auto *ErrorAttr =
6587 ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
6588 D->addAttr(ErrorAttr);
6590 if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
6591 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6594 // For a function, this will validate a compound Swift name, e.g.
6595 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6596 // the function will output the number of parameter names, and whether this is a
6597 // single-arg initializer.
6599 // For a type, enum constant, property, or variable declaration, this will
6600 // validate either a simple identifier, or a qualified
6601 // <code>context.identifier</code> name.
6602 static bool
6603 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
6604 StringRef Name, unsigned &SwiftParamCount,
6605 bool &IsSingleParamInit) {
6606 SwiftParamCount = 0;
6607 IsSingleParamInit = false;
6609 // Check whether this will be mapped to a getter or setter of a property.
6610 bool IsGetter = false, IsSetter = false;
6611 if (Name.startswith("getter:")) {
6612 IsGetter = true;
6613 Name = Name.substr(7);
6614 } else if (Name.startswith("setter:")) {
6615 IsSetter = true;
6616 Name = Name.substr(7);
6619 if (Name.back() != ')') {
6620 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6621 return false;
6624 bool IsMember = false;
6625 StringRef ContextName, BaseName, Parameters;
6627 std::tie(BaseName, Parameters) = Name.split('(');
6629 // Split at the first '.', if it exists, which separates the context name
6630 // from the base name.
6631 std::tie(ContextName, BaseName) = BaseName.split('.');
6632 if (BaseName.empty()) {
6633 BaseName = ContextName;
6634 ContextName = StringRef();
6635 } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
6636 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6637 << AL << /*context*/ 1;
6638 return false;
6639 } else {
6640 IsMember = true;
6643 if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
6644 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6645 << AL << /*basename*/ 0;
6646 return false;
6649 bool IsSubscript = BaseName == "subscript";
6650 // A subscript accessor must be a getter or setter.
6651 if (IsSubscript && !IsGetter && !IsSetter) {
6652 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6653 << AL << /* getter or setter */ 0;
6654 return false;
6657 if (Parameters.empty()) {
6658 S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
6659 return false;
6662 assert(Parameters.back() == ')' && "expected ')'");
6663 Parameters = Parameters.drop_back(); // ')'
6665 if (Parameters.empty()) {
6666 // Setters and subscripts must have at least one parameter.
6667 if (IsSubscript) {
6668 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6669 << AL << /* have at least one parameter */1;
6670 return false;
6673 if (IsSetter) {
6674 S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
6675 return false;
6678 return true;
6681 if (Parameters.back() != ':') {
6682 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6683 return false;
6686 StringRef CurrentParam;
6687 std::optional<unsigned> SelfLocation;
6688 unsigned NewValueCount = 0;
6689 std::optional<unsigned> NewValueLocation;
6690 do {
6691 std::tie(CurrentParam, Parameters) = Parameters.split(':');
6693 if (!isValidAsciiIdentifier(CurrentParam)) {
6694 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6695 << AL << /*parameter*/2;
6696 return false;
6699 if (IsMember && CurrentParam == "self") {
6700 // "self" indicates the "self" argument for a member.
6702 // More than one "self"?
6703 if (SelfLocation) {
6704 S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
6705 return false;
6708 // The "self" location is the current parameter.
6709 SelfLocation = SwiftParamCount;
6710 } else if (CurrentParam == "newValue") {
6711 // "newValue" indicates the "newValue" argument for a setter.
6713 // There should only be one 'newValue', but it's only significant for
6714 // subscript accessors, so don't error right away.
6715 ++NewValueCount;
6717 NewValueLocation = SwiftParamCount;
6720 ++SwiftParamCount;
6721 } while (!Parameters.empty());
6723 // Only instance subscripts are currently supported.
6724 if (IsSubscript && !SelfLocation) {
6725 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6726 << AL << /*have a 'self:' parameter*/2;
6727 return false;
6730 IsSingleParamInit =
6731 SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
6733 // Check the number of parameters for a getter/setter.
6734 if (IsGetter || IsSetter) {
6735 // Setters have one parameter for the new value.
6736 unsigned NumExpectedParams = IsGetter ? 0 : 1;
6737 unsigned ParamDiag =
6738 IsGetter ? diag::warn_attr_swift_name_getter_parameters
6739 : diag::warn_attr_swift_name_setter_parameters;
6741 // Instance methods have one parameter for "self".
6742 if (SelfLocation)
6743 ++NumExpectedParams;
6745 // Subscripts may have additional parameters beyond the expected params for
6746 // the index.
6747 if (IsSubscript) {
6748 if (SwiftParamCount < NumExpectedParams) {
6749 S.Diag(Loc, ParamDiag) << AL;
6750 return false;
6753 // A subscript setter must explicitly label its newValue parameter to
6754 // distinguish it from index parameters.
6755 if (IsSetter) {
6756 if (!NewValueLocation) {
6757 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
6758 << AL;
6759 return false;
6761 if (NewValueCount > 1) {
6762 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6763 << AL;
6764 return false;
6766 } else {
6767 // Subscript getters should have no 'newValue:' parameter.
6768 if (NewValueLocation) {
6769 S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6770 << AL;
6771 return false;
6774 } else {
6775 // Property accessors must have exactly the number of expected params.
6776 if (SwiftParamCount != NumExpectedParams) {
6777 S.Diag(Loc, ParamDiag) << AL;
6778 return false;
6783 return true;
6786 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6787 const ParsedAttr &AL, bool IsAsync) {
6788 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
6789 ArrayRef<ParmVarDecl*> Params;
6790 unsigned ParamCount;
6792 if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
6793 ParamCount = Method->getSelector().getNumArgs();
6794 Params = Method->parameters().slice(0, ParamCount);
6795 } else {
6796 const auto *F = cast<FunctionDecl>(D);
6798 ParamCount = F->getNumParams();
6799 Params = F->parameters();
6801 if (!F->hasWrittenPrototype()) {
6802 Diag(Loc, diag::warn_attribute_wrong_decl_type)
6803 << AL << AL.isRegularKeywordAttribute()
6804 << ExpectedFunctionWithProtoType;
6805 return false;
6809 // The async name drops the last callback parameter.
6810 if (IsAsync) {
6811 if (ParamCount == 0) {
6812 Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6813 << AL << isa<ObjCMethodDecl>(D);
6814 return false;
6816 ParamCount -= 1;
6819 unsigned SwiftParamCount;
6820 bool IsSingleParamInit;
6821 if (!validateSwiftFunctionName(*this, AL, Loc, Name,
6822 SwiftParamCount, IsSingleParamInit))
6823 return false;
6825 bool ParamCountValid;
6826 if (SwiftParamCount == ParamCount) {
6827 ParamCountValid = true;
6828 } else if (SwiftParamCount > ParamCount) {
6829 ParamCountValid = IsSingleParamInit && ParamCount == 0;
6830 } else {
6831 // We have fewer Swift parameters than Objective-C parameters, but that
6832 // might be because we've transformed some of them. Check for potential
6833 // "out" parameters and err on the side of not warning.
6834 unsigned MaybeOutParamCount =
6835 llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool {
6836 QualType ParamTy = Param->getType();
6837 if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6838 return !ParamTy->getPointeeType().isConstQualified();
6839 return false;
6842 ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6845 if (!ParamCountValid) {
6846 Diag(Loc, diag::warn_attr_swift_name_num_params)
6847 << (SwiftParamCount > ParamCount) << AL << ParamCount
6848 << SwiftParamCount;
6849 return false;
6851 } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
6852 isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
6853 isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
6854 isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
6855 !IsAsync) {
6856 StringRef ContextName, BaseName;
6858 std::tie(ContextName, BaseName) = Name.split('.');
6859 if (BaseName.empty()) {
6860 BaseName = ContextName;
6861 ContextName = StringRef();
6862 } else if (!isValidAsciiIdentifier(ContextName)) {
6863 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6864 << /*context*/1;
6865 return false;
6868 if (!isValidAsciiIdentifier(BaseName)) {
6869 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6870 << /*basename*/0;
6871 return false;
6873 } else {
6874 Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6875 return false;
6877 return true;
6880 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6881 StringRef Name;
6882 SourceLocation Loc;
6883 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6884 return;
6886 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6887 return;
6889 D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6892 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6893 StringRef Name;
6894 SourceLocation Loc;
6895 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6896 return;
6898 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6899 return;
6901 D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6904 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6905 // Make sure that there is an identifier as the annotation's single argument.
6906 if (!AL.checkExactlyNumArgs(S, 1))
6907 return;
6909 if (!AL.isArgIdent(0)) {
6910 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6911 << AL << AANT_ArgumentIdentifier;
6912 return;
6915 SwiftNewTypeAttr::NewtypeKind Kind;
6916 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6917 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
6918 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6919 return;
6922 if (!isa<TypedefNameDecl>(D)) {
6923 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
6924 << AL << AL.isRegularKeywordAttribute() << "typedefs";
6925 return;
6928 D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
6931 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6932 if (!AL.isArgIdent(0)) {
6933 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
6934 << AL << 1 << AANT_ArgumentIdentifier;
6935 return;
6938 SwiftAsyncAttr::Kind Kind;
6939 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6940 if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
6941 S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
6942 return;
6945 ParamIdx Idx;
6946 if (Kind == SwiftAsyncAttr::None) {
6947 // If this is 'none', then there shouldn't be any additional arguments.
6948 if (!AL.checkExactlyNumArgs(S, 1))
6949 return;
6950 } else {
6951 // Non-none swift_async requires a completion handler index argument.
6952 if (!AL.checkExactlyNumArgs(S, 2))
6953 return;
6955 Expr *HandlerIdx = AL.getArgAsExpr(1);
6956 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
6957 return;
6959 const ParmVarDecl *CompletionBlock =
6960 getFunctionOrMethodParam(D, Idx.getASTIndex());
6961 QualType CompletionBlockType = CompletionBlock->getType();
6962 if (!CompletionBlockType->isBlockPointerType()) {
6963 S.Diag(CompletionBlock->getLocation(),
6964 diag::err_swift_async_bad_block_type)
6965 << CompletionBlock->getType();
6966 return;
6968 QualType BlockTy =
6969 CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
6970 if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
6971 S.Diag(CompletionBlock->getLocation(),
6972 diag::err_swift_async_bad_block_type)
6973 << CompletionBlock->getType();
6974 return;
6978 auto *AsyncAttr =
6979 ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
6980 D->addAttr(AsyncAttr);
6982 if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
6983 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6986 //===----------------------------------------------------------------------===//
6987 // Microsoft specific attribute handlers.
6988 //===----------------------------------------------------------------------===//
6990 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
6991 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
6992 if (const auto *UA = D->getAttr<UuidAttr>()) {
6993 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
6994 return nullptr;
6995 if (!UA->getGuid().empty()) {
6996 Diag(UA->getLocation(), diag::err_mismatched_uuid);
6997 Diag(CI.getLoc(), diag::note_previous_uuid);
6998 D->dropAttr<UuidAttr>();
7002 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
7005 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7006 if (!S.LangOpts.CPlusPlus) {
7007 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7008 << AL << AttributeLangSupport::C;
7009 return;
7012 StringRef OrigStrRef;
7013 SourceLocation LiteralLoc;
7014 if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
7015 return;
7017 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
7018 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
7019 StringRef StrRef = OrigStrRef;
7020 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
7021 StrRef = StrRef.drop_front().drop_back();
7023 // Validate GUID length.
7024 if (StrRef.size() != 36) {
7025 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7026 return;
7029 for (unsigned i = 0; i < 36; ++i) {
7030 if (i == 8 || i == 13 || i == 18 || i == 23) {
7031 if (StrRef[i] != '-') {
7032 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7033 return;
7035 } else if (!isHexDigit(StrRef[i])) {
7036 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7037 return;
7041 // Convert to our parsed format and canonicalize.
7042 MSGuidDecl::Parts Parsed;
7043 StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
7044 StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
7045 StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
7046 for (unsigned i = 0; i != 8; ++i)
7047 StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
7048 .getAsInteger(16, Parsed.Part4And5[i]);
7049 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
7051 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
7052 // the only thing in the [] list, the [] too), and add an insertion of
7053 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
7054 // separating attributes nor of the [ and the ] are in the AST.
7055 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
7056 // on cfe-dev.
7057 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
7058 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
7060 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
7061 if (UA)
7062 D->addAttr(UA);
7065 static void handleHLSLNumThreadsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7066 using llvm::Triple;
7067 Triple Target = S.Context.getTargetInfo().getTriple();
7068 auto Env = S.Context.getTargetInfo().getTriple().getEnvironment();
7069 if (!llvm::is_contained({Triple::Compute, Triple::Mesh, Triple::Amplification,
7070 Triple::Library},
7071 Env)) {
7072 uint32_t Pipeline =
7073 static_cast<uint32_t>(hlsl::getStageFromEnvironment(Env));
7074 S.Diag(AL.getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
7075 << AL << Pipeline << "Compute, Amplification, Mesh or Library";
7076 return;
7079 llvm::VersionTuple SMVersion = Target.getOSVersion();
7080 uint32_t ZMax = 1024;
7081 uint32_t ThreadMax = 1024;
7082 if (SMVersion.getMajor() <= 4) {
7083 ZMax = 1;
7084 ThreadMax = 768;
7085 } else if (SMVersion.getMajor() == 5) {
7086 ZMax = 64;
7087 ThreadMax = 1024;
7090 uint32_t X;
7091 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), X))
7092 return;
7093 if (X > 1024) {
7094 S.Diag(AL.getArgAsExpr(0)->getExprLoc(),
7095 diag::err_hlsl_numthreads_argument_oor) << 0 << 1024;
7096 return;
7098 uint32_t Y;
7099 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(1), Y))
7100 return;
7101 if (Y > 1024) {
7102 S.Diag(AL.getArgAsExpr(1)->getExprLoc(),
7103 diag::err_hlsl_numthreads_argument_oor) << 1 << 1024;
7104 return;
7106 uint32_t Z;
7107 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(2), Z))
7108 return;
7109 if (Z > ZMax) {
7110 S.Diag(AL.getArgAsExpr(2)->getExprLoc(),
7111 diag::err_hlsl_numthreads_argument_oor) << 2 << ZMax;
7112 return;
7115 if (X * Y * Z > ThreadMax) {
7116 S.Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
7117 return;
7120 HLSLNumThreadsAttr *NewAttr = S.mergeHLSLNumThreadsAttr(D, AL, X, Y, Z);
7121 if (NewAttr)
7122 D->addAttr(NewAttr);
7125 HLSLNumThreadsAttr *Sema::mergeHLSLNumThreadsAttr(Decl *D,
7126 const AttributeCommonInfo &AL,
7127 int X, int Y, int Z) {
7128 if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) {
7129 if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) {
7130 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7131 Diag(AL.getLoc(), diag::note_conflicting_attribute);
7133 return nullptr;
7135 return ::new (Context) HLSLNumThreadsAttr(Context, AL, X, Y, Z);
7138 static void handleHLSLSVGroupIndexAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7139 using llvm::Triple;
7140 auto Env = S.Context.getTargetInfo().getTriple().getEnvironment();
7141 if (Env != Triple::Compute && Env != Triple::Library) {
7142 // FIXME: it is OK for a compute shader entry and pixel shader entry live in
7143 // same HLSL file. Issue https://github.com/llvm/llvm-project/issues/57880.
7144 ShaderStage Pipeline = hlsl::getStageFromEnvironment(Env);
7145 S.Diag(AL.getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
7146 << AL << (uint32_t)Pipeline << "Compute";
7147 return;
7150 D->addAttr(::new (S.Context) HLSLSV_GroupIndexAttr(S.Context, AL));
7153 static bool isLegalTypeForHLSLSV_DispatchThreadID(QualType T) {
7154 if (!T->hasUnsignedIntegerRepresentation())
7155 return false;
7156 if (const auto *VT = T->getAs<VectorType>())
7157 return VT->getNumElements() <= 3;
7158 return true;
7161 static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
7162 const ParsedAttr &AL) {
7163 using llvm::Triple;
7164 Triple Target = S.Context.getTargetInfo().getTriple();
7165 // FIXME: it is OK for a compute shader entry and pixel shader entry live in
7166 // same HLSL file.Issue https://github.com/llvm/llvm-project/issues/57880.
7167 if (Target.getEnvironment() != Triple::Compute &&
7168 Target.getEnvironment() != Triple::Library) {
7169 uint32_t Pipeline =
7170 (uint32_t)S.Context.getTargetInfo().getTriple().getEnvironment() -
7171 (uint32_t)llvm::Triple::Pixel;
7172 S.Diag(AL.getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
7173 << AL << Pipeline << "Compute";
7174 return;
7177 // FIXME: report warning and ignore semantic when cannot apply on the Decl.
7178 // See https://github.com/llvm/llvm-project/issues/57916.
7180 // FIXME: support semantic on field.
7181 // See https://github.com/llvm/llvm-project/issues/57889.
7182 if (isa<FieldDecl>(D)) {
7183 S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
7184 << AL << "parameter";
7185 return;
7188 auto *VD = cast<ValueDecl>(D);
7189 if (!isLegalTypeForHLSLSV_DispatchThreadID(VD->getType())) {
7190 S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
7191 << AL << "uint/uint2/uint3";
7192 return;
7195 D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
7198 static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7199 StringRef Str;
7200 SourceLocation ArgLoc;
7201 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7202 return;
7204 HLSLShaderAttr::ShaderType ShaderType;
7205 if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType) ||
7206 // Library is added to help convert HLSLShaderAttr::ShaderType to
7207 // llvm::Triple::EnviromentType. It is not a legal
7208 // HLSLShaderAttr::ShaderType.
7209 ShaderType == HLSLShaderAttr::Library) {
7210 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7211 << AL << Str << ArgLoc;
7212 return;
7215 // FIXME: check function match the shader stage.
7217 HLSLShaderAttr *NewAttr = S.mergeHLSLShaderAttr(D, AL, ShaderType);
7218 if (NewAttr)
7219 D->addAttr(NewAttr);
7222 HLSLShaderAttr *
7223 Sema::mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
7224 HLSLShaderAttr::ShaderType ShaderType) {
7225 if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) {
7226 if (NT->getType() != ShaderType) {
7227 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7228 Diag(AL.getLoc(), diag::note_conflicting_attribute);
7230 return nullptr;
7232 return HLSLShaderAttr::Create(Context, ShaderType, AL);
7235 static void handleHLSLResourceBindingAttr(Sema &S, Decl *D,
7236 const ParsedAttr &AL) {
7237 StringRef Space = "space0";
7238 StringRef Slot = "";
7240 if (!AL.isArgIdent(0)) {
7241 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7242 << AL << AANT_ArgumentIdentifier;
7243 return;
7246 IdentifierLoc *Loc = AL.getArgAsIdent(0);
7247 StringRef Str = Loc->Ident->getName();
7248 SourceLocation ArgLoc = Loc->Loc;
7250 SourceLocation SpaceArgLoc;
7251 if (AL.getNumArgs() == 2) {
7252 Slot = Str;
7253 if (!AL.isArgIdent(1)) {
7254 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7255 << AL << AANT_ArgumentIdentifier;
7256 return;
7259 IdentifierLoc *Loc = AL.getArgAsIdent(1);
7260 Space = Loc->Ident->getName();
7261 SpaceArgLoc = Loc->Loc;
7262 } else {
7263 Slot = Str;
7266 // Validate.
7267 if (!Slot.empty()) {
7268 switch (Slot[0]) {
7269 case 'u':
7270 case 'b':
7271 case 's':
7272 case 't':
7273 break;
7274 default:
7275 S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_type)
7276 << Slot.substr(0, 1);
7277 return;
7280 StringRef SlotNum = Slot.substr(1);
7281 unsigned Num = 0;
7282 if (SlotNum.getAsInteger(10, Num)) {
7283 S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_number);
7284 return;
7288 if (!Space.startswith("space")) {
7289 S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7290 return;
7292 StringRef SpaceNum = Space.substr(5);
7293 unsigned Num = 0;
7294 if (SpaceNum.getAsInteger(10, Num)) {
7295 S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7296 return;
7299 // FIXME: check reg type match decl. Issue
7300 // https://github.com/llvm/llvm-project/issues/57886.
7301 HLSLResourceBindingAttr *NewAttr =
7302 HLSLResourceBindingAttr::Create(S.getASTContext(), Slot, Space, AL);
7303 if (NewAttr)
7304 D->addAttr(NewAttr);
7307 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7308 if (!S.LangOpts.CPlusPlus) {
7309 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7310 << AL << AttributeLangSupport::C;
7311 return;
7313 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
7314 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
7315 if (IA) {
7316 D->addAttr(IA);
7317 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
7321 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7322 const auto *VD = cast<VarDecl>(D);
7323 if (!S.Context.getTargetInfo().isTLSSupported()) {
7324 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
7325 return;
7327 if (VD->getTSCSpec() != TSCS_unspecified) {
7328 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
7329 return;
7331 if (VD->hasLocalStorage()) {
7332 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
7333 return;
7335 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
7338 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7339 SmallVector<StringRef, 4> Tags;
7340 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7341 StringRef Tag;
7342 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
7343 return;
7344 Tags.push_back(Tag);
7347 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
7348 if (!NS->isInline()) {
7349 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
7350 return;
7352 if (NS->isAnonymousNamespace()) {
7353 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
7354 return;
7356 if (AL.getNumArgs() == 0)
7357 Tags.push_back(NS->getName());
7358 } else if (!AL.checkAtLeastNumArgs(S, 1))
7359 return;
7361 // Store tags sorted and without duplicates.
7362 llvm::sort(Tags);
7363 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
7365 D->addAttr(::new (S.Context)
7366 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
7369 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7370 // Check the attribute arguments.
7371 if (AL.getNumArgs() > 1) {
7372 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7373 return;
7376 StringRef Str;
7377 SourceLocation ArgLoc;
7379 if (AL.getNumArgs() == 0)
7380 Str = "";
7381 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7382 return;
7384 ARMInterruptAttr::InterruptType Kind;
7385 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7386 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7387 << ArgLoc;
7388 return;
7391 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
7394 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7395 // MSP430 'interrupt' attribute is applied to
7396 // a function with no parameters and void return type.
7397 if (!isFunctionOrMethod(D)) {
7398 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7399 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7400 return;
7403 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7404 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7405 << /*MSP430*/ 1 << 0;
7406 return;
7409 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7410 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7411 << /*MSP430*/ 1 << 1;
7412 return;
7415 // The attribute takes one integer argument.
7416 if (!AL.checkExactlyNumArgs(S, 1))
7417 return;
7419 if (!AL.isArgExpr(0)) {
7420 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7421 << AL << AANT_ArgumentIntegerConstant;
7422 return;
7425 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7426 std::optional<llvm::APSInt> NumParams = llvm::APSInt(32);
7427 if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
7428 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7429 << AL << AANT_ArgumentIntegerConstant
7430 << NumParamsExpr->getSourceRange();
7431 return;
7433 // The argument should be in range 0..63.
7434 unsigned Num = NumParams->getLimitedValue(255);
7435 if (Num > 63) {
7436 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7437 << AL << (int)NumParams->getSExtValue()
7438 << NumParamsExpr->getSourceRange();
7439 return;
7442 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
7443 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7446 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7447 // Only one optional argument permitted.
7448 if (AL.getNumArgs() > 1) {
7449 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7450 return;
7453 StringRef Str;
7454 SourceLocation ArgLoc;
7456 if (AL.getNumArgs() == 0)
7457 Str = "";
7458 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7459 return;
7461 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
7462 // a) Must be a function.
7463 // b) Must have no parameters.
7464 // c) Must have the 'void' return type.
7465 // d) Cannot have the 'mips16' attribute, as that instruction set
7466 // lacks the 'eret' instruction.
7467 // e) The attribute itself must either have no argument or one of the
7468 // valid interrupt types, see [MipsInterruptDocs].
7470 if (!isFunctionOrMethod(D)) {
7471 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7472 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7473 return;
7476 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7477 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7478 << /*MIPS*/ 0 << 0;
7479 return;
7482 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7483 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7484 << /*MIPS*/ 0 << 1;
7485 return;
7488 // We still have to do this manually because the Interrupt attributes are
7489 // a bit special due to sharing their spellings across targets.
7490 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
7491 return;
7493 MipsInterruptAttr::InterruptType Kind;
7494 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7495 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7496 << AL << "'" + std::string(Str) + "'";
7497 return;
7500 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
7503 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7504 if (!AL.checkExactlyNumArgs(S, 1))
7505 return;
7507 if (!AL.isArgExpr(0)) {
7508 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7509 << AL << AANT_ArgumentIntegerConstant;
7510 return;
7513 // FIXME: Check for decl - it should be void ()(void).
7515 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7516 auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
7517 if (!MaybeNumParams) {
7518 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7519 << AL << AANT_ArgumentIntegerConstant
7520 << NumParamsExpr->getSourceRange();
7521 return;
7524 unsigned Num = MaybeNumParams->getLimitedValue(255);
7525 if ((Num & 1) || Num > 30) {
7526 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7527 << AL << (int)MaybeNumParams->getSExtValue()
7528 << NumParamsExpr->getSourceRange();
7529 return;
7532 D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
7533 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7536 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7537 // Semantic checks for a function with the 'interrupt' attribute.
7538 // a) Must be a function.
7539 // b) Must have the 'void' return type.
7540 // c) Must take 1 or 2 arguments.
7541 // d) The 1st argument must be a pointer.
7542 // e) The 2nd argument (if any) must be an unsigned integer.
7543 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
7544 CXXMethodDecl::isStaticOverloadedOperator(
7545 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
7546 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
7547 << AL << AL.isRegularKeywordAttribute()
7548 << ExpectedFunctionWithProtoType;
7549 return;
7551 // Interrupt handler must have void return type.
7552 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7553 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
7554 diag::err_anyx86_interrupt_attribute)
7555 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7557 : 1)
7558 << 0;
7559 return;
7561 // Interrupt handler must have 1 or 2 parameters.
7562 unsigned NumParams = getFunctionOrMethodNumParams(D);
7563 if (NumParams < 1 || NumParams > 2) {
7564 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
7565 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7567 : 1)
7568 << 1;
7569 return;
7571 // The first argument must be a pointer.
7572 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
7573 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
7574 diag::err_anyx86_interrupt_attribute)
7575 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7577 : 1)
7578 << 2;
7579 return;
7581 // The second argument, if present, must be an unsigned integer.
7582 unsigned TypeSize =
7583 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
7584 ? 64
7585 : 32;
7586 if (NumParams == 2 &&
7587 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
7588 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
7589 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
7590 diag::err_anyx86_interrupt_attribute)
7591 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7593 : 1)
7594 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
7595 return;
7597 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
7598 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7601 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7602 if (!isFunctionOrMethod(D)) {
7603 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7604 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7605 return;
7608 if (!AL.checkExactlyNumArgs(S, 0))
7609 return;
7611 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
7614 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7615 if (!isFunctionOrMethod(D)) {
7616 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7617 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7618 return;
7621 if (!AL.checkExactlyNumArgs(S, 0))
7622 return;
7624 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
7627 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
7628 // Add preserve_access_index attribute to all fields and inner records.
7629 for (auto *D : RD->decls()) {
7630 if (D->hasAttr<BPFPreserveAccessIndexAttr>())
7631 continue;
7633 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
7634 if (auto *Rec = dyn_cast<RecordDecl>(D))
7635 handleBPFPreserveAIRecord(S, Rec);
7639 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
7640 const ParsedAttr &AL) {
7641 auto *Rec = cast<RecordDecl>(D);
7642 handleBPFPreserveAIRecord(S, Rec);
7643 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
7646 static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
7647 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
7648 if (I->getBTFDeclTag() == Tag)
7649 return true;
7651 return false;
7654 static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7655 StringRef Str;
7656 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
7657 return;
7658 if (hasBTFDeclTagAttr(D, Str))
7659 return;
7661 D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
7664 BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
7665 if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag()))
7666 return nullptr;
7667 return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
7670 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D,
7671 const ParsedAttr &AL) {
7672 if (!isFunctionOrMethod(D)) {
7673 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7674 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7675 return;
7678 auto *FD = cast<FunctionDecl>(D);
7679 if (FD->isThisDeclarationADefinition()) {
7680 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
7681 return;
7684 StringRef Str;
7685 SourceLocation ArgLoc;
7686 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7687 return;
7689 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
7690 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7693 WebAssemblyImportModuleAttr *
7694 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
7695 auto *FD = cast<FunctionDecl>(D);
7697 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
7698 if (ExistingAttr->getImportModule() == AL.getImportModule())
7699 return nullptr;
7700 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
7701 << ExistingAttr->getImportModule() << AL.getImportModule();
7702 Diag(AL.getLoc(), diag::note_previous_attribute);
7703 return nullptr;
7705 if (FD->hasBody()) {
7706 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7707 return nullptr;
7709 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
7710 AL.getImportModule());
7713 WebAssemblyImportNameAttr *
7714 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
7715 auto *FD = cast<FunctionDecl>(D);
7717 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
7718 if (ExistingAttr->getImportName() == AL.getImportName())
7719 return nullptr;
7720 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
7721 << ExistingAttr->getImportName() << AL.getImportName();
7722 Diag(AL.getLoc(), diag::note_previous_attribute);
7723 return nullptr;
7725 if (FD->hasBody()) {
7726 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7727 return nullptr;
7729 return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
7730 AL.getImportName());
7733 static void
7734 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7735 auto *FD = cast<FunctionDecl>(D);
7737 StringRef Str;
7738 SourceLocation ArgLoc;
7739 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7740 return;
7741 if (FD->hasBody()) {
7742 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7743 return;
7746 FD->addAttr(::new (S.Context)
7747 WebAssemblyImportModuleAttr(S.Context, AL, Str));
7750 static void
7751 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7752 auto *FD = cast<FunctionDecl>(D);
7754 StringRef Str;
7755 SourceLocation ArgLoc;
7756 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7757 return;
7758 if (FD->hasBody()) {
7759 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7760 return;
7763 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
7766 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
7767 const ParsedAttr &AL) {
7768 // Warn about repeated attributes.
7769 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
7770 S.Diag(AL.getRange().getBegin(),
7771 diag::warn_riscv_repeated_interrupt_attribute);
7772 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
7773 return;
7776 // Check the attribute argument. Argument is optional.
7777 if (!AL.checkAtMostNumArgs(S, 1))
7778 return;
7780 StringRef Str;
7781 SourceLocation ArgLoc;
7783 // 'machine'is the default interrupt mode.
7784 if (AL.getNumArgs() == 0)
7785 Str = "machine";
7786 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7787 return;
7789 // Semantic checks for a function with the 'interrupt' attribute:
7790 // - Must be a function.
7791 // - Must have no parameters.
7792 // - Must have the 'void' return type.
7793 // - The attribute itself must either have no argument or one of the
7794 // valid interrupt types, see [RISCVInterruptDocs].
7796 if (D->getFunctionType() == nullptr) {
7797 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7798 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7799 return;
7802 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7803 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7804 << /*RISC-V*/ 2 << 0;
7805 return;
7808 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7809 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7810 << /*RISC-V*/ 2 << 1;
7811 return;
7814 RISCVInterruptAttr::InterruptType Kind;
7815 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7816 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7817 << ArgLoc;
7818 return;
7821 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
7824 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7825 // Dispatch the interrupt attribute based on the current target.
7826 switch (S.Context.getTargetInfo().getTriple().getArch()) {
7827 case llvm::Triple::msp430:
7828 handleMSP430InterruptAttr(S, D, AL);
7829 break;
7830 case llvm::Triple::mipsel:
7831 case llvm::Triple::mips:
7832 handleMipsInterruptAttr(S, D, AL);
7833 break;
7834 case llvm::Triple::m68k:
7835 handleM68kInterruptAttr(S, D, AL);
7836 break;
7837 case llvm::Triple::x86:
7838 case llvm::Triple::x86_64:
7839 handleAnyX86InterruptAttr(S, D, AL);
7840 break;
7841 case llvm::Triple::avr:
7842 handleAVRInterruptAttr(S, D, AL);
7843 break;
7844 case llvm::Triple::riscv32:
7845 case llvm::Triple::riscv64:
7846 handleRISCVInterruptAttr(S, D, AL);
7847 break;
7848 default:
7849 handleARMInterruptAttr(S, D, AL);
7850 break;
7854 static bool
7855 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
7856 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
7857 // Accept template arguments for now as they depend on something else.
7858 // We'll get to check them when they eventually get instantiated.
7859 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
7860 return false;
7862 uint32_t Min = 0;
7863 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7864 return true;
7866 uint32_t Max = 0;
7867 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7868 return true;
7870 if (Min == 0 && Max != 0) {
7871 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7872 << &Attr << 0;
7873 return true;
7875 if (Min > Max) {
7876 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7877 << &Attr << 1;
7878 return true;
7881 return false;
7884 AMDGPUFlatWorkGroupSizeAttr *
7885 Sema::CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI,
7886 Expr *MinExpr, Expr *MaxExpr) {
7887 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7889 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
7890 return nullptr;
7891 return ::new (Context)
7892 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr);
7895 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
7896 const AttributeCommonInfo &CI,
7897 Expr *MinExpr, Expr *MaxExpr) {
7898 if (auto *Attr = CreateAMDGPUFlatWorkGroupSizeAttr(CI, MinExpr, MaxExpr))
7899 D->addAttr(Attr);
7902 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
7903 const ParsedAttr &AL) {
7904 Expr *MinExpr = AL.getArgAsExpr(0);
7905 Expr *MaxExpr = AL.getArgAsExpr(1);
7907 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
7910 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
7911 Expr *MaxExpr,
7912 const AMDGPUWavesPerEUAttr &Attr) {
7913 if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
7914 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
7915 return true;
7917 // Accept template arguments for now as they depend on something else.
7918 // We'll get to check them when they eventually get instantiated.
7919 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
7920 return false;
7922 uint32_t Min = 0;
7923 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7924 return true;
7926 uint32_t Max = 0;
7927 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7928 return true;
7930 if (Min == 0 && Max != 0) {
7931 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7932 << &Attr << 0;
7933 return true;
7935 if (Max != 0 && Min > Max) {
7936 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7937 << &Attr << 1;
7938 return true;
7941 return false;
7944 AMDGPUWavesPerEUAttr *
7945 Sema::CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *MinExpr,
7946 Expr *MaxExpr) {
7947 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7949 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
7950 return nullptr;
7952 return ::new (Context) AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr);
7955 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
7956 Expr *MinExpr, Expr *MaxExpr) {
7957 if (auto *Attr = CreateAMDGPUWavesPerEUAttr(CI, MinExpr, MaxExpr))
7958 D->addAttr(Attr);
7961 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7962 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
7963 return;
7965 Expr *MinExpr = AL.getArgAsExpr(0);
7966 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
7968 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
7971 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7972 uint32_t NumSGPR = 0;
7973 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
7974 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
7975 return;
7977 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
7980 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7981 uint32_t NumVGPR = 0;
7982 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
7983 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
7984 return;
7986 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
7989 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
7990 const ParsedAttr &AL) {
7991 // If we try to apply it to a function pointer, don't warn, but don't
7992 // do anything, either. It doesn't matter anyway, because there's nothing
7993 // special about calling a force_align_arg_pointer function.
7994 const auto *VD = dyn_cast<ValueDecl>(D);
7995 if (VD && VD->getType()->isFunctionPointerType())
7996 return;
7997 // Also don't warn on function pointer typedefs.
7998 const auto *TD = dyn_cast<TypedefNameDecl>(D);
7999 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
8000 TD->getUnderlyingType()->isFunctionType()))
8001 return;
8002 // Attribute can only be applied to function types.
8003 if (!isa<FunctionDecl>(D)) {
8004 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
8005 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8006 return;
8009 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
8012 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
8013 uint32_t Version;
8014 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
8015 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
8016 return;
8018 // TODO: Investigate what happens with the next major version of MSVC.
8019 if (Version != LangOptions::MSVC2015 / 100) {
8020 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
8021 << AL << Version << VersionExpr->getSourceRange();
8022 return;
8025 // The attribute expects a "major" version number like 19, but new versions of
8026 // MSVC have moved to updating the "minor", or less significant numbers, so we
8027 // have to multiply by 100 now.
8028 Version *= 100;
8030 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
8033 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
8034 const AttributeCommonInfo &CI) {
8035 if (D->hasAttr<DLLExportAttr>()) {
8036 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
8037 return nullptr;
8040 if (D->hasAttr<DLLImportAttr>())
8041 return nullptr;
8043 return ::new (Context) DLLImportAttr(Context, CI);
8046 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
8047 const AttributeCommonInfo &CI) {
8048 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
8049 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
8050 D->dropAttr<DLLImportAttr>();
8053 if (D->hasAttr<DLLExportAttr>())
8054 return nullptr;
8056 return ::new (Context) DLLExportAttr(Context, CI);
8059 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8060 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
8061 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8062 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
8063 return;
8066 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
8067 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
8068 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8069 // MinGW doesn't allow dllimport on inline functions.
8070 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
8071 << A;
8072 return;
8076 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
8077 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
8078 MD->getParent()->isLambda()) {
8079 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
8080 return;
8084 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
8085 ? (Attr *)S.mergeDLLExportAttr(D, A)
8086 : (Attr *)S.mergeDLLImportAttr(D, A);
8087 if (NewAttr)
8088 D->addAttr(NewAttr);
8091 MSInheritanceAttr *
8092 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
8093 bool BestCase,
8094 MSInheritanceModel Model) {
8095 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
8096 if (IA->getInheritanceModel() == Model)
8097 return nullptr;
8098 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
8099 << 1 /*previous declaration*/;
8100 Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
8101 D->dropAttr<MSInheritanceAttr>();
8104 auto *RD = cast<CXXRecordDecl>(D);
8105 if (RD->hasDefinition()) {
8106 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
8107 Model)) {
8108 return nullptr;
8110 } else {
8111 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
8112 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8113 << 1 /*partial specialization*/;
8114 return nullptr;
8116 if (RD->getDescribedClassTemplate()) {
8117 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8118 << 0 /*primary template*/;
8119 return nullptr;
8123 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
8126 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8127 // The capability attributes take a single string parameter for the name of
8128 // the capability they represent. The lockable attribute does not take any
8129 // parameters. However, semantically, both attributes represent the same
8130 // concept, and so they use the same semantic attribute. Eventually, the
8131 // lockable attribute will be removed.
8133 // For backward compatibility, any capability which has no specified string
8134 // literal will be considered a "mutex."
8135 StringRef N("mutex");
8136 SourceLocation LiteralLoc;
8137 if (AL.getKind() == ParsedAttr::AT_Capability &&
8138 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
8139 return;
8141 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
8144 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8145 SmallVector<Expr*, 1> Args;
8146 if (!checkLockFunAttrCommon(S, D, AL, Args))
8147 return;
8149 D->addAttr(::new (S.Context)
8150 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
8153 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
8154 const ParsedAttr &AL) {
8155 SmallVector<Expr*, 1> Args;
8156 if (!checkLockFunAttrCommon(S, D, AL, Args))
8157 return;
8159 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
8160 Args.size()));
8163 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
8164 const ParsedAttr &AL) {
8165 SmallVector<Expr*, 2> Args;
8166 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
8167 return;
8169 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
8170 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
8173 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
8174 const ParsedAttr &AL) {
8175 // Check that all arguments are lockable objects.
8176 SmallVector<Expr *, 1> Args;
8177 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
8179 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
8180 Args.size()));
8183 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
8184 const ParsedAttr &AL) {
8185 if (!AL.checkAtLeastNumArgs(S, 1))
8186 return;
8188 // check that all arguments are lockable objects
8189 SmallVector<Expr*, 1> Args;
8190 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
8191 if (Args.empty())
8192 return;
8194 RequiresCapabilityAttr *RCA = ::new (S.Context)
8195 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
8197 D->addAttr(RCA);
8200 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8201 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
8202 if (NSD->isAnonymousNamespace()) {
8203 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
8204 // Do not want to attach the attribute to the namespace because that will
8205 // cause confusing diagnostic reports for uses of declarations within the
8206 // namespace.
8207 return;
8209 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
8210 UnresolvedUsingValueDecl>(D)) {
8211 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
8212 << AL;
8213 return;
8216 // Handle the cases where the attribute has a text message.
8217 StringRef Str, Replacement;
8218 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
8219 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
8220 return;
8222 // Support a single optional message only for Declspec and [[]] spellings.
8223 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
8224 AL.checkAtMostNumArgs(S, 1);
8225 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
8226 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
8227 return;
8229 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
8230 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
8232 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
8235 static bool isGlobalVar(const Decl *D) {
8236 if (const auto *S = dyn_cast<VarDecl>(D))
8237 return S->hasGlobalStorage();
8238 return false;
8241 static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer) {
8242 return Sanitizer == "address" || Sanitizer == "hwaddress" ||
8243 Sanitizer == "memtag";
8246 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8247 if (!AL.checkAtLeastNumArgs(S, 1))
8248 return;
8250 std::vector<StringRef> Sanitizers;
8252 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
8253 StringRef SanitizerName;
8254 SourceLocation LiteralLoc;
8256 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
8257 return;
8259 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
8260 SanitizerMask() &&
8261 SanitizerName != "coverage")
8262 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
8263 else if (isGlobalVar(D) && !isSanitizerAttributeAllowedOnGlobals(SanitizerName))
8264 S.Diag(D->getLocation(), diag::warn_attribute_type_not_supported_global)
8265 << AL << SanitizerName;
8266 Sanitizers.push_back(SanitizerName);
8269 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
8270 Sanitizers.size()));
8273 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
8274 const ParsedAttr &AL) {
8275 StringRef AttrName = AL.getAttrName()->getName();
8276 normalizeName(AttrName);
8277 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
8278 .Case("no_address_safety_analysis", "address")
8279 .Case("no_sanitize_address", "address")
8280 .Case("no_sanitize_thread", "thread")
8281 .Case("no_sanitize_memory", "memory");
8282 if (isGlobalVar(D) && SanitizerName != "address")
8283 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8284 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8286 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
8287 // NoSanitizeAttr object; but we need to calculate the correct spelling list
8288 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
8289 // has the same spellings as the index for NoSanitizeAttr. We don't have a
8290 // general way to "translate" between the two, so this hack attempts to work
8291 // around the issue with hard-coded indices. This is critical for calling
8292 // getSpelling() or prettyPrint() on the resulting semantic attribute object
8293 // without failing assertions.
8294 unsigned TranslatedSpellingIndex = 0;
8295 if (AL.isStandardAttributeSyntax())
8296 TranslatedSpellingIndex = 1;
8298 AttributeCommonInfo Info = AL;
8299 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
8300 D->addAttr(::new (S.Context)
8301 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
8304 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8305 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
8306 D->addAttr(Internal);
8309 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8310 if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
8311 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
8312 << AL << "2.0" << 1;
8313 else
8314 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
8315 << AL << S.LangOpts.getOpenCLVersionString();
8318 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8319 if (D->isInvalidDecl())
8320 return;
8322 // Check if there is only one access qualifier.
8323 if (D->hasAttr<OpenCLAccessAttr>()) {
8324 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
8325 AL.getSemanticSpelling()) {
8326 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
8327 << AL.getAttrName()->getName() << AL.getRange();
8328 } else {
8329 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
8330 << D->getSourceRange();
8331 D->setInvalidDecl(true);
8332 return;
8336 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
8337 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
8338 // cannot read from and write to the same pipe object. Using the read_write
8339 // (or __read_write) qualifier with the pipe qualifier is a compilation error.
8340 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
8341 // __opencl_c_read_write_images feature, image objects specified as arguments
8342 // to a kernel can additionally be declared to be read-write.
8343 // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
8344 // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
8345 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
8346 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
8347 if (AL.getAttrName()->getName().contains("read_write")) {
8348 bool ReadWriteImagesUnsupported =
8349 (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
8350 (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
8351 !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
8352 S.getLangOpts()));
8353 if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
8354 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
8355 << AL << PDecl->getType() << DeclTy->isImageType();
8356 D->setInvalidDecl(true);
8357 return;
8362 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
8365 static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8366 // Check that the argument is a string literal.
8367 StringRef KindStr;
8368 SourceLocation LiteralLoc;
8369 if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
8370 return;
8372 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind;
8373 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) {
8374 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8375 << AL << KindStr;
8376 return;
8379 D->dropAttr<ZeroCallUsedRegsAttr>();
8380 D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL));
8383 static void handleFunctionReturnThunksAttr(Sema &S, Decl *D,
8384 const ParsedAttr &AL) {
8385 StringRef KindStr;
8386 SourceLocation LiteralLoc;
8387 if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
8388 return;
8390 FunctionReturnThunksAttr::Kind Kind;
8391 if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr, Kind)) {
8392 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8393 << AL << KindStr;
8394 return;
8396 // FIXME: it would be good to better handle attribute merging rather than
8397 // silently replacing the existing attribute, so long as it does not break
8398 // the expected codegen tests.
8399 D->dropAttr<FunctionReturnThunksAttr>();
8400 D->addAttr(FunctionReturnThunksAttr::Create(S.Context, Kind, AL));
8403 static void handleAvailableOnlyInDefaultEvalMethod(Sema &S, Decl *D,
8404 const ParsedAttr &AL) {
8405 assert(isa<TypedefNameDecl>(D) && "This attribute only applies to a typedef");
8406 handleSimpleAttribute<AvailableOnlyInDefaultEvalMethodAttr>(S, D, AL);
8409 static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8410 auto *VDecl = dyn_cast<VarDecl>(D);
8411 if (VDecl && !VDecl->isFunctionPointerType()) {
8412 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_non_function_pointer)
8413 << AL << VDecl;
8414 return;
8416 D->addAttr(NoMergeAttr::Create(S.Context, AL));
8419 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8420 // The 'sycl_kernel' attribute applies only to function templates.
8421 const auto *FD = cast<FunctionDecl>(D);
8422 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
8423 assert(FT && "Function template is expected");
8425 // Function template must have at least two template parameters.
8426 const TemplateParameterList *TL = FT->getTemplateParameters();
8427 if (TL->size() < 2) {
8428 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
8429 return;
8432 // Template parameters must be typenames.
8433 for (unsigned I = 0; I < 2; ++I) {
8434 const NamedDecl *TParam = TL->getParam(I);
8435 if (isa<NonTypeTemplateParmDecl>(TParam)) {
8436 S.Diag(FT->getLocation(),
8437 diag::warn_sycl_kernel_invalid_template_param_type);
8438 return;
8442 // Function must have at least one argument.
8443 if (getFunctionOrMethodNumParams(D) != 1) {
8444 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
8445 return;
8448 // Function must return void.
8449 QualType RetTy = getFunctionOrMethodResultType(D);
8450 if (!RetTy->isVoidType()) {
8451 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
8452 return;
8455 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
8458 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8459 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
8460 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
8461 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
8462 return;
8465 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
8466 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
8467 else
8468 handleSimpleAttribute<NoDestroyAttr>(S, D, A);
8471 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8472 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
8473 "uninitialized is only valid on automatic duration variables");
8474 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
8477 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
8478 bool DiagnoseFailure) {
8479 QualType Ty = VD->getType();
8480 if (!Ty->isObjCRetainableType()) {
8481 if (DiagnoseFailure) {
8482 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8483 << 0;
8485 return false;
8488 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
8490 // Sema::inferObjCARCLifetime must run after processing decl attributes
8491 // (because __block lowers to an attribute), so if the lifetime hasn't been
8492 // explicitly specified, infer it locally now.
8493 if (LifetimeQual == Qualifiers::OCL_None)
8494 LifetimeQual = Ty->getObjCARCImplicitLifetime();
8496 // The attributes only really makes sense for __strong variables; ignore any
8497 // attempts to annotate a parameter with any other lifetime qualifier.
8498 if (LifetimeQual != Qualifiers::OCL_Strong) {
8499 if (DiagnoseFailure) {
8500 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8501 << 1;
8503 return false;
8506 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
8507 // to ensure that the variable is 'const' so that we can error on
8508 // modification, which can otherwise over-release.
8509 VD->setType(Ty.withConst());
8510 VD->setARCPseudoStrong(true);
8511 return true;
8514 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
8515 const ParsedAttr &AL) {
8516 if (auto *VD = dyn_cast<VarDecl>(D)) {
8517 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
8518 if (!VD->hasLocalStorage()) {
8519 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8520 << 0;
8521 return;
8524 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
8525 return;
8527 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8528 return;
8531 // If D is a function-like declaration (method, block, or function), then we
8532 // make every parameter psuedo-strong.
8533 unsigned NumParams =
8534 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
8535 for (unsigned I = 0; I != NumParams; ++I) {
8536 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
8537 QualType Ty = PVD->getType();
8539 // If a user wrote a parameter with __strong explicitly, then assume they
8540 // want "real" strong semantics for that parameter. This works because if
8541 // the parameter was written with __strong, then the strong qualifier will
8542 // be non-local.
8543 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
8544 Qualifiers::OCL_Strong)
8545 continue;
8547 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
8549 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8552 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8553 // Check that the return type is a `typedef int kern_return_t` or a typedef
8554 // around it, because otherwise MIG convention checks make no sense.
8555 // BlockDecl doesn't store a return type, so it's annoying to check,
8556 // so let's skip it for now.
8557 if (!isa<BlockDecl>(D)) {
8558 QualType T = getFunctionOrMethodResultType(D);
8559 bool IsKernReturnT = false;
8560 while (const auto *TT = T->getAs<TypedefType>()) {
8561 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
8562 T = TT->desugar();
8564 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
8565 S.Diag(D->getBeginLoc(),
8566 diag::warn_mig_server_routine_does_not_return_kern_return_t);
8567 return;
8571 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
8574 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8575 // Warn if the return type is not a pointer or reference type.
8576 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8577 QualType RetTy = FD->getReturnType();
8578 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
8579 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
8580 << AL.getRange() << RetTy;
8581 return;
8585 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
8588 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8589 if (AL.isUsedAsTypeAttr())
8590 return;
8591 // Warn if the parameter is definitely not an output parameter.
8592 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8593 if (PVD->getType()->isIntegerType()) {
8594 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
8595 << AL.getRange();
8596 return;
8599 StringRef Argument;
8600 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8601 return;
8602 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
8605 template<typename Attr>
8606 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8607 StringRef Argument;
8608 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8609 return;
8610 D->addAttr(Attr::Create(S.Context, Argument, AL));
8613 template<typename Attr>
8614 static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
8615 D->addAttr(Attr::Create(S.Context, AL));
8618 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8619 // The guard attribute takes a single identifier argument.
8621 if (!AL.isArgIdent(0)) {
8622 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
8623 << AL << AANT_ArgumentIdentifier;
8624 return;
8627 CFGuardAttr::GuardArg Arg;
8628 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
8629 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
8630 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
8631 return;
8634 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
8638 template <typename AttrTy>
8639 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
8640 auto Attrs = D->specific_attrs<AttrTy>();
8641 auto I = llvm::find_if(Attrs,
8642 [Name](const AttrTy *A) {
8643 return A->getTCBName() == Name;
8645 return I == Attrs.end() ? nullptr : *I;
8648 template <typename AttrTy, typename ConflictingAttrTy>
8649 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8650 StringRef Argument;
8651 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8652 return;
8654 // A function cannot be have both regular and leaf membership in the same TCB.
8655 if (const ConflictingAttrTy *ConflictingAttr =
8656 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
8657 // We could attach a note to the other attribute but in this case
8658 // there's no need given how the two are very close to each other.
8659 S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
8660 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
8661 << Argument;
8663 // Error recovery: drop the non-leaf attribute so that to suppress
8664 // all future warnings caused by erroneous attributes. The leaf attribute
8665 // needs to be kept because it can only suppresses warnings, not cause them.
8666 D->dropAttr<EnforceTCBAttr>();
8667 return;
8670 D->addAttr(AttrTy::Create(S.Context, Argument, AL));
8673 template <typename AttrTy, typename ConflictingAttrTy>
8674 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
8675 // Check if the new redeclaration has different leaf-ness in the same TCB.
8676 StringRef TCBName = AL.getTCBName();
8677 if (const ConflictingAttrTy *ConflictingAttr =
8678 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
8679 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
8680 << ConflictingAttr->getAttrName()->getName()
8681 << AL.getAttrName()->getName() << TCBName;
8683 // Add a note so that the user could easily find the conflicting attribute.
8684 S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
8686 // More error recovery.
8687 D->dropAttr<EnforceTCBAttr>();
8688 return nullptr;
8691 ASTContext &Context = S.getASTContext();
8692 return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
8695 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
8696 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
8697 *this, D, AL);
8700 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
8701 Decl *D, const EnforceTCBLeafAttr &AL) {
8702 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
8703 *this, D, AL);
8706 //===----------------------------------------------------------------------===//
8707 // Top Level Sema Entry Points
8708 //===----------------------------------------------------------------------===//
8710 // Returns true if the attribute must delay setting its arguments until after
8711 // template instantiation, and false otherwise.
8712 static bool MustDelayAttributeArguments(const ParsedAttr &AL) {
8713 // Only attributes that accept expression parameter packs can delay arguments.
8714 if (!AL.acceptsExprPack())
8715 return false;
8717 bool AttrHasVariadicArg = AL.hasVariadicArg();
8718 unsigned AttrNumArgs = AL.getNumArgMembers();
8719 for (size_t I = 0; I < std::min(AL.getNumArgs(), AttrNumArgs); ++I) {
8720 bool IsLastAttrArg = I == (AttrNumArgs - 1);
8721 // If the argument is the last argument and it is variadic it can contain
8722 // any expression.
8723 if (IsLastAttrArg && AttrHasVariadicArg)
8724 return false;
8725 Expr *E = AL.getArgAsExpr(I);
8726 bool ArgMemberCanHoldExpr = AL.isParamExpr(I);
8727 // If the expression is a pack expansion then arguments must be delayed
8728 // unless the argument is an expression and it is the last argument of the
8729 // attribute.
8730 if (isa<PackExpansionExpr>(E))
8731 return !(IsLastAttrArg && ArgMemberCanHoldExpr);
8732 // Last case is if the expression is value dependent then it must delay
8733 // arguments unless the corresponding argument is able to hold the
8734 // expression.
8735 if (E->isValueDependent() && !ArgMemberCanHoldExpr)
8736 return true;
8738 return false;
8742 static void handleArmNewZaAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8743 if (auto *FPT = dyn_cast<FunctionProtoType>(D->getFunctionType())) {
8744 if (FPT->getAArch64SMEAttributes() &
8745 FunctionType::SME_PStateZASharedMask) {
8746 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
8747 << AL << "'__arm_shared_za'" << true;
8748 AL.setInvalid();
8750 if (FPT->getAArch64SMEAttributes() &
8751 FunctionType::SME_PStateZAPreservedMask) {
8752 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
8753 << AL << "'__arm_preserves_za'" << true;
8754 AL.setInvalid();
8756 if (AL.isInvalid())
8757 return;
8760 handleSimpleAttribute<ArmNewZAAttr>(S, D, AL);
8763 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
8764 /// the attribute applies to decls. If the attribute is a type attribute, just
8765 /// silently ignore it if a GNU attribute.
8766 static void
8767 ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
8768 const Sema::ProcessDeclAttributeOptions &Options) {
8769 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
8770 return;
8772 // Ignore C++11 attributes on declarator chunks: they appertain to the type
8773 // instead.
8774 if (AL.isCXX11Attribute() && !Options.IncludeCXX11Attributes)
8775 return;
8777 // Unknown attributes are automatically warned on. Target-specific attributes
8778 // which do not apply to the current target architecture are treated as
8779 // though they were unknown attributes.
8780 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
8781 !AL.existsInTarget(S.Context.getTargetInfo())) {
8782 S.Diag(AL.getLoc(),
8783 AL.isRegularKeywordAttribute()
8784 ? (unsigned)diag::err_keyword_not_supported_on_target
8785 : AL.isDeclspecAttribute()
8786 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
8787 : (unsigned)diag::warn_unknown_attribute_ignored)
8788 << AL << AL.getRange();
8789 return;
8792 // Check if argument population must delayed to after template instantiation.
8793 bool MustDelayArgs = MustDelayAttributeArguments(AL);
8795 // Argument number check must be skipped if arguments are delayed.
8796 if (S.checkCommonAttributeFeatures(D, AL, MustDelayArgs))
8797 return;
8799 if (MustDelayArgs) {
8800 AL.handleAttrWithDelayedArgs(S, D);
8801 return;
8804 switch (AL.getKind()) {
8805 default:
8806 if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
8807 break;
8808 if (!AL.isStmtAttr()) {
8809 assert(AL.isTypeAttr() && "Non-type attribute not handled");
8811 if (AL.isTypeAttr()) {
8812 if (Options.IgnoreTypeAttributes)
8813 break;
8814 if (!AL.isStandardAttributeSyntax() && !AL.isRegularKeywordAttribute()) {
8815 // Non-[[]] type attributes are handled in processTypeAttrs(); silently
8816 // move on.
8817 break;
8820 // According to the C and C++ standards, we should never see a
8821 // [[]] type attribute on a declaration. However, we have in the past
8822 // allowed some type attributes to "slide" to the `DeclSpec`, so we need
8823 // to continue to support this legacy behavior. We only do this, however,
8824 // if
8825 // - we actually have a `DeclSpec`, i.e. if we're looking at a
8826 // `DeclaratorDecl`, or
8827 // - we are looking at an alias-declaration, where historically we have
8828 // allowed type attributes after the identifier to slide to the type.
8829 if (AL.slidesFromDeclToDeclSpecLegacyBehavior() &&
8830 isa<DeclaratorDecl, TypeAliasDecl>(D)) {
8831 // Suggest moving the attribute to the type instead, but only for our
8832 // own vendor attributes; moving other vendors' attributes might hurt
8833 // portability.
8834 if (AL.isClangScope()) {
8835 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
8836 << AL << D->getLocation();
8839 // Allow this type attribute to be handled in processTypeAttrs();
8840 // silently move on.
8841 break;
8844 if (AL.getKind() == ParsedAttr::AT_Regparm) {
8845 // `regparm` is a special case: It's a type attribute but we still want
8846 // to treat it as if it had been written on the declaration because that
8847 // way we'll be able to handle it directly in `processTypeAttr()`.
8848 // If we treated `regparm` it as if it had been written on the
8849 // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
8850 // would try to move it to the declarator, but that doesn't work: We
8851 // can't remove the attribute from the list of declaration attributes
8852 // because it might be needed by other declarators in the same
8853 // declaration.
8854 break;
8857 if (AL.getKind() == ParsedAttr::AT_VectorSize) {
8858 // `vector_size` is a special case: It's a type attribute semantically,
8859 // but GCC expects the [[]] syntax to be written on the declaration (and
8860 // warns that the attribute has no effect if it is placed on the
8861 // decl-specifier-seq).
8862 // Silently move on and allow the attribute to be handled in
8863 // processTypeAttr().
8864 break;
8867 if (AL.getKind() == ParsedAttr::AT_NoDeref) {
8868 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8869 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8870 // We allow processTypeAttrs() to emit a warning and silently move on.
8871 break;
8874 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
8875 // statement attribute is not written on a declaration, but this code is
8876 // needed for type attributes as well as statement attributes in Attr.td
8877 // that do not list any subjects.
8878 S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)
8879 << AL << AL.isRegularKeywordAttribute() << D->getLocation();
8880 break;
8881 case ParsedAttr::AT_Interrupt:
8882 handleInterruptAttr(S, D, AL);
8883 break;
8884 case ParsedAttr::AT_X86ForceAlignArgPointer:
8885 handleX86ForceAlignArgPointerAttr(S, D, AL);
8886 break;
8887 case ParsedAttr::AT_ReadOnlyPlacement:
8888 handleSimpleAttribute<ReadOnlyPlacementAttr>(S, D, AL);
8889 break;
8890 case ParsedAttr::AT_DLLExport:
8891 case ParsedAttr::AT_DLLImport:
8892 handleDLLAttr(S, D, AL);
8893 break;
8894 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
8895 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
8896 break;
8897 case ParsedAttr::AT_AMDGPUWavesPerEU:
8898 handleAMDGPUWavesPerEUAttr(S, D, AL);
8899 break;
8900 case ParsedAttr::AT_AMDGPUNumSGPR:
8901 handleAMDGPUNumSGPRAttr(S, D, AL);
8902 break;
8903 case ParsedAttr::AT_AMDGPUNumVGPR:
8904 handleAMDGPUNumVGPRAttr(S, D, AL);
8905 break;
8906 case ParsedAttr::AT_AVRSignal:
8907 handleAVRSignalAttr(S, D, AL);
8908 break;
8909 case ParsedAttr::AT_BPFPreserveAccessIndex:
8910 handleBPFPreserveAccessIndexAttr(S, D, AL);
8911 break;
8912 case ParsedAttr::AT_BTFDeclTag:
8913 handleBTFDeclTagAttr(S, D, AL);
8914 break;
8915 case ParsedAttr::AT_WebAssemblyExportName:
8916 handleWebAssemblyExportNameAttr(S, D, AL);
8917 break;
8918 case ParsedAttr::AT_WebAssemblyImportModule:
8919 handleWebAssemblyImportModuleAttr(S, D, AL);
8920 break;
8921 case ParsedAttr::AT_WebAssemblyImportName:
8922 handleWebAssemblyImportNameAttr(S, D, AL);
8923 break;
8924 case ParsedAttr::AT_IBOutlet:
8925 handleIBOutlet(S, D, AL);
8926 break;
8927 case ParsedAttr::AT_IBOutletCollection:
8928 handleIBOutletCollection(S, D, AL);
8929 break;
8930 case ParsedAttr::AT_IFunc:
8931 handleIFuncAttr(S, D, AL);
8932 break;
8933 case ParsedAttr::AT_Alias:
8934 handleAliasAttr(S, D, AL);
8935 break;
8936 case ParsedAttr::AT_Aligned:
8937 handleAlignedAttr(S, D, AL);
8938 break;
8939 case ParsedAttr::AT_AlignValue:
8940 handleAlignValueAttr(S, D, AL);
8941 break;
8942 case ParsedAttr::AT_AllocSize:
8943 handleAllocSizeAttr(S, D, AL);
8944 break;
8945 case ParsedAttr::AT_AlwaysInline:
8946 handleAlwaysInlineAttr(S, D, AL);
8947 break;
8948 case ParsedAttr::AT_AnalyzerNoReturn:
8949 handleAnalyzerNoReturnAttr(S, D, AL);
8950 break;
8951 case ParsedAttr::AT_TLSModel:
8952 handleTLSModelAttr(S, D, AL);
8953 break;
8954 case ParsedAttr::AT_Annotate:
8955 handleAnnotateAttr(S, D, AL);
8956 break;
8957 case ParsedAttr::AT_Availability:
8958 handleAvailabilityAttr(S, D, AL);
8959 break;
8960 case ParsedAttr::AT_CarriesDependency:
8961 handleDependencyAttr(S, scope, D, AL);
8962 break;
8963 case ParsedAttr::AT_CPUDispatch:
8964 case ParsedAttr::AT_CPUSpecific:
8965 handleCPUSpecificAttr(S, D, AL);
8966 break;
8967 case ParsedAttr::AT_Common:
8968 handleCommonAttr(S, D, AL);
8969 break;
8970 case ParsedAttr::AT_CUDAConstant:
8971 handleConstantAttr(S, D, AL);
8972 break;
8973 case ParsedAttr::AT_PassObjectSize:
8974 handlePassObjectSizeAttr(S, D, AL);
8975 break;
8976 case ParsedAttr::AT_Constructor:
8977 handleConstructorAttr(S, D, AL);
8978 break;
8979 case ParsedAttr::AT_Deprecated:
8980 handleDeprecatedAttr(S, D, AL);
8981 break;
8982 case ParsedAttr::AT_Destructor:
8983 handleDestructorAttr(S, D, AL);
8984 break;
8985 case ParsedAttr::AT_EnableIf:
8986 handleEnableIfAttr(S, D, AL);
8987 break;
8988 case ParsedAttr::AT_Error:
8989 handleErrorAttr(S, D, AL);
8990 break;
8991 case ParsedAttr::AT_DiagnoseIf:
8992 handleDiagnoseIfAttr(S, D, AL);
8993 break;
8994 case ParsedAttr::AT_DiagnoseAsBuiltin:
8995 handleDiagnoseAsBuiltinAttr(S, D, AL);
8996 break;
8997 case ParsedAttr::AT_NoBuiltin:
8998 handleNoBuiltinAttr(S, D, AL);
8999 break;
9000 case ParsedAttr::AT_ExtVectorType:
9001 handleExtVectorTypeAttr(S, D, AL);
9002 break;
9003 case ParsedAttr::AT_ExternalSourceSymbol:
9004 handleExternalSourceSymbolAttr(S, D, AL);
9005 break;
9006 case ParsedAttr::AT_MinSize:
9007 handleMinSizeAttr(S, D, AL);
9008 break;
9009 case ParsedAttr::AT_OptimizeNone:
9010 handleOptimizeNoneAttr(S, D, AL);
9011 break;
9012 case ParsedAttr::AT_EnumExtensibility:
9013 handleEnumExtensibilityAttr(S, D, AL);
9014 break;
9015 case ParsedAttr::AT_SYCLKernel:
9016 handleSYCLKernelAttr(S, D, AL);
9017 break;
9018 case ParsedAttr::AT_SYCLSpecialClass:
9019 handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL);
9020 break;
9021 case ParsedAttr::AT_Format:
9022 handleFormatAttr(S, D, AL);
9023 break;
9024 case ParsedAttr::AT_FormatArg:
9025 handleFormatArgAttr(S, D, AL);
9026 break;
9027 case ParsedAttr::AT_Callback:
9028 handleCallbackAttr(S, D, AL);
9029 break;
9030 case ParsedAttr::AT_CalledOnce:
9031 handleCalledOnceAttr(S, D, AL);
9032 break;
9033 case ParsedAttr::AT_NVPTXKernel:
9034 case ParsedAttr::AT_CUDAGlobal:
9035 handleGlobalAttr(S, D, AL);
9036 break;
9037 case ParsedAttr::AT_CUDADevice:
9038 handleDeviceAttr(S, D, AL);
9039 break;
9040 case ParsedAttr::AT_HIPManaged:
9041 handleManagedAttr(S, D, AL);
9042 break;
9043 case ParsedAttr::AT_GNUInline:
9044 handleGNUInlineAttr(S, D, AL);
9045 break;
9046 case ParsedAttr::AT_CUDALaunchBounds:
9047 handleLaunchBoundsAttr(S, D, AL);
9048 break;
9049 case ParsedAttr::AT_Restrict:
9050 handleRestrictAttr(S, D, AL);
9051 break;
9052 case ParsedAttr::AT_Mode:
9053 handleModeAttr(S, D, AL);
9054 break;
9055 case ParsedAttr::AT_NonNull:
9056 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
9057 handleNonNullAttrParameter(S, PVD, AL);
9058 else
9059 handleNonNullAttr(S, D, AL);
9060 break;
9061 case ParsedAttr::AT_ReturnsNonNull:
9062 handleReturnsNonNullAttr(S, D, AL);
9063 break;
9064 case ParsedAttr::AT_NoEscape:
9065 handleNoEscapeAttr(S, D, AL);
9066 break;
9067 case ParsedAttr::AT_MaybeUndef:
9068 handleSimpleAttribute<MaybeUndefAttr>(S, D, AL);
9069 break;
9070 case ParsedAttr::AT_AssumeAligned:
9071 handleAssumeAlignedAttr(S, D, AL);
9072 break;
9073 case ParsedAttr::AT_AllocAlign:
9074 handleAllocAlignAttr(S, D, AL);
9075 break;
9076 case ParsedAttr::AT_Ownership:
9077 handleOwnershipAttr(S, D, AL);
9078 break;
9079 case ParsedAttr::AT_Naked:
9080 handleNakedAttr(S, D, AL);
9081 break;
9082 case ParsedAttr::AT_NoReturn:
9083 handleNoReturnAttr(S, D, AL);
9084 break;
9085 case ParsedAttr::AT_CXX11NoReturn:
9086 handleStandardNoReturnAttr(S, D, AL);
9087 break;
9088 case ParsedAttr::AT_AnyX86NoCfCheck:
9089 handleNoCfCheckAttr(S, D, AL);
9090 break;
9091 case ParsedAttr::AT_NoThrow:
9092 if (!AL.isUsedAsTypeAttr())
9093 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
9094 break;
9095 case ParsedAttr::AT_CUDAShared:
9096 handleSharedAttr(S, D, AL);
9097 break;
9098 case ParsedAttr::AT_VecReturn:
9099 handleVecReturnAttr(S, D, AL);
9100 break;
9101 case ParsedAttr::AT_ObjCOwnership:
9102 handleObjCOwnershipAttr(S, D, AL);
9103 break;
9104 case ParsedAttr::AT_ObjCPreciseLifetime:
9105 handleObjCPreciseLifetimeAttr(S, D, AL);
9106 break;
9107 case ParsedAttr::AT_ObjCReturnsInnerPointer:
9108 handleObjCReturnsInnerPointerAttr(S, D, AL);
9109 break;
9110 case ParsedAttr::AT_ObjCRequiresSuper:
9111 handleObjCRequiresSuperAttr(S, D, AL);
9112 break;
9113 case ParsedAttr::AT_ObjCBridge:
9114 handleObjCBridgeAttr(S, D, AL);
9115 break;
9116 case ParsedAttr::AT_ObjCBridgeMutable:
9117 handleObjCBridgeMutableAttr(S, D, AL);
9118 break;
9119 case ParsedAttr::AT_ObjCBridgeRelated:
9120 handleObjCBridgeRelatedAttr(S, D, AL);
9121 break;
9122 case ParsedAttr::AT_ObjCDesignatedInitializer:
9123 handleObjCDesignatedInitializer(S, D, AL);
9124 break;
9125 case ParsedAttr::AT_ObjCRuntimeName:
9126 handleObjCRuntimeName(S, D, AL);
9127 break;
9128 case ParsedAttr::AT_ObjCBoxable:
9129 handleObjCBoxable(S, D, AL);
9130 break;
9131 case ParsedAttr::AT_NSErrorDomain:
9132 handleNSErrorDomain(S, D, AL);
9133 break;
9134 case ParsedAttr::AT_CFConsumed:
9135 case ParsedAttr::AT_NSConsumed:
9136 case ParsedAttr::AT_OSConsumed:
9137 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
9138 /*IsTemplateInstantiation=*/false);
9139 break;
9140 case ParsedAttr::AT_OSReturnsRetainedOnZero:
9141 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
9142 S, D, AL, isValidOSObjectOutParameter(D),
9143 diag::warn_ns_attribute_wrong_parameter_type,
9144 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
9145 break;
9146 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
9147 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
9148 S, D, AL, isValidOSObjectOutParameter(D),
9149 diag::warn_ns_attribute_wrong_parameter_type,
9150 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
9151 break;
9152 case ParsedAttr::AT_NSReturnsAutoreleased:
9153 case ParsedAttr::AT_NSReturnsNotRetained:
9154 case ParsedAttr::AT_NSReturnsRetained:
9155 case ParsedAttr::AT_CFReturnsNotRetained:
9156 case ParsedAttr::AT_CFReturnsRetained:
9157 case ParsedAttr::AT_OSReturnsNotRetained:
9158 case ParsedAttr::AT_OSReturnsRetained:
9159 handleXReturnsXRetainedAttr(S, D, AL);
9160 break;
9161 case ParsedAttr::AT_WorkGroupSizeHint:
9162 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
9163 break;
9164 case ParsedAttr::AT_ReqdWorkGroupSize:
9165 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
9166 break;
9167 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
9168 handleSubGroupSize(S, D, AL);
9169 break;
9170 case ParsedAttr::AT_VecTypeHint:
9171 handleVecTypeHint(S, D, AL);
9172 break;
9173 case ParsedAttr::AT_InitPriority:
9174 handleInitPriorityAttr(S, D, AL);
9175 break;
9176 case ParsedAttr::AT_Packed:
9177 handlePackedAttr(S, D, AL);
9178 break;
9179 case ParsedAttr::AT_PreferredName:
9180 handlePreferredName(S, D, AL);
9181 break;
9182 case ParsedAttr::AT_Section:
9183 handleSectionAttr(S, D, AL);
9184 break;
9185 case ParsedAttr::AT_RandomizeLayout:
9186 handleRandomizeLayoutAttr(S, D, AL);
9187 break;
9188 case ParsedAttr::AT_NoRandomizeLayout:
9189 handleNoRandomizeLayoutAttr(S, D, AL);
9190 break;
9191 case ParsedAttr::AT_CodeSeg:
9192 handleCodeSegAttr(S, D, AL);
9193 break;
9194 case ParsedAttr::AT_Target:
9195 handleTargetAttr(S, D, AL);
9196 break;
9197 case ParsedAttr::AT_TargetVersion:
9198 handleTargetVersionAttr(S, D, AL);
9199 break;
9200 case ParsedAttr::AT_TargetClones:
9201 handleTargetClonesAttr(S, D, AL);
9202 break;
9203 case ParsedAttr::AT_MinVectorWidth:
9204 handleMinVectorWidthAttr(S, D, AL);
9205 break;
9206 case ParsedAttr::AT_Unavailable:
9207 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
9208 break;
9209 case ParsedAttr::AT_Assumption:
9210 handleAssumumptionAttr(S, D, AL);
9211 break;
9212 case ParsedAttr::AT_ObjCDirect:
9213 handleObjCDirectAttr(S, D, AL);
9214 break;
9215 case ParsedAttr::AT_ObjCDirectMembers:
9216 handleObjCDirectMembersAttr(S, D, AL);
9217 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
9218 break;
9219 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
9220 handleObjCSuppresProtocolAttr(S, D, AL);
9221 break;
9222 case ParsedAttr::AT_Unused:
9223 handleUnusedAttr(S, D, AL);
9224 break;
9225 case ParsedAttr::AT_Visibility:
9226 handleVisibilityAttr(S, D, AL, false);
9227 break;
9228 case ParsedAttr::AT_TypeVisibility:
9229 handleVisibilityAttr(S, D, AL, true);
9230 break;
9231 case ParsedAttr::AT_WarnUnusedResult:
9232 handleWarnUnusedResult(S, D, AL);
9233 break;
9234 case ParsedAttr::AT_WeakRef:
9235 handleWeakRefAttr(S, D, AL);
9236 break;
9237 case ParsedAttr::AT_WeakImport:
9238 handleWeakImportAttr(S, D, AL);
9239 break;
9240 case ParsedAttr::AT_TransparentUnion:
9241 handleTransparentUnionAttr(S, D, AL);
9242 break;
9243 case ParsedAttr::AT_ObjCMethodFamily:
9244 handleObjCMethodFamilyAttr(S, D, AL);
9245 break;
9246 case ParsedAttr::AT_ObjCNSObject:
9247 handleObjCNSObject(S, D, AL);
9248 break;
9249 case ParsedAttr::AT_ObjCIndependentClass:
9250 handleObjCIndependentClass(S, D, AL);
9251 break;
9252 case ParsedAttr::AT_Blocks:
9253 handleBlocksAttr(S, D, AL);
9254 break;
9255 case ParsedAttr::AT_Sentinel:
9256 handleSentinelAttr(S, D, AL);
9257 break;
9258 case ParsedAttr::AT_Cleanup:
9259 handleCleanupAttr(S, D, AL);
9260 break;
9261 case ParsedAttr::AT_NoDebug:
9262 handleNoDebugAttr(S, D, AL);
9263 break;
9264 case ParsedAttr::AT_CmseNSEntry:
9265 handleCmseNSEntryAttr(S, D, AL);
9266 break;
9267 case ParsedAttr::AT_StdCall:
9268 case ParsedAttr::AT_CDecl:
9269 case ParsedAttr::AT_FastCall:
9270 case ParsedAttr::AT_ThisCall:
9271 case ParsedAttr::AT_Pascal:
9272 case ParsedAttr::AT_RegCall:
9273 case ParsedAttr::AT_SwiftCall:
9274 case ParsedAttr::AT_SwiftAsyncCall:
9275 case ParsedAttr::AT_VectorCall:
9276 case ParsedAttr::AT_MSABI:
9277 case ParsedAttr::AT_SysVABI:
9278 case ParsedAttr::AT_Pcs:
9279 case ParsedAttr::AT_IntelOclBicc:
9280 case ParsedAttr::AT_PreserveMost:
9281 case ParsedAttr::AT_PreserveAll:
9282 case ParsedAttr::AT_AArch64VectorPcs:
9283 case ParsedAttr::AT_AArch64SVEPcs:
9284 case ParsedAttr::AT_AMDGPUKernelCall:
9285 handleCallConvAttr(S, D, AL);
9286 break;
9287 case ParsedAttr::AT_Suppress:
9288 handleSuppressAttr(S, D, AL);
9289 break;
9290 case ParsedAttr::AT_Owner:
9291 case ParsedAttr::AT_Pointer:
9292 handleLifetimeCategoryAttr(S, D, AL);
9293 break;
9294 case ParsedAttr::AT_OpenCLAccess:
9295 handleOpenCLAccessAttr(S, D, AL);
9296 break;
9297 case ParsedAttr::AT_OpenCLNoSVM:
9298 handleOpenCLNoSVMAttr(S, D, AL);
9299 break;
9300 case ParsedAttr::AT_SwiftContext:
9301 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
9302 break;
9303 case ParsedAttr::AT_SwiftAsyncContext:
9304 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext);
9305 break;
9306 case ParsedAttr::AT_SwiftErrorResult:
9307 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
9308 break;
9309 case ParsedAttr::AT_SwiftIndirectResult:
9310 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
9311 break;
9312 case ParsedAttr::AT_InternalLinkage:
9313 handleInternalLinkageAttr(S, D, AL);
9314 break;
9315 case ParsedAttr::AT_ZeroCallUsedRegs:
9316 handleZeroCallUsedRegsAttr(S, D, AL);
9317 break;
9318 case ParsedAttr::AT_FunctionReturnThunks:
9319 handleFunctionReturnThunksAttr(S, D, AL);
9320 break;
9321 case ParsedAttr::AT_NoMerge:
9322 handleNoMergeAttr(S, D, AL);
9323 break;
9325 case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod:
9326 handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
9327 break;
9329 // Microsoft attributes:
9330 case ParsedAttr::AT_LayoutVersion:
9331 handleLayoutVersion(S, D, AL);
9332 break;
9333 case ParsedAttr::AT_Uuid:
9334 handleUuidAttr(S, D, AL);
9335 break;
9336 case ParsedAttr::AT_MSInheritance:
9337 handleMSInheritanceAttr(S, D, AL);
9338 break;
9339 case ParsedAttr::AT_Thread:
9340 handleDeclspecThreadAttr(S, D, AL);
9341 break;
9343 // HLSL attributes:
9344 case ParsedAttr::AT_HLSLNumThreads:
9345 handleHLSLNumThreadsAttr(S, D, AL);
9346 break;
9347 case ParsedAttr::AT_HLSLSV_GroupIndex:
9348 handleHLSLSVGroupIndexAttr(S, D, AL);
9349 break;
9350 case ParsedAttr::AT_HLSLSV_DispatchThreadID:
9351 handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
9352 break;
9353 case ParsedAttr::AT_HLSLShader:
9354 handleHLSLShaderAttr(S, D, AL);
9355 break;
9356 case ParsedAttr::AT_HLSLResourceBinding:
9357 handleHLSLResourceBindingAttr(S, D, AL);
9358 break;
9360 case ParsedAttr::AT_AbiTag:
9361 handleAbiTagAttr(S, D, AL);
9362 break;
9363 case ParsedAttr::AT_CFGuard:
9364 handleCFGuardAttr(S, D, AL);
9365 break;
9367 // Thread safety attributes:
9368 case ParsedAttr::AT_AssertExclusiveLock:
9369 handleAssertExclusiveLockAttr(S, D, AL);
9370 break;
9371 case ParsedAttr::AT_AssertSharedLock:
9372 handleAssertSharedLockAttr(S, D, AL);
9373 break;
9374 case ParsedAttr::AT_PtGuardedVar:
9375 handlePtGuardedVarAttr(S, D, AL);
9376 break;
9377 case ParsedAttr::AT_NoSanitize:
9378 handleNoSanitizeAttr(S, D, AL);
9379 break;
9380 case ParsedAttr::AT_NoSanitizeSpecific:
9381 handleNoSanitizeSpecificAttr(S, D, AL);
9382 break;
9383 case ParsedAttr::AT_GuardedBy:
9384 handleGuardedByAttr(S, D, AL);
9385 break;
9386 case ParsedAttr::AT_PtGuardedBy:
9387 handlePtGuardedByAttr(S, D, AL);
9388 break;
9389 case ParsedAttr::AT_ExclusiveTrylockFunction:
9390 handleExclusiveTrylockFunctionAttr(S, D, AL);
9391 break;
9392 case ParsedAttr::AT_LockReturned:
9393 handleLockReturnedAttr(S, D, AL);
9394 break;
9395 case ParsedAttr::AT_LocksExcluded:
9396 handleLocksExcludedAttr(S, D, AL);
9397 break;
9398 case ParsedAttr::AT_SharedTrylockFunction:
9399 handleSharedTrylockFunctionAttr(S, D, AL);
9400 break;
9401 case ParsedAttr::AT_AcquiredBefore:
9402 handleAcquiredBeforeAttr(S, D, AL);
9403 break;
9404 case ParsedAttr::AT_AcquiredAfter:
9405 handleAcquiredAfterAttr(S, D, AL);
9406 break;
9408 // Capability analysis attributes.
9409 case ParsedAttr::AT_Capability:
9410 case ParsedAttr::AT_Lockable:
9411 handleCapabilityAttr(S, D, AL);
9412 break;
9413 case ParsedAttr::AT_RequiresCapability:
9414 handleRequiresCapabilityAttr(S, D, AL);
9415 break;
9417 case ParsedAttr::AT_AssertCapability:
9418 handleAssertCapabilityAttr(S, D, AL);
9419 break;
9420 case ParsedAttr::AT_AcquireCapability:
9421 handleAcquireCapabilityAttr(S, D, AL);
9422 break;
9423 case ParsedAttr::AT_ReleaseCapability:
9424 handleReleaseCapabilityAttr(S, D, AL);
9425 break;
9426 case ParsedAttr::AT_TryAcquireCapability:
9427 handleTryAcquireCapabilityAttr(S, D, AL);
9428 break;
9430 // Consumed analysis attributes.
9431 case ParsedAttr::AT_Consumable:
9432 handleConsumableAttr(S, D, AL);
9433 break;
9434 case ParsedAttr::AT_CallableWhen:
9435 handleCallableWhenAttr(S, D, AL);
9436 break;
9437 case ParsedAttr::AT_ParamTypestate:
9438 handleParamTypestateAttr(S, D, AL);
9439 break;
9440 case ParsedAttr::AT_ReturnTypestate:
9441 handleReturnTypestateAttr(S, D, AL);
9442 break;
9443 case ParsedAttr::AT_SetTypestate:
9444 handleSetTypestateAttr(S, D, AL);
9445 break;
9446 case ParsedAttr::AT_TestTypestate:
9447 handleTestTypestateAttr(S, D, AL);
9448 break;
9450 // Type safety attributes.
9451 case ParsedAttr::AT_ArgumentWithTypeTag:
9452 handleArgumentWithTypeTagAttr(S, D, AL);
9453 break;
9454 case ParsedAttr::AT_TypeTagForDatatype:
9455 handleTypeTagForDatatypeAttr(S, D, AL);
9456 break;
9458 // Swift attributes.
9459 case ParsedAttr::AT_SwiftAsyncName:
9460 handleSwiftAsyncName(S, D, AL);
9461 break;
9462 case ParsedAttr::AT_SwiftAttr:
9463 handleSwiftAttrAttr(S, D, AL);
9464 break;
9465 case ParsedAttr::AT_SwiftBridge:
9466 handleSwiftBridge(S, D, AL);
9467 break;
9468 case ParsedAttr::AT_SwiftError:
9469 handleSwiftError(S, D, AL);
9470 break;
9471 case ParsedAttr::AT_SwiftName:
9472 handleSwiftName(S, D, AL);
9473 break;
9474 case ParsedAttr::AT_SwiftNewType:
9475 handleSwiftNewType(S, D, AL);
9476 break;
9477 case ParsedAttr::AT_SwiftAsync:
9478 handleSwiftAsyncAttr(S, D, AL);
9479 break;
9480 case ParsedAttr::AT_SwiftAsyncError:
9481 handleSwiftAsyncError(S, D, AL);
9482 break;
9484 // XRay attributes.
9485 case ParsedAttr::AT_XRayLogArgs:
9486 handleXRayLogArgsAttr(S, D, AL);
9487 break;
9489 case ParsedAttr::AT_PatchableFunctionEntry:
9490 handlePatchableFunctionEntryAttr(S, D, AL);
9491 break;
9493 case ParsedAttr::AT_AlwaysDestroy:
9494 case ParsedAttr::AT_NoDestroy:
9495 handleDestroyAttr(S, D, AL);
9496 break;
9498 case ParsedAttr::AT_Uninitialized:
9499 handleUninitializedAttr(S, D, AL);
9500 break;
9502 case ParsedAttr::AT_ObjCExternallyRetained:
9503 handleObjCExternallyRetainedAttr(S, D, AL);
9504 break;
9506 case ParsedAttr::AT_MIGServerRoutine:
9507 handleMIGServerRoutineAttr(S, D, AL);
9508 break;
9510 case ParsedAttr::AT_MSAllocator:
9511 handleMSAllocatorAttr(S, D, AL);
9512 break;
9514 case ParsedAttr::AT_ArmBuiltinAlias:
9515 handleArmBuiltinAliasAttr(S, D, AL);
9516 break;
9518 case ParsedAttr::AT_ArmLocallyStreaming:
9519 handleSimpleAttribute<ArmLocallyStreamingAttr>(S, D, AL);
9520 break;
9522 case ParsedAttr::AT_ArmNewZA:
9523 handleArmNewZaAttr(S, D, AL);
9524 break;
9526 case ParsedAttr::AT_AcquireHandle:
9527 handleAcquireHandleAttr(S, D, AL);
9528 break;
9530 case ParsedAttr::AT_ReleaseHandle:
9531 handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
9532 break;
9534 case ParsedAttr::AT_UnsafeBufferUsage:
9535 handleUnsafeBufferUsage<UnsafeBufferUsageAttr>(S, D, AL);
9536 break;
9538 case ParsedAttr::AT_UseHandle:
9539 handleHandleAttr<UseHandleAttr>(S, D, AL);
9540 break;
9542 case ParsedAttr::AT_EnforceTCB:
9543 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
9544 break;
9546 case ParsedAttr::AT_EnforceTCBLeaf:
9547 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
9548 break;
9550 case ParsedAttr::AT_BuiltinAlias:
9551 handleBuiltinAliasAttr(S, D, AL);
9552 break;
9554 case ParsedAttr::AT_UsingIfExists:
9555 handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
9556 break;
9560 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
9561 /// attribute list to the specified decl, ignoring any type attributes.
9562 void Sema::ProcessDeclAttributeList(
9563 Scope *S, Decl *D, const ParsedAttributesView &AttrList,
9564 const ProcessDeclAttributeOptions &Options) {
9565 if (AttrList.empty())
9566 return;
9568 for (const ParsedAttr &AL : AttrList)
9569 ProcessDeclAttribute(*this, S, D, AL, Options);
9571 // FIXME: We should be able to handle these cases in TableGen.
9572 // GCC accepts
9573 // static int a9 __attribute__((weakref));
9574 // but that looks really pointless. We reject it.
9575 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
9576 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
9577 << cast<NamedDecl>(D);
9578 D->dropAttr<WeakRefAttr>();
9579 return;
9582 // FIXME: We should be able to handle this in TableGen as well. It would be
9583 // good to have a way to specify "these attributes must appear as a group",
9584 // for these. Additionally, it would be good to have a way to specify "these
9585 // attribute must never appear as a group" for attributes like cold and hot.
9586 if (!D->hasAttr<OpenCLKernelAttr>()) {
9587 // These attributes cannot be applied to a non-kernel function.
9588 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
9589 // FIXME: This emits a different error message than
9590 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
9591 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9592 D->setInvalidDecl();
9593 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
9594 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9595 D->setInvalidDecl();
9596 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
9597 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9598 D->setInvalidDecl();
9599 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
9600 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9601 D->setInvalidDecl();
9602 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
9603 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
9604 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9605 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9606 D->setInvalidDecl();
9607 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
9608 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9609 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9610 D->setInvalidDecl();
9611 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
9612 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9613 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9614 D->setInvalidDecl();
9615 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
9616 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9617 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9618 D->setInvalidDecl();
9623 // Do this check after processing D's attributes because the attribute
9624 // objc_method_family can change whether the given method is in the init
9625 // family, and it can be applied after objc_designated_initializer. This is a
9626 // bit of a hack, but we need it to be compatible with versions of clang that
9627 // processed the attribute list in the wrong order.
9628 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
9629 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
9630 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
9631 D->dropAttr<ObjCDesignatedInitializerAttr>();
9635 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
9636 // attribute.
9637 void Sema::ProcessDeclAttributeDelayed(Decl *D,
9638 const ParsedAttributesView &AttrList) {
9639 for (const ParsedAttr &AL : AttrList)
9640 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
9641 handleTransparentUnionAttr(*this, D, AL);
9642 break;
9645 // For BPFPreserveAccessIndexAttr, we want to populate the attributes
9646 // to fields and inner records as well.
9647 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
9648 handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
9651 // Annotation attributes are the only attributes allowed after an access
9652 // specifier.
9653 bool Sema::ProcessAccessDeclAttributeList(
9654 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
9655 for (const ParsedAttr &AL : AttrList) {
9656 if (AL.getKind() == ParsedAttr::AT_Annotate) {
9657 ProcessDeclAttribute(*this, nullptr, ASDecl, AL,
9658 ProcessDeclAttributeOptions());
9659 } else {
9660 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
9661 return true;
9664 return false;
9667 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
9668 /// contains any decl attributes that we should warn about.
9669 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
9670 for (const ParsedAttr &AL : A) {
9671 // Only warn if the attribute is an unignored, non-type attribute.
9672 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
9673 continue;
9674 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
9675 continue;
9677 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
9678 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
9679 << AL << AL.getRange();
9680 } else {
9681 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
9682 << AL.getRange();
9687 /// checkUnusedDeclAttributes - Given a declarator which is not being
9688 /// used to build a declaration, complain about any decl attributes
9689 /// which might be lying around on it.
9690 void Sema::checkUnusedDeclAttributes(Declarator &D) {
9691 ::checkUnusedDeclAttributes(*this, D.getDeclarationAttributes());
9692 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
9693 ::checkUnusedDeclAttributes(*this, D.getAttributes());
9694 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
9695 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
9698 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
9699 /// \#pragma weak needs a non-definition decl and source may not have one.
9700 NamedDecl *Sema::DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
9701 SourceLocation Loc) {
9702 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
9703 NamedDecl *NewD = nullptr;
9704 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
9705 FunctionDecl *NewFD;
9706 // FIXME: Missing call to CheckFunctionDeclaration().
9707 // FIXME: Mangling?
9708 // FIXME: Is the qualifier info correct?
9709 // FIXME: Is the DeclContext correct?
9710 NewFD = FunctionDecl::Create(
9711 FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
9712 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
9713 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
9714 FD->hasPrototype(), ConstexprSpecKind::Unspecified,
9715 FD->getTrailingRequiresClause());
9716 NewD = NewFD;
9718 if (FD->getQualifier())
9719 NewFD->setQualifierInfo(FD->getQualifierLoc());
9721 // Fake up parameter variables; they are declared as if this were
9722 // a typedef.
9723 QualType FDTy = FD->getType();
9724 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
9725 SmallVector<ParmVarDecl*, 16> Params;
9726 for (const auto &AI : FT->param_types()) {
9727 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
9728 Param->setScopeInfo(0, Params.size());
9729 Params.push_back(Param);
9731 NewFD->setParams(Params);
9733 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
9734 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
9735 VD->getInnerLocStart(), VD->getLocation(), II,
9736 VD->getType(), VD->getTypeSourceInfo(),
9737 VD->getStorageClass());
9738 if (VD->getQualifier())
9739 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
9741 return NewD;
9744 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
9745 /// applied to it, possibly with an alias.
9746 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W) {
9747 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
9748 IdentifierInfo *NDId = ND->getIdentifier();
9749 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
9750 NewD->addAttr(
9751 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
9752 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
9753 WeakTopLevelDecl.push_back(NewD);
9754 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
9755 // to insert Decl at TU scope, sorry.
9756 DeclContext *SavedContext = CurContext;
9757 CurContext = Context.getTranslationUnitDecl();
9758 NewD->setDeclContext(CurContext);
9759 NewD->setLexicalDeclContext(CurContext);
9760 PushOnScopeChains(NewD, S);
9761 CurContext = SavedContext;
9762 } else { // just add weak to existing
9763 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
9767 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
9768 // It's valid to "forward-declare" #pragma weak, in which case we
9769 // have to do this.
9770 LoadExternalWeakUndeclaredIdentifiers();
9771 if (WeakUndeclaredIdentifiers.empty())
9772 return;
9773 NamedDecl *ND = nullptr;
9774 if (auto *VD = dyn_cast<VarDecl>(D))
9775 if (VD->isExternC())
9776 ND = VD;
9777 if (auto *FD = dyn_cast<FunctionDecl>(D))
9778 if (FD->isExternC())
9779 ND = FD;
9780 if (!ND)
9781 return;
9782 if (IdentifierInfo *Id = ND->getIdentifier()) {
9783 auto I = WeakUndeclaredIdentifiers.find(Id);
9784 if (I != WeakUndeclaredIdentifiers.end()) {
9785 auto &WeakInfos = I->second;
9786 for (const auto &W : WeakInfos)
9787 DeclApplyPragmaWeak(S, ND, W);
9788 std::remove_reference_t<decltype(WeakInfos)> EmptyWeakInfos;
9789 WeakInfos.swap(EmptyWeakInfos);
9794 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
9795 /// it, apply them to D. This is a bit tricky because PD can have attributes
9796 /// specified in many different places, and we need to find and apply them all.
9797 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
9798 // Ordering of attributes can be important, so we take care to process
9799 // attributes in the order in which they appeared in the source code.
9801 // First, process attributes that appeared on the declaration itself (but
9802 // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
9803 ParsedAttributesView NonSlidingAttrs;
9804 for (ParsedAttr &AL : PD.getDeclarationAttributes()) {
9805 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
9806 // Skip processing the attribute, but do check if it appertains to the
9807 // declaration. This is needed for the `MatrixType` attribute, which,
9808 // despite being a type attribute, defines a `SubjectList` that only
9809 // allows it to be used on typedef declarations.
9810 AL.diagnoseAppertainsTo(*this, D);
9811 } else {
9812 NonSlidingAttrs.addAtEnd(&AL);
9815 ProcessDeclAttributeList(S, D, NonSlidingAttrs);
9817 // Apply decl attributes from the DeclSpec if present.
9818 if (!PD.getDeclSpec().getAttributes().empty()) {
9819 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes(),
9820 ProcessDeclAttributeOptions()
9821 .WithIncludeCXX11Attributes(false)
9822 .WithIgnoreTypeAttributes(true));
9825 // Walk the declarator structure, applying decl attributes that were in a type
9826 // position to the decl itself. This handles cases like:
9827 // int *__attr__(x)** D;
9828 // when X is a decl attribute.
9829 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) {
9830 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
9831 ProcessDeclAttributeOptions()
9832 .WithIncludeCXX11Attributes(false)
9833 .WithIgnoreTypeAttributes(true));
9836 // Finally, apply any attributes on the decl itself.
9837 ProcessDeclAttributeList(S, D, PD.getAttributes());
9839 // Apply additional attributes specified by '#pragma clang attribute'.
9840 AddPragmaAttributes(S, D);
9843 /// Is the given declaration allowed to use a forbidden type?
9844 /// If so, it'll still be annotated with an attribute that makes it
9845 /// illegal to actually use.
9846 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
9847 const DelayedDiagnostic &diag,
9848 UnavailableAttr::ImplicitReason &reason) {
9849 // Private ivars are always okay. Unfortunately, people don't
9850 // always properly make their ivars private, even in system headers.
9851 // Plus we need to make fields okay, too.
9852 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
9853 !isa<FunctionDecl>(D))
9854 return false;
9856 // Silently accept unsupported uses of __weak in both user and system
9857 // declarations when it's been disabled, for ease of integration with
9858 // -fno-objc-arc files. We do have to take some care against attempts
9859 // to define such things; for now, we've only done that for ivars
9860 // and properties.
9861 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
9862 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
9863 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
9864 reason = UnavailableAttr::IR_ForbiddenWeak;
9865 return true;
9869 // Allow all sorts of things in system headers.
9870 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
9871 // Currently, all the failures dealt with this way are due to ARC
9872 // restrictions.
9873 reason = UnavailableAttr::IR_ARCForbiddenType;
9874 return true;
9877 return false;
9880 /// Handle a delayed forbidden-type diagnostic.
9881 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
9882 Decl *D) {
9883 auto Reason = UnavailableAttr::IR_None;
9884 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
9885 assert(Reason && "didn't set reason?");
9886 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
9887 return;
9889 if (S.getLangOpts().ObjCAutoRefCount)
9890 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9891 // FIXME: we may want to suppress diagnostics for all
9892 // kind of forbidden type messages on unavailable functions.
9893 if (FD->hasAttr<UnavailableAttr>() &&
9894 DD.getForbiddenTypeDiagnostic() ==
9895 diag::err_arc_array_param_no_ownership) {
9896 DD.Triggered = true;
9897 return;
9901 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
9902 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
9903 DD.Triggered = true;
9907 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
9908 assert(DelayedDiagnostics.getCurrentPool());
9909 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
9910 DelayedDiagnostics.popWithoutEmitting(state);
9912 // When delaying diagnostics to run in the context of a parsed
9913 // declaration, we only want to actually emit anything if parsing
9914 // succeeds.
9915 if (!decl) return;
9917 // We emit all the active diagnostics in this pool or any of its
9918 // parents. In general, we'll get one pool for the decl spec
9919 // and a child pool for each declarator; in a decl group like:
9920 // deprecated_typedef foo, *bar, baz();
9921 // only the declarator pops will be passed decls. This is correct;
9922 // we really do need to consider delayed diagnostics from the decl spec
9923 // for each of the different declarations.
9924 const DelayedDiagnosticPool *pool = &poppedPool;
9925 do {
9926 bool AnyAccessFailures = false;
9927 for (DelayedDiagnosticPool::pool_iterator
9928 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
9929 // This const_cast is a bit lame. Really, Triggered should be mutable.
9930 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
9931 if (diag.Triggered)
9932 continue;
9934 switch (diag.Kind) {
9935 case DelayedDiagnostic::Availability:
9936 // Don't bother giving deprecation/unavailable diagnostics if
9937 // the decl is invalid.
9938 if (!decl->isInvalidDecl())
9939 handleDelayedAvailabilityCheck(diag, decl);
9940 break;
9942 case DelayedDiagnostic::Access:
9943 // Only produce one access control diagnostic for a structured binding
9944 // declaration: we don't need to tell the user that all the fields are
9945 // inaccessible one at a time.
9946 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
9947 continue;
9948 HandleDelayedAccessCheck(diag, decl);
9949 if (diag.Triggered)
9950 AnyAccessFailures = true;
9951 break;
9953 case DelayedDiagnostic::ForbiddenType:
9954 handleDelayedForbiddenType(*this, diag, decl);
9955 break;
9958 } while ((pool = pool->getParent()));
9961 /// Given a set of delayed diagnostics, re-emit them as if they had
9962 /// been delayed in the current context instead of in the given pool.
9963 /// Essentially, this just moves them to the current pool.
9964 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
9965 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
9966 assert(curPool && "re-emitting in undelayed context not supported");
9967 curPool->steal(pool);