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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/Basic/CharInfo.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Scope.h"
31 #include "llvm/ADT/StringExtras.h"
32 using namespace clang;
33 using namespace sema;
34 
35 namespace AttributeLangSupport {
36   enum LANG {
37     C,
38     Cpp,
39     ObjC
40   };
41 }
42 
43 //===----------------------------------------------------------------------===//
44 //  Helper functions
45 //===----------------------------------------------------------------------===//
46 
47 /// isFunctionOrMethod - Return true if the given decl has function
48 /// type (function or function-typed variable) or an Objective-C
49 /// method.
50 static bool isFunctionOrMethod(const Decl *D) {
51   return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
52 }
53 
54 /// Return true if the given decl has a declarator that should have
55 /// been processed by Sema::GetTypeForDeclarator.
56 static bool hasDeclarator(const Decl *D) {
57   // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
58   return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
59          isa<ObjCPropertyDecl>(D);
60 }
61 
62 /// hasFunctionProto - Return true if the given decl has a argument
63 /// information. This decl should have already passed
64 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
65 static bool hasFunctionProto(const Decl *D) {
66   if (const FunctionType *FnTy = D->getFunctionType())
67     return isa<FunctionProtoType>(FnTy);
68   return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
69 }
70 
71 /// getFunctionOrMethodNumParams - Return number of function or method
72 /// parameters. It is an error to call this on a K&R function (use
73 /// hasFunctionProto first).
74 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
75   if (const FunctionType *FnTy = D->getFunctionType())
76     return cast<FunctionProtoType>(FnTy)->getNumParams();
77   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
78     return BD->getNumParams();
79   return cast<ObjCMethodDecl>(D)->param_size();
80 }
81 
82 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
83   if (const FunctionType *FnTy = D->getFunctionType())
84     return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
85   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
86     return BD->getParamDecl(Idx)->getType();
87 
88   return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
89 }
90 
91 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
92   if (const auto *FD = dyn_cast<FunctionDecl>(D))
93     return FD->getParamDecl(Idx)->getSourceRange();
94   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
95     return MD->parameters()[Idx]->getSourceRange();
96   if (const auto *BD = dyn_cast<BlockDecl>(D))
97     return BD->getParamDecl(Idx)->getSourceRange();
98   return SourceRange();
99 }
100 
101 static QualType getFunctionOrMethodResultType(const Decl *D) {
102   if (const FunctionType *FnTy = D->getFunctionType())
103     return cast<FunctionType>(FnTy)->getReturnType();
104   return cast<ObjCMethodDecl>(D)->getReturnType();
105 }
106 
107 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
108   if (const auto *FD = dyn_cast<FunctionDecl>(D))
109     return FD->getReturnTypeSourceRange();
110   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
111     return MD->getReturnTypeSourceRange();
112   return SourceRange();
113 }
114 
115 static bool isFunctionOrMethodVariadic(const Decl *D) {
116   if (const FunctionType *FnTy = D->getFunctionType()) {
117     const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
118     return proto->isVariadic();
119   }
120   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
121     return BD->isVariadic();
122 
123   return cast<ObjCMethodDecl>(D)->isVariadic();
124 }
125 
126 static bool isInstanceMethod(const Decl *D) {
127   if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
128     return MethodDecl->isInstance();
129   return false;
130 }
131 
132 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
133   const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
134   if (!PT)
135     return false;
136 
137   ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
138   if (!Cls)
139     return false;
140 
141   IdentifierInfo* ClsName = Cls->getIdentifier();
142 
143   // FIXME: Should we walk the chain of classes?
144   return ClsName == &Ctx.Idents.get("NSString") ||
145          ClsName == &Ctx.Idents.get("NSMutableString");
146 }
147 
148 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
149   const PointerType *PT = T->getAs<PointerType>();
150   if (!PT)
151     return false;
152 
153   const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
154   if (!RT)
155     return false;
156 
157   const RecordDecl *RD = RT->getDecl();
158   if (RD->getTagKind() != TTK_Struct)
159     return false;
160 
161   return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
162 }
163 
164 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
165   // FIXME: Include the type in the argument list.
166   return Attr.getNumArgs() + Attr.hasParsedType();
167 }
168 
169 template <typename Compare>
170 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
171                                       unsigned Num, unsigned Diag,
172                                       Compare Comp) {
173   if (Comp(getNumAttributeArgs(Attr), Num)) {
174     S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
175     return false;
176   }
177 
178   return true;
179 }
180 
181 /// \brief Check if the attribute has exactly as many args as Num. May
182 /// output an error.
183 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
184                                   unsigned Num) {
185   return checkAttributeNumArgsImpl(S, Attr, Num,
186                                    diag::err_attribute_wrong_number_arguments,
187                                    std::not_equal_to<unsigned>());
188 }
189 
190 /// \brief Check if the attribute has at least as many args as Num. May
191 /// output an error.
192 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
193                                          unsigned Num) {
194   return checkAttributeNumArgsImpl(S, Attr, Num,
195                                    diag::err_attribute_too_few_arguments,
196                                    std::less<unsigned>());
197 }
198 
199 /// \brief Check if the attribute has at most as many args as Num. May
200 /// output an error.
201 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
202                                          unsigned Num) {
203   return checkAttributeNumArgsImpl(S, Attr, Num,
204                                    diag::err_attribute_too_many_arguments,
205                                    std::greater<unsigned>());
206 }
207 
208 /// \brief If Expr is a valid integer constant, get the value of the integer
209 /// expression and return success or failure. May output an error.
210 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
211                                 const Expr *Expr, uint32_t &Val,
212                                 unsigned Idx = UINT_MAX) {
213   llvm::APSInt I(32);
214   if (Expr->isTypeDependent() || Expr->isValueDependent() ||
215       !Expr->isIntegerConstantExpr(I, S.Context)) {
216     if (Idx != UINT_MAX)
217       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
218         << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
219         << Expr->getSourceRange();
220     else
221       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
222         << Attr.getName() << AANT_ArgumentIntegerConstant
223         << Expr->getSourceRange();
224     return false;
225   }
226 
227   if (!I.isIntN(32)) {
228     S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
229         << I.toString(10, false) << 32 << /* Unsigned */ 1;
230     return false;
231   }
232 
233   Val = (uint32_t)I.getZExtValue();
234   return true;
235 }
236 
237 /// \brief Diagnose mutually exclusive attributes when present on a given
238 /// declaration. Returns true if diagnosed.
239 template <typename AttrTy>
240 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
241                                      const AttributeList &Attr) {
242   if (AttrTy *A = D->getAttr<AttrTy>()) {
243     S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
244       << Attr.getName() << A;
245     return true;
246   }
247   return false;
248 }
249 
250 /// \brief Check if IdxExpr is a valid parameter index for a function or
251 /// instance method D.  May output an error.
252 ///
253 /// \returns true if IdxExpr is a valid index.
254 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
255                                                 const AttributeList &Attr,
256                                                 unsigned AttrArgNum,
257                                                 const Expr *IdxExpr,
258                                                 uint64_t &Idx) {
259   assert(isFunctionOrMethod(D));
260 
261   // In C++ the implicit 'this' function parameter also counts.
262   // Parameters are counted from one.
263   bool HP = hasFunctionProto(D);
264   bool HasImplicitThisParam = isInstanceMethod(D);
265   bool IV = HP && isFunctionOrMethodVariadic(D);
266   unsigned NumParams =
267       (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
268 
269   llvm::APSInt IdxInt;
270   if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
271       !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
272     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
273       << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
274       << IdxExpr->getSourceRange();
275     return false;
276   }
277 
278   Idx = IdxInt.getLimitedValue();
279   if (Idx < 1 || (!IV && Idx > NumParams)) {
280     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
281       << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
282     return false;
283   }
284   Idx--; // Convert to zero-based.
285   if (HasImplicitThisParam) {
286     if (Idx == 0) {
287       S.Diag(Attr.getLoc(),
288              diag::err_attribute_invalid_implicit_this_argument)
289         << Attr.getName() << IdxExpr->getSourceRange();
290       return false;
291     }
292     --Idx;
293   }
294 
295   return true;
296 }
297 
298 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
299 /// If not emit an error and return false. If the argument is an identifier it
300 /// will emit an error with a fixit hint and treat it as if it was a string
301 /// literal.
302 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
303                                           unsigned ArgNum, StringRef &Str,
304                                           SourceLocation *ArgLocation) {
305   // Look for identifiers. If we have one emit a hint to fix it to a literal.
306   if (Attr.isArgIdent(ArgNum)) {
307     IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
308     Diag(Loc->Loc, diag::err_attribute_argument_type)
309         << Attr.getName() << AANT_ArgumentString
310         << FixItHint::CreateInsertion(Loc->Loc, "\"")
311         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
312     Str = Loc->Ident->getName();
313     if (ArgLocation)
314       *ArgLocation = Loc->Loc;
315     return true;
316   }
317 
318   // Now check for an actual string literal.
319   Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
320   StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
321   if (ArgLocation)
322     *ArgLocation = ArgExpr->getLocStart();
323 
324   if (!Literal || !Literal->isAscii()) {
325     Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
326         << Attr.getName() << AANT_ArgumentString;
327     return false;
328   }
329 
330   Str = Literal->getString();
331   return true;
332 }
333 
334 /// \brief Applies the given attribute to the Decl without performing any
335 /// additional semantic checking.
336 template <typename AttrType>
337 static void handleSimpleAttribute(Sema &S, Decl *D,
338                                   const AttributeList &Attr) {
339   D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
340                                         Attr.getAttributeSpellingListIndex()));
341 }
342 
343 /// \brief Check if the passed-in expression is of type int or bool.
344 static bool isIntOrBool(Expr *Exp) {
345   QualType QT = Exp->getType();
346   return QT->isBooleanType() || QT->isIntegerType();
347 }
348 
349 
350 // Check to see if the type is a smart pointer of some kind.  We assume
351 // it's a smart pointer if it defines both operator-> and operator*.
352 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
353   DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
354     S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
355   if (Res1.empty())
356     return false;
357 
358   DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
359     S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
360   if (Res2.empty())
361     return false;
362 
363   return true;
364 }
365 
366 /// \brief Check if passed in Decl is a pointer type.
367 /// Note that this function may produce an error message.
368 /// \return true if the Decl is a pointer type; false otherwise
369 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
370                                        const AttributeList &Attr) {
371   const ValueDecl *vd = cast<ValueDecl>(D);
372   QualType QT = vd->getType();
373   if (QT->isAnyPointerType())
374     return true;
375 
376   if (const RecordType *RT = QT->getAs<RecordType>()) {
377     // If it's an incomplete type, it could be a smart pointer; skip it.
378     // (We don't want to force template instantiation if we can avoid it,
379     // since that would alter the order in which templates are instantiated.)
380     if (RT->isIncompleteType())
381       return true;
382 
383     if (threadSafetyCheckIsSmartPointer(S, RT))
384       return true;
385   }
386 
387   S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
388     << Attr.getName() << QT;
389   return false;
390 }
391 
392 /// \brief Checks that the passed in QualType either is of RecordType or points
393 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
394 static const RecordType *getRecordType(QualType QT) {
395   if (const RecordType *RT = QT->getAs<RecordType>())
396     return RT;
397 
398   // Now check if we point to record type.
399   if (const PointerType *PT = QT->getAs<PointerType>())
400     return PT->getPointeeType()->getAs<RecordType>();
401 
402   return nullptr;
403 }
404 
405 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
406   const RecordType *RT = getRecordType(Ty);
407 
408   if (!RT)
409     return false;
410 
411   // Don't check for the capability if the class hasn't been defined yet.
412   if (RT->isIncompleteType())
413     return true;
414 
415   // Allow smart pointers to be used as capability objects.
416   // FIXME -- Check the type that the smart pointer points to.
417   if (threadSafetyCheckIsSmartPointer(S, RT))
418     return true;
419 
420   // Check if the record itself has a capability.
421   RecordDecl *RD = RT->getDecl();
422   if (RD->hasAttr<CapabilityAttr>())
423     return true;
424 
425   // Else check if any base classes have a capability.
426   if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
427     CXXBasePaths BPaths(false, false);
428     if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
429       void *) {
430       return BS->getType()->getAs<RecordType>()
431         ->getDecl()->hasAttr<CapabilityAttr>();
432     }, nullptr, BPaths))
433       return true;
434   }
435   return false;
436 }
437 
438 static bool checkTypedefTypeForCapability(QualType Ty) {
439   const auto *TD = Ty->getAs<TypedefType>();
440   if (!TD)
441     return false;
442 
443   TypedefNameDecl *TN = TD->getDecl();
444   if (!TN)
445     return false;
446 
447   return TN->hasAttr<CapabilityAttr>();
448 }
449 
450 static bool typeHasCapability(Sema &S, QualType Ty) {
451   if (checkTypedefTypeForCapability(Ty))
452     return true;
453 
454   if (checkRecordTypeForCapability(S, Ty))
455     return true;
456 
457   return false;
458 }
459 
460 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
461   // Capability expressions are simple expressions involving the boolean logic
462   // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
463   // a DeclRefExpr is found, its type should be checked to determine whether it
464   // is a capability or not.
465 
466   if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
467     return typeHasCapability(S, E->getType());
468   else if (const auto *E = dyn_cast<CastExpr>(Ex))
469     return isCapabilityExpr(S, E->getSubExpr());
470   else if (const auto *E = dyn_cast<ParenExpr>(Ex))
471     return isCapabilityExpr(S, E->getSubExpr());
472   else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
473     if (E->getOpcode() == UO_LNot)
474       return isCapabilityExpr(S, E->getSubExpr());
475     return false;
476   } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
477     if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
478       return isCapabilityExpr(S, E->getLHS()) &&
479              isCapabilityExpr(S, E->getRHS());
480     return false;
481   }
482 
483   return false;
484 }
485 
486 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
487 /// a capability object.
488 /// \param Sidx The attribute argument index to start checking with.
489 /// \param ParamIdxOk Whether an argument can be indexing into a function
490 /// parameter list.
491 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
492                                            const AttributeList &Attr,
493                                            SmallVectorImpl<Expr *> &Args,
494                                            int Sidx = 0,
495                                            bool ParamIdxOk = false) {
496   for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
497     Expr *ArgExp = Attr.getArgAsExpr(Idx);
498 
499     if (ArgExp->isTypeDependent()) {
500       // FIXME -- need to check this again on template instantiation
501       Args.push_back(ArgExp);
502       continue;
503     }
504 
505     if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
506       if (StrLit->getLength() == 0 ||
507           (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
508         // Pass empty strings to the analyzer without warnings.
509         // Treat "*" as the universal lock.
510         Args.push_back(ArgExp);
511         continue;
512       }
513 
514       // We allow constant strings to be used as a placeholder for expressions
515       // that are not valid C++ syntax, but warn that they are ignored.
516       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
517         Attr.getName();
518       Args.push_back(ArgExp);
519       continue;
520     }
521 
522     QualType ArgTy = ArgExp->getType();
523 
524     // A pointer to member expression of the form  &MyClass::mu is treated
525     // specially -- we need to look at the type of the member.
526     if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
527       if (UOp->getOpcode() == UO_AddrOf)
528         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
529           if (DRE->getDecl()->isCXXInstanceMember())
530             ArgTy = DRE->getDecl()->getType();
531 
532     // First see if we can just cast to record type, or pointer to record type.
533     const RecordType *RT = getRecordType(ArgTy);
534 
535     // Now check if we index into a record type function param.
536     if(!RT && ParamIdxOk) {
537       FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
538       IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
539       if(FD && IL) {
540         unsigned int NumParams = FD->getNumParams();
541         llvm::APInt ArgValue = IL->getValue();
542         uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
543         uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
544         if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
545           S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
546             << Attr.getName() << Idx + 1 << NumParams;
547           continue;
548         }
549         ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
550       }
551     }
552 
553     // If the type does not have a capability, see if the components of the
554     // expression have capabilities. This allows for writing C code where the
555     // capability may be on the type, and the expression is a capability
556     // boolean logic expression. Eg) requires_capability(A || B && !C)
557     if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
558       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
559           << Attr.getName() << ArgTy;
560 
561     Args.push_back(ArgExp);
562   }
563 }
564 
565 //===----------------------------------------------------------------------===//
566 // Attribute Implementations
567 //===----------------------------------------------------------------------===//
568 
569 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
570                                    const AttributeList &Attr) {
571   if (!threadSafetyCheckIsPointer(S, D, Attr))
572     return;
573 
574   D->addAttr(::new (S.Context)
575              PtGuardedVarAttr(Attr.getRange(), S.Context,
576                               Attr.getAttributeSpellingListIndex()));
577 }
578 
579 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
580                                      const AttributeList &Attr,
581                                      Expr* &Arg) {
582   SmallVector<Expr*, 1> Args;
583   // check that all arguments are lockable objects
584   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
585   unsigned Size = Args.size();
586   if (Size != 1)
587     return false;
588 
589   Arg = Args[0];
590 
591   return true;
592 }
593 
594 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
595   Expr *Arg = nullptr;
596   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
597     return;
598 
599   D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
600                                         Attr.getAttributeSpellingListIndex()));
601 }
602 
603 static void handlePtGuardedByAttr(Sema &S, Decl *D,
604                                   const AttributeList &Attr) {
605   Expr *Arg = nullptr;
606   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
607     return;
608 
609   if (!threadSafetyCheckIsPointer(S, D, Attr))
610     return;
611 
612   D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
613                                                S.Context, Arg,
614                                         Attr.getAttributeSpellingListIndex()));
615 }
616 
617 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
618                                         const AttributeList &Attr,
619                                         SmallVectorImpl<Expr *> &Args) {
620   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
621     return false;
622 
623   // Check that this attribute only applies to lockable types.
624   QualType QT = cast<ValueDecl>(D)->getType();
625   if (!QT->isDependentType()) {
626     const RecordType *RT = getRecordType(QT);
627     if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
628       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
629         << Attr.getName();
630       return false;
631     }
632   }
633 
634   // Check that all arguments are lockable objects.
635   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
636   if (Args.empty())
637     return false;
638 
639   return true;
640 }
641 
642 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
643                                     const AttributeList &Attr) {
644   SmallVector<Expr*, 1> Args;
645   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
646     return;
647 
648   Expr **StartArg = &Args[0];
649   D->addAttr(::new (S.Context)
650              AcquiredAfterAttr(Attr.getRange(), S.Context,
651                                StartArg, Args.size(),
652                                Attr.getAttributeSpellingListIndex()));
653 }
654 
655 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
656                                      const AttributeList &Attr) {
657   SmallVector<Expr*, 1> Args;
658   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
659     return;
660 
661   Expr **StartArg = &Args[0];
662   D->addAttr(::new (S.Context)
663              AcquiredBeforeAttr(Attr.getRange(), S.Context,
664                                 StartArg, Args.size(),
665                                 Attr.getAttributeSpellingListIndex()));
666 }
667 
668 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
669                                    const AttributeList &Attr,
670                                    SmallVectorImpl<Expr *> &Args) {
671   // zero or more arguments ok
672   // check that all arguments are lockable objects
673   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
674 
675   return true;
676 }
677 
678 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
679                                        const AttributeList &Attr) {
680   SmallVector<Expr*, 1> Args;
681   if (!checkLockFunAttrCommon(S, D, Attr, Args))
682     return;
683 
684   unsigned Size = Args.size();
685   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
686   D->addAttr(::new (S.Context)
687              AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
688                                   Attr.getAttributeSpellingListIndex()));
689 }
690 
691 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
692                                           const AttributeList &Attr) {
693   SmallVector<Expr*, 1> Args;
694   if (!checkLockFunAttrCommon(S, D, Attr, Args))
695     return;
696 
697   unsigned Size = Args.size();
698   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
699   D->addAttr(::new (S.Context)
700              AssertExclusiveLockAttr(Attr.getRange(), S.Context,
701                                      StartArg, Size,
702                                      Attr.getAttributeSpellingListIndex()));
703 }
704 
705 
706 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
707                                       const AttributeList &Attr,
708                                       SmallVectorImpl<Expr *> &Args) {
709   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
710     return false;
711 
712   if (!isIntOrBool(Attr.getArgAsExpr(0))) {
713     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
714       << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
715     return false;
716   }
717 
718   // check that all arguments are lockable objects
719   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
720 
721   return true;
722 }
723 
724 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
725                                             const AttributeList &Attr) {
726   SmallVector<Expr*, 2> Args;
727   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
728     return;
729 
730   D->addAttr(::new (S.Context)
731              SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
732                                        Attr.getArgAsExpr(0),
733                                        Args.data(), Args.size(),
734                                        Attr.getAttributeSpellingListIndex()));
735 }
736 
737 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
738                                                const AttributeList &Attr) {
739   SmallVector<Expr*, 2> Args;
740   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
741     return;
742 
743   D->addAttr(::new (S.Context)
744              ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context,
745                                           Attr.getArgAsExpr(0),
746                                           Args.data(), Args.size(),
747                                           Attr.getAttributeSpellingListIndex()));
748 }
749 
750 static void handleLockReturnedAttr(Sema &S, Decl *D,
751                                    const AttributeList &Attr) {
752   // check that the argument is lockable object
753   SmallVector<Expr*, 1> Args;
754   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
755   unsigned Size = Args.size();
756   if (Size == 0)
757     return;
758 
759   D->addAttr(::new (S.Context)
760              LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
761                               Attr.getAttributeSpellingListIndex()));
762 }
763 
764 static void handleLocksExcludedAttr(Sema &S, Decl *D,
765                                     const AttributeList &Attr) {
766   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
767     return;
768 
769   // check that all arguments are lockable objects
770   SmallVector<Expr*, 1> Args;
771   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
772   unsigned Size = Args.size();
773   if (Size == 0)
774     return;
775   Expr **StartArg = &Args[0];
776 
777   D->addAttr(::new (S.Context)
778              LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
779                                Attr.getAttributeSpellingListIndex()));
780 }
781 
782 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
783   Expr *Cond = Attr.getArgAsExpr(0);
784   if (!Cond->isTypeDependent()) {
785     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
786     if (Converted.isInvalid())
787       return;
788     Cond = Converted.get();
789   }
790 
791   StringRef Msg;
792   if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
793     return;
794 
795   SmallVector<PartialDiagnosticAt, 8> Diags;
796   if (!Cond->isValueDependent() &&
797       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
798                                                 Diags)) {
799     S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
800     for (int I = 0, N = Diags.size(); I != N; ++I)
801       S.Diag(Diags[I].first, Diags[I].second);
802     return;
803   }
804 
805   D->addAttr(::new (S.Context)
806              EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
807                           Attr.getAttributeSpellingListIndex()));
808 }
809 
810 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
811   ConsumableAttr::ConsumedState DefaultState;
812 
813   if (Attr.isArgIdent(0)) {
814     IdentifierLoc *IL = Attr.getArgAsIdent(0);
815     if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
816                                                    DefaultState)) {
817       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
818         << Attr.getName() << IL->Ident;
819       return;
820     }
821   } else {
822     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
823         << Attr.getName() << AANT_ArgumentIdentifier;
824     return;
825   }
826 
827   D->addAttr(::new (S.Context)
828              ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
829                             Attr.getAttributeSpellingListIndex()));
830 }
831 
832 
833 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
834                                         const AttributeList &Attr) {
835   ASTContext &CurrContext = S.getASTContext();
836   QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
837 
838   if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
839     if (!RD->hasAttr<ConsumableAttr>()) {
840       S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
841         RD->getNameAsString();
842 
843       return false;
844     }
845   }
846 
847   return true;
848 }
849 
850 
851 static void handleCallableWhenAttr(Sema &S, Decl *D,
852                                    const AttributeList &Attr) {
853   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
854     return;
855 
856   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
857     return;
858 
859   SmallVector<CallableWhenAttr::ConsumedState, 3> States;
860   for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
861     CallableWhenAttr::ConsumedState CallableState;
862 
863     StringRef StateString;
864     SourceLocation Loc;
865     if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
866       return;
867 
868     if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
869                                                      CallableState)) {
870       S.Diag(Loc, diag::warn_attribute_type_not_supported)
871         << Attr.getName() << StateString;
872       return;
873     }
874 
875     States.push_back(CallableState);
876   }
877 
878   D->addAttr(::new (S.Context)
879              CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
880                States.size(), Attr.getAttributeSpellingListIndex()));
881 }
882 
883 
884 static void handleParamTypestateAttr(Sema &S, Decl *D,
885                                     const AttributeList &Attr) {
886   ParamTypestateAttr::ConsumedState ParamState;
887 
888   if (Attr.isArgIdent(0)) {
889     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
890     StringRef StateString = Ident->Ident->getName();
891 
892     if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
893                                                        ParamState)) {
894       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
895         << Attr.getName() << StateString;
896       return;
897     }
898   } else {
899     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
900       Attr.getName() << AANT_ArgumentIdentifier;
901     return;
902   }
903 
904   // FIXME: This check is currently being done in the analysis.  It can be
905   //        enabled here only after the parser propagates attributes at
906   //        template specialization definition, not declaration.
907   //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
908   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
909   //
910   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
911   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
912   //      ReturnType.getAsString();
913   //    return;
914   //}
915 
916   D->addAttr(::new (S.Context)
917              ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
918                                 Attr.getAttributeSpellingListIndex()));
919 }
920 
921 
922 static void handleReturnTypestateAttr(Sema &S, Decl *D,
923                                       const AttributeList &Attr) {
924   ReturnTypestateAttr::ConsumedState ReturnState;
925 
926   if (Attr.isArgIdent(0)) {
927     IdentifierLoc *IL = Attr.getArgAsIdent(0);
928     if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
929                                                         ReturnState)) {
930       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
931         << Attr.getName() << IL->Ident;
932       return;
933     }
934   } else {
935     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
936       Attr.getName() << AANT_ArgumentIdentifier;
937     return;
938   }
939 
940   // FIXME: This check is currently being done in the analysis.  It can be
941   //        enabled here only after the parser propagates attributes at
942   //        template specialization definition, not declaration.
943   //QualType ReturnType;
944   //
945   //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
946   //  ReturnType = Param->getType();
947   //
948   //} else if (const CXXConstructorDecl *Constructor =
949   //             dyn_cast<CXXConstructorDecl>(D)) {
950   //  ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
951   //
952   //} else {
953   //
954   //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
955   //}
956   //
957   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
958   //
959   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
960   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
961   //      ReturnType.getAsString();
962   //    return;
963   //}
964 
965   D->addAttr(::new (S.Context)
966              ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
967                                  Attr.getAttributeSpellingListIndex()));
968 }
969 
970 
971 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
972   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
973     return;
974 
975   SetTypestateAttr::ConsumedState NewState;
976   if (Attr.isArgIdent(0)) {
977     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
978     StringRef Param = Ident->Ident->getName();
979     if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
980       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
981         << Attr.getName() << Param;
982       return;
983     }
984   } else {
985     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
986       Attr.getName() << AANT_ArgumentIdentifier;
987     return;
988   }
989 
990   D->addAttr(::new (S.Context)
991              SetTypestateAttr(Attr.getRange(), S.Context, NewState,
992                               Attr.getAttributeSpellingListIndex()));
993 }
994 
995 static void handleTestTypestateAttr(Sema &S, Decl *D,
996                                     const AttributeList &Attr) {
997   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
998     return;
999 
1000   TestTypestateAttr::ConsumedState TestState;
1001   if (Attr.isArgIdent(0)) {
1002     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1003     StringRef Param = Ident->Ident->getName();
1004     if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1005       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1006         << Attr.getName() << Param;
1007       return;
1008     }
1009   } else {
1010     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1011       Attr.getName() << AANT_ArgumentIdentifier;
1012     return;
1013   }
1014 
1015   D->addAttr(::new (S.Context)
1016              TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1017                                 Attr.getAttributeSpellingListIndex()));
1018 }
1019 
1020 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1021                                     const AttributeList &Attr) {
1022   // Remember this typedef decl, we will need it later for diagnostics.
1023   S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1024 }
1025 
1026 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1027   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1028     TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1029                                         Attr.getAttributeSpellingListIndex()));
1030   else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1031     // If the alignment is less than or equal to 8 bits, the packed attribute
1032     // has no effect.
1033     if (!FD->getType()->isDependentType() &&
1034         !FD->getType()->isIncompleteType() &&
1035         S.Context.getTypeAlign(FD->getType()) <= 8)
1036       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1037         << Attr.getName() << FD->getType();
1038     else
1039       FD->addAttr(::new (S.Context)
1040                   PackedAttr(Attr.getRange(), S.Context,
1041                              Attr.getAttributeSpellingListIndex()));
1042   } else
1043     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1044 }
1045 
1046 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1047   // The IBOutlet/IBOutletCollection attributes only apply to instance
1048   // variables or properties of Objective-C classes.  The outlet must also
1049   // have an object reference type.
1050   if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1051     if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1052       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1053         << Attr.getName() << VD->getType() << 0;
1054       return false;
1055     }
1056   }
1057   else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1058     if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1059       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1060         << Attr.getName() << PD->getType() << 1;
1061       return false;
1062     }
1063   }
1064   else {
1065     S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1066     return false;
1067   }
1068 
1069   return true;
1070 }
1071 
1072 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1073   if (!checkIBOutletCommon(S, D, Attr))
1074     return;
1075 
1076   D->addAttr(::new (S.Context)
1077              IBOutletAttr(Attr.getRange(), S.Context,
1078                           Attr.getAttributeSpellingListIndex()));
1079 }
1080 
1081 static void handleIBOutletCollection(Sema &S, Decl *D,
1082                                      const AttributeList &Attr) {
1083 
1084   // The iboutletcollection attribute can have zero or one arguments.
1085   if (Attr.getNumArgs() > 1) {
1086     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1087       << Attr.getName() << 1;
1088     return;
1089   }
1090 
1091   if (!checkIBOutletCommon(S, D, Attr))
1092     return;
1093 
1094   ParsedType PT;
1095 
1096   if (Attr.hasParsedType())
1097     PT = Attr.getTypeArg();
1098   else {
1099     PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1100                        S.getScopeForContext(D->getDeclContext()->getParent()));
1101     if (!PT) {
1102       S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1103       return;
1104     }
1105   }
1106 
1107   TypeSourceInfo *QTLoc = nullptr;
1108   QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1109   if (!QTLoc)
1110     QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1111 
1112   // Diagnose use of non-object type in iboutletcollection attribute.
1113   // FIXME. Gnu attribute extension ignores use of builtin types in
1114   // attributes. So, __attribute__((iboutletcollection(char))) will be
1115   // treated as __attribute__((iboutletcollection())).
1116   if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1117     S.Diag(Attr.getLoc(),
1118            QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1119                                : diag::err_iboutletcollection_type) << QT;
1120     return;
1121   }
1122 
1123   D->addAttr(::new (S.Context)
1124              IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1125                                     Attr.getAttributeSpellingListIndex()));
1126 }
1127 
1128 bool Sema::isValidNonNullAttrType(QualType T) {
1129   T = T.getNonReferenceType();
1130 
1131   // The nonnull attribute can be applied to a transparent union that
1132   // contains a pointer type.
1133   if (const RecordType *UT = T->getAsUnionType()) {
1134     if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1135       RecordDecl *UD = UT->getDecl();
1136       for (const auto *I : UD->fields()) {
1137         QualType QT = I->getType();
1138         if (QT->isAnyPointerType() || QT->isBlockPointerType())
1139           return true;
1140       }
1141     }
1142   }
1143 
1144   return T->isAnyPointerType() || T->isBlockPointerType();
1145 }
1146 
1147 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1148                                 SourceRange AttrParmRange,
1149                                 SourceRange NonNullTypeRange,
1150                                 bool isReturnValue = false) {
1151   if (!S.isValidNonNullAttrType(T)) {
1152     S.Diag(Attr.getLoc(), isReturnValue
1153                               ? diag::warn_attribute_return_pointers_only
1154                               : diag::warn_attribute_pointers_only)
1155         << Attr.getName() << AttrParmRange << NonNullTypeRange;
1156     return false;
1157   }
1158   return true;
1159 }
1160 
1161 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1162   SmallVector<unsigned, 8> NonNullArgs;
1163   for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1164     Expr *Ex = Attr.getArgAsExpr(I);
1165     uint64_t Idx;
1166     if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1167       return;
1168 
1169     // Is the function argument a pointer type?
1170     if (Idx < getFunctionOrMethodNumParams(D) &&
1171         !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1172                              Ex->getSourceRange(),
1173                              getFunctionOrMethodParamRange(D, Idx)))
1174       continue;
1175 
1176     NonNullArgs.push_back(Idx);
1177   }
1178 
1179   // If no arguments were specified to __attribute__((nonnull)) then all pointer
1180   // arguments have a nonnull attribute; warn if there aren't any. Skip this
1181   // check if the attribute came from a macro expansion or a template
1182   // instantiation.
1183   if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1184       S.ActiveTemplateInstantiations.empty()) {
1185     bool AnyPointers = isFunctionOrMethodVariadic(D);
1186     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1187          I != E && !AnyPointers; ++I) {
1188       QualType T = getFunctionOrMethodParamType(D, I);
1189       if (T->isDependentType() || S.isValidNonNullAttrType(T))
1190         AnyPointers = true;
1191     }
1192 
1193     if (!AnyPointers)
1194       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1195   }
1196 
1197   unsigned *Start = NonNullArgs.data();
1198   unsigned Size = NonNullArgs.size();
1199   llvm::array_pod_sort(Start, Start + Size);
1200   D->addAttr(::new (S.Context)
1201              NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1202                          Attr.getAttributeSpellingListIndex()));
1203 }
1204 
1205 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1206                                        const AttributeList &Attr) {
1207   if (Attr.getNumArgs() > 0) {
1208     if (D->getFunctionType()) {
1209       handleNonNullAttr(S, D, Attr);
1210     } else {
1211       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1212         << D->getSourceRange();
1213     }
1214     return;
1215   }
1216 
1217   // Is the argument a pointer type?
1218   if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1219                            D->getSourceRange()))
1220     return;
1221 
1222   D->addAttr(::new (S.Context)
1223              NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1224                          Attr.getAttributeSpellingListIndex()));
1225 }
1226 
1227 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1228                                      const AttributeList &Attr) {
1229   QualType ResultType = getFunctionOrMethodResultType(D);
1230   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1231   if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1232                            /* isReturnValue */ true))
1233     return;
1234 
1235   D->addAttr(::new (S.Context)
1236             ReturnsNonNullAttr(Attr.getRange(), S.Context,
1237                                Attr.getAttributeSpellingListIndex()));
1238 }
1239 
1240 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1241   // This attribute must be applied to a function declaration. The first
1242   // argument to the attribute must be an identifier, the name of the resource,
1243   // for example: malloc. The following arguments must be argument indexes, the
1244   // arguments must be of integer type for Returns, otherwise of pointer type.
1245   // The difference between Holds and Takes is that a pointer may still be used
1246   // after being held. free() should be __attribute((ownership_takes)), whereas
1247   // a list append function may well be __attribute((ownership_holds)).
1248 
1249   if (!AL.isArgIdent(0)) {
1250     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1251       << AL.getName() << 1 << AANT_ArgumentIdentifier;
1252     return;
1253   }
1254 
1255   // Figure out our Kind.
1256   OwnershipAttr::OwnershipKind K =
1257       OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1258                     AL.getAttributeSpellingListIndex()).getOwnKind();
1259 
1260   // Check arguments.
1261   switch (K) {
1262   case OwnershipAttr::Takes:
1263   case OwnershipAttr::Holds:
1264     if (AL.getNumArgs() < 2) {
1265       S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1266         << AL.getName() << 2;
1267       return;
1268     }
1269     break;
1270   case OwnershipAttr::Returns:
1271     if (AL.getNumArgs() > 2) {
1272       S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1273         << AL.getName() << 1;
1274       return;
1275     }
1276     break;
1277   }
1278 
1279   IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1280 
1281   // Normalize the argument, __foo__ becomes foo.
1282   StringRef ModuleName = Module->getName();
1283   if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1284       ModuleName.size() > 4) {
1285     ModuleName = ModuleName.drop_front(2).drop_back(2);
1286     Module = &S.PP.getIdentifierTable().get(ModuleName);
1287   }
1288 
1289   SmallVector<unsigned, 8> OwnershipArgs;
1290   for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1291     Expr *Ex = AL.getArgAsExpr(i);
1292     uint64_t Idx;
1293     if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1294       return;
1295 
1296     // Is the function argument a pointer type?
1297     QualType T = getFunctionOrMethodParamType(D, Idx);
1298     int Err = -1;  // No error
1299     switch (K) {
1300       case OwnershipAttr::Takes:
1301       case OwnershipAttr::Holds:
1302         if (!T->isAnyPointerType() && !T->isBlockPointerType())
1303           Err = 0;
1304         break;
1305       case OwnershipAttr::Returns:
1306         if (!T->isIntegerType())
1307           Err = 1;
1308         break;
1309     }
1310     if (-1 != Err) {
1311       S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1312         << Ex->getSourceRange();
1313       return;
1314     }
1315 
1316     // Check we don't have a conflict with another ownership attribute.
1317     for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1318       // Cannot have two ownership attributes of different kinds for the same
1319       // index.
1320       if (I->getOwnKind() != K && I->args_end() !=
1321           std::find(I->args_begin(), I->args_end(), Idx)) {
1322         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1323           << AL.getName() << I;
1324         return;
1325       } else if (K == OwnershipAttr::Returns &&
1326                  I->getOwnKind() == OwnershipAttr::Returns) {
1327         // A returns attribute conflicts with any other returns attribute using
1328         // a different index. Note, diagnostic reporting is 1-based, but stored
1329         // argument indexes are 0-based.
1330         if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1331           S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1332               << *(I->args_begin()) + 1;
1333           if (I->args_size())
1334             S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1335                 << (unsigned)Idx + 1 << Ex->getSourceRange();
1336           return;
1337         }
1338       }
1339     }
1340     OwnershipArgs.push_back(Idx);
1341   }
1342 
1343   unsigned* start = OwnershipArgs.data();
1344   unsigned size = OwnershipArgs.size();
1345   llvm::array_pod_sort(start, start + size);
1346 
1347   D->addAttr(::new (S.Context)
1348              OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1349                            AL.getAttributeSpellingListIndex()));
1350 }
1351 
1352 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1353   // Check the attribute arguments.
1354   if (Attr.getNumArgs() > 1) {
1355     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1356       << Attr.getName() << 1;
1357     return;
1358   }
1359 
1360   NamedDecl *nd = cast<NamedDecl>(D);
1361 
1362   // gcc rejects
1363   // class c {
1364   //   static int a __attribute__((weakref ("v2")));
1365   //   static int b() __attribute__((weakref ("f3")));
1366   // };
1367   // and ignores the attributes of
1368   // void f(void) {
1369   //   static int a __attribute__((weakref ("v2")));
1370   // }
1371   // we reject them
1372   const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1373   if (!Ctx->isFileContext()) {
1374     S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1375       << nd;
1376     return;
1377   }
1378 
1379   // The GCC manual says
1380   //
1381   // At present, a declaration to which `weakref' is attached can only
1382   // be `static'.
1383   //
1384   // It also says
1385   //
1386   // Without a TARGET,
1387   // given as an argument to `weakref' or to `alias', `weakref' is
1388   // equivalent to `weak'.
1389   //
1390   // gcc 4.4.1 will accept
1391   // int a7 __attribute__((weakref));
1392   // as
1393   // int a7 __attribute__((weak));
1394   // This looks like a bug in gcc. We reject that for now. We should revisit
1395   // it if this behaviour is actually used.
1396 
1397   // GCC rejects
1398   // static ((alias ("y"), weakref)).
1399   // Should we? How to check that weakref is before or after alias?
1400 
1401   // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1402   // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1403   // StringRef parameter it was given anyway.
1404   StringRef Str;
1405   if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1406     // GCC will accept anything as the argument of weakref. Should we
1407     // check for an existing decl?
1408     D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1409                                         Attr.getAttributeSpellingListIndex()));
1410 
1411   D->addAttr(::new (S.Context)
1412              WeakRefAttr(Attr.getRange(), S.Context,
1413                          Attr.getAttributeSpellingListIndex()));
1414 }
1415 
1416 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1417   StringRef Str;
1418   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1419     return;
1420 
1421   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1422     S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1423     return;
1424   }
1425 
1426   // FIXME: check if target symbol exists in current file
1427 
1428   D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1429                                          Attr.getAttributeSpellingListIndex()));
1430 }
1431 
1432 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1433   if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1434     return;
1435 
1436   D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1437                                         Attr.getAttributeSpellingListIndex()));
1438 }
1439 
1440 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1441   if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1442     return;
1443 
1444   D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1445                                        Attr.getAttributeSpellingListIndex()));
1446 }
1447 
1448 static void handleTLSModelAttr(Sema &S, Decl *D,
1449                                const AttributeList &Attr) {
1450   StringRef Model;
1451   SourceLocation LiteralLoc;
1452   // Check that it is a string.
1453   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1454     return;
1455 
1456   // Check that the value.
1457   if (Model != "global-dynamic" && Model != "local-dynamic"
1458       && Model != "initial-exec" && Model != "local-exec") {
1459     S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1460     return;
1461   }
1462 
1463   D->addAttr(::new (S.Context)
1464              TLSModelAttr(Attr.getRange(), S.Context, Model,
1465                           Attr.getAttributeSpellingListIndex()));
1466 }
1467 
1468 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1469   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1470     QualType RetTy = FD->getReturnType();
1471     if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1472       D->addAttr(::new (S.Context)
1473                  MallocAttr(Attr.getRange(), S.Context,
1474                             Attr.getAttributeSpellingListIndex()));
1475       return;
1476     }
1477   }
1478 
1479   S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1480 }
1481 
1482 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1483   if (S.LangOpts.CPlusPlus) {
1484     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1485       << Attr.getName() << AttributeLangSupport::Cpp;
1486     return;
1487   }
1488 
1489   D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1490                                         Attr.getAttributeSpellingListIndex()));
1491 }
1492 
1493 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1494   if (hasDeclarator(D)) return;
1495 
1496   if (S.CheckNoReturnAttr(attr)) return;
1497 
1498   if (!isa<ObjCMethodDecl>(D)) {
1499     S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1500       << attr.getName() << ExpectedFunctionOrMethod;
1501     return;
1502   }
1503 
1504   D->addAttr(::new (S.Context)
1505              NoReturnAttr(attr.getRange(), S.Context,
1506                           attr.getAttributeSpellingListIndex()));
1507 }
1508 
1509 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1510   if (!checkAttributeNumArgs(*this, attr, 0)) {
1511     attr.setInvalid();
1512     return true;
1513   }
1514 
1515   return false;
1516 }
1517 
1518 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1519                                        const AttributeList &Attr) {
1520 
1521   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1522   // because 'analyzer_noreturn' does not impact the type.
1523   if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1524     ValueDecl *VD = dyn_cast<ValueDecl>(D);
1525     if (!VD || (!VD->getType()->isBlockPointerType() &&
1526                 !VD->getType()->isFunctionPointerType())) {
1527       S.Diag(Attr.getLoc(),
1528              Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1529              : diag::warn_attribute_wrong_decl_type)
1530         << Attr.getName() << ExpectedFunctionMethodOrBlock;
1531       return;
1532     }
1533   }
1534 
1535   D->addAttr(::new (S.Context)
1536              AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1537                                   Attr.getAttributeSpellingListIndex()));
1538 }
1539 
1540 // PS3 PPU-specific.
1541 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1542 /*
1543   Returning a Vector Class in Registers
1544 
1545   According to the PPU ABI specifications, a class with a single member of
1546   vector type is returned in memory when used as the return value of a function.
1547   This results in inefficient code when implementing vector classes. To return
1548   the value in a single vector register, add the vecreturn attribute to the
1549   class definition. This attribute is also applicable to struct types.
1550 
1551   Example:
1552 
1553   struct Vector
1554   {
1555     __vector float xyzw;
1556   } __attribute__((vecreturn));
1557 
1558   Vector Add(Vector lhs, Vector rhs)
1559   {
1560     Vector result;
1561     result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1562     return result; // This will be returned in a register
1563   }
1564 */
1565   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1566     S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1567     return;
1568   }
1569 
1570   RecordDecl *record = cast<RecordDecl>(D);
1571   int count = 0;
1572 
1573   if (!isa<CXXRecordDecl>(record)) {
1574     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1575     return;
1576   }
1577 
1578   if (!cast<CXXRecordDecl>(record)->isPOD()) {
1579     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1580     return;
1581   }
1582 
1583   for (const auto *I : record->fields()) {
1584     if ((count == 1) || !I->getType()->isVectorType()) {
1585       S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1586       return;
1587     }
1588     count++;
1589   }
1590 
1591   D->addAttr(::new (S.Context)
1592              VecReturnAttr(Attr.getRange(), S.Context,
1593                            Attr.getAttributeSpellingListIndex()));
1594 }
1595 
1596 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1597                                  const AttributeList &Attr) {
1598   if (isa<ParmVarDecl>(D)) {
1599     // [[carries_dependency]] can only be applied to a parameter if it is a
1600     // parameter of a function declaration or lambda.
1601     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1602       S.Diag(Attr.getLoc(),
1603              diag::err_carries_dependency_param_not_function_decl);
1604       return;
1605     }
1606   }
1607 
1608   D->addAttr(::new (S.Context) CarriesDependencyAttr(
1609                                    Attr.getRange(), S.Context,
1610                                    Attr.getAttributeSpellingListIndex()));
1611 }
1612 
1613 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1614   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1615     if (VD->hasLocalStorage()) {
1616       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1617       return;
1618     }
1619   } else if (!isFunctionOrMethod(D)) {
1620     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1621       << Attr.getName() << ExpectedVariableOrFunction;
1622     return;
1623   }
1624 
1625   D->addAttr(::new (S.Context)
1626              UsedAttr(Attr.getRange(), S.Context,
1627                       Attr.getAttributeSpellingListIndex()));
1628 }
1629 
1630 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1631   uint32_t priority = ConstructorAttr::DefaultPriority;
1632   if (Attr.getNumArgs() &&
1633       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1634     return;
1635 
1636   D->addAttr(::new (S.Context)
1637              ConstructorAttr(Attr.getRange(), S.Context, priority,
1638                              Attr.getAttributeSpellingListIndex()));
1639 }
1640 
1641 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1642   uint32_t priority = DestructorAttr::DefaultPriority;
1643   if (Attr.getNumArgs() &&
1644       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1645     return;
1646 
1647   D->addAttr(::new (S.Context)
1648              DestructorAttr(Attr.getRange(), S.Context, priority,
1649                             Attr.getAttributeSpellingListIndex()));
1650 }
1651 
1652 template <typename AttrTy>
1653 static void handleAttrWithMessage(Sema &S, Decl *D,
1654                                   const AttributeList &Attr) {
1655   // Handle the case where the attribute has a text message.
1656   StringRef Str;
1657   if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1658     return;
1659 
1660   D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1661                                       Attr.getAttributeSpellingListIndex()));
1662 }
1663 
1664 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1665                                           const AttributeList &Attr) {
1666   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1667     S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1668       << Attr.getName() << Attr.getRange();
1669     return;
1670   }
1671 
1672   D->addAttr(::new (S.Context)
1673           ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1674                                        Attr.getAttributeSpellingListIndex()));
1675 }
1676 
1677 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1678                                   IdentifierInfo *Platform,
1679                                   VersionTuple Introduced,
1680                                   VersionTuple Deprecated,
1681                                   VersionTuple Obsoleted) {
1682   StringRef PlatformName
1683     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1684   if (PlatformName.empty())
1685     PlatformName = Platform->getName();
1686 
1687   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1688   // of these steps are needed).
1689   if (!Introduced.empty() && !Deprecated.empty() &&
1690       !(Introduced <= Deprecated)) {
1691     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1692       << 1 << PlatformName << Deprecated.getAsString()
1693       << 0 << Introduced.getAsString();
1694     return true;
1695   }
1696 
1697   if (!Introduced.empty() && !Obsoleted.empty() &&
1698       !(Introduced <= Obsoleted)) {
1699     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1700       << 2 << PlatformName << Obsoleted.getAsString()
1701       << 0 << Introduced.getAsString();
1702     return true;
1703   }
1704 
1705   if (!Deprecated.empty() && !Obsoleted.empty() &&
1706       !(Deprecated <= Obsoleted)) {
1707     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1708       << 2 << PlatformName << Obsoleted.getAsString()
1709       << 1 << Deprecated.getAsString();
1710     return true;
1711   }
1712 
1713   return false;
1714 }
1715 
1716 /// \brief Check whether the two versions match.
1717 ///
1718 /// If either version tuple is empty, then they are assumed to match. If
1719 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1720 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1721                           bool BeforeIsOkay) {
1722   if (X.empty() || Y.empty())
1723     return true;
1724 
1725   if (X == Y)
1726     return true;
1727 
1728   if (BeforeIsOkay && X < Y)
1729     return true;
1730 
1731   return false;
1732 }
1733 
1734 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1735                                               IdentifierInfo *Platform,
1736                                               VersionTuple Introduced,
1737                                               VersionTuple Deprecated,
1738                                               VersionTuple Obsoleted,
1739                                               bool IsUnavailable,
1740                                               StringRef Message,
1741                                               bool Override,
1742                                               unsigned AttrSpellingListIndex) {
1743   VersionTuple MergedIntroduced = Introduced;
1744   VersionTuple MergedDeprecated = Deprecated;
1745   VersionTuple MergedObsoleted = Obsoleted;
1746   bool FoundAny = false;
1747 
1748   if (D->hasAttrs()) {
1749     AttrVec &Attrs = D->getAttrs();
1750     for (unsigned i = 0, e = Attrs.size(); i != e;) {
1751       const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1752       if (!OldAA) {
1753         ++i;
1754         continue;
1755       }
1756 
1757       IdentifierInfo *OldPlatform = OldAA->getPlatform();
1758       if (OldPlatform != Platform) {
1759         ++i;
1760         continue;
1761       }
1762 
1763       FoundAny = true;
1764       VersionTuple OldIntroduced = OldAA->getIntroduced();
1765       VersionTuple OldDeprecated = OldAA->getDeprecated();
1766       VersionTuple OldObsoleted = OldAA->getObsoleted();
1767       bool OldIsUnavailable = OldAA->getUnavailable();
1768 
1769       if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1770           !versionsMatch(Deprecated, OldDeprecated, Override) ||
1771           !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1772           !(OldIsUnavailable == IsUnavailable ||
1773             (Override && !OldIsUnavailable && IsUnavailable))) {
1774         if (Override) {
1775           int Which = -1;
1776           VersionTuple FirstVersion;
1777           VersionTuple SecondVersion;
1778           if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1779             Which = 0;
1780             FirstVersion = OldIntroduced;
1781             SecondVersion = Introduced;
1782           } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1783             Which = 1;
1784             FirstVersion = Deprecated;
1785             SecondVersion = OldDeprecated;
1786           } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1787             Which = 2;
1788             FirstVersion = Obsoleted;
1789             SecondVersion = OldObsoleted;
1790           }
1791 
1792           if (Which == -1) {
1793             Diag(OldAA->getLocation(),
1794                  diag::warn_mismatched_availability_override_unavail)
1795               << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1796           } else {
1797             Diag(OldAA->getLocation(),
1798                  diag::warn_mismatched_availability_override)
1799               << Which
1800               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1801               << FirstVersion.getAsString() << SecondVersion.getAsString();
1802           }
1803           Diag(Range.getBegin(), diag::note_overridden_method);
1804         } else {
1805           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1806           Diag(Range.getBegin(), diag::note_previous_attribute);
1807         }
1808 
1809         Attrs.erase(Attrs.begin() + i);
1810         --e;
1811         continue;
1812       }
1813 
1814       VersionTuple MergedIntroduced2 = MergedIntroduced;
1815       VersionTuple MergedDeprecated2 = MergedDeprecated;
1816       VersionTuple MergedObsoleted2 = MergedObsoleted;
1817 
1818       if (MergedIntroduced2.empty())
1819         MergedIntroduced2 = OldIntroduced;
1820       if (MergedDeprecated2.empty())
1821         MergedDeprecated2 = OldDeprecated;
1822       if (MergedObsoleted2.empty())
1823         MergedObsoleted2 = OldObsoleted;
1824 
1825       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1826                                 MergedIntroduced2, MergedDeprecated2,
1827                                 MergedObsoleted2)) {
1828         Attrs.erase(Attrs.begin() + i);
1829         --e;
1830         continue;
1831       }
1832 
1833       MergedIntroduced = MergedIntroduced2;
1834       MergedDeprecated = MergedDeprecated2;
1835       MergedObsoleted = MergedObsoleted2;
1836       ++i;
1837     }
1838   }
1839 
1840   if (FoundAny &&
1841       MergedIntroduced == Introduced &&
1842       MergedDeprecated == Deprecated &&
1843       MergedObsoleted == Obsoleted)
1844     return nullptr;
1845 
1846   // Only create a new attribute if !Override, but we want to do
1847   // the checking.
1848   if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1849                              MergedDeprecated, MergedObsoleted) &&
1850       !Override) {
1851     return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1852                                             Introduced, Deprecated,
1853                                             Obsoleted, IsUnavailable, Message,
1854                                             AttrSpellingListIndex);
1855   }
1856   return nullptr;
1857 }
1858 
1859 static void handleAvailabilityAttr(Sema &S, Decl *D,
1860                                    const AttributeList &Attr) {
1861   if (!checkAttributeNumArgs(S, Attr, 1))
1862     return;
1863   IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1864   unsigned Index = Attr.getAttributeSpellingListIndex();
1865 
1866   IdentifierInfo *II = Platform->Ident;
1867   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1868     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1869       << Platform->Ident;
1870 
1871   NamedDecl *ND = dyn_cast<NamedDecl>(D);
1872   if (!ND) {
1873     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1874     return;
1875   }
1876 
1877   AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1878   AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1879   AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1880   bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1881   StringRef Str;
1882   if (const StringLiteral *SE =
1883           dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1884     Str = SE->getString();
1885 
1886   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1887                                                       Introduced.Version,
1888                                                       Deprecated.Version,
1889                                                       Obsoleted.Version,
1890                                                       IsUnavailable, Str,
1891                                                       /*Override=*/false,
1892                                                       Index);
1893   if (NewAttr)
1894     D->addAttr(NewAttr);
1895 }
1896 
1897 template <class T>
1898 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1899                               typename T::VisibilityType value,
1900                               unsigned attrSpellingListIndex) {
1901   T *existingAttr = D->getAttr<T>();
1902   if (existingAttr) {
1903     typename T::VisibilityType existingValue = existingAttr->getVisibility();
1904     if (existingValue == value)
1905       return nullptr;
1906     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
1907     S.Diag(range.getBegin(), diag::note_previous_attribute);
1908     D->dropAttr<T>();
1909   }
1910   return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
1911 }
1912 
1913 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
1914                                           VisibilityAttr::VisibilityType Vis,
1915                                           unsigned AttrSpellingListIndex) {
1916   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
1917                                                AttrSpellingListIndex);
1918 }
1919 
1920 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1921                                       TypeVisibilityAttr::VisibilityType Vis,
1922                                       unsigned AttrSpellingListIndex) {
1923   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
1924                                                    AttrSpellingListIndex);
1925 }
1926 
1927 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
1928                                  bool isTypeVisibility) {
1929   // Visibility attributes don't mean anything on a typedef.
1930   if (isa<TypedefNameDecl>(D)) {
1931     S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
1932       << Attr.getName();
1933     return;
1934   }
1935 
1936   // 'type_visibility' can only go on a type or namespace.
1937   if (isTypeVisibility &&
1938       !(isa<TagDecl>(D) ||
1939         isa<ObjCInterfaceDecl>(D) ||
1940         isa<NamespaceDecl>(D))) {
1941     S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
1942       << Attr.getName() << ExpectedTypeOrNamespace;
1943     return;
1944   }
1945 
1946   // Check that the argument is a string literal.
1947   StringRef TypeStr;
1948   SourceLocation LiteralLoc;
1949   if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
1950     return;
1951 
1952   VisibilityAttr::VisibilityType type;
1953   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
1954     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
1955       << Attr.getName() << TypeStr;
1956     return;
1957   }
1958 
1959   // Complain about attempts to use protected visibility on targets
1960   // (like Darwin) that don't support it.
1961   if (type == VisibilityAttr::Protected &&
1962       !S.Context.getTargetInfo().hasProtectedVisibility()) {
1963     S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
1964     type = VisibilityAttr::Default;
1965   }
1966 
1967   unsigned Index = Attr.getAttributeSpellingListIndex();
1968   clang::Attr *newAttr;
1969   if (isTypeVisibility) {
1970     newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
1971                                     (TypeVisibilityAttr::VisibilityType) type,
1972                                         Index);
1973   } else {
1974     newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
1975   }
1976   if (newAttr)
1977     D->addAttr(newAttr);
1978 }
1979 
1980 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
1981                                        const AttributeList &Attr) {
1982   ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
1983   if (!Attr.isArgIdent(0)) {
1984     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
1985       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
1986     return;
1987   }
1988 
1989   IdentifierLoc *IL = Attr.getArgAsIdent(0);
1990   ObjCMethodFamilyAttr::FamilyKind F;
1991   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
1992     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
1993       << IL->Ident;
1994     return;
1995   }
1996 
1997   if (F == ObjCMethodFamilyAttr::OMF_init &&
1998       !method->getReturnType()->isObjCObjectPointerType()) {
1999     S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2000         << method->getReturnType();
2001     // Ignore the attribute.
2002     return;
2003   }
2004 
2005   method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2006                                                        S.Context, F,
2007                                         Attr.getAttributeSpellingListIndex()));
2008 }
2009 
2010 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2011   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2012     QualType T = TD->getUnderlyingType();
2013     if (!T->isCARCBridgableType()) {
2014       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2015       return;
2016     }
2017   }
2018   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2019     QualType T = PD->getType();
2020     if (!T->isCARCBridgableType()) {
2021       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2022       return;
2023     }
2024   }
2025   else {
2026     // It is okay to include this attribute on properties, e.g.:
2027     //
2028     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2029     //
2030     // In this case it follows tradition and suppresses an error in the above
2031     // case.
2032     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2033   }
2034   D->addAttr(::new (S.Context)
2035              ObjCNSObjectAttr(Attr.getRange(), S.Context,
2036                               Attr.getAttributeSpellingListIndex()));
2037 }
2038 
2039 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2040   if (!Attr.isArgIdent(0)) {
2041     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2042       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2043     return;
2044   }
2045 
2046   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2047   BlocksAttr::BlockType type;
2048   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2049     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2050       << Attr.getName() << II;
2051     return;
2052   }
2053 
2054   D->addAttr(::new (S.Context)
2055              BlocksAttr(Attr.getRange(), S.Context, type,
2056                         Attr.getAttributeSpellingListIndex()));
2057 }
2058 
2059 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2060   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2061   if (Attr.getNumArgs() > 0) {
2062     Expr *E = Attr.getArgAsExpr(0);
2063     llvm::APSInt Idx(32);
2064     if (E->isTypeDependent() || E->isValueDependent() ||
2065         !E->isIntegerConstantExpr(Idx, S.Context)) {
2066       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2067         << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2068         << E->getSourceRange();
2069       return;
2070     }
2071 
2072     if (Idx.isSigned() && Idx.isNegative()) {
2073       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2074         << E->getSourceRange();
2075       return;
2076     }
2077 
2078     sentinel = Idx.getZExtValue();
2079   }
2080 
2081   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2082   if (Attr.getNumArgs() > 1) {
2083     Expr *E = Attr.getArgAsExpr(1);
2084     llvm::APSInt Idx(32);
2085     if (E->isTypeDependent() || E->isValueDependent() ||
2086         !E->isIntegerConstantExpr(Idx, S.Context)) {
2087       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2088         << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2089         << E->getSourceRange();
2090       return;
2091     }
2092     nullPos = Idx.getZExtValue();
2093 
2094     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2095       // FIXME: This error message could be improved, it would be nice
2096       // to say what the bounds actually are.
2097       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2098         << E->getSourceRange();
2099       return;
2100     }
2101   }
2102 
2103   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2104     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2105     if (isa<FunctionNoProtoType>(FT)) {
2106       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2107       return;
2108     }
2109 
2110     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2111       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2112       return;
2113     }
2114   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2115     if (!MD->isVariadic()) {
2116       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2117       return;
2118     }
2119   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2120     if (!BD->isVariadic()) {
2121       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2122       return;
2123     }
2124   } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2125     QualType Ty = V->getType();
2126     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2127       const FunctionType *FT = Ty->isFunctionPointerType()
2128        ? D->getFunctionType()
2129        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2130       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2131         int m = Ty->isFunctionPointerType() ? 0 : 1;
2132         S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2133         return;
2134       }
2135     } else {
2136       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2137         << Attr.getName() << ExpectedFunctionMethodOrBlock;
2138       return;
2139     }
2140   } else {
2141     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2142       << Attr.getName() << ExpectedFunctionMethodOrBlock;
2143     return;
2144   }
2145   D->addAttr(::new (S.Context)
2146              SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2147                           Attr.getAttributeSpellingListIndex()));
2148 }
2149 
2150 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2151   if (D->getFunctionType() &&
2152       D->getFunctionType()->getReturnType()->isVoidType()) {
2153     S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2154       << Attr.getName() << 0;
2155     return;
2156   }
2157   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2158     if (MD->getReturnType()->isVoidType()) {
2159       S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2160       << Attr.getName() << 1;
2161       return;
2162     }
2163 
2164   D->addAttr(::new (S.Context)
2165              WarnUnusedResultAttr(Attr.getRange(), S.Context,
2166                                   Attr.getAttributeSpellingListIndex()));
2167 }
2168 
2169 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2170   // weak_import only applies to variable & function declarations.
2171   bool isDef = false;
2172   if (!D->canBeWeakImported(isDef)) {
2173     if (isDef)
2174       S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2175         << "weak_import";
2176     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2177              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2178               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2179       // Nothing to warn about here.
2180     } else
2181       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2182         << Attr.getName() << ExpectedVariableOrFunction;
2183 
2184     return;
2185   }
2186 
2187   D->addAttr(::new (S.Context)
2188              WeakImportAttr(Attr.getRange(), S.Context,
2189                             Attr.getAttributeSpellingListIndex()));
2190 }
2191 
2192 // Handles reqd_work_group_size and work_group_size_hint.
2193 template <typename WorkGroupAttr>
2194 static void handleWorkGroupSize(Sema &S, Decl *D,
2195                                 const AttributeList &Attr) {
2196   uint32_t WGSize[3];
2197   for (unsigned i = 0; i < 3; ++i) {
2198     const Expr *E = Attr.getArgAsExpr(i);
2199     if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2200       return;
2201     if (WGSize[i] == 0) {
2202       S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2203         << Attr.getName() << E->getSourceRange();
2204       return;
2205     }
2206   }
2207 
2208   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2209   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2210                     Existing->getYDim() == WGSize[1] &&
2211                     Existing->getZDim() == WGSize[2]))
2212     S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2213 
2214   D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2215                                              WGSize[0], WGSize[1], WGSize[2],
2216                                        Attr.getAttributeSpellingListIndex()));
2217 }
2218 
2219 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2220   if (!Attr.hasParsedType()) {
2221     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2222       << Attr.getName() << 1;
2223     return;
2224   }
2225 
2226   TypeSourceInfo *ParmTSI = nullptr;
2227   QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2228   assert(ParmTSI && "no type source info for attribute argument");
2229 
2230   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2231       (ParmType->isBooleanType() ||
2232        !ParmType->isIntegralType(S.getASTContext()))) {
2233     S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2234         << ParmType;
2235     return;
2236   }
2237 
2238   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2239     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2240       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2241       return;
2242     }
2243   }
2244 
2245   D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2246                                                ParmTSI,
2247                                         Attr.getAttributeSpellingListIndex()));
2248 }
2249 
2250 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2251                                     StringRef Name,
2252                                     unsigned AttrSpellingListIndex) {
2253   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2254     if (ExistingAttr->getName() == Name)
2255       return nullptr;
2256     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2257     Diag(Range.getBegin(), diag::note_previous_attribute);
2258     return nullptr;
2259   }
2260   return ::new (Context) SectionAttr(Range, Context, Name,
2261                                      AttrSpellingListIndex);
2262 }
2263 
2264 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2265   // Make sure that there is a string literal as the sections's single
2266   // argument.
2267   StringRef Str;
2268   SourceLocation LiteralLoc;
2269   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2270     return;
2271 
2272   // If the target wants to validate the section specifier, make it happen.
2273   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2274   if (!Error.empty()) {
2275     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2276     << Error;
2277     return;
2278   }
2279 
2280   unsigned Index = Attr.getAttributeSpellingListIndex();
2281   SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2282   if (NewAttr)
2283     D->addAttr(NewAttr);
2284 }
2285 
2286 
2287 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2288   VarDecl *VD = cast<VarDecl>(D);
2289   if (!VD->hasLocalStorage()) {
2290     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2291     return;
2292   }
2293 
2294   Expr *E = Attr.getArgAsExpr(0);
2295   SourceLocation Loc = E->getExprLoc();
2296   FunctionDecl *FD = nullptr;
2297   DeclarationNameInfo NI;
2298 
2299   // gcc only allows for simple identifiers. Since we support more than gcc, we
2300   // will warn the user.
2301   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2302     if (DRE->hasQualifier())
2303       S.Diag(Loc, diag::warn_cleanup_ext);
2304     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2305     NI = DRE->getNameInfo();
2306     if (!FD) {
2307       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2308         << NI.getName();
2309       return;
2310     }
2311   } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2312     if (ULE->hasExplicitTemplateArgs())
2313       S.Diag(Loc, diag::warn_cleanup_ext);
2314     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2315     NI = ULE->getNameInfo();
2316     if (!FD) {
2317       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2318         << NI.getName();
2319       if (ULE->getType() == S.Context.OverloadTy)
2320         S.NoteAllOverloadCandidates(ULE);
2321       return;
2322     }
2323   } else {
2324     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2325     return;
2326   }
2327 
2328   if (FD->getNumParams() != 1) {
2329     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2330       << NI.getName();
2331     return;
2332   }
2333 
2334   // We're currently more strict than GCC about what function types we accept.
2335   // If this ever proves to be a problem it should be easy to fix.
2336   QualType Ty = S.Context.getPointerType(VD->getType());
2337   QualType ParamTy = FD->getParamDecl(0)->getType();
2338   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2339                                    ParamTy, Ty) != Sema::Compatible) {
2340     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2341       << NI.getName() << ParamTy << Ty;
2342     return;
2343   }
2344 
2345   D->addAttr(::new (S.Context)
2346              CleanupAttr(Attr.getRange(), S.Context, FD,
2347                          Attr.getAttributeSpellingListIndex()));
2348 }
2349 
2350 /// Handle __attribute__((format_arg((idx)))) attribute based on
2351 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2352 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2353   Expr *IdxExpr = Attr.getArgAsExpr(0);
2354   uint64_t Idx;
2355   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2356     return;
2357 
2358   // make sure the format string is really a string
2359   QualType Ty = getFunctionOrMethodParamType(D, Idx);
2360 
2361   bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2362   if (not_nsstring_type &&
2363       !isCFStringType(Ty, S.Context) &&
2364       (!Ty->isPointerType() ||
2365        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2366     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2367         << (not_nsstring_type ? "a string type" : "an NSString")
2368         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2369     return;
2370   }
2371   Ty = getFunctionOrMethodResultType(D);
2372   if (!isNSStringType(Ty, S.Context) &&
2373       !isCFStringType(Ty, S.Context) &&
2374       (!Ty->isPointerType() ||
2375        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2376     S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2377         << (not_nsstring_type ? "string type" : "NSString")
2378         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2379     return;
2380   }
2381 
2382   // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2383   // because that has corrected for the implicit this parameter, and is zero-
2384   // based.  The attribute expects what the user wrote explicitly.
2385   llvm::APSInt Val;
2386   IdxExpr->EvaluateAsInt(Val, S.Context);
2387 
2388   D->addAttr(::new (S.Context)
2389              FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2390                            Attr.getAttributeSpellingListIndex()));
2391 }
2392 
2393 enum FormatAttrKind {
2394   CFStringFormat,
2395   NSStringFormat,
2396   StrftimeFormat,
2397   SupportedFormat,
2398   IgnoredFormat,
2399   InvalidFormat
2400 };
2401 
2402 /// getFormatAttrKind - Map from format attribute names to supported format
2403 /// types.
2404 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2405   return llvm::StringSwitch<FormatAttrKind>(Format)
2406     // Check for formats that get handled specially.
2407     .Case("NSString", NSStringFormat)
2408     .Case("CFString", CFStringFormat)
2409     .Case("strftime", StrftimeFormat)
2410 
2411     // Otherwise, check for supported formats.
2412     .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2413     .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2414     .Case("kprintf", SupportedFormat) // OpenBSD.
2415 
2416     .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2417     .Default(InvalidFormat);
2418 }
2419 
2420 /// Handle __attribute__((init_priority(priority))) attributes based on
2421 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2422 static void handleInitPriorityAttr(Sema &S, Decl *D,
2423                                    const AttributeList &Attr) {
2424   if (!S.getLangOpts().CPlusPlus) {
2425     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2426     return;
2427   }
2428 
2429   if (S.getCurFunctionOrMethodDecl()) {
2430     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2431     Attr.setInvalid();
2432     return;
2433   }
2434   QualType T = cast<VarDecl>(D)->getType();
2435   if (S.Context.getAsArrayType(T))
2436     T = S.Context.getBaseElementType(T);
2437   if (!T->getAs<RecordType>()) {
2438     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2439     Attr.setInvalid();
2440     return;
2441   }
2442 
2443   Expr *E = Attr.getArgAsExpr(0);
2444   uint32_t prioritynum;
2445   if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2446     Attr.setInvalid();
2447     return;
2448   }
2449 
2450   if (prioritynum < 101 || prioritynum > 65535) {
2451     S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2452       << E->getSourceRange();
2453     Attr.setInvalid();
2454     return;
2455   }
2456   D->addAttr(::new (S.Context)
2457              InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2458                               Attr.getAttributeSpellingListIndex()));
2459 }
2460 
2461 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2462                                   IdentifierInfo *Format, int FormatIdx,
2463                                   int FirstArg,
2464                                   unsigned AttrSpellingListIndex) {
2465   // Check whether we already have an equivalent format attribute.
2466   for (auto *F : D->specific_attrs<FormatAttr>()) {
2467     if (F->getType() == Format &&
2468         F->getFormatIdx() == FormatIdx &&
2469         F->getFirstArg() == FirstArg) {
2470       // If we don't have a valid location for this attribute, adopt the
2471       // location.
2472       if (F->getLocation().isInvalid())
2473         F->setRange(Range);
2474       return nullptr;
2475     }
2476   }
2477 
2478   return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2479                                     FirstArg, AttrSpellingListIndex);
2480 }
2481 
2482 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2483 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2484 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2485   if (!Attr.isArgIdent(0)) {
2486     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2487       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2488     return;
2489   }
2490 
2491   // In C++ the implicit 'this' function parameter also counts, and they are
2492   // counted from one.
2493   bool HasImplicitThisParam = isInstanceMethod(D);
2494   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2495 
2496   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2497   StringRef Format = II->getName();
2498 
2499   // Normalize the argument, __foo__ becomes foo.
2500   if (Format.startswith("__") && Format.endswith("__")) {
2501     Format = Format.substr(2, Format.size() - 4);
2502     // If we've modified the string name, we need a new identifier for it.
2503     II = &S.Context.Idents.get(Format);
2504   }
2505 
2506   // Check for supported formats.
2507   FormatAttrKind Kind = getFormatAttrKind(Format);
2508 
2509   if (Kind == IgnoredFormat)
2510     return;
2511 
2512   if (Kind == InvalidFormat) {
2513     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2514       << Attr.getName() << II->getName();
2515     return;
2516   }
2517 
2518   // checks for the 2nd argument
2519   Expr *IdxExpr = Attr.getArgAsExpr(1);
2520   uint32_t Idx;
2521   if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2522     return;
2523 
2524   if (Idx < 1 || Idx > NumArgs) {
2525     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2526       << Attr.getName() << 2 << IdxExpr->getSourceRange();
2527     return;
2528   }
2529 
2530   // FIXME: Do we need to bounds check?
2531   unsigned ArgIdx = Idx - 1;
2532 
2533   if (HasImplicitThisParam) {
2534     if (ArgIdx == 0) {
2535       S.Diag(Attr.getLoc(),
2536              diag::err_format_attribute_implicit_this_format_string)
2537         << IdxExpr->getSourceRange();
2538       return;
2539     }
2540     ArgIdx--;
2541   }
2542 
2543   // make sure the format string is really a string
2544   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2545 
2546   if (Kind == CFStringFormat) {
2547     if (!isCFStringType(Ty, S.Context)) {
2548       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2549         << "a CFString" << IdxExpr->getSourceRange()
2550         << getFunctionOrMethodParamRange(D, ArgIdx);
2551       return;
2552     }
2553   } else if (Kind == NSStringFormat) {
2554     // FIXME: do we need to check if the type is NSString*?  What are the
2555     // semantics?
2556     if (!isNSStringType(Ty, S.Context)) {
2557       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2558         << "an NSString" << IdxExpr->getSourceRange()
2559         << getFunctionOrMethodParamRange(D, ArgIdx);
2560       return;
2561     }
2562   } else if (!Ty->isPointerType() ||
2563              !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2564     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2565       << "a string type" << IdxExpr->getSourceRange()
2566       << getFunctionOrMethodParamRange(D, ArgIdx);
2567     return;
2568   }
2569 
2570   // check the 3rd argument
2571   Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2572   uint32_t FirstArg;
2573   if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2574     return;
2575 
2576   // check if the function is variadic if the 3rd argument non-zero
2577   if (FirstArg != 0) {
2578     if (isFunctionOrMethodVariadic(D)) {
2579       ++NumArgs; // +1 for ...
2580     } else {
2581       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2582       return;
2583     }
2584   }
2585 
2586   // strftime requires FirstArg to be 0 because it doesn't read from any
2587   // variable the input is just the current time + the format string.
2588   if (Kind == StrftimeFormat) {
2589     if (FirstArg != 0) {
2590       S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2591         << FirstArgExpr->getSourceRange();
2592       return;
2593     }
2594   // if 0 it disables parameter checking (to use with e.g. va_list)
2595   } else if (FirstArg != 0 && FirstArg != NumArgs) {
2596     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2597       << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2598     return;
2599   }
2600 
2601   FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2602                                           Idx, FirstArg,
2603                                           Attr.getAttributeSpellingListIndex());
2604   if (NewAttr)
2605     D->addAttr(NewAttr);
2606 }
2607 
2608 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2609                                        const AttributeList &Attr) {
2610   // Try to find the underlying union declaration.
2611   RecordDecl *RD = nullptr;
2612   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2613   if (TD && TD->getUnderlyingType()->isUnionType())
2614     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2615   else
2616     RD = dyn_cast<RecordDecl>(D);
2617 
2618   if (!RD || !RD->isUnion()) {
2619     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2620       << Attr.getName() << ExpectedUnion;
2621     return;
2622   }
2623 
2624   if (!RD->isCompleteDefinition()) {
2625     S.Diag(Attr.getLoc(),
2626         diag::warn_transparent_union_attribute_not_definition);
2627     return;
2628   }
2629 
2630   RecordDecl::field_iterator Field = RD->field_begin(),
2631                           FieldEnd = RD->field_end();
2632   if (Field == FieldEnd) {
2633     S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2634     return;
2635   }
2636 
2637   FieldDecl *FirstField = *Field;
2638   QualType FirstType = FirstField->getType();
2639   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2640     S.Diag(FirstField->getLocation(),
2641            diag::warn_transparent_union_attribute_floating)
2642       << FirstType->isVectorType() << FirstType;
2643     return;
2644   }
2645 
2646   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2647   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2648   for (; Field != FieldEnd; ++Field) {
2649     QualType FieldType = Field->getType();
2650     // FIXME: this isn't fully correct; we also need to test whether the
2651     // members of the union would all have the same calling convention as the
2652     // first member of the union. Checking just the size and alignment isn't
2653     // sufficient (consider structs passed on the stack instead of in registers
2654     // as an example).
2655     if (S.Context.getTypeSize(FieldType) != FirstSize ||
2656         S.Context.getTypeAlign(FieldType) > FirstAlign) {
2657       // Warn if we drop the attribute.
2658       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2659       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2660                                  : S.Context.getTypeAlign(FieldType);
2661       S.Diag(Field->getLocation(),
2662           diag::warn_transparent_union_attribute_field_size_align)
2663         << isSize << Field->getDeclName() << FieldBits;
2664       unsigned FirstBits = isSize? FirstSize : FirstAlign;
2665       S.Diag(FirstField->getLocation(),
2666              diag::note_transparent_union_first_field_size_align)
2667         << isSize << FirstBits;
2668       return;
2669     }
2670   }
2671 
2672   RD->addAttr(::new (S.Context)
2673               TransparentUnionAttr(Attr.getRange(), S.Context,
2674                                    Attr.getAttributeSpellingListIndex()));
2675 }
2676 
2677 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2678   // Make sure that there is a string literal as the annotation's single
2679   // argument.
2680   StringRef Str;
2681   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2682     return;
2683 
2684   // Don't duplicate annotations that are already set.
2685   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2686     if (I->getAnnotation() == Str)
2687       return;
2688   }
2689 
2690   D->addAttr(::new (S.Context)
2691              AnnotateAttr(Attr.getRange(), S.Context, Str,
2692                           Attr.getAttributeSpellingListIndex()));
2693 }
2694 
2695 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2696   // check the attribute arguments.
2697   if (Attr.getNumArgs() > 1) {
2698     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2699       << Attr.getName() << 1;
2700     return;
2701   }
2702 
2703   if (Attr.getNumArgs() == 0) {
2704     D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2705                true, nullptr, Attr.getAttributeSpellingListIndex()));
2706     return;
2707   }
2708 
2709   Expr *E = Attr.getArgAsExpr(0);
2710   if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2711     S.Diag(Attr.getEllipsisLoc(),
2712            diag::err_pack_expansion_without_parameter_packs);
2713     return;
2714   }
2715 
2716   if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2717     return;
2718 
2719   S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2720                    Attr.isPackExpansion());
2721 }
2722 
2723 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2724                           unsigned SpellingListIndex, bool IsPackExpansion) {
2725   AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2726   SourceLocation AttrLoc = AttrRange.getBegin();
2727 
2728   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2729   if (TmpAttr.isAlignas()) {
2730     // C++11 [dcl.align]p1:
2731     //   An alignment-specifier may be applied to a variable or to a class
2732     //   data member, but it shall not be applied to a bit-field, a function
2733     //   parameter, the formal parameter of a catch clause, or a variable
2734     //   declared with the register storage class specifier. An
2735     //   alignment-specifier may also be applied to the declaration of a class
2736     //   or enumeration type.
2737     // C11 6.7.5/2:
2738     //   An alignment attribute shall not be specified in a declaration of
2739     //   a typedef, or a bit-field, or a function, or a parameter, or an
2740     //   object declared with the register storage-class specifier.
2741     int DiagKind = -1;
2742     if (isa<ParmVarDecl>(D)) {
2743       DiagKind = 0;
2744     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2745       if (VD->getStorageClass() == SC_Register)
2746         DiagKind = 1;
2747       if (VD->isExceptionVariable())
2748         DiagKind = 2;
2749     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2750       if (FD->isBitField())
2751         DiagKind = 3;
2752     } else if (!isa<TagDecl>(D)) {
2753       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2754         << (TmpAttr.isC11() ? ExpectedVariableOrField
2755                             : ExpectedVariableFieldOrTag);
2756       return;
2757     }
2758     if (DiagKind != -1) {
2759       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2760         << &TmpAttr << DiagKind;
2761       return;
2762     }
2763   }
2764 
2765   if (E->isTypeDependent() || E->isValueDependent()) {
2766     // Save dependent expressions in the AST to be instantiated.
2767     AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2768     AA->setPackExpansion(IsPackExpansion);
2769     D->addAttr(AA);
2770     return;
2771   }
2772 
2773   // FIXME: Cache the number on the Attr object?
2774   llvm::APSInt Alignment(32);
2775   ExprResult ICE
2776     = VerifyIntegerConstantExpression(E, &Alignment,
2777         diag::err_aligned_attribute_argument_not_int,
2778         /*AllowFold*/ false);
2779   if (ICE.isInvalid())
2780     return;
2781 
2782   // C++11 [dcl.align]p2:
2783   //   -- if the constant expression evaluates to zero, the alignment
2784   //      specifier shall have no effect
2785   // C11 6.7.5p6:
2786   //   An alignment specification of zero has no effect.
2787   if (!(TmpAttr.isAlignas() && !Alignment) &&
2788       !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2789     Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
2790       << E->getSourceRange();
2791     return;
2792   }
2793 
2794   // Alignment calculations can wrap around if it's greater than 2**28.
2795   unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
2796   if (Alignment.getZExtValue() > MaxValidAlignment) {
2797     Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
2798                                                          << E->getSourceRange();
2799     return;
2800   }
2801 
2802   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
2803                                                 ICE.get(), SpellingListIndex);
2804   AA->setPackExpansion(IsPackExpansion);
2805   D->addAttr(AA);
2806 }
2807 
2808 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
2809                           unsigned SpellingListIndex, bool IsPackExpansion) {
2810   // FIXME: Cache the number on the Attr object if non-dependent?
2811   // FIXME: Perform checking of type validity
2812   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
2813                                                 SpellingListIndex);
2814   AA->setPackExpansion(IsPackExpansion);
2815   D->addAttr(AA);
2816 }
2817 
2818 void Sema::CheckAlignasUnderalignment(Decl *D) {
2819   assert(D->hasAttrs() && "no attributes on decl");
2820 
2821   QualType Ty;
2822   if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2823     Ty = VD->getType();
2824   else
2825     Ty = Context.getTagDeclType(cast<TagDecl>(D));
2826   if (Ty->isDependentType() || Ty->isIncompleteType())
2827     return;
2828 
2829   // C++11 [dcl.align]p5, C11 6.7.5/4:
2830   //   The combined effect of all alignment attributes in a declaration shall
2831   //   not specify an alignment that is less strict than the alignment that
2832   //   would otherwise be required for the entity being declared.
2833   AlignedAttr *AlignasAttr = nullptr;
2834   unsigned Align = 0;
2835   for (auto *I : D->specific_attrs<AlignedAttr>()) {
2836     if (I->isAlignmentDependent())
2837       return;
2838     if (I->isAlignas())
2839       AlignasAttr = I;
2840     Align = std::max(Align, I->getAlignment(Context));
2841   }
2842 
2843   if (AlignasAttr && Align) {
2844     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
2845     CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
2846     if (NaturalAlign > RequestedAlign)
2847       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
2848         << Ty << (unsigned)NaturalAlign.getQuantity();
2849   }
2850 }
2851 
2852 bool Sema::checkMSInheritanceAttrOnDefinition(
2853     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2854     MSInheritanceAttr::Spelling SemanticSpelling) {
2855   assert(RD->hasDefinition() && "RD has no definition!");
2856 
2857   // We may not have seen base specifiers or any virtual methods yet.  We will
2858   // have to wait until the record is defined to catch any mismatches.
2859   if (!RD->getDefinition()->isCompleteDefinition())
2860     return false;
2861 
2862   // The unspecified model never matches what a definition could need.
2863   if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
2864     return false;
2865 
2866   if (BestCase) {
2867     if (RD->calculateInheritanceModel() == SemanticSpelling)
2868       return false;
2869   } else {
2870     if (RD->calculateInheritanceModel() <= SemanticSpelling)
2871       return false;
2872   }
2873 
2874   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
2875       << 0 /*definition*/;
2876   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
2877       << RD->getNameAsString();
2878   return true;
2879 }
2880 
2881 /// handleModeAttr - This attribute modifies the width of a decl with primitive
2882 /// type.
2883 ///
2884 /// Despite what would be logical, the mode attribute is a decl attribute, not a
2885 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
2886 /// HImode, not an intermediate pointer.
2887 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2888   // This attribute isn't documented, but glibc uses it.  It changes
2889   // the width of an int or unsigned int to the specified size.
2890   if (!Attr.isArgIdent(0)) {
2891     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
2892       << AANT_ArgumentIdentifier;
2893     return;
2894   }
2895 
2896   IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
2897   StringRef Str = Name->getName();
2898 
2899   // Normalize the attribute name, __foo__ becomes foo.
2900   if (Str.startswith("__") && Str.endswith("__"))
2901     Str = Str.substr(2, Str.size() - 4);
2902 
2903   unsigned DestWidth = 0;
2904   bool IntegerMode = true;
2905   bool ComplexMode = false;
2906   switch (Str.size()) {
2907   case 2:
2908     switch (Str[0]) {
2909     case 'Q': DestWidth = 8; break;
2910     case 'H': DestWidth = 16; break;
2911     case 'S': DestWidth = 32; break;
2912     case 'D': DestWidth = 64; break;
2913     case 'X': DestWidth = 96; break;
2914     case 'T': DestWidth = 128; break;
2915     }
2916     if (Str[1] == 'F') {
2917       IntegerMode = false;
2918     } else if (Str[1] == 'C') {
2919       IntegerMode = false;
2920       ComplexMode = true;
2921     } else if (Str[1] != 'I') {
2922       DestWidth = 0;
2923     }
2924     break;
2925   case 4:
2926     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
2927     // pointer on PIC16 and other embedded platforms.
2928     if (Str == "word")
2929       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2930     else if (Str == "byte")
2931       DestWidth = S.Context.getTargetInfo().getCharWidth();
2932     break;
2933   case 7:
2934     if (Str == "pointer")
2935       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2936     break;
2937   case 11:
2938     if (Str == "unwind_word")
2939       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
2940     break;
2941   }
2942 
2943   QualType OldTy;
2944   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2945     OldTy = TD->getUnderlyingType();
2946   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2947     OldTy = VD->getType();
2948   else {
2949     S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
2950       << Attr.getName() << Attr.getRange();
2951     return;
2952   }
2953 
2954   if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
2955     S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
2956   else if (IntegerMode) {
2957     if (!OldTy->isIntegralOrEnumerationType())
2958       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2959   } else if (ComplexMode) {
2960     if (!OldTy->isComplexType())
2961       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2962   } else {
2963     if (!OldTy->isFloatingType())
2964       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2965   }
2966 
2967   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
2968   // and friends, at least with glibc.
2969   // FIXME: Make sure floating-point mappings are accurate
2970   // FIXME: Support XF and TF types
2971   if (!DestWidth) {
2972     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
2973     return;
2974   }
2975 
2976   QualType NewTy;
2977 
2978   if (IntegerMode)
2979     NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
2980                                             OldTy->isSignedIntegerType());
2981   else
2982     NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
2983 
2984   if (NewTy.isNull()) {
2985     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
2986     return;
2987   }
2988 
2989   if (ComplexMode) {
2990     NewTy = S.Context.getComplexType(NewTy);
2991   }
2992 
2993   // Install the new type.
2994   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2995     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
2996   else
2997     cast<ValueDecl>(D)->setType(NewTy);
2998 
2999   D->addAttr(::new (S.Context)
3000              ModeAttr(Attr.getRange(), S.Context, Name,
3001                       Attr.getAttributeSpellingListIndex()));
3002 }
3003 
3004 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3005   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3006     if (!VD->hasGlobalStorage())
3007       S.Diag(Attr.getLoc(),
3008              diag::warn_attribute_requires_functions_or_static_globals)
3009         << Attr.getName();
3010   } else if (!isFunctionOrMethod(D)) {
3011     S.Diag(Attr.getLoc(),
3012            diag::warn_attribute_requires_functions_or_static_globals)
3013       << Attr.getName();
3014     return;
3015   }
3016 
3017   D->addAttr(::new (S.Context)
3018              NoDebugAttr(Attr.getRange(), S.Context,
3019                          Attr.getAttributeSpellingListIndex()));
3020 }
3021 
3022 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3023                                    const AttributeList &Attr) {
3024   if (checkAttrMutualExclusion<OptimizeNoneAttr>(S, D, Attr))
3025     return;
3026 
3027   D->addAttr(::new (S.Context)
3028              AlwaysInlineAttr(Attr.getRange(), S.Context,
3029                               Attr.getAttributeSpellingListIndex()));
3030 }
3031 
3032 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3033                                    const AttributeList &Attr) {
3034   if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr))
3035     return;
3036 
3037   D->addAttr(::new (S.Context)
3038              OptimizeNoneAttr(Attr.getRange(), S.Context,
3039                               Attr.getAttributeSpellingListIndex()));
3040 }
3041 
3042 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3043   FunctionDecl *FD = cast<FunctionDecl>(D);
3044   if (!FD->getReturnType()->isVoidType()) {
3045     SourceRange RTRange = FD->getReturnTypeSourceRange();
3046     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3047         << FD->getType()
3048         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3049                               : FixItHint());
3050     return;
3051   }
3052 
3053   D->addAttr(::new (S.Context)
3054               CUDAGlobalAttr(Attr.getRange(), S.Context,
3055                             Attr.getAttributeSpellingListIndex()));
3056 }
3057 
3058 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3059   FunctionDecl *Fn = cast<FunctionDecl>(D);
3060   if (!Fn->isInlineSpecified()) {
3061     S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3062     return;
3063   }
3064 
3065   D->addAttr(::new (S.Context)
3066              GNUInlineAttr(Attr.getRange(), S.Context,
3067                            Attr.getAttributeSpellingListIndex()));
3068 }
3069 
3070 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3071   if (hasDeclarator(D)) return;
3072 
3073   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3074   // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3075   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3076   CallingConv CC;
3077   if (S.CheckCallingConvAttr(Attr, CC, FD))
3078     return;
3079 
3080   if (!isa<ObjCMethodDecl>(D)) {
3081     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3082       << Attr.getName() << ExpectedFunctionOrMethod;
3083     return;
3084   }
3085 
3086   switch (Attr.getKind()) {
3087   case AttributeList::AT_FastCall:
3088     D->addAttr(::new (S.Context)
3089                FastCallAttr(Attr.getRange(), S.Context,
3090                             Attr.getAttributeSpellingListIndex()));
3091     return;
3092   case AttributeList::AT_StdCall:
3093     D->addAttr(::new (S.Context)
3094                StdCallAttr(Attr.getRange(), S.Context,
3095                            Attr.getAttributeSpellingListIndex()));
3096     return;
3097   case AttributeList::AT_ThisCall:
3098     D->addAttr(::new (S.Context)
3099                ThisCallAttr(Attr.getRange(), S.Context,
3100                             Attr.getAttributeSpellingListIndex()));
3101     return;
3102   case AttributeList::AT_CDecl:
3103     D->addAttr(::new (S.Context)
3104                CDeclAttr(Attr.getRange(), S.Context,
3105                          Attr.getAttributeSpellingListIndex()));
3106     return;
3107   case AttributeList::AT_Pascal:
3108     D->addAttr(::new (S.Context)
3109                PascalAttr(Attr.getRange(), S.Context,
3110                           Attr.getAttributeSpellingListIndex()));
3111     return;
3112   case AttributeList::AT_MSABI:
3113     D->addAttr(::new (S.Context)
3114                MSABIAttr(Attr.getRange(), S.Context,
3115                          Attr.getAttributeSpellingListIndex()));
3116     return;
3117   case AttributeList::AT_SysVABI:
3118     D->addAttr(::new (S.Context)
3119                SysVABIAttr(Attr.getRange(), S.Context,
3120                            Attr.getAttributeSpellingListIndex()));
3121     return;
3122   case AttributeList::AT_Pcs: {
3123     PcsAttr::PCSType PCS;
3124     switch (CC) {
3125     case CC_AAPCS:
3126       PCS = PcsAttr::AAPCS;
3127       break;
3128     case CC_AAPCS_VFP:
3129       PCS = PcsAttr::AAPCS_VFP;
3130       break;
3131     default:
3132       llvm_unreachable("unexpected calling convention in pcs attribute");
3133     }
3134 
3135     D->addAttr(::new (S.Context)
3136                PcsAttr(Attr.getRange(), S.Context, PCS,
3137                        Attr.getAttributeSpellingListIndex()));
3138     return;
3139   }
3140   case AttributeList::AT_PnaclCall:
3141     D->addAttr(::new (S.Context)
3142                PnaclCallAttr(Attr.getRange(), S.Context,
3143                              Attr.getAttributeSpellingListIndex()));
3144     return;
3145   case AttributeList::AT_IntelOclBicc:
3146     D->addAttr(::new (S.Context)
3147                IntelOclBiccAttr(Attr.getRange(), S.Context,
3148                                 Attr.getAttributeSpellingListIndex()));
3149     return;
3150 
3151   default:
3152     llvm_unreachable("unexpected attribute kind");
3153   }
3154 }
3155 
3156 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3157                                 const FunctionDecl *FD) {
3158   if (attr.isInvalid())
3159     return true;
3160 
3161   unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3162   if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3163     attr.setInvalid();
3164     return true;
3165   }
3166 
3167   // TODO: diagnose uses of these conventions on the wrong target.
3168   switch (attr.getKind()) {
3169   case AttributeList::AT_CDecl: CC = CC_C; break;
3170   case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3171   case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3172   case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3173   case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3174   case AttributeList::AT_MSABI:
3175     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3176                                                              CC_X86_64Win64;
3177     break;
3178   case AttributeList::AT_SysVABI:
3179     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3180                                                              CC_C;
3181     break;
3182   case AttributeList::AT_Pcs: {
3183     StringRef StrRef;
3184     if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3185       attr.setInvalid();
3186       return true;
3187     }
3188     if (StrRef == "aapcs") {
3189       CC = CC_AAPCS;
3190       break;
3191     } else if (StrRef == "aapcs-vfp") {
3192       CC = CC_AAPCS_VFP;
3193       break;
3194     }
3195 
3196     attr.setInvalid();
3197     Diag(attr.getLoc(), diag::err_invalid_pcs);
3198     return true;
3199   }
3200   case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3201   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3202   default: llvm_unreachable("unexpected attribute kind");
3203   }
3204 
3205   const TargetInfo &TI = Context.getTargetInfo();
3206   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3207   if (A == TargetInfo::CCCR_Warning) {
3208     Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3209 
3210     TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3211     if (FD)
3212       MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3213                                     TargetInfo::CCMT_NonMember;
3214     CC = TI.getDefaultCallingConv(MT);
3215   }
3216 
3217   return false;
3218 }
3219 
3220 /// Checks a regparm attribute, returning true if it is ill-formed and
3221 /// otherwise setting numParams to the appropriate value.
3222 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3223   if (Attr.isInvalid())
3224     return true;
3225 
3226   if (!checkAttributeNumArgs(*this, Attr, 1)) {
3227     Attr.setInvalid();
3228     return true;
3229   }
3230 
3231   uint32_t NP;
3232   Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3233   if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3234     Attr.setInvalid();
3235     return true;
3236   }
3237 
3238   if (Context.getTargetInfo().getRegParmMax() == 0) {
3239     Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3240       << NumParamsExpr->getSourceRange();
3241     Attr.setInvalid();
3242     return true;
3243   }
3244 
3245   numParams = NP;
3246   if (numParams > Context.getTargetInfo().getRegParmMax()) {
3247     Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3248       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3249     Attr.setInvalid();
3250     return true;
3251   }
3252 
3253   return false;
3254 }
3255 
3256 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3257                                    const AttributeList &Attr) {
3258   uint32_t MaxThreads, MinBlocks = 0;
3259   if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), MaxThreads, 1))
3260     return;
3261   if (Attr.getNumArgs() > 1 && !checkUInt32Argument(S, Attr,
3262                                                     Attr.getArgAsExpr(1),
3263                                                     MinBlocks, 2))
3264     return;
3265 
3266   D->addAttr(::new (S.Context)
3267               CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3268                                   MaxThreads, MinBlocks,
3269                                   Attr.getAttributeSpellingListIndex()));
3270 }
3271 
3272 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3273                                           const AttributeList &Attr) {
3274   if (!Attr.isArgIdent(0)) {
3275     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3276       << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3277     return;
3278   }
3279 
3280   if (!checkAttributeNumArgs(S, Attr, 3))
3281     return;
3282 
3283   IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3284 
3285   if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3286     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3287       << Attr.getName() << ExpectedFunctionOrMethod;
3288     return;
3289   }
3290 
3291   uint64_t ArgumentIdx;
3292   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3293                                            ArgumentIdx))
3294     return;
3295 
3296   uint64_t TypeTagIdx;
3297   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3298                                            TypeTagIdx))
3299     return;
3300 
3301   bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3302   if (IsPointer) {
3303     // Ensure that buffer has a pointer type.
3304     QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3305     if (!BufferTy->isPointerType()) {
3306       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3307         << Attr.getName();
3308     }
3309   }
3310 
3311   D->addAttr(::new (S.Context)
3312              ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3313                                      ArgumentIdx, TypeTagIdx, IsPointer,
3314                                      Attr.getAttributeSpellingListIndex()));
3315 }
3316 
3317 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3318                                          const AttributeList &Attr) {
3319   if (!Attr.isArgIdent(0)) {
3320     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3321       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3322     return;
3323   }
3324 
3325   if (!checkAttributeNumArgs(S, Attr, 1))
3326     return;
3327 
3328   if (!isa<VarDecl>(D)) {
3329     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3330       << Attr.getName() << ExpectedVariable;
3331     return;
3332   }
3333 
3334   IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3335   TypeSourceInfo *MatchingCTypeLoc = nullptr;
3336   S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3337   assert(MatchingCTypeLoc && "no type source info for attribute argument");
3338 
3339   D->addAttr(::new (S.Context)
3340              TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3341                                     MatchingCTypeLoc,
3342                                     Attr.getLayoutCompatible(),
3343                                     Attr.getMustBeNull(),
3344                                     Attr.getAttributeSpellingListIndex()));
3345 }
3346 
3347 //===----------------------------------------------------------------------===//
3348 // Checker-specific attribute handlers.
3349 //===----------------------------------------------------------------------===//
3350 
3351 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3352   return type->isDependentType() ||
3353          type->isObjCRetainableType();
3354 }
3355 
3356 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3357   return type->isDependentType() ||
3358          type->isObjCObjectPointerType() ||
3359          S.Context.isObjCNSObjectType(type);
3360 }
3361 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3362   return type->isDependentType() ||
3363          type->isPointerType() ||
3364          isValidSubjectOfNSAttribute(S, type);
3365 }
3366 
3367 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3368   ParmVarDecl *param = cast<ParmVarDecl>(D);
3369   bool typeOK, cf;
3370 
3371   if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3372     typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3373     cf = false;
3374   } else {
3375     typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3376     cf = true;
3377   }
3378 
3379   if (!typeOK) {
3380     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3381       << Attr.getRange() << Attr.getName() << cf;
3382     return;
3383   }
3384 
3385   if (cf)
3386     param->addAttr(::new (S.Context)
3387                    CFConsumedAttr(Attr.getRange(), S.Context,
3388                                   Attr.getAttributeSpellingListIndex()));
3389   else
3390     param->addAttr(::new (S.Context)
3391                    NSConsumedAttr(Attr.getRange(), S.Context,
3392                                   Attr.getAttributeSpellingListIndex()));
3393 }
3394 
3395 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3396                                         const AttributeList &Attr) {
3397 
3398   QualType returnType;
3399 
3400   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3401     returnType = MD->getReturnType();
3402   else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3403            (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3404     return; // ignore: was handled as a type attribute
3405   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3406     returnType = PD->getType();
3407   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3408     returnType = FD->getReturnType();
3409   else {
3410     S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3411         << Attr.getRange() << Attr.getName()
3412         << ExpectedFunctionOrMethod;
3413     return;
3414   }
3415 
3416   bool typeOK;
3417   bool cf;
3418   switch (Attr.getKind()) {
3419   default: llvm_unreachable("invalid ownership attribute");
3420   case AttributeList::AT_NSReturnsRetained:
3421     typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
3422     cf = false;
3423     break;
3424 
3425   case AttributeList::AT_NSReturnsAutoreleased:
3426   case AttributeList::AT_NSReturnsNotRetained:
3427     typeOK = isValidSubjectOfNSAttribute(S, returnType);
3428     cf = false;
3429     break;
3430 
3431   case AttributeList::AT_CFReturnsRetained:
3432   case AttributeList::AT_CFReturnsNotRetained:
3433     typeOK = isValidSubjectOfCFAttribute(S, returnType);
3434     cf = true;
3435     break;
3436   }
3437 
3438   if (!typeOK) {
3439     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3440       << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3441     return;
3442   }
3443 
3444   switch (Attr.getKind()) {
3445     default:
3446       llvm_unreachable("invalid ownership attribute");
3447     case AttributeList::AT_NSReturnsAutoreleased:
3448       D->addAttr(::new (S.Context)
3449                  NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
3450                                            Attr.getAttributeSpellingListIndex()));
3451       return;
3452     case AttributeList::AT_CFReturnsNotRetained:
3453       D->addAttr(::new (S.Context)
3454                  CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
3455                                           Attr.getAttributeSpellingListIndex()));
3456       return;
3457     case AttributeList::AT_NSReturnsNotRetained:
3458       D->addAttr(::new (S.Context)
3459                  NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
3460                                           Attr.getAttributeSpellingListIndex()));
3461       return;
3462     case AttributeList::AT_CFReturnsRetained:
3463       D->addAttr(::new (S.Context)
3464                  CFReturnsRetainedAttr(Attr.getRange(), S.Context,
3465                                        Attr.getAttributeSpellingListIndex()));
3466       return;
3467     case AttributeList::AT_NSReturnsRetained:
3468       D->addAttr(::new (S.Context)
3469                  NSReturnsRetainedAttr(Attr.getRange(), S.Context,
3470                                        Attr.getAttributeSpellingListIndex()));
3471       return;
3472   };
3473 }
3474 
3475 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3476                                               const AttributeList &attr) {
3477   const int EP_ObjCMethod = 1;
3478   const int EP_ObjCProperty = 2;
3479 
3480   SourceLocation loc = attr.getLoc();
3481   QualType resultType;
3482   if (isa<ObjCMethodDecl>(D))
3483     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3484   else
3485     resultType = cast<ObjCPropertyDecl>(D)->getType();
3486 
3487   if (!resultType->isReferenceType() &&
3488       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3489     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3490       << SourceRange(loc)
3491     << attr.getName()
3492     << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3493     << /*non-retainable pointer*/ 2;
3494 
3495     // Drop the attribute.
3496     return;
3497   }
3498 
3499   D->addAttr(::new (S.Context)
3500                   ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
3501                                               attr.getAttributeSpellingListIndex()));
3502 }
3503 
3504 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3505                                         const AttributeList &attr) {
3506   ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3507 
3508   DeclContext *DC = method->getDeclContext();
3509   if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3510     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3511     << attr.getName() << 0;
3512     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3513     return;
3514   }
3515   if (method->getMethodFamily() == OMF_dealloc) {
3516     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3517     << attr.getName() << 1;
3518     return;
3519   }
3520 
3521   method->addAttr(::new (S.Context)
3522                   ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3523                                         attr.getAttributeSpellingListIndex()));
3524 }
3525 
3526 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3527                                         const AttributeList &Attr) {
3528   if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3529     return;
3530 
3531   D->addAttr(::new (S.Context)
3532              CFAuditedTransferAttr(Attr.getRange(), S.Context,
3533                                    Attr.getAttributeSpellingListIndex()));
3534 }
3535 
3536 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3537                                         const AttributeList &Attr) {
3538   if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3539     return;
3540 
3541   D->addAttr(::new (S.Context)
3542              CFUnknownTransferAttr(Attr.getRange(), S.Context,
3543              Attr.getAttributeSpellingListIndex()));
3544 }
3545 
3546 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3547                                 const AttributeList &Attr) {
3548   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3549 
3550   if (!Parm) {
3551     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3552     return;
3553   }
3554 
3555   D->addAttr(::new (S.Context)
3556              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3557                            Attr.getAttributeSpellingListIndex()));
3558 }
3559 
3560 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3561                                         const AttributeList &Attr) {
3562   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3563 
3564   if (!Parm) {
3565     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3566     return;
3567   }
3568 
3569   D->addAttr(::new (S.Context)
3570              ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3571                             Attr.getAttributeSpellingListIndex()));
3572 }
3573 
3574 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3575                                  const AttributeList &Attr) {
3576   IdentifierInfo *RelatedClass =
3577     Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
3578   if (!RelatedClass) {
3579     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3580     return;
3581   }
3582   IdentifierInfo *ClassMethod =
3583     Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
3584   IdentifierInfo *InstanceMethod =
3585     Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
3586   D->addAttr(::new (S.Context)
3587              ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3588                                    ClassMethod, InstanceMethod,
3589                                    Attr.getAttributeSpellingListIndex()));
3590 }
3591 
3592 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3593                                             const AttributeList &Attr) {
3594   ObjCInterfaceDecl *IFace;
3595   if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
3596     IFace = CatDecl->getClassInterface();
3597   else
3598     IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3599   IFace->setHasDesignatedInitializers();
3600   D->addAttr(::new (S.Context)
3601                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3602                                          Attr.getAttributeSpellingListIndex()));
3603 }
3604 
3605 static void handleObjCRuntimeName(Sema &S, Decl *D,
3606                                   const AttributeList &Attr) {
3607   StringRef MetaDataName;
3608   if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
3609     return;
3610   D->addAttr(::new (S.Context)
3611              ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
3612                                  MetaDataName,
3613                                  Attr.getAttributeSpellingListIndex()));
3614 }
3615 
3616 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3617                                     const AttributeList &Attr) {
3618   if (hasDeclarator(D)) return;
3619 
3620   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3621     << Attr.getRange() << Attr.getName() << ExpectedVariable;
3622 }
3623 
3624 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3625                                           const AttributeList &Attr) {
3626   ValueDecl *vd = cast<ValueDecl>(D);
3627   QualType type = vd->getType();
3628 
3629   if (!type->isDependentType() &&
3630       !type->isObjCLifetimeType()) {
3631     S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3632       << type;
3633     return;
3634   }
3635 
3636   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3637 
3638   // If we have no lifetime yet, check the lifetime we're presumably
3639   // going to infer.
3640   if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3641     lifetime = type->getObjCARCImplicitLifetime();
3642 
3643   switch (lifetime) {
3644   case Qualifiers::OCL_None:
3645     assert(type->isDependentType() &&
3646            "didn't infer lifetime for non-dependent type?");
3647     break;
3648 
3649   case Qualifiers::OCL_Weak:   // meaningful
3650   case Qualifiers::OCL_Strong: // meaningful
3651     break;
3652 
3653   case Qualifiers::OCL_ExplicitNone:
3654   case Qualifiers::OCL_Autoreleasing:
3655     S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3656       << (lifetime == Qualifiers::OCL_Autoreleasing);
3657     break;
3658   }
3659 
3660   D->addAttr(::new (S.Context)
3661              ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
3662                                      Attr.getAttributeSpellingListIndex()));
3663 }
3664 
3665 //===----------------------------------------------------------------------===//
3666 // Microsoft specific attribute handlers.
3667 //===----------------------------------------------------------------------===//
3668 
3669 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3670   if (!S.LangOpts.CPlusPlus) {
3671     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3672       << Attr.getName() << AttributeLangSupport::C;
3673     return;
3674   }
3675 
3676   if (!isa<CXXRecordDecl>(D)) {
3677     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3678       << Attr.getName() << ExpectedClass;
3679     return;
3680   }
3681 
3682   StringRef StrRef;
3683   SourceLocation LiteralLoc;
3684   if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
3685     return;
3686 
3687   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
3688   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
3689   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
3690     StrRef = StrRef.drop_front().drop_back();
3691 
3692   // Validate GUID length.
3693   if (StrRef.size() != 36) {
3694     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3695     return;
3696   }
3697 
3698   for (unsigned i = 0; i < 36; ++i) {
3699     if (i == 8 || i == 13 || i == 18 || i == 23) {
3700       if (StrRef[i] != '-') {
3701         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3702         return;
3703       }
3704     } else if (!isHexDigit(StrRef[i])) {
3705       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3706       return;
3707     }
3708   }
3709 
3710   D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
3711                                         Attr.getAttributeSpellingListIndex()));
3712 }
3713 
3714 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3715   if (!S.LangOpts.CPlusPlus) {
3716     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3717       << Attr.getName() << AttributeLangSupport::C;
3718     return;
3719   }
3720   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
3721       D, Attr.getRange(), /*BestCase=*/true,
3722       Attr.getAttributeSpellingListIndex(),
3723       (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
3724   if (IA)
3725     D->addAttr(IA);
3726 }
3727 
3728 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
3729                                      const AttributeList &Attr) {
3730   VarDecl *VD = cast<VarDecl>(D);
3731   if (!S.Context.getTargetInfo().isTLSSupported()) {
3732     S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
3733     return;
3734   }
3735   if (VD->getTSCSpec() != TSCS_unspecified) {
3736     S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
3737     return;
3738   }
3739   if (VD->hasLocalStorage()) {
3740     S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
3741     return;
3742   }
3743   VD->addAttr(::new (S.Context) ThreadAttr(
3744       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3745 }
3746 
3747 static void handleARMInterruptAttr(Sema &S, Decl *D,
3748                                    const AttributeList &Attr) {
3749   // Check the attribute arguments.
3750   if (Attr.getNumArgs() > 1) {
3751     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
3752       << Attr.getName() << 1;
3753     return;
3754   }
3755 
3756   StringRef Str;
3757   SourceLocation ArgLoc;
3758 
3759   if (Attr.getNumArgs() == 0)
3760     Str = "";
3761   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
3762     return;
3763 
3764   ARMInterruptAttr::InterruptType Kind;
3765   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
3766     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3767       << Attr.getName() << Str << ArgLoc;
3768     return;
3769   }
3770 
3771   unsigned Index = Attr.getAttributeSpellingListIndex();
3772   D->addAttr(::new (S.Context)
3773              ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
3774 }
3775 
3776 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
3777                                       const AttributeList &Attr) {
3778   if (!checkAttributeNumArgs(S, Attr, 1))
3779     return;
3780 
3781   if (!Attr.isArgExpr(0)) {
3782     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3783       << AANT_ArgumentIntegerConstant;
3784     return;
3785   }
3786 
3787   // FIXME: Check for decl - it should be void ()(void).
3788 
3789   Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3790   llvm::APSInt NumParams(32);
3791   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
3792     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3793       << Attr.getName() << AANT_ArgumentIntegerConstant
3794       << NumParamsExpr->getSourceRange();
3795     return;
3796   }
3797 
3798   unsigned Num = NumParams.getLimitedValue(255);
3799   if ((Num & 1) || Num > 30) {
3800     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3801       << Attr.getName() << (int)NumParams.getSExtValue()
3802       << NumParamsExpr->getSourceRange();
3803     return;
3804   }
3805 
3806   D->addAttr(::new (S.Context)
3807               MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
3808                                   Attr.getAttributeSpellingListIndex()));
3809   D->addAttr(UsedAttr::CreateImplicit(S.Context));
3810 }
3811 
3812 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3813   // Dispatch the interrupt attribute based on the current target.
3814   if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
3815     handleMSP430InterruptAttr(S, D, Attr);
3816   else
3817     handleARMInterruptAttr(S, D, Attr);
3818 }
3819 
3820 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
3821                                               const AttributeList& Attr) {
3822   // If we try to apply it to a function pointer, don't warn, but don't
3823   // do anything, either. It doesn't matter anyway, because there's nothing
3824   // special about calling a force_align_arg_pointer function.
3825   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3826   if (VD && VD->getType()->isFunctionPointerType())
3827     return;
3828   // Also don't warn on function pointer typedefs.
3829   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3830   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
3831     TD->getUnderlyingType()->isFunctionType()))
3832     return;
3833   // Attribute can only be applied to function types.
3834   if (!isa<FunctionDecl>(D)) {
3835     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3836       << Attr.getName() << /* function */0;
3837     return;
3838   }
3839 
3840   D->addAttr(::new (S.Context)
3841               X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
3842                                         Attr.getAttributeSpellingListIndex()));
3843 }
3844 
3845 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
3846                                         unsigned AttrSpellingListIndex) {
3847   if (D->hasAttr<DLLExportAttr>()) {
3848     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
3849     return nullptr;
3850   }
3851 
3852   if (D->hasAttr<DLLImportAttr>())
3853     return nullptr;
3854 
3855   return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
3856 }
3857 
3858 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
3859                                         unsigned AttrSpellingListIndex) {
3860   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
3861     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
3862     D->dropAttr<DLLImportAttr>();
3863   }
3864 
3865   if (D->hasAttr<DLLExportAttr>())
3866     return nullptr;
3867 
3868   return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
3869 }
3870 
3871 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
3872   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
3873       S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3874     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
3875         << A.getName();
3876     return;
3877   }
3878 
3879   unsigned Index = A.getAttributeSpellingListIndex();
3880   Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
3881                       ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
3882                       : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
3883   if (NewAttr)
3884     D->addAttr(NewAttr);
3885 }
3886 
3887 MSInheritanceAttr *
3888 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
3889                              unsigned AttrSpellingListIndex,
3890                              MSInheritanceAttr::Spelling SemanticSpelling) {
3891   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
3892     if (IA->getSemanticSpelling() == SemanticSpelling)
3893       return nullptr;
3894     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
3895         << 1 /*previous declaration*/;
3896     Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
3897     D->dropAttr<MSInheritanceAttr>();
3898   }
3899 
3900   CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3901   if (RD->hasDefinition()) {
3902     if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
3903                                            SemanticSpelling)) {
3904       return nullptr;
3905     }
3906   } else {
3907     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
3908       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
3909           << 1 /*partial specialization*/;
3910       return nullptr;
3911     }
3912     if (RD->getDescribedClassTemplate()) {
3913       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
3914           << 0 /*primary template*/;
3915       return nullptr;
3916     }
3917   }
3918 
3919   return ::new (Context)
3920       MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
3921 }
3922 
3923 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3924   // The capability attributes take a single string parameter for the name of
3925   // the capability they represent. The lockable attribute does not take any
3926   // parameters. However, semantically, both attributes represent the same
3927   // concept, and so they use the same semantic attribute. Eventually, the
3928   // lockable attribute will be removed.
3929   //
3930   // For backward compatibility, any capability which has no specified string
3931   // literal will be considered a "mutex."
3932   StringRef N("mutex");
3933   SourceLocation LiteralLoc;
3934   if (Attr.getKind() == AttributeList::AT_Capability &&
3935       !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
3936     return;
3937 
3938   // Currently, there are only two names allowed for a capability: role and
3939   // mutex (case insensitive). Diagnose other capability names.
3940   if (!N.equals_lower("mutex") && !N.equals_lower("role"))
3941     S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
3942 
3943   D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
3944                                         Attr.getAttributeSpellingListIndex()));
3945 }
3946 
3947 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
3948                                        const AttributeList &Attr) {
3949   D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
3950                                                     Attr.getArgAsExpr(0),
3951                                         Attr.getAttributeSpellingListIndex()));
3952 }
3953 
3954 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
3955                                         const AttributeList &Attr) {
3956   SmallVector<Expr*, 1> Args;
3957   if (!checkLockFunAttrCommon(S, D, Attr, Args))
3958     return;
3959 
3960   D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
3961                                                      S.Context,
3962                                                      Args.data(), Args.size(),
3963                                         Attr.getAttributeSpellingListIndex()));
3964 }
3965 
3966 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
3967                                            const AttributeList &Attr) {
3968   SmallVector<Expr*, 2> Args;
3969   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
3970     return;
3971 
3972   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
3973                                                         S.Context,
3974                                                         Attr.getArgAsExpr(0),
3975                                                         Args.data(),
3976                                                         Args.size(),
3977                                         Attr.getAttributeSpellingListIndex()));
3978 }
3979 
3980 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
3981                                         const AttributeList &Attr) {
3982   // Check that all arguments are lockable objects.
3983   SmallVector<Expr *, 1> Args;
3984   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
3985 
3986   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
3987       Attr.getRange(), S.Context, Args.data(), Args.size(),
3988       Attr.getAttributeSpellingListIndex()));
3989 }
3990 
3991 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
3992                                          const AttributeList &Attr) {
3993   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
3994     return;
3995 
3996   // check that all arguments are lockable objects
3997   SmallVector<Expr*, 1> Args;
3998   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
3999   if (Args.empty())
4000     return;
4001 
4002   RequiresCapabilityAttr *RCA = ::new (S.Context)
4003     RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4004                            Args.size(), Attr.getAttributeSpellingListIndex());
4005 
4006   D->addAttr(RCA);
4007 }
4008 
4009 /// Handles semantic checking for features that are common to all attributes,
4010 /// such as checking whether a parameter was properly specified, or the correct
4011 /// number of arguments were passed, etc.
4012 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4013                                           const AttributeList &Attr) {
4014   // Several attributes carry different semantics than the parsing requires, so
4015   // those are opted out of the common handling.
4016   //
4017   // We also bail on unknown and ignored attributes because those are handled
4018   // as part of the target-specific handling logic.
4019   if (Attr.hasCustomParsing() ||
4020       Attr.getKind() == AttributeList::UnknownAttribute)
4021     return false;
4022 
4023   // Check whether the attribute requires specific language extensions to be
4024   // enabled.
4025   if (!Attr.diagnoseLangOpts(S))
4026     return true;
4027 
4028   if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4029     // If there are no optional arguments, then checking for the argument count
4030     // is trivial.
4031     if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4032       return true;
4033   } else {
4034     // There are optional arguments, so checking is slightly more involved.
4035     if (Attr.getMinArgs() &&
4036         !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4037       return true;
4038     else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4039              !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4040       return true;
4041   }
4042 
4043   // Check whether the attribute appertains to the given subject.
4044   if (!Attr.diagnoseAppertainsTo(S, D))
4045     return true;
4046 
4047   return false;
4048 }
4049 
4050 //===----------------------------------------------------------------------===//
4051 // Top Level Sema Entry Points
4052 //===----------------------------------------------------------------------===//
4053 
4054 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4055 /// the attribute applies to decls.  If the attribute is a type attribute, just
4056 /// silently ignore it if a GNU attribute.
4057 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4058                                  const AttributeList &Attr,
4059                                  bool IncludeCXX11Attributes) {
4060   if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4061     return;
4062 
4063   // Ignore C++11 attributes on declarator chunks: they appertain to the type
4064   // instead.
4065   if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4066     return;
4067 
4068   // Unknown attributes are automatically warned on. Target-specific attributes
4069   // which do not apply to the current target architecture are treated as
4070   // though they were unknown attributes.
4071   if (Attr.getKind() == AttributeList::UnknownAttribute ||
4072       !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4073     S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4074                               ? diag::warn_unhandled_ms_attribute_ignored
4075                               : diag::warn_unknown_attribute_ignored)
4076         << Attr.getName();
4077     return;
4078   }
4079 
4080   if (handleCommonAttributeFeatures(S, scope, D, Attr))
4081     return;
4082 
4083   switch (Attr.getKind()) {
4084   default:
4085     // Type attributes are handled elsewhere; silently move on.
4086     assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4087     break;
4088   case AttributeList::AT_Interrupt:
4089     handleInterruptAttr(S, D, Attr);
4090     break;
4091   case AttributeList::AT_X86ForceAlignArgPointer:
4092     handleX86ForceAlignArgPointerAttr(S, D, Attr);
4093     break;
4094   case AttributeList::AT_DLLExport:
4095   case AttributeList::AT_DLLImport:
4096     handleDLLAttr(S, D, Attr);
4097     break;
4098   case AttributeList::AT_Mips16:
4099     handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4100     break;
4101   case AttributeList::AT_NoMips16:
4102     handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4103     break;
4104   case AttributeList::AT_IBAction:
4105     handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4106     break;
4107   case AttributeList::AT_IBOutlet:
4108     handleIBOutlet(S, D, Attr);
4109     break;
4110   case AttributeList::AT_IBOutletCollection:
4111     handleIBOutletCollection(S, D, Attr);
4112     break;
4113   case AttributeList::AT_Alias:
4114     handleAliasAttr(S, D, Attr);
4115     break;
4116   case AttributeList::AT_Aligned:
4117     handleAlignedAttr(S, D, Attr);
4118     break;
4119   case AttributeList::AT_AlwaysInline:
4120     handleAlwaysInlineAttr(S, D, Attr);
4121     break;
4122   case AttributeList::AT_AnalyzerNoReturn:
4123     handleAnalyzerNoReturnAttr(S, D, Attr);
4124     break;
4125   case AttributeList::AT_TLSModel:
4126     handleTLSModelAttr(S, D, Attr);
4127     break;
4128   case AttributeList::AT_Annotate:
4129     handleAnnotateAttr(S, D, Attr);
4130     break;
4131   case AttributeList::AT_Availability:
4132     handleAvailabilityAttr(S, D, Attr);
4133     break;
4134   case AttributeList::AT_CarriesDependency:
4135     handleDependencyAttr(S, scope, D, Attr);
4136     break;
4137   case AttributeList::AT_Common:
4138     handleCommonAttr(S, D, Attr);
4139     break;
4140   case AttributeList::AT_CUDAConstant:
4141     handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4142     break;
4143   case AttributeList::AT_Constructor:
4144     handleConstructorAttr(S, D, Attr);
4145     break;
4146   case AttributeList::AT_CXX11NoReturn:
4147     handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4148     break;
4149   case AttributeList::AT_Deprecated:
4150     handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4151     break;
4152   case AttributeList::AT_Destructor:
4153     handleDestructorAttr(S, D, Attr);
4154     break;
4155   case AttributeList::AT_EnableIf:
4156     handleEnableIfAttr(S, D, Attr);
4157     break;
4158   case AttributeList::AT_ExtVectorType:
4159     handleExtVectorTypeAttr(S, scope, D, Attr);
4160     break;
4161   case AttributeList::AT_MinSize:
4162     handleSimpleAttribute<MinSizeAttr>(S, D, Attr);
4163     break;
4164   case AttributeList::AT_OptimizeNone:
4165     handleOptimizeNoneAttr(S, D, Attr);
4166     break;
4167   case AttributeList::AT_Flatten:
4168     handleSimpleAttribute<FlattenAttr>(S, D, Attr);
4169     break;
4170   case AttributeList::AT_Format:
4171     handleFormatAttr(S, D, Attr);
4172     break;
4173   case AttributeList::AT_FormatArg:
4174     handleFormatArgAttr(S, D, Attr);
4175     break;
4176   case AttributeList::AT_CUDAGlobal:
4177     handleGlobalAttr(S, D, Attr);
4178     break;
4179   case AttributeList::AT_CUDADevice:
4180     handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4181     break;
4182   case AttributeList::AT_CUDAHost:
4183     handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4184     break;
4185   case AttributeList::AT_GNUInline:
4186     handleGNUInlineAttr(S, D, Attr);
4187     break;
4188   case AttributeList::AT_CUDALaunchBounds:
4189     handleLaunchBoundsAttr(S, D, Attr);
4190     break;
4191   case AttributeList::AT_Malloc:
4192     handleMallocAttr(S, D, Attr);
4193     break;
4194   case AttributeList::AT_MayAlias:
4195     handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4196     break;
4197   case AttributeList::AT_Mode:
4198     handleModeAttr(S, D, Attr);
4199     break;
4200   case AttributeList::AT_NoCommon:
4201     handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4202     break;
4203   case AttributeList::AT_NoSplitStack:
4204     handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
4205     break;
4206   case AttributeList::AT_NonNull:
4207     if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4208       handleNonNullAttrParameter(S, PVD, Attr);
4209     else
4210       handleNonNullAttr(S, D, Attr);
4211     break;
4212   case AttributeList::AT_ReturnsNonNull:
4213     handleReturnsNonNullAttr(S, D, Attr);
4214     break;
4215   case AttributeList::AT_Overloadable:
4216     handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4217     break;
4218   case AttributeList::AT_Ownership:
4219     handleOwnershipAttr(S, D, Attr);
4220     break;
4221   case AttributeList::AT_Cold:
4222     handleColdAttr(S, D, Attr);
4223     break;
4224   case AttributeList::AT_Hot:
4225     handleHotAttr(S, D, Attr);
4226     break;
4227   case AttributeList::AT_Naked:
4228     handleSimpleAttribute<NakedAttr>(S, D, Attr);
4229     break;
4230   case AttributeList::AT_NoReturn:
4231     handleNoReturnAttr(S, D, Attr);
4232     break;
4233   case AttributeList::AT_NoThrow:
4234     handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4235     break;
4236   case AttributeList::AT_CUDAShared:
4237     handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4238     break;
4239   case AttributeList::AT_VecReturn:
4240     handleVecReturnAttr(S, D, Attr);
4241     break;
4242 
4243   case AttributeList::AT_ObjCOwnership:
4244     handleObjCOwnershipAttr(S, D, Attr);
4245     break;
4246   case AttributeList::AT_ObjCPreciseLifetime:
4247     handleObjCPreciseLifetimeAttr(S, D, Attr);
4248     break;
4249 
4250   case AttributeList::AT_ObjCReturnsInnerPointer:
4251     handleObjCReturnsInnerPointerAttr(S, D, Attr);
4252     break;
4253 
4254   case AttributeList::AT_ObjCRequiresSuper:
4255     handleObjCRequiresSuperAttr(S, D, Attr);
4256     break;
4257 
4258   case AttributeList::AT_ObjCBridge:
4259     handleObjCBridgeAttr(S, scope, D, Attr);
4260     break;
4261 
4262   case AttributeList::AT_ObjCBridgeMutable:
4263     handleObjCBridgeMutableAttr(S, scope, D, Attr);
4264     break;
4265 
4266   case AttributeList::AT_ObjCBridgeRelated:
4267     handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4268     break;
4269 
4270   case AttributeList::AT_ObjCDesignatedInitializer:
4271     handleObjCDesignatedInitializer(S, D, Attr);
4272     break;
4273 
4274   case AttributeList::AT_ObjCRuntimeName:
4275     handleObjCRuntimeName(S, D, Attr);
4276     break;
4277 
4278   case AttributeList::AT_CFAuditedTransfer:
4279     handleCFAuditedTransferAttr(S, D, Attr);
4280     break;
4281   case AttributeList::AT_CFUnknownTransfer:
4282     handleCFUnknownTransferAttr(S, D, Attr);
4283     break;
4284 
4285   case AttributeList::AT_CFConsumed:
4286   case AttributeList::AT_NSConsumed:
4287     handleNSConsumedAttr(S, D, Attr);
4288     break;
4289   case AttributeList::AT_NSConsumesSelf:
4290     handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4291     break;
4292 
4293   case AttributeList::AT_NSReturnsAutoreleased:
4294   case AttributeList::AT_NSReturnsNotRetained:
4295   case AttributeList::AT_CFReturnsNotRetained:
4296   case AttributeList::AT_NSReturnsRetained:
4297   case AttributeList::AT_CFReturnsRetained:
4298     handleNSReturnsRetainedAttr(S, D, Attr);
4299     break;
4300   case AttributeList::AT_WorkGroupSizeHint:
4301     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4302     break;
4303   case AttributeList::AT_ReqdWorkGroupSize:
4304     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4305     break;
4306   case AttributeList::AT_VecTypeHint:
4307     handleVecTypeHint(S, D, Attr);
4308     break;
4309 
4310   case AttributeList::AT_InitPriority:
4311     handleInitPriorityAttr(S, D, Attr);
4312     break;
4313 
4314   case AttributeList::AT_Packed:
4315     handlePackedAttr(S, D, Attr);
4316     break;
4317   case AttributeList::AT_Section:
4318     handleSectionAttr(S, D, Attr);
4319     break;
4320   case AttributeList::AT_Unavailable:
4321     handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4322     break;
4323   case AttributeList::AT_ArcWeakrefUnavailable:
4324     handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4325     break;
4326   case AttributeList::AT_ObjCRootClass:
4327     handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4328     break;
4329   case AttributeList::AT_ObjCExplicitProtocolImpl:
4330     handleObjCSuppresProtocolAttr(S, D, Attr);
4331     break;
4332   case AttributeList::AT_ObjCRequiresPropertyDefs:
4333     handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4334     break;
4335   case AttributeList::AT_Unused:
4336     handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4337     break;
4338   case AttributeList::AT_ReturnsTwice:
4339     handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4340     break;
4341   case AttributeList::AT_Used:
4342     handleUsedAttr(S, D, Attr);
4343     break;
4344   case AttributeList::AT_Visibility:
4345     handleVisibilityAttr(S, D, Attr, false);
4346     break;
4347   case AttributeList::AT_TypeVisibility:
4348     handleVisibilityAttr(S, D, Attr, true);
4349     break;
4350   case AttributeList::AT_WarnUnused:
4351     handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4352     break;
4353   case AttributeList::AT_WarnUnusedResult:
4354     handleWarnUnusedResult(S, D, Attr);
4355     break;
4356   case AttributeList::AT_Weak:
4357     handleSimpleAttribute<WeakAttr>(S, D, Attr);
4358     break;
4359   case AttributeList::AT_WeakRef:
4360     handleWeakRefAttr(S, D, Attr);
4361     break;
4362   case AttributeList::AT_WeakImport:
4363     handleWeakImportAttr(S, D, Attr);
4364     break;
4365   case AttributeList::AT_TransparentUnion:
4366     handleTransparentUnionAttr(S, D, Attr);
4367     break;
4368   case AttributeList::AT_ObjCException:
4369     handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4370     break;
4371   case AttributeList::AT_ObjCMethodFamily:
4372     handleObjCMethodFamilyAttr(S, D, Attr);
4373     break;
4374   case AttributeList::AT_ObjCNSObject:
4375     handleObjCNSObject(S, D, Attr);
4376     break;
4377   case AttributeList::AT_Blocks:
4378     handleBlocksAttr(S, D, Attr);
4379     break;
4380   case AttributeList::AT_Sentinel:
4381     handleSentinelAttr(S, D, Attr);
4382     break;
4383   case AttributeList::AT_Const:
4384     handleSimpleAttribute<ConstAttr>(S, D, Attr);
4385     break;
4386   case AttributeList::AT_Pure:
4387     handleSimpleAttribute<PureAttr>(S, D, Attr);
4388     break;
4389   case AttributeList::AT_Cleanup:
4390     handleCleanupAttr(S, D, Attr);
4391     break;
4392   case AttributeList::AT_NoDebug:
4393     handleNoDebugAttr(S, D, Attr);
4394     break;
4395   case AttributeList::AT_NoDuplicate:
4396     handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4397     break;
4398   case AttributeList::AT_NoInline:
4399     handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4400     break;
4401   case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4402     handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4403     break;
4404   case AttributeList::AT_StdCall:
4405   case AttributeList::AT_CDecl:
4406   case AttributeList::AT_FastCall:
4407   case AttributeList::AT_ThisCall:
4408   case AttributeList::AT_Pascal:
4409   case AttributeList::AT_MSABI:
4410   case AttributeList::AT_SysVABI:
4411   case AttributeList::AT_Pcs:
4412   case AttributeList::AT_PnaclCall:
4413   case AttributeList::AT_IntelOclBicc:
4414     handleCallConvAttr(S, D, Attr);
4415     break;
4416   case AttributeList::AT_OpenCLKernel:
4417     handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4418     break;
4419   case AttributeList::AT_OpenCLImageAccess:
4420     handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4421     break;
4422 
4423   // Microsoft attributes:
4424   case AttributeList::AT_MsStruct:
4425     handleSimpleAttribute<MsStructAttr>(S, D, Attr);
4426     break;
4427   case AttributeList::AT_Uuid:
4428     handleUuidAttr(S, D, Attr);
4429     break;
4430   case AttributeList::AT_MSInheritance:
4431     handleMSInheritanceAttr(S, D, Attr);
4432     break;
4433   case AttributeList::AT_SelectAny:
4434     handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4435     break;
4436   case AttributeList::AT_Thread:
4437     handleDeclspecThreadAttr(S, D, Attr);
4438     break;
4439 
4440   // Thread safety attributes:
4441   case AttributeList::AT_AssertExclusiveLock:
4442     handleAssertExclusiveLockAttr(S, D, Attr);
4443     break;
4444   case AttributeList::AT_AssertSharedLock:
4445     handleAssertSharedLockAttr(S, D, Attr);
4446     break;
4447   case AttributeList::AT_GuardedVar:
4448     handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4449     break;
4450   case AttributeList::AT_PtGuardedVar:
4451     handlePtGuardedVarAttr(S, D, Attr);
4452     break;
4453   case AttributeList::AT_ScopedLockable:
4454     handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4455     break;
4456   case AttributeList::AT_NoSanitizeAddress:
4457     handleSimpleAttribute<NoSanitizeAddressAttr>(S, D, Attr);
4458     break;
4459   case AttributeList::AT_NoThreadSafetyAnalysis:
4460     handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
4461     break;
4462   case AttributeList::AT_NoSanitizeThread:
4463     handleSimpleAttribute<NoSanitizeThreadAttr>(S, D, Attr);
4464     break;
4465   case AttributeList::AT_NoSanitizeMemory:
4466     handleSimpleAttribute<NoSanitizeMemoryAttr>(S, D, Attr);
4467     break;
4468   case AttributeList::AT_GuardedBy:
4469     handleGuardedByAttr(S, D, Attr);
4470     break;
4471   case AttributeList::AT_PtGuardedBy:
4472     handlePtGuardedByAttr(S, D, Attr);
4473     break;
4474   case AttributeList::AT_ExclusiveTrylockFunction:
4475     handleExclusiveTrylockFunctionAttr(S, D, Attr);
4476     break;
4477   case AttributeList::AT_LockReturned:
4478     handleLockReturnedAttr(S, D, Attr);
4479     break;
4480   case AttributeList::AT_LocksExcluded:
4481     handleLocksExcludedAttr(S, D, Attr);
4482     break;
4483   case AttributeList::AT_SharedTrylockFunction:
4484     handleSharedTrylockFunctionAttr(S, D, Attr);
4485     break;
4486   case AttributeList::AT_AcquiredBefore:
4487     handleAcquiredBeforeAttr(S, D, Attr);
4488     break;
4489   case AttributeList::AT_AcquiredAfter:
4490     handleAcquiredAfterAttr(S, D, Attr);
4491     break;
4492 
4493   // Capability analysis attributes.
4494   case AttributeList::AT_Capability:
4495   case AttributeList::AT_Lockable:
4496     handleCapabilityAttr(S, D, Attr);
4497     break;
4498   case AttributeList::AT_RequiresCapability:
4499     handleRequiresCapabilityAttr(S, D, Attr);
4500     break;
4501 
4502   case AttributeList::AT_AssertCapability:
4503     handleAssertCapabilityAttr(S, D, Attr);
4504     break;
4505   case AttributeList::AT_AcquireCapability:
4506     handleAcquireCapabilityAttr(S, D, Attr);
4507     break;
4508   case AttributeList::AT_ReleaseCapability:
4509     handleReleaseCapabilityAttr(S, D, Attr);
4510     break;
4511   case AttributeList::AT_TryAcquireCapability:
4512     handleTryAcquireCapabilityAttr(S, D, Attr);
4513     break;
4514 
4515   // Consumed analysis attributes.
4516   case AttributeList::AT_Consumable:
4517     handleConsumableAttr(S, D, Attr);
4518     break;
4519   case AttributeList::AT_ConsumableAutoCast:
4520     handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
4521     break;
4522   case AttributeList::AT_ConsumableSetOnRead:
4523     handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
4524     break;
4525   case AttributeList::AT_CallableWhen:
4526     handleCallableWhenAttr(S, D, Attr);
4527     break;
4528   case AttributeList::AT_ParamTypestate:
4529     handleParamTypestateAttr(S, D, Attr);
4530     break;
4531   case AttributeList::AT_ReturnTypestate:
4532     handleReturnTypestateAttr(S, D, Attr);
4533     break;
4534   case AttributeList::AT_SetTypestate:
4535     handleSetTypestateAttr(S, D, Attr);
4536     break;
4537   case AttributeList::AT_TestTypestate:
4538     handleTestTypestateAttr(S, D, Attr);
4539     break;
4540 
4541   // Type safety attributes.
4542   case AttributeList::AT_ArgumentWithTypeTag:
4543     handleArgumentWithTypeTagAttr(S, D, Attr);
4544     break;
4545   case AttributeList::AT_TypeTagForDatatype:
4546     handleTypeTagForDatatypeAttr(S, D, Attr);
4547     break;
4548   }
4549 }
4550 
4551 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4552 /// attribute list to the specified decl, ignoring any type attributes.
4553 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4554                                     const AttributeList *AttrList,
4555                                     bool IncludeCXX11Attributes) {
4556   for (const AttributeList* l = AttrList; l; l = l->getNext())
4557     ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4558 
4559   // FIXME: We should be able to handle these cases in TableGen.
4560   // GCC accepts
4561   // static int a9 __attribute__((weakref));
4562   // but that looks really pointless. We reject it.
4563   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4564     Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
4565       << cast<NamedDecl>(D);
4566     D->dropAttr<WeakRefAttr>();
4567     return;
4568   }
4569 
4570   if (!D->hasAttr<OpenCLKernelAttr>()) {
4571     // These attributes cannot be applied to a non-kernel function.
4572     if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
4573       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4574       D->setInvalidDecl();
4575     }
4576     if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
4577       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4578       D->setInvalidDecl();
4579     }
4580     if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
4581       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4582       D->setInvalidDecl();
4583     }
4584   }
4585 }
4586 
4587 // Annotation attributes are the only attributes allowed after an access
4588 // specifier.
4589 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4590                                           const AttributeList *AttrList) {
4591   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4592     if (l->getKind() == AttributeList::AT_Annotate) {
4593       handleAnnotateAttr(*this, ASDecl, *l);
4594     } else {
4595       Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4596       return true;
4597     }
4598   }
4599 
4600   return false;
4601 }
4602 
4603 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4604 /// contains any decl attributes that we should warn about.
4605 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4606   for ( ; A; A = A->getNext()) {
4607     // Only warn if the attribute is an unignored, non-type attribute.
4608     if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4609     if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4610 
4611     if (A->getKind() == AttributeList::UnknownAttribute) {
4612       S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4613         << A->getName() << A->getRange();
4614     } else {
4615       S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4616         << A->getName() << A->getRange();
4617     }
4618   }
4619 }
4620 
4621 /// checkUnusedDeclAttributes - Given a declarator which is not being
4622 /// used to build a declaration, complain about any decl attributes
4623 /// which might be lying around on it.
4624 void Sema::checkUnusedDeclAttributes(Declarator &D) {
4625   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4626   ::checkUnusedDeclAttributes(*this, D.getAttributes());
4627   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4628     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4629 }
4630 
4631 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
4632 /// \#pragma weak needs a non-definition decl and source may not have one.
4633 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4634                                       SourceLocation Loc) {
4635   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4636   NamedDecl *NewD = nullptr;
4637   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4638     FunctionDecl *NewFD;
4639     // FIXME: Missing call to CheckFunctionDeclaration().
4640     // FIXME: Mangling?
4641     // FIXME: Is the qualifier info correct?
4642     // FIXME: Is the DeclContext correct?
4643     NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4644                                  Loc, Loc, DeclarationName(II),
4645                                  FD->getType(), FD->getTypeSourceInfo(),
4646                                  SC_None, false/*isInlineSpecified*/,
4647                                  FD->hasPrototype(),
4648                                  false/*isConstexprSpecified*/);
4649     NewD = NewFD;
4650 
4651     if (FD->getQualifier())
4652       NewFD->setQualifierInfo(FD->getQualifierLoc());
4653 
4654     // Fake up parameter variables; they are declared as if this were
4655     // a typedef.
4656     QualType FDTy = FD->getType();
4657     if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4658       SmallVector<ParmVarDecl*, 16> Params;
4659       for (const auto &AI : FT->param_types()) {
4660         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
4661         Param->setScopeInfo(0, Params.size());
4662         Params.push_back(Param);
4663       }
4664       NewFD->setParams(Params);
4665     }
4666   } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4667     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4668                            VD->getInnerLocStart(), VD->getLocation(), II,
4669                            VD->getType(), VD->getTypeSourceInfo(),
4670                            VD->getStorageClass());
4671     if (VD->getQualifier()) {
4672       VarDecl *NewVD = cast<VarDecl>(NewD);
4673       NewVD->setQualifierInfo(VD->getQualifierLoc());
4674     }
4675   }
4676   return NewD;
4677 }
4678 
4679 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4680 /// applied to it, possibly with an alias.
4681 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4682   if (W.getUsed()) return; // only do this once
4683   W.setUsed(true);
4684   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4685     IdentifierInfo *NDId = ND->getIdentifier();
4686     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4687     NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
4688                                             W.getLocation()));
4689     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4690     WeakTopLevelDecl.push_back(NewD);
4691     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4692     // to insert Decl at TU scope, sorry.
4693     DeclContext *SavedContext = CurContext;
4694     CurContext = Context.getTranslationUnitDecl();
4695     NewD->setDeclContext(CurContext);
4696     NewD->setLexicalDeclContext(CurContext);
4697     PushOnScopeChains(NewD, S);
4698     CurContext = SavedContext;
4699   } else { // just add weak to existing
4700     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4701   }
4702 }
4703 
4704 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
4705   // It's valid to "forward-declare" #pragma weak, in which case we
4706   // have to do this.
4707   LoadExternalWeakUndeclaredIdentifiers();
4708   if (!WeakUndeclaredIdentifiers.empty()) {
4709     NamedDecl *ND = nullptr;
4710     if (VarDecl *VD = dyn_cast<VarDecl>(D))
4711       if (VD->isExternC())
4712         ND = VD;
4713     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4714       if (FD->isExternC())
4715         ND = FD;
4716     if (ND) {
4717       if (IdentifierInfo *Id = ND->getIdentifier()) {
4718         llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4719           = WeakUndeclaredIdentifiers.find(Id);
4720         if (I != WeakUndeclaredIdentifiers.end()) {
4721           WeakInfo W = I->second;
4722           DeclApplyPragmaWeak(S, ND, W);
4723           WeakUndeclaredIdentifiers[Id] = W;
4724         }
4725       }
4726     }
4727   }
4728 }
4729 
4730 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4731 /// it, apply them to D.  This is a bit tricky because PD can have attributes
4732 /// specified in many different places, and we need to find and apply them all.
4733 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
4734   // Apply decl attributes from the DeclSpec if present.
4735   if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4736     ProcessDeclAttributeList(S, D, Attrs);
4737 
4738   // Walk the declarator structure, applying decl attributes that were in a type
4739   // position to the decl itself.  This handles cases like:
4740   //   int *__attr__(x)** D;
4741   // when X is a decl attribute.
4742   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
4743     if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
4744       ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
4745 
4746   // Finally, apply any attributes on the decl itself.
4747   if (const AttributeList *Attrs = PD.getAttributes())
4748     ProcessDeclAttributeList(S, D, Attrs);
4749 }
4750 
4751 /// Is the given declaration allowed to use a forbidden type?
4752 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
4753   // Private ivars are always okay.  Unfortunately, people don't
4754   // always properly make their ivars private, even in system headers.
4755   // Plus we need to make fields okay, too.
4756   // Function declarations in sys headers will be marked unavailable.
4757   if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
4758       !isa<FunctionDecl>(decl))
4759     return false;
4760 
4761   // Require it to be declared in a system header.
4762   return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
4763 }
4764 
4765 /// Handle a delayed forbidden-type diagnostic.
4766 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
4767                                        Decl *decl) {
4768   if (decl && isForbiddenTypeAllowed(S, decl)) {
4769     decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
4770                         "this system declaration uses an unsupported type",
4771                         diag.Loc));
4772     return;
4773   }
4774   if (S.getLangOpts().ObjCAutoRefCount)
4775     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
4776       // FIXME: we may want to suppress diagnostics for all
4777       // kind of forbidden type messages on unavailable functions.
4778       if (FD->hasAttr<UnavailableAttr>() &&
4779           diag.getForbiddenTypeDiagnostic() ==
4780           diag::err_arc_array_param_no_ownership) {
4781         diag.Triggered = true;
4782         return;
4783       }
4784     }
4785 
4786   S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
4787     << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
4788   diag.Triggered = true;
4789 }
4790 
4791 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
4792   assert(DelayedDiagnostics.getCurrentPool());
4793   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
4794   DelayedDiagnostics.popWithoutEmitting(state);
4795 
4796   // When delaying diagnostics to run in the context of a parsed
4797   // declaration, we only want to actually emit anything if parsing
4798   // succeeds.
4799   if (!decl) return;
4800 
4801   // We emit all the active diagnostics in this pool or any of its
4802   // parents.  In general, we'll get one pool for the decl spec
4803   // and a child pool for each declarator; in a decl group like:
4804   //   deprecated_typedef foo, *bar, baz();
4805   // only the declarator pops will be passed decls.  This is correct;
4806   // we really do need to consider delayed diagnostics from the decl spec
4807   // for each of the different declarations.
4808   const DelayedDiagnosticPool *pool = &poppedPool;
4809   do {
4810     for (DelayedDiagnosticPool::pool_iterator
4811            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
4812       // This const_cast is a bit lame.  Really, Triggered should be mutable.
4813       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
4814       if (diag.Triggered)
4815         continue;
4816 
4817       switch (diag.Kind) {
4818       case DelayedDiagnostic::Deprecation:
4819       case DelayedDiagnostic::Unavailable:
4820         // Don't bother giving deprecation/unavailable diagnostics if
4821         // the decl is invalid.
4822         if (!decl->isInvalidDecl())
4823           HandleDelayedAvailabilityCheck(diag, decl);
4824         break;
4825 
4826       case DelayedDiagnostic::Access:
4827         HandleDelayedAccessCheck(diag, decl);
4828         break;
4829 
4830       case DelayedDiagnostic::ForbiddenType:
4831         handleDelayedForbiddenType(*this, diag, decl);
4832         break;
4833       }
4834     }
4835   } while ((pool = pool->getParent()));
4836 }
4837 
4838 /// Given a set of delayed diagnostics, re-emit them as if they had
4839 /// been delayed in the current context instead of in the given pool.
4840 /// Essentially, this just moves them to the current pool.
4841 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
4842   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
4843   assert(curPool && "re-emitting in undelayed context not supported");
4844   curPool->steal(pool);
4845 }
4846 
4847 static bool isDeclDeprecated(Decl *D) {
4848   do {
4849     if (D->isDeprecated())
4850       return true;
4851     // A category implicitly has the availability of the interface.
4852     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4853       return CatD->getClassInterface()->isDeprecated();
4854   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4855   return false;
4856 }
4857 
4858 static bool isDeclUnavailable(Decl *D) {
4859   do {
4860     if (D->isUnavailable())
4861       return true;
4862     // A category implicitly has the availability of the interface.
4863     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4864       return CatD->getClassInterface()->isUnavailable();
4865   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4866   return false;
4867 }
4868 
4869 static void
4870 DoEmitAvailabilityWarning(Sema &S,
4871                           DelayedDiagnostic::DDKind K,
4872                           Decl *Ctx,
4873                           const NamedDecl *D,
4874                           StringRef Message,
4875                           SourceLocation Loc,
4876                           const ObjCInterfaceDecl *UnknownObjCClass,
4877                           const ObjCPropertyDecl *ObjCProperty,
4878                           bool ObjCPropertyAccess) {
4879 
4880   // Diagnostics for deprecated or unavailable.
4881   unsigned diag, diag_message, diag_fwdclass_message;
4882 
4883   // Matches 'diag::note_property_attribute' options.
4884   unsigned property_note_select;
4885 
4886   // Matches diag::note_availability_specified_here.
4887   unsigned available_here_select_kind;
4888 
4889   // Don't warn if our current context is deprecated or unavailable.
4890   switch (K) {
4891     case DelayedDiagnostic::Deprecation:
4892       if (isDeclDeprecated(Ctx))
4893         return;
4894       diag = !ObjCPropertyAccess ? diag::warn_deprecated
4895                                  : diag::warn_property_method_deprecated;
4896       diag_message = diag::warn_deprecated_message;
4897       diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
4898       property_note_select = /* deprecated */ 0;
4899       available_here_select_kind = /* deprecated */ 2;
4900       break;
4901 
4902     case DelayedDiagnostic::Unavailable:
4903       if (isDeclUnavailable(Ctx))
4904         return;
4905       diag = !ObjCPropertyAccess ? diag::err_unavailable
4906                                  : diag::err_property_method_unavailable;
4907       diag_message = diag::err_unavailable_message;
4908       diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
4909       property_note_select = /* unavailable */ 1;
4910       available_here_select_kind = /* unavailable */ 0;
4911       break;
4912 
4913     default:
4914       llvm_unreachable("Neither a deprecation or unavailable kind");
4915   }
4916 
4917   DeclarationName Name = D->getDeclName();
4918   if (!Message.empty()) {
4919     S.Diag(Loc, diag_message) << Name << Message;
4920     if (ObjCProperty)
4921       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
4922         << ObjCProperty->getDeclName() << property_note_select;
4923   } else if (!UnknownObjCClass) {
4924     S.Diag(Loc, diag) << Name;
4925     if (ObjCProperty)
4926       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
4927         << ObjCProperty->getDeclName() << property_note_select;
4928   } else {
4929     S.Diag(Loc, diag_fwdclass_message) << Name;
4930     S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
4931   }
4932 
4933   S.Diag(D->getLocation(), diag::note_availability_specified_here)
4934     << D << available_here_select_kind;
4935 }
4936 
4937 void Sema::HandleDelayedAvailabilityCheck(DelayedDiagnostic &DD,
4938                                           Decl *Ctx) {
4939   DD.Triggered = true;
4940   DoEmitAvailabilityWarning(*this,
4941                             (DelayedDiagnostic::DDKind) DD.Kind,
4942                             Ctx,
4943                             DD.getDeprecationDecl(),
4944                             DD.getDeprecationMessage(),
4945                             DD.Loc,
4946                             DD.getUnknownObjCClass(),
4947                             DD.getObjCProperty(), false);
4948 }
4949 
4950 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
4951                                    NamedDecl *D, StringRef Message,
4952                                    SourceLocation Loc,
4953                                    const ObjCInterfaceDecl *UnknownObjCClass,
4954                                    const ObjCPropertyDecl  *ObjCProperty,
4955                                    bool ObjCPropertyAccess) {
4956   // Delay if we're currently parsing a declaration.
4957   if (DelayedDiagnostics.shouldDelayDiagnostics()) {
4958     DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(AD, Loc, D,
4959                                                                UnknownObjCClass,
4960                                                                ObjCProperty,
4961                                                                Message,
4962                                                                ObjCPropertyAccess));
4963     return;
4964   }
4965 
4966   Decl *Ctx = cast<Decl>(getCurLexicalContext());
4967   DelayedDiagnostic::DDKind K;
4968   switch (AD) {
4969     case AD_Deprecation:
4970       K = DelayedDiagnostic::Deprecation;
4971       break;
4972     case AD_Unavailable:
4973       K = DelayedDiagnostic::Unavailable;
4974       break;
4975   }
4976 
4977   DoEmitAvailabilityWarning(*this, K, Ctx, D, Message, Loc,
4978                             UnknownObjCClass, ObjCProperty, ObjCPropertyAccess);
4979 }
4980