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