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