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 handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1996   if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
1997     return;
1998 
1999   if (AL.isDeclspecAttribute()) {
2000     const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2001     const auto &Arch = Triple.getArch();
2002     if (Arch != llvm::Triple::x86 &&
2003         (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2004       S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2005           << AL << Triple.getArchName();
2006       return;
2007     }
2008   }
2009 
2010   D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2011 }
2012 
2013 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2014   if (hasDeclarator(D)) return;
2015 
2016   if (!isa<ObjCMethodDecl>(D)) {
2017     S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2018         << Attrs << ExpectedFunctionOrMethod;
2019     return;
2020   }
2021 
2022   D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2023 }
2024 
2025 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2026   if (!S.getLangOpts().CFProtectionBranch)
2027     S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2028   else
2029     handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2030 }
2031 
2032 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2033   if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2034     Attrs.setInvalid();
2035     return true;
2036   }
2037 
2038   return false;
2039 }
2040 
2041 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2042   // Check whether the attribute is valid on the current target.
2043   if (!AL.existsInTarget(Context.getTargetInfo())) {
2044     Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2045     AL.setInvalid();
2046     return true;
2047   }
2048 
2049   return false;
2050 }
2051 
2052 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2053 
2054   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2055   // because 'analyzer_noreturn' does not impact the type.
2056   if (!isFunctionOrMethodOrBlock(D)) {
2057     ValueDecl *VD = dyn_cast<ValueDecl>(D);
2058     if (!VD || (!VD->getType()->isBlockPointerType() &&
2059                 !VD->getType()->isFunctionPointerType())) {
2060       S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2061                               ? diag::err_attribute_wrong_decl_type
2062                               : diag::warn_attribute_wrong_decl_type)
2063           << AL << ExpectedFunctionMethodOrBlock;
2064       return;
2065     }
2066   }
2067 
2068   D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2069 }
2070 
2071 // PS3 PPU-specific.
2072 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2073   /*
2074     Returning a Vector Class in Registers
2075 
2076     According to the PPU ABI specifications, a class with a single member of
2077     vector type is returned in memory when used as the return value of a
2078     function.
2079     This results in inefficient code when implementing vector classes. To return
2080     the value in a single vector register, add the vecreturn attribute to the
2081     class definition. This attribute is also applicable to struct types.
2082 
2083     Example:
2084 
2085     struct Vector
2086     {
2087       __vector float xyzw;
2088     } __attribute__((vecreturn));
2089 
2090     Vector Add(Vector lhs, Vector rhs)
2091     {
2092       Vector result;
2093       result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2094       return result; // This will be returned in a register
2095     }
2096   */
2097   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2098     S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2099     return;
2100   }
2101 
2102   const auto *R = cast<RecordDecl>(D);
2103   int count = 0;
2104 
2105   if (!isa<CXXRecordDecl>(R)) {
2106     S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2107     return;
2108   }
2109 
2110   if (!cast<CXXRecordDecl>(R)->isPOD()) {
2111     S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2112     return;
2113   }
2114 
2115   for (const auto *I : R->fields()) {
2116     if ((count == 1) || !I->getType()->isVectorType()) {
2117       S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2118       return;
2119     }
2120     count++;
2121   }
2122 
2123   D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2124 }
2125 
2126 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2127                                  const ParsedAttr &AL) {
2128   if (isa<ParmVarDecl>(D)) {
2129     // [[carries_dependency]] can only be applied to a parameter if it is a
2130     // parameter of a function declaration or lambda.
2131     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2132       S.Diag(AL.getLoc(),
2133              diag::err_carries_dependency_param_not_function_decl);
2134       return;
2135     }
2136   }
2137 
2138   D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2139 }
2140 
2141 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2142   bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2143 
2144   // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2145   // about using it as an extension.
2146   if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2147     S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2148 
2149   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2150 }
2151 
2152 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2153   uint32_t priority = ConstructorAttr::DefaultPriority;
2154   if (AL.getNumArgs() &&
2155       !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2156     return;
2157 
2158   D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2159 }
2160 
2161 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2162   uint32_t priority = DestructorAttr::DefaultPriority;
2163   if (AL.getNumArgs() &&
2164       !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2165     return;
2166 
2167   D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2168 }
2169 
2170 template <typename AttrTy>
2171 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2172   // Handle the case where the attribute has a text message.
2173   StringRef Str;
2174   if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2175     return;
2176 
2177   D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2178 }
2179 
2180 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2181                                           const ParsedAttr &AL) {
2182   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2183     S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2184         << AL << AL.getRange();
2185     return;
2186   }
2187 
2188   D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2189 }
2190 
2191 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2192                                   IdentifierInfo *Platform,
2193                                   VersionTuple Introduced,
2194                                   VersionTuple Deprecated,
2195                                   VersionTuple Obsoleted) {
2196   StringRef PlatformName
2197     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2198   if (PlatformName.empty())
2199     PlatformName = Platform->getName();
2200 
2201   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2202   // of these steps are needed).
2203   if (!Introduced.empty() && !Deprecated.empty() &&
2204       !(Introduced <= Deprecated)) {
2205     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2206       << 1 << PlatformName << Deprecated.getAsString()
2207       << 0 << Introduced.getAsString();
2208     return true;
2209   }
2210 
2211   if (!Introduced.empty() && !Obsoleted.empty() &&
2212       !(Introduced <= Obsoleted)) {
2213     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2214       << 2 << PlatformName << Obsoleted.getAsString()
2215       << 0 << Introduced.getAsString();
2216     return true;
2217   }
2218 
2219   if (!Deprecated.empty() && !Obsoleted.empty() &&
2220       !(Deprecated <= Obsoleted)) {
2221     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2222       << 2 << PlatformName << Obsoleted.getAsString()
2223       << 1 << Deprecated.getAsString();
2224     return true;
2225   }
2226 
2227   return false;
2228 }
2229 
2230 /// Check whether the two versions match.
2231 ///
2232 /// If either version tuple is empty, then they are assumed to match. If
2233 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2234 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2235                           bool BeforeIsOkay) {
2236   if (X.empty() || Y.empty())
2237     return true;
2238 
2239   if (X == Y)
2240     return true;
2241 
2242   if (BeforeIsOkay && X < Y)
2243     return true;
2244 
2245   return false;
2246 }
2247 
2248 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2249     NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2250     bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2251     VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2252     bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2253     int Priority) {
2254   VersionTuple MergedIntroduced = Introduced;
2255   VersionTuple MergedDeprecated = Deprecated;
2256   VersionTuple MergedObsoleted = Obsoleted;
2257   bool FoundAny = false;
2258   bool OverrideOrImpl = false;
2259   switch (AMK) {
2260   case AMK_None:
2261   case AMK_Redeclaration:
2262     OverrideOrImpl = false;
2263     break;
2264 
2265   case AMK_Override:
2266   case AMK_ProtocolImplementation:
2267     OverrideOrImpl = true;
2268     break;
2269   }
2270 
2271   if (D->hasAttrs()) {
2272     AttrVec &Attrs = D->getAttrs();
2273     for (unsigned i = 0, e = Attrs.size(); i != e;) {
2274       const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2275       if (!OldAA) {
2276         ++i;
2277         continue;
2278       }
2279 
2280       IdentifierInfo *OldPlatform = OldAA->getPlatform();
2281       if (OldPlatform != Platform) {
2282         ++i;
2283         continue;
2284       }
2285 
2286       // If there is an existing availability attribute for this platform that
2287       // has a lower priority use the existing one and discard the new
2288       // attribute.
2289       if (OldAA->getPriority() < Priority)
2290         return nullptr;
2291 
2292       // If there is an existing attribute for this platform that has a higher
2293       // priority than the new attribute then erase the old one and continue
2294       // processing the attributes.
2295       if (OldAA->getPriority() > Priority) {
2296         Attrs.erase(Attrs.begin() + i);
2297         --e;
2298         continue;
2299       }
2300 
2301       FoundAny = true;
2302       VersionTuple OldIntroduced = OldAA->getIntroduced();
2303       VersionTuple OldDeprecated = OldAA->getDeprecated();
2304       VersionTuple OldObsoleted = OldAA->getObsoleted();
2305       bool OldIsUnavailable = OldAA->getUnavailable();
2306 
2307       if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2308           !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2309           !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2310           !(OldIsUnavailable == IsUnavailable ||
2311             (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2312         if (OverrideOrImpl) {
2313           int Which = -1;
2314           VersionTuple FirstVersion;
2315           VersionTuple SecondVersion;
2316           if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2317             Which = 0;
2318             FirstVersion = OldIntroduced;
2319             SecondVersion = Introduced;
2320           } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2321             Which = 1;
2322             FirstVersion = Deprecated;
2323             SecondVersion = OldDeprecated;
2324           } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2325             Which = 2;
2326             FirstVersion = Obsoleted;
2327             SecondVersion = OldObsoleted;
2328           }
2329 
2330           if (Which == -1) {
2331             Diag(OldAA->getLocation(),
2332                  diag::warn_mismatched_availability_override_unavail)
2333               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2334               << (AMK == AMK_Override);
2335           } else {
2336             Diag(OldAA->getLocation(),
2337                  diag::warn_mismatched_availability_override)
2338               << Which
2339               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2340               << FirstVersion.getAsString() << SecondVersion.getAsString()
2341               << (AMK == AMK_Override);
2342           }
2343           if (AMK == AMK_Override)
2344             Diag(CI.getLoc(), diag::note_overridden_method);
2345           else
2346             Diag(CI.getLoc(), diag::note_protocol_method);
2347         } else {
2348           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2349           Diag(CI.getLoc(), diag::note_previous_attribute);
2350         }
2351 
2352         Attrs.erase(Attrs.begin() + i);
2353         --e;
2354         continue;
2355       }
2356 
2357       VersionTuple MergedIntroduced2 = MergedIntroduced;
2358       VersionTuple MergedDeprecated2 = MergedDeprecated;
2359       VersionTuple MergedObsoleted2 = MergedObsoleted;
2360 
2361       if (MergedIntroduced2.empty())
2362         MergedIntroduced2 = OldIntroduced;
2363       if (MergedDeprecated2.empty())
2364         MergedDeprecated2 = OldDeprecated;
2365       if (MergedObsoleted2.empty())
2366         MergedObsoleted2 = OldObsoleted;
2367 
2368       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2369                                 MergedIntroduced2, MergedDeprecated2,
2370                                 MergedObsoleted2)) {
2371         Attrs.erase(Attrs.begin() + i);
2372         --e;
2373         continue;
2374       }
2375 
2376       MergedIntroduced = MergedIntroduced2;
2377       MergedDeprecated = MergedDeprecated2;
2378       MergedObsoleted = MergedObsoleted2;
2379       ++i;
2380     }
2381   }
2382 
2383   if (FoundAny &&
2384       MergedIntroduced == Introduced &&
2385       MergedDeprecated == Deprecated &&
2386       MergedObsoleted == Obsoleted)
2387     return nullptr;
2388 
2389   // Only create a new attribute if !OverrideOrImpl, but we want to do
2390   // the checking.
2391   if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2392                              MergedDeprecated, MergedObsoleted) &&
2393       !OverrideOrImpl) {
2394     auto *Avail = ::new (Context) AvailabilityAttr(
2395         Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2396         Message, IsStrict, Replacement, Priority);
2397     Avail->setImplicit(Implicit);
2398     return Avail;
2399   }
2400   return nullptr;
2401 }
2402 
2403 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2404   if (!checkAttributeNumArgs(S, AL, 1))
2405     return;
2406   IdentifierLoc *Platform = AL.getArgAsIdent(0);
2407 
2408   IdentifierInfo *II = Platform->Ident;
2409   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2410     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2411       << Platform->Ident;
2412 
2413   auto *ND = dyn_cast<NamedDecl>(D);
2414   if (!ND) // We warned about this already, so just return.
2415     return;
2416 
2417   AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2418   AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2419   AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2420   bool IsUnavailable = AL.getUnavailableLoc().isValid();
2421   bool IsStrict = AL.getStrictLoc().isValid();
2422   StringRef Str;
2423   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2424     Str = SE->getString();
2425   StringRef Replacement;
2426   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2427     Replacement = SE->getString();
2428 
2429   if (II->isStr("swift")) {
2430     if (Introduced.isValid() || Obsoleted.isValid() ||
2431         (!IsUnavailable && !Deprecated.isValid())) {
2432       S.Diag(AL.getLoc(),
2433              diag::warn_availability_swift_unavailable_deprecated_only);
2434       return;
2435     }
2436   }
2437 
2438   int PriorityModifier = AL.isPragmaClangAttribute()
2439                              ? Sema::AP_PragmaClangAttribute
2440                              : Sema::AP_Explicit;
2441   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2442       ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2443       Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2444       Sema::AMK_None, PriorityModifier);
2445   if (NewAttr)
2446     D->addAttr(NewAttr);
2447 
2448   // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2449   // matches before the start of the watchOS platform.
2450   if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2451     IdentifierInfo *NewII = nullptr;
2452     if (II->getName() == "ios")
2453       NewII = &S.Context.Idents.get("watchos");
2454     else if (II->getName() == "ios_app_extension")
2455       NewII = &S.Context.Idents.get("watchos_app_extension");
2456 
2457     if (NewII) {
2458         auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2459           if (Version.empty())
2460             return Version;
2461           auto Major = Version.getMajor();
2462           auto NewMajor = Major >= 9 ? Major - 7 : 0;
2463           if (NewMajor >= 2) {
2464             if (Version.getMinor().hasValue()) {
2465               if (Version.getSubminor().hasValue())
2466                 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2467                                     Version.getSubminor().getValue());
2468               else
2469                 return VersionTuple(NewMajor, Version.getMinor().getValue());
2470             }
2471             return VersionTuple(NewMajor);
2472           }
2473 
2474           return VersionTuple(2, 0);
2475         };
2476 
2477         auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2478         auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2479         auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2480 
2481         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2482             ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2483             NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2484             Sema::AMK_None,
2485             PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2486         if (NewAttr)
2487           D->addAttr(NewAttr);
2488       }
2489   } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2490     // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2491     // matches before the start of the tvOS platform.
2492     IdentifierInfo *NewII = nullptr;
2493     if (II->getName() == "ios")
2494       NewII = &S.Context.Idents.get("tvos");
2495     else if (II->getName() == "ios_app_extension")
2496       NewII = &S.Context.Idents.get("tvos_app_extension");
2497 
2498     if (NewII) {
2499       AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2500           ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2501           Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2502           Replacement, Sema::AMK_None,
2503           PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2504       if (NewAttr)
2505         D->addAttr(NewAttr);
2506       }
2507   }
2508 }
2509 
2510 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2511                                            const ParsedAttr &AL) {
2512   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2513     return;
2514   assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2515          "Invalid number of arguments in an external_source_symbol attribute");
2516 
2517   StringRef Language;
2518   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2519     Language = SE->getString();
2520   StringRef DefinedIn;
2521   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2522     DefinedIn = SE->getString();
2523   bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2524 
2525   D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2526       S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2527 }
2528 
2529 template <class T>
2530 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2531                               typename T::VisibilityType value) {
2532   T *existingAttr = D->getAttr<T>();
2533   if (existingAttr) {
2534     typename T::VisibilityType existingValue = existingAttr->getVisibility();
2535     if (existingValue == value)
2536       return nullptr;
2537     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2538     S.Diag(CI.getLoc(), diag::note_previous_attribute);
2539     D->dropAttr<T>();
2540   }
2541   return ::new (S.Context) T(S.Context, CI, value);
2542 }
2543 
2544 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2545                                           const AttributeCommonInfo &CI,
2546                                           VisibilityAttr::VisibilityType Vis) {
2547   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2548 }
2549 
2550 TypeVisibilityAttr *
2551 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2552                               TypeVisibilityAttr::VisibilityType Vis) {
2553   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2554 }
2555 
2556 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2557                                  bool isTypeVisibility) {
2558   // Visibility attributes don't mean anything on a typedef.
2559   if (isa<TypedefNameDecl>(D)) {
2560     S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2561     return;
2562   }
2563 
2564   // 'type_visibility' can only go on a type or namespace.
2565   if (isTypeVisibility &&
2566       !(isa<TagDecl>(D) ||
2567         isa<ObjCInterfaceDecl>(D) ||
2568         isa<NamespaceDecl>(D))) {
2569     S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2570         << AL << ExpectedTypeOrNamespace;
2571     return;
2572   }
2573 
2574   // Check that the argument is a string literal.
2575   StringRef TypeStr;
2576   SourceLocation LiteralLoc;
2577   if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2578     return;
2579 
2580   VisibilityAttr::VisibilityType type;
2581   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2582     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2583                                                                 << TypeStr;
2584     return;
2585   }
2586 
2587   // Complain about attempts to use protected visibility on targets
2588   // (like Darwin) that don't support it.
2589   if (type == VisibilityAttr::Protected &&
2590       !S.Context.getTargetInfo().hasProtectedVisibility()) {
2591     S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2592     type = VisibilityAttr::Default;
2593   }
2594 
2595   Attr *newAttr;
2596   if (isTypeVisibility) {
2597     newAttr = S.mergeTypeVisibilityAttr(
2598         D, AL, (TypeVisibilityAttr::VisibilityType)type);
2599   } else {
2600     newAttr = S.mergeVisibilityAttr(D, AL, type);
2601   }
2602   if (newAttr)
2603     D->addAttr(newAttr);
2604 }
2605 
2606 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2607   // objc_direct cannot be set on methods declared in the context of a protocol
2608   if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2609     S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2610     return;
2611   }
2612 
2613   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2614     handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2615   } else {
2616     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2617   }
2618 }
2619 
2620 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2621                                         const ParsedAttr &AL) {
2622   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2623     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2624   } else {
2625     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2626   }
2627 }
2628 
2629 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2630   const auto *M = cast<ObjCMethodDecl>(D);
2631   if (!AL.isArgIdent(0)) {
2632     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2633         << AL << 1 << AANT_ArgumentIdentifier;
2634     return;
2635   }
2636 
2637   IdentifierLoc *IL = AL.getArgAsIdent(0);
2638   ObjCMethodFamilyAttr::FamilyKind F;
2639   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2640     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2641     return;
2642   }
2643 
2644   if (F == ObjCMethodFamilyAttr::OMF_init &&
2645       !M->getReturnType()->isObjCObjectPointerType()) {
2646     S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2647         << M->getReturnType();
2648     // Ignore the attribute.
2649     return;
2650   }
2651 
2652   D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2653 }
2654 
2655 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2656   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2657     QualType T = TD->getUnderlyingType();
2658     if (!T->isCARCBridgableType()) {
2659       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2660       return;
2661     }
2662   }
2663   else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2664     QualType T = PD->getType();
2665     if (!T->isCARCBridgableType()) {
2666       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2667       return;
2668     }
2669   }
2670   else {
2671     // It is okay to include this attribute on properties, e.g.:
2672     //
2673     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2674     //
2675     // In this case it follows tradition and suppresses an error in the above
2676     // case.
2677     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2678   }
2679   D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2680 }
2681 
2682 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2683   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2684     QualType T = TD->getUnderlyingType();
2685     if (!T->isObjCObjectPointerType()) {
2686       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2687       return;
2688     }
2689   } else {
2690     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2691     return;
2692   }
2693   D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2694 }
2695 
2696 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2697   if (!AL.isArgIdent(0)) {
2698     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2699         << AL << 1 << AANT_ArgumentIdentifier;
2700     return;
2701   }
2702 
2703   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2704   BlocksAttr::BlockType type;
2705   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2706     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2707     return;
2708   }
2709 
2710   D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2711 }
2712 
2713 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2714   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2715   if (AL.getNumArgs() > 0) {
2716     Expr *E = AL.getArgAsExpr(0);
2717     llvm::APSInt Idx(32);
2718     if (E->isTypeDependent() || E->isValueDependent() ||
2719         !E->isIntegerConstantExpr(Idx, S.Context)) {
2720       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2721           << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2722       return;
2723     }
2724 
2725     if (Idx.isSigned() && Idx.isNegative()) {
2726       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2727         << E->getSourceRange();
2728       return;
2729     }
2730 
2731     sentinel = Idx.getZExtValue();
2732   }
2733 
2734   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2735   if (AL.getNumArgs() > 1) {
2736     Expr *E = AL.getArgAsExpr(1);
2737     llvm::APSInt Idx(32);
2738     if (E->isTypeDependent() || E->isValueDependent() ||
2739         !E->isIntegerConstantExpr(Idx, S.Context)) {
2740       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2741           << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2742       return;
2743     }
2744     nullPos = Idx.getZExtValue();
2745 
2746     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2747       // FIXME: This error message could be improved, it would be nice
2748       // to say what the bounds actually are.
2749       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2750         << E->getSourceRange();
2751       return;
2752     }
2753   }
2754 
2755   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2756     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2757     if (isa<FunctionNoProtoType>(FT)) {
2758       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2759       return;
2760     }
2761 
2762     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2763       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2764       return;
2765     }
2766   } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2767     if (!MD->isVariadic()) {
2768       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2769       return;
2770     }
2771   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2772     if (!BD->isVariadic()) {
2773       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2774       return;
2775     }
2776   } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2777     QualType Ty = V->getType();
2778     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2779       const FunctionType *FT = Ty->isFunctionPointerType()
2780        ? D->getFunctionType()
2781        : Ty->castAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2782       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2783         int m = Ty->isFunctionPointerType() ? 0 : 1;
2784         S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2785         return;
2786       }
2787     } else {
2788       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2789           << AL << ExpectedFunctionMethodOrBlock;
2790       return;
2791     }
2792   } else {
2793     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2794         << AL << ExpectedFunctionMethodOrBlock;
2795     return;
2796   }
2797   D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2798 }
2799 
2800 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2801   if (D->getFunctionType() &&
2802       D->getFunctionType()->getReturnType()->isVoidType() &&
2803       !isa<CXXConstructorDecl>(D)) {
2804     S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2805     return;
2806   }
2807   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2808     if (MD->getReturnType()->isVoidType()) {
2809       S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2810       return;
2811     }
2812 
2813   StringRef Str;
2814   if ((AL.isCXX11Attribute() || AL.isC2xAttribute()) && !AL.getScopeName()) {
2815     // If this is spelled as the standard C++17 attribute, but not in C++17,
2816     // warn about using it as an extension. If there are attribute arguments,
2817     // then claim it's a C++2a extension instead.
2818     // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2819     // extension warning for C2x mode.
2820     const LangOptions &LO = S.getLangOpts();
2821     if (AL.getNumArgs() == 1) {
2822       if (LO.CPlusPlus && !LO.CPlusPlus2a)
2823         S.Diag(AL.getLoc(), diag::ext_cxx2a_attr) << AL;
2824 
2825       // Since this this is spelled [[nodiscard]], get the optional string
2826       // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2827       // extension.
2828       // FIXME: C2x should support this feature as well, even as an extension.
2829       if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2830         return;
2831     } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2832       S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2833   }
2834 
2835   D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2836 }
2837 
2838 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2839   // weak_import only applies to variable & function declarations.
2840   bool isDef = false;
2841   if (!D->canBeWeakImported(isDef)) {
2842     if (isDef)
2843       S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2844         << "weak_import";
2845     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2846              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2847               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2848       // Nothing to warn about here.
2849     } else
2850       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2851           << AL << ExpectedVariableOrFunction;
2852 
2853     return;
2854   }
2855 
2856   D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2857 }
2858 
2859 // Handles reqd_work_group_size and work_group_size_hint.
2860 template <typename WorkGroupAttr>
2861 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2862   uint32_t WGSize[3];
2863   for (unsigned i = 0; i < 3; ++i) {
2864     const Expr *E = AL.getArgAsExpr(i);
2865     if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2866                              /*StrictlyUnsigned=*/true))
2867       return;
2868     if (WGSize[i] == 0) {
2869       S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2870           << AL << E->getSourceRange();
2871       return;
2872     }
2873   }
2874 
2875   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2876   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2877                     Existing->getYDim() == WGSize[1] &&
2878                     Existing->getZDim() == WGSize[2]))
2879     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2880 
2881   D->addAttr(::new (S.Context)
2882                  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2883 }
2884 
2885 // Handles intel_reqd_sub_group_size.
2886 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2887   uint32_t SGSize;
2888   const Expr *E = AL.getArgAsExpr(0);
2889   if (!checkUInt32Argument(S, AL, E, SGSize))
2890     return;
2891   if (SGSize == 0) {
2892     S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2893         << AL << E->getSourceRange();
2894     return;
2895   }
2896 
2897   OpenCLIntelReqdSubGroupSizeAttr *Existing =
2898       D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2899   if (Existing && Existing->getSubGroupSize() != SGSize)
2900     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2901 
2902   D->addAttr(::new (S.Context)
2903                  OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
2904 }
2905 
2906 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2907   if (!AL.hasParsedType()) {
2908     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2909     return;
2910   }
2911 
2912   TypeSourceInfo *ParmTSI = nullptr;
2913   QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2914   assert(ParmTSI && "no type source info for attribute argument");
2915 
2916   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2917       (ParmType->isBooleanType() ||
2918        !ParmType->isIntegralType(S.getASTContext()))) {
2919     S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
2920     return;
2921   }
2922 
2923   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2924     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2925       S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2926       return;
2927     }
2928   }
2929 
2930   D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
2931 }
2932 
2933 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2934                                     StringRef Name) {
2935   // Explicit or partial specializations do not inherit
2936   // the section attribute from the primary template.
2937   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2938     if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
2939         FD->isFunctionTemplateSpecialization())
2940       return nullptr;
2941   }
2942   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2943     if (ExistingAttr->getName() == Name)
2944       return nullptr;
2945     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2946          << 1 /*section*/;
2947     Diag(CI.getLoc(), diag::note_previous_attribute);
2948     return nullptr;
2949   }
2950   return ::new (Context) SectionAttr(Context, CI, Name);
2951 }
2952 
2953 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2954   std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2955   if (!Error.empty()) {
2956     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2957          << 1 /*'section'*/;
2958     return false;
2959   }
2960   return true;
2961 }
2962 
2963 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2964   // Make sure that there is a string literal as the sections's single
2965   // argument.
2966   StringRef Str;
2967   SourceLocation LiteralLoc;
2968   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2969     return;
2970 
2971   if (!S.checkSectionName(LiteralLoc, Str))
2972     return;
2973 
2974   // If the target wants to validate the section specifier, make it happen.
2975   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2976   if (!Error.empty()) {
2977     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2978     << Error;
2979     return;
2980   }
2981 
2982   SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
2983   if (NewAttr)
2984     D->addAttr(NewAttr);
2985 }
2986 
2987 // This is used for `__declspec(code_seg("segname"))` on a decl.
2988 // `#pragma code_seg("segname")` uses checkSectionName() instead.
2989 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
2990                              StringRef CodeSegName) {
2991   std::string Error =
2992       S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
2993   if (!Error.empty()) {
2994     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2995         << Error << 0 /*'code-seg'*/;
2996     return false;
2997   }
2998 
2999   return true;
3000 }
3001 
3002 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3003                                     StringRef Name) {
3004   // Explicit or partial specializations do not inherit
3005   // the code_seg attribute from the primary template.
3006   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3007     if (FD->isFunctionTemplateSpecialization())
3008       return nullptr;
3009   }
3010   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3011     if (ExistingAttr->getName() == Name)
3012       return nullptr;
3013     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3014          << 0 /*codeseg*/;
3015     Diag(CI.getLoc(), diag::note_previous_attribute);
3016     return nullptr;
3017   }
3018   return ::new (Context) CodeSegAttr(Context, CI, Name);
3019 }
3020 
3021 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3022   StringRef Str;
3023   SourceLocation LiteralLoc;
3024   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3025     return;
3026   if (!checkCodeSegName(S, LiteralLoc, Str))
3027     return;
3028   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3029     if (!ExistingAttr->isImplicit()) {
3030       S.Diag(AL.getLoc(),
3031              ExistingAttr->getName() == Str
3032              ? diag::warn_duplicate_codeseg_attribute
3033              : diag::err_conflicting_codeseg_attribute);
3034       return;
3035     }
3036     D->dropAttr<CodeSegAttr>();
3037   }
3038   if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3039     D->addAttr(CSA);
3040 }
3041 
3042 // Check for things we'd like to warn about. Multiversioning issues are
3043 // handled later in the process, once we know how many exist.
3044 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3045   enum FirstParam { Unsupported, Duplicate };
3046   enum SecondParam { None, Architecture };
3047   for (auto Str : {"tune=", "fpmath="})
3048     if (AttrStr.find(Str) != StringRef::npos)
3049       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3050              << Unsupported << None << Str;
3051 
3052   ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3053 
3054   if (!ParsedAttrs.Architecture.empty() &&
3055       !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3056     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3057            << Unsupported << Architecture << ParsedAttrs.Architecture;
3058 
3059   if (ParsedAttrs.DuplicateArchitecture)
3060     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3061            << Duplicate << None << "arch=";
3062 
3063   for (const auto &Feature : ParsedAttrs.Features) {
3064     auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3065     if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3066       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3067              << Unsupported << None << CurFeature;
3068   }
3069 
3070   TargetInfo::BranchProtectionInfo BPI;
3071   StringRef Error;
3072   if (!ParsedAttrs.BranchProtection.empty() &&
3073       !Context.getTargetInfo().validateBranchProtection(
3074           ParsedAttrs.BranchProtection, BPI, Error)) {
3075     if (Error.empty())
3076       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3077              << Unsupported << None << "branch-protection";
3078     else
3079       return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3080              << Error;
3081   }
3082 
3083   return false;
3084 }
3085 
3086 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3087   StringRef Str;
3088   SourceLocation LiteralLoc;
3089   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3090       S.checkTargetAttr(LiteralLoc, Str))
3091     return;
3092 
3093   TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3094   D->addAttr(NewAttr);
3095 }
3096 
3097 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3098   Expr *E = AL.getArgAsExpr(0);
3099   uint32_t VecWidth;
3100   if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3101     AL.setInvalid();
3102     return;
3103   }
3104 
3105   MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3106   if (Existing && Existing->getVectorWidth() != VecWidth) {
3107     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3108     return;
3109   }
3110 
3111   D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3112 }
3113 
3114 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3115   Expr *E = AL.getArgAsExpr(0);
3116   SourceLocation Loc = E->getExprLoc();
3117   FunctionDecl *FD = nullptr;
3118   DeclarationNameInfo NI;
3119 
3120   // gcc only allows for simple identifiers. Since we support more than gcc, we
3121   // will warn the user.
3122   if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3123     if (DRE->hasQualifier())
3124       S.Diag(Loc, diag::warn_cleanup_ext);
3125     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3126     NI = DRE->getNameInfo();
3127     if (!FD) {
3128       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3129         << NI.getName();
3130       return;
3131     }
3132   } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3133     if (ULE->hasExplicitTemplateArgs())
3134       S.Diag(Loc, diag::warn_cleanup_ext);
3135     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3136     NI = ULE->getNameInfo();
3137     if (!FD) {
3138       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3139         << NI.getName();
3140       if (ULE->getType() == S.Context.OverloadTy)
3141         S.NoteAllOverloadCandidates(ULE);
3142       return;
3143     }
3144   } else {
3145     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3146     return;
3147   }
3148 
3149   if (FD->getNumParams() != 1) {
3150     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3151       << NI.getName();
3152     return;
3153   }
3154 
3155   // We're currently more strict than GCC about what function types we accept.
3156   // If this ever proves to be a problem it should be easy to fix.
3157   QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3158   QualType ParamTy = FD->getParamDecl(0)->getType();
3159   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3160                                    ParamTy, Ty) != Sema::Compatible) {
3161     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3162       << NI.getName() << ParamTy << Ty;
3163     return;
3164   }
3165 
3166   D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3167 }
3168 
3169 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3170                                         const ParsedAttr &AL) {
3171   if (!AL.isArgIdent(0)) {
3172     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3173         << AL << 0 << AANT_ArgumentIdentifier;
3174     return;
3175   }
3176 
3177   EnumExtensibilityAttr::Kind ExtensibilityKind;
3178   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3179   if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3180                                                ExtensibilityKind)) {
3181     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3182     return;
3183   }
3184 
3185   D->addAttr(::new (S.Context)
3186                  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3187 }
3188 
3189 /// Handle __attribute__((format_arg((idx)))) attribute based on
3190 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3191 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3192   Expr *IdxExpr = AL.getArgAsExpr(0);
3193   ParamIdx Idx;
3194   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3195     return;
3196 
3197   // Make sure the format string is really a string.
3198   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3199 
3200   bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3201   if (NotNSStringTy &&
3202       !isCFStringType(Ty, S.Context) &&
3203       (!Ty->isPointerType() ||
3204        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3205     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3206         << "a string type" << IdxExpr->getSourceRange()
3207         << getFunctionOrMethodParamRange(D, 0);
3208     return;
3209   }
3210   Ty = getFunctionOrMethodResultType(D);
3211   if (!isNSStringType(Ty, S.Context) &&
3212       !isCFStringType(Ty, S.Context) &&
3213       (!Ty->isPointerType() ||
3214        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3215     S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3216         << (NotNSStringTy ? "string type" : "NSString")
3217         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3218     return;
3219   }
3220 
3221   D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3222 }
3223 
3224 enum FormatAttrKind {
3225   CFStringFormat,
3226   NSStringFormat,
3227   StrftimeFormat,
3228   SupportedFormat,
3229   IgnoredFormat,
3230   InvalidFormat
3231 };
3232 
3233 /// getFormatAttrKind - Map from format attribute names to supported format
3234 /// types.
3235 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3236   return llvm::StringSwitch<FormatAttrKind>(Format)
3237       // Check for formats that get handled specially.
3238       .Case("NSString", NSStringFormat)
3239       .Case("CFString", CFStringFormat)
3240       .Case("strftime", StrftimeFormat)
3241 
3242       // Otherwise, check for supported formats.
3243       .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3244       .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3245       .Case("kprintf", SupportedFormat)         // OpenBSD.
3246       .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3247       .Case("os_trace", SupportedFormat)
3248       .Case("os_log", SupportedFormat)
3249 
3250       .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3251       .Default(InvalidFormat);
3252 }
3253 
3254 /// Handle __attribute__((init_priority(priority))) attributes based on
3255 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3256 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3257   if (!S.getLangOpts().CPlusPlus) {
3258     S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3259     return;
3260   }
3261 
3262   if (S.getCurFunctionOrMethodDecl()) {
3263     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3264     AL.setInvalid();
3265     return;
3266   }
3267   QualType T = cast<VarDecl>(D)->getType();
3268   if (S.Context.getAsArrayType(T))
3269     T = S.Context.getBaseElementType(T);
3270   if (!T->getAs<RecordType>()) {
3271     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3272     AL.setInvalid();
3273     return;
3274   }
3275 
3276   Expr *E = AL.getArgAsExpr(0);
3277   uint32_t prioritynum;
3278   if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3279     AL.setInvalid();
3280     return;
3281   }
3282 
3283   if (prioritynum < 101 || prioritynum > 65535) {
3284     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3285         << E->getSourceRange() << AL << 101 << 65535;
3286     AL.setInvalid();
3287     return;
3288   }
3289   D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3290 }
3291 
3292 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3293                                   IdentifierInfo *Format, int FormatIdx,
3294                                   int FirstArg) {
3295   // Check whether we already have an equivalent format attribute.
3296   for (auto *F : D->specific_attrs<FormatAttr>()) {
3297     if (F->getType() == Format &&
3298         F->getFormatIdx() == FormatIdx &&
3299         F->getFirstArg() == FirstArg) {
3300       // If we don't have a valid location for this attribute, adopt the
3301       // location.
3302       if (F->getLocation().isInvalid())
3303         F->setRange(CI.getRange());
3304       return nullptr;
3305     }
3306   }
3307 
3308   return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3309 }
3310 
3311 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3312 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3313 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3314   if (!AL.isArgIdent(0)) {
3315     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3316         << AL << 1 << AANT_ArgumentIdentifier;
3317     return;
3318   }
3319 
3320   // In C++ the implicit 'this' function parameter also counts, and they are
3321   // counted from one.
3322   bool HasImplicitThisParam = isInstanceMethod(D);
3323   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3324 
3325   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3326   StringRef Format = II->getName();
3327 
3328   if (normalizeName(Format)) {
3329     // If we've modified the string name, we need a new identifier for it.
3330     II = &S.Context.Idents.get(Format);
3331   }
3332 
3333   // Check for supported formats.
3334   FormatAttrKind Kind = getFormatAttrKind(Format);
3335 
3336   if (Kind == IgnoredFormat)
3337     return;
3338 
3339   if (Kind == InvalidFormat) {
3340     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3341         << AL << II->getName();
3342     return;
3343   }
3344 
3345   // checks for the 2nd argument
3346   Expr *IdxExpr = AL.getArgAsExpr(1);
3347   uint32_t Idx;
3348   if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3349     return;
3350 
3351   if (Idx < 1 || Idx > NumArgs) {
3352     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3353         << AL << 2 << IdxExpr->getSourceRange();
3354     return;
3355   }
3356 
3357   // FIXME: Do we need to bounds check?
3358   unsigned ArgIdx = Idx - 1;
3359 
3360   if (HasImplicitThisParam) {
3361     if (ArgIdx == 0) {
3362       S.Diag(AL.getLoc(),
3363              diag::err_format_attribute_implicit_this_format_string)
3364         << IdxExpr->getSourceRange();
3365       return;
3366     }
3367     ArgIdx--;
3368   }
3369 
3370   // make sure the format string is really a string
3371   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3372 
3373   if (Kind == CFStringFormat) {
3374     if (!isCFStringType(Ty, S.Context)) {
3375       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3376         << "a CFString" << IdxExpr->getSourceRange()
3377         << getFunctionOrMethodParamRange(D, ArgIdx);
3378       return;
3379     }
3380   } else if (Kind == NSStringFormat) {
3381     // FIXME: do we need to check if the type is NSString*?  What are the
3382     // semantics?
3383     if (!isNSStringType(Ty, S.Context)) {
3384       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3385         << "an NSString" << IdxExpr->getSourceRange()
3386         << getFunctionOrMethodParamRange(D, ArgIdx);
3387       return;
3388     }
3389   } else if (!Ty->isPointerType() ||
3390              !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3391     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3392       << "a string type" << IdxExpr->getSourceRange()
3393       << getFunctionOrMethodParamRange(D, ArgIdx);
3394     return;
3395   }
3396 
3397   // check the 3rd argument
3398   Expr *FirstArgExpr = AL.getArgAsExpr(2);
3399   uint32_t FirstArg;
3400   if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3401     return;
3402 
3403   // check if the function is variadic if the 3rd argument non-zero
3404   if (FirstArg != 0) {
3405     if (isFunctionOrMethodVariadic(D)) {
3406       ++NumArgs; // +1 for ...
3407     } else {
3408       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3409       return;
3410     }
3411   }
3412 
3413   // strftime requires FirstArg to be 0 because it doesn't read from any
3414   // variable the input is just the current time + the format string.
3415   if (Kind == StrftimeFormat) {
3416     if (FirstArg != 0) {
3417       S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3418         << FirstArgExpr->getSourceRange();
3419       return;
3420     }
3421   // if 0 it disables parameter checking (to use with e.g. va_list)
3422   } else if (FirstArg != 0 && FirstArg != NumArgs) {
3423     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3424         << AL << 3 << FirstArgExpr->getSourceRange();
3425     return;
3426   }
3427 
3428   FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3429   if (NewAttr)
3430     D->addAttr(NewAttr);
3431 }
3432 
3433 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3434 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3435   // The index that identifies the callback callee is mandatory.
3436   if (AL.getNumArgs() == 0) {
3437     S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3438         << AL.getRange();
3439     return;
3440   }
3441 
3442   bool HasImplicitThisParam = isInstanceMethod(D);
3443   int32_t NumArgs = getFunctionOrMethodNumParams(D);
3444 
3445   FunctionDecl *FD = D->getAsFunction();
3446   assert(FD && "Expected a function declaration!");
3447 
3448   llvm::StringMap<int> NameIdxMapping;
3449   NameIdxMapping["__"] = -1;
3450 
3451   NameIdxMapping["this"] = 0;
3452 
3453   int Idx = 1;
3454   for (const ParmVarDecl *PVD : FD->parameters())
3455     NameIdxMapping[PVD->getName()] = Idx++;
3456 
3457   auto UnknownName = NameIdxMapping.end();
3458 
3459   SmallVector<int, 8> EncodingIndices;
3460   for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3461     SourceRange SR;
3462     int32_t ArgIdx;
3463 
3464     if (AL.isArgIdent(I)) {
3465       IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3466       auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3467       if (It == UnknownName) {
3468         S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3469             << IdLoc->Ident << IdLoc->Loc;
3470         return;
3471       }
3472 
3473       SR = SourceRange(IdLoc->Loc);
3474       ArgIdx = It->second;
3475     } else if (AL.isArgExpr(I)) {
3476       Expr *IdxExpr = AL.getArgAsExpr(I);
3477 
3478       // If the expression is not parseable as an int32_t we have a problem.
3479       if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3480                                false)) {
3481         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3482             << AL << (I + 1) << IdxExpr->getSourceRange();
3483         return;
3484       }
3485 
3486       // Check oob, excluding the special values, 0 and -1.
3487       if (ArgIdx < -1 || ArgIdx > NumArgs) {
3488         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3489             << AL << (I + 1) << IdxExpr->getSourceRange();
3490         return;
3491       }
3492 
3493       SR = IdxExpr->getSourceRange();
3494     } else {
3495       llvm_unreachable("Unexpected ParsedAttr argument type!");
3496     }
3497 
3498     if (ArgIdx == 0 && !HasImplicitThisParam) {
3499       S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3500           << (I + 1) << SR;
3501       return;
3502     }
3503 
3504     // Adjust for the case we do not have an implicit "this" parameter. In this
3505     // case we decrease all positive values by 1 to get LLVM argument indices.
3506     if (!HasImplicitThisParam && ArgIdx > 0)
3507       ArgIdx -= 1;
3508 
3509     EncodingIndices.push_back(ArgIdx);
3510   }
3511 
3512   int CalleeIdx = EncodingIndices.front();
3513   // Check if the callee index is proper, thus not "this" and not "unknown".
3514   // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3515   // is false and positive if "HasImplicitThisParam" is true.
3516   if (CalleeIdx < (int)HasImplicitThisParam) {
3517     S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3518         << AL.getRange();
3519     return;
3520   }
3521 
3522   // Get the callee type, note the index adjustment as the AST doesn't contain
3523   // the this type (which the callee cannot reference anyway!).
3524   const Type *CalleeType =
3525       getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3526           .getTypePtr();
3527   if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3528     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3529         << AL.getRange();
3530     return;
3531   }
3532 
3533   const Type *CalleeFnType =
3534       CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3535 
3536   // TODO: Check the type of the callee arguments.
3537 
3538   const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3539   if (!CalleeFnProtoType) {
3540     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3541         << AL.getRange();
3542     return;
3543   }
3544 
3545   if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3546     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3547         << AL << (unsigned)(EncodingIndices.size() - 1);
3548     return;
3549   }
3550 
3551   if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3552     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3553         << AL << (unsigned)(EncodingIndices.size() - 1);
3554     return;
3555   }
3556 
3557   if (CalleeFnProtoType->isVariadic()) {
3558     S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3559     return;
3560   }
3561 
3562   // Do not allow multiple callback attributes.
3563   if (D->hasAttr<CallbackAttr>()) {
3564     S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3565     return;
3566   }
3567 
3568   D->addAttr(::new (S.Context) CallbackAttr(
3569       S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3570 }
3571 
3572 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3573   // Try to find the underlying union declaration.
3574   RecordDecl *RD = nullptr;
3575   const auto *TD = dyn_cast<TypedefNameDecl>(D);
3576   if (TD && TD->getUnderlyingType()->isUnionType())
3577     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3578   else
3579     RD = dyn_cast<RecordDecl>(D);
3580 
3581   if (!RD || !RD->isUnion()) {
3582     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3583                                                               << ExpectedUnion;
3584     return;
3585   }
3586 
3587   if (!RD->isCompleteDefinition()) {
3588     if (!RD->isBeingDefined())
3589       S.Diag(AL.getLoc(),
3590              diag::warn_transparent_union_attribute_not_definition);
3591     return;
3592   }
3593 
3594   RecordDecl::field_iterator Field = RD->field_begin(),
3595                           FieldEnd = RD->field_end();
3596   if (Field == FieldEnd) {
3597     S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3598     return;
3599   }
3600 
3601   FieldDecl *FirstField = *Field;
3602   QualType FirstType = FirstField->getType();
3603   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3604     S.Diag(FirstField->getLocation(),
3605            diag::warn_transparent_union_attribute_floating)
3606       << FirstType->isVectorType() << FirstType;
3607     return;
3608   }
3609 
3610   if (FirstType->isIncompleteType())
3611     return;
3612   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3613   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3614   for (; Field != FieldEnd; ++Field) {
3615     QualType FieldType = Field->getType();
3616     if (FieldType->isIncompleteType())
3617       return;
3618     // FIXME: this isn't fully correct; we also need to test whether the
3619     // members of the union would all have the same calling convention as the
3620     // first member of the union. Checking just the size and alignment isn't
3621     // sufficient (consider structs passed on the stack instead of in registers
3622     // as an example).
3623     if (S.Context.getTypeSize(FieldType) != FirstSize ||
3624         S.Context.getTypeAlign(FieldType) > FirstAlign) {
3625       // Warn if we drop the attribute.
3626       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3627       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3628                                  : S.Context.getTypeAlign(FieldType);
3629       S.Diag(Field->getLocation(),
3630           diag::warn_transparent_union_attribute_field_size_align)
3631         << isSize << Field->getDeclName() << FieldBits;
3632       unsigned FirstBits = isSize? FirstSize : FirstAlign;
3633       S.Diag(FirstField->getLocation(),
3634              diag::note_transparent_union_first_field_size_align)
3635         << isSize << FirstBits;
3636       return;
3637     }
3638   }
3639 
3640   RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3641 }
3642 
3643 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3644   // Make sure that there is a string literal as the annotation's single
3645   // argument.
3646   StringRef Str;
3647   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3648     return;
3649 
3650   // Don't duplicate annotations that are already set.
3651   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3652     if (I->getAnnotation() == Str)
3653       return;
3654   }
3655 
3656   D->addAttr(::new (S.Context) AnnotateAttr(S.Context, AL, Str));
3657 }
3658 
3659 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3660   S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3661 }
3662 
3663 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3664   AlignValueAttr TmpAttr(Context, CI, E);
3665   SourceLocation AttrLoc = CI.getLoc();
3666 
3667   QualType T;
3668   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3669     T = TD->getUnderlyingType();
3670   else if (const auto *VD = dyn_cast<ValueDecl>(D))
3671     T = VD->getType();
3672   else
3673     llvm_unreachable("Unknown decl type for align_value");
3674 
3675   if (!T->isDependentType() && !T->isAnyPointerType() &&
3676       !T->isReferenceType() && !T->isMemberPointerType()) {
3677     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3678       << &TmpAttr << T << D->getSourceRange();
3679     return;
3680   }
3681 
3682   if (!E->isValueDependent()) {
3683     llvm::APSInt Alignment;
3684     ExprResult ICE
3685       = VerifyIntegerConstantExpression(E, &Alignment,
3686           diag::err_align_value_attribute_argument_not_int,
3687             /*AllowFold*/ false);
3688     if (ICE.isInvalid())
3689       return;
3690 
3691     if (!Alignment.isPowerOf2()) {
3692       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3693         << E->getSourceRange();
3694       return;
3695     }
3696 
3697     D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3698     return;
3699   }
3700 
3701   // Save dependent expressions in the AST to be instantiated.
3702   D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3703 }
3704 
3705 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3706   // check the attribute arguments.
3707   if (AL.getNumArgs() > 1) {
3708     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3709     return;
3710   }
3711 
3712   if (AL.getNumArgs() == 0) {
3713     D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3714     return;
3715   }
3716 
3717   Expr *E = AL.getArgAsExpr(0);
3718   if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3719     S.Diag(AL.getEllipsisLoc(),
3720            diag::err_pack_expansion_without_parameter_packs);
3721     return;
3722   }
3723 
3724   if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3725     return;
3726 
3727   S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3728 }
3729 
3730 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3731                           bool IsPackExpansion) {
3732   AlignedAttr TmpAttr(Context, CI, true, E);
3733   SourceLocation AttrLoc = CI.getLoc();
3734 
3735   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3736   if (TmpAttr.isAlignas()) {
3737     // C++11 [dcl.align]p1:
3738     //   An alignment-specifier may be applied to a variable or to a class
3739     //   data member, but it shall not be applied to a bit-field, a function
3740     //   parameter, the formal parameter of a catch clause, or a variable
3741     //   declared with the register storage class specifier. An
3742     //   alignment-specifier may also be applied to the declaration of a class
3743     //   or enumeration type.
3744     // C11 6.7.5/2:
3745     //   An alignment attribute shall not be specified in a declaration of
3746     //   a typedef, or a bit-field, or a function, or a parameter, or an
3747     //   object declared with the register storage-class specifier.
3748     int DiagKind = -1;
3749     if (isa<ParmVarDecl>(D)) {
3750       DiagKind = 0;
3751     } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3752       if (VD->getStorageClass() == SC_Register)
3753         DiagKind = 1;
3754       if (VD->isExceptionVariable())
3755         DiagKind = 2;
3756     } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3757       if (FD->isBitField())
3758         DiagKind = 3;
3759     } else if (!isa<TagDecl>(D)) {
3760       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3761         << (TmpAttr.isC11() ? ExpectedVariableOrField
3762                             : ExpectedVariableFieldOrTag);
3763       return;
3764     }
3765     if (DiagKind != -1) {
3766       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3767         << &TmpAttr << DiagKind;
3768       return;
3769     }
3770   }
3771 
3772   if (E->isValueDependent()) {
3773     // We can't support a dependent alignment on a non-dependent type,
3774     // because we have no way to model that a type is "alignment-dependent"
3775     // but not dependent in any other way.
3776     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3777       if (!TND->getUnderlyingType()->isDependentType()) {
3778         Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3779             << E->getSourceRange();
3780         return;
3781       }
3782     }
3783 
3784     // Save dependent expressions in the AST to be instantiated.
3785     AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
3786     AA->setPackExpansion(IsPackExpansion);
3787     D->addAttr(AA);
3788     return;
3789   }
3790 
3791   // FIXME: Cache the number on the AL object?
3792   llvm::APSInt Alignment;
3793   ExprResult ICE
3794     = VerifyIntegerConstantExpression(E, &Alignment,
3795         diag::err_aligned_attribute_argument_not_int,
3796         /*AllowFold*/ false);
3797   if (ICE.isInvalid())
3798     return;
3799 
3800   uint64_t AlignVal = Alignment.getZExtValue();
3801 
3802   // C++11 [dcl.align]p2:
3803   //   -- if the constant expression evaluates to zero, the alignment
3804   //      specifier shall have no effect
3805   // C11 6.7.5p6:
3806   //   An alignment specification of zero has no effect.
3807   if (!(TmpAttr.isAlignas() && !Alignment)) {
3808     if (!llvm::isPowerOf2_64(AlignVal)) {
3809       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3810         << E->getSourceRange();
3811       return;
3812     }
3813   }
3814 
3815   unsigned MaximumAlignment = Sema::MaximumAlignment;
3816   if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
3817     MaximumAlignment = std::min(MaximumAlignment, 8192u);
3818   if (AlignVal > MaximumAlignment) {
3819     Diag(AttrLoc, diag::err_attribute_aligned_too_great)
3820         << MaximumAlignment << E->getSourceRange();
3821     return;
3822   }
3823 
3824   if (Context.getTargetInfo().isTLSSupported()) {
3825     unsigned MaxTLSAlign =
3826         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3827             .getQuantity();
3828     const auto *VD = dyn_cast<VarDecl>(D);
3829     if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3830         VD->getTLSKind() != VarDecl::TLS_None) {
3831       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3832           << (unsigned)AlignVal << VD << MaxTLSAlign;
3833       return;
3834     }
3835   }
3836 
3837   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
3838   AA->setPackExpansion(IsPackExpansion);
3839   D->addAttr(AA);
3840 }
3841 
3842 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
3843                           TypeSourceInfo *TS, bool IsPackExpansion) {
3844   // FIXME: Cache the number on the AL object if non-dependent?
3845   // FIXME: Perform checking of type validity
3846   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
3847   AA->setPackExpansion(IsPackExpansion);
3848   D->addAttr(AA);
3849 }
3850 
3851 void Sema::CheckAlignasUnderalignment(Decl *D) {
3852   assert(D->hasAttrs() && "no attributes on decl");
3853 
3854   QualType UnderlyingTy, DiagTy;
3855   if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3856     UnderlyingTy = DiagTy = VD->getType();
3857   } else {
3858     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3859     if (const auto *ED = dyn_cast<EnumDecl>(D))
3860       UnderlyingTy = ED->getIntegerType();
3861   }
3862   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3863     return;
3864 
3865   // C++11 [dcl.align]p5, C11 6.7.5/4:
3866   //   The combined effect of all alignment attributes in a declaration shall
3867   //   not specify an alignment that is less strict than the alignment that
3868   //   would otherwise be required for the entity being declared.
3869   AlignedAttr *AlignasAttr = nullptr;
3870   AlignedAttr *LastAlignedAttr = nullptr;
3871   unsigned Align = 0;
3872   for (auto *I : D->specific_attrs<AlignedAttr>()) {
3873     if (I->isAlignmentDependent())
3874       return;
3875     if (I->isAlignas())
3876       AlignasAttr = I;
3877     Align = std::max(Align, I->getAlignment(Context));
3878     LastAlignedAttr = I;
3879   }
3880 
3881   if (Align && DiagTy->isSizelessType()) {
3882     Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
3883         << LastAlignedAttr << DiagTy;
3884   } else if (AlignasAttr && Align) {
3885     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3886     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3887     if (NaturalAlign > RequestedAlign)
3888       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3889         << DiagTy << (unsigned)NaturalAlign.getQuantity();
3890   }
3891 }
3892 
3893 bool Sema::checkMSInheritanceAttrOnDefinition(
3894     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3895     MSInheritanceModel ExplicitModel) {
3896   assert(RD->hasDefinition() && "RD has no definition!");
3897 
3898   // We may not have seen base specifiers or any virtual methods yet.  We will
3899   // have to wait until the record is defined to catch any mismatches.
3900   if (!RD->getDefinition()->isCompleteDefinition())
3901     return false;
3902 
3903   // The unspecified model never matches what a definition could need.
3904   if (ExplicitModel == MSInheritanceModel::Unspecified)
3905     return false;
3906 
3907   if (BestCase) {
3908     if (RD->calculateInheritanceModel() == ExplicitModel)
3909       return false;
3910   } else {
3911     if (RD->calculateInheritanceModel() <= ExplicitModel)
3912       return false;
3913   }
3914 
3915   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3916       << 0 /*definition*/;
3917   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
3918   return true;
3919 }
3920 
3921 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3922 /// attribute.
3923 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3924                              bool &IntegerMode, bool &ComplexMode) {
3925   IntegerMode = true;
3926   ComplexMode = false;
3927   switch (Str.size()) {
3928   case 2:
3929     switch (Str[0]) {
3930     case 'Q':
3931       DestWidth = 8;
3932       break;
3933     case 'H':
3934       DestWidth = 16;
3935       break;
3936     case 'S':
3937       DestWidth = 32;
3938       break;
3939     case 'D':
3940       DestWidth = 64;
3941       break;
3942     case 'X':
3943       DestWidth = 96;
3944       break;
3945     case 'T':
3946       DestWidth = 128;
3947       break;
3948     }
3949     if (Str[1] == 'F') {
3950       IntegerMode = false;
3951     } else if (Str[1] == 'C') {
3952       IntegerMode = false;
3953       ComplexMode = true;
3954     } else if (Str[1] != 'I') {
3955       DestWidth = 0;
3956     }
3957     break;
3958   case 4:
3959     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3960     // pointer on PIC16 and other embedded platforms.
3961     if (Str == "word")
3962       DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3963     else if (Str == "byte")
3964       DestWidth = S.Context.getTargetInfo().getCharWidth();
3965     break;
3966   case 7:
3967     if (Str == "pointer")
3968       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3969     break;
3970   case 11:
3971     if (Str == "unwind_word")
3972       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3973     break;
3974   }
3975 }
3976 
3977 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3978 /// type.
3979 ///
3980 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3981 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3982 /// HImode, not an intermediate pointer.
3983 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3984   // This attribute isn't documented, but glibc uses it.  It changes
3985   // the width of an int or unsigned int to the specified size.
3986   if (!AL.isArgIdent(0)) {
3987     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
3988         << AL << AANT_ArgumentIdentifier;
3989     return;
3990   }
3991 
3992   IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3993 
3994   S.AddModeAttr(D, AL, Name);
3995 }
3996 
3997 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
3998                        IdentifierInfo *Name, bool InInstantiation) {
3999   StringRef Str = Name->getName();
4000   normalizeName(Str);
4001   SourceLocation AttrLoc = CI.getLoc();
4002 
4003   unsigned DestWidth = 0;
4004   bool IntegerMode = true;
4005   bool ComplexMode = false;
4006   llvm::APInt VectorSize(64, 0);
4007   if (Str.size() >= 4 && Str[0] == 'V') {
4008     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4009     size_t StrSize = Str.size();
4010     size_t VectorStringLength = 0;
4011     while ((VectorStringLength + 1) < StrSize &&
4012            isdigit(Str[VectorStringLength + 1]))
4013       ++VectorStringLength;
4014     if (VectorStringLength &&
4015         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4016         VectorSize.isPowerOf2()) {
4017       parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4018                        IntegerMode, ComplexMode);
4019       // Avoid duplicate warning from template instantiation.
4020       if (!InInstantiation)
4021         Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4022     } else {
4023       VectorSize = 0;
4024     }
4025   }
4026 
4027   if (!VectorSize)
4028     parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
4029 
4030   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4031   // and friends, at least with glibc.
4032   // FIXME: Make sure floating-point mappings are accurate
4033   // FIXME: Support XF and TF types
4034   if (!DestWidth) {
4035     Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4036     return;
4037   }
4038 
4039   QualType OldTy;
4040   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4041     OldTy = TD->getUnderlyingType();
4042   else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4043     // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4044     // Try to get type from enum declaration, default to int.
4045     OldTy = ED->getIntegerType();
4046     if (OldTy.isNull())
4047       OldTy = Context.IntTy;
4048   } else
4049     OldTy = cast<ValueDecl>(D)->getType();
4050 
4051   if (OldTy->isDependentType()) {
4052     D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4053     return;
4054   }
4055 
4056   // Base type can also be a vector type (see PR17453).
4057   // Distinguish between base type and base element type.
4058   QualType OldElemTy = OldTy;
4059   if (const auto *VT = OldTy->getAs<VectorType>())
4060     OldElemTy = VT->getElementType();
4061 
4062   // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4063   // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4064   // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4065   if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4066       VectorSize.getBoolValue()) {
4067     Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4068     return;
4069   }
4070   bool IntegralOrAnyEnumType =
4071       OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
4072 
4073   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4074       !IntegralOrAnyEnumType)
4075     Diag(AttrLoc, diag::err_mode_not_primitive);
4076   else if (IntegerMode) {
4077     if (!IntegralOrAnyEnumType)
4078       Diag(AttrLoc, diag::err_mode_wrong_type);
4079   } else if (ComplexMode) {
4080     if (!OldElemTy->isComplexType())
4081       Diag(AttrLoc, diag::err_mode_wrong_type);
4082   } else {
4083     if (!OldElemTy->isFloatingType())
4084       Diag(AttrLoc, diag::err_mode_wrong_type);
4085   }
4086 
4087   QualType NewElemTy;
4088 
4089   if (IntegerMode)
4090     NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4091                                               OldElemTy->isSignedIntegerType());
4092   else
4093     NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4094 
4095   if (NewElemTy.isNull()) {
4096     Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4097     return;
4098   }
4099 
4100   if (ComplexMode) {
4101     NewElemTy = Context.getComplexType(NewElemTy);
4102   }
4103 
4104   QualType NewTy = NewElemTy;
4105   if (VectorSize.getBoolValue()) {
4106     NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4107                                   VectorType::GenericVector);
4108   } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4109     // Complex machine mode does not support base vector types.
4110     if (ComplexMode) {
4111       Diag(AttrLoc, diag::err_complex_mode_vector_type);
4112       return;
4113     }
4114     unsigned NumElements = Context.getTypeSize(OldElemTy) *
4115                            OldVT->getNumElements() /
4116                            Context.getTypeSize(NewElemTy);
4117     NewTy =
4118         Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4119   }
4120 
4121   if (NewTy.isNull()) {
4122     Diag(AttrLoc, diag::err_mode_wrong_type);
4123     return;
4124   }
4125 
4126   // Install the new type.
4127   if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4128     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4129   else if (auto *ED = dyn_cast<EnumDecl>(D))
4130     ED->setIntegerType(NewTy);
4131   else
4132     cast<ValueDecl>(D)->setType(NewTy);
4133 
4134   D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4135 }
4136 
4137 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4138   D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4139 }
4140 
4141 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4142                                               const AttributeCommonInfo &CI,
4143                                               const IdentifierInfo *Ident) {
4144   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4145     Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4146     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4147     return nullptr;
4148   }
4149 
4150   if (D->hasAttr<AlwaysInlineAttr>())
4151     return nullptr;
4152 
4153   return ::new (Context) AlwaysInlineAttr(Context, CI);
4154 }
4155 
4156 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4157   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4158     return nullptr;
4159 
4160   return ::new (Context) CommonAttr(Context, AL);
4161 }
4162 
4163 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4164   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4165     return nullptr;
4166 
4167   return ::new (Context) CommonAttr(Context, AL);
4168 }
4169 
4170 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4171                                                     const ParsedAttr &AL) {
4172   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4173     // Attribute applies to Var but not any subclass of it (like ParmVar,
4174     // ImplicitParm or VarTemplateSpecialization).
4175     if (VD->getKind() != Decl::Var) {
4176       Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4177           << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4178                                             : ExpectedVariableOrFunction);
4179       return nullptr;
4180     }
4181     // Attribute does not apply to non-static local variables.
4182     if (VD->hasLocalStorage()) {
4183       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4184       return nullptr;
4185     }
4186   }
4187 
4188   if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4189     return nullptr;
4190 
4191   return ::new (Context) InternalLinkageAttr(Context, AL);
4192 }
4193 InternalLinkageAttr *
4194 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4195   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4196     // Attribute applies to Var but not any subclass of it (like ParmVar,
4197     // ImplicitParm or VarTemplateSpecialization).
4198     if (VD->getKind() != Decl::Var) {
4199       Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4200           << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4201                                              : ExpectedVariableOrFunction);
4202       return nullptr;
4203     }
4204     // Attribute does not apply to non-static local variables.
4205     if (VD->hasLocalStorage()) {
4206       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4207       return nullptr;
4208     }
4209   }
4210 
4211   if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4212     return nullptr;
4213 
4214   return ::new (Context) InternalLinkageAttr(Context, AL);
4215 }
4216 
4217 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4218   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4219     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4220     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4221     return nullptr;
4222   }
4223 
4224   if (D->hasAttr<MinSizeAttr>())
4225     return nullptr;
4226 
4227   return ::new (Context) MinSizeAttr(Context, CI);
4228 }
4229 
4230 NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4231     Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4232   if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4233     return nullptr;
4234 
4235   return ::new (Context) NoSpeculativeLoadHardeningAttr(Context, AL);
4236 }
4237 
4238 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4239                                               const AttributeCommonInfo &CI) {
4240   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4241     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4242     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4243     D->dropAttr<AlwaysInlineAttr>();
4244   }
4245   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4246     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4247     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4248     D->dropAttr<MinSizeAttr>();
4249   }
4250 
4251   if (D->hasAttr<OptimizeNoneAttr>())
4252     return nullptr;
4253 
4254   return ::new (Context) OptimizeNoneAttr(Context, CI);
4255 }
4256 
4257 SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4258     Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4259   if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4260     return nullptr;
4261 
4262   return ::new (Context) SpeculativeLoadHardeningAttr(Context, AL);
4263 }
4264 
4265 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4266   if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4267     return;
4268 
4269   if (AlwaysInlineAttr *Inline =
4270           S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4271     D->addAttr(Inline);
4272 }
4273 
4274 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4275   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4276     D->addAttr(MinSize);
4277 }
4278 
4279 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4280   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4281     D->addAttr(Optnone);
4282 }
4283 
4284 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4285   if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4286     return;
4287   const auto *VD = cast<VarDecl>(D);
4288   if (!VD->hasGlobalStorage()) {
4289     S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4290     return;
4291   }
4292   D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4293 }
4294 
4295 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4296   if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4297     return;
4298   const auto *VD = cast<VarDecl>(D);
4299   // extern __shared__ is only allowed on arrays with no length (e.g.
4300   // "int x[]").
4301   if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4302       !isa<IncompleteArrayType>(VD->getType())) {
4303     S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4304     return;
4305   }
4306   if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4307       S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4308           << S.CurrentCUDATarget())
4309     return;
4310   D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4311 }
4312 
4313 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4314   if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4315       checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4316     return;
4317   }
4318   const auto *FD = cast<FunctionDecl>(D);
4319   if (!FD->getReturnType()->isVoidType() &&
4320       !FD->getReturnType()->getAs<AutoType>() &&
4321       !FD->getReturnType()->isInstantiationDependentType()) {
4322     SourceRange RTRange = FD->getReturnTypeSourceRange();
4323     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4324         << FD->getType()
4325         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4326                               : FixItHint());
4327     return;
4328   }
4329   if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4330     if (Method->isInstance()) {
4331       S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4332           << Method;
4333       return;
4334     }
4335     S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4336   }
4337   // Only warn for "inline" when compiling for host, to cut down on noise.
4338   if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4339     S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4340 
4341   D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4342 }
4343 
4344 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4345   const auto *Fn = cast<FunctionDecl>(D);
4346   if (!Fn->isInlineSpecified()) {
4347     S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4348     return;
4349   }
4350 
4351   if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4352     S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4353 
4354   D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4355 }
4356 
4357 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4358   if (hasDeclarator(D)) return;
4359 
4360   // Diagnostic is emitted elsewhere: here we store the (valid) AL
4361   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4362   CallingConv CC;
4363   if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4364     return;
4365 
4366   if (!isa<ObjCMethodDecl>(D)) {
4367     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4368         << AL << ExpectedFunctionOrMethod;
4369     return;
4370   }
4371 
4372   switch (AL.getKind()) {
4373   case ParsedAttr::AT_FastCall:
4374     D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4375     return;
4376   case ParsedAttr::AT_StdCall:
4377     D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4378     return;
4379   case ParsedAttr::AT_ThisCall:
4380     D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4381     return;
4382   case ParsedAttr::AT_CDecl:
4383     D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4384     return;
4385   case ParsedAttr::AT_Pascal:
4386     D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4387     return;
4388   case ParsedAttr::AT_SwiftCall:
4389     D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4390     return;
4391   case ParsedAttr::AT_VectorCall:
4392     D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4393     return;
4394   case ParsedAttr::AT_MSABI:
4395     D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4396     return;
4397   case ParsedAttr::AT_SysVABI:
4398     D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4399     return;
4400   case ParsedAttr::AT_RegCall:
4401     D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4402     return;
4403   case ParsedAttr::AT_Pcs: {
4404     PcsAttr::PCSType PCS;
4405     switch (CC) {
4406     case CC_AAPCS:
4407       PCS = PcsAttr::AAPCS;
4408       break;
4409     case CC_AAPCS_VFP:
4410       PCS = PcsAttr::AAPCS_VFP;
4411       break;
4412     default:
4413       llvm_unreachable("unexpected calling convention in pcs attribute");
4414     }
4415 
4416     D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4417     return;
4418   }
4419   case ParsedAttr::AT_AArch64VectorPcs:
4420     D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4421     return;
4422   case ParsedAttr::AT_IntelOclBicc:
4423     D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4424     return;
4425   case ParsedAttr::AT_PreserveMost:
4426     D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4427     return;
4428   case ParsedAttr::AT_PreserveAll:
4429     D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4430     return;
4431   default:
4432     llvm_unreachable("unexpected attribute kind");
4433   }
4434 }
4435 
4436 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4437   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4438     return;
4439 
4440   std::vector<StringRef> DiagnosticIdentifiers;
4441   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4442     StringRef RuleName;
4443 
4444     if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4445       return;
4446 
4447     // FIXME: Warn if the rule name is unknown. This is tricky because only
4448     // clang-tidy knows about available rules.
4449     DiagnosticIdentifiers.push_back(RuleName);
4450   }
4451   D->addAttr(::new (S.Context)
4452                  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4453                               DiagnosticIdentifiers.size()));
4454 }
4455 
4456 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4457   TypeSourceInfo *DerefTypeLoc = nullptr;
4458   QualType ParmType;
4459   if (AL.hasParsedType()) {
4460     ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4461 
4462     unsigned SelectIdx = ~0U;
4463     if (ParmType->isReferenceType())
4464       SelectIdx = 0;
4465     else if (ParmType->isArrayType())
4466       SelectIdx = 1;
4467 
4468     if (SelectIdx != ~0U) {
4469       S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4470           << SelectIdx << AL;
4471       return;
4472     }
4473   }
4474 
4475   // To check if earlier decl attributes do not conflict the newly parsed ones
4476   // we always add (and check) the attribute to the cannonical decl.
4477   D = D->getCanonicalDecl();
4478   if (AL.getKind() == ParsedAttr::AT_Owner) {
4479     if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4480       return;
4481     if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4482       const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4483                                           ? OAttr->getDerefType().getTypePtr()
4484                                           : nullptr;
4485       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4486         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4487             << AL << OAttr;
4488         S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4489       }
4490       return;
4491     }
4492     for (Decl *Redecl : D->redecls()) {
4493       Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4494     }
4495   } else {
4496     if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4497       return;
4498     if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4499       const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4500                                           ? PAttr->getDerefType().getTypePtr()
4501                                           : nullptr;
4502       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4503         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4504             << AL << PAttr;
4505         S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4506       }
4507       return;
4508     }
4509     for (Decl *Redecl : D->redecls()) {
4510       Redecl->addAttr(::new (S.Context)
4511                           PointerAttr(S.Context, AL, DerefTypeLoc));
4512     }
4513   }
4514 }
4515 
4516 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4517                                 const FunctionDecl *FD) {
4518   if (Attrs.isInvalid())
4519     return true;
4520 
4521   if (Attrs.hasProcessingCache()) {
4522     CC = (CallingConv) Attrs.getProcessingCache();
4523     return false;
4524   }
4525 
4526   unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4527   if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4528     Attrs.setInvalid();
4529     return true;
4530   }
4531 
4532   // TODO: diagnose uses of these conventions on the wrong target.
4533   switch (Attrs.getKind()) {
4534   case ParsedAttr::AT_CDecl:
4535     CC = CC_C;
4536     break;
4537   case ParsedAttr::AT_FastCall:
4538     CC = CC_X86FastCall;
4539     break;
4540   case ParsedAttr::AT_StdCall:
4541     CC = CC_X86StdCall;
4542     break;
4543   case ParsedAttr::AT_ThisCall:
4544     CC = CC_X86ThisCall;
4545     break;
4546   case ParsedAttr::AT_Pascal:
4547     CC = CC_X86Pascal;
4548     break;
4549   case ParsedAttr::AT_SwiftCall:
4550     CC = CC_Swift;
4551     break;
4552   case ParsedAttr::AT_VectorCall:
4553     CC = CC_X86VectorCall;
4554     break;
4555   case ParsedAttr::AT_AArch64VectorPcs:
4556     CC = CC_AArch64VectorCall;
4557     break;
4558   case ParsedAttr::AT_RegCall:
4559     CC = CC_X86RegCall;
4560     break;
4561   case ParsedAttr::AT_MSABI:
4562     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4563                                                              CC_Win64;
4564     break;
4565   case ParsedAttr::AT_SysVABI:
4566     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4567                                                              CC_C;
4568     break;
4569   case ParsedAttr::AT_Pcs: {
4570     StringRef StrRef;
4571     if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4572       Attrs.setInvalid();
4573       return true;
4574     }
4575     if (StrRef == "aapcs") {
4576       CC = CC_AAPCS;
4577       break;
4578     } else if (StrRef == "aapcs-vfp") {
4579       CC = CC_AAPCS_VFP;
4580       break;
4581     }
4582 
4583     Attrs.setInvalid();
4584     Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4585     return true;
4586   }
4587   case ParsedAttr::AT_IntelOclBicc:
4588     CC = CC_IntelOclBicc;
4589     break;
4590   case ParsedAttr::AT_PreserveMost:
4591     CC = CC_PreserveMost;
4592     break;
4593   case ParsedAttr::AT_PreserveAll:
4594     CC = CC_PreserveAll;
4595     break;
4596   default: llvm_unreachable("unexpected attribute kind");
4597   }
4598 
4599   TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4600   const TargetInfo &TI = Context.getTargetInfo();
4601   // CUDA functions may have host and/or device attributes which indicate
4602   // their targeted execution environment, therefore the calling convention
4603   // of functions in CUDA should be checked against the target deduced based
4604   // on their host/device attributes.
4605   if (LangOpts.CUDA) {
4606     auto *Aux = Context.getAuxTargetInfo();
4607     auto CudaTarget = IdentifyCUDATarget(FD);
4608     bool CheckHost = false, CheckDevice = false;
4609     switch (CudaTarget) {
4610     case CFT_HostDevice:
4611       CheckHost = true;
4612       CheckDevice = true;
4613       break;
4614     case CFT_Host:
4615       CheckHost = true;
4616       break;
4617     case CFT_Device:
4618     case CFT_Global:
4619       CheckDevice = true;
4620       break;
4621     case CFT_InvalidTarget:
4622       llvm_unreachable("unexpected cuda target");
4623     }
4624     auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4625     auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4626     if (CheckHost && HostTI)
4627       A = HostTI->checkCallingConvention(CC);
4628     if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4629       A = DeviceTI->checkCallingConvention(CC);
4630   } else {
4631     A = TI.checkCallingConvention(CC);
4632   }
4633 
4634   switch (A) {
4635   case TargetInfo::CCCR_OK:
4636     break;
4637 
4638   case TargetInfo::CCCR_Ignore:
4639     // Treat an ignored convention as if it was an explicit C calling convention
4640     // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4641     // that command line flags that change the default convention to
4642     // __vectorcall don't affect declarations marked __stdcall.
4643     CC = CC_C;
4644     break;
4645 
4646   case TargetInfo::CCCR_Error:
4647     Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4648         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4649     break;
4650 
4651   case TargetInfo::CCCR_Warning: {
4652     Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4653         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4654 
4655     // This convention is not valid for the target. Use the default function or
4656     // method calling convention.
4657     bool IsCXXMethod = false, IsVariadic = false;
4658     if (FD) {
4659       IsCXXMethod = FD->isCXXInstanceMember();
4660       IsVariadic = FD->isVariadic();
4661     }
4662     CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4663     break;
4664   }
4665   }
4666 
4667   Attrs.setProcessingCache((unsigned) CC);
4668   return false;
4669 }
4670 
4671 /// Pointer-like types in the default address space.
4672 static bool isValidSwiftContextType(QualType Ty) {
4673   if (!Ty->hasPointerRepresentation())
4674     return Ty->isDependentType();
4675   return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4676 }
4677 
4678 /// Pointers and references in the default address space.
4679 static bool isValidSwiftIndirectResultType(QualType Ty) {
4680   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4681     Ty = PtrType->getPointeeType();
4682   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4683     Ty = RefType->getPointeeType();
4684   } else {
4685     return Ty->isDependentType();
4686   }
4687   return Ty.getAddressSpace() == LangAS::Default;
4688 }
4689 
4690 /// Pointers and references to pointers in the default address space.
4691 static bool isValidSwiftErrorResultType(QualType Ty) {
4692   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4693     Ty = PtrType->getPointeeType();
4694   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4695     Ty = RefType->getPointeeType();
4696   } else {
4697     return Ty->isDependentType();
4698   }
4699   if (!Ty.getQualifiers().empty())
4700     return false;
4701   return isValidSwiftContextType(Ty);
4702 }
4703 
4704 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
4705                                ParameterABI abi) {
4706 
4707   QualType type = cast<ParmVarDecl>(D)->getType();
4708 
4709   if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4710     if (existingAttr->getABI() != abi) {
4711       Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4712           << getParameterABISpelling(abi) << existingAttr;
4713       Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4714       return;
4715     }
4716   }
4717 
4718   switch (abi) {
4719   case ParameterABI::Ordinary:
4720     llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4721 
4722   case ParameterABI::SwiftContext:
4723     if (!isValidSwiftContextType(type)) {
4724       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4725           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
4726     }
4727     D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
4728     return;
4729 
4730   case ParameterABI::SwiftErrorResult:
4731     if (!isValidSwiftErrorResultType(type)) {
4732       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4733           << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
4734     }
4735     D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
4736     return;
4737 
4738   case ParameterABI::SwiftIndirectResult:
4739     if (!isValidSwiftIndirectResultType(type)) {
4740       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4741           << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
4742     }
4743     D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
4744     return;
4745   }
4746   llvm_unreachable("bad parameter ABI attribute");
4747 }
4748 
4749 /// Checks a regparm attribute, returning true if it is ill-formed and
4750 /// otherwise setting numParams to the appropriate value.
4751 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4752   if (AL.isInvalid())
4753     return true;
4754 
4755   if (!checkAttributeNumArgs(*this, AL, 1)) {
4756     AL.setInvalid();
4757     return true;
4758   }
4759 
4760   uint32_t NP;
4761   Expr *NumParamsExpr = AL.getArgAsExpr(0);
4762   if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4763     AL.setInvalid();
4764     return true;
4765   }
4766 
4767   if (Context.getTargetInfo().getRegParmMax() == 0) {
4768     Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4769       << NumParamsExpr->getSourceRange();
4770     AL.setInvalid();
4771     return true;
4772   }
4773 
4774   numParams = NP;
4775   if (numParams > Context.getTargetInfo().getRegParmMax()) {
4776     Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4777       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4778     AL.setInvalid();
4779     return true;
4780   }
4781 
4782   return false;
4783 }
4784 
4785 // Checks whether an argument of launch_bounds attribute is
4786 // acceptable, performs implicit conversion to Rvalue, and returns
4787 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4788 // and may output an error.
4789 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4790                                      const CUDALaunchBoundsAttr &AL,
4791                                      const unsigned Idx) {
4792   if (S.DiagnoseUnexpandedParameterPack(E))
4793     return nullptr;
4794 
4795   // Accept template arguments for now as they depend on something else.
4796   // We'll get to check them when they eventually get instantiated.
4797   if (E->isValueDependent())
4798     return E;
4799 
4800   llvm::APSInt I(64);
4801   if (!E->isIntegerConstantExpr(I, S.Context)) {
4802     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4803         << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4804     return nullptr;
4805   }
4806   // Make sure we can fit it in 32 bits.
4807   if (!I.isIntN(32)) {
4808     S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4809                                                      << 32 << /* Unsigned */ 1;
4810     return nullptr;
4811   }
4812   if (I < 0)
4813     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4814         << &AL << Idx << E->getSourceRange();
4815 
4816   // We may need to perform implicit conversion of the argument.
4817   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4818       S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4819   ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4820   assert(!ValArg.isInvalid() &&
4821          "Unexpected PerformCopyInitialization() failure.");
4822 
4823   return ValArg.getAs<Expr>();
4824 }
4825 
4826 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
4827                                Expr *MaxThreads, Expr *MinBlocks) {
4828   CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
4829   MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4830   if (MaxThreads == nullptr)
4831     return;
4832 
4833   if (MinBlocks) {
4834     MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4835     if (MinBlocks == nullptr)
4836       return;
4837   }
4838 
4839   D->addAttr(::new (Context)
4840                  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
4841 }
4842 
4843 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4844   if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4845       !checkAttributeAtMostNumArgs(S, AL, 2))
4846     return;
4847 
4848   S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
4849                         AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
4850 }
4851 
4852 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4853                                           const ParsedAttr &AL) {
4854   if (!AL.isArgIdent(0)) {
4855     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4856         << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4857     return;
4858   }
4859 
4860   ParamIdx ArgumentIdx;
4861   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4862                                            ArgumentIdx))
4863     return;
4864 
4865   ParamIdx TypeTagIdx;
4866   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4867                                            TypeTagIdx))
4868     return;
4869 
4870   bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
4871   if (IsPointer) {
4872     // Ensure that buffer has a pointer type.
4873     unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4874     if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4875         !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4876       S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4877   }
4878 
4879   D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4880       S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
4881       IsPointer));
4882 }
4883 
4884 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4885                                          const ParsedAttr &AL) {
4886   if (!AL.isArgIdent(0)) {
4887     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4888         << AL << 1 << AANT_ArgumentIdentifier;
4889     return;
4890   }
4891 
4892   if (!checkAttributeNumArgs(S, AL, 1))
4893     return;
4894 
4895   if (!isa<VarDecl>(D)) {
4896     S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4897         << AL << ExpectedVariable;
4898     return;
4899   }
4900 
4901   IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4902   TypeSourceInfo *MatchingCTypeLoc = nullptr;
4903   S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4904   assert(MatchingCTypeLoc && "no type source info for attribute argument");
4905 
4906   D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
4907       S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
4908       AL.getMustBeNull()));
4909 }
4910 
4911 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4912   ParamIdx ArgCount;
4913 
4914   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4915                                            ArgCount,
4916                                            true /* CanIndexImplicitThis */))
4917     return;
4918 
4919   // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4920   D->addAttr(::new (S.Context)
4921                  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
4922 }
4923 
4924 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
4925                                              const ParsedAttr &AL) {
4926   uint32_t Count = 0, Offset = 0;
4927   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
4928     return;
4929   if (AL.getNumArgs() == 2) {
4930     Expr *Arg = AL.getArgAsExpr(1);
4931     if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
4932       return;
4933     if (Count < Offset) {
4934       S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
4935           << &AL << 0 << Count << Arg->getBeginLoc();
4936       return;
4937     }
4938   }
4939   D->addAttr(::new (S.Context)
4940                  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
4941 }
4942 
4943 namespace {
4944 struct IntrinToName {
4945   uint32_t Id;
4946   int32_t FullName;
4947   int32_t ShortName;
4948 };
4949 } // unnamed namespace
4950 
4951 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
4952                                  ArrayRef<IntrinToName> Map,
4953                                  const char *IntrinNames) {
4954   if (AliasName.startswith("__arm_"))
4955     AliasName = AliasName.substr(6);
4956   const IntrinToName *It = std::lower_bound(
4957       Map.begin(), Map.end(), BuiltinID,
4958       [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
4959   if (It == Map.end() || It->Id != BuiltinID)
4960     return false;
4961   StringRef FullName(&IntrinNames[It->FullName]);
4962   if (AliasName == FullName)
4963     return true;
4964   if (It->ShortName == -1)
4965     return false;
4966   StringRef ShortName(&IntrinNames[It->ShortName]);
4967   return AliasName == ShortName;
4968 }
4969 
4970 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
4971 #include "clang/Basic/arm_mve_builtin_aliases.inc"
4972   // The included file defines:
4973   // - ArrayRef<IntrinToName> Map
4974   // - const char IntrinNames[]
4975   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
4976 }
4977 
4978 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
4979 #include "clang/Basic/arm_cde_builtin_aliases.inc"
4980   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
4981 }
4982 
4983 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4984   if (!AL.isArgIdent(0)) {
4985     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4986         << AL << 1 << AANT_ArgumentIdentifier;
4987     return;
4988   }
4989 
4990   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
4991   unsigned BuiltinID = Ident->getBuiltinID();
4992   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
4993 
4994   if (!ArmMveAliasValid(BuiltinID, AliasName) &&
4995       !ArmCdeAliasValid(BuiltinID, AliasName)) {
4996     S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
4997     return;
4998   }
4999 
5000   D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5001 }
5002 
5003 //===----------------------------------------------------------------------===//
5004 // Checker-specific attribute handlers.
5005 //===----------------------------------------------------------------------===//
5006 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5007   return QT->isDependentType() || QT->isObjCRetainableType();
5008 }
5009 
5010 static bool isValidSubjectOfNSAttribute(QualType QT) {
5011   return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5012          QT->isObjCNSObjectType();
5013 }
5014 
5015 static bool isValidSubjectOfCFAttribute(QualType QT) {
5016   return QT->isDependentType() || QT->isPointerType() ||
5017          isValidSubjectOfNSAttribute(QT);
5018 }
5019 
5020 static bool isValidSubjectOfOSAttribute(QualType QT) {
5021   if (QT->isDependentType())
5022     return true;
5023   QualType PT = QT->getPointeeType();
5024   return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5025 }
5026 
5027 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5028                             RetainOwnershipKind K,
5029                             bool IsTemplateInstantiation) {
5030   ValueDecl *VD = cast<ValueDecl>(D);
5031   switch (K) {
5032   case RetainOwnershipKind::OS:
5033     handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5034         *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5035         diag::warn_ns_attribute_wrong_parameter_type,
5036         /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5037     return;
5038   case RetainOwnershipKind::NS:
5039     handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5040         *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5041 
5042         // These attributes are normally just advisory, but in ARC, ns_consumed
5043         // is significant.  Allow non-dependent code to contain inappropriate
5044         // attributes even in ARC, but require template instantiations to be
5045         // set up correctly.
5046         ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5047              ? diag::err_ns_attribute_wrong_parameter_type
5048              : diag::warn_ns_attribute_wrong_parameter_type),
5049         /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5050     return;
5051   case RetainOwnershipKind::CF:
5052     handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5053         *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5054         diag::warn_ns_attribute_wrong_parameter_type,
5055         /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5056     return;
5057   }
5058 }
5059 
5060 static Sema::RetainOwnershipKind
5061 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5062   switch (AL.getKind()) {
5063   case ParsedAttr::AT_CFConsumed:
5064   case ParsedAttr::AT_CFReturnsRetained:
5065   case ParsedAttr::AT_CFReturnsNotRetained:
5066     return Sema::RetainOwnershipKind::CF;
5067   case ParsedAttr::AT_OSConsumesThis:
5068   case ParsedAttr::AT_OSConsumed:
5069   case ParsedAttr::AT_OSReturnsRetained:
5070   case ParsedAttr::AT_OSReturnsNotRetained:
5071   case ParsedAttr::AT_OSReturnsRetainedOnZero:
5072   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5073     return Sema::RetainOwnershipKind::OS;
5074   case ParsedAttr::AT_NSConsumesSelf:
5075   case ParsedAttr::AT_NSConsumed:
5076   case ParsedAttr::AT_NSReturnsRetained:
5077   case ParsedAttr::AT_NSReturnsNotRetained:
5078   case ParsedAttr::AT_NSReturnsAutoreleased:
5079     return Sema::RetainOwnershipKind::NS;
5080   default:
5081     llvm_unreachable("Wrong argument supplied");
5082   }
5083 }
5084 
5085 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5086   if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5087     return false;
5088 
5089   Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5090       << "'ns_returns_retained'" << 0 << 0;
5091   return true;
5092 }
5093 
5094 /// \return whether the parameter is a pointer to OSObject pointer.
5095 static bool isValidOSObjectOutParameter(const Decl *D) {
5096   const auto *PVD = dyn_cast<ParmVarDecl>(D);
5097   if (!PVD)
5098     return false;
5099   QualType QT = PVD->getType();
5100   QualType PT = QT->getPointeeType();
5101   return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5102 }
5103 
5104 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5105                                         const ParsedAttr &AL) {
5106   QualType ReturnType;
5107   Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5108 
5109   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5110     ReturnType = MD->getReturnType();
5111   } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5112              (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5113     return; // ignore: was handled as a type attribute
5114   } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5115     ReturnType = PD->getType();
5116   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5117     ReturnType = FD->getReturnType();
5118   } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5119     // Attributes on parameters are used for out-parameters,
5120     // passed as pointers-to-pointers.
5121     unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5122             ? /*pointer-to-CF-pointer*/2
5123             : /*pointer-to-OSObject-pointer*/3;
5124     ReturnType = Param->getType()->getPointeeType();
5125     if (ReturnType.isNull()) {
5126       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5127           << AL << DiagID << AL.getRange();
5128       return;
5129     }
5130   } else if (AL.isUsedAsTypeAttr()) {
5131     return;
5132   } else {
5133     AttributeDeclKind ExpectedDeclKind;
5134     switch (AL.getKind()) {
5135     default: llvm_unreachable("invalid ownership attribute");
5136     case ParsedAttr::AT_NSReturnsRetained:
5137     case ParsedAttr::AT_NSReturnsAutoreleased:
5138     case ParsedAttr::AT_NSReturnsNotRetained:
5139       ExpectedDeclKind = ExpectedFunctionOrMethod;
5140       break;
5141 
5142     case ParsedAttr::AT_OSReturnsRetained:
5143     case ParsedAttr::AT_OSReturnsNotRetained:
5144     case ParsedAttr::AT_CFReturnsRetained:
5145     case ParsedAttr::AT_CFReturnsNotRetained:
5146       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5147       break;
5148     }
5149     S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5150         << AL.getRange() << AL << ExpectedDeclKind;
5151     return;
5152   }
5153 
5154   bool TypeOK;
5155   bool Cf;
5156   unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5157   switch (AL.getKind()) {
5158   default: llvm_unreachable("invalid ownership attribute");
5159   case ParsedAttr::AT_NSReturnsRetained:
5160     TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5161     Cf = false;
5162     break;
5163 
5164   case ParsedAttr::AT_NSReturnsAutoreleased:
5165   case ParsedAttr::AT_NSReturnsNotRetained:
5166     TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5167     Cf = false;
5168     break;
5169 
5170   case ParsedAttr::AT_CFReturnsRetained:
5171   case ParsedAttr::AT_CFReturnsNotRetained:
5172     TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5173     Cf = true;
5174     break;
5175 
5176   case ParsedAttr::AT_OSReturnsRetained:
5177   case ParsedAttr::AT_OSReturnsNotRetained:
5178     TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5179     Cf = true;
5180     ParmDiagID = 3; // Pointer-to-OSObject-pointer
5181     break;
5182   }
5183 
5184   if (!TypeOK) {
5185     if (AL.isUsedAsTypeAttr())
5186       return;
5187 
5188     if (isa<ParmVarDecl>(D)) {
5189       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5190           << AL << ParmDiagID << AL.getRange();
5191     } else {
5192       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5193       enum : unsigned {
5194         Function,
5195         Method,
5196         Property
5197       } SubjectKind = Function;
5198       if (isa<ObjCMethodDecl>(D))
5199         SubjectKind = Method;
5200       else if (isa<ObjCPropertyDecl>(D))
5201         SubjectKind = Property;
5202       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5203           << AL << SubjectKind << Cf << AL.getRange();
5204     }
5205     return;
5206   }
5207 
5208   switch (AL.getKind()) {
5209     default:
5210       llvm_unreachable("invalid ownership attribute");
5211     case ParsedAttr::AT_NSReturnsAutoreleased:
5212       handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5213       return;
5214     case ParsedAttr::AT_CFReturnsNotRetained:
5215       handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5216       return;
5217     case ParsedAttr::AT_NSReturnsNotRetained:
5218       handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5219       return;
5220     case ParsedAttr::AT_CFReturnsRetained:
5221       handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5222       return;
5223     case ParsedAttr::AT_NSReturnsRetained:
5224       handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5225       return;
5226     case ParsedAttr::AT_OSReturnsRetained:
5227       handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5228       return;
5229     case ParsedAttr::AT_OSReturnsNotRetained:
5230       handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5231       return;
5232   };
5233 }
5234 
5235 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5236                                               const ParsedAttr &Attrs) {
5237   const int EP_ObjCMethod = 1;
5238   const int EP_ObjCProperty = 2;
5239 
5240   SourceLocation loc = Attrs.getLoc();
5241   QualType resultType;
5242   if (isa<ObjCMethodDecl>(D))
5243     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5244   else
5245     resultType = cast<ObjCPropertyDecl>(D)->getType();
5246 
5247   if (!resultType->isReferenceType() &&
5248       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5249     S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5250         << SourceRange(loc) << Attrs
5251         << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5252         << /*non-retainable pointer*/ 2;
5253 
5254     // Drop the attribute.
5255     return;
5256   }
5257 
5258   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5259 }
5260 
5261 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5262                                         const ParsedAttr &Attrs) {
5263   const auto *Method = cast<ObjCMethodDecl>(D);
5264 
5265   const DeclContext *DC = Method->getDeclContext();
5266   if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5267     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5268                                                                       << 0;
5269     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5270     return;
5271   }
5272   if (Method->getMethodFamily() == OMF_dealloc) {
5273     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5274                                                                       << 1;
5275     return;
5276   }
5277 
5278   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5279 }
5280 
5281 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5282   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5283 
5284   if (!Parm) {
5285     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5286     return;
5287   }
5288 
5289   // Typedefs only allow objc_bridge(id) and have some additional checking.
5290   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5291     if (!Parm->Ident->isStr("id")) {
5292       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5293       return;
5294     }
5295 
5296     // Only allow 'cv void *'.
5297     QualType T = TD->getUnderlyingType();
5298     if (!T->isVoidPointerType()) {
5299       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5300       return;
5301     }
5302   }
5303 
5304   D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5305 }
5306 
5307 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5308                                         const ParsedAttr &AL) {
5309   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5310 
5311   if (!Parm) {
5312     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5313     return;
5314   }
5315 
5316   D->addAttr(::new (S.Context)
5317                  ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5318 }
5319 
5320 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5321                                         const ParsedAttr &AL) {
5322   IdentifierInfo *RelatedClass =
5323       AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5324   if (!RelatedClass) {
5325     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5326     return;
5327   }
5328   IdentifierInfo *ClassMethod =
5329     AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5330   IdentifierInfo *InstanceMethod =
5331     AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5332   D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5333       S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5334 }
5335 
5336 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5337                                             const ParsedAttr &AL) {
5338   DeclContext *Ctx = D->getDeclContext();
5339 
5340   // This attribute can only be applied to methods in interfaces or class
5341   // extensions.
5342   if (!isa<ObjCInterfaceDecl>(Ctx) &&
5343       !(isa<ObjCCategoryDecl>(Ctx) &&
5344         cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5345     S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5346     return;
5347   }
5348 
5349   ObjCInterfaceDecl *IFace;
5350   if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5351     IFace = CatDecl->getClassInterface();
5352   else
5353     IFace = cast<ObjCInterfaceDecl>(Ctx);
5354 
5355   if (!IFace)
5356     return;
5357 
5358   IFace->setHasDesignatedInitializers();
5359   D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5360 }
5361 
5362 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5363   StringRef MetaDataName;
5364   if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5365     return;
5366   D->addAttr(::new (S.Context)
5367                  ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5368 }
5369 
5370 // When a user wants to use objc_boxable with a union or struct
5371 // but they don't have access to the declaration (legacy/third-party code)
5372 // then they can 'enable' this feature with a typedef:
5373 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5374 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5375   bool notify = false;
5376 
5377   auto *RD = dyn_cast<RecordDecl>(D);
5378   if (RD && RD->getDefinition()) {
5379     RD = RD->getDefinition();
5380     notify = true;
5381   }
5382 
5383   if (RD) {
5384     ObjCBoxableAttr *BoxableAttr =
5385         ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5386     RD->addAttr(BoxableAttr);
5387     if (notify) {
5388       // we need to notify ASTReader/ASTWriter about
5389       // modification of existing declaration
5390       if (ASTMutationListener *L = S.getASTMutationListener())
5391         L->AddedAttributeToRecord(BoxableAttr, RD);
5392     }
5393   }
5394 }
5395 
5396 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5397   if (hasDeclarator(D)) return;
5398 
5399   S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5400       << AL.getRange() << AL << ExpectedVariable;
5401 }
5402 
5403 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5404                                           const ParsedAttr &AL) {
5405   const auto *VD = cast<ValueDecl>(D);
5406   QualType QT = VD->getType();
5407 
5408   if (!QT->isDependentType() &&
5409       !QT->isObjCLifetimeType()) {
5410     S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5411       << QT;
5412     return;
5413   }
5414 
5415   Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5416 
5417   // If we have no lifetime yet, check the lifetime we're presumably
5418   // going to infer.
5419   if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5420     Lifetime = QT->getObjCARCImplicitLifetime();
5421 
5422   switch (Lifetime) {
5423   case Qualifiers::OCL_None:
5424     assert(QT->isDependentType() &&
5425            "didn't infer lifetime for non-dependent type?");
5426     break;
5427 
5428   case Qualifiers::OCL_Weak:   // meaningful
5429   case Qualifiers::OCL_Strong: // meaningful
5430     break;
5431 
5432   case Qualifiers::OCL_ExplicitNone:
5433   case Qualifiers::OCL_Autoreleasing:
5434     S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5435         << (Lifetime == Qualifiers::OCL_Autoreleasing);
5436     break;
5437   }
5438 
5439   D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5440 }
5441 
5442 //===----------------------------------------------------------------------===//
5443 // Microsoft specific attribute handlers.
5444 //===----------------------------------------------------------------------===//
5445 
5446 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5447                               StringRef Uuid) {
5448   if (const auto *UA = D->getAttr<UuidAttr>()) {
5449     if (UA->getGuid().equals_lower(Uuid))
5450       return nullptr;
5451     if (!UA->getGuid().empty()) {
5452       Diag(UA->getLocation(), diag::err_mismatched_uuid);
5453       Diag(CI.getLoc(), diag::note_previous_uuid);
5454       D->dropAttr<UuidAttr>();
5455     }
5456   }
5457 
5458   return ::new (Context) UuidAttr(Context, CI, Uuid);
5459 }
5460 
5461 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5462   if (!S.LangOpts.CPlusPlus) {
5463     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5464         << AL << AttributeLangSupport::C;
5465     return;
5466   }
5467 
5468   StringRef StrRef;
5469   SourceLocation LiteralLoc;
5470   if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5471     return;
5472 
5473   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5474   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5475   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5476     StrRef = StrRef.drop_front().drop_back();
5477 
5478   // Validate GUID length.
5479   if (StrRef.size() != 36) {
5480     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5481     return;
5482   }
5483 
5484   for (unsigned i = 0; i < 36; ++i) {
5485     if (i == 8 || i == 13 || i == 18 || i == 23) {
5486       if (StrRef[i] != '-') {
5487         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5488         return;
5489       }
5490     } else if (!isHexDigit(StrRef[i])) {
5491       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5492       return;
5493     }
5494   }
5495 
5496   // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5497   // the only thing in the [] list, the [] too), and add an insertion of
5498   // __declspec(uuid(...)).  But sadly, neither the SourceLocs of the commas
5499   // separating attributes nor of the [ and the ] are in the AST.
5500   // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5501   // on cfe-dev.
5502   if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5503     S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5504 
5505   UuidAttr *UA = S.mergeUuidAttr(D, AL, StrRef);
5506   if (UA)
5507     D->addAttr(UA);
5508 }
5509 
5510 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5511   if (!S.LangOpts.CPlusPlus) {
5512     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5513         << AL << AttributeLangSupport::C;
5514     return;
5515   }
5516   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5517       D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
5518   if (IA) {
5519     D->addAttr(IA);
5520     S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5521   }
5522 }
5523 
5524 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5525   const auto *VD = cast<VarDecl>(D);
5526   if (!S.Context.getTargetInfo().isTLSSupported()) {
5527     S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5528     return;
5529   }
5530   if (VD->getTSCSpec() != TSCS_unspecified) {
5531     S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5532     return;
5533   }
5534   if (VD->hasLocalStorage()) {
5535     S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5536     return;
5537   }
5538   D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
5539 }
5540 
5541 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5542   SmallVector<StringRef, 4> Tags;
5543   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5544     StringRef Tag;
5545     if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5546       return;
5547     Tags.push_back(Tag);
5548   }
5549 
5550   if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5551     if (!NS->isInline()) {
5552       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5553       return;
5554     }
5555     if (NS->isAnonymousNamespace()) {
5556       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5557       return;
5558     }
5559     if (AL.getNumArgs() == 0)
5560       Tags.push_back(NS->getName());
5561   } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5562     return;
5563 
5564   // Store tags sorted and without duplicates.
5565   llvm::sort(Tags);
5566   Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5567 
5568   D->addAttr(::new (S.Context)
5569                  AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
5570 }
5571 
5572 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5573   // Check the attribute arguments.
5574   if (AL.getNumArgs() > 1) {
5575     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5576     return;
5577   }
5578 
5579   StringRef Str;
5580   SourceLocation ArgLoc;
5581 
5582   if (AL.getNumArgs() == 0)
5583     Str = "";
5584   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5585     return;
5586 
5587   ARMInterruptAttr::InterruptType Kind;
5588   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5589     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5590                                                                  << ArgLoc;
5591     return;
5592   }
5593 
5594   D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
5595 }
5596 
5597 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5598   // MSP430 'interrupt' attribute is applied to
5599   // a function with no parameters and void return type.
5600   if (!isFunctionOrMethod(D)) {
5601     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5602         << "'interrupt'" << ExpectedFunctionOrMethod;
5603     return;
5604   }
5605 
5606   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5607     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5608         << /*MSP430*/ 1 << 0;
5609     return;
5610   }
5611 
5612   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5613     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5614         << /*MSP430*/ 1 << 1;
5615     return;
5616   }
5617 
5618   // The attribute takes one integer argument.
5619   if (!checkAttributeNumArgs(S, AL, 1))
5620     return;
5621 
5622   if (!AL.isArgExpr(0)) {
5623     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5624         << AL << AANT_ArgumentIntegerConstant;
5625     return;
5626   }
5627 
5628   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5629   llvm::APSInt NumParams(32);
5630   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5631     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5632         << AL << AANT_ArgumentIntegerConstant
5633         << NumParamsExpr->getSourceRange();
5634     return;
5635   }
5636   // The argument should be in range 0..63.
5637   unsigned Num = NumParams.getLimitedValue(255);
5638   if (Num > 63) {
5639     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5640         << AL << (int)NumParams.getSExtValue()
5641         << NumParamsExpr->getSourceRange();
5642     return;
5643   }
5644 
5645   D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
5646   D->addAttr(UsedAttr::CreateImplicit(S.Context));
5647 }
5648 
5649 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5650   // Only one optional argument permitted.
5651   if (AL.getNumArgs() > 1) {
5652     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5653     return;
5654   }
5655 
5656   StringRef Str;
5657   SourceLocation ArgLoc;
5658 
5659   if (AL.getNumArgs() == 0)
5660     Str = "";
5661   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5662     return;
5663 
5664   // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5665   // a) Must be a function.
5666   // b) Must have no parameters.
5667   // c) Must have the 'void' return type.
5668   // d) Cannot have the 'mips16' attribute, as that instruction set
5669   //    lacks the 'eret' instruction.
5670   // e) The attribute itself must either have no argument or one of the
5671   //    valid interrupt types, see [MipsInterruptDocs].
5672 
5673   if (!isFunctionOrMethod(D)) {
5674     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5675         << "'interrupt'" << ExpectedFunctionOrMethod;
5676     return;
5677   }
5678 
5679   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5680     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5681         << /*MIPS*/ 0 << 0;
5682     return;
5683   }
5684 
5685   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5686     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5687         << /*MIPS*/ 0 << 1;
5688     return;
5689   }
5690 
5691   if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5692     return;
5693 
5694   MipsInterruptAttr::InterruptType Kind;
5695   if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5696     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5697         << AL << "'" + std::string(Str) + "'";
5698     return;
5699   }
5700 
5701   D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
5702 }
5703 
5704 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5705   // Semantic checks for a function with the 'interrupt' attribute.
5706   // a) Must be a function.
5707   // b) Must have the 'void' return type.
5708   // c) Must take 1 or 2 arguments.
5709   // d) The 1st argument must be a pointer.
5710   // e) The 2nd argument (if any) must be an unsigned integer.
5711   if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5712       CXXMethodDecl::isStaticOverloadedOperator(
5713           cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5714     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5715         << AL << ExpectedFunctionWithProtoType;
5716     return;
5717   }
5718   // Interrupt handler must have void return type.
5719   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5720     S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5721            diag::err_anyx86_interrupt_attribute)
5722         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5723                 ? 0
5724                 : 1)
5725         << 0;
5726     return;
5727   }
5728   // Interrupt handler must have 1 or 2 parameters.
5729   unsigned NumParams = getFunctionOrMethodNumParams(D);
5730   if (NumParams < 1 || NumParams > 2) {
5731     S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5732         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5733                 ? 0
5734                 : 1)
5735         << 1;
5736     return;
5737   }
5738   // The first argument must be a pointer.
5739   if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5740     S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5741            diag::err_anyx86_interrupt_attribute)
5742         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5743                 ? 0
5744                 : 1)
5745         << 2;
5746     return;
5747   }
5748   // The second argument, if present, must be an unsigned integer.
5749   unsigned TypeSize =
5750       S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5751           ? 64
5752           : 32;
5753   if (NumParams == 2 &&
5754       (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5755        S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5756     S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5757            diag::err_anyx86_interrupt_attribute)
5758         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5759                 ? 0
5760                 : 1)
5761         << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5762     return;
5763   }
5764   D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
5765   D->addAttr(UsedAttr::CreateImplicit(S.Context));
5766 }
5767 
5768 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5769   if (!isFunctionOrMethod(D)) {
5770     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5771         << "'interrupt'" << ExpectedFunction;
5772     return;
5773   }
5774 
5775   if (!checkAttributeNumArgs(S, AL, 0))
5776     return;
5777 
5778   handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5779 }
5780 
5781 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5782   if (!isFunctionOrMethod(D)) {
5783     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5784         << "'signal'" << ExpectedFunction;
5785     return;
5786   }
5787 
5788   if (!checkAttributeNumArgs(S, AL, 0))
5789     return;
5790 
5791   handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5792 }
5793 
5794 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
5795   // Add preserve_access_index attribute to all fields and inner records.
5796   for (auto D : RD->decls()) {
5797     if (D->hasAttr<BPFPreserveAccessIndexAttr>())
5798       continue;
5799 
5800     D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
5801     if (auto *Rec = dyn_cast<RecordDecl>(D))
5802       handleBPFPreserveAIRecord(S, Rec);
5803   }
5804 }
5805 
5806 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
5807     const ParsedAttr &AL) {
5808   auto *Rec = cast<RecordDecl>(D);
5809   handleBPFPreserveAIRecord(S, Rec);
5810   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
5811 }
5812 
5813 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5814   if (!isFunctionOrMethod(D)) {
5815     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5816         << "'export_name'" << ExpectedFunction;
5817     return;
5818   }
5819 
5820   auto *FD = cast<FunctionDecl>(D);
5821   if (FD->isThisDeclarationADefinition()) {
5822     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5823     return;
5824   }
5825 
5826   StringRef Str;
5827   SourceLocation ArgLoc;
5828   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5829     return;
5830 
5831   D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
5832   D->addAttr(UsedAttr::CreateImplicit(S.Context));
5833 }
5834 
5835 static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5836   if (!isFunctionOrMethod(D)) {
5837     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5838         << "'import_module'" << ExpectedFunction;
5839     return;
5840   }
5841 
5842   auto *FD = cast<FunctionDecl>(D);
5843   if (FD->isThisDeclarationADefinition()) {
5844     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5845     return;
5846   }
5847 
5848   StringRef Str;
5849   SourceLocation ArgLoc;
5850   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5851     return;
5852 
5853   FD->addAttr(::new (S.Context)
5854                   WebAssemblyImportModuleAttr(S.Context, AL, Str));
5855 }
5856 
5857 static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5858   if (!isFunctionOrMethod(D)) {
5859     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5860         << "'import_name'" << ExpectedFunction;
5861     return;
5862   }
5863 
5864   auto *FD = cast<FunctionDecl>(D);
5865   if (FD->isThisDeclarationADefinition()) {
5866     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5867     return;
5868   }
5869 
5870   StringRef Str;
5871   SourceLocation ArgLoc;
5872   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5873     return;
5874 
5875   FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
5876 }
5877 
5878 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5879                                      const ParsedAttr &AL) {
5880   // Warn about repeated attributes.
5881   if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5882     S.Diag(AL.getRange().getBegin(),
5883       diag::warn_riscv_repeated_interrupt_attribute);
5884     S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5885     return;
5886   }
5887 
5888   // Check the attribute argument. Argument is optional.
5889   if (!checkAttributeAtMostNumArgs(S, AL, 1))
5890     return;
5891 
5892   StringRef Str;
5893   SourceLocation ArgLoc;
5894 
5895   // 'machine'is the default interrupt mode.
5896   if (AL.getNumArgs() == 0)
5897     Str = "machine";
5898   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5899     return;
5900 
5901   // Semantic checks for a function with the 'interrupt' attribute:
5902   // - Must be a function.
5903   // - Must have no parameters.
5904   // - Must have the 'void' return type.
5905   // - The attribute itself must either have no argument or one of the
5906   //   valid interrupt types, see [RISCVInterruptDocs].
5907 
5908   if (D->getFunctionType() == nullptr) {
5909     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5910       << "'interrupt'" << ExpectedFunction;
5911     return;
5912   }
5913 
5914   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5915     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5916       << /*RISC-V*/ 2 << 0;
5917     return;
5918   }
5919 
5920   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5921     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5922       << /*RISC-V*/ 2 << 1;
5923     return;
5924   }
5925 
5926   RISCVInterruptAttr::InterruptType Kind;
5927   if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5928     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5929                                                                  << ArgLoc;
5930     return;
5931   }
5932 
5933   D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
5934 }
5935 
5936 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5937   // Dispatch the interrupt attribute based on the current target.
5938   switch (S.Context.getTargetInfo().getTriple().getArch()) {
5939   case llvm::Triple::msp430:
5940     handleMSP430InterruptAttr(S, D, AL);
5941     break;
5942   case llvm::Triple::mipsel:
5943   case llvm::Triple::mips:
5944     handleMipsInterruptAttr(S, D, AL);
5945     break;
5946   case llvm::Triple::x86:
5947   case llvm::Triple::x86_64:
5948     handleAnyX86InterruptAttr(S, D, AL);
5949     break;
5950   case llvm::Triple::avr:
5951     handleAVRInterruptAttr(S, D, AL);
5952     break;
5953   case llvm::Triple::riscv32:
5954   case llvm::Triple::riscv64:
5955     handleRISCVInterruptAttr(S, D, AL);
5956     break;
5957   default:
5958     handleARMInterruptAttr(S, D, AL);
5959     break;
5960   }
5961 }
5962 
5963 static bool
5964 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
5965                                       const AMDGPUFlatWorkGroupSizeAttr &Attr) {
5966   // Accept template arguments for now as they depend on something else.
5967   // We'll get to check them when they eventually get instantiated.
5968   if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
5969     return false;
5970 
5971   uint32_t Min = 0;
5972   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
5973     return true;
5974 
5975   uint32_t Max = 0;
5976   if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
5977     return true;
5978 
5979   if (Min == 0 && Max != 0) {
5980     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5981         << &Attr << 0;
5982     return true;
5983   }
5984   if (Min > Max) {
5985     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5986         << &Attr << 1;
5987     return true;
5988   }
5989 
5990   return false;
5991 }
5992 
5993 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
5994                                           const AttributeCommonInfo &CI,
5995                                           Expr *MinExpr, Expr *MaxExpr) {
5996   AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
5997 
5998   if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
5999     return;
6000 
6001   D->addAttr(::new (Context)
6002                  AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
6003 }
6004 
6005 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
6006                                               const ParsedAttr &AL) {
6007   Expr *MinExpr = AL.getArgAsExpr(0);
6008   Expr *MaxExpr = AL.getArgAsExpr(1);
6009 
6010   S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
6011 }
6012 
6013 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
6014                                            Expr *MaxExpr,
6015                                            const AMDGPUWavesPerEUAttr &Attr) {
6016   if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
6017       (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
6018     return true;
6019 
6020   // Accept template arguments for now as they depend on something else.
6021   // We'll get to check them when they eventually get instantiated.
6022   if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
6023     return false;
6024 
6025   uint32_t Min = 0;
6026   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
6027     return true;
6028 
6029   uint32_t Max = 0;
6030   if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
6031     return true;
6032 
6033   if (Min == 0 && Max != 0) {
6034     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6035         << &Attr << 0;
6036     return true;
6037   }
6038   if (Max != 0 && Min > Max) {
6039     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6040         << &Attr << 1;
6041     return true;
6042   }
6043 
6044   return false;
6045 }
6046 
6047 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
6048                                    Expr *MinExpr, Expr *MaxExpr) {
6049   AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
6050 
6051   if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
6052     return;
6053 
6054   D->addAttr(::new (Context)
6055                  AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
6056 }
6057 
6058 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6059   if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
6060       !checkAttributeAtMostNumArgs(S, AL, 2))
6061     return;
6062 
6063   Expr *MinExpr = AL.getArgAsExpr(0);
6064   Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
6065 
6066   S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
6067 }
6068 
6069 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6070   uint32_t NumSGPR = 0;
6071   Expr *NumSGPRExpr = AL.getArgAsExpr(0);
6072   if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
6073     return;
6074 
6075   D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
6076 }
6077 
6078 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6079   uint32_t NumVGPR = 0;
6080   Expr *NumVGPRExpr = AL.getArgAsExpr(0);
6081   if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
6082     return;
6083 
6084   D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
6085 }
6086 
6087 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
6088                                               const ParsedAttr &AL) {
6089   // If we try to apply it to a function pointer, don't warn, but don't
6090   // do anything, either. It doesn't matter anyway, because there's nothing
6091   // special about calling a force_align_arg_pointer function.
6092   const auto *VD = dyn_cast<ValueDecl>(D);
6093   if (VD && VD->getType()->isFunctionPointerType())
6094     return;
6095   // Also don't warn on function pointer typedefs.
6096   const auto *TD = dyn_cast<TypedefNameDecl>(D);
6097   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
6098     TD->getUnderlyingType()->isFunctionType()))
6099     return;
6100   // Attribute can only be applied to function types.
6101   if (!isa<FunctionDecl>(D)) {
6102     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6103         << AL << ExpectedFunction;
6104     return;
6105   }
6106 
6107   D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
6108 }
6109 
6110 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
6111   uint32_t Version;
6112   Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6113   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
6114     return;
6115 
6116   // TODO: Investigate what happens with the next major version of MSVC.
6117   if (Version != LangOptions::MSVC2015 / 100) {
6118     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6119         << AL << Version << VersionExpr->getSourceRange();
6120     return;
6121   }
6122 
6123   // The attribute expects a "major" version number like 19, but new versions of
6124   // MSVC have moved to updating the "minor", or less significant numbers, so we
6125   // have to multiply by 100 now.
6126   Version *= 100;
6127 
6128   D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
6129 }
6130 
6131 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
6132                                         const AttributeCommonInfo &CI) {
6133   if (D->hasAttr<DLLExportAttr>()) {
6134     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
6135     return nullptr;
6136   }
6137 
6138   if (D->hasAttr<DLLImportAttr>())
6139     return nullptr;
6140 
6141   return ::new (Context) DLLImportAttr(Context, CI);
6142 }
6143 
6144 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
6145                                         const AttributeCommonInfo &CI) {
6146   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
6147     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
6148     D->dropAttr<DLLImportAttr>();
6149   }
6150 
6151   if (D->hasAttr<DLLExportAttr>())
6152     return nullptr;
6153 
6154   return ::new (Context) DLLExportAttr(Context, CI);
6155 }
6156 
6157 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6158   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
6159       S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6160     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
6161     return;
6162   }
6163 
6164   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6165     if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
6166         !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6167       // MinGW doesn't allow dllimport on inline functions.
6168       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
6169           << A;
6170       return;
6171     }
6172   }
6173 
6174   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
6175     if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6176         MD->getParent()->isLambda()) {
6177       S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
6178       return;
6179     }
6180   }
6181 
6182   Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
6183                       ? (Attr *)S.mergeDLLExportAttr(D, A)
6184                       : (Attr *)S.mergeDLLImportAttr(D, A);
6185   if (NewAttr)
6186     D->addAttr(NewAttr);
6187 }
6188 
6189 MSInheritanceAttr *
6190 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
6191                              bool BestCase,
6192                              MSInheritanceModel Model) {
6193   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
6194     if (IA->getInheritanceModel() == Model)
6195       return nullptr;
6196     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
6197         << 1 /*previous declaration*/;
6198     Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
6199     D->dropAttr<MSInheritanceAttr>();
6200   }
6201 
6202   auto *RD = cast<CXXRecordDecl>(D);
6203   if (RD->hasDefinition()) {
6204     if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
6205                                            Model)) {
6206       return nullptr;
6207     }
6208   } else {
6209     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
6210       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
6211           << 1 /*partial specialization*/;
6212       return nullptr;
6213     }
6214     if (RD->getDescribedClassTemplate()) {
6215       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
6216           << 0 /*primary template*/;
6217       return nullptr;
6218     }
6219   }
6220 
6221   return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
6222 }
6223 
6224 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6225   // The capability attributes take a single string parameter for the name of
6226   // the capability they represent. The lockable attribute does not take any
6227   // parameters. However, semantically, both attributes represent the same
6228   // concept, and so they use the same semantic attribute. Eventually, the
6229   // lockable attribute will be removed.
6230   //
6231   // For backward compatibility, any capability which has no specified string
6232   // literal will be considered a "mutex."
6233   StringRef N("mutex");
6234   SourceLocation LiteralLoc;
6235   if (AL.getKind() == ParsedAttr::AT_Capability &&
6236       !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
6237     return;
6238 
6239   D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
6240 }
6241 
6242 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6243   SmallVector<Expr*, 1> Args;
6244   if (!checkLockFunAttrCommon(S, D, AL, Args))
6245     return;
6246 
6247   D->addAttr(::new (S.Context)
6248                  AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
6249 }
6250 
6251 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
6252                                         const ParsedAttr &AL) {
6253   SmallVector<Expr*, 1> Args;
6254   if (!checkLockFunAttrCommon(S, D, AL, Args))
6255     return;
6256 
6257   D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
6258                                                      Args.size()));
6259 }
6260 
6261 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
6262                                            const ParsedAttr &AL) {
6263   SmallVector<Expr*, 2> Args;
6264   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
6265     return;
6266 
6267   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
6268       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
6269 }
6270 
6271 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6272                                         const ParsedAttr &AL) {
6273   // Check that all arguments are lockable objects.
6274   SmallVector<Expr *, 1> Args;
6275   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6276 
6277   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
6278                                                      Args.size()));
6279 }
6280 
6281 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6282                                          const ParsedAttr &AL) {
6283   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6284     return;
6285 
6286   // check that all arguments are lockable objects
6287   SmallVector<Expr*, 1> Args;
6288   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6289   if (Args.empty())
6290     return;
6291 
6292   RequiresCapabilityAttr *RCA = ::new (S.Context)
6293       RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
6294 
6295   D->addAttr(RCA);
6296 }
6297 
6298 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6299   if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6300     if (NSD->isAnonymousNamespace()) {
6301       S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6302       // Do not want to attach the attribute to the namespace because that will
6303       // cause confusing diagnostic reports for uses of declarations within the
6304       // namespace.
6305       return;
6306     }
6307   }
6308 
6309   // Handle the cases where the attribute has a text message.
6310   StringRef Str, Replacement;
6311   if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6312       !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6313     return;
6314 
6315   // Only support a single optional message for Declspec and CXX11.
6316   if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6317     checkAttributeAtMostNumArgs(S, AL, 1);
6318   else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6319            !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6320     return;
6321 
6322   if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6323     S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6324 
6325   D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
6326 }
6327 
6328 static bool isGlobalVar(const Decl *D) {
6329   if (const auto *S = dyn_cast<VarDecl>(D))
6330     return S->hasGlobalStorage();
6331   return false;
6332 }
6333 
6334 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6335   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6336     return;
6337 
6338   std::vector<StringRef> Sanitizers;
6339 
6340   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6341     StringRef SanitizerName;
6342     SourceLocation LiteralLoc;
6343 
6344     if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6345       return;
6346 
6347     if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
6348         SanitizerMask())
6349       S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6350     else if (isGlobalVar(D) && SanitizerName != "address")
6351       S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6352           << AL << ExpectedFunctionOrMethod;
6353     Sanitizers.push_back(SanitizerName);
6354   }
6355 
6356   D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
6357                                               Sanitizers.size()));
6358 }
6359 
6360 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6361                                          const ParsedAttr &AL) {
6362   StringRef AttrName = AL.getAttrName()->getName();
6363   normalizeName(AttrName);
6364   StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6365                                 .Case("no_address_safety_analysis", "address")
6366                                 .Case("no_sanitize_address", "address")
6367                                 .Case("no_sanitize_thread", "thread")
6368                                 .Case("no_sanitize_memory", "memory");
6369   if (isGlobalVar(D) && SanitizerName != "address")
6370     S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6371         << AL << ExpectedFunction;
6372 
6373   // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
6374   // NoSanitizeAttr object; but we need to calculate the correct spelling list
6375   // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
6376   // has the same spellings as the index for NoSanitizeAttr. We don't have a
6377   // general way to "translate" between the two, so this hack attempts to work
6378   // around the issue with hard-coded indicies. This is critical for calling
6379   // getSpelling() or prettyPrint() on the resulting semantic attribute object
6380   // without failing assertions.
6381   unsigned TranslatedSpellingIndex = 0;
6382   if (AL.isC2xAttribute() || AL.isCXX11Attribute())
6383     TranslatedSpellingIndex = 1;
6384 
6385   AttributeCommonInfo Info = AL;
6386   Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
6387   D->addAttr(::new (S.Context)
6388                  NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
6389 }
6390 
6391 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6392   if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6393     D->addAttr(Internal);
6394 }
6395 
6396 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6397   if (S.LangOpts.OpenCLVersion != 200)
6398     S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6399         << AL << "2.0" << 0;
6400   else
6401     S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6402                                                                    << "2.0";
6403 }
6404 
6405 /// Handles semantic checking for features that are common to all attributes,
6406 /// such as checking whether a parameter was properly specified, or the correct
6407 /// number of arguments were passed, etc.
6408 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6409                                           const ParsedAttr &AL) {
6410   // Several attributes carry different semantics than the parsing requires, so
6411   // those are opted out of the common argument checks.
6412   //
6413   // We also bail on unknown and ignored attributes because those are handled
6414   // as part of the target-specific handling logic.
6415   if (AL.getKind() == ParsedAttr::UnknownAttribute)
6416     return false;
6417   // Check whether the attribute requires specific language extensions to be
6418   // enabled.
6419   if (!AL.diagnoseLangOpts(S))
6420     return true;
6421   // Check whether the attribute appertains to the given subject.
6422   if (!AL.diagnoseAppertainsTo(S, D))
6423     return true;
6424   if (AL.hasCustomParsing())
6425     return false;
6426 
6427   if (AL.getMinArgs() == AL.getMaxArgs()) {
6428     // If there are no optional arguments, then checking for the argument count
6429     // is trivial.
6430     if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6431       return true;
6432   } else {
6433     // There are optional arguments, so checking is slightly more involved.
6434     if (AL.getMinArgs() &&
6435         !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6436       return true;
6437     else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6438              !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6439       return true;
6440   }
6441 
6442   if (S.CheckAttrTarget(AL))
6443     return true;
6444 
6445   return false;
6446 }
6447 
6448 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6449   if (D->isInvalidDecl())
6450     return;
6451 
6452   // Check if there is only one access qualifier.
6453   if (D->hasAttr<OpenCLAccessAttr>()) {
6454     if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6455         AL.getSemanticSpelling()) {
6456       S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6457           << AL.getAttrName()->getName() << AL.getRange();
6458     } else {
6459       S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6460           << D->getSourceRange();
6461       D->setInvalidDecl(true);
6462       return;
6463     }
6464   }
6465 
6466   // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6467   // image object can be read and written.
6468   // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6469   // object. Using the read_write (or __read_write) qualifier with the pipe
6470   // qualifier is a compilation error.
6471   if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6472     const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6473     if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
6474       if ((!S.getLangOpts().OpenCLCPlusPlus &&
6475            S.getLangOpts().OpenCLVersion < 200) ||
6476           DeclTy->isPipeType()) {
6477         S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6478             << AL << PDecl->getType() << DeclTy->isImageType();
6479         D->setInvalidDecl(true);
6480         return;
6481       }
6482     }
6483   }
6484 
6485   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
6486 }
6487 
6488 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6489   // The 'sycl_kernel' attribute applies only to function templates.
6490   const auto *FD = cast<FunctionDecl>(D);
6491   const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
6492   assert(FT && "Function template is expected");
6493 
6494   // Function template must have at least two template parameters.
6495   const TemplateParameterList *TL = FT->getTemplateParameters();
6496   if (TL->size() < 2) {
6497     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
6498     return;
6499   }
6500 
6501   // Template parameters must be typenames.
6502   for (unsigned I = 0; I < 2; ++I) {
6503     const NamedDecl *TParam = TL->getParam(I);
6504     if (isa<NonTypeTemplateParmDecl>(TParam)) {
6505       S.Diag(FT->getLocation(),
6506              diag::warn_sycl_kernel_invalid_template_param_type);
6507       return;
6508     }
6509   }
6510 
6511   // Function must have at least one argument.
6512   if (getFunctionOrMethodNumParams(D) != 1) {
6513     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
6514     return;
6515   }
6516 
6517   // Function must return void.
6518   QualType RetTy = getFunctionOrMethodResultType(D);
6519   if (!RetTy->isVoidType()) {
6520     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
6521     return;
6522   }
6523 
6524   handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
6525 }
6526 
6527 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6528   if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6529     S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6530         << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6531     return;
6532   }
6533 
6534   if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6535     handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6536   else
6537     handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6538 }
6539 
6540 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6541   assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6542          "uninitialized is only valid on automatic duration variables");
6543   D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
6544 }
6545 
6546 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6547                                         bool DiagnoseFailure) {
6548   QualType Ty = VD->getType();
6549   if (!Ty->isObjCRetainableType()) {
6550     if (DiagnoseFailure) {
6551       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6552           << 0;
6553     }
6554     return false;
6555   }
6556 
6557   Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6558 
6559   // Sema::inferObjCARCLifetime must run after processing decl attributes
6560   // (because __block lowers to an attribute), so if the lifetime hasn't been
6561   // explicitly specified, infer it locally now.
6562   if (LifetimeQual == Qualifiers::OCL_None)
6563     LifetimeQual = Ty->getObjCARCImplicitLifetime();
6564 
6565   // The attributes only really makes sense for __strong variables; ignore any
6566   // attempts to annotate a parameter with any other lifetime qualifier.
6567   if (LifetimeQual != Qualifiers::OCL_Strong) {
6568     if (DiagnoseFailure) {
6569       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6570           << 1;
6571     }
6572     return false;
6573   }
6574 
6575   // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6576   // to ensure that the variable is 'const' so that we can error on
6577   // modification, which can otherwise over-release.
6578   VD->setType(Ty.withConst());
6579   VD->setARCPseudoStrong(true);
6580   return true;
6581 }
6582 
6583 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6584                                              const ParsedAttr &AL) {
6585   if (auto *VD = dyn_cast<VarDecl>(D)) {
6586     assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6587     if (!VD->hasLocalStorage()) {
6588       S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6589           << 0;
6590       return;
6591     }
6592 
6593     if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6594       return;
6595 
6596     handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6597     return;
6598   }
6599 
6600   // If D is a function-like declaration (method, block, or function), then we
6601   // make every parameter psuedo-strong.
6602   unsigned NumParams =
6603       hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
6604   for (unsigned I = 0; I != NumParams; ++I) {
6605     auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6606     QualType Ty = PVD->getType();
6607 
6608     // If a user wrote a parameter with __strong explicitly, then assume they
6609     // want "real" strong semantics for that parameter. This works because if
6610     // the parameter was written with __strong, then the strong qualifier will
6611     // be non-local.
6612     if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6613         Qualifiers::OCL_Strong)
6614       continue;
6615 
6616     tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6617   }
6618   handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6619 }
6620 
6621 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6622   // Check that the return type is a `typedef int kern_return_t` or a typedef
6623   // around it, because otherwise MIG convention checks make no sense.
6624   // BlockDecl doesn't store a return type, so it's annoying to check,
6625   // so let's skip it for now.
6626   if (!isa<BlockDecl>(D)) {
6627     QualType T = getFunctionOrMethodResultType(D);
6628     bool IsKernReturnT = false;
6629     while (const auto *TT = T->getAs<TypedefType>()) {
6630       IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
6631       T = TT->desugar();
6632     }
6633     if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
6634       S.Diag(D->getBeginLoc(),
6635              diag::warn_mig_server_routine_does_not_return_kern_return_t);
6636       return;
6637     }
6638   }
6639 
6640   handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
6641 }
6642 
6643 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6644   // Warn if the return type is not a pointer or reference type.
6645   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6646     QualType RetTy = FD->getReturnType();
6647     if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
6648       S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
6649           << AL.getRange() << RetTy;
6650       return;
6651     }
6652   }
6653 
6654   handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
6655 }
6656 
6657 static void handeAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6658   if (AL.isUsedAsTypeAttr())
6659     return;
6660   // Warn if the parameter is definitely not an output parameter.
6661   if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
6662     if (PVD->getType()->isIntegerType()) {
6663       S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
6664           << AL.getRange();
6665       return;
6666     }
6667   }
6668   StringRef Argument;
6669   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
6670     return;
6671   D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
6672 }
6673 
6674 template<typename Attr>
6675 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6676   StringRef Argument;
6677   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
6678     return;
6679   D->addAttr(Attr::Create(S.Context, Argument, AL));
6680 }
6681 
6682 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6683   // The guard attribute takes a single identifier argument.
6684 
6685   if (!AL.isArgIdent(0)) {
6686     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6687         << AL << AANT_ArgumentIdentifier;
6688     return;
6689   }
6690 
6691   CFGuardAttr::GuardArg Arg;
6692   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6693   if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
6694     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6695     return;
6696   }
6697 
6698   D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
6699 }
6700 
6701 //===----------------------------------------------------------------------===//
6702 // Top Level Sema Entry Points
6703 //===----------------------------------------------------------------------===//
6704 
6705 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6706 /// the attribute applies to decls.  If the attribute is a type attribute, just
6707 /// silently ignore it if a GNU attribute.
6708 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6709                                  const ParsedAttr &AL,
6710                                  bool IncludeCXX11Attributes) {
6711   if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6712     return;
6713 
6714   // Ignore C++11 attributes on declarator chunks: they appertain to the type
6715   // instead.
6716   if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6717     return;
6718 
6719   // Unknown attributes are automatically warned on. Target-specific attributes
6720   // which do not apply to the current target architecture are treated as
6721   // though they were unknown attributes.
6722   if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6723       !AL.existsInTarget(S.Context.getTargetInfo())) {
6724     S.Diag(AL.getLoc(),
6725            AL.isDeclspecAttribute()
6726                ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6727                : (unsigned)diag::warn_unknown_attribute_ignored)
6728         << AL;
6729     return;
6730   }
6731 
6732   if (handleCommonAttributeFeatures(S, D, AL))
6733     return;
6734 
6735   switch (AL.getKind()) {
6736   default:
6737     if (!AL.isStmtAttr()) {
6738       // Type attributes are handled elsewhere; silently move on.
6739       assert(AL.isTypeAttr() && "Non-type attribute not handled");
6740       break;
6741     }
6742     S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6743         << AL << D->getLocation();
6744     break;
6745   case ParsedAttr::AT_Interrupt:
6746     handleInterruptAttr(S, D, AL);
6747     break;
6748   case ParsedAttr::AT_X86ForceAlignArgPointer:
6749     handleX86ForceAlignArgPointerAttr(S, D, AL);
6750     break;
6751   case ParsedAttr::AT_DLLExport:
6752   case ParsedAttr::AT_DLLImport:
6753     handleDLLAttr(S, D, AL);
6754     break;
6755   case ParsedAttr::AT_Mips16:
6756     handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6757                                         MipsInterruptAttr>(S, D, AL);
6758     break;
6759   case ParsedAttr::AT_NoMips16:
6760     handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6761     break;
6762   case ParsedAttr::AT_MicroMips:
6763     handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6764     break;
6765   case ParsedAttr::AT_NoMicroMips:
6766     handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6767     break;
6768   case ParsedAttr::AT_MipsLongCall:
6769     handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6770         S, D, AL);
6771     break;
6772   case ParsedAttr::AT_MipsShortCall:
6773     handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6774         S, D, AL);
6775     break;
6776   case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6777     handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6778     break;
6779   case ParsedAttr::AT_AMDGPUWavesPerEU:
6780     handleAMDGPUWavesPerEUAttr(S, D, AL);
6781     break;
6782   case ParsedAttr::AT_AMDGPUNumSGPR:
6783     handleAMDGPUNumSGPRAttr(S, D, AL);
6784     break;
6785   case ParsedAttr::AT_AMDGPUNumVGPR:
6786     handleAMDGPUNumVGPRAttr(S, D, AL);
6787     break;
6788   case ParsedAttr::AT_AVRSignal:
6789     handleAVRSignalAttr(S, D, AL);
6790     break;
6791   case ParsedAttr::AT_BPFPreserveAccessIndex:
6792     handleBPFPreserveAccessIndexAttr(S, D, AL);
6793     break;
6794   case ParsedAttr::AT_WebAssemblyExportName:
6795     handleWebAssemblyExportNameAttr(S, D, AL);
6796     break;
6797   case ParsedAttr::AT_WebAssemblyImportModule:
6798     handleWebAssemblyImportModuleAttr(S, D, AL);
6799     break;
6800   case ParsedAttr::AT_WebAssemblyImportName:
6801     handleWebAssemblyImportNameAttr(S, D, AL);
6802     break;
6803   case ParsedAttr::AT_IBAction:
6804     handleSimpleAttribute<IBActionAttr>(S, D, AL);
6805     break;
6806   case ParsedAttr::AT_IBOutlet:
6807     handleIBOutlet(S, D, AL);
6808     break;
6809   case ParsedAttr::AT_IBOutletCollection:
6810     handleIBOutletCollection(S, D, AL);
6811     break;
6812   case ParsedAttr::AT_IFunc:
6813     handleIFuncAttr(S, D, AL);
6814     break;
6815   case ParsedAttr::AT_Alias:
6816     handleAliasAttr(S, D, AL);
6817     break;
6818   case ParsedAttr::AT_Aligned:
6819     handleAlignedAttr(S, D, AL);
6820     break;
6821   case ParsedAttr::AT_AlignValue:
6822     handleAlignValueAttr(S, D, AL);
6823     break;
6824   case ParsedAttr::AT_AllocSize:
6825     handleAllocSizeAttr(S, D, AL);
6826     break;
6827   case ParsedAttr::AT_AlwaysInline:
6828     handleAlwaysInlineAttr(S, D, AL);
6829     break;
6830   case ParsedAttr::AT_Artificial:
6831     handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6832     break;
6833   case ParsedAttr::AT_AnalyzerNoReturn:
6834     handleAnalyzerNoReturnAttr(S, D, AL);
6835     break;
6836   case ParsedAttr::AT_TLSModel:
6837     handleTLSModelAttr(S, D, AL);
6838     break;
6839   case ParsedAttr::AT_Annotate:
6840     handleAnnotateAttr(S, D, AL);
6841     break;
6842   case ParsedAttr::AT_Availability:
6843     handleAvailabilityAttr(S, D, AL);
6844     break;
6845   case ParsedAttr::AT_CarriesDependency:
6846     handleDependencyAttr(S, scope, D, AL);
6847     break;
6848   case ParsedAttr::AT_CPUDispatch:
6849   case ParsedAttr::AT_CPUSpecific:
6850     handleCPUSpecificAttr(S, D, AL);
6851     break;
6852   case ParsedAttr::AT_Common:
6853     handleCommonAttr(S, D, AL);
6854     break;
6855   case ParsedAttr::AT_CUDAConstant:
6856     handleConstantAttr(S, D, AL);
6857     break;
6858   case ParsedAttr::AT_PassObjectSize:
6859     handlePassObjectSizeAttr(S, D, AL);
6860     break;
6861   case ParsedAttr::AT_Constructor:
6862     handleConstructorAttr(S, D, AL);
6863     break;
6864   case ParsedAttr::AT_CXX11NoReturn:
6865     handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6866     break;
6867   case ParsedAttr::AT_Deprecated:
6868     handleDeprecatedAttr(S, D, AL);
6869     break;
6870   case ParsedAttr::AT_Destructor:
6871     handleDestructorAttr(S, D, AL);
6872     break;
6873   case ParsedAttr::AT_EnableIf:
6874     handleEnableIfAttr(S, D, AL);
6875     break;
6876   case ParsedAttr::AT_DiagnoseIf:
6877     handleDiagnoseIfAttr(S, D, AL);
6878     break;
6879   case ParsedAttr::AT_NoBuiltin:
6880     handleNoBuiltinAttr(S, D, AL);
6881     break;
6882   case ParsedAttr::AT_ExtVectorType:
6883     handleExtVectorTypeAttr(S, D, AL);
6884     break;
6885   case ParsedAttr::AT_ExternalSourceSymbol:
6886     handleExternalSourceSymbolAttr(S, D, AL);
6887     break;
6888   case ParsedAttr::AT_MinSize:
6889     handleMinSizeAttr(S, D, AL);
6890     break;
6891   case ParsedAttr::AT_OptimizeNone:
6892     handleOptimizeNoneAttr(S, D, AL);
6893     break;
6894   case ParsedAttr::AT_FlagEnum:
6895     handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6896     break;
6897   case ParsedAttr::AT_EnumExtensibility:
6898     handleEnumExtensibilityAttr(S, D, AL);
6899     break;
6900   case ParsedAttr::AT_Flatten:
6901     handleSimpleAttribute<FlattenAttr>(S, D, AL);
6902     break;
6903   case ParsedAttr::AT_SYCLKernel:
6904     handleSYCLKernelAttr(S, D, AL);
6905     break;
6906   case ParsedAttr::AT_Format:
6907     handleFormatAttr(S, D, AL);
6908     break;
6909   case ParsedAttr::AT_FormatArg:
6910     handleFormatArgAttr(S, D, AL);
6911     break;
6912   case ParsedAttr::AT_Callback:
6913     handleCallbackAttr(S, D, AL);
6914     break;
6915   case ParsedAttr::AT_CUDAGlobal:
6916     handleGlobalAttr(S, D, AL);
6917     break;
6918   case ParsedAttr::AT_CUDADevice:
6919     handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6920                                                                         AL);
6921     break;
6922   case ParsedAttr::AT_CUDAHost:
6923     handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6924     break;
6925   case ParsedAttr::AT_HIPPinnedShadow:
6926     handleSimpleAttributeWithExclusions<HIPPinnedShadowAttr, CUDADeviceAttr,
6927                                         CUDAConstantAttr>(S, D, AL);
6928     break;
6929   case ParsedAttr::AT_GNUInline:
6930     handleGNUInlineAttr(S, D, AL);
6931     break;
6932   case ParsedAttr::AT_CUDALaunchBounds:
6933     handleLaunchBoundsAttr(S, D, AL);
6934     break;
6935   case ParsedAttr::AT_Restrict:
6936     handleRestrictAttr(S, D, AL);
6937     break;
6938   case ParsedAttr::AT_LifetimeBound:
6939     handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6940     break;
6941   case ParsedAttr::AT_MayAlias:
6942     handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6943     break;
6944   case ParsedAttr::AT_Mode:
6945     handleModeAttr(S, D, AL);
6946     break;
6947   case ParsedAttr::AT_NoAlias:
6948     handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6949     break;
6950   case ParsedAttr::AT_NoCommon:
6951     handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6952     break;
6953   case ParsedAttr::AT_NoSplitStack:
6954     handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6955     break;
6956   case ParsedAttr::AT_NoUniqueAddress:
6957     handleSimpleAttribute<NoUniqueAddressAttr>(S, D, AL);
6958     break;
6959   case ParsedAttr::AT_NonNull:
6960     if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6961       handleNonNullAttrParameter(S, PVD, AL);
6962     else
6963       handleNonNullAttr(S, D, AL);
6964     break;
6965   case ParsedAttr::AT_ReturnsNonNull:
6966     handleReturnsNonNullAttr(S, D, AL);
6967     break;
6968   case ParsedAttr::AT_NoEscape:
6969     handleNoEscapeAttr(S, D, AL);
6970     break;
6971   case ParsedAttr::AT_AssumeAligned:
6972     handleAssumeAlignedAttr(S, D, AL);
6973     break;
6974   case ParsedAttr::AT_AllocAlign:
6975     handleAllocAlignAttr(S, D, AL);
6976     break;
6977   case ParsedAttr::AT_Overloadable:
6978     handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6979     break;
6980   case ParsedAttr::AT_Ownership:
6981     handleOwnershipAttr(S, D, AL);
6982     break;
6983   case ParsedAttr::AT_Cold:
6984     handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6985     break;
6986   case ParsedAttr::AT_Hot:
6987     handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6988     break;
6989   case ParsedAttr::AT_Naked:
6990     handleNakedAttr(S, D, AL);
6991     break;
6992   case ParsedAttr::AT_NoReturn:
6993     handleNoReturnAttr(S, D, AL);
6994     break;
6995   case ParsedAttr::AT_AnyX86NoCfCheck:
6996     handleNoCfCheckAttr(S, D, AL);
6997     break;
6998   case ParsedAttr::AT_NoThrow:
6999     if (!AL.isUsedAsTypeAttr())
7000       handleSimpleAttribute<NoThrowAttr>(S, D, AL);
7001     break;
7002   case ParsedAttr::AT_CUDAShared:
7003     handleSharedAttr(S, D, AL);
7004     break;
7005   case ParsedAttr::AT_VecReturn:
7006     handleVecReturnAttr(S, D, AL);
7007     break;
7008   case ParsedAttr::AT_ObjCOwnership:
7009     handleObjCOwnershipAttr(S, D, AL);
7010     break;
7011   case ParsedAttr::AT_ObjCPreciseLifetime:
7012     handleObjCPreciseLifetimeAttr(S, D, AL);
7013     break;
7014   case ParsedAttr::AT_ObjCReturnsInnerPointer:
7015     handleObjCReturnsInnerPointerAttr(S, D, AL);
7016     break;
7017   case ParsedAttr::AT_ObjCRequiresSuper:
7018     handleObjCRequiresSuperAttr(S, D, AL);
7019     break;
7020   case ParsedAttr::AT_ObjCBridge:
7021     handleObjCBridgeAttr(S, D, AL);
7022     break;
7023   case ParsedAttr::AT_ObjCBridgeMutable:
7024     handleObjCBridgeMutableAttr(S, D, AL);
7025     break;
7026   case ParsedAttr::AT_ObjCBridgeRelated:
7027     handleObjCBridgeRelatedAttr(S, D, AL);
7028     break;
7029   case ParsedAttr::AT_ObjCDesignatedInitializer:
7030     handleObjCDesignatedInitializer(S, D, AL);
7031     break;
7032   case ParsedAttr::AT_ObjCRuntimeName:
7033     handleObjCRuntimeName(S, D, AL);
7034     break;
7035   case ParsedAttr::AT_ObjCRuntimeVisible:
7036     handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
7037     break;
7038   case ParsedAttr::AT_ObjCBoxable:
7039     handleObjCBoxable(S, D, AL);
7040     break;
7041   case ParsedAttr::AT_CFAuditedTransfer:
7042     handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
7043                                         CFUnknownTransferAttr>(S, D, AL);
7044     break;
7045   case ParsedAttr::AT_CFUnknownTransfer:
7046     handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
7047                                         CFAuditedTransferAttr>(S, D, AL);
7048     break;
7049   case ParsedAttr::AT_CFConsumed:
7050   case ParsedAttr::AT_NSConsumed:
7051   case ParsedAttr::AT_OSConsumed:
7052     S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
7053                        /*IsTemplateInstantiation=*/false);
7054     break;
7055   case ParsedAttr::AT_NSConsumesSelf:
7056     handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
7057     break;
7058   case ParsedAttr::AT_OSConsumesThis:
7059     handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
7060     break;
7061   case ParsedAttr::AT_OSReturnsRetainedOnZero:
7062     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
7063         S, D, AL, isValidOSObjectOutParameter(D),
7064         diag::warn_ns_attribute_wrong_parameter_type,
7065         /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
7066     break;
7067   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
7068     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
7069         S, D, AL, isValidOSObjectOutParameter(D),
7070         diag::warn_ns_attribute_wrong_parameter_type,
7071         /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
7072     break;
7073   case ParsedAttr::AT_NSReturnsAutoreleased:
7074   case ParsedAttr::AT_NSReturnsNotRetained:
7075   case ParsedAttr::AT_NSReturnsRetained:
7076   case ParsedAttr::AT_CFReturnsNotRetained:
7077   case ParsedAttr::AT_CFReturnsRetained:
7078   case ParsedAttr::AT_OSReturnsNotRetained:
7079   case ParsedAttr::AT_OSReturnsRetained:
7080     handleXReturnsXRetainedAttr(S, D, AL);
7081     break;
7082   case ParsedAttr::AT_WorkGroupSizeHint:
7083     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
7084     break;
7085   case ParsedAttr::AT_ReqdWorkGroupSize:
7086     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
7087     break;
7088   case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
7089     handleSubGroupSize(S, D, AL);
7090     break;
7091   case ParsedAttr::AT_VecTypeHint:
7092     handleVecTypeHint(S, D, AL);
7093     break;
7094   case ParsedAttr::AT_ConstInit:
7095     handleSimpleAttribute<ConstInitAttr>(S, D, AL);
7096     break;
7097   case ParsedAttr::AT_InitPriority:
7098     handleInitPriorityAttr(S, D, AL);
7099     break;
7100   case ParsedAttr::AT_Packed:
7101     handlePackedAttr(S, D, AL);
7102     break;
7103   case ParsedAttr::AT_Section:
7104     handleSectionAttr(S, D, AL);
7105     break;
7106   case ParsedAttr::AT_SpeculativeLoadHardening:
7107     handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
7108                                         NoSpeculativeLoadHardeningAttr>(S, D,
7109                                                                         AL);
7110     break;
7111   case ParsedAttr::AT_NoSpeculativeLoadHardening:
7112     handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
7113                                         SpeculativeLoadHardeningAttr>(S, D, AL);
7114     break;
7115   case ParsedAttr::AT_CodeSeg:
7116     handleCodeSegAttr(S, D, AL);
7117     break;
7118   case ParsedAttr::AT_Target:
7119     handleTargetAttr(S, D, AL);
7120     break;
7121   case ParsedAttr::AT_MinVectorWidth:
7122     handleMinVectorWidthAttr(S, D, AL);
7123     break;
7124   case ParsedAttr::AT_Unavailable:
7125     handleAttrWithMessage<UnavailableAttr>(S, D, AL);
7126     break;
7127   case ParsedAttr::AT_ArcWeakrefUnavailable:
7128     handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
7129     break;
7130   case ParsedAttr::AT_ObjCRootClass:
7131     handleSimpleAttribute<ObjCRootClassAttr>(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_ObjCNonLazyClass:
7141     handleSimpleAttribute<ObjCNonLazyClassAttr>(S, D, AL);
7142     break;
7143   case ParsedAttr::AT_ObjCSubclassingRestricted:
7144     handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
7145     break;
7146   case ParsedAttr::AT_ObjCClassStub:
7147     handleSimpleAttribute<ObjCClassStubAttr>(S, D, AL);
7148     break;
7149   case ParsedAttr::AT_ObjCExplicitProtocolImpl:
7150     handleObjCSuppresProtocolAttr(S, D, AL);
7151     break;
7152   case ParsedAttr::AT_ObjCRequiresPropertyDefs:
7153     handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
7154     break;
7155   case ParsedAttr::AT_Unused:
7156     handleUnusedAttr(S, D, AL);
7157     break;
7158   case ParsedAttr::AT_ReturnsTwice:
7159     handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
7160     break;
7161   case ParsedAttr::AT_NotTailCalled:
7162     handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
7163         S, D, AL);
7164     break;
7165   case ParsedAttr::AT_DisableTailCalls:
7166     handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
7167                                                                          AL);
7168     break;
7169   case ParsedAttr::AT_Used:
7170     handleSimpleAttribute<UsedAttr>(S, D, AL);
7171     break;
7172   case ParsedAttr::AT_Visibility:
7173     handleVisibilityAttr(S, D, AL, false);
7174     break;
7175   case ParsedAttr::AT_TypeVisibility:
7176     handleVisibilityAttr(S, D, AL, true);
7177     break;
7178   case ParsedAttr::AT_WarnUnused:
7179     handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
7180     break;
7181   case ParsedAttr::AT_WarnUnusedResult:
7182     handleWarnUnusedResult(S, D, AL);
7183     break;
7184   case ParsedAttr::AT_Weak:
7185     handleSimpleAttribute<WeakAttr>(S, D, AL);
7186     break;
7187   case ParsedAttr::AT_WeakRef:
7188     handleWeakRefAttr(S, D, AL);
7189     break;
7190   case ParsedAttr::AT_WeakImport:
7191     handleWeakImportAttr(S, D, AL);
7192     break;
7193   case ParsedAttr::AT_TransparentUnion:
7194     handleTransparentUnionAttr(S, D, AL);
7195     break;
7196   case ParsedAttr::AT_ObjCException:
7197     handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
7198     break;
7199   case ParsedAttr::AT_ObjCMethodFamily:
7200     handleObjCMethodFamilyAttr(S, D, AL);
7201     break;
7202   case ParsedAttr::AT_ObjCNSObject:
7203     handleObjCNSObject(S, D, AL);
7204     break;
7205   case ParsedAttr::AT_ObjCIndependentClass:
7206     handleObjCIndependentClass(S, D, AL);
7207     break;
7208   case ParsedAttr::AT_Blocks:
7209     handleBlocksAttr(S, D, AL);
7210     break;
7211   case ParsedAttr::AT_Sentinel:
7212     handleSentinelAttr(S, D, AL);
7213     break;
7214   case ParsedAttr::AT_Const:
7215     handleSimpleAttribute<ConstAttr>(S, D, AL);
7216     break;
7217   case ParsedAttr::AT_Pure:
7218     handleSimpleAttribute<PureAttr>(S, D, AL);
7219     break;
7220   case ParsedAttr::AT_Cleanup:
7221     handleCleanupAttr(S, D, AL);
7222     break;
7223   case ParsedAttr::AT_NoDebug:
7224     handleNoDebugAttr(S, D, AL);
7225     break;
7226   case ParsedAttr::AT_NoDuplicate:
7227     handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
7228     break;
7229   case ParsedAttr::AT_Convergent:
7230     handleSimpleAttribute<ConvergentAttr>(S, D, AL);
7231     break;
7232   case ParsedAttr::AT_NoInline:
7233     handleSimpleAttribute<NoInlineAttr>(S, D, AL);
7234     break;
7235   case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
7236     handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
7237     break;
7238   case ParsedAttr::AT_NoStackProtector:
7239     // Interacts with -fstack-protector options.
7240     handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
7241     break;
7242   case ParsedAttr::AT_CFICanonicalJumpTable:
7243     handleSimpleAttribute<CFICanonicalJumpTableAttr>(S, D, AL);
7244     break;
7245   case ParsedAttr::AT_StdCall:
7246   case ParsedAttr::AT_CDecl:
7247   case ParsedAttr::AT_FastCall:
7248   case ParsedAttr::AT_ThisCall:
7249   case ParsedAttr::AT_Pascal:
7250   case ParsedAttr::AT_RegCall:
7251   case ParsedAttr::AT_SwiftCall:
7252   case ParsedAttr::AT_VectorCall:
7253   case ParsedAttr::AT_MSABI:
7254   case ParsedAttr::AT_SysVABI:
7255   case ParsedAttr::AT_Pcs:
7256   case ParsedAttr::AT_IntelOclBicc:
7257   case ParsedAttr::AT_PreserveMost:
7258   case ParsedAttr::AT_PreserveAll:
7259   case ParsedAttr::AT_AArch64VectorPcs:
7260     handleCallConvAttr(S, D, AL);
7261     break;
7262   case ParsedAttr::AT_Suppress:
7263     handleSuppressAttr(S, D, AL);
7264     break;
7265   case ParsedAttr::AT_Owner:
7266   case ParsedAttr::AT_Pointer:
7267     handleLifetimeCategoryAttr(S, D, AL);
7268     break;
7269   case ParsedAttr::AT_OpenCLKernel:
7270     handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
7271     break;
7272   case ParsedAttr::AT_OpenCLAccess:
7273     handleOpenCLAccessAttr(S, D, AL);
7274     break;
7275   case ParsedAttr::AT_OpenCLNoSVM:
7276     handleOpenCLNoSVMAttr(S, D, AL);
7277     break;
7278   case ParsedAttr::AT_SwiftContext:
7279     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
7280     break;
7281   case ParsedAttr::AT_SwiftErrorResult:
7282     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
7283     break;
7284   case ParsedAttr::AT_SwiftIndirectResult:
7285     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
7286     break;
7287   case ParsedAttr::AT_InternalLinkage:
7288     handleInternalLinkageAttr(S, D, AL);
7289     break;
7290   case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
7291     handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
7292     break;
7293   case ParsedAttr::AT_LTOVisibilityPublic:
7294     handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
7295     break;
7296 
7297   // Microsoft attributes:
7298   case ParsedAttr::AT_EmptyBases:
7299     handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
7300     break;
7301   case ParsedAttr::AT_LayoutVersion:
7302     handleLayoutVersion(S, D, AL);
7303     break;
7304   case ParsedAttr::AT_TrivialABI:
7305     handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
7306     break;
7307   case ParsedAttr::AT_MSNoVTable:
7308     handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
7309     break;
7310   case ParsedAttr::AT_MSStruct:
7311     handleSimpleAttribute<MSStructAttr>(S, D, AL);
7312     break;
7313   case ParsedAttr::AT_Uuid:
7314     handleUuidAttr(S, D, AL);
7315     break;
7316   case ParsedAttr::AT_MSInheritance:
7317     handleMSInheritanceAttr(S, D, AL);
7318     break;
7319   case ParsedAttr::AT_SelectAny:
7320     handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
7321     break;
7322   case ParsedAttr::AT_Thread:
7323     handleDeclspecThreadAttr(S, D, AL);
7324     break;
7325 
7326   case ParsedAttr::AT_AbiTag:
7327     handleAbiTagAttr(S, D, AL);
7328     break;
7329   case ParsedAttr::AT_CFGuard:
7330     handleCFGuardAttr(S, D, AL);
7331     break;
7332 
7333   // Thread safety attributes:
7334   case ParsedAttr::AT_AssertExclusiveLock:
7335     handleAssertExclusiveLockAttr(S, D, AL);
7336     break;
7337   case ParsedAttr::AT_AssertSharedLock:
7338     handleAssertSharedLockAttr(S, D, AL);
7339     break;
7340   case ParsedAttr::AT_GuardedVar:
7341     handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
7342     break;
7343   case ParsedAttr::AT_PtGuardedVar:
7344     handlePtGuardedVarAttr(S, D, AL);
7345     break;
7346   case ParsedAttr::AT_ScopedLockable:
7347     handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
7348     break;
7349   case ParsedAttr::AT_NoSanitize:
7350     handleNoSanitizeAttr(S, D, AL);
7351     break;
7352   case ParsedAttr::AT_NoSanitizeSpecific:
7353     handleNoSanitizeSpecificAttr(S, D, AL);
7354     break;
7355   case ParsedAttr::AT_NoThreadSafetyAnalysis:
7356     handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
7357     break;
7358   case ParsedAttr::AT_GuardedBy:
7359     handleGuardedByAttr(S, D, AL);
7360     break;
7361   case ParsedAttr::AT_PtGuardedBy:
7362     handlePtGuardedByAttr(S, D, AL);
7363     break;
7364   case ParsedAttr::AT_ExclusiveTrylockFunction:
7365     handleExclusiveTrylockFunctionAttr(S, D, AL);
7366     break;
7367   case ParsedAttr::AT_LockReturned:
7368     handleLockReturnedAttr(S, D, AL);
7369     break;
7370   case ParsedAttr::AT_LocksExcluded:
7371     handleLocksExcludedAttr(S, D, AL);
7372     break;
7373   case ParsedAttr::AT_SharedTrylockFunction:
7374     handleSharedTrylockFunctionAttr(S, D, AL);
7375     break;
7376   case ParsedAttr::AT_AcquiredBefore:
7377     handleAcquiredBeforeAttr(S, D, AL);
7378     break;
7379   case ParsedAttr::AT_AcquiredAfter:
7380     handleAcquiredAfterAttr(S, D, AL);
7381     break;
7382 
7383   // Capability analysis attributes.
7384   case ParsedAttr::AT_Capability:
7385   case ParsedAttr::AT_Lockable:
7386     handleCapabilityAttr(S, D, AL);
7387     break;
7388   case ParsedAttr::AT_RequiresCapability:
7389     handleRequiresCapabilityAttr(S, D, AL);
7390     break;
7391 
7392   case ParsedAttr::AT_AssertCapability:
7393     handleAssertCapabilityAttr(S, D, AL);
7394     break;
7395   case ParsedAttr::AT_AcquireCapability:
7396     handleAcquireCapabilityAttr(S, D, AL);
7397     break;
7398   case ParsedAttr::AT_ReleaseCapability:
7399     handleReleaseCapabilityAttr(S, D, AL);
7400     break;
7401   case ParsedAttr::AT_TryAcquireCapability:
7402     handleTryAcquireCapabilityAttr(S, D, AL);
7403     break;
7404 
7405   // Consumed analysis attributes.
7406   case ParsedAttr::AT_Consumable:
7407     handleConsumableAttr(S, D, AL);
7408     break;
7409   case ParsedAttr::AT_ConsumableAutoCast:
7410     handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
7411     break;
7412   case ParsedAttr::AT_ConsumableSetOnRead:
7413     handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
7414     break;
7415   case ParsedAttr::AT_CallableWhen:
7416     handleCallableWhenAttr(S, D, AL);
7417     break;
7418   case ParsedAttr::AT_ParamTypestate:
7419     handleParamTypestateAttr(S, D, AL);
7420     break;
7421   case ParsedAttr::AT_ReturnTypestate:
7422     handleReturnTypestateAttr(S, D, AL);
7423     break;
7424   case ParsedAttr::AT_SetTypestate:
7425     handleSetTypestateAttr(S, D, AL);
7426     break;
7427   case ParsedAttr::AT_TestTypestate:
7428     handleTestTypestateAttr(S, D, AL);
7429     break;
7430 
7431   // Type safety attributes.
7432   case ParsedAttr::AT_ArgumentWithTypeTag:
7433     handleArgumentWithTypeTagAttr(S, D, AL);
7434     break;
7435   case ParsedAttr::AT_TypeTagForDatatype:
7436     handleTypeTagForDatatypeAttr(S, D, AL);
7437     break;
7438   case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
7439     handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
7440     break;
7441   case ParsedAttr::AT_RenderScriptKernel:
7442     handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
7443     break;
7444   // XRay attributes.
7445   case ParsedAttr::AT_XRayInstrument:
7446     handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
7447     break;
7448   case ParsedAttr::AT_XRayLogArgs:
7449     handleXRayLogArgsAttr(S, D, AL);
7450     break;
7451 
7452   case ParsedAttr::AT_PatchableFunctionEntry:
7453     handlePatchableFunctionEntryAttr(S, D, AL);
7454     break;
7455 
7456   // Move semantics attribute.
7457   case ParsedAttr::AT_Reinitializes:
7458     handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7459     break;
7460 
7461   case ParsedAttr::AT_AlwaysDestroy:
7462   case ParsedAttr::AT_NoDestroy:
7463     handleDestroyAttr(S, D, AL);
7464     break;
7465 
7466   case ParsedAttr::AT_Uninitialized:
7467     handleUninitializedAttr(S, D, AL);
7468     break;
7469 
7470   case ParsedAttr::AT_ObjCExternallyRetained:
7471     handleObjCExternallyRetainedAttr(S, D, AL);
7472     break;
7473 
7474   case ParsedAttr::AT_MIGServerRoutine:
7475     handleMIGServerRoutineAttr(S, D, AL);
7476     break;
7477 
7478   case ParsedAttr::AT_MSAllocator:
7479     handleMSAllocatorAttr(S, D, AL);
7480     break;
7481 
7482   case ParsedAttr::AT_ArmBuiltinAlias:
7483     handleArmBuiltinAliasAttr(S, D, AL);
7484     break;
7485 
7486   case ParsedAttr::AT_AcquireHandle:
7487     handeAcquireHandleAttr(S, D, AL);
7488     break;
7489 
7490   case ParsedAttr::AT_ReleaseHandle:
7491     handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
7492     break;
7493 
7494   case ParsedAttr::AT_UseHandle:
7495     handleHandleAttr<UseHandleAttr>(S, D, AL);
7496     break;
7497   }
7498 }
7499 
7500 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7501 /// attribute list to the specified decl, ignoring any type attributes.
7502 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7503                                     const ParsedAttributesView &AttrList,
7504                                     bool IncludeCXX11Attributes) {
7505   if (AttrList.empty())
7506     return;
7507 
7508   for (const ParsedAttr &AL : AttrList)
7509     ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7510 
7511   // FIXME: We should be able to handle these cases in TableGen.
7512   // GCC accepts
7513   // static int a9 __attribute__((weakref));
7514   // but that looks really pointless. We reject it.
7515   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7516     Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7517         << cast<NamedDecl>(D);
7518     D->dropAttr<WeakRefAttr>();
7519     return;
7520   }
7521 
7522   // FIXME: We should be able to handle this in TableGen as well. It would be
7523   // good to have a way to specify "these attributes must appear as a group",
7524   // for these. Additionally, it would be good to have a way to specify "these
7525   // attribute must never appear as a group" for attributes like cold and hot.
7526   if (!D->hasAttr<OpenCLKernelAttr>()) {
7527     // These attributes cannot be applied to a non-kernel function.
7528     if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7529       // FIXME: This emits a different error message than
7530       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7531       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7532       D->setInvalidDecl();
7533     } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7534       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7535       D->setInvalidDecl();
7536     } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7537       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7538       D->setInvalidDecl();
7539     } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7540       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7541       D->setInvalidDecl();
7542     } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7543       if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7544         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7545             << A << ExpectedKernelFunction;
7546         D->setInvalidDecl();
7547       } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7548         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7549             << A << ExpectedKernelFunction;
7550         D->setInvalidDecl();
7551       } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7552         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7553             << A << ExpectedKernelFunction;
7554         D->setInvalidDecl();
7555       } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7556         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7557             << A << ExpectedKernelFunction;
7558         D->setInvalidDecl();
7559       }
7560     }
7561   }
7562 
7563   // Do this check after processing D's attributes because the attribute
7564   // objc_method_family can change whether the given method is in the init
7565   // family, and it can be applied after objc_designated_initializer. This is a
7566   // bit of a hack, but we need it to be compatible with versions of clang that
7567   // processed the attribute list in the wrong order.
7568   if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7569       cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7570     Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7571     D->dropAttr<ObjCDesignatedInitializerAttr>();
7572   }
7573 }
7574 
7575 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
7576 // attribute.
7577 void Sema::ProcessDeclAttributeDelayed(Decl *D,
7578                                        const ParsedAttributesView &AttrList) {
7579   for (const ParsedAttr &AL : AttrList)
7580     if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7581       handleTransparentUnionAttr(*this, D, AL);
7582       break;
7583     }
7584 
7585   // For BPFPreserveAccessIndexAttr, we want to populate the attributes
7586   // to fields and inner records as well.
7587   if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
7588     handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
7589 }
7590 
7591 // Annotation attributes are the only attributes allowed after an access
7592 // specifier.
7593 bool Sema::ProcessAccessDeclAttributeList(
7594     AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7595   for (const ParsedAttr &AL : AttrList) {
7596     if (AL.getKind() == ParsedAttr::AT_Annotate) {
7597       ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7598     } else {
7599       Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7600       return true;
7601     }
7602   }
7603   return false;
7604 }
7605 
7606 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7607 /// contains any decl attributes that we should warn about.
7608 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7609   for (const ParsedAttr &AL : A) {
7610     // Only warn if the attribute is an unignored, non-type attribute.
7611     if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7612       continue;
7613     if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7614       continue;
7615 
7616     if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7617       S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7618           << AL << AL.getRange();
7619     } else {
7620       S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7621                                                             << AL.getRange();
7622     }
7623   }
7624 }
7625 
7626 /// checkUnusedDeclAttributes - Given a declarator which is not being
7627 /// used to build a declaration, complain about any decl attributes
7628 /// which might be lying around on it.
7629 void Sema::checkUnusedDeclAttributes(Declarator &D) {
7630   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7631   ::checkUnusedDeclAttributes(*this, D.getAttributes());
7632   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7633     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7634 }
7635 
7636 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7637 /// \#pragma weak needs a non-definition decl and source may not have one.
7638 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7639                                       SourceLocation Loc) {
7640   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7641   NamedDecl *NewD = nullptr;
7642   if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7643     FunctionDecl *NewFD;
7644     // FIXME: Missing call to CheckFunctionDeclaration().
7645     // FIXME: Mangling?
7646     // FIXME: Is the qualifier info correct?
7647     // FIXME: Is the DeclContext correct?
7648     NewFD = FunctionDecl::Create(
7649         FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
7650         DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
7651         false /*isInlineSpecified*/, FD->hasPrototype(), CSK_unspecified,
7652         FD->getTrailingRequiresClause());
7653     NewD = NewFD;
7654 
7655     if (FD->getQualifier())
7656       NewFD->setQualifierInfo(FD->getQualifierLoc());
7657 
7658     // Fake up parameter variables; they are declared as if this were
7659     // a typedef.
7660     QualType FDTy = FD->getType();
7661     if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7662       SmallVector<ParmVarDecl*, 16> Params;
7663       for (const auto &AI : FT->param_types()) {
7664         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7665         Param->setScopeInfo(0, Params.size());
7666         Params.push_back(Param);
7667       }
7668       NewFD->setParams(Params);
7669     }
7670   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7671     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7672                            VD->getInnerLocStart(), VD->getLocation(), II,
7673                            VD->getType(), VD->getTypeSourceInfo(),
7674                            VD->getStorageClass());
7675     if (VD->getQualifier())
7676       cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7677   }
7678   return NewD;
7679 }
7680 
7681 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7682 /// applied to it, possibly with an alias.
7683 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7684   if (W.getUsed()) return; // only do this once
7685   W.setUsed(true);
7686   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7687     IdentifierInfo *NDId = ND->getIdentifier();
7688     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7689     NewD->addAttr(
7690         AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
7691     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7692                                            AttributeCommonInfo::AS_Pragma));
7693     WeakTopLevelDecl.push_back(NewD);
7694     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7695     // to insert Decl at TU scope, sorry.
7696     DeclContext *SavedContext = CurContext;
7697     CurContext = Context.getTranslationUnitDecl();
7698     NewD->setDeclContext(CurContext);
7699     NewD->setLexicalDeclContext(CurContext);
7700     PushOnScopeChains(NewD, S);
7701     CurContext = SavedContext;
7702   } else { // just add weak to existing
7703     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7704                                          AttributeCommonInfo::AS_Pragma));
7705   }
7706 }
7707 
7708 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7709   // It's valid to "forward-declare" #pragma weak, in which case we
7710   // have to do this.
7711   LoadExternalWeakUndeclaredIdentifiers();
7712   if (!WeakUndeclaredIdentifiers.empty()) {
7713     NamedDecl *ND = nullptr;
7714     if (auto *VD = dyn_cast<VarDecl>(D))
7715       if (VD->isExternC())
7716         ND = VD;
7717     if (auto *FD = dyn_cast<FunctionDecl>(D))
7718       if (FD->isExternC())
7719         ND = FD;
7720     if (ND) {
7721       if (IdentifierInfo *Id = ND->getIdentifier()) {
7722         auto I = WeakUndeclaredIdentifiers.find(Id);
7723         if (I != WeakUndeclaredIdentifiers.end()) {
7724           WeakInfo W = I->second;
7725           DeclApplyPragmaWeak(S, ND, W);
7726           WeakUndeclaredIdentifiers[Id] = W;
7727         }
7728       }
7729     }
7730   }
7731 }
7732 
7733 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7734 /// it, apply them to D.  This is a bit tricky because PD can have attributes
7735 /// specified in many different places, and we need to find and apply them all.
7736 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7737   // Apply decl attributes from the DeclSpec if present.
7738   if (!PD.getDeclSpec().getAttributes().empty())
7739     ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7740 
7741   // Walk the declarator structure, applying decl attributes that were in a type
7742   // position to the decl itself.  This handles cases like:
7743   //   int *__attr__(x)** D;
7744   // when X is a decl attribute.
7745   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7746     ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7747                              /*IncludeCXX11Attributes=*/false);
7748 
7749   // Finally, apply any attributes on the decl itself.
7750   ProcessDeclAttributeList(S, D, PD.getAttributes());
7751 
7752   // Apply additional attributes specified by '#pragma clang attribute'.
7753   AddPragmaAttributes(S, D);
7754 }
7755 
7756 /// Is the given declaration allowed to use a forbidden type?
7757 /// If so, it'll still be annotated with an attribute that makes it
7758 /// illegal to actually use.
7759 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7760                                    const DelayedDiagnostic &diag,
7761                                    UnavailableAttr::ImplicitReason &reason) {
7762   // Private ivars are always okay.  Unfortunately, people don't
7763   // always properly make their ivars private, even in system headers.
7764   // Plus we need to make fields okay, too.
7765   if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7766       !isa<FunctionDecl>(D))
7767     return false;
7768 
7769   // Silently accept unsupported uses of __weak in both user and system
7770   // declarations when it's been disabled, for ease of integration with
7771   // -fno-objc-arc files.  We do have to take some care against attempts
7772   // to define such things;  for now, we've only done that for ivars
7773   // and properties.
7774   if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7775     if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7776         diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7777       reason = UnavailableAttr::IR_ForbiddenWeak;
7778       return true;
7779     }
7780   }
7781 
7782   // Allow all sorts of things in system headers.
7783   if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7784     // Currently, all the failures dealt with this way are due to ARC
7785     // restrictions.
7786     reason = UnavailableAttr::IR_ARCForbiddenType;
7787     return true;
7788   }
7789 
7790   return false;
7791 }
7792 
7793 /// Handle a delayed forbidden-type diagnostic.
7794 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7795                                        Decl *D) {
7796   auto Reason = UnavailableAttr::IR_None;
7797   if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7798     assert(Reason && "didn't set reason?");
7799     D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7800     return;
7801   }
7802   if (S.getLangOpts().ObjCAutoRefCount)
7803     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7804       // FIXME: we may want to suppress diagnostics for all
7805       // kind of forbidden type messages on unavailable functions.
7806       if (FD->hasAttr<UnavailableAttr>() &&
7807           DD.getForbiddenTypeDiagnostic() ==
7808               diag::err_arc_array_param_no_ownership) {
7809         DD.Triggered = true;
7810         return;
7811       }
7812     }
7813 
7814   S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7815       << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7816   DD.Triggered = true;
7817 }
7818 
7819 
7820 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7821   assert(DelayedDiagnostics.getCurrentPool());
7822   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7823   DelayedDiagnostics.popWithoutEmitting(state);
7824 
7825   // When delaying diagnostics to run in the context of a parsed
7826   // declaration, we only want to actually emit anything if parsing
7827   // succeeds.
7828   if (!decl) return;
7829 
7830   // We emit all the active diagnostics in this pool or any of its
7831   // parents.  In general, we'll get one pool for the decl spec
7832   // and a child pool for each declarator; in a decl group like:
7833   //   deprecated_typedef foo, *bar, baz();
7834   // only the declarator pops will be passed decls.  This is correct;
7835   // we really do need to consider delayed diagnostics from the decl spec
7836   // for each of the different declarations.
7837   const DelayedDiagnosticPool *pool = &poppedPool;
7838   do {
7839     bool AnyAccessFailures = false;
7840     for (DelayedDiagnosticPool::pool_iterator
7841            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7842       // This const_cast is a bit lame.  Really, Triggered should be mutable.
7843       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7844       if (diag.Triggered)
7845         continue;
7846 
7847       switch (diag.Kind) {
7848       case DelayedDiagnostic::Availability:
7849         // Don't bother giving deprecation/unavailable diagnostics if
7850         // the decl is invalid.
7851         if (!decl->isInvalidDecl())
7852           handleDelayedAvailabilityCheck(diag, decl);
7853         break;
7854 
7855       case DelayedDiagnostic::Access:
7856         // Only produce one access control diagnostic for a structured binding
7857         // declaration: we don't need to tell the user that all the fields are
7858         // inaccessible one at a time.
7859         if (AnyAccessFailures && isa<DecompositionDecl>(decl))
7860           continue;
7861         HandleDelayedAccessCheck(diag, decl);
7862         if (diag.Triggered)
7863           AnyAccessFailures = true;
7864         break;
7865 
7866       case DelayedDiagnostic::ForbiddenType:
7867         handleDelayedForbiddenType(*this, diag, decl);
7868         break;
7869       }
7870     }
7871   } while ((pool = pool->getParent()));
7872 }
7873 
7874 /// Given a set of delayed diagnostics, re-emit them as if they had
7875 /// been delayed in the current context instead of in the given pool.
7876 /// Essentially, this just moves them to the current pool.
7877 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7878   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7879   assert(curPool && "re-emitting in undelayed context not supported");
7880   curPool->steal(pool);
7881 }
7882