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