SemaDeclAttr.cpp revision 51ceb7bab599ea7d39d290ff5e88e4a1f0f5bc5c
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/DeclTemplate.h"
20#include "clang/AST/DeclObjC.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.first == Res1.second)
299    return false;
300
301  DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
302    S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
303  if (Res2.first == Res2.second)
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}
2153
2154VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2155                                          VisibilityAttr::VisibilityType Vis) {
2156  if (isa<TypedefNameDecl>(D)) {
2157    Diag(Range.getBegin(), diag::warn_attribute_ignored) << "visibility";
2158    return NULL;
2159  }
2160  VisibilityAttr *ExistingAttr = D->getAttr<VisibilityAttr>();
2161  if (ExistingAttr) {
2162    VisibilityAttr::VisibilityType ExistingVis = ExistingAttr->getVisibility();
2163    if (ExistingVis == Vis)
2164      return NULL;
2165    Diag(ExistingAttr->getLocation(), diag::err_mismatched_visibility);
2166    Diag(Range.getBegin(), diag::note_previous_attribute);
2167    D->dropAttr<VisibilityAttr>();
2168  }
2169  return ::new (Context) VisibilityAttr(Range, Context, Vis);
2170}
2171
2172static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2173  // check the attribute arguments.
2174  if(!checkAttributeNumArgs(S, Attr, 1))
2175    return;
2176
2177  Expr *Arg = Attr.getArg(0);
2178  Arg = Arg->IgnoreParenCasts();
2179  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2180
2181  if (!Str || !Str->isAscii()) {
2182    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2183      << "visibility" << 1;
2184    return;
2185  }
2186
2187  StringRef TypeStr = Str->getString();
2188  VisibilityAttr::VisibilityType type;
2189
2190  if (TypeStr == "default")
2191    type = VisibilityAttr::Default;
2192  else if (TypeStr == "hidden")
2193    type = VisibilityAttr::Hidden;
2194  else if (TypeStr == "internal")
2195    type = VisibilityAttr::Hidden; // FIXME
2196  else if (TypeStr == "protected") {
2197    // Complain about attempts to use protected visibility on targets
2198    // (like Darwin) that don't support it.
2199    if (!S.Context.getTargetInfo().hasProtectedVisibility()) {
2200      S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2201      type = VisibilityAttr::Default;
2202    } else {
2203      type = VisibilityAttr::Protected;
2204    }
2205  } else {
2206    S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
2207    return;
2208  }
2209
2210  VisibilityAttr *NewAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type);
2211  if (NewAttr)
2212    D->addAttr(NewAttr);
2213}
2214
2215static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2216                                       const AttributeList &Attr) {
2217  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
2218  if (!method) {
2219    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2220      << ExpectedMethod;
2221    return;
2222  }
2223
2224  if (Attr.getNumArgs() != 0 || !Attr.getParameterName()) {
2225    if (!Attr.getParameterName() && Attr.getNumArgs() == 1) {
2226      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2227        << "objc_method_family" << 1;
2228    } else {
2229      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2230    }
2231    Attr.setInvalid();
2232    return;
2233  }
2234
2235  StringRef param = Attr.getParameterName()->getName();
2236  ObjCMethodFamilyAttr::FamilyKind family;
2237  if (param == "none")
2238    family = ObjCMethodFamilyAttr::OMF_None;
2239  else if (param == "alloc")
2240    family = ObjCMethodFamilyAttr::OMF_alloc;
2241  else if (param == "copy")
2242    family = ObjCMethodFamilyAttr::OMF_copy;
2243  else if (param == "init")
2244    family = ObjCMethodFamilyAttr::OMF_init;
2245  else if (param == "mutableCopy")
2246    family = ObjCMethodFamilyAttr::OMF_mutableCopy;
2247  else if (param == "new")
2248    family = ObjCMethodFamilyAttr::OMF_new;
2249  else {
2250    // Just warn and ignore it.  This is future-proof against new
2251    // families being used in system headers.
2252    S.Diag(Attr.getParameterLoc(), diag::warn_unknown_method_family);
2253    return;
2254  }
2255
2256  if (family == ObjCMethodFamilyAttr::OMF_init &&
2257      !method->getResultType()->isObjCObjectPointerType()) {
2258    S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2259      << method->getResultType();
2260    // Ignore the attribute.
2261    return;
2262  }
2263
2264  method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2265                                                       S.Context, family));
2266}
2267
2268static void handleObjCExceptionAttr(Sema &S, Decl *D,
2269                                    const AttributeList &Attr) {
2270  if (!checkAttributeNumArgs(S, Attr, 0))
2271    return;
2272
2273  ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
2274  if (OCI == 0) {
2275    S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
2276    return;
2277  }
2278
2279  D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getRange(), S.Context));
2280}
2281
2282static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2283  if (Attr.getNumArgs() != 0) {
2284    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2285    return;
2286  }
2287  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2288    QualType T = TD->getUnderlyingType();
2289    if (!T->isCARCBridgableType()) {
2290      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2291      return;
2292    }
2293  }
2294  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2295    QualType T = PD->getType();
2296    if (!T->isCARCBridgableType()) {
2297      S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2298      return;
2299    }
2300  }
2301  else {
2302    // It is okay to include this attribute on properties, e.g.:
2303    //
2304    //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2305    //
2306    // In this case it follows tradition and suppresses an error in the above
2307    // case.
2308    S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2309  }
2310  D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getRange(), S.Context));
2311}
2312
2313static void
2314handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2315  if (Attr.getNumArgs() != 0) {
2316    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2317    return;
2318  }
2319
2320  if (!isa<FunctionDecl>(D)) {
2321    S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
2322    return;
2323  }
2324
2325  D->addAttr(::new (S.Context) OverloadableAttr(Attr.getRange(), S.Context));
2326}
2327
2328static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2329  if (!Attr.getParameterName()) {
2330    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2331      << "blocks" << 1;
2332    return;
2333  }
2334
2335  if (Attr.getNumArgs() != 0) {
2336    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2337    return;
2338  }
2339
2340  BlocksAttr::BlockType type;
2341  if (Attr.getParameterName()->isStr("byref"))
2342    type = BlocksAttr::ByRef;
2343  else {
2344    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2345      << "blocks" << Attr.getParameterName();
2346    return;
2347  }
2348
2349  D->addAttr(::new (S.Context) BlocksAttr(Attr.getRange(), S.Context, type));
2350}
2351
2352static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2353  // check the attribute arguments.
2354  if (Attr.getNumArgs() > 2) {
2355    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2356    return;
2357  }
2358
2359  unsigned sentinel = 0;
2360  if (Attr.getNumArgs() > 0) {
2361    Expr *E = Attr.getArg(0);
2362    llvm::APSInt Idx(32);
2363    if (E->isTypeDependent() || E->isValueDependent() ||
2364        !E->isIntegerConstantExpr(Idx, S.Context)) {
2365      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2366       << "sentinel" << 1 << E->getSourceRange();
2367      return;
2368    }
2369
2370    if (Idx.isSigned() && Idx.isNegative()) {
2371      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2372        << E->getSourceRange();
2373      return;
2374    }
2375
2376    sentinel = Idx.getZExtValue();
2377  }
2378
2379  unsigned nullPos = 0;
2380  if (Attr.getNumArgs() > 1) {
2381    Expr *E = Attr.getArg(1);
2382    llvm::APSInt Idx(32);
2383    if (E->isTypeDependent() || E->isValueDependent() ||
2384        !E->isIntegerConstantExpr(Idx, S.Context)) {
2385      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2386        << "sentinel" << 2 << E->getSourceRange();
2387      return;
2388    }
2389    nullPos = Idx.getZExtValue();
2390
2391    if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2392      // FIXME: This error message could be improved, it would be nice
2393      // to say what the bounds actually are.
2394      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2395        << E->getSourceRange();
2396      return;
2397    }
2398  }
2399
2400  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2401    const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2402    if (isa<FunctionNoProtoType>(FT)) {
2403      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2404      return;
2405    }
2406
2407    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2408      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2409      return;
2410    }
2411  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2412    if (!MD->isVariadic()) {
2413      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2414      return;
2415    }
2416  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2417    if (!BD->isVariadic()) {
2418      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2419      return;
2420    }
2421  } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2422    QualType Ty = V->getType();
2423    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2424      const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
2425       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2426      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2427        int m = Ty->isFunctionPointerType() ? 0 : 1;
2428        S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2429        return;
2430      }
2431    } else {
2432      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2433        << Attr.getName() << ExpectedFunctionMethodOrBlock;
2434      return;
2435    }
2436  } else {
2437    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2438      << Attr.getName() << ExpectedFunctionMethodOrBlock;
2439    return;
2440  }
2441  D->addAttr(::new (S.Context) SentinelAttr(Attr.getRange(), S.Context, sentinel,
2442                                            nullPos));
2443}
2444
2445static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2446  // check the attribute arguments.
2447  if (!checkAttributeNumArgs(S, Attr, 0))
2448    return;
2449
2450  if (!isFunction(D) && !isa<ObjCMethodDecl>(D) && !isa<CXXRecordDecl>(D)) {
2451    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2452      << Attr.getName() << ExpectedFunctionOrMethod;
2453    return;
2454  }
2455
2456  if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
2457    S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2458      << Attr.getName() << 0;
2459    return;
2460  }
2461  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2462    if (MD->getResultType()->isVoidType()) {
2463      S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2464      << Attr.getName() << 1;
2465      return;
2466    }
2467
2468  D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getRange(), S.Context));
2469}
2470
2471static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2472  // check the attribute arguments.
2473  if (Attr.hasParameterOrArguments()) {
2474    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2475    return;
2476  }
2477
2478  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
2479    if (isa<CXXRecordDecl>(D)) {
2480      D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2481      return;
2482    }
2483    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2484      << Attr.getName() << ExpectedVariableOrFunction;
2485    return;
2486  }
2487
2488  NamedDecl *nd = cast<NamedDecl>(D);
2489
2490  // 'weak' only applies to declarations with external linkage.
2491  if (hasEffectivelyInternalLinkage(nd)) {
2492    S.Diag(Attr.getLoc(), diag::err_attribute_weak_static);
2493    return;
2494  }
2495
2496  nd->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2497}
2498
2499static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2500  // check the attribute arguments.
2501  if (!checkAttributeNumArgs(S, Attr, 0))
2502    return;
2503
2504
2505  // weak_import only applies to variable & function declarations.
2506  bool isDef = false;
2507  if (!D->canBeWeakImported(isDef)) {
2508    if (isDef)
2509      S.Diag(Attr.getLoc(),
2510             diag::warn_attribute_weak_import_invalid_on_definition)
2511        << "weak_import" << 2 /*variable and function*/;
2512    else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2513             (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2514              (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2515      // Nothing to warn about here.
2516    } else
2517      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2518        << Attr.getName() << ExpectedVariableOrFunction;
2519
2520    return;
2521  }
2522
2523  D->addAttr(::new (S.Context) WeakImportAttr(Attr.getRange(), S.Context));
2524}
2525
2526// Handles reqd_work_group_size and work_group_size_hint.
2527static void handleWorkGroupSize(Sema &S, Decl *D,
2528                                const AttributeList &Attr) {
2529  assert(Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2530      || Attr.getKind() == AttributeList::AT_WorkGroupSizeHint);
2531
2532  // Attribute has 3 arguments.
2533  if (!checkAttributeNumArgs(S, Attr, 3)) return;
2534
2535  unsigned WGSize[3];
2536  for (unsigned i = 0; i < 3; ++i) {
2537    Expr *E = Attr.getArg(i);
2538    llvm::APSInt ArgNum(32);
2539    if (E->isTypeDependent() || E->isValueDependent() ||
2540        !E->isIntegerConstantExpr(ArgNum, S.Context)) {
2541      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2542        << Attr.getName()->getName() << E->getSourceRange();
2543      return;
2544    }
2545    WGSize[i] = (unsigned) ArgNum.getZExtValue();
2546  }
2547
2548  if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2549    && D->hasAttr<ReqdWorkGroupSizeAttr>()) {
2550      ReqdWorkGroupSizeAttr *A = D->getAttr<ReqdWorkGroupSizeAttr>();
2551      if (!(A->getXDim() == WGSize[0] &&
2552            A->getYDim() == WGSize[1] &&
2553            A->getZDim() == WGSize[2])) {
2554        S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2555          Attr.getName();
2556      }
2557  }
2558
2559  if (Attr.getKind() == AttributeList::AT_WorkGroupSizeHint
2560    && D->hasAttr<WorkGroupSizeHintAttr>()) {
2561      WorkGroupSizeHintAttr *A = D->getAttr<WorkGroupSizeHintAttr>();
2562      if (!(A->getXDim() == WGSize[0] &&
2563            A->getYDim() == WGSize[1] &&
2564            A->getZDim() == WGSize[2])) {
2565        S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2566          Attr.getName();
2567      }
2568  }
2569
2570  if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize)
2571    D->addAttr(::new (S.Context)
2572                 ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
2573                                       WGSize[0], WGSize[1], WGSize[2]));
2574  else
2575    D->addAttr(::new (S.Context)
2576                 WorkGroupSizeHintAttr(Attr.getRange(), S.Context,
2577                                       WGSize[0], WGSize[1], WGSize[2]));
2578}
2579
2580SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2581                                    StringRef Name) {
2582  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2583    if (ExistingAttr->getName() == Name)
2584      return NULL;
2585    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2586    Diag(Range.getBegin(), diag::note_previous_attribute);
2587    return NULL;
2588  }
2589  return ::new (Context) SectionAttr(Range, Context, Name);
2590}
2591
2592static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2593  // Attribute has no arguments.
2594  if (!checkAttributeNumArgs(S, Attr, 1))
2595    return;
2596
2597  // Make sure that there is a string literal as the sections's single
2598  // argument.
2599  Expr *ArgExpr = Attr.getArg(0);
2600  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
2601  if (!SE) {
2602    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
2603    return;
2604  }
2605
2606  // If the target wants to validate the section specifier, make it happen.
2607  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(SE->getString());
2608  if (!Error.empty()) {
2609    S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
2610    << Error;
2611    return;
2612  }
2613
2614  // This attribute cannot be applied to local variables.
2615  if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2616    S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
2617    return;
2618  }
2619  SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(),
2620                                            SE->getString());
2621  if (NewAttr)
2622    D->addAttr(NewAttr);
2623}
2624
2625
2626static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2627  // check the attribute arguments.
2628  if (Attr.hasParameterOrArguments()) {
2629    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2630    return;
2631  }
2632
2633  if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2634    if (Existing->getLocation().isInvalid())
2635      Existing->setRange(Attr.getRange());
2636  } else {
2637    D->addAttr(::new (S.Context) NoThrowAttr(Attr.getRange(), S.Context));
2638  }
2639}
2640
2641static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2642  // check the attribute arguments.
2643  if (Attr.hasParameterOrArguments()) {
2644    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2645    return;
2646  }
2647
2648  if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2649   if (Existing->getLocation().isInvalid())
2650     Existing->setRange(Attr.getRange());
2651  } else {
2652    D->addAttr(::new (S.Context) ConstAttr(Attr.getRange(), S.Context));
2653  }
2654}
2655
2656static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2657  // check the attribute arguments.
2658  if (!checkAttributeNumArgs(S, Attr, 0))
2659    return;
2660
2661  D->addAttr(::new (S.Context) PureAttr(Attr.getRange(), S.Context));
2662}
2663
2664static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2665  if (!Attr.getParameterName()) {
2666    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2667    return;
2668  }
2669
2670  if (Attr.getNumArgs() != 0) {
2671    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2672    return;
2673  }
2674
2675  VarDecl *VD = dyn_cast<VarDecl>(D);
2676
2677  if (!VD || !VD->hasLocalStorage()) {
2678    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
2679    return;
2680  }
2681
2682  // Look up the function
2683  // FIXME: Lookup probably isn't looking in the right place
2684  NamedDecl *CleanupDecl
2685    = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
2686                         Attr.getParameterLoc(), Sema::LookupOrdinaryName);
2687  if (!CleanupDecl) {
2688    S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
2689      Attr.getParameterName();
2690    return;
2691  }
2692
2693  FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
2694  if (!FD) {
2695    S.Diag(Attr.getParameterLoc(),
2696           diag::err_attribute_cleanup_arg_not_function)
2697      << Attr.getParameterName();
2698    return;
2699  }
2700
2701  if (FD->getNumParams() != 1) {
2702    S.Diag(Attr.getParameterLoc(),
2703           diag::err_attribute_cleanup_func_must_take_one_arg)
2704      << Attr.getParameterName();
2705    return;
2706  }
2707
2708  // We're currently more strict than GCC about what function types we accept.
2709  // If this ever proves to be a problem it should be easy to fix.
2710  QualType Ty = S.Context.getPointerType(VD->getType());
2711  QualType ParamTy = FD->getParamDecl(0)->getType();
2712  if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2713                                   ParamTy, Ty) != Sema::Compatible) {
2714    S.Diag(Attr.getParameterLoc(),
2715           diag::err_attribute_cleanup_func_arg_incompatible_type) <<
2716      Attr.getParameterName() << ParamTy << Ty;
2717    return;
2718  }
2719
2720  D->addAttr(::new (S.Context) CleanupAttr(Attr.getRange(), S.Context, FD));
2721  S.MarkFunctionReferenced(Attr.getParameterLoc(), FD);
2722}
2723
2724/// Handle __attribute__((format_arg((idx)))) attribute based on
2725/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2726static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2727  if (!checkAttributeNumArgs(S, Attr, 1))
2728    return;
2729
2730  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2731    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2732      << Attr.getName() << ExpectedFunction;
2733    return;
2734  }
2735
2736  // In C++ the implicit 'this' function parameter also counts, and they are
2737  // counted from one.
2738  bool HasImplicitThisParam = isInstanceMethod(D);
2739  unsigned NumArgs  = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2740  unsigned FirstIdx = 1;
2741
2742  // checks for the 2nd argument
2743  Expr *IdxExpr = Attr.getArg(0);
2744  llvm::APSInt Idx(32);
2745  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2746      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2747    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2748    << "format" << 2 << IdxExpr->getSourceRange();
2749    return;
2750  }
2751
2752  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2753    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2754    << "format" << 2 << IdxExpr->getSourceRange();
2755    return;
2756  }
2757
2758  unsigned ArgIdx = Idx.getZExtValue() - 1;
2759
2760  if (HasImplicitThisParam) {
2761    if (ArgIdx == 0) {
2762      S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
2763        << "format_arg" << IdxExpr->getSourceRange();
2764      return;
2765    }
2766    ArgIdx--;
2767  }
2768
2769  // make sure the format string is really a string
2770  QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2771
2772  bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2773  if (not_nsstring_type &&
2774      !isCFStringType(Ty, S.Context) &&
2775      (!Ty->isPointerType() ||
2776       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2777    // FIXME: Should highlight the actual expression that has the wrong type.
2778    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2779    << (not_nsstring_type ? "a string type" : "an NSString")
2780       << IdxExpr->getSourceRange();
2781    return;
2782  }
2783  Ty = getFunctionOrMethodResultType(D);
2784  if (!isNSStringType(Ty, S.Context) &&
2785      !isCFStringType(Ty, S.Context) &&
2786      (!Ty->isPointerType() ||
2787       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2788    // FIXME: Should highlight the actual expression that has the wrong type.
2789    S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2790    << (not_nsstring_type ? "string type" : "NSString")
2791       << IdxExpr->getSourceRange();
2792    return;
2793  }
2794
2795  D->addAttr(::new (S.Context) FormatArgAttr(Attr.getRange(), S.Context,
2796                                             Idx.getZExtValue()));
2797}
2798
2799enum FormatAttrKind {
2800  CFStringFormat,
2801  NSStringFormat,
2802  StrftimeFormat,
2803  SupportedFormat,
2804  IgnoredFormat,
2805  InvalidFormat
2806};
2807
2808/// getFormatAttrKind - Map from format attribute names to supported format
2809/// types.
2810static FormatAttrKind getFormatAttrKind(StringRef Format) {
2811  return llvm::StringSwitch<FormatAttrKind>(Format)
2812    // Check for formats that get handled specially.
2813    .Case("NSString", NSStringFormat)
2814    .Case("CFString", CFStringFormat)
2815    .Case("strftime", StrftimeFormat)
2816
2817    // Otherwise, check for supported formats.
2818    .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2819    .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2820    .Case("kprintf", SupportedFormat) // OpenBSD.
2821
2822    .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2823    .Default(InvalidFormat);
2824}
2825
2826/// Handle __attribute__((init_priority(priority))) attributes based on
2827/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2828static void handleInitPriorityAttr(Sema &S, Decl *D,
2829                                   const AttributeList &Attr) {
2830  if (!S.getLangOpts().CPlusPlus) {
2831    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2832    return;
2833  }
2834
2835  if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
2836    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2837    Attr.setInvalid();
2838    return;
2839  }
2840  QualType T = dyn_cast<VarDecl>(D)->getType();
2841  if (S.Context.getAsArrayType(T))
2842    T = S.Context.getBaseElementType(T);
2843  if (!T->getAs<RecordType>()) {
2844    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2845    Attr.setInvalid();
2846    return;
2847  }
2848
2849  if (Attr.getNumArgs() != 1) {
2850    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2851    Attr.setInvalid();
2852    return;
2853  }
2854  Expr *priorityExpr = Attr.getArg(0);
2855
2856  llvm::APSInt priority(32);
2857  if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
2858      !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
2859    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2860    << "init_priority" << priorityExpr->getSourceRange();
2861    Attr.setInvalid();
2862    return;
2863  }
2864  unsigned prioritynum = priority.getZExtValue();
2865  if (prioritynum < 101 || prioritynum > 65535) {
2866    S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2867    <<  priorityExpr->getSourceRange();
2868    Attr.setInvalid();
2869    return;
2870  }
2871  D->addAttr(::new (S.Context) InitPriorityAttr(Attr.getRange(), S.Context,
2872                                                prioritynum));
2873}
2874
2875FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
2876                                  int FormatIdx, int FirstArg) {
2877  // Check whether we already have an equivalent format attribute.
2878  for (specific_attr_iterator<FormatAttr>
2879         i = D->specific_attr_begin<FormatAttr>(),
2880         e = D->specific_attr_end<FormatAttr>();
2881       i != e ; ++i) {
2882    FormatAttr *f = *i;
2883    if (f->getType() == Format &&
2884        f->getFormatIdx() == FormatIdx &&
2885        f->getFirstArg() == FirstArg) {
2886      // If we don't have a valid location for this attribute, adopt the
2887      // location.
2888      if (f->getLocation().isInvalid())
2889        f->setRange(Range);
2890      return NULL;
2891    }
2892  }
2893
2894  return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2895                                    FirstArg);
2896}
2897
2898/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2899/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2900static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2901
2902  if (!Attr.getParameterName()) {
2903    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2904      << "format" << 1;
2905    return;
2906  }
2907
2908  if (Attr.getNumArgs() != 2) {
2909    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
2910    return;
2911  }
2912
2913  if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
2914    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2915      << Attr.getName() << ExpectedFunction;
2916    return;
2917  }
2918
2919  // In C++ the implicit 'this' function parameter also counts, and they are
2920  // counted from one.
2921  bool HasImplicitThisParam = isInstanceMethod(D);
2922  unsigned NumArgs  = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
2923  unsigned FirstIdx = 1;
2924
2925  StringRef Format = Attr.getParameterName()->getName();
2926
2927  // Normalize the argument, __foo__ becomes foo.
2928  if (Format.startswith("__") && Format.endswith("__"))
2929    Format = Format.substr(2, Format.size() - 4);
2930
2931  // Check for supported formats.
2932  FormatAttrKind Kind = getFormatAttrKind(Format);
2933
2934  if (Kind == IgnoredFormat)
2935    return;
2936
2937  if (Kind == InvalidFormat) {
2938    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2939      << "format" << Attr.getParameterName()->getName();
2940    return;
2941  }
2942
2943  // checks for the 2nd argument
2944  Expr *IdxExpr = Attr.getArg(0);
2945  llvm::APSInt Idx(32);
2946  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
2947      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
2948    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2949      << "format" << 2 << IdxExpr->getSourceRange();
2950    return;
2951  }
2952
2953  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2954    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2955      << "format" << 2 << IdxExpr->getSourceRange();
2956    return;
2957  }
2958
2959  // FIXME: Do we need to bounds check?
2960  unsigned ArgIdx = Idx.getZExtValue() - 1;
2961
2962  if (HasImplicitThisParam) {
2963    if (ArgIdx == 0) {
2964      S.Diag(Attr.getLoc(),
2965             diag::err_format_attribute_implicit_this_format_string)
2966        << IdxExpr->getSourceRange();
2967      return;
2968    }
2969    ArgIdx--;
2970  }
2971
2972  // make sure the format string is really a string
2973  QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2974
2975  if (Kind == CFStringFormat) {
2976    if (!isCFStringType(Ty, S.Context)) {
2977      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2978        << "a CFString" << IdxExpr->getSourceRange();
2979      return;
2980    }
2981  } else if (Kind == NSStringFormat) {
2982    // FIXME: do we need to check if the type is NSString*?  What are the
2983    // semantics?
2984    if (!isNSStringType(Ty, S.Context)) {
2985      // FIXME: Should highlight the actual expression that has the wrong type.
2986      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2987        << "an NSString" << IdxExpr->getSourceRange();
2988      return;
2989    }
2990  } else if (!Ty->isPointerType() ||
2991             !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2992    // FIXME: Should highlight the actual expression that has the wrong type.
2993    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2994      << "a string type" << IdxExpr->getSourceRange();
2995    return;
2996  }
2997
2998  // check the 3rd argument
2999  Expr *FirstArgExpr = Attr.getArg(1);
3000  llvm::APSInt FirstArg(32);
3001  if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
3002      !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
3003    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3004      << "format" << 3 << FirstArgExpr->getSourceRange();
3005    return;
3006  }
3007
3008  // check if the function is variadic if the 3rd argument non-zero
3009  if (FirstArg != 0) {
3010    if (isFunctionOrMethodVariadic(D)) {
3011      ++NumArgs; // +1 for ...
3012    } else {
3013      S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3014      return;
3015    }
3016  }
3017
3018  // strftime requires FirstArg to be 0 because it doesn't read from any
3019  // variable the input is just the current time + the format string.
3020  if (Kind == StrftimeFormat) {
3021    if (FirstArg != 0) {
3022      S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3023        << FirstArgExpr->getSourceRange();
3024      return;
3025    }
3026  // if 0 it disables parameter checking (to use with e.g. va_list)
3027  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3028    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3029      << "format" << 3 << FirstArgExpr->getSourceRange();
3030    return;
3031  }
3032
3033  FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), Format,
3034                                          Idx.getZExtValue(),
3035                                          FirstArg.getZExtValue());
3036  if (NewAttr)
3037    D->addAttr(NewAttr);
3038}
3039
3040static void handleTransparentUnionAttr(Sema &S, Decl *D,
3041                                       const AttributeList &Attr) {
3042  // check the attribute arguments.
3043  if (!checkAttributeNumArgs(S, Attr, 0))
3044    return;
3045
3046
3047  // Try to find the underlying union declaration.
3048  RecordDecl *RD = 0;
3049  TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3050  if (TD && TD->getUnderlyingType()->isUnionType())
3051    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3052  else
3053    RD = dyn_cast<RecordDecl>(D);
3054
3055  if (!RD || !RD->isUnion()) {
3056    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3057      << Attr.getName() << ExpectedUnion;
3058    return;
3059  }
3060
3061  if (!RD->isCompleteDefinition()) {
3062    S.Diag(Attr.getLoc(),
3063        diag::warn_transparent_union_attribute_not_definition);
3064    return;
3065  }
3066
3067  RecordDecl::field_iterator Field = RD->field_begin(),
3068                          FieldEnd = RD->field_end();
3069  if (Field == FieldEnd) {
3070    S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3071    return;
3072  }
3073
3074  FieldDecl *FirstField = *Field;
3075  QualType FirstType = FirstField->getType();
3076  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3077    S.Diag(FirstField->getLocation(),
3078           diag::warn_transparent_union_attribute_floating)
3079      << FirstType->isVectorType() << FirstType;
3080    return;
3081  }
3082
3083  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3084  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3085  for (; Field != FieldEnd; ++Field) {
3086    QualType FieldType = Field->getType();
3087    if (S.Context.getTypeSize(FieldType) != FirstSize ||
3088        S.Context.getTypeAlign(FieldType) != FirstAlign) {
3089      // Warn if we drop the attribute.
3090      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3091      unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3092                                 : S.Context.getTypeAlign(FieldType);
3093      S.Diag(Field->getLocation(),
3094          diag::warn_transparent_union_attribute_field_size_align)
3095        << isSize << Field->getDeclName() << FieldBits;
3096      unsigned FirstBits = isSize? FirstSize : FirstAlign;
3097      S.Diag(FirstField->getLocation(),
3098             diag::note_transparent_union_first_field_size_align)
3099        << isSize << FirstBits;
3100      return;
3101    }
3102  }
3103
3104  RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getRange(), S.Context));
3105}
3106
3107static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3108  // check the attribute arguments.
3109  if (!checkAttributeNumArgs(S, Attr, 1))
3110    return;
3111
3112  Expr *ArgExpr = Attr.getArg(0);
3113  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
3114
3115  // Make sure that there is a string literal as the annotation's single
3116  // argument.
3117  if (!SE) {
3118    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
3119    return;
3120  }
3121
3122  // Don't duplicate annotations that are already set.
3123  for (specific_attr_iterator<AnnotateAttr>
3124       i = D->specific_attr_begin<AnnotateAttr>(),
3125       e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
3126      if ((*i)->getAnnotation() == SE->getString())
3127          return;
3128  }
3129  D->addAttr(::new (S.Context) AnnotateAttr(Attr.getRange(), S.Context,
3130                                            SE->getString()));
3131}
3132
3133static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3134  // check the attribute arguments.
3135  if (Attr.getNumArgs() > 1) {
3136    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3137    return;
3138  }
3139
3140  //FIXME: The C++0x version of this attribute has more limited applicabilty
3141  //       than GNU's, and should error out when it is used to specify a
3142  //       weaker alignment, rather than being silently ignored.
3143
3144  if (Attr.getNumArgs() == 0) {
3145    D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3146               true, 0, Attr.isDeclspecAttribute()));
3147    return;
3148  }
3149
3150  S.AddAlignedAttr(Attr.getRange(), D, Attr.getArg(0),
3151                   Attr.isDeclspecAttribute());
3152}
3153
3154void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3155                          bool isDeclSpec) {
3156  // FIXME: Handle pack-expansions here.
3157  if (DiagnoseUnexpandedParameterPack(E))
3158    return;
3159
3160  if (E->isTypeDependent() || E->isValueDependent()) {
3161    // Save dependent expressions in the AST to be instantiated.
3162    D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E,
3163                                           isDeclSpec));
3164    return;
3165  }
3166
3167  SourceLocation AttrLoc = AttrRange.getBegin();
3168  // FIXME: Cache the number on the Attr object?
3169  llvm::APSInt Alignment(32);
3170  ExprResult ICE
3171    = VerifyIntegerConstantExpression(E, &Alignment,
3172        diag::err_aligned_attribute_argument_not_int,
3173        /*AllowFold*/ false);
3174  if (ICE.isInvalid())
3175    return;
3176  if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
3177    Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
3178      << E->getSourceRange();
3179    return;
3180  }
3181  if (isDeclSpec) {
3182    // We've already verified it's a power of 2, now let's make sure it's
3183    // 8192 or less.
3184    if (Alignment.getZExtValue() > 8192) {
3185      Diag(AttrLoc, diag::err_attribute_aligned_greater_than_8192)
3186        << E->getSourceRange();
3187      return;
3188    }
3189  }
3190
3191  D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, ICE.take(),
3192                                         isDeclSpec));
3193}
3194
3195void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3196                          bool isDeclSpec) {
3197  // FIXME: Cache the number on the Attr object if non-dependent?
3198  // FIXME: Perform checking of type validity
3199  D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3200                                         isDeclSpec));
3201  return;
3202}
3203
3204/// handleModeAttr - This attribute modifies the width of a decl with primitive
3205/// type.
3206///
3207/// Despite what would be logical, the mode attribute is a decl attribute, not a
3208/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3209/// HImode, not an intermediate pointer.
3210static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3211  // This attribute isn't documented, but glibc uses it.  It changes
3212  // the width of an int or unsigned int to the specified size.
3213
3214  // Check that there aren't any arguments
3215  if (!checkAttributeNumArgs(S, Attr, 0))
3216    return;
3217
3218
3219  IdentifierInfo *Name = Attr.getParameterName();
3220  if (!Name) {
3221    S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
3222    return;
3223  }
3224
3225  StringRef Str = Attr.getParameterName()->getName();
3226
3227  // Normalize the attribute name, __foo__ becomes foo.
3228  if (Str.startswith("__") && Str.endswith("__"))
3229    Str = Str.substr(2, Str.size() - 4);
3230
3231  unsigned DestWidth = 0;
3232  bool IntegerMode = true;
3233  bool ComplexMode = false;
3234  switch (Str.size()) {
3235  case 2:
3236    switch (Str[0]) {
3237    case 'Q': DestWidth = 8; break;
3238    case 'H': DestWidth = 16; break;
3239    case 'S': DestWidth = 32; break;
3240    case 'D': DestWidth = 64; break;
3241    case 'X': DestWidth = 96; break;
3242    case 'T': DestWidth = 128; break;
3243    }
3244    if (Str[1] == 'F') {
3245      IntegerMode = false;
3246    } else if (Str[1] == 'C') {
3247      IntegerMode = false;
3248      ComplexMode = true;
3249    } else if (Str[1] != 'I') {
3250      DestWidth = 0;
3251    }
3252    break;
3253  case 4:
3254    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3255    // pointer on PIC16 and other embedded platforms.
3256    if (Str == "word")
3257      DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3258    else if (Str == "byte")
3259      DestWidth = S.Context.getTargetInfo().getCharWidth();
3260    break;
3261  case 7:
3262    if (Str == "pointer")
3263      DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3264    break;
3265  }
3266
3267  QualType OldTy;
3268  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3269    OldTy = TD->getUnderlyingType();
3270  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3271    OldTy = VD->getType();
3272  else {
3273    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3274      << "mode" << Attr.getRange();
3275    return;
3276  }
3277
3278  if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3279    S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3280  else if (IntegerMode) {
3281    if (!OldTy->isIntegralOrEnumerationType())
3282      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3283  } else if (ComplexMode) {
3284    if (!OldTy->isComplexType())
3285      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3286  } else {
3287    if (!OldTy->isFloatingType())
3288      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3289  }
3290
3291  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3292  // and friends, at least with glibc.
3293  // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
3294  // width on unusual platforms.
3295  // FIXME: Make sure floating-point mappings are accurate
3296  // FIXME: Support XF and TF types
3297  QualType NewTy;
3298  switch (DestWidth) {
3299  case 0:
3300    S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
3301    return;
3302  default:
3303    S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3304    return;
3305  case 8:
3306    if (!IntegerMode) {
3307      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3308      return;
3309    }
3310    if (OldTy->isSignedIntegerType())
3311      NewTy = S.Context.SignedCharTy;
3312    else
3313      NewTy = S.Context.UnsignedCharTy;
3314    break;
3315  case 16:
3316    if (!IntegerMode) {
3317      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3318      return;
3319    }
3320    if (OldTy->isSignedIntegerType())
3321      NewTy = S.Context.ShortTy;
3322    else
3323      NewTy = S.Context.UnsignedShortTy;
3324    break;
3325  case 32:
3326    if (!IntegerMode)
3327      NewTy = S.Context.FloatTy;
3328    else if (OldTy->isSignedIntegerType())
3329      NewTy = S.Context.IntTy;
3330    else
3331      NewTy = S.Context.UnsignedIntTy;
3332    break;
3333  case 64:
3334    if (!IntegerMode)
3335      NewTy = S.Context.DoubleTy;
3336    else if (OldTy->isSignedIntegerType())
3337      if (S.Context.getTargetInfo().getLongWidth() == 64)
3338        NewTy = S.Context.LongTy;
3339      else
3340        NewTy = S.Context.LongLongTy;
3341    else
3342      if (S.Context.getTargetInfo().getLongWidth() == 64)
3343        NewTy = S.Context.UnsignedLongTy;
3344      else
3345        NewTy = S.Context.UnsignedLongLongTy;
3346    break;
3347  case 96:
3348    NewTy = S.Context.LongDoubleTy;
3349    break;
3350  case 128:
3351    if (!IntegerMode) {
3352      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3353      return;
3354    }
3355    if (OldTy->isSignedIntegerType())
3356      NewTy = S.Context.Int128Ty;
3357    else
3358      NewTy = S.Context.UnsignedInt128Ty;
3359    break;
3360  }
3361
3362  if (ComplexMode) {
3363    NewTy = S.Context.getComplexType(NewTy);
3364  }
3365
3366  // Install the new type.
3367  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
3368    // FIXME: preserve existing source info.
3369    TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
3370  } else
3371    cast<ValueDecl>(D)->setType(NewTy);
3372}
3373
3374static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3375  // check the attribute arguments.
3376  if (!checkAttributeNumArgs(S, Attr, 0))
3377    return;
3378
3379  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3380    if (!VD->hasGlobalStorage())
3381      S.Diag(Attr.getLoc(),
3382             diag::warn_attribute_requires_functions_or_static_globals)
3383        << Attr.getName();
3384  } else if (!isFunctionOrMethod(D)) {
3385    S.Diag(Attr.getLoc(),
3386           diag::warn_attribute_requires_functions_or_static_globals)
3387      << Attr.getName();
3388    return;
3389  }
3390
3391  D->addAttr(::new (S.Context) NoDebugAttr(Attr.getRange(), S.Context));
3392}
3393
3394static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3395  // check the attribute arguments.
3396  if (!checkAttributeNumArgs(S, Attr, 0))
3397    return;
3398
3399
3400  if (!isa<FunctionDecl>(D)) {
3401    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3402      << Attr.getName() << ExpectedFunction;
3403    return;
3404  }
3405
3406  D->addAttr(::new (S.Context) NoInlineAttr(Attr.getRange(), S.Context));
3407}
3408
3409static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
3410                                           const AttributeList &Attr) {
3411  // check the attribute arguments.
3412  if (!checkAttributeNumArgs(S, Attr, 0))
3413    return;
3414
3415
3416  if (!isa<FunctionDecl>(D)) {
3417    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3418      << Attr.getName() << ExpectedFunction;
3419    return;
3420  }
3421
3422  D->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getRange(),
3423                                                        S.Context));
3424}
3425
3426static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3427  if (S.LangOpts.CUDA) {
3428    // check the attribute arguments.
3429    if (Attr.hasParameterOrArguments()) {
3430      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3431      return;
3432    }
3433
3434    if (!isa<VarDecl>(D)) {
3435      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3436        << Attr.getName() << ExpectedVariable;
3437      return;
3438    }
3439
3440    D->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getRange(), S.Context));
3441  } else {
3442    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
3443  }
3444}
3445
3446static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3447  if (S.LangOpts.CUDA) {
3448    // check the attribute arguments.
3449    if (Attr.getNumArgs() != 0) {
3450      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
3451      return;
3452    }
3453
3454    if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
3455      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3456        << Attr.getName() << ExpectedVariableOrFunction;
3457      return;
3458    }
3459
3460    D->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getRange(), S.Context));
3461  } else {
3462    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
3463  }
3464}
3465
3466static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3467  if (S.LangOpts.CUDA) {
3468    // check the attribute arguments.
3469    if (!checkAttributeNumArgs(S, Attr, 0))
3470      return;
3471
3472    if (!isa<FunctionDecl>(D)) {
3473      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3474        << Attr.getName() << ExpectedFunction;
3475      return;
3476    }
3477
3478    FunctionDecl *FD = cast<FunctionDecl>(D);
3479    if (!FD->getResultType()->isVoidType()) {
3480      TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3481      if (FunctionTypeLoc* FTL = dyn_cast<FunctionTypeLoc>(&TL)) {
3482        S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3483          << FD->getType()
3484          << FixItHint::CreateReplacement(FTL->getResultLoc().getSourceRange(),
3485                                          "void");
3486      } else {
3487        S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3488          << FD->getType();
3489      }
3490      return;
3491    }
3492
3493    D->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getRange(), S.Context));
3494  } else {
3495    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
3496  }
3497}
3498
3499static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3500  if (S.LangOpts.CUDA) {
3501    // check the attribute arguments.
3502    if (!checkAttributeNumArgs(S, Attr, 0))
3503      return;
3504
3505
3506    if (!isa<FunctionDecl>(D)) {
3507      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3508        << Attr.getName() << ExpectedFunction;
3509      return;
3510    }
3511
3512    D->addAttr(::new (S.Context) CUDAHostAttr(Attr.getRange(), S.Context));
3513  } else {
3514    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
3515  }
3516}
3517
3518static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3519  if (S.LangOpts.CUDA) {
3520    // check the attribute arguments.
3521    if (!checkAttributeNumArgs(S, Attr, 0))
3522      return;
3523
3524
3525    if (!isa<VarDecl>(D)) {
3526      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3527        << Attr.getName() << ExpectedVariable;
3528      return;
3529    }
3530
3531    D->addAttr(::new (S.Context) CUDASharedAttr(Attr.getRange(), S.Context));
3532  } else {
3533    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
3534  }
3535}
3536
3537static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3538  // check the attribute arguments.
3539  if (!checkAttributeNumArgs(S, Attr, 0))
3540    return;
3541
3542  FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
3543  if (Fn == 0) {
3544    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3545      << Attr.getName() << ExpectedFunction;
3546    return;
3547  }
3548
3549  if (!Fn->isInlineSpecified()) {
3550    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3551    return;
3552  }
3553
3554  D->addAttr(::new (S.Context) GNUInlineAttr(Attr.getRange(), S.Context));
3555}
3556
3557static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3558  if (hasDeclarator(D)) return;
3559
3560  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3561  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3562  CallingConv CC;
3563  if (S.CheckCallingConvAttr(Attr, CC))
3564    return;
3565
3566  if (!isa<ObjCMethodDecl>(D)) {
3567    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3568      << Attr.getName() << ExpectedFunctionOrMethod;
3569    return;
3570  }
3571
3572  switch (Attr.getKind()) {
3573  case AttributeList::AT_FastCall:
3574    D->addAttr(::new (S.Context) FastCallAttr(Attr.getRange(), S.Context));
3575    return;
3576  case AttributeList::AT_StdCall:
3577    D->addAttr(::new (S.Context) StdCallAttr(Attr.getRange(), S.Context));
3578    return;
3579  case AttributeList::AT_ThisCall:
3580    D->addAttr(::new (S.Context) ThisCallAttr(Attr.getRange(), S.Context));
3581    return;
3582  case AttributeList::AT_CDecl:
3583    D->addAttr(::new (S.Context) CDeclAttr(Attr.getRange(), S.Context));
3584    return;
3585  case AttributeList::AT_Pascal:
3586    D->addAttr(::new (S.Context) PascalAttr(Attr.getRange(), S.Context));
3587    return;
3588  case AttributeList::AT_Pcs: {
3589    PcsAttr::PCSType PCS;
3590    switch (CC) {
3591    case CC_AAPCS:
3592      PCS = PcsAttr::AAPCS;
3593      break;
3594    case CC_AAPCS_VFP:
3595      PCS = PcsAttr::AAPCS_VFP;
3596      break;
3597    default:
3598      llvm_unreachable("unexpected calling convention in pcs attribute");
3599    }
3600
3601    D->addAttr(::new (S.Context) PcsAttr(Attr.getRange(), S.Context, PCS));
3602    return;
3603  }
3604  case AttributeList::AT_PnaclCall:
3605    D->addAttr(::new (S.Context) PnaclCallAttr(Attr.getRange(), S.Context));
3606    return;
3607
3608  default:
3609    llvm_unreachable("unexpected attribute kind");
3610  }
3611}
3612
3613static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
3614  assert(!Attr.isInvalid());
3615  D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
3616}
3617
3618bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC) {
3619  if (attr.isInvalid())
3620    return true;
3621
3622  unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3623  if (attr.getNumArgs() != ReqArgs || attr.getParameterName()) {
3624    Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << ReqArgs;
3625    attr.setInvalid();
3626    return true;
3627  }
3628
3629  // TODO: diagnose uses of these conventions on the wrong target. Or, better
3630  // move to TargetAttributesSema one day.
3631  switch (attr.getKind()) {
3632  case AttributeList::AT_CDecl: CC = CC_C; break;
3633  case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3634  case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3635  case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3636  case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3637  case AttributeList::AT_Pcs: {
3638    Expr *Arg = attr.getArg(0);
3639    StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
3640    if (!Str || !Str->isAscii()) {
3641      Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3642        << "pcs" << 1;
3643      attr.setInvalid();
3644      return true;
3645    }
3646
3647    StringRef StrRef = Str->getString();
3648    if (StrRef == "aapcs") {
3649      CC = CC_AAPCS;
3650      break;
3651    } else if (StrRef == "aapcs-vfp") {
3652      CC = CC_AAPCS_VFP;
3653      break;
3654    }
3655
3656    attr.setInvalid();
3657    Diag(attr.getLoc(), diag::err_invalid_pcs);
3658    return true;
3659  }
3660  case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3661  default: llvm_unreachable("unexpected attribute kind");
3662  }
3663
3664  const TargetInfo &TI = Context.getTargetInfo();
3665  TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3666  if (A == TargetInfo::CCCR_Warning) {
3667    Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3668    CC = TI.getDefaultCallingConv();
3669  }
3670
3671  return false;
3672}
3673
3674static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3675  if (hasDeclarator(D)) return;
3676
3677  unsigned numParams;
3678  if (S.CheckRegparmAttr(Attr, numParams))
3679    return;
3680
3681  if (!isa<ObjCMethodDecl>(D)) {
3682    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3683      << Attr.getName() << ExpectedFunctionOrMethod;
3684    return;
3685  }
3686
3687  D->addAttr(::new (S.Context) RegparmAttr(Attr.getRange(), S.Context, numParams));
3688}
3689
3690/// Checks a regparm attribute, returning true if it is ill-formed and
3691/// otherwise setting numParams to the appropriate value.
3692bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3693  if (Attr.isInvalid())
3694    return true;
3695
3696  if (Attr.getNumArgs() != 1) {
3697    Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3698    Attr.setInvalid();
3699    return true;
3700  }
3701
3702  Expr *NumParamsExpr = Attr.getArg(0);
3703  llvm::APSInt NumParams(32);
3704  if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
3705      !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
3706    Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3707      << "regparm" << NumParamsExpr->getSourceRange();
3708    Attr.setInvalid();
3709    return true;
3710  }
3711
3712  if (Context.getTargetInfo().getRegParmMax() == 0) {
3713    Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3714      << NumParamsExpr->getSourceRange();
3715    Attr.setInvalid();
3716    return true;
3717  }
3718
3719  numParams = NumParams.getZExtValue();
3720  if (numParams > Context.getTargetInfo().getRegParmMax()) {
3721    Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3722      << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3723    Attr.setInvalid();
3724    return true;
3725  }
3726
3727  return false;
3728}
3729
3730static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
3731  if (S.LangOpts.CUDA) {
3732    // check the attribute arguments.
3733    if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
3734      // FIXME: 0 is not okay.
3735      S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
3736      return;
3737    }
3738
3739    if (!isFunctionOrMethod(D)) {
3740      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3741        << Attr.getName() << ExpectedFunctionOrMethod;
3742      return;
3743    }
3744
3745    Expr *MaxThreadsExpr = Attr.getArg(0);
3746    llvm::APSInt MaxThreads(32);
3747    if (MaxThreadsExpr->isTypeDependent() ||
3748        MaxThreadsExpr->isValueDependent() ||
3749        !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
3750      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3751        << "launch_bounds" << 1 << MaxThreadsExpr->getSourceRange();
3752      return;
3753    }
3754
3755    llvm::APSInt MinBlocks(32);
3756    if (Attr.getNumArgs() > 1) {
3757      Expr *MinBlocksExpr = Attr.getArg(1);
3758      if (MinBlocksExpr->isTypeDependent() ||
3759          MinBlocksExpr->isValueDependent() ||
3760          !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
3761        S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
3762          << "launch_bounds" << 2 << MinBlocksExpr->getSourceRange();
3763        return;
3764      }
3765    }
3766
3767    D->addAttr(::new (S.Context) CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3768                                                      MaxThreads.getZExtValue(),
3769                                                     MinBlocks.getZExtValue()));
3770  } else {
3771    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
3772  }
3773}
3774
3775static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3776                                          const AttributeList &Attr) {
3777  StringRef AttrName = Attr.getName()->getName();
3778  if (!Attr.getParameterName()) {
3779    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_identifier)
3780      << Attr.getName() << /* arg num = */ 1;
3781    return;
3782  }
3783
3784  if (Attr.getNumArgs() != 2) {
3785    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3786      << /* required args = */ 3;
3787    return;
3788  }
3789
3790  IdentifierInfo *ArgumentKind = Attr.getParameterName();
3791
3792  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3793    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3794      << Attr.getName() << ExpectedFunctionOrMethod;
3795    return;
3796  }
3797
3798  uint64_t ArgumentIdx;
3799  if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
3800                                          Attr.getLoc(), 2,
3801                                          Attr.getArg(0), ArgumentIdx))
3802    return;
3803
3804  uint64_t TypeTagIdx;
3805  if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
3806                                          Attr.getLoc(), 3,
3807                                          Attr.getArg(1), TypeTagIdx))
3808    return;
3809
3810  bool IsPointer = (AttrName == "pointer_with_type_tag");
3811  if (IsPointer) {
3812    // Ensure that buffer has a pointer type.
3813    QualType BufferTy = getFunctionOrMethodArgType(D, ArgumentIdx);
3814    if (!BufferTy->isPointerType()) {
3815      S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3816        << AttrName;
3817    }
3818  }
3819
3820  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(Attr.getRange(),
3821                                                       S.Context,
3822                                                       ArgumentKind,
3823                                                       ArgumentIdx,
3824                                                       TypeTagIdx,
3825                                                       IsPointer));
3826}
3827
3828static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3829                                         const AttributeList &Attr) {
3830  IdentifierInfo *PointerKind = Attr.getParameterName();
3831  if (!PointerKind) {
3832    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_identifier)
3833      << "type_tag_for_datatype" << 1;
3834    return;
3835  }
3836
3837  QualType MatchingCType = S.GetTypeFromParser(Attr.getMatchingCType(), NULL);
3838
3839  D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
3840                                  Attr.getRange(),
3841                                  S.Context,
3842                                  PointerKind,
3843                                  MatchingCType,
3844                                  Attr.getLayoutCompatible(),
3845                                  Attr.getMustBeNull()));
3846}
3847
3848//===----------------------------------------------------------------------===//
3849// Checker-specific attribute handlers.
3850//===----------------------------------------------------------------------===//
3851
3852static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3853  return type->isDependentType() ||
3854         type->isObjCObjectPointerType() ||
3855         S.Context.isObjCNSObjectType(type);
3856}
3857static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3858  return type->isDependentType() ||
3859         type->isPointerType() ||
3860         isValidSubjectOfNSAttribute(S, type);
3861}
3862
3863static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3864  ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
3865  if (!param) {
3866    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3867      << Attr.getRange() << Attr.getName() << ExpectedParameter;
3868    return;
3869  }
3870
3871  bool typeOK, cf;
3872  if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3873    typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3874    cf = false;
3875  } else {
3876    typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3877    cf = true;
3878  }
3879
3880  if (!typeOK) {
3881    S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3882      << Attr.getRange() << Attr.getName() << cf;
3883    return;
3884  }
3885
3886  if (cf)
3887    param->addAttr(::new (S.Context) CFConsumedAttr(Attr.getRange(), S.Context));
3888  else
3889    param->addAttr(::new (S.Context) NSConsumedAttr(Attr.getRange(), S.Context));
3890}
3891
3892static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
3893                                     const AttributeList &Attr) {
3894  if (!isa<ObjCMethodDecl>(D)) {
3895    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3896      << Attr.getRange() << Attr.getName() << ExpectedMethod;
3897    return;
3898  }
3899
3900  D->addAttr(::new (S.Context) NSConsumesSelfAttr(Attr.getRange(), S.Context));
3901}
3902
3903static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3904                                        const AttributeList &Attr) {
3905
3906  QualType returnType;
3907
3908  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3909    returnType = MD->getResultType();
3910  else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3911           (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3912    return; // ignore: was handled as a type attribute
3913  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3914    returnType = PD->getType();
3915  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3916    returnType = FD->getResultType();
3917  else {
3918    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3919        << Attr.getRange() << Attr.getName()
3920        << ExpectedFunctionOrMethod;
3921    return;
3922  }
3923
3924  bool typeOK;
3925  bool cf;
3926  switch (Attr.getKind()) {
3927  default: llvm_unreachable("invalid ownership attribute");
3928  case AttributeList::AT_NSReturnsAutoreleased:
3929  case AttributeList::AT_NSReturnsRetained:
3930  case AttributeList::AT_NSReturnsNotRetained:
3931    typeOK = isValidSubjectOfNSAttribute(S, returnType);
3932    cf = false;
3933    break;
3934
3935  case AttributeList::AT_CFReturnsRetained:
3936  case AttributeList::AT_CFReturnsNotRetained:
3937    typeOK = isValidSubjectOfCFAttribute(S, returnType);
3938    cf = true;
3939    break;
3940  }
3941
3942  if (!typeOK) {
3943    S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3944      << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3945    return;
3946  }
3947
3948  switch (Attr.getKind()) {
3949    default:
3950      llvm_unreachable("invalid ownership attribute");
3951    case AttributeList::AT_NSReturnsAutoreleased:
3952      D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(Attr.getRange(),
3953                                                             S.Context));
3954      return;
3955    case AttributeList::AT_CFReturnsNotRetained:
3956      D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getRange(),
3957                                                            S.Context));
3958      return;
3959    case AttributeList::AT_NSReturnsNotRetained:
3960      D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getRange(),
3961                                                            S.Context));
3962      return;
3963    case AttributeList::AT_CFReturnsRetained:
3964      D->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getRange(),
3965                                                         S.Context));
3966      return;
3967    case AttributeList::AT_NSReturnsRetained:
3968      D->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getRange(),
3969                                                         S.Context));
3970      return;
3971  };
3972}
3973
3974static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3975                                              const AttributeList &attr) {
3976  SourceLocation loc = attr.getLoc();
3977
3978  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
3979
3980  if (!method) {
3981    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3982      << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
3983    return;
3984  }
3985
3986  // Check that the method returns a normal pointer.
3987  QualType resultType = method->getResultType();
3988
3989  if (!resultType->isReferenceType() &&
3990      (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3991    S.Diag(method->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3992      << SourceRange(loc)
3993      << attr.getName() << /*method*/ 1 << /*non-retainable pointer*/ 2;
3994
3995    // Drop the attribute.
3996    return;
3997  }
3998
3999  method->addAttr(
4000    ::new (S.Context) ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context));
4001}
4002
4003static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4004                                        const AttributeList &attr) {
4005  SourceLocation loc = attr.getLoc();
4006  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4007
4008  if (!method) {
4009   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4010   << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
4011    return;
4012  }
4013  DeclContext *DC = method->getDeclContext();
4014  if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4015    S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4016    << attr.getName() << 0;
4017    S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4018    return;
4019  }
4020  if (method->getMethodFamily() == OMF_dealloc) {
4021    S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4022    << attr.getName() << 1;
4023    return;
4024  }
4025
4026  method->addAttr(
4027    ::new (S.Context) ObjCRequiresSuperAttr(attr.getRange(), S.Context));
4028}
4029
4030/// Handle cf_audited_transfer and cf_unknown_transfer.
4031static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
4032  if (!isa<FunctionDecl>(D)) {
4033    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4034      << A.getRange() << A.getName() << ExpectedFunction;
4035    return;
4036  }
4037
4038  bool IsAudited = (A.getKind() == AttributeList::AT_CFAuditedTransfer);
4039
4040  // Check whether there's a conflicting attribute already present.
4041  Attr *Existing;
4042  if (IsAudited) {
4043    Existing = D->getAttr<CFUnknownTransferAttr>();
4044  } else {
4045    Existing = D->getAttr<CFAuditedTransferAttr>();
4046  }
4047  if (Existing) {
4048    S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
4049      << A.getName()
4050      << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
4051      << A.getRange() << Existing->getRange();
4052    return;
4053  }
4054
4055  // All clear;  add the attribute.
4056  if (IsAudited) {
4057    D->addAttr(
4058      ::new (S.Context) CFAuditedTransferAttr(A.getRange(), S.Context));
4059  } else {
4060    D->addAttr(
4061      ::new (S.Context) CFUnknownTransferAttr(A.getRange(), S.Context));
4062  }
4063}
4064
4065static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
4066                                const AttributeList &Attr) {
4067  RecordDecl *RD = dyn_cast<RecordDecl>(D);
4068  if (!RD || RD->isUnion()) {
4069    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4070      << Attr.getRange() << Attr.getName() << ExpectedStruct;
4071  }
4072
4073  IdentifierInfo *ParmName = Attr.getParameterName();
4074
4075  // In Objective-C, verify that the type names an Objective-C type.
4076  // We don't want to check this outside of ObjC because people sometimes
4077  // do crazy C declarations of Objective-C types.
4078  if (ParmName && S.getLangOpts().ObjC1) {
4079    // Check for an existing type with this name.
4080    LookupResult R(S, DeclarationName(ParmName), Attr.getParameterLoc(),
4081                   Sema::LookupOrdinaryName);
4082    if (S.LookupName(R, Sc)) {
4083      NamedDecl *Target = R.getFoundDecl();
4084      if (Target && !isa<ObjCInterfaceDecl>(Target)) {
4085        S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
4086        S.Diag(Target->getLocStart(), diag::note_declared_at);
4087      }
4088    }
4089  }
4090
4091  D->addAttr(::new (S.Context) NSBridgedAttr(Attr.getRange(), S.Context,
4092                                             ParmName));
4093}
4094
4095static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4096                                    const AttributeList &Attr) {
4097  if (hasDeclarator(D)) return;
4098
4099  S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4100    << Attr.getRange() << Attr.getName() << ExpectedVariable;
4101}
4102
4103static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4104                                          const AttributeList &Attr) {
4105  if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
4106    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4107      << Attr.getRange() << Attr.getName() << ExpectedVariable;
4108    return;
4109  }
4110
4111  ValueDecl *vd = cast<ValueDecl>(D);
4112  QualType type = vd->getType();
4113
4114  if (!type->isDependentType() &&
4115      !type->isObjCLifetimeType()) {
4116    S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4117      << type;
4118    return;
4119  }
4120
4121  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4122
4123  // If we have no lifetime yet, check the lifetime we're presumably
4124  // going to infer.
4125  if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4126    lifetime = type->getObjCARCImplicitLifetime();
4127
4128  switch (lifetime) {
4129  case Qualifiers::OCL_None:
4130    assert(type->isDependentType() &&
4131           "didn't infer lifetime for non-dependent type?");
4132    break;
4133
4134  case Qualifiers::OCL_Weak:   // meaningful
4135  case Qualifiers::OCL_Strong: // meaningful
4136    break;
4137
4138  case Qualifiers::OCL_ExplicitNone:
4139  case Qualifiers::OCL_Autoreleasing:
4140    S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4141      << (lifetime == Qualifiers::OCL_Autoreleasing);
4142    break;
4143  }
4144
4145  D->addAttr(::new (S.Context)
4146                 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context));
4147}
4148
4149//===----------------------------------------------------------------------===//
4150// Microsoft specific attribute handlers.
4151//===----------------------------------------------------------------------===//
4152
4153static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4154  if (S.LangOpts.MicrosoftExt || S.LangOpts.Borland) {
4155    // check the attribute arguments.
4156    if (!checkAttributeNumArgs(S, Attr, 1))
4157      return;
4158
4159    Expr *Arg = Attr.getArg(0);
4160    StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
4161    if (!Str || !Str->isAscii()) {
4162      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
4163        << "uuid" << 1;
4164      return;
4165    }
4166
4167    StringRef StrRef = Str->getString();
4168
4169    bool IsCurly = StrRef.size() > 1 && StrRef.front() == '{' &&
4170                   StrRef.back() == '}';
4171
4172    // Validate GUID length.
4173    if (IsCurly && StrRef.size() != 38) {
4174      S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4175      return;
4176    }
4177    if (!IsCurly && StrRef.size() != 36) {
4178      S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4179      return;
4180    }
4181
4182    // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4183    // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
4184    StringRef::iterator I = StrRef.begin();
4185    if (IsCurly) // Skip the optional '{'
4186       ++I;
4187
4188    for (int i = 0; i < 36; ++i) {
4189      if (i == 8 || i == 13 || i == 18 || i == 23) {
4190        if (*I != '-') {
4191          S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4192          return;
4193        }
4194      } else if (!isxdigit(*I)) {
4195        S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
4196        return;
4197      }
4198      I++;
4199    }
4200
4201    D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context,
4202                                          Str->getString()));
4203  } else
4204    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "uuid";
4205}
4206
4207static void handleInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4208  if (!S.LangOpts.MicrosoftExt) {
4209    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4210    return;
4211  }
4212
4213  AttributeList::Kind Kind = Attr.getKind();
4214  if (Kind == AttributeList::AT_SingleInheritance)
4215    D->addAttr(
4216        ::new (S.Context) SingleInheritanceAttr(Attr.getRange(), S.Context));
4217  else if (Kind == AttributeList::AT_MultipleInheritance)
4218    D->addAttr(
4219        ::new (S.Context) MultipleInheritanceAttr(Attr.getRange(), S.Context));
4220  else if (Kind == AttributeList::AT_VirtualInheritance)
4221    D->addAttr(
4222        ::new (S.Context) VirtualInheritanceAttr(Attr.getRange(), S.Context));
4223}
4224
4225static void handlePortabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4226  if (S.LangOpts.MicrosoftExt) {
4227    AttributeList::Kind Kind = Attr.getKind();
4228    if (Kind == AttributeList::AT_Ptr32)
4229      D->addAttr(
4230          ::new (S.Context) Ptr32Attr(Attr.getRange(), S.Context));
4231    else if (Kind == AttributeList::AT_Ptr64)
4232      D->addAttr(
4233          ::new (S.Context) Ptr64Attr(Attr.getRange(), S.Context));
4234    else if (Kind == AttributeList::AT_Win64)
4235      D->addAttr(
4236          ::new (S.Context) Win64Attr(Attr.getRange(), S.Context));
4237  } else
4238    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4239}
4240
4241static void handleForceInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4242  if (S.LangOpts.MicrosoftExt)
4243    D->addAttr(::new (S.Context) ForceInlineAttr(Attr.getRange(), S.Context));
4244  else
4245    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4246}
4247
4248//===----------------------------------------------------------------------===//
4249// Top Level Sema Entry Points
4250//===----------------------------------------------------------------------===//
4251
4252static void ProcessNonInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4253                                          const AttributeList &Attr) {
4254  switch (Attr.getKind()) {
4255  case AttributeList::AT_CUDADevice:  handleDeviceAttr      (S, D, Attr); break;
4256  case AttributeList::AT_CUDAHost:    handleHostAttr        (S, D, Attr); break;
4257  case AttributeList::AT_Overloadable:handleOverloadableAttr(S, D, Attr); break;
4258  default:
4259    break;
4260  }
4261}
4262
4263static void ProcessInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
4264                                       const AttributeList &Attr) {
4265  switch (Attr.getKind()) {
4266    case AttributeList::AT_IBAction:          handleIBAction(S, D, Attr); break;
4267    case AttributeList::AT_IBOutlet:          handleIBOutlet(S, D, Attr); break;
4268    case AttributeList::AT_IBOutletCollection:
4269      handleIBOutletCollection(S, D, Attr); break;
4270  case AttributeList::AT_AddressSpace:
4271  case AttributeList::AT_OpenCLImageAccess:
4272  case AttributeList::AT_ObjCGC:
4273  case AttributeList::AT_VectorSize:
4274  case AttributeList::AT_NeonVectorType:
4275  case AttributeList::AT_NeonPolyVectorType:
4276    // Ignore these, these are type attributes, handled by
4277    // ProcessTypeAttributes.
4278    break;
4279  case AttributeList::AT_CUDADevice:
4280  case AttributeList::AT_CUDAHost:
4281  case AttributeList::AT_Overloadable:
4282    // Ignore, this is a non-inheritable attribute, handled
4283    // by ProcessNonInheritableDeclAttr.
4284    break;
4285  case AttributeList::AT_Alias:       handleAliasAttr       (S, D, Attr); break;
4286  case AttributeList::AT_Aligned:     handleAlignedAttr     (S, D, Attr); break;
4287  case AttributeList::AT_AllocSize:   handleAllocSizeAttr   (S, D, Attr); break;
4288  case AttributeList::AT_AlwaysInline:
4289    handleAlwaysInlineAttr  (S, D, Attr); break;
4290  case AttributeList::AT_AnalyzerNoReturn:
4291    handleAnalyzerNoReturnAttr  (S, D, Attr); break;
4292  case AttributeList::AT_TLSModel:    handleTLSModelAttr    (S, D, Attr); break;
4293  case AttributeList::AT_Annotate:    handleAnnotateAttr    (S, D, Attr); break;
4294  case AttributeList::AT_Availability:handleAvailabilityAttr(S, D, Attr); break;
4295  case AttributeList::AT_CarriesDependency:
4296                                      handleDependencyAttr  (S, D, Attr); break;
4297  case AttributeList::AT_Common:      handleCommonAttr      (S, D, Attr); break;
4298  case AttributeList::AT_CUDAConstant:handleConstantAttr    (S, D, Attr); break;
4299  case AttributeList::AT_Constructor: handleConstructorAttr (S, D, Attr); break;
4300  case AttributeList::AT_Deprecated:
4301    handleAttrWithMessage<DeprecatedAttr>(S, D, Attr, "deprecated");
4302    break;
4303  case AttributeList::AT_Destructor:  handleDestructorAttr  (S, D, Attr); break;
4304  case AttributeList::AT_ExtVectorType:
4305    handleExtVectorTypeAttr(S, scope, D, Attr);
4306    break;
4307  case AttributeList::AT_MinSize:
4308    handleMinSizeAttr(S, D, Attr);
4309    break;
4310  case AttributeList::AT_Format:      handleFormatAttr      (S, D, Attr); break;
4311  case AttributeList::AT_FormatArg:   handleFormatArgAttr   (S, D, Attr); break;
4312  case AttributeList::AT_CUDAGlobal:  handleGlobalAttr      (S, D, Attr); break;
4313  case AttributeList::AT_GNUInline:   handleGNUInlineAttr   (S, D, Attr); break;
4314  case AttributeList::AT_CUDALaunchBounds:
4315    handleLaunchBoundsAttr(S, D, Attr);
4316    break;
4317  case AttributeList::AT_Mode:        handleModeAttr        (S, D, Attr); break;
4318  case AttributeList::AT_Malloc:      handleMallocAttr      (S, D, Attr); break;
4319  case AttributeList::AT_MayAlias:    handleMayAliasAttr    (S, D, Attr); break;
4320  case AttributeList::AT_NoCommon:    handleNoCommonAttr    (S, D, Attr); break;
4321  case AttributeList::AT_NonNull:     handleNonNullAttr     (S, D, Attr); break;
4322  case AttributeList::AT_ownership_returns:
4323  case AttributeList::AT_ownership_takes:
4324  case AttributeList::AT_ownership_holds:
4325      handleOwnershipAttr     (S, D, Attr); break;
4326  case AttributeList::AT_Cold:        handleColdAttr        (S, D, Attr); break;
4327  case AttributeList::AT_Hot:         handleHotAttr         (S, D, Attr); break;
4328  case AttributeList::AT_Naked:       handleNakedAttr       (S, D, Attr); break;
4329  case AttributeList::AT_NoReturn:    handleNoReturnAttr    (S, D, Attr); break;
4330  case AttributeList::AT_NoThrow:     handleNothrowAttr     (S, D, Attr); break;
4331  case AttributeList::AT_CUDAShared:  handleSharedAttr      (S, D, Attr); break;
4332  case AttributeList::AT_VecReturn:   handleVecReturnAttr   (S, D, Attr); break;
4333
4334  case AttributeList::AT_ObjCOwnership:
4335    handleObjCOwnershipAttr(S, D, Attr); break;
4336  case AttributeList::AT_ObjCPreciseLifetime:
4337    handleObjCPreciseLifetimeAttr(S, D, Attr); break;
4338
4339  case AttributeList::AT_ObjCReturnsInnerPointer:
4340    handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
4341
4342  case AttributeList::AT_ObjCRequiresSuper:
4343      handleObjCRequiresSuperAttr(S, D, Attr); break;
4344
4345  case AttributeList::AT_NSBridged:
4346    handleNSBridgedAttr(S, scope, D, Attr); break;
4347
4348  case AttributeList::AT_CFAuditedTransfer:
4349  case AttributeList::AT_CFUnknownTransfer:
4350    handleCFTransferAttr(S, D, Attr); break;
4351
4352  // Checker-specific.
4353  case AttributeList::AT_CFConsumed:
4354  case AttributeList::AT_NSConsumed:  handleNSConsumedAttr  (S, D, Attr); break;
4355  case AttributeList::AT_NSConsumesSelf:
4356    handleNSConsumesSelfAttr(S, D, Attr); break;
4357
4358  case AttributeList::AT_NSReturnsAutoreleased:
4359  case AttributeList::AT_NSReturnsNotRetained:
4360  case AttributeList::AT_CFReturnsNotRetained:
4361  case AttributeList::AT_NSReturnsRetained:
4362  case AttributeList::AT_CFReturnsRetained:
4363    handleNSReturnsRetainedAttr(S, D, Attr); break;
4364
4365  case AttributeList::AT_WorkGroupSizeHint:
4366  case AttributeList::AT_ReqdWorkGroupSize:
4367    handleWorkGroupSize(S, D, Attr); break;
4368
4369  case AttributeList::AT_InitPriority:
4370      handleInitPriorityAttr(S, D, Attr); break;
4371
4372  case AttributeList::AT_Packed:      handlePackedAttr      (S, D, Attr); break;
4373  case AttributeList::AT_Section:     handleSectionAttr     (S, D, Attr); break;
4374  case AttributeList::AT_Unavailable:
4375    handleAttrWithMessage<UnavailableAttr>(S, D, Attr, "unavailable");
4376    break;
4377  case AttributeList::AT_ArcWeakrefUnavailable:
4378    handleArcWeakrefUnavailableAttr (S, D, Attr);
4379    break;
4380  case AttributeList::AT_ObjCRootClass:
4381    handleObjCRootClassAttr(S, D, Attr);
4382    break;
4383  case AttributeList::AT_ObjCRequiresPropertyDefs:
4384    handleObjCRequiresPropertyDefsAttr (S, D, Attr);
4385    break;
4386  case AttributeList::AT_Unused:      handleUnusedAttr      (S, D, Attr); break;
4387  case AttributeList::AT_ReturnsTwice:
4388    handleReturnsTwiceAttr(S, D, Attr);
4389    break;
4390  case AttributeList::AT_Used:        handleUsedAttr        (S, D, Attr); break;
4391  case AttributeList::AT_Visibility:  handleVisibilityAttr  (S, D, Attr); break;
4392  case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr);
4393    break;
4394  case AttributeList::AT_Weak:        handleWeakAttr        (S, D, Attr); break;
4395  case AttributeList::AT_WeakRef:     handleWeakRefAttr     (S, D, Attr); break;
4396  case AttributeList::AT_WeakImport:  handleWeakImportAttr  (S, D, Attr); break;
4397  case AttributeList::AT_TransparentUnion:
4398    handleTransparentUnionAttr(S, D, Attr);
4399    break;
4400  case AttributeList::AT_ObjCException:
4401    handleObjCExceptionAttr(S, D, Attr);
4402    break;
4403  case AttributeList::AT_ObjCMethodFamily:
4404    handleObjCMethodFamilyAttr(S, D, Attr);
4405    break;
4406  case AttributeList::AT_ObjCNSObject:handleObjCNSObject    (S, D, Attr); break;
4407  case AttributeList::AT_Blocks:      handleBlocksAttr      (S, D, Attr); break;
4408  case AttributeList::AT_Sentinel:    handleSentinelAttr    (S, D, Attr); break;
4409  case AttributeList::AT_Const:       handleConstAttr       (S, D, Attr); break;
4410  case AttributeList::AT_Pure:        handlePureAttr        (S, D, Attr); break;
4411  case AttributeList::AT_Cleanup:     handleCleanupAttr     (S, D, Attr); break;
4412  case AttributeList::AT_NoDebug:     handleNoDebugAttr     (S, D, Attr); break;
4413  case AttributeList::AT_NoInline:    handleNoInlineAttr    (S, D, Attr); break;
4414  case AttributeList::AT_Regparm:     handleRegparmAttr     (S, D, Attr); break;
4415  case AttributeList::IgnoredAttribute:
4416    // Just ignore
4417    break;
4418  case AttributeList::AT_NoInstrumentFunction:  // Interacts with -pg.
4419    handleNoInstrumentFunctionAttr(S, D, Attr);
4420    break;
4421  case AttributeList::AT_StdCall:
4422  case AttributeList::AT_CDecl:
4423  case AttributeList::AT_FastCall:
4424  case AttributeList::AT_ThisCall:
4425  case AttributeList::AT_Pascal:
4426  case AttributeList::AT_Pcs:
4427  case AttributeList::AT_PnaclCall:
4428    handleCallConvAttr(S, D, Attr);
4429    break;
4430  case AttributeList::AT_OpenCLKernel:
4431    handleOpenCLKernelAttr(S, D, Attr);
4432    break;
4433
4434  // Microsoft attributes:
4435  case AttributeList::AT_MsStruct:
4436    handleMsStructAttr(S, D, Attr);
4437    break;
4438  case AttributeList::AT_Uuid:
4439    handleUuidAttr(S, D, Attr);
4440    break;
4441  case AttributeList::AT_SingleInheritance:
4442  case AttributeList::AT_MultipleInheritance:
4443  case AttributeList::AT_VirtualInheritance:
4444    handleInheritanceAttr(S, D, Attr);
4445    break;
4446  case AttributeList::AT_Win64:
4447  case AttributeList::AT_Ptr32:
4448  case AttributeList::AT_Ptr64:
4449    handlePortabilityAttr(S, D, Attr);
4450    break;
4451  case AttributeList::AT_ForceInline:
4452    handleForceInlineAttr(S, D, Attr);
4453    break;
4454
4455  // Thread safety attributes:
4456  case AttributeList::AT_GuardedVar:
4457    handleGuardedVarAttr(S, D, Attr);
4458    break;
4459  case AttributeList::AT_PtGuardedVar:
4460    handlePtGuardedVarAttr(S, D, Attr);
4461    break;
4462  case AttributeList::AT_ScopedLockable:
4463    handleScopedLockableAttr(S, D, Attr);
4464    break;
4465  case AttributeList::AT_NoAddressSafetyAnalysis:
4466    handleNoAddressSafetyAttr(S, D, Attr);
4467    break;
4468  case AttributeList::AT_NoThreadSafetyAnalysis:
4469    handleNoThreadSafetyAttr(S, D, Attr);
4470    break;
4471  case AttributeList::AT_Lockable:
4472    handleLockableAttr(S, D, Attr);
4473    break;
4474  case AttributeList::AT_GuardedBy:
4475    handleGuardedByAttr(S, D, Attr);
4476    break;
4477  case AttributeList::AT_PtGuardedBy:
4478    handlePtGuardedByAttr(S, D, Attr);
4479    break;
4480  case AttributeList::AT_ExclusiveLockFunction:
4481    handleExclusiveLockFunctionAttr(S, D, Attr);
4482    break;
4483  case AttributeList::AT_ExclusiveLocksRequired:
4484    handleExclusiveLocksRequiredAttr(S, D, Attr);
4485    break;
4486  case AttributeList::AT_ExclusiveTrylockFunction:
4487    handleExclusiveTrylockFunctionAttr(S, D, Attr);
4488    break;
4489  case AttributeList::AT_LockReturned:
4490    handleLockReturnedAttr(S, D, Attr);
4491    break;
4492  case AttributeList::AT_LocksExcluded:
4493    handleLocksExcludedAttr(S, D, Attr);
4494    break;
4495  case AttributeList::AT_SharedLockFunction:
4496    handleSharedLockFunctionAttr(S, D, Attr);
4497    break;
4498  case AttributeList::AT_SharedLocksRequired:
4499    handleSharedLocksRequiredAttr(S, D, Attr);
4500    break;
4501  case AttributeList::AT_SharedTrylockFunction:
4502    handleSharedTrylockFunctionAttr(S, D, Attr);
4503    break;
4504  case AttributeList::AT_UnlockFunction:
4505    handleUnlockFunAttr(S, D, Attr);
4506    break;
4507  case AttributeList::AT_AcquiredBefore:
4508    handleAcquiredBeforeAttr(S, D, Attr);
4509    break;
4510  case AttributeList::AT_AcquiredAfter:
4511    handleAcquiredAfterAttr(S, D, Attr);
4512    break;
4513
4514  // Type safety attributes.
4515  case AttributeList::AT_ArgumentWithTypeTag:
4516    handleArgumentWithTypeTagAttr(S, D, Attr);
4517    break;
4518  case AttributeList::AT_TypeTagForDatatype:
4519    handleTypeTagForDatatypeAttr(S, D, Attr);
4520    break;
4521
4522  default:
4523    // Ask target about the attribute.
4524    const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
4525    if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
4526      S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ?
4527             diag::warn_unhandled_ms_attribute_ignored :
4528             diag::warn_unknown_attribute_ignored) << Attr.getName();
4529    break;
4530  }
4531}
4532
4533/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4534/// the attribute applies to decls.  If the attribute is a type attribute, just
4535/// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
4536/// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
4537static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4538                                 const AttributeList &Attr,
4539                                 bool NonInheritable, bool Inheritable) {
4540  if (Attr.isInvalid())
4541    return;
4542
4543  // Type attributes are still treated as declaration attributes by
4544  // ParseMicrosoftTypeAttributes and ParseBorlandTypeAttributes.  We don't
4545  // want to process them, however, because we will simply warn about ignoring
4546  // them.  So instead, we will bail out early.
4547  if (Attr.isMSTypespecAttribute())
4548    return;
4549
4550  if (NonInheritable)
4551    ProcessNonInheritableDeclAttr(S, scope, D, Attr);
4552
4553  if (Inheritable)
4554    ProcessInheritableDeclAttr(S, scope, D, Attr);
4555}
4556
4557/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4558/// attribute list to the specified decl, ignoring any type attributes.
4559void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4560                                    const AttributeList *AttrList,
4561                                    bool NonInheritable, bool Inheritable) {
4562  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4563    ProcessDeclAttribute(*this, S, D, *l, NonInheritable, Inheritable);
4564  }
4565
4566  // GCC accepts
4567  // static int a9 __attribute__((weakref));
4568  // but that looks really pointless. We reject it.
4569  if (Inheritable && D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4570    Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
4571    dyn_cast<NamedDecl>(D)->getNameAsString();
4572    return;
4573  }
4574}
4575
4576// Annotation attributes are the only attributes allowed after an access
4577// specifier.
4578bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4579                                          const AttributeList *AttrList) {
4580  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4581    if (l->getKind() == AttributeList::AT_Annotate) {
4582      handleAnnotateAttr(*this, ASDecl, *l);
4583    } else {
4584      Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4585      return true;
4586    }
4587  }
4588
4589  return false;
4590}
4591
4592/// checkUnusedDeclAttributes - Check a list of attributes to see if it
4593/// contains any decl attributes that we should warn about.
4594static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4595  for ( ; A; A = A->getNext()) {
4596    // Only warn if the attribute is an unignored, non-type attribute.
4597    if (A->isUsedAsTypeAttr()) continue;
4598    if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4599
4600    if (A->getKind() == AttributeList::UnknownAttribute) {
4601      S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4602        << A->getName() << A->getRange();
4603    } else {
4604      S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4605        << A->getName() << A->getRange();
4606    }
4607  }
4608}
4609
4610/// checkUnusedDeclAttributes - Given a declarator which is not being
4611/// used to build a declaration, complain about any decl attributes
4612/// which might be lying around on it.
4613void Sema::checkUnusedDeclAttributes(Declarator &D) {
4614  ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4615  ::checkUnusedDeclAttributes(*this, D.getAttributes());
4616  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4617    ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4618}
4619
4620/// DeclClonePragmaWeak - clone existing decl (maybe definition),
4621/// \#pragma weak needs a non-definition decl and source may not have one.
4622NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4623                                      SourceLocation Loc) {
4624  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4625  NamedDecl *NewD = 0;
4626  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4627    FunctionDecl *NewFD;
4628    // FIXME: Missing call to CheckFunctionDeclaration().
4629    // FIXME: Mangling?
4630    // FIXME: Is the qualifier info correct?
4631    // FIXME: Is the DeclContext correct?
4632    NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4633                                 Loc, Loc, DeclarationName(II),
4634                                 FD->getType(), FD->getTypeSourceInfo(),
4635                                 SC_None, SC_None,
4636                                 false/*isInlineSpecified*/,
4637                                 FD->hasPrototype(),
4638                                 false/*isConstexprSpecified*/);
4639    NewD = NewFD;
4640
4641    if (FD->getQualifier())
4642      NewFD->setQualifierInfo(FD->getQualifierLoc());
4643
4644    // Fake up parameter variables; they are declared as if this were
4645    // a typedef.
4646    QualType FDTy = FD->getType();
4647    if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4648      SmallVector<ParmVarDecl*, 16> Params;
4649      for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4650           AE = FT->arg_type_end(); AI != AE; ++AI) {
4651        ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
4652        Param->setScopeInfo(0, Params.size());
4653        Params.push_back(Param);
4654      }
4655      NewFD->setParams(Params);
4656    }
4657  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4658    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4659                           VD->getInnerLocStart(), VD->getLocation(), II,
4660                           VD->getType(), VD->getTypeSourceInfo(),
4661                           VD->getStorageClass(),
4662                           VD->getStorageClassAsWritten());
4663    if (VD->getQualifier()) {
4664      VarDecl *NewVD = cast<VarDecl>(NewD);
4665      NewVD->setQualifierInfo(VD->getQualifierLoc());
4666    }
4667  }
4668  return NewD;
4669}
4670
4671/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4672/// applied to it, possibly with an alias.
4673void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4674  if (W.getUsed()) return; // only do this once
4675  W.setUsed(true);
4676  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4677    IdentifierInfo *NDId = ND->getIdentifier();
4678    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4679    NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
4680                                            NDId->getName()));
4681    NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4682    WeakTopLevelDecl.push_back(NewD);
4683    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4684    // to insert Decl at TU scope, sorry.
4685    DeclContext *SavedContext = CurContext;
4686    CurContext = Context.getTranslationUnitDecl();
4687    PushOnScopeChains(NewD, S);
4688    CurContext = SavedContext;
4689  } else { // just add weak to existing
4690    ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4691  }
4692}
4693
4694/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4695/// it, apply them to D.  This is a bit tricky because PD can have attributes
4696/// specified in many different places, and we need to find and apply them all.
4697void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
4698                                 bool NonInheritable, bool Inheritable) {
4699  // It's valid to "forward-declare" #pragma weak, in which case we
4700  // have to do this.
4701  if (Inheritable) {
4702    LoadExternalWeakUndeclaredIdentifiers();
4703    if (!WeakUndeclaredIdentifiers.empty()) {
4704      if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
4705        if (IdentifierInfo *Id = ND->getIdentifier()) {
4706          llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4707            = WeakUndeclaredIdentifiers.find(Id);
4708          if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
4709            WeakInfo W = I->second;
4710            DeclApplyPragmaWeak(S, ND, W);
4711            WeakUndeclaredIdentifiers[Id] = W;
4712          }
4713        }
4714      }
4715    }
4716  }
4717
4718  // Apply decl attributes from the DeclSpec if present.
4719  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4720    ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4721
4722  // Walk the declarator structure, applying decl attributes that were in a type
4723  // position to the decl itself.  This handles cases like:
4724  //   int *__attr__(x)** D;
4725  // when X is a decl attribute.
4726  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
4727    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
4728      ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4729
4730  // Finally, apply any attributes on the decl itself.
4731  if (const AttributeList *Attrs = PD.getAttributes())
4732    ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
4733}
4734
4735/// Is the given declaration allowed to use a forbidden type?
4736static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
4737  // Private ivars are always okay.  Unfortunately, people don't
4738  // always properly make their ivars private, even in system headers.
4739  // Plus we need to make fields okay, too.
4740  // Function declarations in sys headers will be marked unavailable.
4741  if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
4742      !isa<FunctionDecl>(decl))
4743    return false;
4744
4745  // Require it to be declared in a system header.
4746  return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
4747}
4748
4749/// Handle a delayed forbidden-type diagnostic.
4750static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
4751                                       Decl *decl) {
4752  if (decl && isForbiddenTypeAllowed(S, decl)) {
4753    decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
4754                        "this system declaration uses an unsupported type"));
4755    return;
4756  }
4757  if (S.getLangOpts().ObjCAutoRefCount)
4758    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
4759      // FIXME: we may want to suppress diagnostics for all
4760      // kind of forbidden type messages on unavailable functions.
4761      if (FD->hasAttr<UnavailableAttr>() &&
4762          diag.getForbiddenTypeDiagnostic() ==
4763          diag::err_arc_array_param_no_ownership) {
4764        diag.Triggered = true;
4765        return;
4766      }
4767    }
4768
4769  S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
4770    << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
4771  diag.Triggered = true;
4772}
4773
4774void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
4775  assert(DelayedDiagnostics.getCurrentPool());
4776  DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
4777  DelayedDiagnostics.popWithoutEmitting(state);
4778
4779  // When delaying diagnostics to run in the context of a parsed
4780  // declaration, we only want to actually emit anything if parsing
4781  // succeeds.
4782  if (!decl) return;
4783
4784  // We emit all the active diagnostics in this pool or any of its
4785  // parents.  In general, we'll get one pool for the decl spec
4786  // and a child pool for each declarator; in a decl group like:
4787  //   deprecated_typedef foo, *bar, baz();
4788  // only the declarator pops will be passed decls.  This is correct;
4789  // we really do need to consider delayed diagnostics from the decl spec
4790  // for each of the different declarations.
4791  const DelayedDiagnosticPool *pool = &poppedPool;
4792  do {
4793    for (DelayedDiagnosticPool::pool_iterator
4794           i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
4795      // This const_cast is a bit lame.  Really, Triggered should be mutable.
4796      DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
4797      if (diag.Triggered)
4798        continue;
4799
4800      switch (diag.Kind) {
4801      case DelayedDiagnostic::Deprecation:
4802        // Don't bother giving deprecation diagnostics if the decl is invalid.
4803        if (!decl->isInvalidDecl())
4804          HandleDelayedDeprecationCheck(diag, decl);
4805        break;
4806
4807      case DelayedDiagnostic::Access:
4808        HandleDelayedAccessCheck(diag, decl);
4809        break;
4810
4811      case DelayedDiagnostic::ForbiddenType:
4812        handleDelayedForbiddenType(*this, diag, decl);
4813        break;
4814      }
4815    }
4816  } while ((pool = pool->getParent()));
4817}
4818
4819/// Given a set of delayed diagnostics, re-emit them as if they had
4820/// been delayed in the current context instead of in the given pool.
4821/// Essentially, this just moves them to the current pool.
4822void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
4823  DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
4824  assert(curPool && "re-emitting in undelayed context not supported");
4825  curPool->steal(pool);
4826}
4827
4828static bool isDeclDeprecated(Decl *D) {
4829  do {
4830    if (D->isDeprecated())
4831      return true;
4832    // A category implicitly has the availability of the interface.
4833    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
4834      return CatD->getClassInterface()->isDeprecated();
4835  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
4836  return false;
4837}
4838
4839static void
4840DoEmitDeprecationWarning(Sema &S, const NamedDecl *D, StringRef Message,
4841                         SourceLocation Loc,
4842                         const ObjCInterfaceDecl *UnknownObjCClass,
4843                         const ObjCPropertyDecl *ObjCPropery) {
4844  DeclarationName Name = D->getDeclName();
4845  if (!Message.empty()) {
4846    S.Diag(Loc, diag::warn_deprecated_message) << Name << Message;
4847    S.Diag(D->getLocation(),
4848           isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
4849                                  : diag::note_previous_decl) << Name;
4850    if (ObjCPropery)
4851      S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
4852        << ObjCPropery->getDeclName() << 0;
4853  } else if (!UnknownObjCClass) {
4854    S.Diag(Loc, diag::warn_deprecated) << D->getDeclName();
4855    S.Diag(D->getLocation(),
4856           isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
4857                                  : diag::note_previous_decl) << Name;
4858    if (ObjCPropery)
4859      S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
4860        << ObjCPropery->getDeclName() << 0;
4861  } else {
4862    S.Diag(Loc, diag::warn_deprecated_fwdclass_message) << Name;
4863    S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
4864  }
4865}
4866
4867void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
4868                                         Decl *Ctx) {
4869  if (isDeclDeprecated(Ctx))
4870    return;
4871
4872  DD.Triggered = true;
4873  DoEmitDeprecationWarning(*this, DD.getDeprecationDecl(),
4874                           DD.getDeprecationMessage(), DD.Loc,
4875                           DD.getUnknownObjCClass(),
4876                           DD.getObjCProperty());
4877}
4878
4879void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
4880                                  SourceLocation Loc,
4881                                  const ObjCInterfaceDecl *UnknownObjCClass,
4882                                  const ObjCPropertyDecl  *ObjCProperty) {
4883  // Delay if we're currently parsing a declaration.
4884  if (DelayedDiagnostics.shouldDelayDiagnostics()) {
4885    DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,
4886                                                              UnknownObjCClass,
4887                                                              ObjCProperty,
4888                                                              Message));
4889    return;
4890  }
4891
4892  // Otherwise, don't warn if our current context is deprecated.
4893  if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
4894    return;
4895  DoEmitDeprecationWarning(*this, D, Message, Loc, UnknownObjCClass, ObjCProperty);
4896}
4897