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