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