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