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