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