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