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 (const auto *I : UD->fields()) {
1108         QualType QT = I->getType();
1109         if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
1110           T = QT;
1111           return;
1112         }
1113       }
1114     }
1115 }
1116 
1117 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1118                                 SourceRange R, bool isReturnValue = false) {
1119   T = T.getNonReferenceType();
1120   possibleTransparentUnionPointerType(T);
1121 
1122   if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1123     S.Diag(Attr.getLoc(),
1124            isReturnValue ? diag::warn_attribute_return_pointers_only
1125                          : diag::warn_attribute_pointers_only)
1126       << Attr.getName() << R;
1127     return false;
1128   }
1129   return true;
1130 }
1131 
1132 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1133   SmallVector<unsigned, 8> NonNullArgs;
1134   for (unsigned i = 0; i < Attr.getNumArgs(); ++i) {
1135     Expr *Ex = Attr.getArgAsExpr(i);
1136     uint64_t Idx;
1137     if (!checkFunctionOrMethodParameterIndex(S, D, Attr, i + 1, Ex, Idx))
1138       return;
1139 
1140     // Is the function argument a pointer type?
1141     // FIXME: Should also highlight argument in decl in the diagnostic.
1142     if (!attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1143                              Ex->getSourceRange()))
1144       continue;
1145 
1146     NonNullArgs.push_back(Idx);
1147   }
1148 
1149   // If no arguments were specified to __attribute__((nonnull)) then all pointer
1150   // arguments have a nonnull attribute.
1151   if (NonNullArgs.empty()) {
1152     for (unsigned i = 0, e = getFunctionOrMethodNumParams(D); i != e; ++i) {
1153       QualType T = getFunctionOrMethodParamType(D, i).getNonReferenceType();
1154       possibleTransparentUnionPointerType(T);
1155       if (T->isAnyPointerType() || T->isBlockPointerType())
1156         NonNullArgs.push_back(i);
1157     }
1158 
1159     // No pointer arguments?
1160     if (NonNullArgs.empty()) {
1161       // Warn the trivial case only if attribute is not coming from a
1162       // macro instantiation.
1163       if (Attr.getLoc().isFileID())
1164         S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1165       return;
1166     }
1167   }
1168 
1169   unsigned *start = &NonNullArgs[0];
1170   unsigned size = NonNullArgs.size();
1171   llvm::array_pod_sort(start, start + size);
1172   D->addAttr(::new (S.Context)
1173              NonNullAttr(Attr.getRange(), S.Context, start, size,
1174                          Attr.getAttributeSpellingListIndex()));
1175 }
1176 
1177 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1178                                        const AttributeList &Attr) {
1179   if (Attr.getNumArgs() > 0) {
1180     if (D->getFunctionType()) {
1181       handleNonNullAttr(S, D, Attr);
1182     } else {
1183       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1184         << D->getSourceRange();
1185     }
1186     return;
1187   }
1188 
1189   // Is the argument a pointer type?
1190   if (!attrNonNullArgCheck(S, D->getType(), Attr, D->getSourceRange()))
1191     return;
1192 
1193   D->addAttr(::new (S.Context)
1194              NonNullAttr(Attr.getRange(), S.Context, 0, 0,
1195                          Attr.getAttributeSpellingListIndex()));
1196 }
1197 
1198 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1199                                      const AttributeList &Attr) {
1200   QualType ResultType = getFunctionOrMethodResultType(D);
1201   if (!attrNonNullArgCheck(S, ResultType, Attr, Attr.getRange(),
1202                            /* isReturnValue */ true))
1203     return;
1204 
1205   D->addAttr(::new (S.Context)
1206             ReturnsNonNullAttr(Attr.getRange(), S.Context,
1207                                Attr.getAttributeSpellingListIndex()));
1208 }
1209 
1210 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1211   // This attribute must be applied to a function declaration. The first
1212   // argument to the attribute must be an identifier, the name of the resource,
1213   // for example: malloc. The following arguments must be argument indexes, the
1214   // arguments must be of integer type for Returns, otherwise of pointer type.
1215   // The difference between Holds and Takes is that a pointer may still be used
1216   // after being held. free() should be __attribute((ownership_takes)), whereas
1217   // a list append function may well be __attribute((ownership_holds)).
1218 
1219   if (!AL.isArgIdent(0)) {
1220     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1221       << AL.getName() << 1 << AANT_ArgumentIdentifier;
1222     return;
1223   }
1224 
1225   // Figure out our Kind.
1226   OwnershipAttr::OwnershipKind K =
1227       OwnershipAttr(AL.getLoc(), S.Context, 0, 0, 0,
1228                     AL.getAttributeSpellingListIndex()).getOwnKind();
1229 
1230   // Check arguments.
1231   switch (K) {
1232   case OwnershipAttr::Takes:
1233   case OwnershipAttr::Holds:
1234     if (AL.getNumArgs() < 2) {
1235       S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1236         << AL.getName() << 2;
1237       return;
1238     }
1239     break;
1240   case OwnershipAttr::Returns:
1241     if (AL.getNumArgs() > 2) {
1242       S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1243         << AL.getName() << 1;
1244       return;
1245     }
1246     break;
1247   }
1248 
1249   IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1250 
1251   // Normalize the argument, __foo__ becomes foo.
1252   StringRef ModuleName = Module->getName();
1253   if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1254       ModuleName.size() > 4) {
1255     ModuleName = ModuleName.drop_front(2).drop_back(2);
1256     Module = &S.PP.getIdentifierTable().get(ModuleName);
1257   }
1258 
1259   SmallVector<unsigned, 8> OwnershipArgs;
1260   for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1261     Expr *Ex = AL.getArgAsExpr(i);
1262     uint64_t Idx;
1263     if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1264       return;
1265 
1266     // Is the function argument a pointer type?
1267     QualType T = getFunctionOrMethodParamType(D, Idx);
1268     int Err = -1;  // No error
1269     switch (K) {
1270       case OwnershipAttr::Takes:
1271       case OwnershipAttr::Holds:
1272         if (!T->isAnyPointerType() && !T->isBlockPointerType())
1273           Err = 0;
1274         break;
1275       case OwnershipAttr::Returns:
1276         if (!T->isIntegerType())
1277           Err = 1;
1278         break;
1279     }
1280     if (-1 != Err) {
1281       S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1282         << Ex->getSourceRange();
1283       return;
1284     }
1285 
1286     // Check we don't have a conflict with another ownership attribute.
1287     for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1288       // FIXME: A returns attribute should conflict with any returns attribute
1289       // with a different index too.
1290       if (I->getOwnKind() != K && I->args_end() !=
1291           std::find(I->args_begin(), I->args_end(), Idx)) {
1292         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1293           << AL.getName() << I;
1294         return;
1295       }
1296     }
1297     OwnershipArgs.push_back(Idx);
1298   }
1299 
1300   unsigned* start = OwnershipArgs.data();
1301   unsigned size = OwnershipArgs.size();
1302   llvm::array_pod_sort(start, start + size);
1303 
1304   D->addAttr(::new (S.Context)
1305              OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1306                            AL.getAttributeSpellingListIndex()));
1307 }
1308 
1309 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1310   // Check the attribute arguments.
1311   if (Attr.getNumArgs() > 1) {
1312     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1313       << Attr.getName() << 1;
1314     return;
1315   }
1316 
1317   NamedDecl *nd = cast<NamedDecl>(D);
1318 
1319   // gcc rejects
1320   // class c {
1321   //   static int a __attribute__((weakref ("v2")));
1322   //   static int b() __attribute__((weakref ("f3")));
1323   // };
1324   // and ignores the attributes of
1325   // void f(void) {
1326   //   static int a __attribute__((weakref ("v2")));
1327   // }
1328   // we reject them
1329   const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1330   if (!Ctx->isFileContext()) {
1331     S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1332       << nd;
1333     return;
1334   }
1335 
1336   // The GCC manual says
1337   //
1338   // At present, a declaration to which `weakref' is attached can only
1339   // be `static'.
1340   //
1341   // It also says
1342   //
1343   // Without a TARGET,
1344   // given as an argument to `weakref' or to `alias', `weakref' is
1345   // equivalent to `weak'.
1346   //
1347   // gcc 4.4.1 will accept
1348   // int a7 __attribute__((weakref));
1349   // as
1350   // int a7 __attribute__((weak));
1351   // This looks like a bug in gcc. We reject that for now. We should revisit
1352   // it if this behaviour is actually used.
1353 
1354   // GCC rejects
1355   // static ((alias ("y"), weakref)).
1356   // Should we? How to check that weakref is before or after alias?
1357 
1358   // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1359   // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1360   // StringRef parameter it was given anyway.
1361   StringRef Str;
1362   if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1363     // GCC will accept anything as the argument of weakref. Should we
1364     // check for an existing decl?
1365     D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1366                                         Attr.getAttributeSpellingListIndex()));
1367 
1368   D->addAttr(::new (S.Context)
1369              WeakRefAttr(Attr.getRange(), S.Context,
1370                          Attr.getAttributeSpellingListIndex()));
1371 }
1372 
1373 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1374   StringRef Str;
1375   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1376     return;
1377 
1378   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1379     S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1380     return;
1381   }
1382 
1383   // FIXME: check if target symbol exists in current file
1384 
1385   D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1386                                          Attr.getAttributeSpellingListIndex()));
1387 }
1388 
1389 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1390   if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1391     return;
1392 
1393   D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1394                                         Attr.getAttributeSpellingListIndex()));
1395 }
1396 
1397 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1398   if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1399     return;
1400 
1401   D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1402                                        Attr.getAttributeSpellingListIndex()));
1403 }
1404 
1405 static void handleTLSModelAttr(Sema &S, Decl *D,
1406                                const AttributeList &Attr) {
1407   StringRef Model;
1408   SourceLocation LiteralLoc;
1409   // Check that it is a string.
1410   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1411     return;
1412 
1413   // Check that the value.
1414   if (Model != "global-dynamic" && Model != "local-dynamic"
1415       && Model != "initial-exec" && Model != "local-exec") {
1416     S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1417     return;
1418   }
1419 
1420   D->addAttr(::new (S.Context)
1421              TLSModelAttr(Attr.getRange(), S.Context, Model,
1422                           Attr.getAttributeSpellingListIndex()));
1423 }
1424 
1425 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1426   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1427     QualType RetTy = FD->getReturnType();
1428     if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1429       D->addAttr(::new (S.Context)
1430                  MallocAttr(Attr.getRange(), S.Context,
1431                             Attr.getAttributeSpellingListIndex()));
1432       return;
1433     }
1434   }
1435 
1436   S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1437 }
1438 
1439 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1440   if (S.LangOpts.CPlusPlus) {
1441     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1442       << Attr.getName() << AttributeLangSupport::Cpp;
1443     return;
1444   }
1445 
1446   D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1447                                         Attr.getAttributeSpellingListIndex()));
1448 }
1449 
1450 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1451   if (hasDeclarator(D)) return;
1452 
1453   if (S.CheckNoReturnAttr(attr)) return;
1454 
1455   if (!isa<ObjCMethodDecl>(D)) {
1456     S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1457       << attr.getName() << ExpectedFunctionOrMethod;
1458     return;
1459   }
1460 
1461   D->addAttr(::new (S.Context)
1462              NoReturnAttr(attr.getRange(), S.Context,
1463                           attr.getAttributeSpellingListIndex()));
1464 }
1465 
1466 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1467   if (!checkAttributeNumArgs(*this, attr, 0)) {
1468     attr.setInvalid();
1469     return true;
1470   }
1471 
1472   return false;
1473 }
1474 
1475 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1476                                        const AttributeList &Attr) {
1477 
1478   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1479   // because 'analyzer_noreturn' does not impact the type.
1480   if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1481     ValueDecl *VD = dyn_cast<ValueDecl>(D);
1482     if (VD == 0 || (!VD->getType()->isBlockPointerType()
1483                     && !VD->getType()->isFunctionPointerType())) {
1484       S.Diag(Attr.getLoc(),
1485              Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1486              : diag::warn_attribute_wrong_decl_type)
1487         << Attr.getName() << ExpectedFunctionMethodOrBlock;
1488       return;
1489     }
1490   }
1491 
1492   D->addAttr(::new (S.Context)
1493              AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1494                                   Attr.getAttributeSpellingListIndex()));
1495 }
1496 
1497 // PS3 PPU-specific.
1498 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1499 /*
1500   Returning a Vector Class in Registers
1501 
1502   According to the PPU ABI specifications, a class with a single member of
1503   vector type is returned in memory when used as the return value of a function.
1504   This results in inefficient code when implementing vector classes. To return
1505   the value in a single vector register, add the vecreturn attribute to the
1506   class definition. This attribute is also applicable to struct types.
1507 
1508   Example:
1509 
1510   struct Vector
1511   {
1512     __vector float xyzw;
1513   } __attribute__((vecreturn));
1514 
1515   Vector Add(Vector lhs, Vector rhs)
1516   {
1517     Vector result;
1518     result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1519     return result; // This will be returned in a register
1520   }
1521 */
1522   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1523     S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1524     return;
1525   }
1526 
1527   RecordDecl *record = cast<RecordDecl>(D);
1528   int count = 0;
1529 
1530   if (!isa<CXXRecordDecl>(record)) {
1531     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1532     return;
1533   }
1534 
1535   if (!cast<CXXRecordDecl>(record)->isPOD()) {
1536     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1537     return;
1538   }
1539 
1540   for (const auto *I : record->fields()) {
1541     if ((count == 1) || !I->getType()->isVectorType()) {
1542       S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1543       return;
1544     }
1545     count++;
1546   }
1547 
1548   D->addAttr(::new (S.Context)
1549              VecReturnAttr(Attr.getRange(), S.Context,
1550                            Attr.getAttributeSpellingListIndex()));
1551 }
1552 
1553 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1554                                  const AttributeList &Attr) {
1555   if (isa<ParmVarDecl>(D)) {
1556     // [[carries_dependency]] can only be applied to a parameter if it is a
1557     // parameter of a function declaration or lambda.
1558     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1559       S.Diag(Attr.getLoc(),
1560              diag::err_carries_dependency_param_not_function_decl);
1561       return;
1562     }
1563   }
1564 
1565   D->addAttr(::new (S.Context) CarriesDependencyAttr(
1566                                    Attr.getRange(), S.Context,
1567                                    Attr.getAttributeSpellingListIndex()));
1568 }
1569 
1570 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1571   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1572     if (VD->hasLocalStorage()) {
1573       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1574       return;
1575     }
1576   } else if (!isFunctionOrMethod(D)) {
1577     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1578       << Attr.getName() << ExpectedVariableOrFunction;
1579     return;
1580   }
1581 
1582   D->addAttr(::new (S.Context)
1583              UsedAttr(Attr.getRange(), S.Context,
1584                       Attr.getAttributeSpellingListIndex()));
1585 }
1586 
1587 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1588   // check the attribute arguments.
1589   if (Attr.getNumArgs() > 1) {
1590     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
1591       << Attr.getName() << 1;
1592     return;
1593   }
1594 
1595   uint32_t priority = ConstructorAttr::DefaultPriority;
1596   if (Attr.getNumArgs() > 0 &&
1597       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1598     return;
1599 
1600   D->addAttr(::new (S.Context)
1601              ConstructorAttr(Attr.getRange(), S.Context, priority,
1602                              Attr.getAttributeSpellingListIndex()));
1603 }
1604 
1605 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1606   // check the attribute arguments.
1607   if (Attr.getNumArgs() > 1) {
1608     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
1609       << Attr.getName() << 1;
1610     return;
1611   }
1612 
1613   uint32_t priority = DestructorAttr::DefaultPriority;
1614   if (Attr.getNumArgs() > 0 &&
1615       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1616     return;
1617 
1618   D->addAttr(::new (S.Context)
1619              DestructorAttr(Attr.getRange(), S.Context, priority,
1620                             Attr.getAttributeSpellingListIndex()));
1621 }
1622 
1623 template <typename AttrTy>
1624 static void handleAttrWithMessage(Sema &S, Decl *D,
1625                                   const AttributeList &Attr) {
1626   unsigned NumArgs = Attr.getNumArgs();
1627   if (NumArgs > 1) {
1628     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
1629       << Attr.getName() << 1;
1630     return;
1631   }
1632 
1633   // Handle the case where the attribute has a text message.
1634   StringRef Str;
1635   if (NumArgs == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1636     return;
1637 
1638   D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1639                                       Attr.getAttributeSpellingListIndex()));
1640 }
1641 
1642 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1643                                           const AttributeList &Attr) {
1644   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1645     S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1646       << Attr.getName() << Attr.getRange();
1647     return;
1648   }
1649 
1650   D->addAttr(::new (S.Context)
1651           ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1652                                        Attr.getAttributeSpellingListIndex()));
1653 }
1654 
1655 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1656                                   IdentifierInfo *Platform,
1657                                   VersionTuple Introduced,
1658                                   VersionTuple Deprecated,
1659                                   VersionTuple Obsoleted) {
1660   StringRef PlatformName
1661     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1662   if (PlatformName.empty())
1663     PlatformName = Platform->getName();
1664 
1665   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1666   // of these steps are needed).
1667   if (!Introduced.empty() && !Deprecated.empty() &&
1668       !(Introduced <= Deprecated)) {
1669     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1670       << 1 << PlatformName << Deprecated.getAsString()
1671       << 0 << Introduced.getAsString();
1672     return true;
1673   }
1674 
1675   if (!Introduced.empty() && !Obsoleted.empty() &&
1676       !(Introduced <= Obsoleted)) {
1677     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1678       << 2 << PlatformName << Obsoleted.getAsString()
1679       << 0 << Introduced.getAsString();
1680     return true;
1681   }
1682 
1683   if (!Deprecated.empty() && !Obsoleted.empty() &&
1684       !(Deprecated <= Obsoleted)) {
1685     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1686       << 2 << PlatformName << Obsoleted.getAsString()
1687       << 1 << Deprecated.getAsString();
1688     return true;
1689   }
1690 
1691   return false;
1692 }
1693 
1694 /// \brief Check whether the two versions match.
1695 ///
1696 /// If either version tuple is empty, then they are assumed to match. If
1697 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1698 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1699                           bool BeforeIsOkay) {
1700   if (X.empty() || Y.empty())
1701     return true;
1702 
1703   if (X == Y)
1704     return true;
1705 
1706   if (BeforeIsOkay && X < Y)
1707     return true;
1708 
1709   return false;
1710 }
1711 
1712 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1713                                               IdentifierInfo *Platform,
1714                                               VersionTuple Introduced,
1715                                               VersionTuple Deprecated,
1716                                               VersionTuple Obsoleted,
1717                                               bool IsUnavailable,
1718                                               StringRef Message,
1719                                               bool Override,
1720                                               unsigned AttrSpellingListIndex) {
1721   VersionTuple MergedIntroduced = Introduced;
1722   VersionTuple MergedDeprecated = Deprecated;
1723   VersionTuple MergedObsoleted = Obsoleted;
1724   bool FoundAny = false;
1725 
1726   if (D->hasAttrs()) {
1727     AttrVec &Attrs = D->getAttrs();
1728     for (unsigned i = 0, e = Attrs.size(); i != e;) {
1729       const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1730       if (!OldAA) {
1731         ++i;
1732         continue;
1733       }
1734 
1735       IdentifierInfo *OldPlatform = OldAA->getPlatform();
1736       if (OldPlatform != Platform) {
1737         ++i;
1738         continue;
1739       }
1740 
1741       FoundAny = true;
1742       VersionTuple OldIntroduced = OldAA->getIntroduced();
1743       VersionTuple OldDeprecated = OldAA->getDeprecated();
1744       VersionTuple OldObsoleted = OldAA->getObsoleted();
1745       bool OldIsUnavailable = OldAA->getUnavailable();
1746 
1747       if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1748           !versionsMatch(Deprecated, OldDeprecated, Override) ||
1749           !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1750           !(OldIsUnavailable == IsUnavailable ||
1751             (Override && !OldIsUnavailable && IsUnavailable))) {
1752         if (Override) {
1753           int Which = -1;
1754           VersionTuple FirstVersion;
1755           VersionTuple SecondVersion;
1756           if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1757             Which = 0;
1758             FirstVersion = OldIntroduced;
1759             SecondVersion = Introduced;
1760           } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1761             Which = 1;
1762             FirstVersion = Deprecated;
1763             SecondVersion = OldDeprecated;
1764           } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1765             Which = 2;
1766             FirstVersion = Obsoleted;
1767             SecondVersion = OldObsoleted;
1768           }
1769 
1770           if (Which == -1) {
1771             Diag(OldAA->getLocation(),
1772                  diag::warn_mismatched_availability_override_unavail)
1773               << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1774           } else {
1775             Diag(OldAA->getLocation(),
1776                  diag::warn_mismatched_availability_override)
1777               << Which
1778               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1779               << FirstVersion.getAsString() << SecondVersion.getAsString();
1780           }
1781           Diag(Range.getBegin(), diag::note_overridden_method);
1782         } else {
1783           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1784           Diag(Range.getBegin(), diag::note_previous_attribute);
1785         }
1786 
1787         Attrs.erase(Attrs.begin() + i);
1788         --e;
1789         continue;
1790       }
1791 
1792       VersionTuple MergedIntroduced2 = MergedIntroduced;
1793       VersionTuple MergedDeprecated2 = MergedDeprecated;
1794       VersionTuple MergedObsoleted2 = MergedObsoleted;
1795 
1796       if (MergedIntroduced2.empty())
1797         MergedIntroduced2 = OldIntroduced;
1798       if (MergedDeprecated2.empty())
1799         MergedDeprecated2 = OldDeprecated;
1800       if (MergedObsoleted2.empty())
1801         MergedObsoleted2 = OldObsoleted;
1802 
1803       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1804                                 MergedIntroduced2, MergedDeprecated2,
1805                                 MergedObsoleted2)) {
1806         Attrs.erase(Attrs.begin() + i);
1807         --e;
1808         continue;
1809       }
1810 
1811       MergedIntroduced = MergedIntroduced2;
1812       MergedDeprecated = MergedDeprecated2;
1813       MergedObsoleted = MergedObsoleted2;
1814       ++i;
1815     }
1816   }
1817 
1818   if (FoundAny &&
1819       MergedIntroduced == Introduced &&
1820       MergedDeprecated == Deprecated &&
1821       MergedObsoleted == Obsoleted)
1822     return NULL;
1823 
1824   // Only create a new attribute if !Override, but we want to do
1825   // the checking.
1826   if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1827                              MergedDeprecated, MergedObsoleted) &&
1828       !Override) {
1829     return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1830                                             Introduced, Deprecated,
1831                                             Obsoleted, IsUnavailable, Message,
1832                                             AttrSpellingListIndex);
1833   }
1834   return NULL;
1835 }
1836 
1837 static void handleAvailabilityAttr(Sema &S, Decl *D,
1838                                    const AttributeList &Attr) {
1839   if (!checkAttributeNumArgs(S, Attr, 1))
1840     return;
1841   IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1842   unsigned Index = Attr.getAttributeSpellingListIndex();
1843 
1844   IdentifierInfo *II = Platform->Ident;
1845   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1846     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1847       << Platform->Ident;
1848 
1849   NamedDecl *ND = dyn_cast<NamedDecl>(D);
1850   if (!ND) {
1851     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1852     return;
1853   }
1854 
1855   AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1856   AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1857   AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1858   bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1859   StringRef Str;
1860   if (const StringLiteral *SE =
1861           dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1862     Str = SE->getString();
1863 
1864   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1865                                                       Introduced.Version,
1866                                                       Deprecated.Version,
1867                                                       Obsoleted.Version,
1868                                                       IsUnavailable, Str,
1869                                                       /*Override=*/false,
1870                                                       Index);
1871   if (NewAttr)
1872     D->addAttr(NewAttr);
1873 }
1874 
1875 template <class T>
1876 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1877                               typename T::VisibilityType value,
1878                               unsigned attrSpellingListIndex) {
1879   T *existingAttr = D->getAttr<T>();
1880   if (existingAttr) {
1881     typename T::VisibilityType existingValue = existingAttr->getVisibility();
1882     if (existingValue == value)
1883       return NULL;
1884     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
1885     S.Diag(range.getBegin(), diag::note_previous_attribute);
1886     D->dropAttr<T>();
1887   }
1888   return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
1889 }
1890 
1891 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
1892                                           VisibilityAttr::VisibilityType Vis,
1893                                           unsigned AttrSpellingListIndex) {
1894   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
1895                                                AttrSpellingListIndex);
1896 }
1897 
1898 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1899                                       TypeVisibilityAttr::VisibilityType Vis,
1900                                       unsigned AttrSpellingListIndex) {
1901   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
1902                                                    AttrSpellingListIndex);
1903 }
1904 
1905 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
1906                                  bool isTypeVisibility) {
1907   // Visibility attributes don't mean anything on a typedef.
1908   if (isa<TypedefNameDecl>(D)) {
1909     S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
1910       << Attr.getName();
1911     return;
1912   }
1913 
1914   // 'type_visibility' can only go on a type or namespace.
1915   if (isTypeVisibility &&
1916       !(isa<TagDecl>(D) ||
1917         isa<ObjCInterfaceDecl>(D) ||
1918         isa<NamespaceDecl>(D))) {
1919     S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
1920       << Attr.getName() << ExpectedTypeOrNamespace;
1921     return;
1922   }
1923 
1924   // Check that the argument is a string literal.
1925   StringRef TypeStr;
1926   SourceLocation LiteralLoc;
1927   if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
1928     return;
1929 
1930   VisibilityAttr::VisibilityType type;
1931   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
1932     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
1933       << Attr.getName() << TypeStr;
1934     return;
1935   }
1936 
1937   // Complain about attempts to use protected visibility on targets
1938   // (like Darwin) that don't support it.
1939   if (type == VisibilityAttr::Protected &&
1940       !S.Context.getTargetInfo().hasProtectedVisibility()) {
1941     S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
1942     type = VisibilityAttr::Default;
1943   }
1944 
1945   unsigned Index = Attr.getAttributeSpellingListIndex();
1946   clang::Attr *newAttr;
1947   if (isTypeVisibility) {
1948     newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
1949                                     (TypeVisibilityAttr::VisibilityType) type,
1950                                         Index);
1951   } else {
1952     newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
1953   }
1954   if (newAttr)
1955     D->addAttr(newAttr);
1956 }
1957 
1958 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
1959                                        const AttributeList &Attr) {
1960   ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
1961   if (!Attr.isArgIdent(0)) {
1962     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
1963       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
1964     return;
1965   }
1966 
1967   IdentifierLoc *IL = Attr.getArgAsIdent(0);
1968   ObjCMethodFamilyAttr::FamilyKind F;
1969   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
1970     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
1971       << IL->Ident;
1972     return;
1973   }
1974 
1975   if (F == ObjCMethodFamilyAttr::OMF_init &&
1976       !method->getReturnType()->isObjCObjectPointerType()) {
1977     S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
1978         << method->getReturnType();
1979     // Ignore the attribute.
1980     return;
1981   }
1982 
1983   method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
1984                                                        S.Context, F,
1985                                         Attr.getAttributeSpellingListIndex()));
1986 }
1987 
1988 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
1989   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1990     QualType T = TD->getUnderlyingType();
1991     if (!T->isCARCBridgableType()) {
1992       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
1993       return;
1994     }
1995   }
1996   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1997     QualType T = PD->getType();
1998     if (!T->isCARCBridgableType()) {
1999       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2000       return;
2001     }
2002   }
2003   else {
2004     // It is okay to include this attribute on properties, e.g.:
2005     //
2006     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2007     //
2008     // In this case it follows tradition and suppresses an error in the above
2009     // case.
2010     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2011   }
2012   D->addAttr(::new (S.Context)
2013              ObjCNSObjectAttr(Attr.getRange(), S.Context,
2014                               Attr.getAttributeSpellingListIndex()));
2015 }
2016 
2017 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2018   if (!Attr.isArgIdent(0)) {
2019     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2020       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2021     return;
2022   }
2023 
2024   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2025   BlocksAttr::BlockType type;
2026   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2027     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2028       << Attr.getName() << II;
2029     return;
2030   }
2031 
2032   D->addAttr(::new (S.Context)
2033              BlocksAttr(Attr.getRange(), S.Context, type,
2034                         Attr.getAttributeSpellingListIndex()));
2035 }
2036 
2037 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2038   // check the attribute arguments.
2039   if (Attr.getNumArgs() > 2) {
2040     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
2041       << Attr.getName() << 2;
2042     return;
2043   }
2044 
2045   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2046   if (Attr.getNumArgs() > 0) {
2047     Expr *E = Attr.getArgAsExpr(0);
2048     llvm::APSInt Idx(32);
2049     if (E->isTypeDependent() || E->isValueDependent() ||
2050         !E->isIntegerConstantExpr(Idx, S.Context)) {
2051       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2052         << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2053         << E->getSourceRange();
2054       return;
2055     }
2056 
2057     if (Idx.isSigned() && Idx.isNegative()) {
2058       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2059         << E->getSourceRange();
2060       return;
2061     }
2062 
2063     sentinel = Idx.getZExtValue();
2064   }
2065 
2066   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2067   if (Attr.getNumArgs() > 1) {
2068     Expr *E = Attr.getArgAsExpr(1);
2069     llvm::APSInt Idx(32);
2070     if (E->isTypeDependent() || E->isValueDependent() ||
2071         !E->isIntegerConstantExpr(Idx, S.Context)) {
2072       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2073         << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2074         << E->getSourceRange();
2075       return;
2076     }
2077     nullPos = Idx.getZExtValue();
2078 
2079     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2080       // FIXME: This error message could be improved, it would be nice
2081       // to say what the bounds actually are.
2082       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2083         << E->getSourceRange();
2084       return;
2085     }
2086   }
2087 
2088   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2089     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2090     if (isa<FunctionNoProtoType>(FT)) {
2091       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2092       return;
2093     }
2094 
2095     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2096       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2097       return;
2098     }
2099   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2100     if (!MD->isVariadic()) {
2101       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2102       return;
2103     }
2104   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2105     if (!BD->isVariadic()) {
2106       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2107       return;
2108     }
2109   } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2110     QualType Ty = V->getType();
2111     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2112       const FunctionType *FT = Ty->isFunctionPointerType()
2113        ? D->getFunctionType()
2114        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2115       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2116         int m = Ty->isFunctionPointerType() ? 0 : 1;
2117         S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2118         return;
2119       }
2120     } else {
2121       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2122         << Attr.getName() << ExpectedFunctionMethodOrBlock;
2123       return;
2124     }
2125   } else {
2126     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2127       << Attr.getName() << ExpectedFunctionMethodOrBlock;
2128     return;
2129   }
2130   D->addAttr(::new (S.Context)
2131              SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2132                           Attr.getAttributeSpellingListIndex()));
2133 }
2134 
2135 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2136   if (D->getFunctionType() &&
2137       D->getFunctionType()->getReturnType()->isVoidType()) {
2138     S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2139       << Attr.getName() << 0;
2140     return;
2141   }
2142   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2143     if (MD->getReturnType()->isVoidType()) {
2144       S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2145       << Attr.getName() << 1;
2146       return;
2147     }
2148 
2149   D->addAttr(::new (S.Context)
2150              WarnUnusedResultAttr(Attr.getRange(), S.Context,
2151                                   Attr.getAttributeSpellingListIndex()));
2152 }
2153 
2154 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2155   // weak_import only applies to variable & function declarations.
2156   bool isDef = false;
2157   if (!D->canBeWeakImported(isDef)) {
2158     if (isDef)
2159       S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2160         << "weak_import";
2161     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2162              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2163               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2164       // Nothing to warn about here.
2165     } else
2166       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2167         << Attr.getName() << ExpectedVariableOrFunction;
2168 
2169     return;
2170   }
2171 
2172   D->addAttr(::new (S.Context)
2173              WeakImportAttr(Attr.getRange(), S.Context,
2174                             Attr.getAttributeSpellingListIndex()));
2175 }
2176 
2177 // Handles reqd_work_group_size and work_group_size_hint.
2178 template <typename WorkGroupAttr>
2179 static void handleWorkGroupSize(Sema &S, Decl *D,
2180                                 const AttributeList &Attr) {
2181   uint32_t WGSize[3];
2182   for (unsigned i = 0; i < 3; ++i)
2183     if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(i), WGSize[i], i))
2184       return;
2185 
2186   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2187   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2188                     Existing->getYDim() == WGSize[1] &&
2189                     Existing->getZDim() == WGSize[2]))
2190     S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2191 
2192   D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2193                                              WGSize[0], WGSize[1], WGSize[2],
2194                                        Attr.getAttributeSpellingListIndex()));
2195 }
2196 
2197 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2198   if (!Attr.hasParsedType()) {
2199     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2200       << Attr.getName() << 1;
2201     return;
2202   }
2203 
2204   TypeSourceInfo *ParmTSI = 0;
2205   QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2206   assert(ParmTSI && "no type source info for attribute argument");
2207 
2208   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2209       (ParmType->isBooleanType() ||
2210        !ParmType->isIntegralType(S.getASTContext()))) {
2211     S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2212         << ParmType;
2213     return;
2214   }
2215 
2216   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2217     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2218       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2219       return;
2220     }
2221   }
2222 
2223   D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2224                                                ParmTSI,
2225                                         Attr.getAttributeSpellingListIndex()));
2226 }
2227 
2228 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2229                                     StringRef Name,
2230                                     unsigned AttrSpellingListIndex) {
2231   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2232     if (ExistingAttr->getName() == Name)
2233       return NULL;
2234     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2235     Diag(Range.getBegin(), diag::note_previous_attribute);
2236     return NULL;
2237   }
2238   return ::new (Context) SectionAttr(Range, Context, Name,
2239                                      AttrSpellingListIndex);
2240 }
2241 
2242 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2243   // Make sure that there is a string literal as the sections's single
2244   // argument.
2245   StringRef Str;
2246   SourceLocation LiteralLoc;
2247   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2248     return;
2249 
2250   // If the target wants to validate the section specifier, make it happen.
2251   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2252   if (!Error.empty()) {
2253     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2254     << Error;
2255     return;
2256   }
2257 
2258   unsigned Index = Attr.getAttributeSpellingListIndex();
2259   SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2260   if (NewAttr)
2261     D->addAttr(NewAttr);
2262 }
2263 
2264 
2265 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2266   VarDecl *VD = cast<VarDecl>(D);
2267   if (!VD->hasLocalStorage()) {
2268     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2269     return;
2270   }
2271 
2272   Expr *E = Attr.getArgAsExpr(0);
2273   SourceLocation Loc = E->getExprLoc();
2274   FunctionDecl *FD = 0;
2275   DeclarationNameInfo NI;
2276 
2277   // gcc only allows for simple identifiers. Since we support more than gcc, we
2278   // will warn the user.
2279   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2280     if (DRE->hasQualifier())
2281       S.Diag(Loc, diag::warn_cleanup_ext);
2282     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2283     NI = DRE->getNameInfo();
2284     if (!FD) {
2285       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2286         << NI.getName();
2287       return;
2288     }
2289   } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2290     if (ULE->hasExplicitTemplateArgs())
2291       S.Diag(Loc, diag::warn_cleanup_ext);
2292     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2293     NI = ULE->getNameInfo();
2294     if (!FD) {
2295       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2296         << NI.getName();
2297       if (ULE->getType() == S.Context.OverloadTy)
2298         S.NoteAllOverloadCandidates(ULE);
2299       return;
2300     }
2301   } else {
2302     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2303     return;
2304   }
2305 
2306   if (FD->getNumParams() != 1) {
2307     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2308       << NI.getName();
2309     return;
2310   }
2311 
2312   // We're currently more strict than GCC about what function types we accept.
2313   // If this ever proves to be a problem it should be easy to fix.
2314   QualType Ty = S.Context.getPointerType(VD->getType());
2315   QualType ParamTy = FD->getParamDecl(0)->getType();
2316   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2317                                    ParamTy, Ty) != Sema::Compatible) {
2318     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2319       << NI.getName() << ParamTy << Ty;
2320     return;
2321   }
2322 
2323   D->addAttr(::new (S.Context)
2324              CleanupAttr(Attr.getRange(), S.Context, FD,
2325                          Attr.getAttributeSpellingListIndex()));
2326 }
2327 
2328 /// Handle __attribute__((format_arg((idx)))) attribute based on
2329 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2330 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2331   Expr *IdxExpr = Attr.getArgAsExpr(0);
2332   uint64_t Idx;
2333   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2334     return;
2335 
2336   // make sure the format string is really a string
2337   QualType Ty = getFunctionOrMethodParamType(D, Idx);
2338 
2339   bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2340   if (not_nsstring_type &&
2341       !isCFStringType(Ty, S.Context) &&
2342       (!Ty->isPointerType() ||
2343        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2344     // FIXME: Should highlight the actual expression that has the wrong type.
2345     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2346     << (not_nsstring_type ? "a string type" : "an NSString")
2347        << IdxExpr->getSourceRange();
2348     return;
2349   }
2350   Ty = getFunctionOrMethodResultType(D);
2351   if (!isNSStringType(Ty, S.Context) &&
2352       !isCFStringType(Ty, S.Context) &&
2353       (!Ty->isPointerType() ||
2354        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2355     // FIXME: Should highlight the actual expression that has the wrong type.
2356     S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2357     << (not_nsstring_type ? "string type" : "NSString")
2358        << IdxExpr->getSourceRange();
2359     return;
2360   }
2361 
2362   // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2363   // because that has corrected for the implicit this parameter, and is zero-
2364   // based.  The attribute expects what the user wrote explicitly.
2365   llvm::APSInt Val;
2366   IdxExpr->EvaluateAsInt(Val, S.Context);
2367 
2368   D->addAttr(::new (S.Context)
2369              FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2370                            Attr.getAttributeSpellingListIndex()));
2371 }
2372 
2373 enum FormatAttrKind {
2374   CFStringFormat,
2375   NSStringFormat,
2376   StrftimeFormat,
2377   SupportedFormat,
2378   IgnoredFormat,
2379   InvalidFormat
2380 };
2381 
2382 /// getFormatAttrKind - Map from format attribute names to supported format
2383 /// types.
2384 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2385   return llvm::StringSwitch<FormatAttrKind>(Format)
2386     // Check for formats that get handled specially.
2387     .Case("NSString", NSStringFormat)
2388     .Case("CFString", CFStringFormat)
2389     .Case("strftime", StrftimeFormat)
2390 
2391     // Otherwise, check for supported formats.
2392     .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2393     .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2394     .Case("kprintf", SupportedFormat) // OpenBSD.
2395 
2396     .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2397     .Default(InvalidFormat);
2398 }
2399 
2400 /// Handle __attribute__((init_priority(priority))) attributes based on
2401 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2402 static void handleInitPriorityAttr(Sema &S, Decl *D,
2403                                    const AttributeList &Attr) {
2404   if (!S.getLangOpts().CPlusPlus) {
2405     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2406     return;
2407   }
2408 
2409   if (S.getCurFunctionOrMethodDecl()) {
2410     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2411     Attr.setInvalid();
2412     return;
2413   }
2414   QualType T = cast<VarDecl>(D)->getType();
2415   if (S.Context.getAsArrayType(T))
2416     T = S.Context.getBaseElementType(T);
2417   if (!T->getAs<RecordType>()) {
2418     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2419     Attr.setInvalid();
2420     return;
2421   }
2422 
2423   Expr *E = Attr.getArgAsExpr(0);
2424   uint32_t prioritynum;
2425   if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2426     Attr.setInvalid();
2427     return;
2428   }
2429 
2430   if (prioritynum < 101 || prioritynum > 65535) {
2431     S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2432       << E->getSourceRange();
2433     Attr.setInvalid();
2434     return;
2435   }
2436   D->addAttr(::new (S.Context)
2437              InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2438                               Attr.getAttributeSpellingListIndex()));
2439 }
2440 
2441 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2442                                   IdentifierInfo *Format, int FormatIdx,
2443                                   int FirstArg,
2444                                   unsigned AttrSpellingListIndex) {
2445   // Check whether we already have an equivalent format attribute.
2446   for (auto *F : D->specific_attrs<FormatAttr>()) {
2447     if (F->getType() == Format &&
2448         F->getFormatIdx() == FormatIdx &&
2449         F->getFirstArg() == FirstArg) {
2450       // If we don't have a valid location for this attribute, adopt the
2451       // location.
2452       if (F->getLocation().isInvalid())
2453         F->setRange(Range);
2454       return NULL;
2455     }
2456   }
2457 
2458   return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2459                                     FirstArg, AttrSpellingListIndex);
2460 }
2461 
2462 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2463 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2464 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2465   if (!Attr.isArgIdent(0)) {
2466     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2467       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2468     return;
2469   }
2470 
2471   // In C++ the implicit 'this' function parameter also counts, and they are
2472   // counted from one.
2473   bool HasImplicitThisParam = isInstanceMethod(D);
2474   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2475 
2476   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2477   StringRef Format = II->getName();
2478 
2479   // Normalize the argument, __foo__ becomes foo.
2480   if (Format.startswith("__") && Format.endswith("__")) {
2481     Format = Format.substr(2, Format.size() - 4);
2482     // If we've modified the string name, we need a new identifier for it.
2483     II = &S.Context.Idents.get(Format);
2484   }
2485 
2486   // Check for supported formats.
2487   FormatAttrKind Kind = getFormatAttrKind(Format);
2488 
2489   if (Kind == IgnoredFormat)
2490     return;
2491 
2492   if (Kind == InvalidFormat) {
2493     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2494       << Attr.getName() << II->getName();
2495     return;
2496   }
2497 
2498   // checks for the 2nd argument
2499   Expr *IdxExpr = Attr.getArgAsExpr(1);
2500   uint32_t Idx;
2501   if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2502     return;
2503 
2504   if (Idx < 1 || Idx > NumArgs) {
2505     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2506       << Attr.getName() << 2 << IdxExpr->getSourceRange();
2507     return;
2508   }
2509 
2510   // FIXME: Do we need to bounds check?
2511   unsigned ArgIdx = Idx - 1;
2512 
2513   if (HasImplicitThisParam) {
2514     if (ArgIdx == 0) {
2515       S.Diag(Attr.getLoc(),
2516              diag::err_format_attribute_implicit_this_format_string)
2517         << IdxExpr->getSourceRange();
2518       return;
2519     }
2520     ArgIdx--;
2521   }
2522 
2523   // make sure the format string is really a string
2524   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2525 
2526   if (Kind == CFStringFormat) {
2527     if (!isCFStringType(Ty, S.Context)) {
2528       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2529         << "a CFString" << IdxExpr->getSourceRange();
2530       return;
2531     }
2532   } else if (Kind == NSStringFormat) {
2533     // FIXME: do we need to check if the type is NSString*?  What are the
2534     // semantics?
2535     if (!isNSStringType(Ty, S.Context)) {
2536       // FIXME: Should highlight the actual expression that has the wrong type.
2537       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2538         << "an NSString" << IdxExpr->getSourceRange();
2539       return;
2540     }
2541   } else if (!Ty->isPointerType() ||
2542              !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2543     // FIXME: Should highlight the actual expression that has the wrong type.
2544     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2545       << "a string type" << IdxExpr->getSourceRange();
2546     return;
2547   }
2548 
2549   // check the 3rd argument
2550   Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2551   uint32_t FirstArg;
2552   if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2553     return;
2554 
2555   // check if the function is variadic if the 3rd argument non-zero
2556   if (FirstArg != 0) {
2557     if (isFunctionOrMethodVariadic(D)) {
2558       ++NumArgs; // +1 for ...
2559     } else {
2560       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2561       return;
2562     }
2563   }
2564 
2565   // strftime requires FirstArg to be 0 because it doesn't read from any
2566   // variable the input is just the current time + the format string.
2567   if (Kind == StrftimeFormat) {
2568     if (FirstArg != 0) {
2569       S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2570         << FirstArgExpr->getSourceRange();
2571       return;
2572     }
2573   // if 0 it disables parameter checking (to use with e.g. va_list)
2574   } else if (FirstArg != 0 && FirstArg != NumArgs) {
2575     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2576       << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2577     return;
2578   }
2579 
2580   FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2581                                           Idx, FirstArg,
2582                                           Attr.getAttributeSpellingListIndex());
2583   if (NewAttr)
2584     D->addAttr(NewAttr);
2585 }
2586 
2587 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2588                                        const AttributeList &Attr) {
2589   // Try to find the underlying union declaration.
2590   RecordDecl *RD = 0;
2591   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2592   if (TD && TD->getUnderlyingType()->isUnionType())
2593     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2594   else
2595     RD = dyn_cast<RecordDecl>(D);
2596 
2597   if (!RD || !RD->isUnion()) {
2598     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2599       << Attr.getName() << ExpectedUnion;
2600     return;
2601   }
2602 
2603   if (!RD->isCompleteDefinition()) {
2604     S.Diag(Attr.getLoc(),
2605         diag::warn_transparent_union_attribute_not_definition);
2606     return;
2607   }
2608 
2609   RecordDecl::field_iterator Field = RD->field_begin(),
2610                           FieldEnd = RD->field_end();
2611   if (Field == FieldEnd) {
2612     S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2613     return;
2614   }
2615 
2616   FieldDecl *FirstField = *Field;
2617   QualType FirstType = FirstField->getType();
2618   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2619     S.Diag(FirstField->getLocation(),
2620            diag::warn_transparent_union_attribute_floating)
2621       << FirstType->isVectorType() << FirstType;
2622     return;
2623   }
2624 
2625   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2626   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2627   for (; Field != FieldEnd; ++Field) {
2628     QualType FieldType = Field->getType();
2629     // FIXME: this isn't fully correct; we also need to test whether the
2630     // members of the union would all have the same calling convention as the
2631     // first member of the union. Checking just the size and alignment isn't
2632     // sufficient (consider structs passed on the stack instead of in registers
2633     // as an example).
2634     if (S.Context.getTypeSize(FieldType) != FirstSize ||
2635         S.Context.getTypeAlign(FieldType) > FirstAlign) {
2636       // Warn if we drop the attribute.
2637       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2638       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2639                                  : S.Context.getTypeAlign(FieldType);
2640       S.Diag(Field->getLocation(),
2641           diag::warn_transparent_union_attribute_field_size_align)
2642         << isSize << Field->getDeclName() << FieldBits;
2643       unsigned FirstBits = isSize? FirstSize : FirstAlign;
2644       S.Diag(FirstField->getLocation(),
2645              diag::note_transparent_union_first_field_size_align)
2646         << isSize << FirstBits;
2647       return;
2648     }
2649   }
2650 
2651   RD->addAttr(::new (S.Context)
2652               TransparentUnionAttr(Attr.getRange(), S.Context,
2653                                    Attr.getAttributeSpellingListIndex()));
2654 }
2655 
2656 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2657   // Make sure that there is a string literal as the annotation's single
2658   // argument.
2659   StringRef Str;
2660   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2661     return;
2662 
2663   // Don't duplicate annotations that are already set.
2664   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2665     if (I->getAnnotation() == Str)
2666       return;
2667   }
2668 
2669   D->addAttr(::new (S.Context)
2670              AnnotateAttr(Attr.getRange(), S.Context, Str,
2671                           Attr.getAttributeSpellingListIndex()));
2672 }
2673 
2674 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2675   // check the attribute arguments.
2676   if (Attr.getNumArgs() > 1) {
2677     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2678       << Attr.getName() << 1;
2679     return;
2680   }
2681 
2682   if (Attr.getNumArgs() == 0) {
2683     D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2684                true, 0, Attr.getAttributeSpellingListIndex()));
2685     return;
2686   }
2687 
2688   Expr *E = Attr.getArgAsExpr(0);
2689   if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2690     S.Diag(Attr.getEllipsisLoc(),
2691            diag::err_pack_expansion_without_parameter_packs);
2692     return;
2693   }
2694 
2695   if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2696     return;
2697 
2698   S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2699                    Attr.isPackExpansion());
2700 }
2701 
2702 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2703                           unsigned SpellingListIndex, bool IsPackExpansion) {
2704   AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2705   SourceLocation AttrLoc = AttrRange.getBegin();
2706 
2707   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2708   if (TmpAttr.isAlignas()) {
2709     // C++11 [dcl.align]p1:
2710     //   An alignment-specifier may be applied to a variable or to a class
2711     //   data member, but it shall not be applied to a bit-field, a function
2712     //   parameter, the formal parameter of a catch clause, or a variable
2713     //   declared with the register storage class specifier. An
2714     //   alignment-specifier may also be applied to the declaration of a class
2715     //   or enumeration type.
2716     // C11 6.7.5/2:
2717     //   An alignment attribute shall not be specified in a declaration of
2718     //   a typedef, or a bit-field, or a function, or a parameter, or an
2719     //   object declared with the register storage-class specifier.
2720     int DiagKind = -1;
2721     if (isa<ParmVarDecl>(D)) {
2722       DiagKind = 0;
2723     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2724       if (VD->getStorageClass() == SC_Register)
2725         DiagKind = 1;
2726       if (VD->isExceptionVariable())
2727         DiagKind = 2;
2728     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2729       if (FD->isBitField())
2730         DiagKind = 3;
2731     } else if (!isa<TagDecl>(D)) {
2732       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2733         << (TmpAttr.isC11() ? ExpectedVariableOrField
2734                             : ExpectedVariableFieldOrTag);
2735       return;
2736     }
2737     if (DiagKind != -1) {
2738       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2739         << &TmpAttr << DiagKind;
2740       return;
2741     }
2742   }
2743 
2744   if (E->isTypeDependent() || E->isValueDependent()) {
2745     // Save dependent expressions in the AST to be instantiated.
2746     AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2747     AA->setPackExpansion(IsPackExpansion);
2748     D->addAttr(AA);
2749     return;
2750   }
2751 
2752   // FIXME: Cache the number on the Attr object?
2753   llvm::APSInt Alignment(32);
2754   ExprResult ICE
2755     = VerifyIntegerConstantExpression(E, &Alignment,
2756         diag::err_aligned_attribute_argument_not_int,
2757         /*AllowFold*/ false);
2758   if (ICE.isInvalid())
2759     return;
2760 
2761   // C++11 [dcl.align]p2:
2762   //   -- if the constant expression evaluates to zero, the alignment
2763   //      specifier shall have no effect
2764   // C11 6.7.5p6:
2765   //   An alignment specification of zero has no effect.
2766   if (!(TmpAttr.isAlignas() && !Alignment) &&
2767       !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2768     Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
2769       << E->getSourceRange();
2770     return;
2771   }
2772 
2773   // Alignment calculations can wrap around if it's greater than 2**28.
2774   unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
2775   if (Alignment.getZExtValue() > MaxValidAlignment) {
2776     Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
2777                                                          << E->getSourceRange();
2778     return;
2779   }
2780 
2781   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
2782                                                 ICE.take(), SpellingListIndex);
2783   AA->setPackExpansion(IsPackExpansion);
2784   D->addAttr(AA);
2785 }
2786 
2787 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
2788                           unsigned SpellingListIndex, bool IsPackExpansion) {
2789   // FIXME: Cache the number on the Attr object if non-dependent?
2790   // FIXME: Perform checking of type validity
2791   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
2792                                                 SpellingListIndex);
2793   AA->setPackExpansion(IsPackExpansion);
2794   D->addAttr(AA);
2795 }
2796 
2797 void Sema::CheckAlignasUnderalignment(Decl *D) {
2798   assert(D->hasAttrs() && "no attributes on decl");
2799 
2800   QualType Ty;
2801   if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2802     Ty = VD->getType();
2803   else
2804     Ty = Context.getTagDeclType(cast<TagDecl>(D));
2805   if (Ty->isDependentType() || Ty->isIncompleteType())
2806     return;
2807 
2808   // C++11 [dcl.align]p5, C11 6.7.5/4:
2809   //   The combined effect of all alignment attributes in a declaration shall
2810   //   not specify an alignment that is less strict than the alignment that
2811   //   would otherwise be required for the entity being declared.
2812   AlignedAttr *AlignasAttr = 0;
2813   unsigned Align = 0;
2814   for (auto *I : D->specific_attrs<AlignedAttr>()) {
2815     if (I->isAlignmentDependent())
2816       return;
2817     if (I->isAlignas())
2818       AlignasAttr = I;
2819     Align = std::max(Align, I->getAlignment(Context));
2820   }
2821 
2822   if (AlignasAttr && Align) {
2823     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
2824     CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
2825     if (NaturalAlign > RequestedAlign)
2826       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
2827         << Ty << (unsigned)NaturalAlign.getQuantity();
2828   }
2829 }
2830 
2831 bool Sema::checkMSInheritanceAttrOnDefinition(
2832     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2833     MSInheritanceAttr::Spelling SemanticSpelling) {
2834   assert(RD->hasDefinition() && "RD has no definition!");
2835 
2836   // We may not have seen base specifiers or any virtual methods yet.  We will
2837   // have to wait until the record is defined to catch any mismatches.
2838   if (!RD->getDefinition()->isCompleteDefinition())
2839     return false;
2840 
2841   // The unspecified model never matches what a definition could need.
2842   if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
2843     return false;
2844 
2845   if (BestCase) {
2846     if (RD->calculateInheritanceModel() == SemanticSpelling)
2847       return false;
2848   } else {
2849     if (RD->calculateInheritanceModel() <= SemanticSpelling)
2850       return false;
2851   }
2852 
2853   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
2854       << 0 /*definition*/;
2855   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
2856       << RD->getNameAsString();
2857   return true;
2858 }
2859 
2860 /// handleModeAttr - This attribute modifies the width of a decl with primitive
2861 /// type.
2862 ///
2863 /// Despite what would be logical, the mode attribute is a decl attribute, not a
2864 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
2865 /// HImode, not an intermediate pointer.
2866 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2867   // This attribute isn't documented, but glibc uses it.  It changes
2868   // the width of an int or unsigned int to the specified size.
2869   if (!Attr.isArgIdent(0)) {
2870     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
2871       << AANT_ArgumentIdentifier;
2872     return;
2873   }
2874 
2875   IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
2876   StringRef Str = Name->getName();
2877 
2878   // Normalize the attribute name, __foo__ becomes foo.
2879   if (Str.startswith("__") && Str.endswith("__"))
2880     Str = Str.substr(2, Str.size() - 4);
2881 
2882   unsigned DestWidth = 0;
2883   bool IntegerMode = true;
2884   bool ComplexMode = false;
2885   switch (Str.size()) {
2886   case 2:
2887     switch (Str[0]) {
2888     case 'Q': DestWidth = 8; break;
2889     case 'H': DestWidth = 16; break;
2890     case 'S': DestWidth = 32; break;
2891     case 'D': DestWidth = 64; break;
2892     case 'X': DestWidth = 96; break;
2893     case 'T': DestWidth = 128; break;
2894     }
2895     if (Str[1] == 'F') {
2896       IntegerMode = false;
2897     } else if (Str[1] == 'C') {
2898       IntegerMode = false;
2899       ComplexMode = true;
2900     } else if (Str[1] != 'I') {
2901       DestWidth = 0;
2902     }
2903     break;
2904   case 4:
2905     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
2906     // pointer on PIC16 and other embedded platforms.
2907     if (Str == "word")
2908       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2909     else if (Str == "byte")
2910       DestWidth = S.Context.getTargetInfo().getCharWidth();
2911     break;
2912   case 7:
2913     if (Str == "pointer")
2914       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
2915     break;
2916   case 11:
2917     if (Str == "unwind_word")
2918       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
2919     break;
2920   }
2921 
2922   QualType OldTy;
2923   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2924     OldTy = TD->getUnderlyingType();
2925   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2926     OldTy = VD->getType();
2927   else {
2928     S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
2929       << Attr.getName() << Attr.getRange();
2930     return;
2931   }
2932 
2933   if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
2934     S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
2935   else if (IntegerMode) {
2936     if (!OldTy->isIntegralOrEnumerationType())
2937       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2938   } else if (ComplexMode) {
2939     if (!OldTy->isComplexType())
2940       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2941   } else {
2942     if (!OldTy->isFloatingType())
2943       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2944   }
2945 
2946   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
2947   // and friends, at least with glibc.
2948   // FIXME: Make sure floating-point mappings are accurate
2949   // FIXME: Support XF and TF types
2950   if (!DestWidth) {
2951     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
2952     return;
2953   }
2954 
2955   QualType NewTy;
2956 
2957   if (IntegerMode)
2958     NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
2959                                             OldTy->isSignedIntegerType());
2960   else
2961     NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
2962 
2963   if (NewTy.isNull()) {
2964     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
2965     return;
2966   }
2967 
2968   if (ComplexMode) {
2969     NewTy = S.Context.getComplexType(NewTy);
2970   }
2971 
2972   // Install the new type.
2973   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2974     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
2975   else
2976     cast<ValueDecl>(D)->setType(NewTy);
2977 
2978   D->addAttr(::new (S.Context)
2979              ModeAttr(Attr.getRange(), S.Context, Name,
2980                       Attr.getAttributeSpellingListIndex()));
2981 }
2982 
2983 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2984   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2985     if (!VD->hasGlobalStorage())
2986       S.Diag(Attr.getLoc(),
2987              diag::warn_attribute_requires_functions_or_static_globals)
2988         << Attr.getName();
2989   } else if (!isFunctionOrMethod(D)) {
2990     S.Diag(Attr.getLoc(),
2991            diag::warn_attribute_requires_functions_or_static_globals)
2992       << Attr.getName();
2993     return;
2994   }
2995 
2996   D->addAttr(::new (S.Context)
2997              NoDebugAttr(Attr.getRange(), S.Context,
2998                          Attr.getAttributeSpellingListIndex()));
2999 }
3000 
3001 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3002   FunctionDecl *FD = cast<FunctionDecl>(D);
3003   if (!FD->getReturnType()->isVoidType()) {
3004     TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3005     if (FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>()) {
3006       S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3007         << FD->getType()
3008         << FixItHint::CreateReplacement(FTL.getReturnLoc().getSourceRange(),
3009                                         "void");
3010     } else {
3011       S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3012         << FD->getType();
3013     }
3014     return;
3015   }
3016 
3017   D->addAttr(::new (S.Context)
3018               CUDAGlobalAttr(Attr.getRange(), S.Context,
3019                             Attr.getAttributeSpellingListIndex()));
3020 }
3021 
3022 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3023   FunctionDecl *Fn = cast<FunctionDecl>(D);
3024   if (!Fn->isInlineSpecified()) {
3025     S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3026     return;
3027   }
3028 
3029   D->addAttr(::new (S.Context)
3030              GNUInlineAttr(Attr.getRange(), S.Context,
3031                            Attr.getAttributeSpellingListIndex()));
3032 }
3033 
3034 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3035   if (hasDeclarator(D)) return;
3036 
3037   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3038   // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3039   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3040   CallingConv CC;
3041   if (S.CheckCallingConvAttr(Attr, CC, FD))
3042     return;
3043 
3044   if (!isa<ObjCMethodDecl>(D)) {
3045     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3046       << Attr.getName() << ExpectedFunctionOrMethod;
3047     return;
3048   }
3049 
3050   switch (Attr.getKind()) {
3051   case AttributeList::AT_FastCall:
3052     D->addAttr(::new (S.Context)
3053                FastCallAttr(Attr.getRange(), S.Context,
3054                             Attr.getAttributeSpellingListIndex()));
3055     return;
3056   case AttributeList::AT_StdCall:
3057     D->addAttr(::new (S.Context)
3058                StdCallAttr(Attr.getRange(), S.Context,
3059                            Attr.getAttributeSpellingListIndex()));
3060     return;
3061   case AttributeList::AT_ThisCall:
3062     D->addAttr(::new (S.Context)
3063                ThisCallAttr(Attr.getRange(), S.Context,
3064                             Attr.getAttributeSpellingListIndex()));
3065     return;
3066   case AttributeList::AT_CDecl:
3067     D->addAttr(::new (S.Context)
3068                CDeclAttr(Attr.getRange(), S.Context,
3069                          Attr.getAttributeSpellingListIndex()));
3070     return;
3071   case AttributeList::AT_Pascal:
3072     D->addAttr(::new (S.Context)
3073                PascalAttr(Attr.getRange(), S.Context,
3074                           Attr.getAttributeSpellingListIndex()));
3075     return;
3076   case AttributeList::AT_MSABI:
3077     D->addAttr(::new (S.Context)
3078                MSABIAttr(Attr.getRange(), S.Context,
3079                          Attr.getAttributeSpellingListIndex()));
3080     return;
3081   case AttributeList::AT_SysVABI:
3082     D->addAttr(::new (S.Context)
3083                SysVABIAttr(Attr.getRange(), S.Context,
3084                            Attr.getAttributeSpellingListIndex()));
3085     return;
3086   case AttributeList::AT_Pcs: {
3087     PcsAttr::PCSType PCS;
3088     switch (CC) {
3089     case CC_AAPCS:
3090       PCS = PcsAttr::AAPCS;
3091       break;
3092     case CC_AAPCS_VFP:
3093       PCS = PcsAttr::AAPCS_VFP;
3094       break;
3095     default:
3096       llvm_unreachable("unexpected calling convention in pcs attribute");
3097     }
3098 
3099     D->addAttr(::new (S.Context)
3100                PcsAttr(Attr.getRange(), S.Context, PCS,
3101                        Attr.getAttributeSpellingListIndex()));
3102     return;
3103   }
3104   case AttributeList::AT_PnaclCall:
3105     D->addAttr(::new (S.Context)
3106                PnaclCallAttr(Attr.getRange(), S.Context,
3107                              Attr.getAttributeSpellingListIndex()));
3108     return;
3109   case AttributeList::AT_IntelOclBicc:
3110     D->addAttr(::new (S.Context)
3111                IntelOclBiccAttr(Attr.getRange(), S.Context,
3112                                 Attr.getAttributeSpellingListIndex()));
3113     return;
3114 
3115   default:
3116     llvm_unreachable("unexpected attribute kind");
3117   }
3118 }
3119 
3120 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3121                                 const FunctionDecl *FD) {
3122   if (attr.isInvalid())
3123     return true;
3124 
3125   unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3126   if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3127     attr.setInvalid();
3128     return true;
3129   }
3130 
3131   // TODO: diagnose uses of these conventions on the wrong target.
3132   switch (attr.getKind()) {
3133   case AttributeList::AT_CDecl: CC = CC_C; break;
3134   case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3135   case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3136   case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3137   case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3138   case AttributeList::AT_MSABI:
3139     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3140                                                              CC_X86_64Win64;
3141     break;
3142   case AttributeList::AT_SysVABI:
3143     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3144                                                              CC_C;
3145     break;
3146   case AttributeList::AT_Pcs: {
3147     StringRef StrRef;
3148     if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3149       attr.setInvalid();
3150       return true;
3151     }
3152     if (StrRef == "aapcs") {
3153       CC = CC_AAPCS;
3154       break;
3155     } else if (StrRef == "aapcs-vfp") {
3156       CC = CC_AAPCS_VFP;
3157       break;
3158     }
3159 
3160     attr.setInvalid();
3161     Diag(attr.getLoc(), diag::err_invalid_pcs);
3162     return true;
3163   }
3164   case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3165   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3166   default: llvm_unreachable("unexpected attribute kind");
3167   }
3168 
3169   const TargetInfo &TI = Context.getTargetInfo();
3170   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3171   if (A == TargetInfo::CCCR_Warning) {
3172     Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3173 
3174     TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3175     if (FD)
3176       MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3177                                     TargetInfo::CCMT_NonMember;
3178     CC = TI.getDefaultCallingConv(MT);
3179   }
3180 
3181   return false;
3182 }
3183 
3184 /// Checks a regparm attribute, returning true if it is ill-formed and
3185 /// otherwise setting numParams to the appropriate value.
3186 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3187   if (Attr.isInvalid())
3188     return true;
3189 
3190   if (!checkAttributeNumArgs(*this, Attr, 1)) {
3191     Attr.setInvalid();
3192     return true;
3193   }
3194 
3195   uint32_t NP;
3196   Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3197   if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3198     Attr.setInvalid();
3199     return true;
3200   }
3201 
3202   if (Context.getTargetInfo().getRegParmMax() == 0) {
3203     Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3204       << NumParamsExpr->getSourceRange();
3205     Attr.setInvalid();
3206     return true;
3207   }
3208 
3209   numParams = NP;
3210   if (numParams > Context.getTargetInfo().getRegParmMax()) {
3211     Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3212       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3213     Attr.setInvalid();
3214     return true;
3215   }
3216 
3217   return false;
3218 }
3219 
3220 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3221                                    const AttributeList &Attr) {
3222   // check the attribute arguments.
3223   if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
3224     // FIXME: 0 is not okay.
3225     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
3226       << Attr.getName() << 2;
3227     return;
3228   }
3229 
3230   uint32_t MaxThreads, MinBlocks = 0;
3231   if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), MaxThreads, 1))
3232     return;
3233   if (Attr.getNumArgs() > 1 && !checkUInt32Argument(S, Attr,
3234                                                     Attr.getArgAsExpr(1),
3235                                                     MinBlocks, 2))
3236     return;
3237 
3238   D->addAttr(::new (S.Context)
3239               CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3240                                   MaxThreads, MinBlocks,
3241                                   Attr.getAttributeSpellingListIndex()));
3242 }
3243 
3244 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3245                                           const AttributeList &Attr) {
3246   if (!Attr.isArgIdent(0)) {
3247     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3248       << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3249     return;
3250   }
3251 
3252   if (!checkAttributeNumArgs(S, Attr, 3))
3253     return;
3254 
3255   IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3256 
3257   if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3258     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3259       << Attr.getName() << ExpectedFunctionOrMethod;
3260     return;
3261   }
3262 
3263   uint64_t ArgumentIdx;
3264   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3265                                            ArgumentIdx))
3266     return;
3267 
3268   uint64_t TypeTagIdx;
3269   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3270                                            TypeTagIdx))
3271     return;
3272 
3273   bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3274   if (IsPointer) {
3275     // Ensure that buffer has a pointer type.
3276     QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3277     if (!BufferTy->isPointerType()) {
3278       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3279         << Attr.getName();
3280     }
3281   }
3282 
3283   D->addAttr(::new (S.Context)
3284              ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3285                                      ArgumentIdx, TypeTagIdx, IsPointer,
3286                                      Attr.getAttributeSpellingListIndex()));
3287 }
3288 
3289 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3290                                          const AttributeList &Attr) {
3291   if (!Attr.isArgIdent(0)) {
3292     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3293       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3294     return;
3295   }
3296 
3297   if (!checkAttributeNumArgs(S, Attr, 1))
3298     return;
3299 
3300   if (!isa<VarDecl>(D)) {
3301     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3302       << Attr.getName() << ExpectedVariable;
3303     return;
3304   }
3305 
3306   IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3307   TypeSourceInfo *MatchingCTypeLoc = 0;
3308   S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3309   assert(MatchingCTypeLoc && "no type source info for attribute argument");
3310 
3311   D->addAttr(::new (S.Context)
3312              TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3313                                     MatchingCTypeLoc,
3314                                     Attr.getLayoutCompatible(),
3315                                     Attr.getMustBeNull(),
3316                                     Attr.getAttributeSpellingListIndex()));
3317 }
3318 
3319 //===----------------------------------------------------------------------===//
3320 // Checker-specific attribute handlers.
3321 //===----------------------------------------------------------------------===//
3322 
3323 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3324   return type->isDependentType() ||
3325          type->isObjCObjectPointerType() ||
3326          S.Context.isObjCNSObjectType(type);
3327 }
3328 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3329   return type->isDependentType() ||
3330          type->isPointerType() ||
3331          isValidSubjectOfNSAttribute(S, type);
3332 }
3333 
3334 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3335   ParmVarDecl *param = cast<ParmVarDecl>(D);
3336   bool typeOK, cf;
3337 
3338   if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3339     typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3340     cf = false;
3341   } else {
3342     typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3343     cf = true;
3344   }
3345 
3346   if (!typeOK) {
3347     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3348       << Attr.getRange() << Attr.getName() << cf;
3349     return;
3350   }
3351 
3352   if (cf)
3353     param->addAttr(::new (S.Context)
3354                    CFConsumedAttr(Attr.getRange(), S.Context,
3355                                   Attr.getAttributeSpellingListIndex()));
3356   else
3357     param->addAttr(::new (S.Context)
3358                    NSConsumedAttr(Attr.getRange(), S.Context,
3359                                   Attr.getAttributeSpellingListIndex()));
3360 }
3361 
3362 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3363                                         const AttributeList &Attr) {
3364 
3365   QualType returnType;
3366 
3367   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3368     returnType = MD->getReturnType();
3369   else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3370            (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3371     return; // ignore: was handled as a type attribute
3372   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3373     returnType = PD->getType();
3374   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3375     returnType = FD->getReturnType();
3376   else {
3377     S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3378         << Attr.getRange() << Attr.getName()
3379         << ExpectedFunctionOrMethod;
3380     return;
3381   }
3382 
3383   bool typeOK;
3384   bool cf;
3385   switch (Attr.getKind()) {
3386   default: llvm_unreachable("invalid ownership attribute");
3387   case AttributeList::AT_NSReturnsAutoreleased:
3388   case AttributeList::AT_NSReturnsRetained:
3389   case AttributeList::AT_NSReturnsNotRetained:
3390     typeOK = isValidSubjectOfNSAttribute(S, returnType);
3391     cf = false;
3392     break;
3393 
3394   case AttributeList::AT_CFReturnsRetained:
3395   case AttributeList::AT_CFReturnsNotRetained:
3396     typeOK = isValidSubjectOfCFAttribute(S, returnType);
3397     cf = true;
3398     break;
3399   }
3400 
3401   if (!typeOK) {
3402     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3403       << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3404     return;
3405   }
3406 
3407   switch (Attr.getKind()) {
3408     default:
3409       llvm_unreachable("invalid ownership attribute");
3410     case AttributeList::AT_NSReturnsAutoreleased:
3411       D->addAttr(::new (S.Context)
3412                  NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
3413                                            Attr.getAttributeSpellingListIndex()));
3414       return;
3415     case AttributeList::AT_CFReturnsNotRetained:
3416       D->addAttr(::new (S.Context)
3417                  CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
3418                                           Attr.getAttributeSpellingListIndex()));
3419       return;
3420     case AttributeList::AT_NSReturnsNotRetained:
3421       D->addAttr(::new (S.Context)
3422                  NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
3423                                           Attr.getAttributeSpellingListIndex()));
3424       return;
3425     case AttributeList::AT_CFReturnsRetained:
3426       D->addAttr(::new (S.Context)
3427                  CFReturnsRetainedAttr(Attr.getRange(), S.Context,
3428                                        Attr.getAttributeSpellingListIndex()));
3429       return;
3430     case AttributeList::AT_NSReturnsRetained:
3431       D->addAttr(::new (S.Context)
3432                  NSReturnsRetainedAttr(Attr.getRange(), S.Context,
3433                                        Attr.getAttributeSpellingListIndex()));
3434       return;
3435   };
3436 }
3437 
3438 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3439                                               const AttributeList &attr) {
3440   const int EP_ObjCMethod = 1;
3441   const int EP_ObjCProperty = 2;
3442 
3443   SourceLocation loc = attr.getLoc();
3444   QualType resultType;
3445   if (isa<ObjCMethodDecl>(D))
3446     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3447   else
3448     resultType = cast<ObjCPropertyDecl>(D)->getType();
3449 
3450   if (!resultType->isReferenceType() &&
3451       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3452     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3453       << SourceRange(loc)
3454     << attr.getName()
3455     << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3456     << /*non-retainable pointer*/ 2;
3457 
3458     // Drop the attribute.
3459     return;
3460   }
3461 
3462   D->addAttr(::new (S.Context)
3463                   ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
3464                                               attr.getAttributeSpellingListIndex()));
3465 }
3466 
3467 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3468                                         const AttributeList &attr) {
3469   ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3470 
3471   DeclContext *DC = method->getDeclContext();
3472   if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3473     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3474     << attr.getName() << 0;
3475     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3476     return;
3477   }
3478   if (method->getMethodFamily() == OMF_dealloc) {
3479     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3480     << attr.getName() << 1;
3481     return;
3482   }
3483 
3484   method->addAttr(::new (S.Context)
3485                   ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3486                                         attr.getAttributeSpellingListIndex()));
3487 }
3488 
3489 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3490                                         const AttributeList &Attr) {
3491   if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3492     return;
3493 
3494   D->addAttr(::new (S.Context)
3495              CFAuditedTransferAttr(Attr.getRange(), S.Context,
3496                                    Attr.getAttributeSpellingListIndex()));
3497 }
3498 
3499 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3500                                         const AttributeList &Attr) {
3501   if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3502     return;
3503 
3504   D->addAttr(::new (S.Context)
3505              CFUnknownTransferAttr(Attr.getRange(), S.Context,
3506              Attr.getAttributeSpellingListIndex()));
3507 }
3508 
3509 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3510                                 const AttributeList &Attr) {
3511   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
3512 
3513   if (!Parm) {
3514     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3515     return;
3516   }
3517 
3518   D->addAttr(::new (S.Context)
3519              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3520                            Attr.getAttributeSpellingListIndex()));
3521 }
3522 
3523 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3524                                         const AttributeList &Attr) {
3525   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
3526 
3527   if (!Parm) {
3528     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3529     return;
3530   }
3531 
3532   D->addAttr(::new (S.Context)
3533              ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3534                             Attr.getAttributeSpellingListIndex()));
3535 }
3536 
3537 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3538                                  const AttributeList &Attr) {
3539   IdentifierInfo *RelatedClass =
3540     Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : 0;
3541   if (!RelatedClass) {
3542     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3543     return;
3544   }
3545   IdentifierInfo *ClassMethod =
3546     Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : 0;
3547   IdentifierInfo *InstanceMethod =
3548     Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : 0;
3549   D->addAttr(::new (S.Context)
3550              ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3551                                    ClassMethod, InstanceMethod,
3552                                    Attr.getAttributeSpellingListIndex()));
3553 }
3554 
3555 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3556                                             const AttributeList &Attr) {
3557   ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3558   IFace->setHasDesignatedInitializers();
3559   D->addAttr(::new (S.Context)
3560                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3561                                          Attr.getAttributeSpellingListIndex()));
3562 }
3563 
3564 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3565                                     const AttributeList &Attr) {
3566   if (hasDeclarator(D)) return;
3567 
3568   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3569     << Attr.getRange() << Attr.getName() << ExpectedVariable;
3570 }
3571 
3572 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3573                                           const AttributeList &Attr) {
3574   ValueDecl *vd = cast<ValueDecl>(D);
3575   QualType type = vd->getType();
3576 
3577   if (!type->isDependentType() &&
3578       !type->isObjCLifetimeType()) {
3579     S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3580       << type;
3581     return;
3582   }
3583 
3584   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3585 
3586   // If we have no lifetime yet, check the lifetime we're presumably
3587   // going to infer.
3588   if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3589     lifetime = type->getObjCARCImplicitLifetime();
3590 
3591   switch (lifetime) {
3592   case Qualifiers::OCL_None:
3593     assert(type->isDependentType() &&
3594            "didn't infer lifetime for non-dependent type?");
3595     break;
3596 
3597   case Qualifiers::OCL_Weak:   // meaningful
3598   case Qualifiers::OCL_Strong: // meaningful
3599     break;
3600 
3601   case Qualifiers::OCL_ExplicitNone:
3602   case Qualifiers::OCL_Autoreleasing:
3603     S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3604       << (lifetime == Qualifiers::OCL_Autoreleasing);
3605     break;
3606   }
3607 
3608   D->addAttr(::new (S.Context)
3609              ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
3610                                      Attr.getAttributeSpellingListIndex()));
3611 }
3612 
3613 //===----------------------------------------------------------------------===//
3614 // Microsoft specific attribute handlers.
3615 //===----------------------------------------------------------------------===//
3616 
3617 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3618   if (!S.LangOpts.CPlusPlus) {
3619     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3620       << Attr.getName() << AttributeLangSupport::C;
3621     return;
3622   }
3623 
3624   if (!isa<CXXRecordDecl>(D)) {
3625     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3626       << Attr.getName() << ExpectedClass;
3627     return;
3628   }
3629 
3630   StringRef StrRef;
3631   SourceLocation LiteralLoc;
3632   if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
3633     return;
3634 
3635   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
3636   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
3637   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
3638     StrRef = StrRef.drop_front().drop_back();
3639 
3640   // Validate GUID length.
3641   if (StrRef.size() != 36) {
3642     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3643     return;
3644   }
3645 
3646   for (unsigned i = 0; i < 36; ++i) {
3647     if (i == 8 || i == 13 || i == 18 || i == 23) {
3648       if (StrRef[i] != '-') {
3649         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3650         return;
3651       }
3652     } else if (!isHexDigit(StrRef[i])) {
3653       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3654       return;
3655     }
3656   }
3657 
3658   D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
3659                                         Attr.getAttributeSpellingListIndex()));
3660 }
3661 
3662 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3663   if (!S.LangOpts.CPlusPlus) {
3664     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3665       << Attr.getName() << AttributeLangSupport::C;
3666     return;
3667   }
3668   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
3669       D, Attr.getRange(), /*BestCase=*/true,
3670       Attr.getAttributeSpellingListIndex(),
3671       (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
3672   if (IA)
3673     D->addAttr(IA);
3674 }
3675 
3676 static void handleARMInterruptAttr(Sema &S, Decl *D,
3677                                    const AttributeList &Attr) {
3678   // Check the attribute arguments.
3679   if (Attr.getNumArgs() > 1) {
3680     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
3681       << Attr.getName() << 1;
3682     return;
3683   }
3684 
3685   StringRef Str;
3686   SourceLocation ArgLoc;
3687 
3688   if (Attr.getNumArgs() == 0)
3689     Str = "";
3690   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
3691     return;
3692 
3693   ARMInterruptAttr::InterruptType Kind;
3694   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
3695     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3696       << Attr.getName() << Str << ArgLoc;
3697     return;
3698   }
3699 
3700   unsigned Index = Attr.getAttributeSpellingListIndex();
3701   D->addAttr(::new (S.Context)
3702              ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
3703 }
3704 
3705 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
3706                                       const AttributeList &Attr) {
3707   if (!checkAttributeNumArgs(S, Attr, 1))
3708     return;
3709 
3710   if (!Attr.isArgExpr(0)) {
3711     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3712       << AANT_ArgumentIntegerConstant;
3713     return;
3714   }
3715 
3716   // FIXME: Check for decl - it should be void ()(void).
3717 
3718   Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3719   llvm::APSInt NumParams(32);
3720   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
3721     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3722       << Attr.getName() << AANT_ArgumentIntegerConstant
3723       << NumParamsExpr->getSourceRange();
3724     return;
3725   }
3726 
3727   unsigned Num = NumParams.getLimitedValue(255);
3728   if ((Num & 1) || Num > 30) {
3729     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3730       << Attr.getName() << (int)NumParams.getSExtValue()
3731       << NumParamsExpr->getSourceRange();
3732     return;
3733   }
3734 
3735   D->addAttr(::new (S.Context)
3736               MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
3737                                   Attr.getAttributeSpellingListIndex()));
3738   D->addAttr(UsedAttr::CreateImplicit(S.Context));
3739 }
3740 
3741 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3742   // Dispatch the interrupt attribute based on the current target.
3743   if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
3744     handleMSP430InterruptAttr(S, D, Attr);
3745   else
3746     handleARMInterruptAttr(S, D, Attr);
3747 }
3748 
3749 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
3750                                               const AttributeList& Attr) {
3751   // If we try to apply it to a function pointer, don't warn, but don't
3752   // do anything, either. It doesn't matter anyway, because there's nothing
3753   // special about calling a force_align_arg_pointer function.
3754   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3755   if (VD && VD->getType()->isFunctionPointerType())
3756     return;
3757   // Also don't warn on function pointer typedefs.
3758   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3759   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
3760     TD->getUnderlyingType()->isFunctionType()))
3761     return;
3762   // Attribute can only be applied to function types.
3763   if (!isa<FunctionDecl>(D)) {
3764     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3765       << Attr.getName() << /* function */0;
3766     return;
3767   }
3768 
3769   D->addAttr(::new (S.Context)
3770               X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
3771                                         Attr.getAttributeSpellingListIndex()));
3772 }
3773 
3774 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
3775                                         unsigned AttrSpellingListIndex) {
3776   if (D->hasAttr<DLLExportAttr>()) {
3777     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
3778     return NULL;
3779   }
3780 
3781   if (D->hasAttr<DLLImportAttr>())
3782     return NULL;
3783 
3784   return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
3785 }
3786 
3787 static void handleDLLImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3788   // Attribute can be applied only to functions or variables.
3789   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3790   if (!FD && !isa<VarDecl>(D)) {
3791     // Apparently Visual C++ thinks it is okay to not emit a warning
3792     // in this case, so only emit a warning when -fms-extensions is not
3793     // specified.
3794     if (!S.getLangOpts().MicrosoftExt)
3795       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3796         << Attr.getName() << ExpectedVariableOrFunction;
3797     return;
3798   }
3799 
3800   // Currently, the dllimport attribute is ignored for inlined functions.
3801   // Warning is emitted.
3802   if (FD && FD->isInlineSpecified()) {
3803     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3804     return;
3805   }
3806 
3807   unsigned Index = Attr.getAttributeSpellingListIndex();
3808   DLLImportAttr *NewAttr = S.mergeDLLImportAttr(D, Attr.getRange(), Index);
3809   if (NewAttr)
3810     D->addAttr(NewAttr);
3811 }
3812 
3813 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
3814                                         unsigned AttrSpellingListIndex) {
3815   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
3816     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
3817     D->dropAttr<DLLImportAttr>();
3818   }
3819 
3820   if (D->hasAttr<DLLExportAttr>())
3821     return NULL;
3822 
3823   return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
3824 }
3825 
3826 static void handleDLLExportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3827   // Currently, the dllexport attribute is ignored for inlined functions, unless
3828   // the -fkeep-inline-functions flag has been used. Warning is emitted.
3829   if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isInlineSpecified()) {
3830     // FIXME: ... unless the -fkeep-inline-functions flag has been used.
3831     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3832     return;
3833   }
3834 
3835   unsigned Index = Attr.getAttributeSpellingListIndex();
3836   DLLExportAttr *NewAttr = S.mergeDLLExportAttr(D, Attr.getRange(), Index);
3837   if (NewAttr)
3838     D->addAttr(NewAttr);
3839 }
3840 
3841 MSInheritanceAttr *
3842 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
3843                              unsigned AttrSpellingListIndex,
3844                              MSInheritanceAttr::Spelling SemanticSpelling) {
3845   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
3846     if (IA->getSemanticSpelling() == SemanticSpelling)
3847       return 0;
3848     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
3849         << 1 /*previous declaration*/;
3850     Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
3851     D->dropAttr<MSInheritanceAttr>();
3852   }
3853 
3854   CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3855   if (RD->hasDefinition()) {
3856     if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
3857                                            SemanticSpelling)) {
3858       return 0;
3859     }
3860   } else {
3861     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
3862       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
3863           << 1 /*partial specialization*/;
3864       return 0;
3865     }
3866     if (RD->getDescribedClassTemplate()) {
3867       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
3868           << 0 /*primary template*/;
3869       return 0;
3870     }
3871   }
3872 
3873   return ::new (Context)
3874       MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
3875 }
3876 
3877 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3878   // The capability attributes take a single string parameter for the name of
3879   // the capability they represent. The lockable attribute does not take any
3880   // parameters. However, semantically, both attributes represent the same
3881   // concept, and so they use the same semantic attribute. Eventually, the
3882   // lockable attribute will be removed.
3883   //
3884   // For backwards compatibility, any capability which has no specified string
3885   // literal will be considered a "mutex."
3886   StringRef N("mutex");
3887   SourceLocation LiteralLoc;
3888   if (Attr.getKind() == AttributeList::AT_Capability &&
3889       !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
3890     return;
3891 
3892   // Currently, there are only two names allowed for a capability: role and
3893   // mutex (case insensitive). Diagnose other capability names.
3894   if (!N.equals_lower("mutex") && !N.equals_lower("role"))
3895     S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
3896 
3897   D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
3898                                         Attr.getAttributeSpellingListIndex()));
3899 }
3900 
3901 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
3902                                        const AttributeList &Attr) {
3903   D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
3904                                                     Attr.getArgAsExpr(0),
3905                                         Attr.getAttributeSpellingListIndex()));
3906 }
3907 
3908 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
3909                                         const AttributeList &Attr) {
3910   SmallVector<Expr*, 1> Args;
3911   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
3912     return;
3913 
3914   // Check that all arguments are lockable objects.
3915   checkAttrArgsAreLockableObjs(S, D, Attr, Args);
3916   if (Args.empty())
3917     return;
3918 
3919   D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
3920                                                      S.Context,
3921                                                      Args.data(), Args.size(),
3922                                         Attr.getAttributeSpellingListIndex()));
3923 }
3924 
3925 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
3926                                            const AttributeList &Attr) {
3927   SmallVector<Expr*, 2> Args;
3928   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
3929     return;
3930 
3931   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
3932                                                         S.Context,
3933                                                         Attr.getArgAsExpr(0),
3934                                                         Args.data(),
3935                                                         Args.size(),
3936                                         Attr.getAttributeSpellingListIndex()));
3937 }
3938 
3939 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
3940                                         const AttributeList &Attr) {
3941   SmallVector<Expr*, 1> Args;
3942   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
3943     return;
3944 
3945   // Check that all arguments are lockable objects.
3946   checkAttrArgsAreLockableObjs(S, D, Attr, Args);
3947   if (Args.empty())
3948     return;
3949 
3950   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(Attr.getRange(),
3951                                                      S.Context,
3952                                                      Args.data(), Args.size(),
3953                                         Attr.getAttributeSpellingListIndex()));
3954 }
3955 
3956 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
3957                                          const AttributeList &Attr) {
3958   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
3959     return;
3960 
3961   // check that all arguments are lockable objects
3962   SmallVector<Expr*, 1> Args;
3963   checkAttrArgsAreLockableObjs(S, D, Attr, Args);
3964   if (Args.empty())
3965     return;
3966 
3967   RequiresCapabilityAttr *RCA = ::new (S.Context)
3968     RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
3969                            Args.size(), Attr.getAttributeSpellingListIndex());
3970 
3971   D->addAttr(RCA);
3972 }
3973 
3974 /// Handles semantic checking for features that are common to all attributes,
3975 /// such as checking whether a parameter was properly specified, or the correct
3976 /// number of arguments were passed, etc.
3977 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
3978                                           const AttributeList &Attr) {
3979   // Several attributes carry different semantics than the parsing requires, so
3980   // those are opted out of the common handling.
3981   //
3982   // We also bail on unknown and ignored attributes because those are handled
3983   // as part of the target-specific handling logic.
3984   if (Attr.hasCustomParsing() ||
3985       Attr.getKind() == AttributeList::UnknownAttribute)
3986     return false;
3987 
3988   // Check whether the attribute requires specific language extensions to be
3989   // enabled.
3990   if (!Attr.diagnoseLangOpts(S))
3991     return true;
3992 
3993   // If there are no optional arguments, then checking for the argument count
3994   // is trivial.
3995   if (Attr.getMinArgs() == Attr.getMaxArgs() &&
3996       !checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
3997     return true;
3998 
3999   // Check whether the attribute appertains to the given subject.
4000   if (!Attr.diagnoseAppertainsTo(S, D))
4001     return true;
4002 
4003   return false;
4004 }
4005 
4006 //===----------------------------------------------------------------------===//
4007 // Top Level Sema Entry Points
4008 //===----------------------------------------------------------------------===//
4009 
4010 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4011 /// the attribute applies to decls.  If the attribute is a type attribute, just
4012 /// silently ignore it if a GNU attribute.
4013 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4014                                  const AttributeList &Attr,
4015                                  bool IncludeCXX11Attributes) {
4016   if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4017     return;
4018 
4019   // Ignore C++11 attributes on declarator chunks: they appertain to the type
4020   // instead.
4021   if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4022     return;
4023 
4024   // Unknown attributes are automatically warned on. Target-specific attributes
4025   // which do not apply to the current target architecture are treated as
4026   // though they were unknown attributes.
4027   if (Attr.getKind() == AttributeList::UnknownAttribute ||
4028       !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4029     S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4030                               ? diag::warn_unhandled_ms_attribute_ignored
4031                               : diag::warn_unknown_attribute_ignored)
4032         << Attr.getName();
4033     return;
4034   }
4035 
4036   if (handleCommonAttributeFeatures(S, scope, D, Attr))
4037     return;
4038 
4039   switch (Attr.getKind()) {
4040   default:
4041     // Type attributes are handled elsewhere; silently move on.
4042     assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4043     break;
4044   case AttributeList::AT_Interrupt:
4045     handleInterruptAttr(S, D, Attr);
4046     break;
4047   case AttributeList::AT_X86ForceAlignArgPointer:
4048     handleX86ForceAlignArgPointerAttr(S, D, Attr);
4049     break;
4050   case AttributeList::AT_DLLExport:
4051     handleDLLExportAttr(S, D, Attr);
4052     break;
4053   case AttributeList::AT_DLLImport:
4054     handleDLLImportAttr(S, D, Attr);
4055     break;
4056   case AttributeList::AT_Mips16:
4057     handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4058     break;
4059   case AttributeList::AT_NoMips16:
4060     handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4061     break;
4062   case AttributeList::AT_IBAction:
4063     handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4064     break;
4065   case AttributeList::AT_IBOutlet:
4066     handleIBOutlet(S, D, Attr);
4067     break;
4068   case AttributeList::AT_IBOutletCollection:
4069     handleIBOutletCollection(S, D, Attr);
4070     break;
4071   case AttributeList::AT_Alias:
4072     handleAliasAttr(S, D, Attr);
4073     break;
4074   case AttributeList::AT_Aligned:
4075     handleAlignedAttr(S, D, Attr);
4076     break;
4077   case AttributeList::AT_AlwaysInline:
4078     handleSimpleAttribute<AlwaysInlineAttr>(S, D, Attr);
4079     break;
4080   case AttributeList::AT_AnalyzerNoReturn:
4081     handleAnalyzerNoReturnAttr(S, D, Attr);
4082     break;
4083   case AttributeList::AT_TLSModel:
4084     handleTLSModelAttr(S, D, Attr);
4085     break;
4086   case AttributeList::AT_Annotate:
4087     handleAnnotateAttr(S, D, Attr);
4088     break;
4089   case AttributeList::AT_Availability:
4090     handleAvailabilityAttr(S, D, Attr);
4091     break;
4092   case AttributeList::AT_CarriesDependency:
4093     handleDependencyAttr(S, scope, D, Attr);
4094     break;
4095   case AttributeList::AT_Common:
4096     handleCommonAttr(S, D, Attr);
4097     break;
4098   case AttributeList::AT_CUDAConstant:
4099     handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4100     break;
4101   case AttributeList::AT_Constructor:
4102     handleConstructorAttr(S, D, Attr);
4103     break;
4104   case AttributeList::AT_CXX11NoReturn:
4105     handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4106     break;
4107   case AttributeList::AT_Deprecated:
4108     handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4109     break;
4110   case AttributeList::AT_Destructor:
4111     handleDestructorAttr(S, D, Attr);
4112     break;
4113   case AttributeList::AT_EnableIf:
4114     handleEnableIfAttr(S, D, Attr);
4115     break;
4116   case AttributeList::AT_ExtVectorType:
4117     handleExtVectorTypeAttr(S, scope, D, Attr);
4118     break;
4119   case AttributeList::AT_MinSize:
4120     handleSimpleAttribute<MinSizeAttr>(S, D, Attr);
4121     break;
4122   case AttributeList::AT_Format:
4123     handleFormatAttr(S, D, Attr);
4124     break;
4125   case AttributeList::AT_FormatArg:
4126     handleFormatArgAttr(S, D, Attr);
4127     break;
4128   case AttributeList::AT_CUDAGlobal:
4129     handleGlobalAttr(S, D, Attr);
4130     break;
4131   case AttributeList::AT_CUDADevice:
4132     handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4133     break;
4134   case AttributeList::AT_CUDAHost:
4135     handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4136     break;
4137   case AttributeList::AT_GNUInline:
4138     handleGNUInlineAttr(S, D, Attr);
4139     break;
4140   case AttributeList::AT_CUDALaunchBounds:
4141     handleLaunchBoundsAttr(S, D, Attr);
4142     break;
4143   case AttributeList::AT_Malloc:
4144     handleMallocAttr(S, D, Attr);
4145     break;
4146   case AttributeList::AT_MayAlias:
4147     handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4148     break;
4149   case AttributeList::AT_Mode:
4150     handleModeAttr(S, D, Attr);
4151     break;
4152   case AttributeList::AT_NoCommon:
4153     handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4154     break;
4155   case AttributeList::AT_NonNull:
4156     if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4157       handleNonNullAttrParameter(S, PVD, Attr);
4158     else
4159       handleNonNullAttr(S, D, Attr);
4160     break;
4161   case AttributeList::AT_ReturnsNonNull:
4162     handleReturnsNonNullAttr(S, D, Attr);
4163     break;
4164   case AttributeList::AT_Overloadable:
4165     handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4166     break;
4167   case AttributeList::AT_Ownership:
4168     handleOwnershipAttr(S, D, Attr);
4169     break;
4170   case AttributeList::AT_Cold:
4171     handleColdAttr(S, D, Attr);
4172     break;
4173   case AttributeList::AT_Hot:
4174     handleHotAttr(S, D, Attr);
4175     break;
4176   case AttributeList::AT_Naked:
4177     handleSimpleAttribute<NakedAttr>(S, D, Attr);
4178     break;
4179   case AttributeList::AT_NoReturn:
4180     handleNoReturnAttr(S, D, Attr);
4181     break;
4182   case AttributeList::AT_NoThrow:
4183     handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4184     break;
4185   case AttributeList::AT_CUDAShared:
4186     handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4187     break;
4188   case AttributeList::AT_VecReturn:
4189     handleVecReturnAttr(S, D, Attr);
4190     break;
4191 
4192   case AttributeList::AT_ObjCOwnership:
4193     handleObjCOwnershipAttr(S, D, Attr);
4194     break;
4195   case AttributeList::AT_ObjCPreciseLifetime:
4196     handleObjCPreciseLifetimeAttr(S, D, Attr);
4197     break;
4198 
4199   case AttributeList::AT_ObjCReturnsInnerPointer:
4200     handleObjCReturnsInnerPointerAttr(S, D, Attr);
4201     break;
4202 
4203   case AttributeList::AT_ObjCRequiresSuper:
4204     handleObjCRequiresSuperAttr(S, D, Attr);
4205     break;
4206 
4207   case AttributeList::AT_ObjCBridge:
4208     handleObjCBridgeAttr(S, scope, D, Attr);
4209     break;
4210 
4211   case AttributeList::AT_ObjCBridgeMutable:
4212     handleObjCBridgeMutableAttr(S, scope, D, Attr);
4213     break;
4214 
4215   case AttributeList::AT_ObjCBridgeRelated:
4216     handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4217     break;
4218 
4219   case AttributeList::AT_ObjCDesignatedInitializer:
4220     handleObjCDesignatedInitializer(S, D, Attr);
4221     break;
4222 
4223   case AttributeList::AT_CFAuditedTransfer:
4224     handleCFAuditedTransferAttr(S, D, Attr);
4225     break;
4226   case AttributeList::AT_CFUnknownTransfer:
4227     handleCFUnknownTransferAttr(S, D, Attr);
4228     break;
4229 
4230   case AttributeList::AT_CFConsumed:
4231   case AttributeList::AT_NSConsumed:
4232     handleNSConsumedAttr(S, D, Attr);
4233     break;
4234   case AttributeList::AT_NSConsumesSelf:
4235     handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4236     break;
4237 
4238   case AttributeList::AT_NSReturnsAutoreleased:
4239   case AttributeList::AT_NSReturnsNotRetained:
4240   case AttributeList::AT_CFReturnsNotRetained:
4241   case AttributeList::AT_NSReturnsRetained:
4242   case AttributeList::AT_CFReturnsRetained:
4243     handleNSReturnsRetainedAttr(S, D, Attr);
4244     break;
4245   case AttributeList::AT_WorkGroupSizeHint:
4246     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4247     break;
4248   case AttributeList::AT_ReqdWorkGroupSize:
4249     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4250     break;
4251   case AttributeList::AT_VecTypeHint:
4252     handleVecTypeHint(S, D, Attr);
4253     break;
4254 
4255   case AttributeList::AT_InitPriority:
4256     handleInitPriorityAttr(S, D, Attr);
4257     break;
4258 
4259   case AttributeList::AT_Packed:
4260     handlePackedAttr(S, D, Attr);
4261     break;
4262   case AttributeList::AT_Section:
4263     handleSectionAttr(S, D, Attr);
4264     break;
4265   case AttributeList::AT_Unavailable:
4266     handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4267     break;
4268   case AttributeList::AT_ArcWeakrefUnavailable:
4269     handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4270     break;
4271   case AttributeList::AT_ObjCRootClass:
4272     handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4273     break;
4274   case AttributeList::AT_ObjCExplicitProtocolImpl:
4275     handleObjCSuppresProtocolAttr(S, D, Attr);
4276     break;
4277   case AttributeList::AT_ObjCRequiresPropertyDefs:
4278     handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4279     break;
4280   case AttributeList::AT_Unused:
4281     handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4282     break;
4283   case AttributeList::AT_ReturnsTwice:
4284     handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4285     break;
4286   case AttributeList::AT_Used:
4287     handleUsedAttr(S, D, Attr);
4288     break;
4289   case AttributeList::AT_Visibility:
4290     handleVisibilityAttr(S, D, Attr, false);
4291     break;
4292   case AttributeList::AT_TypeVisibility:
4293     handleVisibilityAttr(S, D, Attr, true);
4294     break;
4295   case AttributeList::AT_WarnUnused:
4296     handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4297     break;
4298   case AttributeList::AT_WarnUnusedResult:
4299     handleWarnUnusedResult(S, D, Attr);
4300     break;
4301   case AttributeList::AT_Weak:
4302     handleSimpleAttribute<WeakAttr>(S, D, Attr);
4303     break;
4304   case AttributeList::AT_WeakRef:
4305     handleWeakRefAttr(S, D, Attr);
4306     break;
4307   case AttributeList::AT_WeakImport:
4308     handleWeakImportAttr(S, D, Attr);
4309     break;
4310   case AttributeList::AT_TransparentUnion:
4311     handleTransparentUnionAttr(S, D, Attr);
4312     break;
4313   case AttributeList::AT_ObjCException:
4314     handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4315     break;
4316   case AttributeList::AT_ObjCMethodFamily:
4317     handleObjCMethodFamilyAttr(S, D, Attr);
4318     break;
4319   case AttributeList::AT_ObjCNSObject:
4320     handleObjCNSObject(S, D, Attr);
4321     break;
4322   case AttributeList::AT_Blocks:
4323     handleBlocksAttr(S, D, Attr);
4324     break;
4325   case AttributeList::AT_Sentinel:
4326     handleSentinelAttr(S, D, Attr);
4327     break;
4328   case AttributeList::AT_Const:
4329     handleSimpleAttribute<ConstAttr>(S, D, Attr);
4330     break;
4331   case AttributeList::AT_Pure:
4332     handleSimpleAttribute<PureAttr>(S, D, Attr);
4333     break;
4334   case AttributeList::AT_Cleanup:
4335     handleCleanupAttr(S, D, Attr);
4336     break;
4337   case AttributeList::AT_NoDebug:
4338     handleNoDebugAttr(S, D, Attr);
4339     break;
4340   case AttributeList::AT_NoDuplicate:
4341     handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4342     break;
4343   case AttributeList::AT_NoInline:
4344     handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4345     break;
4346   case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4347     handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4348     break;
4349   case AttributeList::AT_StdCall:
4350   case AttributeList::AT_CDecl:
4351   case AttributeList::AT_FastCall:
4352   case AttributeList::AT_ThisCall:
4353   case AttributeList::AT_Pascal:
4354   case AttributeList::AT_MSABI:
4355   case AttributeList::AT_SysVABI:
4356   case AttributeList::AT_Pcs:
4357   case AttributeList::AT_PnaclCall:
4358   case AttributeList::AT_IntelOclBicc:
4359     handleCallConvAttr(S, D, Attr);
4360     break;
4361   case AttributeList::AT_OpenCLKernel:
4362     handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4363     break;
4364   case AttributeList::AT_OpenCLImageAccess:
4365     handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4366     break;
4367 
4368   // Microsoft attributes:
4369   case AttributeList::AT_MsStruct:
4370     handleSimpleAttribute<MsStructAttr>(S, D, Attr);
4371     break;
4372   case AttributeList::AT_Uuid:
4373     handleUuidAttr(S, D, Attr);
4374     break;
4375   case AttributeList::AT_MSInheritance:
4376     handleMSInheritanceAttr(S, D, Attr);
4377     break;
4378   case AttributeList::AT_SelectAny:
4379     handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4380     break;
4381 
4382   // Thread safety attributes:
4383   case AttributeList::AT_AssertExclusiveLock:
4384     handleAssertExclusiveLockAttr(S, D, Attr);
4385     break;
4386   case AttributeList::AT_AssertSharedLock:
4387     handleAssertSharedLockAttr(S, D, Attr);
4388     break;
4389   case AttributeList::AT_GuardedVar:
4390     handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4391     break;
4392   case AttributeList::AT_PtGuardedVar:
4393     handlePtGuardedVarAttr(S, D, Attr);
4394     break;
4395   case AttributeList::AT_ScopedLockable:
4396     handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4397     break;
4398   case AttributeList::AT_NoSanitizeAddress:
4399     handleSimpleAttribute<NoSanitizeAddressAttr>(S, D, Attr);
4400     break;
4401   case AttributeList::AT_NoThreadSafetyAnalysis:
4402     handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
4403     break;
4404   case AttributeList::AT_NoSanitizeThread:
4405     handleSimpleAttribute<NoSanitizeThreadAttr>(S, D, Attr);
4406     break;
4407   case AttributeList::AT_NoSanitizeMemory:
4408     handleSimpleAttribute<NoSanitizeMemoryAttr>(S, D, Attr);
4409     break;
4410   case AttributeList::AT_GuardedBy:
4411     handleGuardedByAttr(S, D, Attr);
4412     break;
4413   case AttributeList::AT_PtGuardedBy:
4414     handlePtGuardedByAttr(S, D, Attr);
4415     break;
4416   case AttributeList::AT_ExclusiveLockFunction:
4417     handleExclusiveLockFunctionAttr(S, D, Attr);
4418     break;
4419   case AttributeList::AT_ExclusiveTrylockFunction:
4420     handleExclusiveTrylockFunctionAttr(S, D, Attr);
4421     break;
4422   case AttributeList::AT_LockReturned:
4423     handleLockReturnedAttr(S, D, Attr);
4424     break;
4425   case AttributeList::AT_LocksExcluded:
4426     handleLocksExcludedAttr(S, D, Attr);
4427     break;
4428   case AttributeList::AT_SharedLockFunction:
4429     handleSharedLockFunctionAttr(S, D, Attr);
4430     break;
4431   case AttributeList::AT_SharedTrylockFunction:
4432     handleSharedTrylockFunctionAttr(S, D, Attr);
4433     break;
4434   case AttributeList::AT_UnlockFunction:
4435     handleUnlockFunAttr(S, D, Attr);
4436     break;
4437   case AttributeList::AT_AcquiredBefore:
4438     handleAcquiredBeforeAttr(S, D, Attr);
4439     break;
4440   case AttributeList::AT_AcquiredAfter:
4441     handleAcquiredAfterAttr(S, D, Attr);
4442     break;
4443 
4444   // Capability analysis attributes.
4445   case AttributeList::AT_Capability:
4446   case AttributeList::AT_Lockable:
4447     handleCapabilityAttr(S, D, Attr);
4448     break;
4449   case AttributeList::AT_RequiresCapability:
4450     handleRequiresCapabilityAttr(S, D, Attr);
4451     break;
4452 
4453   case AttributeList::AT_AssertCapability:
4454     handleAssertCapabilityAttr(S, D, Attr);
4455     break;
4456   case AttributeList::AT_AcquireCapability:
4457     handleAcquireCapabilityAttr(S, D, Attr);
4458     break;
4459   case AttributeList::AT_ReleaseCapability:
4460     handleReleaseCapabilityAttr(S, D, Attr);
4461     break;
4462   case AttributeList::AT_TryAcquireCapability:
4463     handleTryAcquireCapabilityAttr(S, D, Attr);
4464     break;
4465 
4466   // Consumed analysis attributes.
4467   case AttributeList::AT_Consumable:
4468     handleConsumableAttr(S, D, Attr);
4469     break;
4470   case AttributeList::AT_ConsumableAutoCast:
4471     handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
4472     break;
4473   case AttributeList::AT_ConsumableSetOnRead:
4474     handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
4475     break;
4476   case AttributeList::AT_CallableWhen:
4477     handleCallableWhenAttr(S, D, Attr);
4478     break;
4479   case AttributeList::AT_ParamTypestate:
4480     handleParamTypestateAttr(S, D, Attr);
4481     break;
4482   case AttributeList::AT_ReturnTypestate:
4483     handleReturnTypestateAttr(S, D, Attr);
4484     break;
4485   case AttributeList::AT_SetTypestate:
4486     handleSetTypestateAttr(S, D, Attr);
4487     break;
4488   case AttributeList::AT_TestTypestate:
4489     handleTestTypestateAttr(S, D, Attr);
4490     break;
4491 
4492   // Type safety attributes.
4493   case AttributeList::AT_ArgumentWithTypeTag:
4494     handleArgumentWithTypeTagAttr(S, D, Attr);
4495     break;
4496   case AttributeList::AT_TypeTagForDatatype:
4497     handleTypeTagForDatatypeAttr(S, D, Attr);
4498     break;
4499   }
4500 }
4501 
4502 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4503 /// attribute list to the specified decl, ignoring any type attributes.
4504 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4505                                     const AttributeList *AttrList,
4506                                     bool IncludeCXX11Attributes) {
4507   for (const AttributeList* l = AttrList; l; l = l->getNext())
4508     ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4509 
4510   // FIXME: We should be able to handle these cases in TableGen.
4511   // GCC accepts
4512   // static int a9 __attribute__((weakref));
4513   // but that looks really pointless. We reject it.
4514   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4515     Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
4516       << cast<NamedDecl>(D);
4517     D->dropAttr<WeakRefAttr>();
4518     return;
4519   }
4520 
4521   if (!D->hasAttr<OpenCLKernelAttr>()) {
4522     // These attributes cannot be applied to a non-kernel function.
4523     if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
4524       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4525       D->setInvalidDecl();
4526     }
4527     if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
4528       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4529       D->setInvalidDecl();
4530     }
4531     if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
4532       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4533       D->setInvalidDecl();
4534     }
4535   }
4536 }
4537 
4538 // Annotation attributes are the only attributes allowed after an access
4539 // specifier.
4540 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4541                                           const AttributeList *AttrList) {
4542   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4543     if (l->getKind() == AttributeList::AT_Annotate) {
4544       handleAnnotateAttr(*this, ASDecl, *l);
4545     } else {
4546       Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4547       return true;
4548     }
4549   }
4550 
4551   return false;
4552 }
4553 
4554 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4555 /// contains any decl attributes that we should warn about.
4556 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4557   for ( ; A; A = A->getNext()) {
4558     // Only warn if the attribute is an unignored, non-type attribute.
4559     if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4560     if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4561 
4562     if (A->getKind() == AttributeList::UnknownAttribute) {
4563       S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4564         << A->getName() << A->getRange();
4565     } else {
4566       S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4567         << A->getName() << A->getRange();
4568     }
4569   }
4570 }
4571 
4572 /// checkUnusedDeclAttributes - Given a declarator which is not being
4573 /// used to build a declaration, complain about any decl attributes
4574 /// which might be lying around on it.
4575 void Sema::checkUnusedDeclAttributes(Declarator &D) {
4576   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4577   ::checkUnusedDeclAttributes(*this, D.getAttributes());
4578   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4579     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4580 }
4581 
4582 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
4583 /// \#pragma weak needs a non-definition decl and source may not have one.
4584 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4585                                       SourceLocation Loc) {
4586   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4587   NamedDecl *NewD = 0;
4588   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4589     FunctionDecl *NewFD;
4590     // FIXME: Missing call to CheckFunctionDeclaration().
4591     // FIXME: Mangling?
4592     // FIXME: Is the qualifier info correct?
4593     // FIXME: Is the DeclContext correct?
4594     NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4595                                  Loc, Loc, DeclarationName(II),
4596                                  FD->getType(), FD->getTypeSourceInfo(),
4597                                  SC_None, false/*isInlineSpecified*/,
4598                                  FD->hasPrototype(),
4599                                  false/*isConstexprSpecified*/);
4600     NewD = NewFD;
4601 
4602     if (FD->getQualifier())
4603       NewFD->setQualifierInfo(FD->getQualifierLoc());
4604 
4605     // Fake up parameter variables; they are declared as if this were
4606     // a typedef.
4607     QualType FDTy = FD->getType();
4608     if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4609       SmallVector<ParmVarDecl*, 16> Params;
4610       for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
4611                                                   AE = FT->param_type_end();
4612            AI != AE; ++AI) {
4613         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
4614         Param->setScopeInfo(0, Params.size());
4615         Params.push_back(Param);
4616       }
4617       NewFD->setParams(Params);
4618     }
4619   } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4620     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4621                            VD->getInnerLocStart(), VD->getLocation(), II,
4622                            VD->getType(), VD->getTypeSourceInfo(),
4623                            VD->getStorageClass());
4624     if (VD->getQualifier()) {
4625       VarDecl *NewVD = cast<VarDecl>(NewD);
4626       NewVD->setQualifierInfo(VD->getQualifierLoc());
4627     }
4628   }
4629   return NewD;
4630 }
4631 
4632 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4633 /// applied to it, possibly with an alias.
4634 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4635   if (W.getUsed()) return; // only do this once
4636   W.setUsed(true);
4637   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4638     IdentifierInfo *NDId = ND->getIdentifier();
4639     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4640     NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
4641                                             W.getLocation()));
4642     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4643     WeakTopLevelDecl.push_back(NewD);
4644     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4645     // to insert Decl at TU scope, sorry.
4646     DeclContext *SavedContext = CurContext;
4647     CurContext = Context.getTranslationUnitDecl();
4648     NewD->setDeclContext(CurContext);
4649     NewD->setLexicalDeclContext(CurContext);
4650     PushOnScopeChains(NewD, S);
4651     CurContext = SavedContext;
4652   } else { // just add weak to existing
4653     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
4654   }
4655 }
4656 
4657 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
4658   // It's valid to "forward-declare" #pragma weak, in which case we
4659   // have to do this.
4660   LoadExternalWeakUndeclaredIdentifiers();
4661   if (!WeakUndeclaredIdentifiers.empty()) {
4662     NamedDecl *ND = NULL;
4663     if (VarDecl *VD = dyn_cast<VarDecl>(D))
4664       if (VD->isExternC())
4665         ND = VD;
4666     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4667       if (FD->isExternC())
4668         ND = FD;
4669     if (ND) {
4670       if (IdentifierInfo *Id = ND->getIdentifier()) {
4671         llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4672           = WeakUndeclaredIdentifiers.find(Id);
4673         if (I != WeakUndeclaredIdentifiers.end()) {
4674           WeakInfo W = I->second;
4675           DeclApplyPragmaWeak(S, ND, W);
4676           WeakUndeclaredIdentifiers[Id] = W;
4677         }
4678       }
4679     }
4680   }
4681 }
4682 
4683 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4684 /// it, apply them to D.  This is a bit tricky because PD can have attributes
4685 /// specified in many different places, and we need to find and apply them all.
4686 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
4687   // Apply decl attributes from the DeclSpec if present.
4688   if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4689     ProcessDeclAttributeList(S, D, Attrs);
4690 
4691   // Walk the declarator structure, applying decl attributes that were in a type
4692   // position to the decl itself.  This handles cases like:
4693   //   int *__attr__(x)** D;
4694   // when X is a decl attribute.
4695   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
4696     if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
4697       ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
4698 
4699   // Finally, apply any attributes on the decl itself.
4700   if (const AttributeList *Attrs = PD.getAttributes())
4701     ProcessDeclAttributeList(S, D, Attrs);
4702 }
4703 
4704 /// Is the given declaration allowed to use a forbidden type?
4705 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
4706   // Private ivars are always okay.  Unfortunately, people don't
4707   // always properly make their ivars private, even in system headers.
4708   // Plus we need to make fields okay, too.
4709   // Function declarations in sys headers will be marked unavailable.
4710   if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
4711       !isa<FunctionDecl>(decl))
4712     return false;
4713 
4714   // Require it to be declared in a system header.
4715   return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
4716 }
4717 
4718 /// Handle a delayed forbidden-type diagnostic.
4719 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
4720                                        Decl *decl) {
4721   if (decl && isForbiddenTypeAllowed(S, decl)) {
4722     decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
4723                         "this system declaration uses an unsupported type",
4724                         diag.Loc));
4725     return;
4726   }
4727   if (S.getLangOpts().ObjCAutoRefCount)
4728     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
4729       // FIXME: we may want to suppress diagnostics for all
4730       // kind of forbidden type messages on unavailable functions.
4731       if (FD->hasAttr<UnavailableAttr>() &&
4732           diag.getForbiddenTypeDiagnostic() ==
4733           diag::err_arc_array_param_no_ownership) {
4734         diag.Triggered = true;
4735         return;
4736       }
4737     }
4738 
4739   S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
4740     << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
4741   diag.Triggered = true;
4742 }
4743 
4744 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
4745   assert(DelayedDiagnostics.getCurrentPool());
4746   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
4747   DelayedDiagnostics.popWithoutEmitting(state);
4748 
4749   // When delaying diagnostics to run in the context of a parsed
4750   // declaration, we only want to actually emit anything if parsing
4751   // succeeds.
4752   if (!decl) return;
4753 
4754   // We emit all the active diagnostics in this pool or any of its
4755   // parents.  In general, we'll get one pool for the decl spec
4756   // and a child pool for each declarator; in a decl group like:
4757   //   deprecated_typedef foo, *bar, baz();
4758   // only the declarator pops will be passed decls.  This is correct;
4759   // we really do need to consider delayed diagnostics from the decl spec
4760   // for each of the different declarations.
4761   const DelayedDiagnosticPool *pool = &poppedPool;
4762   do {
4763     for (DelayedDiagnosticPool::pool_iterator
4764            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
4765       // This const_cast is a bit lame.  Really, Triggered should be mutable.
4766       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
4767       if (diag.Triggered)
4768         continue;
4769 
4770       switch (diag.Kind) {
4771       case DelayedDiagnostic::Deprecation:
4772       case DelayedDiagnostic::Unavailable:
4773         // Don't bother giving deprecation/unavailable diagnostics if
4774         // the decl is invalid.
4775         if (!decl->isInvalidDecl())
4776           HandleDelayedAvailabilityCheck(diag, decl);
4777         break;
4778 
4779       case DelayedDiagnostic::Access:
4780         HandleDelayedAccessCheck(diag, decl);
4781         break;
4782 
4783       case DelayedDiagnostic::ForbiddenType:
4784         handleDelayedForbiddenType(*this, diag, decl);
4785         break;
4786       }
4787     }
4788   } while ((pool = pool->getParent()));
4789 }
4790 
4791 /// Given a set of delayed diagnostics, re-emit them as if they had
4792 /// been delayed in the current context instead of in the given pool.
4793 /// Essentially, this just moves them to the current pool.
4794 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
4795   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
4796   assert(curPool && "re-emitting in undelayed context not supported");
4797   curPool->steal(pool);
4798 }
4799 
4800 static bool isDeclDeprecated(Decl *D) {
4801   do {
4802     if (D->isDeprecated())
4803       return true;
4804     // A category implicitly has the availability of the interface.
4805     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4806       return CatD->getClassInterface()->isDeprecated();
4807   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4808   return false;
4809 }
4810 
4811 static bool isDeclUnavailable(Decl *D) {
4812   do {
4813     if (D->isUnavailable())
4814       return true;
4815     // A category implicitly has the availability of the interface.
4816     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4817       return CatD->getClassInterface()->isUnavailable();
4818   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4819   return false;
4820 }
4821 
4822 static void
4823 DoEmitAvailabilityWarning(Sema &S,
4824                           DelayedDiagnostic::DDKind K,
4825                           Decl *Ctx,
4826                           const NamedDecl *D,
4827                           StringRef Message,
4828                           SourceLocation Loc,
4829                           const ObjCInterfaceDecl *UnknownObjCClass,
4830                           const ObjCPropertyDecl *ObjCProperty) {
4831 
4832   // Diagnostics for deprecated or unavailable.
4833   unsigned diag, diag_message, diag_fwdclass_message;
4834 
4835   // Matches 'diag::note_property_attribute' options.
4836   unsigned property_note_select;
4837 
4838   // Matches diag::note_availability_specified_here.
4839   unsigned available_here_select_kind;
4840 
4841   // Don't warn if our current context is deprecated or unavailable.
4842   switch (K) {
4843     case DelayedDiagnostic::Deprecation:
4844       if (isDeclDeprecated(Ctx))
4845         return;
4846       diag = diag::warn_deprecated;
4847       diag_message = diag::warn_deprecated_message;
4848       diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
4849       property_note_select = /* deprecated */ 0;
4850       available_here_select_kind = /* deprecated */ 2;
4851       break;
4852 
4853     case DelayedDiagnostic::Unavailable:
4854       if (isDeclUnavailable(Ctx))
4855         return;
4856       diag = diag::err_unavailable;
4857       diag_message = diag::err_unavailable_message;
4858       diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
4859       property_note_select = /* unavailable */ 1;
4860       available_here_select_kind = /* unavailable */ 0;
4861       break;
4862 
4863     default:
4864       llvm_unreachable("Neither a deprecation or unavailable kind");
4865   }
4866 
4867   DeclarationName Name = D->getDeclName();
4868   if (!Message.empty()) {
4869     S.Diag(Loc, diag_message) << Name << Message;
4870     if (ObjCProperty)
4871       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
4872         << ObjCProperty->getDeclName() << property_note_select;
4873   } else if (!UnknownObjCClass) {
4874     S.Diag(Loc, diag) << Name;
4875     if (ObjCProperty)
4876       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
4877         << ObjCProperty->getDeclName() << property_note_select;
4878   } else {
4879     S.Diag(Loc, diag_fwdclass_message) << Name;
4880     S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
4881   }
4882 
4883   S.Diag(D->getLocation(), diag::note_availability_specified_here)
4884     << D << available_here_select_kind;
4885 }
4886 
4887 void Sema::HandleDelayedAvailabilityCheck(DelayedDiagnostic &DD,
4888                                           Decl *Ctx) {
4889   DD.Triggered = true;
4890   DoEmitAvailabilityWarning(*this,
4891                             (DelayedDiagnostic::DDKind) DD.Kind,
4892                             Ctx,
4893                             DD.getDeprecationDecl(),
4894                             DD.getDeprecationMessage(),
4895                             DD.Loc,
4896                             DD.getUnknownObjCClass(),
4897                             DD.getObjCProperty());
4898 }
4899 
4900 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
4901                                    NamedDecl *D, StringRef Message,
4902                                    SourceLocation Loc,
4903                                    const ObjCInterfaceDecl *UnknownObjCClass,
4904                                    const ObjCPropertyDecl  *ObjCProperty) {
4905   // Delay if we're currently parsing a declaration.
4906   if (DelayedDiagnostics.shouldDelayDiagnostics()) {
4907     DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(AD, Loc, D,
4908                                                                UnknownObjCClass,
4909                                                                ObjCProperty,
4910                                                                Message));
4911     return;
4912   }
4913 
4914   Decl *Ctx = cast<Decl>(getCurLexicalContext());
4915   DelayedDiagnostic::DDKind K;
4916   switch (AD) {
4917     case AD_Deprecation:
4918       K = DelayedDiagnostic::Deprecation;
4919       break;
4920     case AD_Unavailable:
4921       K = DelayedDiagnostic::Unavailable;
4922       break;
4923   }
4924 
4925   DoEmitAvailabilityWarning(*this, K, Ctx, D, Message, Loc,
4926                             UnknownObjCClass, ObjCProperty);
4927 }
4928