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