xref: /openbsd-src/gnu/llvm/clang/lib/Sema/SemaDeclAttr.cpp (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
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       .Case("syslog", SupportedFormat)
3415 
3416       .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3417       .Default(InvalidFormat);
3418 }
3419 
3420 /// Handle __attribute__((init_priority(priority))) attributes based on
3421 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3422 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3423   if (!S.getLangOpts().CPlusPlus) {
3424     S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3425     return;
3426   }
3427 
3428   if (S.getCurFunctionOrMethodDecl()) {
3429     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3430     AL.setInvalid();
3431     return;
3432   }
3433   QualType T = cast<VarDecl>(D)->getType();
3434   if (S.Context.getAsArrayType(T))
3435     T = S.Context.getBaseElementType(T);
3436   if (!T->getAs<RecordType>()) {
3437     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3438     AL.setInvalid();
3439     return;
3440   }
3441 
3442   Expr *E = AL.getArgAsExpr(0);
3443   uint32_t prioritynum;
3444   if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3445     AL.setInvalid();
3446     return;
3447   }
3448 
3449   // Only perform the priority check if the attribute is outside of a system
3450   // header. Values <= 100 are reserved for the implementation, and libc++
3451   // benefits from being able to specify values in that range.
3452   if ((prioritynum < 101 || prioritynum > 65535) &&
3453       !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3454     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3455         << E->getSourceRange() << AL << 101 << 65535;
3456     AL.setInvalid();
3457     return;
3458   }
3459   D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3460 }
3461 
3462 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3463                                   IdentifierInfo *Format, int FormatIdx,
3464                                   int FirstArg) {
3465   // Check whether we already have an equivalent format attribute.
3466   for (auto *F : D->specific_attrs<FormatAttr>()) {
3467     if (F->getType() == Format &&
3468         F->getFormatIdx() == FormatIdx &&
3469         F->getFirstArg() == FirstArg) {
3470       // If we don't have a valid location for this attribute, adopt the
3471       // location.
3472       if (F->getLocation().isInvalid())
3473         F->setRange(CI.getRange());
3474       return nullptr;
3475     }
3476   }
3477 
3478   return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3479 }
3480 
3481 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3482 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3483 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3484   if (!AL.isArgIdent(0)) {
3485     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3486         << AL << 1 << AANT_ArgumentIdentifier;
3487     return;
3488   }
3489 
3490   // In C++ the implicit 'this' function parameter also counts, and they are
3491   // counted from one.
3492   bool HasImplicitThisParam = isInstanceMethod(D);
3493   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3494 
3495   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3496   StringRef Format = II->getName();
3497 
3498   if (normalizeName(Format)) {
3499     // If we've modified the string name, we need a new identifier for it.
3500     II = &S.Context.Idents.get(Format);
3501   }
3502 
3503   // Check for supported formats.
3504   FormatAttrKind Kind = getFormatAttrKind(Format);
3505 
3506   if (Kind == IgnoredFormat)
3507     return;
3508 
3509   if (Kind == InvalidFormat) {
3510     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3511         << AL << II->getName();
3512     return;
3513   }
3514 
3515   // checks for the 2nd argument
3516   Expr *IdxExpr = AL.getArgAsExpr(1);
3517   uint32_t Idx;
3518   if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3519     return;
3520 
3521   if (Idx < 1 || Idx > NumArgs) {
3522     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3523         << AL << 2 << IdxExpr->getSourceRange();
3524     return;
3525   }
3526 
3527   // FIXME: Do we need to bounds check?
3528   unsigned ArgIdx = Idx - 1;
3529 
3530   if (HasImplicitThisParam) {
3531     if (ArgIdx == 0) {
3532       S.Diag(AL.getLoc(),
3533              diag::err_format_attribute_implicit_this_format_string)
3534         << IdxExpr->getSourceRange();
3535       return;
3536     }
3537     ArgIdx--;
3538   }
3539 
3540   // make sure the format string is really a string
3541   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3542 
3543   if (Kind == CFStringFormat) {
3544     if (!isCFStringType(Ty, S.Context)) {
3545       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3546         << "a CFString" << IdxExpr->getSourceRange()
3547         << getFunctionOrMethodParamRange(D, ArgIdx);
3548       return;
3549     }
3550   } else if (Kind == NSStringFormat) {
3551     // FIXME: do we need to check if the type is NSString*?  What are the
3552     // semantics?
3553     if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
3554       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3555         << "an NSString" << IdxExpr->getSourceRange()
3556         << getFunctionOrMethodParamRange(D, ArgIdx);
3557       return;
3558     }
3559   } else if (!Ty->isPointerType() ||
3560              !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3561     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3562       << "a string type" << IdxExpr->getSourceRange()
3563       << getFunctionOrMethodParamRange(D, ArgIdx);
3564     return;
3565   }
3566 
3567   // check the 3rd argument
3568   Expr *FirstArgExpr = AL.getArgAsExpr(2);
3569   uint32_t FirstArg;
3570   if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3571     return;
3572 
3573   // check if the function is variadic if the 3rd argument non-zero
3574   if (FirstArg != 0) {
3575     if (isFunctionOrMethodVariadic(D)) {
3576       ++NumArgs; // +1 for ...
3577     } else {
3578       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3579       return;
3580     }
3581   }
3582 
3583   // strftime requires FirstArg to be 0 because it doesn't read from any
3584   // variable the input is just the current time + the format string.
3585   if (Kind == StrftimeFormat) {
3586     if (FirstArg != 0) {
3587       S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3588         << FirstArgExpr->getSourceRange();
3589       return;
3590     }
3591   // if 0 it disables parameter checking (to use with e.g. va_list)
3592   } else if (FirstArg != 0 && FirstArg != NumArgs) {
3593     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3594         << AL << 3 << FirstArgExpr->getSourceRange();
3595     return;
3596   }
3597 
3598   FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3599   if (NewAttr)
3600     D->addAttr(NewAttr);
3601 }
3602 
3603 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3604 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3605   // The index that identifies the callback callee is mandatory.
3606   if (AL.getNumArgs() == 0) {
3607     S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3608         << AL.getRange();
3609     return;
3610   }
3611 
3612   bool HasImplicitThisParam = isInstanceMethod(D);
3613   int32_t NumArgs = getFunctionOrMethodNumParams(D);
3614 
3615   FunctionDecl *FD = D->getAsFunction();
3616   assert(FD && "Expected a function declaration!");
3617 
3618   llvm::StringMap<int> NameIdxMapping;
3619   NameIdxMapping["__"] = -1;
3620 
3621   NameIdxMapping["this"] = 0;
3622 
3623   int Idx = 1;
3624   for (const ParmVarDecl *PVD : FD->parameters())
3625     NameIdxMapping[PVD->getName()] = Idx++;
3626 
3627   auto UnknownName = NameIdxMapping.end();
3628 
3629   SmallVector<int, 8> EncodingIndices;
3630   for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3631     SourceRange SR;
3632     int32_t ArgIdx;
3633 
3634     if (AL.isArgIdent(I)) {
3635       IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3636       auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3637       if (It == UnknownName) {
3638         S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3639             << IdLoc->Ident << IdLoc->Loc;
3640         return;
3641       }
3642 
3643       SR = SourceRange(IdLoc->Loc);
3644       ArgIdx = It->second;
3645     } else if (AL.isArgExpr(I)) {
3646       Expr *IdxExpr = AL.getArgAsExpr(I);
3647 
3648       // If the expression is not parseable as an int32_t we have a problem.
3649       if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3650                                false)) {
3651         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3652             << AL << (I + 1) << IdxExpr->getSourceRange();
3653         return;
3654       }
3655 
3656       // Check oob, excluding the special values, 0 and -1.
3657       if (ArgIdx < -1 || ArgIdx > NumArgs) {
3658         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3659             << AL << (I + 1) << IdxExpr->getSourceRange();
3660         return;
3661       }
3662 
3663       SR = IdxExpr->getSourceRange();
3664     } else {
3665       llvm_unreachable("Unexpected ParsedAttr argument type!");
3666     }
3667 
3668     if (ArgIdx == 0 && !HasImplicitThisParam) {
3669       S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3670           << (I + 1) << SR;
3671       return;
3672     }
3673 
3674     // Adjust for the case we do not have an implicit "this" parameter. In this
3675     // case we decrease all positive values by 1 to get LLVM argument indices.
3676     if (!HasImplicitThisParam && ArgIdx > 0)
3677       ArgIdx -= 1;
3678 
3679     EncodingIndices.push_back(ArgIdx);
3680   }
3681 
3682   int CalleeIdx = EncodingIndices.front();
3683   // Check if the callee index is proper, thus not "this" and not "unknown".
3684   // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3685   // is false and positive if "HasImplicitThisParam" is true.
3686   if (CalleeIdx < (int)HasImplicitThisParam) {
3687     S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3688         << AL.getRange();
3689     return;
3690   }
3691 
3692   // Get the callee type, note the index adjustment as the AST doesn't contain
3693   // the this type (which the callee cannot reference anyway!).
3694   const Type *CalleeType =
3695       getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3696           .getTypePtr();
3697   if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3698     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3699         << AL.getRange();
3700     return;
3701   }
3702 
3703   const Type *CalleeFnType =
3704       CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3705 
3706   // TODO: Check the type of the callee arguments.
3707 
3708   const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3709   if (!CalleeFnProtoType) {
3710     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3711         << AL.getRange();
3712     return;
3713   }
3714 
3715   if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3716     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3717         << AL << (unsigned)(EncodingIndices.size() - 1);
3718     return;
3719   }
3720 
3721   if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3722     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3723         << AL << (unsigned)(EncodingIndices.size() - 1);
3724     return;
3725   }
3726 
3727   if (CalleeFnProtoType->isVariadic()) {
3728     S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3729     return;
3730   }
3731 
3732   // Do not allow multiple callback attributes.
3733   if (D->hasAttr<CallbackAttr>()) {
3734     S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3735     return;
3736   }
3737 
3738   D->addAttr(::new (S.Context) CallbackAttr(
3739       S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3740 }
3741 
3742 static bool isFunctionLike(const Type &T) {
3743   // Check for explicit function types.
3744   // 'called_once' is only supported in Objective-C and it has
3745   // function pointers and block pointers.
3746   return T.isFunctionPointerType() || T.isBlockPointerType();
3747 }
3748 
3749 /// Handle 'called_once' attribute.
3750 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3751   // 'called_once' only applies to parameters representing functions.
3752   QualType T = cast<ParmVarDecl>(D)->getType();
3753 
3754   if (!isFunctionLike(*T)) {
3755     S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3756     return;
3757   }
3758 
3759   D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3760 }
3761 
3762 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3763   // Try to find the underlying union declaration.
3764   RecordDecl *RD = nullptr;
3765   const auto *TD = dyn_cast<TypedefNameDecl>(D);
3766   if (TD && TD->getUnderlyingType()->isUnionType())
3767     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3768   else
3769     RD = dyn_cast<RecordDecl>(D);
3770 
3771   if (!RD || !RD->isUnion()) {
3772     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3773                                                               << ExpectedUnion;
3774     return;
3775   }
3776 
3777   if (!RD->isCompleteDefinition()) {
3778     if (!RD->isBeingDefined())
3779       S.Diag(AL.getLoc(),
3780              diag::warn_transparent_union_attribute_not_definition);
3781     return;
3782   }
3783 
3784   RecordDecl::field_iterator Field = RD->field_begin(),
3785                           FieldEnd = RD->field_end();
3786   if (Field == FieldEnd) {
3787     S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3788     return;
3789   }
3790 
3791   FieldDecl *FirstField = *Field;
3792   QualType FirstType = FirstField->getType();
3793   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3794     S.Diag(FirstField->getLocation(),
3795            diag::warn_transparent_union_attribute_floating)
3796       << FirstType->isVectorType() << FirstType;
3797     return;
3798   }
3799 
3800   if (FirstType->isIncompleteType())
3801     return;
3802   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3803   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3804   for (; Field != FieldEnd; ++Field) {
3805     QualType FieldType = Field->getType();
3806     if (FieldType->isIncompleteType())
3807       return;
3808     // FIXME: this isn't fully correct; we also need to test whether the
3809     // members of the union would all have the same calling convention as the
3810     // first member of the union. Checking just the size and alignment isn't
3811     // sufficient (consider structs passed on the stack instead of in registers
3812     // as an example).
3813     if (S.Context.getTypeSize(FieldType) != FirstSize ||
3814         S.Context.getTypeAlign(FieldType) > FirstAlign) {
3815       // Warn if we drop the attribute.
3816       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3817       unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3818                                   : S.Context.getTypeAlign(FieldType);
3819       S.Diag(Field->getLocation(),
3820              diag::warn_transparent_union_attribute_field_size_align)
3821           << isSize << *Field << FieldBits;
3822       unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3823       S.Diag(FirstField->getLocation(),
3824              diag::note_transparent_union_first_field_size_align)
3825           << isSize << FirstBits;
3826       return;
3827     }
3828   }
3829 
3830   RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3831 }
3832 
3833 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
3834                              StringRef Str, MutableArrayRef<Expr *> Args) {
3835   auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3836   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3837   for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) {
3838     Expr *&E = Attr->args_begin()[Idx];
3839     assert(E && "error are handled before");
3840     if (E->isValueDependent() || E->isTypeDependent())
3841       continue;
3842 
3843     if (E->getType()->isArrayType())
3844       E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
3845                             clang::CK_ArrayToPointerDecay)
3846               .get();
3847     if (E->getType()->isFunctionType())
3848       E = ImplicitCastExpr::Create(Context,
3849                                    Context.getPointerType(E->getType()),
3850                                    clang::CK_FunctionToPointerDecay, E, nullptr,
3851                                    VK_PRValue, FPOptionsOverride());
3852     if (E->isLValue())
3853       E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
3854                                    clang::CK_LValueToRValue, E, nullptr,
3855                                    VK_PRValue, FPOptionsOverride());
3856 
3857     Expr::EvalResult Eval;
3858     Notes.clear();
3859     Eval.Diag = &Notes;
3860 
3861     bool Result =
3862         E->EvaluateAsConstantExpr(Eval, Context);
3863 
3864     /// Result means the expression can be folded to a constant.
3865     /// Note.empty() means the expression is a valid constant expression in the
3866     /// current language mode.
3867     if (!Result || !Notes.empty()) {
3868       Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
3869           << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
3870       for (auto &Note : Notes)
3871         Diag(Note.first, Note.second);
3872       return;
3873     }
3874     assert(Eval.Val.hasValue());
3875     E = ConstantExpr::Create(Context, E, Eval.Val);
3876   }
3877   D->addAttr(Attr);
3878 }
3879 
3880 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3881   // Make sure that there is a string literal as the annotation's first
3882   // argument.
3883   StringRef Str;
3884   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3885     return;
3886 
3887   llvm::SmallVector<Expr *, 4> Args;
3888   Args.reserve(AL.getNumArgs() - 1);
3889   for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3890     assert(!AL.isArgIdent(Idx));
3891     Args.push_back(AL.getArgAsExpr(Idx));
3892   }
3893 
3894   S.AddAnnotationAttr(D, AL, Str, Args);
3895 }
3896 
3897 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3898   S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3899 }
3900 
3901 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3902   AlignValueAttr TmpAttr(Context, CI, E);
3903   SourceLocation AttrLoc = CI.getLoc();
3904 
3905   QualType T;
3906   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3907     T = TD->getUnderlyingType();
3908   else if (const auto *VD = dyn_cast<ValueDecl>(D))
3909     T = VD->getType();
3910   else
3911     llvm_unreachable("Unknown decl type for align_value");
3912 
3913   if (!T->isDependentType() && !T->isAnyPointerType() &&
3914       !T->isReferenceType() && !T->isMemberPointerType()) {
3915     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3916       << &TmpAttr << T << D->getSourceRange();
3917     return;
3918   }
3919 
3920   if (!E->isValueDependent()) {
3921     llvm::APSInt Alignment;
3922     ExprResult ICE = VerifyIntegerConstantExpression(
3923         E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3924     if (ICE.isInvalid())
3925       return;
3926 
3927     if (!Alignment.isPowerOf2()) {
3928       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3929         << E->getSourceRange();
3930       return;
3931     }
3932 
3933     D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3934     return;
3935   }
3936 
3937   // Save dependent expressions in the AST to be instantiated.
3938   D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3939 }
3940 
3941 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3942   // check the attribute arguments.
3943   if (AL.getNumArgs() > 1) {
3944     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3945     return;
3946   }
3947 
3948   if (AL.getNumArgs() == 0) {
3949     D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3950     return;
3951   }
3952 
3953   Expr *E = AL.getArgAsExpr(0);
3954   if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3955     S.Diag(AL.getEllipsisLoc(),
3956            diag::err_pack_expansion_without_parameter_packs);
3957     return;
3958   }
3959 
3960   if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3961     return;
3962 
3963   S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3964 }
3965 
3966 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3967                           bool IsPackExpansion) {
3968   AlignedAttr TmpAttr(Context, CI, true, E);
3969   SourceLocation AttrLoc = CI.getLoc();
3970 
3971   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3972   if (TmpAttr.isAlignas()) {
3973     // C++11 [dcl.align]p1:
3974     //   An alignment-specifier may be applied to a variable or to a class
3975     //   data member, but it shall not be applied to a bit-field, a function
3976     //   parameter, the formal parameter of a catch clause, or a variable
3977     //   declared with the register storage class specifier. An
3978     //   alignment-specifier may also be applied to the declaration of a class
3979     //   or enumeration type.
3980     // C11 6.7.5/2:
3981     //   An alignment attribute shall not be specified in a declaration of
3982     //   a typedef, or a bit-field, or a function, or a parameter, or an
3983     //   object declared with the register storage-class specifier.
3984     int DiagKind = -1;
3985     if (isa<ParmVarDecl>(D)) {
3986       DiagKind = 0;
3987     } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3988       if (VD->getStorageClass() == SC_Register)
3989         DiagKind = 1;
3990       if (VD->isExceptionVariable())
3991         DiagKind = 2;
3992     } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3993       if (FD->isBitField())
3994         DiagKind = 3;
3995     } else if (!isa<TagDecl>(D)) {
3996       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3997         << (TmpAttr.isC11() ? ExpectedVariableOrField
3998                             : ExpectedVariableFieldOrTag);
3999       return;
4000     }
4001     if (DiagKind != -1) {
4002       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4003         << &TmpAttr << DiagKind;
4004       return;
4005     }
4006   }
4007 
4008   if (E->isValueDependent()) {
4009     // We can't support a dependent alignment on a non-dependent type,
4010     // because we have no way to model that a type is "alignment-dependent"
4011     // but not dependent in any other way.
4012     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4013       if (!TND->getUnderlyingType()->isDependentType()) {
4014         Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4015             << E->getSourceRange();
4016         return;
4017       }
4018     }
4019 
4020     // Save dependent expressions in the AST to be instantiated.
4021     AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4022     AA->setPackExpansion(IsPackExpansion);
4023     D->addAttr(AA);
4024     return;
4025   }
4026 
4027   // FIXME: Cache the number on the AL object?
4028   llvm::APSInt Alignment;
4029   ExprResult ICE = VerifyIntegerConstantExpression(
4030       E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4031   if (ICE.isInvalid())
4032     return;
4033 
4034   uint64_t AlignVal = Alignment.getZExtValue();
4035   // 16 byte ByVal alignment not due to a vector member is not honoured by XL
4036   // on AIX. Emit a warning here that users are generating binary incompatible
4037   // code to be safe.
4038   if (AlignVal >= 16 && isa<FieldDecl>(D) &&
4039       Context.getTargetInfo().getTriple().isOSAIX())
4040     Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange();
4041 
4042   // C++11 [dcl.align]p2:
4043   //   -- if the constant expression evaluates to zero, the alignment
4044   //      specifier shall have no effect
4045   // C11 6.7.5p6:
4046   //   An alignment specification of zero has no effect.
4047   if (!(TmpAttr.isAlignas() && !Alignment)) {
4048     if (!llvm::isPowerOf2_64(AlignVal)) {
4049       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4050         << E->getSourceRange();
4051       return;
4052     }
4053   }
4054 
4055   unsigned MaximumAlignment = Sema::MaximumAlignment;
4056   if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4057     MaximumAlignment = std::min(MaximumAlignment, 8192u);
4058   if (AlignVal > MaximumAlignment) {
4059     Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4060         << MaximumAlignment << E->getSourceRange();
4061     return;
4062   }
4063 
4064   if (Context.getTargetInfo().isTLSSupported()) {
4065     unsigned MaxTLSAlign =
4066         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4067             .getQuantity();
4068     const auto *VD = dyn_cast<VarDecl>(D);
4069     if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
4070         VD->getTLSKind() != VarDecl::TLS_None) {
4071       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4072           << (unsigned)AlignVal << VD << MaxTLSAlign;
4073       return;
4074     }
4075   }
4076 
4077   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4078   AA->setPackExpansion(IsPackExpansion);
4079   D->addAttr(AA);
4080 }
4081 
4082 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4083                           TypeSourceInfo *TS, bool IsPackExpansion) {
4084   // FIXME: Cache the number on the AL object if non-dependent?
4085   // FIXME: Perform checking of type validity
4086   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4087   AA->setPackExpansion(IsPackExpansion);
4088   D->addAttr(AA);
4089 }
4090 
4091 void Sema::CheckAlignasUnderalignment(Decl *D) {
4092   assert(D->hasAttrs() && "no attributes on decl");
4093 
4094   QualType UnderlyingTy, DiagTy;
4095   if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4096     UnderlyingTy = DiagTy = VD->getType();
4097   } else {
4098     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4099     if (const auto *ED = dyn_cast<EnumDecl>(D))
4100       UnderlyingTy = ED->getIntegerType();
4101   }
4102   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4103     return;
4104 
4105   // C++11 [dcl.align]p5, C11 6.7.5/4:
4106   //   The combined effect of all alignment attributes in a declaration shall
4107   //   not specify an alignment that is less strict than the alignment that
4108   //   would otherwise be required for the entity being declared.
4109   AlignedAttr *AlignasAttr = nullptr;
4110   AlignedAttr *LastAlignedAttr = nullptr;
4111   unsigned Align = 0;
4112   for (auto *I : D->specific_attrs<AlignedAttr>()) {
4113     if (I->isAlignmentDependent())
4114       return;
4115     if (I->isAlignas())
4116       AlignasAttr = I;
4117     Align = std::max(Align, I->getAlignment(Context));
4118     LastAlignedAttr = I;
4119   }
4120 
4121   if (Align && DiagTy->isSizelessType()) {
4122     Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4123         << LastAlignedAttr << DiagTy;
4124   } else if (AlignasAttr && Align) {
4125     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4126     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4127     if (NaturalAlign > RequestedAlign)
4128       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4129         << DiagTy << (unsigned)NaturalAlign.getQuantity();
4130   }
4131 }
4132 
4133 bool Sema::checkMSInheritanceAttrOnDefinition(
4134     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4135     MSInheritanceModel ExplicitModel) {
4136   assert(RD->hasDefinition() && "RD has no definition!");
4137 
4138   // We may not have seen base specifiers or any virtual methods yet.  We will
4139   // have to wait until the record is defined to catch any mismatches.
4140   if (!RD->getDefinition()->isCompleteDefinition())
4141     return false;
4142 
4143   // The unspecified model never matches what a definition could need.
4144   if (ExplicitModel == MSInheritanceModel::Unspecified)
4145     return false;
4146 
4147   if (BestCase) {
4148     if (RD->calculateInheritanceModel() == ExplicitModel)
4149       return false;
4150   } else {
4151     if (RD->calculateInheritanceModel() <= ExplicitModel)
4152       return false;
4153   }
4154 
4155   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4156       << 0 /*definition*/;
4157   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4158   return true;
4159 }
4160 
4161 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4162 /// attribute.
4163 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4164                              bool &IntegerMode, bool &ComplexMode,
4165                              bool &ExplicitIEEE) {
4166   IntegerMode = true;
4167   ComplexMode = false;
4168   switch (Str.size()) {
4169   case 2:
4170     switch (Str[0]) {
4171     case 'Q':
4172       DestWidth = 8;
4173       break;
4174     case 'H':
4175       DestWidth = 16;
4176       break;
4177     case 'S':
4178       DestWidth = 32;
4179       break;
4180     case 'D':
4181       DestWidth = 64;
4182       break;
4183     case 'X':
4184       DestWidth = 96;
4185       break;
4186     case 'K': // KFmode - IEEE quad precision (__float128)
4187       ExplicitIEEE = true;
4188       DestWidth = Str[1] == 'I' ? 0 : 128;
4189       break;
4190     case 'T':
4191       ExplicitIEEE = false;
4192       DestWidth = 128;
4193       break;
4194     }
4195     if (Str[1] == 'F') {
4196       IntegerMode = false;
4197     } else if (Str[1] == 'C') {
4198       IntegerMode = false;
4199       ComplexMode = true;
4200     } else if (Str[1] != 'I') {
4201       DestWidth = 0;
4202     }
4203     break;
4204   case 4:
4205     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4206     // pointer on PIC16 and other embedded platforms.
4207     if (Str == "word")
4208       DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4209     else if (Str == "byte")
4210       DestWidth = S.Context.getTargetInfo().getCharWidth();
4211     break;
4212   case 7:
4213     if (Str == "pointer")
4214       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4215     break;
4216   case 11:
4217     if (Str == "unwind_word")
4218       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4219     break;
4220   }
4221 }
4222 
4223 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4224 /// type.
4225 ///
4226 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4227 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4228 /// HImode, not an intermediate pointer.
4229 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4230   // This attribute isn't documented, but glibc uses it.  It changes
4231   // the width of an int or unsigned int to the specified size.
4232   if (!AL.isArgIdent(0)) {
4233     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4234         << AL << AANT_ArgumentIdentifier;
4235     return;
4236   }
4237 
4238   IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4239 
4240   S.AddModeAttr(D, AL, Name);
4241 }
4242 
4243 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4244                        IdentifierInfo *Name, bool InInstantiation) {
4245   StringRef Str = Name->getName();
4246   normalizeName(Str);
4247   SourceLocation AttrLoc = CI.getLoc();
4248 
4249   unsigned DestWidth = 0;
4250   bool IntegerMode = true;
4251   bool ComplexMode = false;
4252   bool ExplicitIEEE = false;
4253   llvm::APInt VectorSize(64, 0);
4254   if (Str.size() >= 4 && Str[0] == 'V') {
4255     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4256     size_t StrSize = Str.size();
4257     size_t VectorStringLength = 0;
4258     while ((VectorStringLength + 1) < StrSize &&
4259            isdigit(Str[VectorStringLength + 1]))
4260       ++VectorStringLength;
4261     if (VectorStringLength &&
4262         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4263         VectorSize.isPowerOf2()) {
4264       parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4265                        IntegerMode, ComplexMode, ExplicitIEEE);
4266       // Avoid duplicate warning from template instantiation.
4267       if (!InInstantiation)
4268         Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4269     } else {
4270       VectorSize = 0;
4271     }
4272   }
4273 
4274   if (!VectorSize)
4275     parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4276                      ExplicitIEEE);
4277 
4278   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4279   // and friends, at least with glibc.
4280   // FIXME: Make sure floating-point mappings are accurate
4281   // FIXME: Support XF and TF types
4282   if (!DestWidth) {
4283     Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4284     return;
4285   }
4286 
4287   QualType OldTy;
4288   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4289     OldTy = TD->getUnderlyingType();
4290   else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4291     // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4292     // Try to get type from enum declaration, default to int.
4293     OldTy = ED->getIntegerType();
4294     if (OldTy.isNull())
4295       OldTy = Context.IntTy;
4296   } else
4297     OldTy = cast<ValueDecl>(D)->getType();
4298 
4299   if (OldTy->isDependentType()) {
4300     D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4301     return;
4302   }
4303 
4304   // Base type can also be a vector type (see PR17453).
4305   // Distinguish between base type and base element type.
4306   QualType OldElemTy = OldTy;
4307   if (const auto *VT = OldTy->getAs<VectorType>())
4308     OldElemTy = VT->getElementType();
4309 
4310   // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4311   // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4312   // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4313   if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4314       VectorSize.getBoolValue()) {
4315     Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4316     return;
4317   }
4318   bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4319                                 !OldElemTy->isExtIntType()) ||
4320                                OldElemTy->getAs<EnumType>();
4321 
4322   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4323       !IntegralOrAnyEnumType)
4324     Diag(AttrLoc, diag::err_mode_not_primitive);
4325   else if (IntegerMode) {
4326     if (!IntegralOrAnyEnumType)
4327       Diag(AttrLoc, diag::err_mode_wrong_type);
4328   } else if (ComplexMode) {
4329     if (!OldElemTy->isComplexType())
4330       Diag(AttrLoc, diag::err_mode_wrong_type);
4331   } else {
4332     if (!OldElemTy->isFloatingType())
4333       Diag(AttrLoc, diag::err_mode_wrong_type);
4334   }
4335 
4336   QualType NewElemTy;
4337 
4338   if (IntegerMode)
4339     NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4340                                               OldElemTy->isSignedIntegerType());
4341   else
4342     NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE);
4343 
4344   if (NewElemTy.isNull()) {
4345     Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4346     return;
4347   }
4348 
4349   if (ComplexMode) {
4350     NewElemTy = Context.getComplexType(NewElemTy);
4351   }
4352 
4353   QualType NewTy = NewElemTy;
4354   if (VectorSize.getBoolValue()) {
4355     NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4356                                   VectorType::GenericVector);
4357   } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4358     // Complex machine mode does not support base vector types.
4359     if (ComplexMode) {
4360       Diag(AttrLoc, diag::err_complex_mode_vector_type);
4361       return;
4362     }
4363     unsigned NumElements = Context.getTypeSize(OldElemTy) *
4364                            OldVT->getNumElements() /
4365                            Context.getTypeSize(NewElemTy);
4366     NewTy =
4367         Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4368   }
4369 
4370   if (NewTy.isNull()) {
4371     Diag(AttrLoc, diag::err_mode_wrong_type);
4372     return;
4373   }
4374 
4375   // Install the new type.
4376   if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4377     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4378   else if (auto *ED = dyn_cast<EnumDecl>(D))
4379     ED->setIntegerType(NewTy);
4380   else
4381     cast<ValueDecl>(D)->setType(NewTy);
4382 
4383   D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4384 }
4385 
4386 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4387   D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4388 }
4389 
4390 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4391                                               const AttributeCommonInfo &CI,
4392                                               const IdentifierInfo *Ident) {
4393   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4394     Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4395     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4396     return nullptr;
4397   }
4398 
4399   if (D->hasAttr<AlwaysInlineAttr>())
4400     return nullptr;
4401 
4402   return ::new (Context) AlwaysInlineAttr(Context, CI);
4403 }
4404 
4405 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4406                                                     const ParsedAttr &AL) {
4407   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4408     // Attribute applies to Var but not any subclass of it (like ParmVar,
4409     // ImplicitParm or VarTemplateSpecialization).
4410     if (VD->getKind() != Decl::Var) {
4411       Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4412           << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4413                                             : ExpectedVariableOrFunction);
4414       return nullptr;
4415     }
4416     // Attribute does not apply to non-static local variables.
4417     if (VD->hasLocalStorage()) {
4418       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4419       return nullptr;
4420     }
4421   }
4422 
4423   return ::new (Context) InternalLinkageAttr(Context, AL);
4424 }
4425 InternalLinkageAttr *
4426 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4427   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4428     // Attribute applies to Var but not any subclass of it (like ParmVar,
4429     // ImplicitParm or VarTemplateSpecialization).
4430     if (VD->getKind() != Decl::Var) {
4431       Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4432           << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4433                                              : ExpectedVariableOrFunction);
4434       return nullptr;
4435     }
4436     // Attribute does not apply to non-static local variables.
4437     if (VD->hasLocalStorage()) {
4438       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4439       return nullptr;
4440     }
4441   }
4442 
4443   return ::new (Context) InternalLinkageAttr(Context, AL);
4444 }
4445 
4446 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4447   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4448     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4449     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4450     return nullptr;
4451   }
4452 
4453   if (D->hasAttr<MinSizeAttr>())
4454     return nullptr;
4455 
4456   return ::new (Context) MinSizeAttr(Context, CI);
4457 }
4458 
4459 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4460                                         StringRef Name) {
4461   if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4462     if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4463       Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4464           << PrevSNA << &SNA;
4465       Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4466     }
4467 
4468     D->dropAttr<SwiftNameAttr>();
4469   }
4470   return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4471 }
4472 
4473 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4474                                               const AttributeCommonInfo &CI) {
4475   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4476     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4477     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4478     D->dropAttr<AlwaysInlineAttr>();
4479   }
4480   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4481     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4482     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4483     D->dropAttr<MinSizeAttr>();
4484   }
4485 
4486   if (D->hasAttr<OptimizeNoneAttr>())
4487     return nullptr;
4488 
4489   return ::new (Context) OptimizeNoneAttr(Context, CI);
4490 }
4491 
4492 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4493   if (AlwaysInlineAttr *Inline =
4494           S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4495     D->addAttr(Inline);
4496 }
4497 
4498 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4499   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4500     D->addAttr(MinSize);
4501 }
4502 
4503 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4504   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4505     D->addAttr(Optnone);
4506 }
4507 
4508 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4509   const auto *VD = cast<VarDecl>(D);
4510   if (VD->hasLocalStorage()) {
4511     S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4512     return;
4513   }
4514   // constexpr variable may already get an implicit constant attr, which should
4515   // be replaced by the explicit constant attr.
4516   if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4517     if (!A->isImplicit())
4518       return;
4519     D->dropAttr<CUDAConstantAttr>();
4520   }
4521   D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4522 }
4523 
4524 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4525   const auto *VD = cast<VarDecl>(D);
4526   // extern __shared__ is only allowed on arrays with no length (e.g.
4527   // "int x[]").
4528   if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4529       !isa<IncompleteArrayType>(VD->getType())) {
4530     S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4531     return;
4532   }
4533   if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4534       S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4535           << S.CurrentCUDATarget())
4536     return;
4537   D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4538 }
4539 
4540 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4541   const auto *FD = cast<FunctionDecl>(D);
4542   if (!FD->getReturnType()->isVoidType() &&
4543       !FD->getReturnType()->getAs<AutoType>() &&
4544       !FD->getReturnType()->isInstantiationDependentType()) {
4545     SourceRange RTRange = FD->getReturnTypeSourceRange();
4546     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4547         << FD->getType()
4548         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4549                               : FixItHint());
4550     return;
4551   }
4552   if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4553     if (Method->isInstance()) {
4554       S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4555           << Method;
4556       return;
4557     }
4558     S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4559   }
4560   // Only warn for "inline" when compiling for host, to cut down on noise.
4561   if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4562     S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4563 
4564   D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4565   // In host compilation the kernel is emitted as a stub function, which is
4566   // a helper function for launching the kernel. The instructions in the helper
4567   // function has nothing to do with the source code of the kernel. Do not emit
4568   // debug info for the stub function to avoid confusing the debugger.
4569   if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4570     D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4571 }
4572 
4573 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4574   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4575     if (VD->hasLocalStorage()) {
4576       S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4577       return;
4578     }
4579   }
4580 
4581   if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4582     if (!A->isImplicit())
4583       return;
4584     D->dropAttr<CUDADeviceAttr>();
4585   }
4586   D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4587 }
4588 
4589 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4590   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4591     if (VD->hasLocalStorage()) {
4592       S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4593       return;
4594     }
4595   }
4596   if (!D->hasAttr<HIPManagedAttr>())
4597     D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4598   if (!D->hasAttr<CUDADeviceAttr>())
4599     D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4600 }
4601 
4602 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4603   const auto *Fn = cast<FunctionDecl>(D);
4604   if (!Fn->isInlineSpecified()) {
4605     S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4606     return;
4607   }
4608 
4609   if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4610     S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4611 
4612   D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4613 }
4614 
4615 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4616   if (hasDeclarator(D)) return;
4617 
4618   // Diagnostic is emitted elsewhere: here we store the (valid) AL
4619   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4620   CallingConv CC;
4621   if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4622     return;
4623 
4624   if (!isa<ObjCMethodDecl>(D)) {
4625     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4626         << AL << ExpectedFunctionOrMethod;
4627     return;
4628   }
4629 
4630   switch (AL.getKind()) {
4631   case ParsedAttr::AT_FastCall:
4632     D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4633     return;
4634   case ParsedAttr::AT_StdCall:
4635     D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4636     return;
4637   case ParsedAttr::AT_ThisCall:
4638     D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4639     return;
4640   case ParsedAttr::AT_CDecl:
4641     D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4642     return;
4643   case ParsedAttr::AT_Pascal:
4644     D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4645     return;
4646   case ParsedAttr::AT_SwiftCall:
4647     D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4648     return;
4649   case ParsedAttr::AT_SwiftAsyncCall:
4650     D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
4651     return;
4652   case ParsedAttr::AT_VectorCall:
4653     D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4654     return;
4655   case ParsedAttr::AT_MSABI:
4656     D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4657     return;
4658   case ParsedAttr::AT_SysVABI:
4659     D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4660     return;
4661   case ParsedAttr::AT_RegCall:
4662     D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4663     return;
4664   case ParsedAttr::AT_Pcs: {
4665     PcsAttr::PCSType PCS;
4666     switch (CC) {
4667     case CC_AAPCS:
4668       PCS = PcsAttr::AAPCS;
4669       break;
4670     case CC_AAPCS_VFP:
4671       PCS = PcsAttr::AAPCS_VFP;
4672       break;
4673     default:
4674       llvm_unreachable("unexpected calling convention in pcs attribute");
4675     }
4676 
4677     D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4678     return;
4679   }
4680   case ParsedAttr::AT_AArch64VectorPcs:
4681     D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4682     return;
4683   case ParsedAttr::AT_IntelOclBicc:
4684     D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4685     return;
4686   case ParsedAttr::AT_PreserveMost:
4687     D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4688     return;
4689   case ParsedAttr::AT_PreserveAll:
4690     D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4691     return;
4692   default:
4693     llvm_unreachable("unexpected attribute kind");
4694   }
4695 }
4696 
4697 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4698   if (!AL.checkAtLeastNumArgs(S, 1))
4699     return;
4700 
4701   std::vector<StringRef> DiagnosticIdentifiers;
4702   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4703     StringRef RuleName;
4704 
4705     if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4706       return;
4707 
4708     // FIXME: Warn if the rule name is unknown. This is tricky because only
4709     // clang-tidy knows about available rules.
4710     DiagnosticIdentifiers.push_back(RuleName);
4711   }
4712   D->addAttr(::new (S.Context)
4713                  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4714                               DiagnosticIdentifiers.size()));
4715 }
4716 
4717 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4718   TypeSourceInfo *DerefTypeLoc = nullptr;
4719   QualType ParmType;
4720   if (AL.hasParsedType()) {
4721     ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4722 
4723     unsigned SelectIdx = ~0U;
4724     if (ParmType->isReferenceType())
4725       SelectIdx = 0;
4726     else if (ParmType->isArrayType())
4727       SelectIdx = 1;
4728 
4729     if (SelectIdx != ~0U) {
4730       S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4731           << SelectIdx << AL;
4732       return;
4733     }
4734   }
4735 
4736   // To check if earlier decl attributes do not conflict the newly parsed ones
4737   // we always add (and check) the attribute to the cannonical decl. We need
4738   // to repeat the check for attribute mutual exclusion because we're attaching
4739   // all of the attributes to the canonical declaration rather than the current
4740   // declaration.
4741   D = D->getCanonicalDecl();
4742   if (AL.getKind() == ParsedAttr::AT_Owner) {
4743     if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4744       return;
4745     if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4746       const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4747                                           ? OAttr->getDerefType().getTypePtr()
4748                                           : nullptr;
4749       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4750         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4751             << AL << OAttr;
4752         S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4753       }
4754       return;
4755     }
4756     for (Decl *Redecl : D->redecls()) {
4757       Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4758     }
4759   } else {
4760     if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4761       return;
4762     if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4763       const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4764                                           ? PAttr->getDerefType().getTypePtr()
4765                                           : nullptr;
4766       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4767         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4768             << AL << PAttr;
4769         S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4770       }
4771       return;
4772     }
4773     for (Decl *Redecl : D->redecls()) {
4774       Redecl->addAttr(::new (S.Context)
4775                           PointerAttr(S.Context, AL, DerefTypeLoc));
4776     }
4777   }
4778 }
4779 
4780 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4781                                 const FunctionDecl *FD) {
4782   if (Attrs.isInvalid())
4783     return true;
4784 
4785   if (Attrs.hasProcessingCache()) {
4786     CC = (CallingConv) Attrs.getProcessingCache();
4787     return false;
4788   }
4789 
4790   unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4791   if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
4792     Attrs.setInvalid();
4793     return true;
4794   }
4795 
4796   // TODO: diagnose uses of these conventions on the wrong target.
4797   switch (Attrs.getKind()) {
4798   case ParsedAttr::AT_CDecl:
4799     CC = CC_C;
4800     break;
4801   case ParsedAttr::AT_FastCall:
4802     CC = CC_X86FastCall;
4803     break;
4804   case ParsedAttr::AT_StdCall:
4805     CC = CC_X86StdCall;
4806     break;
4807   case ParsedAttr::AT_ThisCall:
4808     CC = CC_X86ThisCall;
4809     break;
4810   case ParsedAttr::AT_Pascal:
4811     CC = CC_X86Pascal;
4812     break;
4813   case ParsedAttr::AT_SwiftCall:
4814     CC = CC_Swift;
4815     break;
4816   case ParsedAttr::AT_SwiftAsyncCall:
4817     CC = CC_SwiftAsync;
4818     break;
4819   case ParsedAttr::AT_VectorCall:
4820     CC = CC_X86VectorCall;
4821     break;
4822   case ParsedAttr::AT_AArch64VectorPcs:
4823     CC = CC_AArch64VectorCall;
4824     break;
4825   case ParsedAttr::AT_RegCall:
4826     CC = CC_X86RegCall;
4827     break;
4828   case ParsedAttr::AT_MSABI:
4829     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4830                                                              CC_Win64;
4831     break;
4832   case ParsedAttr::AT_SysVABI:
4833     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4834                                                              CC_C;
4835     break;
4836   case ParsedAttr::AT_Pcs: {
4837     StringRef StrRef;
4838     if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4839       Attrs.setInvalid();
4840       return true;
4841     }
4842     if (StrRef == "aapcs") {
4843       CC = CC_AAPCS;
4844       break;
4845     } else if (StrRef == "aapcs-vfp") {
4846       CC = CC_AAPCS_VFP;
4847       break;
4848     }
4849 
4850     Attrs.setInvalid();
4851     Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4852     return true;
4853   }
4854   case ParsedAttr::AT_IntelOclBicc:
4855     CC = CC_IntelOclBicc;
4856     break;
4857   case ParsedAttr::AT_PreserveMost:
4858     CC = CC_PreserveMost;
4859     break;
4860   case ParsedAttr::AT_PreserveAll:
4861     CC = CC_PreserveAll;
4862     break;
4863   default: llvm_unreachable("unexpected attribute kind");
4864   }
4865 
4866   TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4867   const TargetInfo &TI = Context.getTargetInfo();
4868   // CUDA functions may have host and/or device attributes which indicate
4869   // their targeted execution environment, therefore the calling convention
4870   // of functions in CUDA should be checked against the target deduced based
4871   // on their host/device attributes.
4872   if (LangOpts.CUDA) {
4873     auto *Aux = Context.getAuxTargetInfo();
4874     auto CudaTarget = IdentifyCUDATarget(FD);
4875     bool CheckHost = false, CheckDevice = false;
4876     switch (CudaTarget) {
4877     case CFT_HostDevice:
4878       CheckHost = true;
4879       CheckDevice = true;
4880       break;
4881     case CFT_Host:
4882       CheckHost = true;
4883       break;
4884     case CFT_Device:
4885     case CFT_Global:
4886       CheckDevice = true;
4887       break;
4888     case CFT_InvalidTarget:
4889       llvm_unreachable("unexpected cuda target");
4890     }
4891     auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4892     auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4893     if (CheckHost && HostTI)
4894       A = HostTI->checkCallingConvention(CC);
4895     if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4896       A = DeviceTI->checkCallingConvention(CC);
4897   } else {
4898     A = TI.checkCallingConvention(CC);
4899   }
4900 
4901   switch (A) {
4902   case TargetInfo::CCCR_OK:
4903     break;
4904 
4905   case TargetInfo::CCCR_Ignore:
4906     // Treat an ignored convention as if it was an explicit C calling convention
4907     // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4908     // that command line flags that change the default convention to
4909     // __vectorcall don't affect declarations marked __stdcall.
4910     CC = CC_C;
4911     break;
4912 
4913   case TargetInfo::CCCR_Error:
4914     Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4915         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4916     break;
4917 
4918   case TargetInfo::CCCR_Warning: {
4919     Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4920         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4921 
4922     // This convention is not valid for the target. Use the default function or
4923     // method calling convention.
4924     bool IsCXXMethod = false, IsVariadic = false;
4925     if (FD) {
4926       IsCXXMethod = FD->isCXXInstanceMember();
4927       IsVariadic = FD->isVariadic();
4928     }
4929     CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4930     break;
4931   }
4932   }
4933 
4934   Attrs.setProcessingCache((unsigned) CC);
4935   return false;
4936 }
4937 
4938 /// Pointer-like types in the default address space.
4939 static bool isValidSwiftContextType(QualType Ty) {
4940   if (!Ty->hasPointerRepresentation())
4941     return Ty->isDependentType();
4942   return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4943 }
4944 
4945 /// Pointers and references in the default address space.
4946 static bool isValidSwiftIndirectResultType(QualType Ty) {
4947   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4948     Ty = PtrType->getPointeeType();
4949   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4950     Ty = RefType->getPointeeType();
4951   } else {
4952     return Ty->isDependentType();
4953   }
4954   return Ty.getAddressSpace() == LangAS::Default;
4955 }
4956 
4957 /// Pointers and references to pointers in the default address space.
4958 static bool isValidSwiftErrorResultType(QualType Ty) {
4959   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4960     Ty = PtrType->getPointeeType();
4961   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4962     Ty = RefType->getPointeeType();
4963   } else {
4964     return Ty->isDependentType();
4965   }
4966   if (!Ty.getQualifiers().empty())
4967     return false;
4968   return isValidSwiftContextType(Ty);
4969 }
4970 
4971 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
4972                                ParameterABI abi) {
4973 
4974   QualType type = cast<ParmVarDecl>(D)->getType();
4975 
4976   if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4977     if (existingAttr->getABI() != abi) {
4978       Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4979           << getParameterABISpelling(abi) << existingAttr;
4980       Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4981       return;
4982     }
4983   }
4984 
4985   switch (abi) {
4986   case ParameterABI::Ordinary:
4987     llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4988 
4989   case ParameterABI::SwiftContext:
4990     if (!isValidSwiftContextType(type)) {
4991       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4992           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
4993     }
4994     D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
4995     return;
4996 
4997   case ParameterABI::SwiftAsyncContext:
4998     if (!isValidSwiftContextType(type)) {
4999       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5000           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5001     }
5002     D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5003     return;
5004 
5005   case ParameterABI::SwiftErrorResult:
5006     if (!isValidSwiftErrorResultType(type)) {
5007       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5008           << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5009     }
5010     D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5011     return;
5012 
5013   case ParameterABI::SwiftIndirectResult:
5014     if (!isValidSwiftIndirectResultType(type)) {
5015       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5016           << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5017     }
5018     D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5019     return;
5020   }
5021   llvm_unreachable("bad parameter ABI attribute");
5022 }
5023 
5024 /// Checks a regparm attribute, returning true if it is ill-formed and
5025 /// otherwise setting numParams to the appropriate value.
5026 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5027   if (AL.isInvalid())
5028     return true;
5029 
5030   if (!AL.checkExactlyNumArgs(*this, 1)) {
5031     AL.setInvalid();
5032     return true;
5033   }
5034 
5035   uint32_t NP;
5036   Expr *NumParamsExpr = AL.getArgAsExpr(0);
5037   if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
5038     AL.setInvalid();
5039     return true;
5040   }
5041 
5042   if (Context.getTargetInfo().getRegParmMax() == 0) {
5043     Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5044       << NumParamsExpr->getSourceRange();
5045     AL.setInvalid();
5046     return true;
5047   }
5048 
5049   numParams = NP;
5050   if (numParams > Context.getTargetInfo().getRegParmMax()) {
5051     Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5052       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5053     AL.setInvalid();
5054     return true;
5055   }
5056 
5057   return false;
5058 }
5059 
5060 // Checks whether an argument of launch_bounds attribute is
5061 // acceptable, performs implicit conversion to Rvalue, and returns
5062 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5063 // and may output an error.
5064 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5065                                      const CUDALaunchBoundsAttr &AL,
5066                                      const unsigned Idx) {
5067   if (S.DiagnoseUnexpandedParameterPack(E))
5068     return nullptr;
5069 
5070   // Accept template arguments for now as they depend on something else.
5071   // We'll get to check them when they eventually get instantiated.
5072   if (E->isValueDependent())
5073     return E;
5074 
5075   Optional<llvm::APSInt> I = llvm::APSInt(64);
5076   if (!(I = E->getIntegerConstantExpr(S.Context))) {
5077     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5078         << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5079     return nullptr;
5080   }
5081   // Make sure we can fit it in 32 bits.
5082   if (!I->isIntN(32)) {
5083     S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5084         << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5085     return nullptr;
5086   }
5087   if (*I < 0)
5088     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5089         << &AL << Idx << E->getSourceRange();
5090 
5091   // We may need to perform implicit conversion of the argument.
5092   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5093       S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5094   ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5095   assert(!ValArg.isInvalid() &&
5096          "Unexpected PerformCopyInitialization() failure.");
5097 
5098   return ValArg.getAs<Expr>();
5099 }
5100 
5101 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5102                                Expr *MaxThreads, Expr *MinBlocks) {
5103   CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
5104   MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5105   if (MaxThreads == nullptr)
5106     return;
5107 
5108   if (MinBlocks) {
5109     MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5110     if (MinBlocks == nullptr)
5111       return;
5112   }
5113 
5114   D->addAttr(::new (Context)
5115                  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
5116 }
5117 
5118 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5119   if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
5120     return;
5121 
5122   S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5123                         AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
5124 }
5125 
5126 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5127                                           const ParsedAttr &AL) {
5128   if (!AL.isArgIdent(0)) {
5129     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5130         << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5131     return;
5132   }
5133 
5134   ParamIdx ArgumentIdx;
5135   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5136                                            ArgumentIdx))
5137     return;
5138 
5139   ParamIdx TypeTagIdx;
5140   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5141                                            TypeTagIdx))
5142     return;
5143 
5144   bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5145   if (IsPointer) {
5146     // Ensure that buffer has a pointer type.
5147     unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5148     if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5149         !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5150       S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5151   }
5152 
5153   D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5154       S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5155       IsPointer));
5156 }
5157 
5158 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5159                                          const ParsedAttr &AL) {
5160   if (!AL.isArgIdent(0)) {
5161     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5162         << AL << 1 << AANT_ArgumentIdentifier;
5163     return;
5164   }
5165 
5166   if (!AL.checkExactlyNumArgs(S, 1))
5167     return;
5168 
5169   if (!isa<VarDecl>(D)) {
5170     S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5171         << AL << ExpectedVariable;
5172     return;
5173   }
5174 
5175   IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5176   TypeSourceInfo *MatchingCTypeLoc = nullptr;
5177   S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5178   assert(MatchingCTypeLoc && "no type source info for attribute argument");
5179 
5180   D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5181       S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5182       AL.getMustBeNull()));
5183 }
5184 
5185 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5186   ParamIdx ArgCount;
5187 
5188   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5189                                            ArgCount,
5190                                            true /* CanIndexImplicitThis */))
5191     return;
5192 
5193   // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5194   D->addAttr(::new (S.Context)
5195                  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5196 }
5197 
5198 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5199                                              const ParsedAttr &AL) {
5200   uint32_t Count = 0, Offset = 0;
5201   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5202     return;
5203   if (AL.getNumArgs() == 2) {
5204     Expr *Arg = AL.getArgAsExpr(1);
5205     if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5206       return;
5207     if (Count < Offset) {
5208       S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5209           << &AL << 0 << Count << Arg->getBeginLoc();
5210       return;
5211     }
5212   }
5213   D->addAttr(::new (S.Context)
5214                  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5215 }
5216 
5217 namespace {
5218 struct IntrinToName {
5219   uint32_t Id;
5220   int32_t FullName;
5221   int32_t ShortName;
5222 };
5223 } // unnamed namespace
5224 
5225 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5226                                  ArrayRef<IntrinToName> Map,
5227                                  const char *IntrinNames) {
5228   if (AliasName.startswith("__arm_"))
5229     AliasName = AliasName.substr(6);
5230   const IntrinToName *It = std::lower_bound(
5231       Map.begin(), Map.end(), BuiltinID,
5232       [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
5233   if (It == Map.end() || It->Id != BuiltinID)
5234     return false;
5235   StringRef FullName(&IntrinNames[It->FullName]);
5236   if (AliasName == FullName)
5237     return true;
5238   if (It->ShortName == -1)
5239     return false;
5240   StringRef ShortName(&IntrinNames[It->ShortName]);
5241   return AliasName == ShortName;
5242 }
5243 
5244 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5245 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5246   // The included file defines:
5247   // - ArrayRef<IntrinToName> Map
5248   // - const char IntrinNames[]
5249   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5250 }
5251 
5252 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5253 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5254   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5255 }
5256 
5257 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5258                              StringRef AliasName) {
5259   if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5260     BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5261   return BuiltinID >= AArch64::FirstSVEBuiltin &&
5262          BuiltinID <= AArch64::LastSVEBuiltin;
5263 }
5264 
5265 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5266   if (!AL.isArgIdent(0)) {
5267     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5268         << AL << 1 << AANT_ArgumentIdentifier;
5269     return;
5270   }
5271 
5272   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5273   unsigned BuiltinID = Ident->getBuiltinID();
5274   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5275 
5276   bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5277   if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5278       (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5279        !ArmCdeAliasValid(BuiltinID, AliasName))) {
5280     S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5281     return;
5282   }
5283 
5284   D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5285 }
5286 
5287 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
5288   return BuiltinID >= Builtin::FirstTSBuiltin &&
5289          BuiltinID < RISCV::LastTSBuiltin;
5290 }
5291 
5292 static void handleBuiltinAliasAttr(Sema &S, Decl *D,
5293                                         const ParsedAttr &AL) {
5294   if (!AL.isArgIdent(0)) {
5295     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5296         << AL << 1 << AANT_ArgumentIdentifier;
5297     return;
5298   }
5299 
5300   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5301   unsigned BuiltinID = Ident->getBuiltinID();
5302   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5303 
5304   bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5305   bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
5306   bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
5307   if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5308       (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
5309        !ArmCdeAliasValid(BuiltinID, AliasName)) ||
5310       (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
5311       (!IsAArch64 && !IsARM && !IsRISCV)) {
5312     S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
5313     return;
5314   }
5315 
5316   D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
5317 }
5318 
5319 //===----------------------------------------------------------------------===//
5320 // Checker-specific attribute handlers.
5321 //===----------------------------------------------------------------------===//
5322 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5323   return QT->isDependentType() || QT->isObjCRetainableType();
5324 }
5325 
5326 static bool isValidSubjectOfNSAttribute(QualType QT) {
5327   return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5328          QT->isObjCNSObjectType();
5329 }
5330 
5331 static bool isValidSubjectOfCFAttribute(QualType QT) {
5332   return QT->isDependentType() || QT->isPointerType() ||
5333          isValidSubjectOfNSAttribute(QT);
5334 }
5335 
5336 static bool isValidSubjectOfOSAttribute(QualType QT) {
5337   if (QT->isDependentType())
5338     return true;
5339   QualType PT = QT->getPointeeType();
5340   return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5341 }
5342 
5343 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5344                             RetainOwnershipKind K,
5345                             bool IsTemplateInstantiation) {
5346   ValueDecl *VD = cast<ValueDecl>(D);
5347   switch (K) {
5348   case RetainOwnershipKind::OS:
5349     handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5350         *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5351         diag::warn_ns_attribute_wrong_parameter_type,
5352         /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5353     return;
5354   case RetainOwnershipKind::NS:
5355     handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5356         *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5357 
5358         // These attributes are normally just advisory, but in ARC, ns_consumed
5359         // is significant.  Allow non-dependent code to contain inappropriate
5360         // attributes even in ARC, but require template instantiations to be
5361         // set up correctly.
5362         ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5363              ? diag::err_ns_attribute_wrong_parameter_type
5364              : diag::warn_ns_attribute_wrong_parameter_type),
5365         /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5366     return;
5367   case RetainOwnershipKind::CF:
5368     handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5369         *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5370         diag::warn_ns_attribute_wrong_parameter_type,
5371         /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5372     return;
5373   }
5374 }
5375 
5376 static Sema::RetainOwnershipKind
5377 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5378   switch (AL.getKind()) {
5379   case ParsedAttr::AT_CFConsumed:
5380   case ParsedAttr::AT_CFReturnsRetained:
5381   case ParsedAttr::AT_CFReturnsNotRetained:
5382     return Sema::RetainOwnershipKind::CF;
5383   case ParsedAttr::AT_OSConsumesThis:
5384   case ParsedAttr::AT_OSConsumed:
5385   case ParsedAttr::AT_OSReturnsRetained:
5386   case ParsedAttr::AT_OSReturnsNotRetained:
5387   case ParsedAttr::AT_OSReturnsRetainedOnZero:
5388   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5389     return Sema::RetainOwnershipKind::OS;
5390   case ParsedAttr::AT_NSConsumesSelf:
5391   case ParsedAttr::AT_NSConsumed:
5392   case ParsedAttr::AT_NSReturnsRetained:
5393   case ParsedAttr::AT_NSReturnsNotRetained:
5394   case ParsedAttr::AT_NSReturnsAutoreleased:
5395     return Sema::RetainOwnershipKind::NS;
5396   default:
5397     llvm_unreachable("Wrong argument supplied");
5398   }
5399 }
5400 
5401 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5402   if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5403     return false;
5404 
5405   Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5406       << "'ns_returns_retained'" << 0 << 0;
5407   return true;
5408 }
5409 
5410 /// \return whether the parameter is a pointer to OSObject pointer.
5411 static bool isValidOSObjectOutParameter(const Decl *D) {
5412   const auto *PVD = dyn_cast<ParmVarDecl>(D);
5413   if (!PVD)
5414     return false;
5415   QualType QT = PVD->getType();
5416   QualType PT = QT->getPointeeType();
5417   return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5418 }
5419 
5420 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5421                                         const ParsedAttr &AL) {
5422   QualType ReturnType;
5423   Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5424 
5425   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5426     ReturnType = MD->getReturnType();
5427   } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5428              (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5429     return; // ignore: was handled as a type attribute
5430   } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5431     ReturnType = PD->getType();
5432   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5433     ReturnType = FD->getReturnType();
5434   } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5435     // Attributes on parameters are used for out-parameters,
5436     // passed as pointers-to-pointers.
5437     unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5438             ? /*pointer-to-CF-pointer*/2
5439             : /*pointer-to-OSObject-pointer*/3;
5440     ReturnType = Param->getType()->getPointeeType();
5441     if (ReturnType.isNull()) {
5442       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5443           << AL << DiagID << AL.getRange();
5444       return;
5445     }
5446   } else if (AL.isUsedAsTypeAttr()) {
5447     return;
5448   } else {
5449     AttributeDeclKind ExpectedDeclKind;
5450     switch (AL.getKind()) {
5451     default: llvm_unreachable("invalid ownership attribute");
5452     case ParsedAttr::AT_NSReturnsRetained:
5453     case ParsedAttr::AT_NSReturnsAutoreleased:
5454     case ParsedAttr::AT_NSReturnsNotRetained:
5455       ExpectedDeclKind = ExpectedFunctionOrMethod;
5456       break;
5457 
5458     case ParsedAttr::AT_OSReturnsRetained:
5459     case ParsedAttr::AT_OSReturnsNotRetained:
5460     case ParsedAttr::AT_CFReturnsRetained:
5461     case ParsedAttr::AT_CFReturnsNotRetained:
5462       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5463       break;
5464     }
5465     S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5466         << AL.getRange() << AL << ExpectedDeclKind;
5467     return;
5468   }
5469 
5470   bool TypeOK;
5471   bool Cf;
5472   unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5473   switch (AL.getKind()) {
5474   default: llvm_unreachable("invalid ownership attribute");
5475   case ParsedAttr::AT_NSReturnsRetained:
5476     TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5477     Cf = false;
5478     break;
5479 
5480   case ParsedAttr::AT_NSReturnsAutoreleased:
5481   case ParsedAttr::AT_NSReturnsNotRetained:
5482     TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5483     Cf = false;
5484     break;
5485 
5486   case ParsedAttr::AT_CFReturnsRetained:
5487   case ParsedAttr::AT_CFReturnsNotRetained:
5488     TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5489     Cf = true;
5490     break;
5491 
5492   case ParsedAttr::AT_OSReturnsRetained:
5493   case ParsedAttr::AT_OSReturnsNotRetained:
5494     TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5495     Cf = true;
5496     ParmDiagID = 3; // Pointer-to-OSObject-pointer
5497     break;
5498   }
5499 
5500   if (!TypeOK) {
5501     if (AL.isUsedAsTypeAttr())
5502       return;
5503 
5504     if (isa<ParmVarDecl>(D)) {
5505       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5506           << AL << ParmDiagID << AL.getRange();
5507     } else {
5508       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5509       enum : unsigned {
5510         Function,
5511         Method,
5512         Property
5513       } SubjectKind = Function;
5514       if (isa<ObjCMethodDecl>(D))
5515         SubjectKind = Method;
5516       else if (isa<ObjCPropertyDecl>(D))
5517         SubjectKind = Property;
5518       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5519           << AL << SubjectKind << Cf << AL.getRange();
5520     }
5521     return;
5522   }
5523 
5524   switch (AL.getKind()) {
5525     default:
5526       llvm_unreachable("invalid ownership attribute");
5527     case ParsedAttr::AT_NSReturnsAutoreleased:
5528       handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5529       return;
5530     case ParsedAttr::AT_CFReturnsNotRetained:
5531       handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5532       return;
5533     case ParsedAttr::AT_NSReturnsNotRetained:
5534       handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5535       return;
5536     case ParsedAttr::AT_CFReturnsRetained:
5537       handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5538       return;
5539     case ParsedAttr::AT_NSReturnsRetained:
5540       handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5541       return;
5542     case ParsedAttr::AT_OSReturnsRetained:
5543       handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5544       return;
5545     case ParsedAttr::AT_OSReturnsNotRetained:
5546       handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5547       return;
5548   };
5549 }
5550 
5551 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5552                                               const ParsedAttr &Attrs) {
5553   const int EP_ObjCMethod = 1;
5554   const int EP_ObjCProperty = 2;
5555 
5556   SourceLocation loc = Attrs.getLoc();
5557   QualType resultType;
5558   if (isa<ObjCMethodDecl>(D))
5559     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5560   else
5561     resultType = cast<ObjCPropertyDecl>(D)->getType();
5562 
5563   if (!resultType->isReferenceType() &&
5564       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5565     S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5566         << SourceRange(loc) << Attrs
5567         << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5568         << /*non-retainable pointer*/ 2;
5569 
5570     // Drop the attribute.
5571     return;
5572   }
5573 
5574   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5575 }
5576 
5577 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5578                                         const ParsedAttr &Attrs) {
5579   const auto *Method = cast<ObjCMethodDecl>(D);
5580 
5581   const DeclContext *DC = Method->getDeclContext();
5582   if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5583     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5584                                                                       << 0;
5585     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5586     return;
5587   }
5588   if (Method->getMethodFamily() == OMF_dealloc) {
5589     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5590                                                                       << 1;
5591     return;
5592   }
5593 
5594   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5595 }
5596 
5597 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
5598   auto *E = AL.getArgAsExpr(0);
5599   auto Loc = E ? E->getBeginLoc() : AL.getLoc();
5600 
5601   auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
5602   if (!DRE) {
5603     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
5604     return;
5605   }
5606 
5607   auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
5608   if (!VD) {
5609     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
5610     return;
5611   }
5612 
5613   if (!isNSStringType(VD->getType(), S.Context) &&
5614       !isCFStringType(VD->getType(), S.Context)) {
5615     S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
5616     return;
5617   }
5618 
5619   D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
5620 }
5621 
5622 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5623   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5624 
5625   if (!Parm) {
5626     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5627     return;
5628   }
5629 
5630   // Typedefs only allow objc_bridge(id) and have some additional checking.
5631   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5632     if (!Parm->Ident->isStr("id")) {
5633       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5634       return;
5635     }
5636 
5637     // Only allow 'cv void *'.
5638     QualType T = TD->getUnderlyingType();
5639     if (!T->isVoidPointerType()) {
5640       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5641       return;
5642     }
5643   }
5644 
5645   D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5646 }
5647 
5648 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5649                                         const ParsedAttr &AL) {
5650   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5651 
5652   if (!Parm) {
5653     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5654     return;
5655   }
5656 
5657   D->addAttr(::new (S.Context)
5658                  ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5659 }
5660 
5661 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5662                                         const ParsedAttr &AL) {
5663   IdentifierInfo *RelatedClass =
5664       AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5665   if (!RelatedClass) {
5666     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5667     return;
5668   }
5669   IdentifierInfo *ClassMethod =
5670     AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5671   IdentifierInfo *InstanceMethod =
5672     AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5673   D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5674       S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5675 }
5676 
5677 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5678                                             const ParsedAttr &AL) {
5679   DeclContext *Ctx = D->getDeclContext();
5680 
5681   // This attribute can only be applied to methods in interfaces or class
5682   // extensions.
5683   if (!isa<ObjCInterfaceDecl>(Ctx) &&
5684       !(isa<ObjCCategoryDecl>(Ctx) &&
5685         cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5686     S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5687     return;
5688   }
5689 
5690   ObjCInterfaceDecl *IFace;
5691   if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5692     IFace = CatDecl->getClassInterface();
5693   else
5694     IFace = cast<ObjCInterfaceDecl>(Ctx);
5695 
5696   if (!IFace)
5697     return;
5698 
5699   IFace->setHasDesignatedInitializers();
5700   D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5701 }
5702 
5703 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5704   StringRef MetaDataName;
5705   if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5706     return;
5707   D->addAttr(::new (S.Context)
5708                  ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5709 }
5710 
5711 // When a user wants to use objc_boxable with a union or struct
5712 // but they don't have access to the declaration (legacy/third-party code)
5713 // then they can 'enable' this feature with a typedef:
5714 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5715 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5716   bool notify = false;
5717 
5718   auto *RD = dyn_cast<RecordDecl>(D);
5719   if (RD && RD->getDefinition()) {
5720     RD = RD->getDefinition();
5721     notify = true;
5722   }
5723 
5724   if (RD) {
5725     ObjCBoxableAttr *BoxableAttr =
5726         ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5727     RD->addAttr(BoxableAttr);
5728     if (notify) {
5729       // we need to notify ASTReader/ASTWriter about
5730       // modification of existing declaration
5731       if (ASTMutationListener *L = S.getASTMutationListener())
5732         L->AddedAttributeToRecord(BoxableAttr, RD);
5733     }
5734   }
5735 }
5736 
5737 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5738   if (hasDeclarator(D)) return;
5739 
5740   S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5741       << AL.getRange() << AL << ExpectedVariable;
5742 }
5743 
5744 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5745                                           const ParsedAttr &AL) {
5746   const auto *VD = cast<ValueDecl>(D);
5747   QualType QT = VD->getType();
5748 
5749   if (!QT->isDependentType() &&
5750       !QT->isObjCLifetimeType()) {
5751     S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5752       << QT;
5753     return;
5754   }
5755 
5756   Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5757 
5758   // If we have no lifetime yet, check the lifetime we're presumably
5759   // going to infer.
5760   if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5761     Lifetime = QT->getObjCARCImplicitLifetime();
5762 
5763   switch (Lifetime) {
5764   case Qualifiers::OCL_None:
5765     assert(QT->isDependentType() &&
5766            "didn't infer lifetime for non-dependent type?");
5767     break;
5768 
5769   case Qualifiers::OCL_Weak:   // meaningful
5770   case Qualifiers::OCL_Strong: // meaningful
5771     break;
5772 
5773   case Qualifiers::OCL_ExplicitNone:
5774   case Qualifiers::OCL_Autoreleasing:
5775     S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5776         << (Lifetime == Qualifiers::OCL_Autoreleasing);
5777     break;
5778   }
5779 
5780   D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5781 }
5782 
5783 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5784   // Make sure that there is a string literal as the annotation's single
5785   // argument.
5786   StringRef Str;
5787   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
5788     return;
5789 
5790   D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
5791 }
5792 
5793 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
5794   // Make sure that there is a string literal as the annotation's single
5795   // argument.
5796   StringRef BT;
5797   if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
5798     return;
5799 
5800   // Warn about duplicate attributes if they have different arguments, but drop
5801   // any duplicate attributes regardless.
5802   if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
5803     if (Other->getSwiftType() != BT)
5804       S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
5805     return;
5806   }
5807 
5808   D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
5809 }
5810 
5811 static bool isErrorParameter(Sema &S, QualType QT) {
5812   const auto *PT = QT->getAs<PointerType>();
5813   if (!PT)
5814     return false;
5815 
5816   QualType Pointee = PT->getPointeeType();
5817 
5818   // Check for NSError**.
5819   if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
5820     if (const auto *ID = OPT->getInterfaceDecl())
5821       if (ID->getIdentifier() == S.getNSErrorIdent())
5822         return true;
5823 
5824   // Check for CFError**.
5825   if (const auto *PT = Pointee->getAs<PointerType>())
5826     if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
5827       if (S.isCFError(RT->getDecl()))
5828         return true;
5829 
5830   return false;
5831 }
5832 
5833 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
5834   auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5835     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
5836       if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
5837         return true;
5838     }
5839 
5840     S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
5841         << AL << isa<ObjCMethodDecl>(D);
5842     return false;
5843   };
5844 
5845   auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5846     // - C, ObjC, and block pointers are definitely okay.
5847     // - References are definitely not okay.
5848     // - nullptr_t is weird, but acceptable.
5849     QualType RT = getFunctionOrMethodResultType(D);
5850     if (RT->hasPointerRepresentation() && !RT->isReferenceType())
5851       return true;
5852 
5853     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5854         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5855         << /*pointer*/ 1;
5856     return false;
5857   };
5858 
5859   auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5860     QualType RT = getFunctionOrMethodResultType(D);
5861     if (RT->isIntegralType(S.Context))
5862       return true;
5863 
5864     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5865         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5866         << /*integral*/ 0;
5867     return false;
5868   };
5869 
5870   if (D->isInvalidDecl())
5871     return;
5872 
5873   IdentifierLoc *Loc = AL.getArgAsIdent(0);
5874   SwiftErrorAttr::ConventionKind Convention;
5875   if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
5876                                                   Convention)) {
5877     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5878         << AL << Loc->Ident;
5879     return;
5880   }
5881 
5882   switch (Convention) {
5883   case SwiftErrorAttr::None:
5884     // No additional validation required.
5885     break;
5886 
5887   case SwiftErrorAttr::NonNullError:
5888     if (!hasErrorParameter(S, D, AL))
5889       return;
5890     break;
5891 
5892   case SwiftErrorAttr::NullResult:
5893     if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
5894       return;
5895     break;
5896 
5897   case SwiftErrorAttr::NonZeroResult:
5898   case SwiftErrorAttr::ZeroResult:
5899     if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
5900       return;
5901     break;
5902   }
5903 
5904   D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
5905 }
5906 
5907 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
5908                                       const SwiftAsyncErrorAttr *ErrorAttr,
5909                                       const SwiftAsyncAttr *AsyncAttr) {
5910   if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
5911     if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
5912       S.Diag(AsyncAttr->getLocation(),
5913              diag::err_swift_async_error_without_swift_async)
5914           << AsyncAttr << isa<ObjCMethodDecl>(D);
5915     }
5916     return;
5917   }
5918 
5919   const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
5920       D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
5921   // handleSwiftAsyncAttr already verified the type is correct, so no need to
5922   // double-check it here.
5923   const auto *FuncTy = HandlerParam->getType()
5924                            ->castAs<BlockPointerType>()
5925                            ->getPointeeType()
5926                            ->getAs<FunctionProtoType>();
5927   ArrayRef<QualType> BlockParams;
5928   if (FuncTy)
5929     BlockParams = FuncTy->getParamTypes();
5930 
5931   switch (ErrorAttr->getConvention()) {
5932   case SwiftAsyncErrorAttr::ZeroArgument:
5933   case SwiftAsyncErrorAttr::NonZeroArgument: {
5934     uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
5935     if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
5936       S.Diag(ErrorAttr->getLocation(),
5937              diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
5938       return;
5939     }
5940     QualType ErrorParam = BlockParams[ParamIdx - 1];
5941     if (!ErrorParam->isIntegralType(S.Context)) {
5942       StringRef ConvStr =
5943           ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
5944               ? "zero_argument"
5945               : "nonzero_argument";
5946       S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
5947           << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
5948       return;
5949     }
5950     break;
5951   }
5952   case SwiftAsyncErrorAttr::NonNullError: {
5953     bool AnyErrorParams = false;
5954     for (QualType Param : BlockParams) {
5955       // Check for NSError *.
5956       if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
5957         if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
5958           if (ID->getIdentifier() == S.getNSErrorIdent()) {
5959             AnyErrorParams = true;
5960             break;
5961           }
5962         }
5963       }
5964       // Check for CFError *.
5965       if (const auto *PtrTy = Param->getAs<PointerType>()) {
5966         if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
5967           if (S.isCFError(RT->getDecl())) {
5968             AnyErrorParams = true;
5969             break;
5970           }
5971         }
5972       }
5973     }
5974 
5975     if (!AnyErrorParams) {
5976       S.Diag(ErrorAttr->getLocation(),
5977              diag::err_swift_async_error_no_error_parameter)
5978           << ErrorAttr << isa<ObjCMethodDecl>(D);
5979       return;
5980     }
5981     break;
5982   }
5983   case SwiftAsyncErrorAttr::None:
5984     break;
5985   }
5986 }
5987 
5988 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
5989   IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
5990   SwiftAsyncErrorAttr::ConventionKind ConvKind;
5991   if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
5992                                                        ConvKind)) {
5993     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5994         << AL << IDLoc->Ident;
5995     return;
5996   }
5997 
5998   uint32_t ParamIdx = 0;
5999   switch (ConvKind) {
6000   case SwiftAsyncErrorAttr::ZeroArgument:
6001   case SwiftAsyncErrorAttr::NonZeroArgument: {
6002     if (!AL.checkExactlyNumArgs(S, 2))
6003       return;
6004 
6005     Expr *IdxExpr = AL.getArgAsExpr(1);
6006     if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
6007       return;
6008     break;
6009   }
6010   case SwiftAsyncErrorAttr::NonNullError:
6011   case SwiftAsyncErrorAttr::None: {
6012     if (!AL.checkExactlyNumArgs(S, 1))
6013       return;
6014     break;
6015   }
6016   }
6017 
6018   auto *ErrorAttr =
6019       ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
6020   D->addAttr(ErrorAttr);
6021 
6022   if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
6023     checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6024 }
6025 
6026 // For a function, this will validate a compound Swift name, e.g.
6027 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6028 // the function will output the number of parameter names, and whether this is a
6029 // single-arg initializer.
6030 //
6031 // For a type, enum constant, property, or variable declaration, this will
6032 // validate either a simple identifier, or a qualified
6033 // <code>context.identifier</code> name.
6034 static bool
6035 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
6036                           StringRef Name, unsigned &SwiftParamCount,
6037                           bool &IsSingleParamInit) {
6038   SwiftParamCount = 0;
6039   IsSingleParamInit = false;
6040 
6041   // Check whether this will be mapped to a getter or setter of a property.
6042   bool IsGetter = false, IsSetter = false;
6043   if (Name.startswith("getter:")) {
6044     IsGetter = true;
6045     Name = Name.substr(7);
6046   } else if (Name.startswith("setter:")) {
6047     IsSetter = true;
6048     Name = Name.substr(7);
6049   }
6050 
6051   if (Name.back() != ')') {
6052     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6053     return false;
6054   }
6055 
6056   bool IsMember = false;
6057   StringRef ContextName, BaseName, Parameters;
6058 
6059   std::tie(BaseName, Parameters) = Name.split('(');
6060 
6061   // Split at the first '.', if it exists, which separates the context name
6062   // from the base name.
6063   std::tie(ContextName, BaseName) = BaseName.split('.');
6064   if (BaseName.empty()) {
6065     BaseName = ContextName;
6066     ContextName = StringRef();
6067   } else if (ContextName.empty() || !isValidIdentifier(ContextName)) {
6068     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6069         << AL << /*context*/ 1;
6070     return false;
6071   } else {
6072     IsMember = true;
6073   }
6074 
6075   if (!isValidIdentifier(BaseName) || BaseName == "_") {
6076     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6077         << AL << /*basename*/ 0;
6078     return false;
6079   }
6080 
6081   bool IsSubscript = BaseName == "subscript";
6082   // A subscript accessor must be a getter or setter.
6083   if (IsSubscript && !IsGetter && !IsSetter) {
6084     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6085         << AL << /* getter or setter */ 0;
6086     return false;
6087   }
6088 
6089   if (Parameters.empty()) {
6090     S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
6091     return false;
6092   }
6093 
6094   assert(Parameters.back() == ')' && "expected ')'");
6095   Parameters = Parameters.drop_back(); // ')'
6096 
6097   if (Parameters.empty()) {
6098     // Setters and subscripts must have at least one parameter.
6099     if (IsSubscript) {
6100       S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6101           << AL << /* have at least one parameter */1;
6102       return false;
6103     }
6104 
6105     if (IsSetter) {
6106       S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
6107       return false;
6108     }
6109 
6110     return true;
6111   }
6112 
6113   if (Parameters.back() != ':') {
6114     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6115     return false;
6116   }
6117 
6118   StringRef CurrentParam;
6119   llvm::Optional<unsigned> SelfLocation;
6120   unsigned NewValueCount = 0;
6121   llvm::Optional<unsigned> NewValueLocation;
6122   do {
6123     std::tie(CurrentParam, Parameters) = Parameters.split(':');
6124 
6125     if (!isValidIdentifier(CurrentParam)) {
6126       S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6127           << AL << /*parameter*/2;
6128       return false;
6129     }
6130 
6131     if (IsMember && CurrentParam == "self") {
6132       // "self" indicates the "self" argument for a member.
6133 
6134       // More than one "self"?
6135       if (SelfLocation) {
6136         S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
6137         return false;
6138       }
6139 
6140       // The "self" location is the current parameter.
6141       SelfLocation = SwiftParamCount;
6142     } else if (CurrentParam == "newValue") {
6143       // "newValue" indicates the "newValue" argument for a setter.
6144 
6145       // There should only be one 'newValue', but it's only significant for
6146       // subscript accessors, so don't error right away.
6147       ++NewValueCount;
6148 
6149       NewValueLocation = SwiftParamCount;
6150     }
6151 
6152     ++SwiftParamCount;
6153   } while (!Parameters.empty());
6154 
6155   // Only instance subscripts are currently supported.
6156   if (IsSubscript && !SelfLocation) {
6157     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6158         << AL << /*have a 'self:' parameter*/2;
6159     return false;
6160   }
6161 
6162   IsSingleParamInit =
6163         SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
6164 
6165   // Check the number of parameters for a getter/setter.
6166   if (IsGetter || IsSetter) {
6167     // Setters have one parameter for the new value.
6168     unsigned NumExpectedParams = IsGetter ? 0 : 1;
6169     unsigned ParamDiag =
6170         IsGetter ? diag::warn_attr_swift_name_getter_parameters
6171                  : diag::warn_attr_swift_name_setter_parameters;
6172 
6173     // Instance methods have one parameter for "self".
6174     if (SelfLocation)
6175       ++NumExpectedParams;
6176 
6177     // Subscripts may have additional parameters beyond the expected params for
6178     // the index.
6179     if (IsSubscript) {
6180       if (SwiftParamCount < NumExpectedParams) {
6181         S.Diag(Loc, ParamDiag) << AL;
6182         return false;
6183       }
6184 
6185       // A subscript setter must explicitly label its newValue parameter to
6186       // distinguish it from index parameters.
6187       if (IsSetter) {
6188         if (!NewValueLocation) {
6189           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
6190               << AL;
6191           return false;
6192         }
6193         if (NewValueCount > 1) {
6194           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6195               << AL;
6196           return false;
6197         }
6198       } else {
6199         // Subscript getters should have no 'newValue:' parameter.
6200         if (NewValueLocation) {
6201           S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6202               << AL;
6203           return false;
6204         }
6205       }
6206     } else {
6207       // Property accessors must have exactly the number of expected params.
6208       if (SwiftParamCount != NumExpectedParams) {
6209         S.Diag(Loc, ParamDiag) << AL;
6210         return false;
6211       }
6212     }
6213   }
6214 
6215   return true;
6216 }
6217 
6218 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6219                              const ParsedAttr &AL, bool IsAsync) {
6220   if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
6221     ArrayRef<ParmVarDecl*> Params;
6222     unsigned ParamCount;
6223 
6224     if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
6225       ParamCount = Method->getSelector().getNumArgs();
6226       Params = Method->parameters().slice(0, ParamCount);
6227     } else {
6228       const auto *F = cast<FunctionDecl>(D);
6229 
6230       ParamCount = F->getNumParams();
6231       Params = F->parameters();
6232 
6233       if (!F->hasWrittenPrototype()) {
6234         Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL
6235             << ExpectedFunctionWithProtoType;
6236         return false;
6237       }
6238     }
6239 
6240     // The async name drops the last callback parameter.
6241     if (IsAsync) {
6242       if (ParamCount == 0) {
6243         Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6244             << AL << isa<ObjCMethodDecl>(D);
6245         return false;
6246       }
6247       ParamCount -= 1;
6248     }
6249 
6250     unsigned SwiftParamCount;
6251     bool IsSingleParamInit;
6252     if (!validateSwiftFunctionName(*this, AL, Loc, Name,
6253                                    SwiftParamCount, IsSingleParamInit))
6254       return false;
6255 
6256     bool ParamCountValid;
6257     if (SwiftParamCount == ParamCount) {
6258       ParamCountValid = true;
6259     } else if (SwiftParamCount > ParamCount) {
6260       ParamCountValid = IsSingleParamInit && ParamCount == 0;
6261     } else {
6262       // We have fewer Swift parameters than Objective-C parameters, but that
6263       // might be because we've transformed some of them. Check for potential
6264       // "out" parameters and err on the side of not warning.
6265       unsigned MaybeOutParamCount =
6266           std::count_if(Params.begin(), Params.end(),
6267                         [](const ParmVarDecl *Param) -> bool {
6268         QualType ParamTy = Param->getType();
6269         if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6270           return !ParamTy->getPointeeType().isConstQualified();
6271         return false;
6272       });
6273 
6274       ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6275     }
6276 
6277     if (!ParamCountValid) {
6278       Diag(Loc, diag::warn_attr_swift_name_num_params)
6279           << (SwiftParamCount > ParamCount) << AL << ParamCount
6280           << SwiftParamCount;
6281       return false;
6282     }
6283   } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
6284               isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
6285               isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
6286               isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
6287              !IsAsync) {
6288     StringRef ContextName, BaseName;
6289 
6290     std::tie(ContextName, BaseName) = Name.split('.');
6291     if (BaseName.empty()) {
6292       BaseName = ContextName;
6293       ContextName = StringRef();
6294     } else if (!isValidIdentifier(ContextName)) {
6295       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6296           << /*context*/1;
6297       return false;
6298     }
6299 
6300     if (!isValidIdentifier(BaseName)) {
6301       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6302           << /*basename*/0;
6303       return false;
6304     }
6305   } else {
6306     Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6307     return false;
6308   }
6309   return true;
6310 }
6311 
6312 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6313   StringRef Name;
6314   SourceLocation Loc;
6315   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6316     return;
6317 
6318   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6319     return;
6320 
6321   D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6322 }
6323 
6324 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6325   StringRef Name;
6326   SourceLocation Loc;
6327   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6328     return;
6329 
6330   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6331     return;
6332 
6333   D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6334 }
6335 
6336 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6337   // Make sure that there is an identifier as the annotation's single argument.
6338   if (!AL.checkExactlyNumArgs(S, 1))
6339     return;
6340 
6341   if (!AL.isArgIdent(0)) {
6342     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6343         << AL << AANT_ArgumentIdentifier;
6344     return;
6345   }
6346 
6347   SwiftNewTypeAttr::NewtypeKind Kind;
6348   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6349   if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
6350     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6351     return;
6352   }
6353 
6354   if (!isa<TypedefNameDecl>(D)) {
6355     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
6356         << AL << "typedefs";
6357     return;
6358   }
6359 
6360   D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
6361 }
6362 
6363 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6364   if (!AL.isArgIdent(0)) {
6365     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
6366         << AL << 1 << AANT_ArgumentIdentifier;
6367     return;
6368   }
6369 
6370   SwiftAsyncAttr::Kind Kind;
6371   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6372   if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
6373     S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
6374     return;
6375   }
6376 
6377   ParamIdx Idx;
6378   if (Kind == SwiftAsyncAttr::None) {
6379     // If this is 'none', then there shouldn't be any additional arguments.
6380     if (!AL.checkExactlyNumArgs(S, 1))
6381       return;
6382   } else {
6383     // Non-none swift_async requires a completion handler index argument.
6384     if (!AL.checkExactlyNumArgs(S, 2))
6385       return;
6386 
6387     Expr *HandlerIdx = AL.getArgAsExpr(1);
6388     if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
6389       return;
6390 
6391     const ParmVarDecl *CompletionBlock =
6392         getFunctionOrMethodParam(D, Idx.getASTIndex());
6393     QualType CompletionBlockType = CompletionBlock->getType();
6394     if (!CompletionBlockType->isBlockPointerType()) {
6395       S.Diag(CompletionBlock->getLocation(),
6396              diag::err_swift_async_bad_block_type)
6397           << CompletionBlock->getType();
6398       return;
6399     }
6400     QualType BlockTy =
6401         CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
6402     if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
6403       S.Diag(CompletionBlock->getLocation(),
6404              diag::err_swift_async_bad_block_type)
6405           << CompletionBlock->getType();
6406       return;
6407     }
6408   }
6409 
6410   auto *AsyncAttr =
6411       ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
6412   D->addAttr(AsyncAttr);
6413 
6414   if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
6415     checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6416 }
6417 
6418 //===----------------------------------------------------------------------===//
6419 // Microsoft specific attribute handlers.
6420 //===----------------------------------------------------------------------===//
6421 
6422 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
6423                               StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
6424   if (const auto *UA = D->getAttr<UuidAttr>()) {
6425     if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
6426       return nullptr;
6427     if (!UA->getGuid().empty()) {
6428       Diag(UA->getLocation(), diag::err_mismatched_uuid);
6429       Diag(CI.getLoc(), diag::note_previous_uuid);
6430       D->dropAttr<UuidAttr>();
6431     }
6432   }
6433 
6434   return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
6435 }
6436 
6437 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6438   if (!S.LangOpts.CPlusPlus) {
6439     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6440         << AL << AttributeLangSupport::C;
6441     return;
6442   }
6443 
6444   StringRef OrigStrRef;
6445   SourceLocation LiteralLoc;
6446   if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
6447     return;
6448 
6449   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
6450   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
6451   StringRef StrRef = OrigStrRef;
6452   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
6453     StrRef = StrRef.drop_front().drop_back();
6454 
6455   // Validate GUID length.
6456   if (StrRef.size() != 36) {
6457     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6458     return;
6459   }
6460 
6461   for (unsigned i = 0; i < 36; ++i) {
6462     if (i == 8 || i == 13 || i == 18 || i == 23) {
6463       if (StrRef[i] != '-') {
6464         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6465         return;
6466       }
6467     } else if (!isHexDigit(StrRef[i])) {
6468       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6469       return;
6470     }
6471   }
6472 
6473   // Convert to our parsed format and canonicalize.
6474   MSGuidDecl::Parts Parsed;
6475   StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
6476   StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
6477   StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
6478   for (unsigned i = 0; i != 8; ++i)
6479     StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
6480         .getAsInteger(16, Parsed.Part4And5[i]);
6481   MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
6482 
6483   // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
6484   // the only thing in the [] list, the [] too), and add an insertion of
6485   // __declspec(uuid(...)).  But sadly, neither the SourceLocs of the commas
6486   // separating attributes nor of the [ and the ] are in the AST.
6487   // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
6488   // on cfe-dev.
6489   if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
6490     S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
6491 
6492   UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
6493   if (UA)
6494     D->addAttr(UA);
6495 }
6496 
6497 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6498   if (!S.LangOpts.CPlusPlus) {
6499     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6500         << AL << AttributeLangSupport::C;
6501     return;
6502   }
6503   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
6504       D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
6505   if (IA) {
6506     D->addAttr(IA);
6507     S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
6508   }
6509 }
6510 
6511 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6512   const auto *VD = cast<VarDecl>(D);
6513   if (!S.Context.getTargetInfo().isTLSSupported()) {
6514     S.Diag(AL.getLoc(), diag::err_thread_unsupported);
6515     return;
6516   }
6517   if (VD->getTSCSpec() != TSCS_unspecified) {
6518     S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
6519     return;
6520   }
6521   if (VD->hasLocalStorage()) {
6522     S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
6523     return;
6524   }
6525   D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
6526 }
6527 
6528 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6529   SmallVector<StringRef, 4> Tags;
6530   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6531     StringRef Tag;
6532     if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
6533       return;
6534     Tags.push_back(Tag);
6535   }
6536 
6537   if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
6538     if (!NS->isInline()) {
6539       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
6540       return;
6541     }
6542     if (NS->isAnonymousNamespace()) {
6543       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
6544       return;
6545     }
6546     if (AL.getNumArgs() == 0)
6547       Tags.push_back(NS->getName());
6548   } else if (!AL.checkAtLeastNumArgs(S, 1))
6549     return;
6550 
6551   // Store tags sorted and without duplicates.
6552   llvm::sort(Tags);
6553   Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
6554 
6555   D->addAttr(::new (S.Context)
6556                  AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
6557 }
6558 
6559 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6560   // Check the attribute arguments.
6561   if (AL.getNumArgs() > 1) {
6562     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6563     return;
6564   }
6565 
6566   StringRef Str;
6567   SourceLocation ArgLoc;
6568 
6569   if (AL.getNumArgs() == 0)
6570     Str = "";
6571   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6572     return;
6573 
6574   ARMInterruptAttr::InterruptType Kind;
6575   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6576     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6577                                                                  << ArgLoc;
6578     return;
6579   }
6580 
6581   D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
6582 }
6583 
6584 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6585   // MSP430 'interrupt' attribute is applied to
6586   // a function with no parameters and void return type.
6587   if (!isFunctionOrMethod(D)) {
6588     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6589         << "'interrupt'" << ExpectedFunctionOrMethod;
6590     return;
6591   }
6592 
6593   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6594     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6595         << /*MSP430*/ 1 << 0;
6596     return;
6597   }
6598 
6599   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6600     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6601         << /*MSP430*/ 1 << 1;
6602     return;
6603   }
6604 
6605   // The attribute takes one integer argument.
6606   if (!AL.checkExactlyNumArgs(S, 1))
6607     return;
6608 
6609   if (!AL.isArgExpr(0)) {
6610     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6611         << AL << AANT_ArgumentIntegerConstant;
6612     return;
6613   }
6614 
6615   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6616   Optional<llvm::APSInt> NumParams = llvm::APSInt(32);
6617   if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
6618     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6619         << AL << AANT_ArgumentIntegerConstant
6620         << NumParamsExpr->getSourceRange();
6621     return;
6622   }
6623   // The argument should be in range 0..63.
6624   unsigned Num = NumParams->getLimitedValue(255);
6625   if (Num > 63) {
6626     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6627         << AL << (int)NumParams->getSExtValue()
6628         << NumParamsExpr->getSourceRange();
6629     return;
6630   }
6631 
6632   D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
6633   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6634 }
6635 
6636 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6637   // Only one optional argument permitted.
6638   if (AL.getNumArgs() > 1) {
6639     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6640     return;
6641   }
6642 
6643   StringRef Str;
6644   SourceLocation ArgLoc;
6645 
6646   if (AL.getNumArgs() == 0)
6647     Str = "";
6648   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6649     return;
6650 
6651   // Semantic checks for a function with the 'interrupt' attribute for MIPS:
6652   // a) Must be a function.
6653   // b) Must have no parameters.
6654   // c) Must have the 'void' return type.
6655   // d) Cannot have the 'mips16' attribute, as that instruction set
6656   //    lacks the 'eret' instruction.
6657   // e) The attribute itself must either have no argument or one of the
6658   //    valid interrupt types, see [MipsInterruptDocs].
6659 
6660   if (!isFunctionOrMethod(D)) {
6661     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6662         << "'interrupt'" << ExpectedFunctionOrMethod;
6663     return;
6664   }
6665 
6666   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6667     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6668         << /*MIPS*/ 0 << 0;
6669     return;
6670   }
6671 
6672   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6673     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6674         << /*MIPS*/ 0 << 1;
6675     return;
6676   }
6677 
6678   // We still have to do this manually because the Interrupt attributes are
6679   // a bit special due to sharing their spellings across targets.
6680   if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
6681     return;
6682 
6683   MipsInterruptAttr::InterruptType Kind;
6684   if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6685     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6686         << AL << "'" + std::string(Str) + "'";
6687     return;
6688   }
6689 
6690   D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
6691 }
6692 
6693 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6694   if (!AL.checkExactlyNumArgs(S, 1))
6695     return;
6696 
6697   if (!AL.isArgExpr(0)) {
6698     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6699         << AL << AANT_ArgumentIntegerConstant;
6700     return;
6701   }
6702 
6703   // FIXME: Check for decl - it should be void ()(void).
6704 
6705   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6706   auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
6707   if (!MaybeNumParams) {
6708     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6709         << AL << AANT_ArgumentIntegerConstant
6710         << NumParamsExpr->getSourceRange();
6711     return;
6712   }
6713 
6714   unsigned Num = MaybeNumParams->getLimitedValue(255);
6715   if ((Num & 1) || Num > 30) {
6716     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6717         << AL << (int)MaybeNumParams->getSExtValue()
6718         << NumParamsExpr->getSourceRange();
6719     return;
6720   }
6721 
6722   D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
6723   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6724 }
6725 
6726 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6727   // Semantic checks for a function with the 'interrupt' attribute.
6728   // a) Must be a function.
6729   // b) Must have the 'void' return type.
6730   // c) Must take 1 or 2 arguments.
6731   // d) The 1st argument must be a pointer.
6732   // e) The 2nd argument (if any) must be an unsigned integer.
6733   if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
6734       CXXMethodDecl::isStaticOverloadedOperator(
6735           cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
6736     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6737         << AL << ExpectedFunctionWithProtoType;
6738     return;
6739   }
6740   // Interrupt handler must have void return type.
6741   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6742     S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
6743            diag::err_anyx86_interrupt_attribute)
6744         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6745                 ? 0
6746                 : 1)
6747         << 0;
6748     return;
6749   }
6750   // Interrupt handler must have 1 or 2 parameters.
6751   unsigned NumParams = getFunctionOrMethodNumParams(D);
6752   if (NumParams < 1 || NumParams > 2) {
6753     S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
6754         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6755                 ? 0
6756                 : 1)
6757         << 1;
6758     return;
6759   }
6760   // The first argument must be a pointer.
6761   if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
6762     S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
6763            diag::err_anyx86_interrupt_attribute)
6764         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6765                 ? 0
6766                 : 1)
6767         << 2;
6768     return;
6769   }
6770   // The second argument, if present, must be an unsigned integer.
6771   unsigned TypeSize =
6772       S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
6773           ? 64
6774           : 32;
6775   if (NumParams == 2 &&
6776       (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
6777        S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
6778     S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
6779            diag::err_anyx86_interrupt_attribute)
6780         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6781                 ? 0
6782                 : 1)
6783         << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
6784     return;
6785   }
6786   D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
6787   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6788 }
6789 
6790 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6791   if (!isFunctionOrMethod(D)) {
6792     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6793         << "'interrupt'" << ExpectedFunction;
6794     return;
6795   }
6796 
6797   if (!AL.checkExactlyNumArgs(S, 0))
6798     return;
6799 
6800   handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
6801 }
6802 
6803 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6804   if (!isFunctionOrMethod(D)) {
6805     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6806         << "'signal'" << ExpectedFunction;
6807     return;
6808   }
6809 
6810   if (!AL.checkExactlyNumArgs(S, 0))
6811     return;
6812 
6813   handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
6814 }
6815 
6816 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
6817   // Add preserve_access_index attribute to all fields and inner records.
6818   for (auto D : RD->decls()) {
6819     if (D->hasAttr<BPFPreserveAccessIndexAttr>())
6820       continue;
6821 
6822     D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
6823     if (auto *Rec = dyn_cast<RecordDecl>(D))
6824       handleBPFPreserveAIRecord(S, Rec);
6825   }
6826 }
6827 
6828 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
6829     const ParsedAttr &AL) {
6830   auto *Rec = cast<RecordDecl>(D);
6831   handleBPFPreserveAIRecord(S, Rec);
6832   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
6833 }
6834 
6835 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6836   if (!isFunctionOrMethod(D)) {
6837     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6838         << "'export_name'" << ExpectedFunction;
6839     return;
6840   }
6841 
6842   auto *FD = cast<FunctionDecl>(D);
6843   if (FD->isThisDeclarationADefinition()) {
6844     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
6845     return;
6846   }
6847 
6848   StringRef Str;
6849   SourceLocation ArgLoc;
6850   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6851     return;
6852 
6853   D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
6854   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6855 }
6856 
6857 WebAssemblyImportModuleAttr *
6858 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
6859   auto *FD = cast<FunctionDecl>(D);
6860 
6861   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
6862     if (ExistingAttr->getImportModule() == AL.getImportModule())
6863       return nullptr;
6864     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
6865       << ExistingAttr->getImportModule() << AL.getImportModule();
6866     Diag(AL.getLoc(), diag::note_previous_attribute);
6867     return nullptr;
6868   }
6869   if (FD->hasBody()) {
6870     Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6871     return nullptr;
6872   }
6873   return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
6874                                                      AL.getImportModule());
6875 }
6876 
6877 WebAssemblyImportNameAttr *
6878 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
6879   auto *FD = cast<FunctionDecl>(D);
6880 
6881   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
6882     if (ExistingAttr->getImportName() == AL.getImportName())
6883       return nullptr;
6884     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
6885       << ExistingAttr->getImportName() << AL.getImportName();
6886     Diag(AL.getLoc(), diag::note_previous_attribute);
6887     return nullptr;
6888   }
6889   if (FD->hasBody()) {
6890     Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6891     return nullptr;
6892   }
6893   return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
6894                                                    AL.getImportName());
6895 }
6896 
6897 static void
6898 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6899   auto *FD = cast<FunctionDecl>(D);
6900 
6901   StringRef Str;
6902   SourceLocation ArgLoc;
6903   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6904     return;
6905   if (FD->hasBody()) {
6906     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6907     return;
6908   }
6909 
6910   FD->addAttr(::new (S.Context)
6911                   WebAssemblyImportModuleAttr(S.Context, AL, Str));
6912 }
6913 
6914 static void
6915 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6916   auto *FD = cast<FunctionDecl>(D);
6917 
6918   StringRef Str;
6919   SourceLocation ArgLoc;
6920   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6921     return;
6922   if (FD->hasBody()) {
6923     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6924     return;
6925   }
6926 
6927   FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
6928 }
6929 
6930 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
6931                                      const ParsedAttr &AL) {
6932   // Warn about repeated attributes.
6933   if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
6934     S.Diag(AL.getRange().getBegin(),
6935       diag::warn_riscv_repeated_interrupt_attribute);
6936     S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
6937     return;
6938   }
6939 
6940   // Check the attribute argument. Argument is optional.
6941   if (!AL.checkAtMostNumArgs(S, 1))
6942     return;
6943 
6944   StringRef Str;
6945   SourceLocation ArgLoc;
6946 
6947   // 'machine'is the default interrupt mode.
6948   if (AL.getNumArgs() == 0)
6949     Str = "machine";
6950   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6951     return;
6952 
6953   // Semantic checks for a function with the 'interrupt' attribute:
6954   // - Must be a function.
6955   // - Must have no parameters.
6956   // - Must have the 'void' return type.
6957   // - The attribute itself must either have no argument or one of the
6958   //   valid interrupt types, see [RISCVInterruptDocs].
6959 
6960   if (D->getFunctionType() == nullptr) {
6961     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6962       << "'interrupt'" << ExpectedFunction;
6963     return;
6964   }
6965 
6966   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6967     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6968       << /*RISC-V*/ 2 << 0;
6969     return;
6970   }
6971 
6972   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6973     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6974       << /*RISC-V*/ 2 << 1;
6975     return;
6976   }
6977 
6978   RISCVInterruptAttr::InterruptType Kind;
6979   if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6980     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6981                                                                  << ArgLoc;
6982     return;
6983   }
6984 
6985   D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
6986 }
6987 
6988 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6989   // Dispatch the interrupt attribute based on the current target.
6990   switch (S.Context.getTargetInfo().getTriple().getArch()) {
6991   case llvm::Triple::msp430:
6992     handleMSP430InterruptAttr(S, D, AL);
6993     break;
6994   case llvm::Triple::mipsel:
6995   case llvm::Triple::mips:
6996     handleMipsInterruptAttr(S, D, AL);
6997     break;
6998   case llvm::Triple::m68k:
6999     handleM68kInterruptAttr(S, D, AL);
7000     break;
7001   case llvm::Triple::x86:
7002   case llvm::Triple::x86_64:
7003     handleAnyX86InterruptAttr(S, D, AL);
7004     break;
7005   case llvm::Triple::avr:
7006     handleAVRInterruptAttr(S, D, AL);
7007     break;
7008   case llvm::Triple::riscv32:
7009   case llvm::Triple::riscv64:
7010     handleRISCVInterruptAttr(S, D, AL);
7011     break;
7012   default:
7013     handleARMInterruptAttr(S, D, AL);
7014     break;
7015   }
7016 }
7017 
7018 static bool
7019 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
7020                                       const AMDGPUFlatWorkGroupSizeAttr &Attr) {
7021   // Accept template arguments for now as they depend on something else.
7022   // We'll get to check them when they eventually get instantiated.
7023   if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
7024     return false;
7025 
7026   uint32_t Min = 0;
7027   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7028     return true;
7029 
7030   uint32_t Max = 0;
7031   if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7032     return true;
7033 
7034   if (Min == 0 && Max != 0) {
7035     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7036         << &Attr << 0;
7037     return true;
7038   }
7039   if (Min > Max) {
7040     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7041         << &Attr << 1;
7042     return true;
7043   }
7044 
7045   return false;
7046 }
7047 
7048 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
7049                                           const AttributeCommonInfo &CI,
7050                                           Expr *MinExpr, Expr *MaxExpr) {
7051   AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7052 
7053   if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
7054     return;
7055 
7056   D->addAttr(::new (Context)
7057                  AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
7058 }
7059 
7060 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
7061                                               const ParsedAttr &AL) {
7062   Expr *MinExpr = AL.getArgAsExpr(0);
7063   Expr *MaxExpr = AL.getArgAsExpr(1);
7064 
7065   S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
7066 }
7067 
7068 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
7069                                            Expr *MaxExpr,
7070                                            const AMDGPUWavesPerEUAttr &Attr) {
7071   if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
7072       (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
7073     return true;
7074 
7075   // Accept template arguments for now as they depend on something else.
7076   // We'll get to check them when they eventually get instantiated.
7077   if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
7078     return false;
7079 
7080   uint32_t Min = 0;
7081   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7082     return true;
7083 
7084   uint32_t Max = 0;
7085   if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7086     return true;
7087 
7088   if (Min == 0 && Max != 0) {
7089     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7090         << &Attr << 0;
7091     return true;
7092   }
7093   if (Max != 0 && Min > Max) {
7094     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7095         << &Attr << 1;
7096     return true;
7097   }
7098 
7099   return false;
7100 }
7101 
7102 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
7103                                    Expr *MinExpr, Expr *MaxExpr) {
7104   AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7105 
7106   if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
7107     return;
7108 
7109   D->addAttr(::new (Context)
7110                  AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
7111 }
7112 
7113 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7114   if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
7115     return;
7116 
7117   Expr *MinExpr = AL.getArgAsExpr(0);
7118   Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
7119 
7120   S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
7121 }
7122 
7123 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7124   uint32_t NumSGPR = 0;
7125   Expr *NumSGPRExpr = AL.getArgAsExpr(0);
7126   if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
7127     return;
7128 
7129   D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
7130 }
7131 
7132 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7133   uint32_t NumVGPR = 0;
7134   Expr *NumVGPRExpr = AL.getArgAsExpr(0);
7135   if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
7136     return;
7137 
7138   D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
7139 }
7140 
7141 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
7142                                               const ParsedAttr &AL) {
7143   // If we try to apply it to a function pointer, don't warn, but don't
7144   // do anything, either. It doesn't matter anyway, because there's nothing
7145   // special about calling a force_align_arg_pointer function.
7146   const auto *VD = dyn_cast<ValueDecl>(D);
7147   if (VD && VD->getType()->isFunctionPointerType())
7148     return;
7149   // Also don't warn on function pointer typedefs.
7150   const auto *TD = dyn_cast<TypedefNameDecl>(D);
7151   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
7152     TD->getUnderlyingType()->isFunctionType()))
7153     return;
7154   // Attribute can only be applied to function types.
7155   if (!isa<FunctionDecl>(D)) {
7156     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
7157         << AL << ExpectedFunction;
7158     return;
7159   }
7160 
7161   D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
7162 }
7163 
7164 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
7165   uint32_t Version;
7166   Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7167   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
7168     return;
7169 
7170   // TODO: Investigate what happens with the next major version of MSVC.
7171   if (Version != LangOptions::MSVC2015 / 100) {
7172     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7173         << AL << Version << VersionExpr->getSourceRange();
7174     return;
7175   }
7176 
7177   // The attribute expects a "major" version number like 19, but new versions of
7178   // MSVC have moved to updating the "minor", or less significant numbers, so we
7179   // have to multiply by 100 now.
7180   Version *= 100;
7181 
7182   D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
7183 }
7184 
7185 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
7186                                         const AttributeCommonInfo &CI) {
7187   if (D->hasAttr<DLLExportAttr>()) {
7188     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
7189     return nullptr;
7190   }
7191 
7192   if (D->hasAttr<DLLImportAttr>())
7193     return nullptr;
7194 
7195   return ::new (Context) DLLImportAttr(Context, CI);
7196 }
7197 
7198 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
7199                                         const AttributeCommonInfo &CI) {
7200   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
7201     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
7202     D->dropAttr<DLLImportAttr>();
7203   }
7204 
7205   if (D->hasAttr<DLLExportAttr>())
7206     return nullptr;
7207 
7208   return ::new (Context) DLLExportAttr(Context, CI);
7209 }
7210 
7211 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7212   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
7213       (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
7214     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
7215     return;
7216   }
7217 
7218   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7219     if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
7220         !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
7221       // MinGW doesn't allow dllimport on inline functions.
7222       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
7223           << A;
7224       return;
7225     }
7226   }
7227 
7228   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
7229     if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
7230         MD->getParent()->isLambda()) {
7231       S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
7232       return;
7233     }
7234   }
7235 
7236   Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
7237                       ? (Attr *)S.mergeDLLExportAttr(D, A)
7238                       : (Attr *)S.mergeDLLImportAttr(D, A);
7239   if (NewAttr)
7240     D->addAttr(NewAttr);
7241 }
7242 
7243 MSInheritanceAttr *
7244 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
7245                              bool BestCase,
7246                              MSInheritanceModel Model) {
7247   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
7248     if (IA->getInheritanceModel() == Model)
7249       return nullptr;
7250     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
7251         << 1 /*previous declaration*/;
7252     Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
7253     D->dropAttr<MSInheritanceAttr>();
7254   }
7255 
7256   auto *RD = cast<CXXRecordDecl>(D);
7257   if (RD->hasDefinition()) {
7258     if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
7259                                            Model)) {
7260       return nullptr;
7261     }
7262   } else {
7263     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
7264       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7265           << 1 /*partial specialization*/;
7266       return nullptr;
7267     }
7268     if (RD->getDescribedClassTemplate()) {
7269       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7270           << 0 /*primary template*/;
7271       return nullptr;
7272     }
7273   }
7274 
7275   return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
7276 }
7277 
7278 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7279   // The capability attributes take a single string parameter for the name of
7280   // the capability they represent. The lockable attribute does not take any
7281   // parameters. However, semantically, both attributes represent the same
7282   // concept, and so they use the same semantic attribute. Eventually, the
7283   // lockable attribute will be removed.
7284   //
7285   // For backward compatibility, any capability which has no specified string
7286   // literal will be considered a "mutex."
7287   StringRef N("mutex");
7288   SourceLocation LiteralLoc;
7289   if (AL.getKind() == ParsedAttr::AT_Capability &&
7290       !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
7291     return;
7292 
7293   D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
7294 }
7295 
7296 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7297   SmallVector<Expr*, 1> Args;
7298   if (!checkLockFunAttrCommon(S, D, AL, Args))
7299     return;
7300 
7301   D->addAttr(::new (S.Context)
7302                  AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
7303 }
7304 
7305 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
7306                                         const ParsedAttr &AL) {
7307   SmallVector<Expr*, 1> Args;
7308   if (!checkLockFunAttrCommon(S, D, AL, Args))
7309     return;
7310 
7311   D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
7312                                                      Args.size()));
7313 }
7314 
7315 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
7316                                            const ParsedAttr &AL) {
7317   SmallVector<Expr*, 2> Args;
7318   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
7319     return;
7320 
7321   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
7322       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
7323 }
7324 
7325 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
7326                                         const ParsedAttr &AL) {
7327   // Check that all arguments are lockable objects.
7328   SmallVector<Expr *, 1> Args;
7329   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
7330 
7331   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
7332                                                      Args.size()));
7333 }
7334 
7335 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
7336                                          const ParsedAttr &AL) {
7337   if (!AL.checkAtLeastNumArgs(S, 1))
7338     return;
7339 
7340   // check that all arguments are lockable objects
7341   SmallVector<Expr*, 1> Args;
7342   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
7343   if (Args.empty())
7344     return;
7345 
7346   RequiresCapabilityAttr *RCA = ::new (S.Context)
7347       RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
7348 
7349   D->addAttr(RCA);
7350 }
7351 
7352 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7353   if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
7354     if (NSD->isAnonymousNamespace()) {
7355       S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
7356       // Do not want to attach the attribute to the namespace because that will
7357       // cause confusing diagnostic reports for uses of declarations within the
7358       // namespace.
7359       return;
7360     }
7361   } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
7362                  UnresolvedUsingValueDecl>(D)) {
7363     S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
7364         << AL;
7365     return;
7366   }
7367 
7368   // Handle the cases where the attribute has a text message.
7369   StringRef Str, Replacement;
7370   if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
7371       !S.checkStringLiteralArgumentAttr(AL, 0, Str))
7372     return;
7373 
7374   // Support a single optional message only for Declspec and [[]] spellings.
7375   if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
7376     AL.checkAtMostNumArgs(S, 1);
7377   else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
7378            !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
7379     return;
7380 
7381   if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
7382     S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
7383 
7384   D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
7385 }
7386 
7387 static bool isGlobalVar(const Decl *D) {
7388   if (const auto *S = dyn_cast<VarDecl>(D))
7389     return S->hasGlobalStorage();
7390   return false;
7391 }
7392 
7393 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7394   if (!AL.checkAtLeastNumArgs(S, 1))
7395     return;
7396 
7397   std::vector<StringRef> Sanitizers;
7398 
7399   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7400     StringRef SanitizerName;
7401     SourceLocation LiteralLoc;
7402 
7403     if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
7404       return;
7405 
7406     if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
7407             SanitizerMask() &&
7408         SanitizerName != "coverage")
7409       S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
7410     else if (isGlobalVar(D) && SanitizerName != "address")
7411       S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7412           << AL << ExpectedFunctionOrMethod;
7413     Sanitizers.push_back(SanitizerName);
7414   }
7415 
7416   D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
7417                                               Sanitizers.size()));
7418 }
7419 
7420 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
7421                                          const ParsedAttr &AL) {
7422   StringRef AttrName = AL.getAttrName()->getName();
7423   normalizeName(AttrName);
7424   StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
7425                                 .Case("no_address_safety_analysis", "address")
7426                                 .Case("no_sanitize_address", "address")
7427                                 .Case("no_sanitize_thread", "thread")
7428                                 .Case("no_sanitize_memory", "memory");
7429   if (isGlobalVar(D) && SanitizerName != "address")
7430     S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7431         << AL << ExpectedFunction;
7432 
7433   // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
7434   // NoSanitizeAttr object; but we need to calculate the correct spelling list
7435   // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
7436   // has the same spellings as the index for NoSanitizeAttr. We don't have a
7437   // general way to "translate" between the two, so this hack attempts to work
7438   // around the issue with hard-coded indicies. This is critical for calling
7439   // getSpelling() or prettyPrint() on the resulting semantic attribute object
7440   // without failing assertions.
7441   unsigned TranslatedSpellingIndex = 0;
7442   if (AL.isStandardAttributeSyntax())
7443     TranslatedSpellingIndex = 1;
7444 
7445   AttributeCommonInfo Info = AL;
7446   Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
7447   D->addAttr(::new (S.Context)
7448                  NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7449 }
7450 
7451 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7452   if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
7453     D->addAttr(Internal);
7454 }
7455 
7456 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7457   if (S.LangOpts.OpenCLVersion != 200)
7458     S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
7459         << AL << "2.0" << 0;
7460   else
7461     S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
7462                                                                    << "2.0";
7463 }
7464 
7465 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7466   if (D->isInvalidDecl())
7467     return;
7468 
7469   // Check if there is only one access qualifier.
7470   if (D->hasAttr<OpenCLAccessAttr>()) {
7471     if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
7472         AL.getSemanticSpelling()) {
7473       S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
7474           << AL.getAttrName()->getName() << AL.getRange();
7475     } else {
7476       S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
7477           << D->getSourceRange();
7478       D->setInvalidDecl(true);
7479       return;
7480     }
7481   }
7482 
7483   // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
7484   // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
7485   // cannot read from and write to the same pipe object. Using the read_write
7486   // (or __read_write) qualifier with the pipe qualifier is a compilation error.
7487   // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
7488   // __opencl_c_read_write_images feature, image objects specified as arguments
7489   // to a kernel can additionally be declared to be read-write.
7490   // C++ for OpenCL inherits rule from OpenCL C v2.0.
7491   if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
7492     const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
7493     if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
7494       bool ReadWriteImagesUnsupportedForOCLC =
7495           (S.getLangOpts().OpenCLVersion < 200) ||
7496           (S.getLangOpts().OpenCLVersion == 300 &&
7497            !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
7498                                              S.getLangOpts()));
7499       if ((!S.getLangOpts().OpenCLCPlusPlus &&
7500            ReadWriteImagesUnsupportedForOCLC) ||
7501           DeclTy->isPipeType()) {
7502         S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
7503             << AL << PDecl->getType() << DeclTy->isImageType();
7504         D->setInvalidDecl(true);
7505         return;
7506       }
7507     }
7508   }
7509 
7510   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
7511 }
7512 
7513 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7514   // The 'sycl_kernel' attribute applies only to function templates.
7515   const auto *FD = cast<FunctionDecl>(D);
7516   const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
7517   assert(FT && "Function template is expected");
7518 
7519   // Function template must have at least two template parameters.
7520   const TemplateParameterList *TL = FT->getTemplateParameters();
7521   if (TL->size() < 2) {
7522     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
7523     return;
7524   }
7525 
7526   // Template parameters must be typenames.
7527   for (unsigned I = 0; I < 2; ++I) {
7528     const NamedDecl *TParam = TL->getParam(I);
7529     if (isa<NonTypeTemplateParmDecl>(TParam)) {
7530       S.Diag(FT->getLocation(),
7531              diag::warn_sycl_kernel_invalid_template_param_type);
7532       return;
7533     }
7534   }
7535 
7536   // Function must have at least one argument.
7537   if (getFunctionOrMethodNumParams(D) != 1) {
7538     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
7539     return;
7540   }
7541 
7542   // Function must return void.
7543   QualType RetTy = getFunctionOrMethodResultType(D);
7544   if (!RetTy->isVoidType()) {
7545     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
7546     return;
7547   }
7548 
7549   handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
7550 }
7551 
7552 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7553   if (!cast<VarDecl>(D)->hasGlobalStorage()) {
7554     S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
7555         << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
7556     return;
7557   }
7558 
7559   if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
7560     handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
7561   else
7562     handleSimpleAttribute<NoDestroyAttr>(S, D, A);
7563 }
7564 
7565 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7566   assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
7567          "uninitialized is only valid on automatic duration variables");
7568   D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
7569 }
7570 
7571 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
7572                                         bool DiagnoseFailure) {
7573   QualType Ty = VD->getType();
7574   if (!Ty->isObjCRetainableType()) {
7575     if (DiagnoseFailure) {
7576       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7577           << 0;
7578     }
7579     return false;
7580   }
7581 
7582   Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
7583 
7584   // Sema::inferObjCARCLifetime must run after processing decl attributes
7585   // (because __block lowers to an attribute), so if the lifetime hasn't been
7586   // explicitly specified, infer it locally now.
7587   if (LifetimeQual == Qualifiers::OCL_None)
7588     LifetimeQual = Ty->getObjCARCImplicitLifetime();
7589 
7590   // The attributes only really makes sense for __strong variables; ignore any
7591   // attempts to annotate a parameter with any other lifetime qualifier.
7592   if (LifetimeQual != Qualifiers::OCL_Strong) {
7593     if (DiagnoseFailure) {
7594       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7595           << 1;
7596     }
7597     return false;
7598   }
7599 
7600   // Tampering with the type of a VarDecl here is a bit of a hack, but we need
7601   // to ensure that the variable is 'const' so that we can error on
7602   // modification, which can otherwise over-release.
7603   VD->setType(Ty.withConst());
7604   VD->setARCPseudoStrong(true);
7605   return true;
7606 }
7607 
7608 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
7609                                              const ParsedAttr &AL) {
7610   if (auto *VD = dyn_cast<VarDecl>(D)) {
7611     assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
7612     if (!VD->hasLocalStorage()) {
7613       S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7614           << 0;
7615       return;
7616     }
7617 
7618     if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
7619       return;
7620 
7621     handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7622     return;
7623   }
7624 
7625   // If D is a function-like declaration (method, block, or function), then we
7626   // make every parameter psuedo-strong.
7627   unsigned NumParams =
7628       hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
7629   for (unsigned I = 0; I != NumParams; ++I) {
7630     auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
7631     QualType Ty = PVD->getType();
7632 
7633     // If a user wrote a parameter with __strong explicitly, then assume they
7634     // want "real" strong semantics for that parameter. This works because if
7635     // the parameter was written with __strong, then the strong qualifier will
7636     // be non-local.
7637     if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
7638         Qualifiers::OCL_Strong)
7639       continue;
7640 
7641     tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
7642   }
7643   handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7644 }
7645 
7646 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7647   // Check that the return type is a `typedef int kern_return_t` or a typedef
7648   // around it, because otherwise MIG convention checks make no sense.
7649   // BlockDecl doesn't store a return type, so it's annoying to check,
7650   // so let's skip it for now.
7651   if (!isa<BlockDecl>(D)) {
7652     QualType T = getFunctionOrMethodResultType(D);
7653     bool IsKernReturnT = false;
7654     while (const auto *TT = T->getAs<TypedefType>()) {
7655       IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
7656       T = TT->desugar();
7657     }
7658     if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
7659       S.Diag(D->getBeginLoc(),
7660              diag::warn_mig_server_routine_does_not_return_kern_return_t);
7661       return;
7662     }
7663   }
7664 
7665   handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
7666 }
7667 
7668 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7669   // Warn if the return type is not a pointer or reference type.
7670   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7671     QualType RetTy = FD->getReturnType();
7672     if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
7673       S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
7674           << AL.getRange() << RetTy;
7675       return;
7676     }
7677   }
7678 
7679   handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
7680 }
7681 
7682 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7683   if (AL.isUsedAsTypeAttr())
7684     return;
7685   // Warn if the parameter is definitely not an output parameter.
7686   if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
7687     if (PVD->getType()->isIntegerType()) {
7688       S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
7689           << AL.getRange();
7690       return;
7691     }
7692   }
7693   StringRef Argument;
7694   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7695     return;
7696   D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
7697 }
7698 
7699 template<typename Attr>
7700 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7701   StringRef Argument;
7702   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7703     return;
7704   D->addAttr(Attr::Create(S.Context, Argument, AL));
7705 }
7706 
7707 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7708   // The guard attribute takes a single identifier argument.
7709 
7710   if (!AL.isArgIdent(0)) {
7711     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7712         << AL << AANT_ArgumentIdentifier;
7713     return;
7714   }
7715 
7716   CFGuardAttr::GuardArg Arg;
7717   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
7718   if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
7719     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
7720     return;
7721   }
7722 
7723   D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
7724 }
7725 
7726 
7727 template <typename AttrTy>
7728 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
7729   auto Attrs = D->specific_attrs<AttrTy>();
7730   auto I = llvm::find_if(Attrs,
7731                          [Name](const AttrTy *A) {
7732                            return A->getTCBName() == Name;
7733                          });
7734   return I == Attrs.end() ? nullptr : *I;
7735 }
7736 
7737 template <typename AttrTy, typename ConflictingAttrTy>
7738 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7739   StringRef Argument;
7740   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7741     return;
7742 
7743   // A function cannot be have both regular and leaf membership in the same TCB.
7744   if (const ConflictingAttrTy *ConflictingAttr =
7745       findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
7746     // We could attach a note to the other attribute but in this case
7747     // there's no need given how the two are very close to each other.
7748     S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
7749       << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
7750       << Argument;
7751 
7752     // Error recovery: drop the non-leaf attribute so that to suppress
7753     // all future warnings caused by erroneous attributes. The leaf attribute
7754     // needs to be kept because it can only suppresses warnings, not cause them.
7755     D->dropAttr<EnforceTCBAttr>();
7756     return;
7757   }
7758 
7759   D->addAttr(AttrTy::Create(S.Context, Argument, AL));
7760 }
7761 
7762 template <typename AttrTy, typename ConflictingAttrTy>
7763 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
7764   // Check if the new redeclaration has different leaf-ness in the same TCB.
7765   StringRef TCBName = AL.getTCBName();
7766   if (const ConflictingAttrTy *ConflictingAttr =
7767       findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
7768     S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
7769       << ConflictingAttr->getAttrName()->getName()
7770       << AL.getAttrName()->getName() << TCBName;
7771 
7772     // Add a note so that the user could easily find the conflicting attribute.
7773     S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
7774 
7775     // More error recovery.
7776     D->dropAttr<EnforceTCBAttr>();
7777     return nullptr;
7778   }
7779 
7780   ASTContext &Context = S.getASTContext();
7781   return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
7782 }
7783 
7784 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
7785   return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
7786       *this, D, AL);
7787 }
7788 
7789 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
7790     Decl *D, const EnforceTCBLeafAttr &AL) {
7791   return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
7792       *this, D, AL);
7793 }
7794 
7795 //===----------------------------------------------------------------------===//
7796 // Top Level Sema Entry Points
7797 //===----------------------------------------------------------------------===//
7798 
7799 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
7800 /// the attribute applies to decls.  If the attribute is a type attribute, just
7801 /// silently ignore it if a GNU attribute.
7802 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
7803                                  const ParsedAttr &AL,
7804                                  bool IncludeCXX11Attributes) {
7805   if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
7806     return;
7807 
7808   // Ignore C++11 attributes on declarator chunks: they appertain to the type
7809   // instead.
7810   if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
7811     return;
7812 
7813   // Unknown attributes are automatically warned on. Target-specific attributes
7814   // which do not apply to the current target architecture are treated as
7815   // though they were unknown attributes.
7816   if (AL.getKind() == ParsedAttr::UnknownAttribute ||
7817       !AL.existsInTarget(S.Context.getTargetInfo())) {
7818     S.Diag(AL.getLoc(),
7819            AL.isDeclspecAttribute()
7820                ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
7821                : (unsigned)diag::warn_unknown_attribute_ignored)
7822         << AL << AL.getRange();
7823     return;
7824   }
7825 
7826   if (S.checkCommonAttributeFeatures(D, AL))
7827     return;
7828 
7829   switch (AL.getKind()) {
7830   default:
7831     if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
7832       break;
7833     if (!AL.isStmtAttr()) {
7834       // Type attributes are handled elsewhere; silently move on.
7835       assert(AL.isTypeAttr() && "Non-type attribute not handled");
7836       break;
7837     }
7838     // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
7839     // statement attribute is not written on a declaration, but this code is
7840     // needed for attributes in Attr.td that do not list any subjects.
7841     S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
7842         << AL << D->getLocation();
7843     break;
7844   case ParsedAttr::AT_Interrupt:
7845     handleInterruptAttr(S, D, AL);
7846     break;
7847   case ParsedAttr::AT_X86ForceAlignArgPointer:
7848     handleX86ForceAlignArgPointerAttr(S, D, AL);
7849     break;
7850   case ParsedAttr::AT_DLLExport:
7851   case ParsedAttr::AT_DLLImport:
7852     handleDLLAttr(S, D, AL);
7853     break;
7854   case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
7855     handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
7856     break;
7857   case ParsedAttr::AT_AMDGPUWavesPerEU:
7858     handleAMDGPUWavesPerEUAttr(S, D, AL);
7859     break;
7860   case ParsedAttr::AT_AMDGPUNumSGPR:
7861     handleAMDGPUNumSGPRAttr(S, D, AL);
7862     break;
7863   case ParsedAttr::AT_AMDGPUNumVGPR:
7864     handleAMDGPUNumVGPRAttr(S, D, AL);
7865     break;
7866   case ParsedAttr::AT_AVRSignal:
7867     handleAVRSignalAttr(S, D, AL);
7868     break;
7869   case ParsedAttr::AT_BPFPreserveAccessIndex:
7870     handleBPFPreserveAccessIndexAttr(S, D, AL);
7871     break;
7872   case ParsedAttr::AT_WebAssemblyExportName:
7873     handleWebAssemblyExportNameAttr(S, D, AL);
7874     break;
7875   case ParsedAttr::AT_WebAssemblyImportModule:
7876     handleWebAssemblyImportModuleAttr(S, D, AL);
7877     break;
7878   case ParsedAttr::AT_WebAssemblyImportName:
7879     handleWebAssemblyImportNameAttr(S, D, AL);
7880     break;
7881   case ParsedAttr::AT_IBOutlet:
7882     handleIBOutlet(S, D, AL);
7883     break;
7884   case ParsedAttr::AT_IBOutletCollection:
7885     handleIBOutletCollection(S, D, AL);
7886     break;
7887   case ParsedAttr::AT_IFunc:
7888     handleIFuncAttr(S, D, AL);
7889     break;
7890   case ParsedAttr::AT_Alias:
7891     handleAliasAttr(S, D, AL);
7892     break;
7893   case ParsedAttr::AT_Aligned:
7894     handleAlignedAttr(S, D, AL);
7895     break;
7896   case ParsedAttr::AT_AlignValue:
7897     handleAlignValueAttr(S, D, AL);
7898     break;
7899   case ParsedAttr::AT_AllocSize:
7900     handleAllocSizeAttr(S, D, AL);
7901     break;
7902   case ParsedAttr::AT_AlwaysInline:
7903     handleAlwaysInlineAttr(S, D, AL);
7904     break;
7905   case ParsedAttr::AT_AnalyzerNoReturn:
7906     handleAnalyzerNoReturnAttr(S, D, AL);
7907     break;
7908   case ParsedAttr::AT_TLSModel:
7909     handleTLSModelAttr(S, D, AL);
7910     break;
7911   case ParsedAttr::AT_Annotate:
7912     handleAnnotateAttr(S, D, AL);
7913     break;
7914   case ParsedAttr::AT_Availability:
7915     handleAvailabilityAttr(S, D, AL);
7916     break;
7917   case ParsedAttr::AT_CarriesDependency:
7918     handleDependencyAttr(S, scope, D, AL);
7919     break;
7920   case ParsedAttr::AT_CPUDispatch:
7921   case ParsedAttr::AT_CPUSpecific:
7922     handleCPUSpecificAttr(S, D, AL);
7923     break;
7924   case ParsedAttr::AT_Common:
7925     handleCommonAttr(S, D, AL);
7926     break;
7927   case ParsedAttr::AT_CUDAConstant:
7928     handleConstantAttr(S, D, AL);
7929     break;
7930   case ParsedAttr::AT_PassObjectSize:
7931     handlePassObjectSizeAttr(S, D, AL);
7932     break;
7933   case ParsedAttr::AT_Constructor:
7934       handleConstructorAttr(S, D, AL);
7935     break;
7936   case ParsedAttr::AT_Deprecated:
7937     handleDeprecatedAttr(S, D, AL);
7938     break;
7939   case ParsedAttr::AT_Destructor:
7940       handleDestructorAttr(S, D, AL);
7941     break;
7942   case ParsedAttr::AT_EnableIf:
7943     handleEnableIfAttr(S, D, AL);
7944     break;
7945   case ParsedAttr::AT_DiagnoseIf:
7946     handleDiagnoseIfAttr(S, D, AL);
7947     break;
7948   case ParsedAttr::AT_NoBuiltin:
7949     handleNoBuiltinAttr(S, D, AL);
7950     break;
7951   case ParsedAttr::AT_ExtVectorType:
7952     handleExtVectorTypeAttr(S, D, AL);
7953     break;
7954   case ParsedAttr::AT_ExternalSourceSymbol:
7955     handleExternalSourceSymbolAttr(S, D, AL);
7956     break;
7957   case ParsedAttr::AT_MinSize:
7958     handleMinSizeAttr(S, D, AL);
7959     break;
7960   case ParsedAttr::AT_OptimizeNone:
7961     handleOptimizeNoneAttr(S, D, AL);
7962     break;
7963   case ParsedAttr::AT_EnumExtensibility:
7964     handleEnumExtensibilityAttr(S, D, AL);
7965     break;
7966   case ParsedAttr::AT_SYCLKernel:
7967     handleSYCLKernelAttr(S, D, AL);
7968     break;
7969   case ParsedAttr::AT_Format:
7970     handleFormatAttr(S, D, AL);
7971     break;
7972   case ParsedAttr::AT_FormatArg:
7973     handleFormatArgAttr(S, D, AL);
7974     break;
7975   case ParsedAttr::AT_Callback:
7976     handleCallbackAttr(S, D, AL);
7977     break;
7978   case ParsedAttr::AT_CalledOnce:
7979     handleCalledOnceAttr(S, D, AL);
7980     break;
7981   case ParsedAttr::AT_CUDAGlobal:
7982     handleGlobalAttr(S, D, AL);
7983     break;
7984   case ParsedAttr::AT_CUDADevice:
7985     handleDeviceAttr(S, D, AL);
7986     break;
7987   case ParsedAttr::AT_HIPManaged:
7988     handleManagedAttr(S, D, AL);
7989     break;
7990   case ParsedAttr::AT_GNUInline:
7991     handleGNUInlineAttr(S, D, AL);
7992     break;
7993   case ParsedAttr::AT_CUDALaunchBounds:
7994     handleLaunchBoundsAttr(S, D, AL);
7995     break;
7996   case ParsedAttr::AT_Restrict:
7997     handleRestrictAttr(S, D, AL);
7998     break;
7999   case ParsedAttr::AT_Mode:
8000     handleModeAttr(S, D, AL);
8001     break;
8002   case ParsedAttr::AT_NonNull:
8003     if (auto *PVD = dyn_cast<ParmVarDecl>(D))
8004       handleNonNullAttrParameter(S, PVD, AL);
8005     else
8006       handleNonNullAttr(S, D, AL);
8007     break;
8008   case ParsedAttr::AT_ReturnsNonNull:
8009     handleReturnsNonNullAttr(S, D, AL);
8010     break;
8011   case ParsedAttr::AT_NoEscape:
8012     handleNoEscapeAttr(S, D, AL);
8013     break;
8014   case ParsedAttr::AT_AssumeAligned:
8015     handleAssumeAlignedAttr(S, D, AL);
8016     break;
8017   case ParsedAttr::AT_AllocAlign:
8018     handleAllocAlignAttr(S, D, AL);
8019     break;
8020   case ParsedAttr::AT_Ownership:
8021     handleOwnershipAttr(S, D, AL);
8022     break;
8023   case ParsedAttr::AT_Naked:
8024     handleNakedAttr(S, D, AL);
8025     break;
8026   case ParsedAttr::AT_NoReturn:
8027     handleNoReturnAttr(S, D, AL);
8028     break;
8029   case ParsedAttr::AT_AnyX86NoCfCheck:
8030     handleNoCfCheckAttr(S, D, AL);
8031     break;
8032   case ParsedAttr::AT_NoThrow:
8033     if (!AL.isUsedAsTypeAttr())
8034       handleSimpleAttribute<NoThrowAttr>(S, D, AL);
8035     break;
8036   case ParsedAttr::AT_CUDAShared:
8037     handleSharedAttr(S, D, AL);
8038     break;
8039   case ParsedAttr::AT_VecReturn:
8040     handleVecReturnAttr(S, D, AL);
8041     break;
8042   case ParsedAttr::AT_ObjCOwnership:
8043     handleObjCOwnershipAttr(S, D, AL);
8044     break;
8045   case ParsedAttr::AT_ObjCPreciseLifetime:
8046     handleObjCPreciseLifetimeAttr(S, D, AL);
8047     break;
8048   case ParsedAttr::AT_ObjCReturnsInnerPointer:
8049     handleObjCReturnsInnerPointerAttr(S, D, AL);
8050     break;
8051   case ParsedAttr::AT_ObjCRequiresSuper:
8052     handleObjCRequiresSuperAttr(S, D, AL);
8053     break;
8054   case ParsedAttr::AT_ObjCBridge:
8055     handleObjCBridgeAttr(S, D, AL);
8056     break;
8057   case ParsedAttr::AT_ObjCBridgeMutable:
8058     handleObjCBridgeMutableAttr(S, D, AL);
8059     break;
8060   case ParsedAttr::AT_ObjCBridgeRelated:
8061     handleObjCBridgeRelatedAttr(S, D, AL);
8062     break;
8063   case ParsedAttr::AT_ObjCDesignatedInitializer:
8064     handleObjCDesignatedInitializer(S, D, AL);
8065     break;
8066   case ParsedAttr::AT_ObjCRuntimeName:
8067     handleObjCRuntimeName(S, D, AL);
8068     break;
8069   case ParsedAttr::AT_ObjCBoxable:
8070     handleObjCBoxable(S, D, AL);
8071     break;
8072   case ParsedAttr::AT_NSErrorDomain:
8073     handleNSErrorDomain(S, D, AL);
8074     break;
8075   case ParsedAttr::AT_CFConsumed:
8076   case ParsedAttr::AT_NSConsumed:
8077   case ParsedAttr::AT_OSConsumed:
8078     S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
8079                        /*IsTemplateInstantiation=*/false);
8080     break;
8081   case ParsedAttr::AT_OSReturnsRetainedOnZero:
8082     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
8083         S, D, AL, isValidOSObjectOutParameter(D),
8084         diag::warn_ns_attribute_wrong_parameter_type,
8085         /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
8086     break;
8087   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
8088     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
8089         S, D, AL, isValidOSObjectOutParameter(D),
8090         diag::warn_ns_attribute_wrong_parameter_type,
8091         /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
8092     break;
8093   case ParsedAttr::AT_NSReturnsAutoreleased:
8094   case ParsedAttr::AT_NSReturnsNotRetained:
8095   case ParsedAttr::AT_NSReturnsRetained:
8096   case ParsedAttr::AT_CFReturnsNotRetained:
8097   case ParsedAttr::AT_CFReturnsRetained:
8098   case ParsedAttr::AT_OSReturnsNotRetained:
8099   case ParsedAttr::AT_OSReturnsRetained:
8100     handleXReturnsXRetainedAttr(S, D, AL);
8101     break;
8102   case ParsedAttr::AT_WorkGroupSizeHint:
8103     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
8104     break;
8105   case ParsedAttr::AT_ReqdWorkGroupSize:
8106     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
8107     break;
8108   case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
8109     handleSubGroupSize(S, D, AL);
8110     break;
8111   case ParsedAttr::AT_VecTypeHint:
8112     handleVecTypeHint(S, D, AL);
8113     break;
8114   case ParsedAttr::AT_InitPriority:
8115       handleInitPriorityAttr(S, D, AL);
8116     break;
8117   case ParsedAttr::AT_Packed:
8118     handlePackedAttr(S, D, AL);
8119     break;
8120   case ParsedAttr::AT_PreferredName:
8121     handlePreferredName(S, D, AL);
8122     break;
8123   case ParsedAttr::AT_Section:
8124     handleSectionAttr(S, D, AL);
8125     break;
8126   case ParsedAttr::AT_CodeSeg:
8127     handleCodeSegAttr(S, D, AL);
8128     break;
8129   case ParsedAttr::AT_Target:
8130     handleTargetAttr(S, D, AL);
8131     break;
8132   case ParsedAttr::AT_MinVectorWidth:
8133     handleMinVectorWidthAttr(S, D, AL);
8134     break;
8135   case ParsedAttr::AT_Unavailable:
8136     handleAttrWithMessage<UnavailableAttr>(S, D, AL);
8137     break;
8138   case ParsedAttr::AT_Assumption:
8139     handleAssumumptionAttr(S, D, AL);
8140     break;
8141   case ParsedAttr::AT_ObjCDirect:
8142     handleObjCDirectAttr(S, D, AL);
8143     break;
8144   case ParsedAttr::AT_ObjCDirectMembers:
8145     handleObjCDirectMembersAttr(S, D, AL);
8146     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
8147     break;
8148   case ParsedAttr::AT_ObjCExplicitProtocolImpl:
8149     handleObjCSuppresProtocolAttr(S, D, AL);
8150     break;
8151   case ParsedAttr::AT_Unused:
8152     handleUnusedAttr(S, D, AL);
8153     break;
8154   case ParsedAttr::AT_Visibility:
8155     handleVisibilityAttr(S, D, AL, false);
8156     break;
8157   case ParsedAttr::AT_TypeVisibility:
8158     handleVisibilityAttr(S, D, AL, true);
8159     break;
8160   case ParsedAttr::AT_WarnUnusedResult:
8161     handleWarnUnusedResult(S, D, AL);
8162     break;
8163   case ParsedAttr::AT_WeakRef:
8164     handleWeakRefAttr(S, D, AL);
8165     break;
8166   case ParsedAttr::AT_WeakImport:
8167     handleWeakImportAttr(S, D, AL);
8168     break;
8169   case ParsedAttr::AT_TransparentUnion:
8170     handleTransparentUnionAttr(S, D, AL);
8171     break;
8172   case ParsedAttr::AT_ObjCMethodFamily:
8173     handleObjCMethodFamilyAttr(S, D, AL);
8174     break;
8175   case ParsedAttr::AT_ObjCNSObject:
8176     handleObjCNSObject(S, D, AL);
8177     break;
8178   case ParsedAttr::AT_ObjCIndependentClass:
8179     handleObjCIndependentClass(S, D, AL);
8180     break;
8181   case ParsedAttr::AT_Blocks:
8182     handleBlocksAttr(S, D, AL);
8183     break;
8184   case ParsedAttr::AT_Sentinel:
8185     handleSentinelAttr(S, D, AL);
8186     break;
8187   case ParsedAttr::AT_Cleanup:
8188     handleCleanupAttr(S, D, AL);
8189     break;
8190   case ParsedAttr::AT_NoDebug:
8191     handleNoDebugAttr(S, D, AL);
8192     break;
8193   case ParsedAttr::AT_CmseNSEntry:
8194     handleCmseNSEntryAttr(S, D, AL);
8195     break;
8196   case ParsedAttr::AT_StdCall:
8197   case ParsedAttr::AT_CDecl:
8198   case ParsedAttr::AT_FastCall:
8199   case ParsedAttr::AT_ThisCall:
8200   case ParsedAttr::AT_Pascal:
8201   case ParsedAttr::AT_RegCall:
8202   case ParsedAttr::AT_SwiftCall:
8203   case ParsedAttr::AT_SwiftAsyncCall:
8204   case ParsedAttr::AT_VectorCall:
8205   case ParsedAttr::AT_MSABI:
8206   case ParsedAttr::AT_SysVABI:
8207   case ParsedAttr::AT_Pcs:
8208   case ParsedAttr::AT_IntelOclBicc:
8209   case ParsedAttr::AT_PreserveMost:
8210   case ParsedAttr::AT_PreserveAll:
8211   case ParsedAttr::AT_AArch64VectorPcs:
8212     handleCallConvAttr(S, D, AL);
8213     break;
8214   case ParsedAttr::AT_Suppress:
8215     handleSuppressAttr(S, D, AL);
8216     break;
8217   case ParsedAttr::AT_Owner:
8218   case ParsedAttr::AT_Pointer:
8219     handleLifetimeCategoryAttr(S, D, AL);
8220     break;
8221   case ParsedAttr::AT_OpenCLAccess:
8222     handleOpenCLAccessAttr(S, D, AL);
8223     break;
8224   case ParsedAttr::AT_OpenCLNoSVM:
8225     handleOpenCLNoSVMAttr(S, D, AL);
8226     break;
8227   case ParsedAttr::AT_SwiftContext:
8228     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
8229     break;
8230   case ParsedAttr::AT_SwiftAsyncContext:
8231     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext);
8232     break;
8233   case ParsedAttr::AT_SwiftErrorResult:
8234     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
8235     break;
8236   case ParsedAttr::AT_SwiftIndirectResult:
8237     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
8238     break;
8239   case ParsedAttr::AT_InternalLinkage:
8240     handleInternalLinkageAttr(S, D, AL);
8241     break;
8242 
8243   // Microsoft attributes:
8244   case ParsedAttr::AT_LayoutVersion:
8245     handleLayoutVersion(S, D, AL);
8246     break;
8247   case ParsedAttr::AT_Uuid:
8248     handleUuidAttr(S, D, AL);
8249     break;
8250   case ParsedAttr::AT_MSInheritance:
8251     handleMSInheritanceAttr(S, D, AL);
8252     break;
8253   case ParsedAttr::AT_Thread:
8254     handleDeclspecThreadAttr(S, D, AL);
8255     break;
8256 
8257   case ParsedAttr::AT_AbiTag:
8258     handleAbiTagAttr(S, D, AL);
8259     break;
8260   case ParsedAttr::AT_CFGuard:
8261     handleCFGuardAttr(S, D, AL);
8262     break;
8263 
8264   // Thread safety attributes:
8265   case ParsedAttr::AT_AssertExclusiveLock:
8266     handleAssertExclusiveLockAttr(S, D, AL);
8267     break;
8268   case ParsedAttr::AT_AssertSharedLock:
8269     handleAssertSharedLockAttr(S, D, AL);
8270     break;
8271   case ParsedAttr::AT_PtGuardedVar:
8272     handlePtGuardedVarAttr(S, D, AL);
8273     break;
8274   case ParsedAttr::AT_NoSanitize:
8275     handleNoSanitizeAttr(S, D, AL);
8276     break;
8277   case ParsedAttr::AT_NoSanitizeSpecific:
8278     handleNoSanitizeSpecificAttr(S, D, AL);
8279     break;
8280   case ParsedAttr::AT_GuardedBy:
8281     handleGuardedByAttr(S, D, AL);
8282     break;
8283   case ParsedAttr::AT_PtGuardedBy:
8284     handlePtGuardedByAttr(S, D, AL);
8285     break;
8286   case ParsedAttr::AT_ExclusiveTrylockFunction:
8287     handleExclusiveTrylockFunctionAttr(S, D, AL);
8288     break;
8289   case ParsedAttr::AT_LockReturned:
8290     handleLockReturnedAttr(S, D, AL);
8291     break;
8292   case ParsedAttr::AT_LocksExcluded:
8293     handleLocksExcludedAttr(S, D, AL);
8294     break;
8295   case ParsedAttr::AT_SharedTrylockFunction:
8296     handleSharedTrylockFunctionAttr(S, D, AL);
8297     break;
8298   case ParsedAttr::AT_AcquiredBefore:
8299     handleAcquiredBeforeAttr(S, D, AL);
8300     break;
8301   case ParsedAttr::AT_AcquiredAfter:
8302     handleAcquiredAfterAttr(S, D, AL);
8303     break;
8304 
8305   // Capability analysis attributes.
8306   case ParsedAttr::AT_Capability:
8307   case ParsedAttr::AT_Lockable:
8308     handleCapabilityAttr(S, D, AL);
8309     break;
8310   case ParsedAttr::AT_RequiresCapability:
8311     handleRequiresCapabilityAttr(S, D, AL);
8312     break;
8313 
8314   case ParsedAttr::AT_AssertCapability:
8315     handleAssertCapabilityAttr(S, D, AL);
8316     break;
8317   case ParsedAttr::AT_AcquireCapability:
8318     handleAcquireCapabilityAttr(S, D, AL);
8319     break;
8320   case ParsedAttr::AT_ReleaseCapability:
8321     handleReleaseCapabilityAttr(S, D, AL);
8322     break;
8323   case ParsedAttr::AT_TryAcquireCapability:
8324     handleTryAcquireCapabilityAttr(S, D, AL);
8325     break;
8326 
8327   // Consumed analysis attributes.
8328   case ParsedAttr::AT_Consumable:
8329     handleConsumableAttr(S, D, AL);
8330     break;
8331   case ParsedAttr::AT_CallableWhen:
8332     handleCallableWhenAttr(S, D, AL);
8333     break;
8334   case ParsedAttr::AT_ParamTypestate:
8335     handleParamTypestateAttr(S, D, AL);
8336     break;
8337   case ParsedAttr::AT_ReturnTypestate:
8338     handleReturnTypestateAttr(S, D, AL);
8339     break;
8340   case ParsedAttr::AT_SetTypestate:
8341     handleSetTypestateAttr(S, D, AL);
8342     break;
8343   case ParsedAttr::AT_TestTypestate:
8344     handleTestTypestateAttr(S, D, AL);
8345     break;
8346 
8347   // Type safety attributes.
8348   case ParsedAttr::AT_ArgumentWithTypeTag:
8349     handleArgumentWithTypeTagAttr(S, D, AL);
8350     break;
8351   case ParsedAttr::AT_TypeTagForDatatype:
8352     handleTypeTagForDatatypeAttr(S, D, AL);
8353     break;
8354 
8355   // Swift attributes.
8356   case ParsedAttr::AT_SwiftAsyncName:
8357     handleSwiftAsyncName(S, D, AL);
8358     break;
8359   case ParsedAttr::AT_SwiftAttr:
8360     handleSwiftAttrAttr(S, D, AL);
8361     break;
8362   case ParsedAttr::AT_SwiftBridge:
8363     handleSwiftBridge(S, D, AL);
8364     break;
8365   case ParsedAttr::AT_SwiftError:
8366     handleSwiftError(S, D, AL);
8367     break;
8368   case ParsedAttr::AT_SwiftName:
8369     handleSwiftName(S, D, AL);
8370     break;
8371   case ParsedAttr::AT_SwiftNewType:
8372     handleSwiftNewType(S, D, AL);
8373     break;
8374   case ParsedAttr::AT_SwiftAsync:
8375     handleSwiftAsyncAttr(S, D, AL);
8376     break;
8377   case ParsedAttr::AT_SwiftAsyncError:
8378     handleSwiftAsyncError(S, D, AL);
8379     break;
8380 
8381   // XRay attributes.
8382   case ParsedAttr::AT_XRayLogArgs:
8383     handleXRayLogArgsAttr(S, D, AL);
8384     break;
8385 
8386   case ParsedAttr::AT_PatchableFunctionEntry:
8387     handlePatchableFunctionEntryAttr(S, D, AL);
8388     break;
8389 
8390   case ParsedAttr::AT_AlwaysDestroy:
8391   case ParsedAttr::AT_NoDestroy:
8392     handleDestroyAttr(S, D, AL);
8393     break;
8394 
8395   case ParsedAttr::AT_Uninitialized:
8396     handleUninitializedAttr(S, D, AL);
8397     break;
8398 
8399   case ParsedAttr::AT_ObjCExternallyRetained:
8400     handleObjCExternallyRetainedAttr(S, D, AL);
8401     break;
8402 
8403   case ParsedAttr::AT_MIGServerRoutine:
8404     handleMIGServerRoutineAttr(S, D, AL);
8405     break;
8406 
8407   case ParsedAttr::AT_MSAllocator:
8408     handleMSAllocatorAttr(S, D, AL);
8409     break;
8410 
8411   case ParsedAttr::AT_ArmBuiltinAlias:
8412     handleArmBuiltinAliasAttr(S, D, AL);
8413     break;
8414 
8415   case ParsedAttr::AT_AcquireHandle:
8416     handleAcquireHandleAttr(S, D, AL);
8417     break;
8418 
8419   case ParsedAttr::AT_ReleaseHandle:
8420     handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
8421     break;
8422 
8423   case ParsedAttr::AT_UseHandle:
8424     handleHandleAttr<UseHandleAttr>(S, D, AL);
8425     break;
8426 
8427   case ParsedAttr::AT_EnforceTCB:
8428     handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
8429     break;
8430 
8431   case ParsedAttr::AT_EnforceTCBLeaf:
8432     handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
8433     break;
8434 
8435   case ParsedAttr::AT_BuiltinAlias:
8436     handleBuiltinAliasAttr(S, D, AL);
8437     break;
8438 
8439   case ParsedAttr::AT_UsingIfExists:
8440     handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
8441     break;
8442   }
8443 }
8444 
8445 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
8446 /// attribute list to the specified decl, ignoring any type attributes.
8447 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
8448                                     const ParsedAttributesView &AttrList,
8449                                     bool IncludeCXX11Attributes) {
8450   if (AttrList.empty())
8451     return;
8452 
8453   for (const ParsedAttr &AL : AttrList)
8454     ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
8455 
8456   // FIXME: We should be able to handle these cases in TableGen.
8457   // GCC accepts
8458   // static int a9 __attribute__((weakref));
8459   // but that looks really pointless. We reject it.
8460   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
8461     Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
8462         << cast<NamedDecl>(D);
8463     D->dropAttr<WeakRefAttr>();
8464     return;
8465   }
8466 
8467   // FIXME: We should be able to handle this in TableGen as well. It would be
8468   // good to have a way to specify "these attributes must appear as a group",
8469   // for these. Additionally, it would be good to have a way to specify "these
8470   // attribute must never appear as a group" for attributes like cold and hot.
8471   if (!D->hasAttr<OpenCLKernelAttr>()) {
8472     // These attributes cannot be applied to a non-kernel function.
8473     if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
8474       // FIXME: This emits a different error message than
8475       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
8476       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8477       D->setInvalidDecl();
8478     } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
8479       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8480       D->setInvalidDecl();
8481     } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
8482       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8483       D->setInvalidDecl();
8484     } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
8485       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8486       D->setInvalidDecl();
8487     } else if (!D->hasAttr<CUDAGlobalAttr>()) {
8488       if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
8489         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8490             << A << ExpectedKernelFunction;
8491         D->setInvalidDecl();
8492       } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
8493         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8494             << A << ExpectedKernelFunction;
8495         D->setInvalidDecl();
8496       } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
8497         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8498             << A << ExpectedKernelFunction;
8499         D->setInvalidDecl();
8500       } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
8501         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8502             << A << ExpectedKernelFunction;
8503         D->setInvalidDecl();
8504       }
8505     }
8506   }
8507 
8508   // Do this check after processing D's attributes because the attribute
8509   // objc_method_family can change whether the given method is in the init
8510   // family, and it can be applied after objc_designated_initializer. This is a
8511   // bit of a hack, but we need it to be compatible with versions of clang that
8512   // processed the attribute list in the wrong order.
8513   if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
8514       cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
8515     Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
8516     D->dropAttr<ObjCDesignatedInitializerAttr>();
8517   }
8518 }
8519 
8520 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
8521 // attribute.
8522 void Sema::ProcessDeclAttributeDelayed(Decl *D,
8523                                        const ParsedAttributesView &AttrList) {
8524   for (const ParsedAttr &AL : AttrList)
8525     if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
8526       handleTransparentUnionAttr(*this, D, AL);
8527       break;
8528     }
8529 
8530   // For BPFPreserveAccessIndexAttr, we want to populate the attributes
8531   // to fields and inner records as well.
8532   if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
8533     handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
8534 }
8535 
8536 // Annotation attributes are the only attributes allowed after an access
8537 // specifier.
8538 bool Sema::ProcessAccessDeclAttributeList(
8539     AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
8540   for (const ParsedAttr &AL : AttrList) {
8541     if (AL.getKind() == ParsedAttr::AT_Annotate) {
8542       ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
8543     } else {
8544       Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
8545       return true;
8546     }
8547   }
8548   return false;
8549 }
8550 
8551 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
8552 /// contains any decl attributes that we should warn about.
8553 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
8554   for (const ParsedAttr &AL : A) {
8555     // Only warn if the attribute is an unignored, non-type attribute.
8556     if (AL.isUsedAsTypeAttr() || AL.isInvalid())
8557       continue;
8558     if (AL.getKind() == ParsedAttr::IgnoredAttribute)
8559       continue;
8560 
8561     if (AL.getKind() == ParsedAttr::UnknownAttribute) {
8562       S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
8563           << AL << AL.getRange();
8564     } else {
8565       S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
8566                                                             << AL.getRange();
8567     }
8568   }
8569 }
8570 
8571 /// checkUnusedDeclAttributes - Given a declarator which is not being
8572 /// used to build a declaration, complain about any decl attributes
8573 /// which might be lying around on it.
8574 void Sema::checkUnusedDeclAttributes(Declarator &D) {
8575   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
8576   ::checkUnusedDeclAttributes(*this, D.getAttributes());
8577   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
8578     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
8579 }
8580 
8581 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
8582 /// \#pragma weak needs a non-definition decl and source may not have one.
8583 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8584                                       SourceLocation Loc) {
8585   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
8586   NamedDecl *NewD = nullptr;
8587   if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
8588     FunctionDecl *NewFD;
8589     // FIXME: Missing call to CheckFunctionDeclaration().
8590     // FIXME: Mangling?
8591     // FIXME: Is the qualifier info correct?
8592     // FIXME: Is the DeclContext correct?
8593     NewFD = FunctionDecl::Create(
8594         FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
8595         DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
8596         false /*isInlineSpecified*/, FD->hasPrototype(),
8597         ConstexprSpecKind::Unspecified, FD->getTrailingRequiresClause());
8598     NewD = NewFD;
8599 
8600     if (FD->getQualifier())
8601       NewFD->setQualifierInfo(FD->getQualifierLoc());
8602 
8603     // Fake up parameter variables; they are declared as if this were
8604     // a typedef.
8605     QualType FDTy = FD->getType();
8606     if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
8607       SmallVector<ParmVarDecl*, 16> Params;
8608       for (const auto &AI : FT->param_types()) {
8609         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
8610         Param->setScopeInfo(0, Params.size());
8611         Params.push_back(Param);
8612       }
8613       NewFD->setParams(Params);
8614     }
8615   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
8616     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
8617                            VD->getInnerLocStart(), VD->getLocation(), II,
8618                            VD->getType(), VD->getTypeSourceInfo(),
8619                            VD->getStorageClass());
8620     if (VD->getQualifier())
8621       cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
8622   }
8623   return NewD;
8624 }
8625 
8626 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
8627 /// applied to it, possibly with an alias.
8628 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
8629   if (W.getUsed()) return; // only do this once
8630   W.setUsed(true);
8631   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
8632     IdentifierInfo *NDId = ND->getIdentifier();
8633     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
8634     NewD->addAttr(
8635         AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
8636     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8637                                            AttributeCommonInfo::AS_Pragma));
8638     WeakTopLevelDecl.push_back(NewD);
8639     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
8640     // to insert Decl at TU scope, sorry.
8641     DeclContext *SavedContext = CurContext;
8642     CurContext = Context.getTranslationUnitDecl();
8643     NewD->setDeclContext(CurContext);
8644     NewD->setLexicalDeclContext(CurContext);
8645     PushOnScopeChains(NewD, S);
8646     CurContext = SavedContext;
8647   } else { // just add weak to existing
8648     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8649                                          AttributeCommonInfo::AS_Pragma));
8650   }
8651 }
8652 
8653 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
8654   // It's valid to "forward-declare" #pragma weak, in which case we
8655   // have to do this.
8656   LoadExternalWeakUndeclaredIdentifiers();
8657   if (!WeakUndeclaredIdentifiers.empty()) {
8658     NamedDecl *ND = nullptr;
8659     if (auto *VD = dyn_cast<VarDecl>(D))
8660       if (VD->isExternC())
8661         ND = VD;
8662     if (auto *FD = dyn_cast<FunctionDecl>(D))
8663       if (FD->isExternC())
8664         ND = FD;
8665     if (ND) {
8666       if (IdentifierInfo *Id = ND->getIdentifier()) {
8667         auto I = WeakUndeclaredIdentifiers.find(Id);
8668         if (I != WeakUndeclaredIdentifiers.end()) {
8669           WeakInfo W = I->second;
8670           DeclApplyPragmaWeak(S, ND, W);
8671           WeakUndeclaredIdentifiers[Id] = W;
8672         }
8673       }
8674     }
8675   }
8676 }
8677 
8678 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
8679 /// it, apply them to D.  This is a bit tricky because PD can have attributes
8680 /// specified in many different places, and we need to find and apply them all.
8681 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
8682   // Apply decl attributes from the DeclSpec if present.
8683   if (!PD.getDeclSpec().getAttributes().empty())
8684     ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
8685 
8686   // Walk the declarator structure, applying decl attributes that were in a type
8687   // position to the decl itself.  This handles cases like:
8688   //   int *__attr__(x)** D;
8689   // when X is a decl attribute.
8690   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
8691     ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
8692                              /*IncludeCXX11Attributes=*/false);
8693 
8694   // Finally, apply any attributes on the decl itself.
8695   ProcessDeclAttributeList(S, D, PD.getAttributes());
8696 
8697   // Apply additional attributes specified by '#pragma clang attribute'.
8698   AddPragmaAttributes(S, D);
8699 }
8700 
8701 /// Is the given declaration allowed to use a forbidden type?
8702 /// If so, it'll still be annotated with an attribute that makes it
8703 /// illegal to actually use.
8704 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
8705                                    const DelayedDiagnostic &diag,
8706                                    UnavailableAttr::ImplicitReason &reason) {
8707   // Private ivars are always okay.  Unfortunately, people don't
8708   // always properly make their ivars private, even in system headers.
8709   // Plus we need to make fields okay, too.
8710   if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
8711       !isa<FunctionDecl>(D))
8712     return false;
8713 
8714   // Silently accept unsupported uses of __weak in both user and system
8715   // declarations when it's been disabled, for ease of integration with
8716   // -fno-objc-arc files.  We do have to take some care against attempts
8717   // to define such things;  for now, we've only done that for ivars
8718   // and properties.
8719   if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
8720     if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
8721         diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
8722       reason = UnavailableAttr::IR_ForbiddenWeak;
8723       return true;
8724     }
8725   }
8726 
8727   // Allow all sorts of things in system headers.
8728   if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
8729     // Currently, all the failures dealt with this way are due to ARC
8730     // restrictions.
8731     reason = UnavailableAttr::IR_ARCForbiddenType;
8732     return true;
8733   }
8734 
8735   return false;
8736 }
8737 
8738 /// Handle a delayed forbidden-type diagnostic.
8739 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
8740                                        Decl *D) {
8741   auto Reason = UnavailableAttr::IR_None;
8742   if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
8743     assert(Reason && "didn't set reason?");
8744     D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
8745     return;
8746   }
8747   if (S.getLangOpts().ObjCAutoRefCount)
8748     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
8749       // FIXME: we may want to suppress diagnostics for all
8750       // kind of forbidden type messages on unavailable functions.
8751       if (FD->hasAttr<UnavailableAttr>() &&
8752           DD.getForbiddenTypeDiagnostic() ==
8753               diag::err_arc_array_param_no_ownership) {
8754         DD.Triggered = true;
8755         return;
8756       }
8757     }
8758 
8759   S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
8760       << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
8761   DD.Triggered = true;
8762 }
8763 
8764 
8765 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
8766   assert(DelayedDiagnostics.getCurrentPool());
8767   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
8768   DelayedDiagnostics.popWithoutEmitting(state);
8769 
8770   // When delaying diagnostics to run in the context of a parsed
8771   // declaration, we only want to actually emit anything if parsing
8772   // succeeds.
8773   if (!decl) return;
8774 
8775   // We emit all the active diagnostics in this pool or any of its
8776   // parents.  In general, we'll get one pool for the decl spec
8777   // and a child pool for each declarator; in a decl group like:
8778   //   deprecated_typedef foo, *bar, baz();
8779   // only the declarator pops will be passed decls.  This is correct;
8780   // we really do need to consider delayed diagnostics from the decl spec
8781   // for each of the different declarations.
8782   const DelayedDiagnosticPool *pool = &poppedPool;
8783   do {
8784     bool AnyAccessFailures = false;
8785     for (DelayedDiagnosticPool::pool_iterator
8786            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
8787       // This const_cast is a bit lame.  Really, Triggered should be mutable.
8788       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
8789       if (diag.Triggered)
8790         continue;
8791 
8792       switch (diag.Kind) {
8793       case DelayedDiagnostic::Availability:
8794         // Don't bother giving deprecation/unavailable diagnostics if
8795         // the decl is invalid.
8796         if (!decl->isInvalidDecl())
8797           handleDelayedAvailabilityCheck(diag, decl);
8798         break;
8799 
8800       case DelayedDiagnostic::Access:
8801         // Only produce one access control diagnostic for a structured binding
8802         // declaration: we don't need to tell the user that all the fields are
8803         // inaccessible one at a time.
8804         if (AnyAccessFailures && isa<DecompositionDecl>(decl))
8805           continue;
8806         HandleDelayedAccessCheck(diag, decl);
8807         if (diag.Triggered)
8808           AnyAccessFailures = true;
8809         break;
8810 
8811       case DelayedDiagnostic::ForbiddenType:
8812         handleDelayedForbiddenType(*this, diag, decl);
8813         break;
8814       }
8815     }
8816   } while ((pool = pool->getParent()));
8817 }
8818 
8819 /// Given a set of delayed diagnostics, re-emit them as if they had
8820 /// been delayed in the current context instead of in the given pool.
8821 /// Essentially, this just moves them to the current pool.
8822 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
8823   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
8824   assert(curPool && "re-emitting in undelayed context not supported");
8825   curPool->steal(pool);
8826 }
8827