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