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