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