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