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