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