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