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