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