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