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