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