SemaDeclAttr.cpp revision c44208598d88308695d0e7c5a6d7ba3ead6e6904
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 "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Parse/DeclSpec.h"
20#include "llvm/ADT/StringExtras.h"
21using namespace clang;
22
23//===----------------------------------------------------------------------===//
24//  Helper functions
25//===----------------------------------------------------------------------===//
26
27static const FunctionType *getFunctionType(const Decl *d,
28                                           bool blocksToo = true) {
29  QualType Ty;
30  if (const ValueDecl *decl = dyn_cast<ValueDecl>(d))
31    Ty = decl->getType();
32  else if (const FieldDecl *decl = dyn_cast<FieldDecl>(d))
33    Ty = decl->getType();
34  else if (const TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
35    Ty = decl->getUnderlyingType();
36  else
37    return 0;
38
39  if (Ty->isFunctionPointerType())
40    Ty = Ty->getAs<PointerType>()->getPointeeType();
41  else if (blocksToo && Ty->isBlockPointerType())
42    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
43
44  return Ty->getAs<FunctionType>();
45}
46
47// FIXME: We should provide an abstraction around a method or function
48// to provide the following bits of information.
49
50/// isFunctionOrMethod - Return true if the given decl has function
51/// type (function or function-typed variable).
52static bool isFunction(const Decl *d) {
53  return getFunctionType(d, false) != NULL;
54}
55
56/// isFunctionOrMethod - Return true if the given decl has function
57/// type (function or function-typed variable) or an Objective-C
58/// method.
59static bool isFunctionOrMethod(const Decl *d) {
60  return isFunction(d)|| isa<ObjCMethodDecl>(d);
61}
62
63/// isFunctionOrMethodOrBlock - Return true if the given decl has function
64/// type (function or function-typed variable) or an Objective-C
65/// method or a block.
66static bool isFunctionOrMethodOrBlock(const Decl *d) {
67  if (isFunctionOrMethod(d))
68    return true;
69  // check for block is more involved.
70  if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
71    QualType Ty = V->getType();
72    return Ty->isBlockPointerType();
73  }
74  return isa<BlockDecl>(d);
75}
76
77/// hasFunctionProto - Return true if the given decl has a argument
78/// information. This decl should have already passed
79/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
80static bool hasFunctionProto(const Decl *d) {
81  if (const FunctionType *FnTy = getFunctionType(d))
82    return isa<FunctionProtoType>(FnTy);
83  else {
84    assert(isa<ObjCMethodDecl>(d) || isa<BlockDecl>(d));
85    return true;
86  }
87}
88
89/// getFunctionOrMethodNumArgs - Return number of function or method
90/// arguments. It is an error to call this on a K&R function (use
91/// hasFunctionProto first).
92static unsigned getFunctionOrMethodNumArgs(const Decl *d) {
93  if (const FunctionType *FnTy = getFunctionType(d))
94    return cast<FunctionProtoType>(FnTy)->getNumArgs();
95  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
96    return BD->getNumParams();
97  return cast<ObjCMethodDecl>(d)->param_size();
98}
99
100static QualType getFunctionOrMethodArgType(const Decl *d, unsigned Idx) {
101  if (const FunctionType *FnTy = getFunctionType(d))
102    return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
103  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
104    return BD->getParamDecl(Idx)->getType();
105
106  return cast<ObjCMethodDecl>(d)->param_begin()[Idx]->getType();
107}
108
109static QualType getFunctionOrMethodResultType(const Decl *d) {
110  if (const FunctionType *FnTy = getFunctionType(d))
111    return cast<FunctionProtoType>(FnTy)->getResultType();
112  return cast<ObjCMethodDecl>(d)->getResultType();
113}
114
115static bool isFunctionOrMethodVariadic(const Decl *d) {
116  if (const FunctionType *FnTy = getFunctionType(d)) {
117    const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
118    return proto->isVariadic();
119  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
120    return BD->IsVariadic();
121  else {
122    return cast<ObjCMethodDecl>(d)->isVariadic();
123  }
124}
125
126static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
127  const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
128  if (!PT)
129    return false;
130
131  const ObjCInterfaceType *ClsT =PT->getPointeeType()->getAs<ObjCInterfaceType>();
132  if (!ClsT)
133    return false;
134
135  IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
136
137  // FIXME: Should we walk the chain of classes?
138  return ClsName == &Ctx.Idents.get("NSString") ||
139         ClsName == &Ctx.Idents.get("NSMutableString");
140}
141
142static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
143  const PointerType *PT = T->getAs<PointerType>();
144  if (!PT)
145    return false;
146
147  const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
148  if (!RT)
149    return false;
150
151  const RecordDecl *RD = RT->getDecl();
152  if (RD->getTagKind() != TagDecl::TK_struct)
153    return false;
154
155  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
156}
157
158//===----------------------------------------------------------------------===//
159// Attribute Implementations
160//===----------------------------------------------------------------------===//
161
162// FIXME: All this manual attribute parsing code is gross. At the
163// least add some helper functions to check most argument patterns (#
164// and types of args).
165
166static void HandleExtVectorTypeAttr(Scope *scope, Decl *d,
167                                    const AttributeList &Attr, Sema &S) {
168  TypedefDecl *tDecl = dyn_cast<TypedefDecl>(d);
169  if (tDecl == 0) {
170    S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
171    return;
172  }
173
174  QualType curType = tDecl->getUnderlyingType();
175
176  Expr *sizeExpr;
177
178  // Special case where the argument is a template id.
179  if (Attr.getParameterName()) {
180    CXXScopeSpec SS;
181    UnqualifiedId id;
182    id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
183    sizeExpr = S.ActOnIdExpression(scope, SS, id, false, false).takeAs<Expr>();
184  } else {
185    // check the attribute arguments.
186    if (Attr.getNumArgs() != 1) {
187      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
188      return;
189    }
190    sizeExpr = static_cast<Expr *>(Attr.getArg(0));
191  }
192
193  // Instantiate/Install the vector type, and let Sema build the type for us.
194  // This will run the reguired checks.
195  QualType T = S.BuildExtVectorType(curType, S.Owned(sizeExpr), Attr.getLoc());
196  if (!T.isNull()) {
197    // FIXME: preserve the old source info.
198    tDecl->setTypeDeclaratorInfo(S.Context.getTrivialDeclaratorInfo(T));
199
200    // Remember this typedef decl, we will need it later for diagnostics.
201    S.ExtVectorDecls.push_back(tDecl);
202  }
203}
204
205
206/// HandleVectorSizeAttribute - this attribute is only applicable to integral
207/// and float scalars, although arrays, pointers, and function return values are
208/// allowed in conjunction with this construct. Aggregates with this attribute
209/// are invalid, even if they are of the same size as a corresponding scalar.
210/// The raw attribute should contain precisely 1 argument, the vector size for
211/// the variable, measured in bytes. If curType and rawAttr are well formed,
212/// this routine will return a new vector type.
213static void HandleVectorSizeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
214  QualType CurType;
215  if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
216    CurType = VD->getType();
217  else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D))
218    CurType = TD->getUnderlyingType();
219  else {
220    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
221      << "vector_size" << SourceRange(Attr.getLoc(), Attr.getLoc());
222    return;
223  }
224
225  // Check the attribute arugments.
226  if (Attr.getNumArgs() != 1) {
227    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
228    return;
229  }
230  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
231  llvm::APSInt vecSize(32);
232  if (!sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
233    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
234      << "vector_size" << sizeExpr->getSourceRange();
235    return;
236  }
237  // navigate to the base type - we need to provide for vector pointers, vector
238  // arrays, and functions returning vectors.
239  if (CurType->isPointerType() || CurType->isArrayType() ||
240      CurType->isFunctionType()) {
241    S.Diag(Attr.getLoc(), diag::err_unsupported_vector_size) << CurType;
242    return;
243    /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
244     do {
245     if (PointerType *PT = dyn_cast<PointerType>(canonType))
246     canonType = PT->getPointeeType().getTypePtr();
247     else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
248     canonType = AT->getElementType().getTypePtr();
249     else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
250     canonType = FT->getResultType().getTypePtr();
251     } while (canonType->isPointerType() || canonType->isArrayType() ||
252     canonType->isFunctionType());
253     */
254  }
255  // the base type must be integer or float, and can't already be a vector.
256  if (CurType->isVectorType() ||
257      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
258    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
259    return;
260  }
261  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
262  // vecSize is specified in bytes - convert to bits.
263  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
264
265  // the vector size needs to be an integral multiple of the type size.
266  if (vectorSize % typeSize) {
267    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
268      << sizeExpr->getSourceRange();
269    return;
270  }
271  if (vectorSize == 0) {
272    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
273      << sizeExpr->getSourceRange();
274    return;
275  }
276
277  // Success! Instantiate the vector type, the number of elements is > 0, and
278  // not required to be a power of 2, unlike GCC.
279  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize);
280
281  if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
282    VD->setType(CurType);
283  else {
284    // FIXME: preserve existing source info.
285    DeclaratorInfo *DInfo = S.Context.getTrivialDeclaratorInfo(CurType);
286    cast<TypedefDecl>(D)->setTypeDeclaratorInfo(DInfo);
287  }
288}
289
290static void HandlePackedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
291  // check the attribute arguments.
292  if (Attr.getNumArgs() > 0) {
293    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
294    return;
295  }
296
297  if (TagDecl *TD = dyn_cast<TagDecl>(d))
298    TD->addAttr(::new (S.Context) PackedAttr);
299  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
300    // If the alignment is less than or equal to 8 bits, the packed attribute
301    // has no effect.
302    if (!FD->getType()->isIncompleteType() &&
303        S.Context.getTypeAlign(FD->getType()) <= 8)
304      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
305        << Attr.getName() << FD->getType();
306    else
307      FD->addAttr(::new (S.Context) PackedAttr);
308  } else
309    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
310}
311
312static void HandleIBOutletAttr(Decl *d, const AttributeList &Attr, Sema &S) {
313  // check the attribute arguments.
314  if (Attr.getNumArgs() > 0) {
315    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
316    return;
317  }
318
319  // The IBOutlet attribute only applies to instance variables of Objective-C
320  // classes.
321  if (isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d))
322    d->addAttr(::new (S.Context) IBOutletAttr());
323  else
324    S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet);
325}
326
327static void HandleNonNullAttr(Decl *d, const AttributeList &Attr, Sema &S) {
328  // GCC ignores the nonnull attribute on K&R style function prototypes, so we
329  // ignore it as well
330  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
331    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
332      << Attr.getName() << 0 /*function*/;
333    return;
334  }
335
336  unsigned NumArgs = getFunctionOrMethodNumArgs(d);
337
338  // The nonnull attribute only applies to pointers.
339  llvm::SmallVector<unsigned, 10> NonNullArgs;
340
341  for (AttributeList::arg_iterator I=Attr.arg_begin(),
342                                   E=Attr.arg_end(); I!=E; ++I) {
343
344
345    // The argument must be an integer constant expression.
346    Expr *Ex = static_cast<Expr *>(*I);
347    llvm::APSInt ArgNum(32);
348    if (!Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
349      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
350        << "nonnull" << Ex->getSourceRange();
351      return;
352    }
353
354    unsigned x = (unsigned) ArgNum.getZExtValue();
355
356    if (x < 1 || x > NumArgs) {
357      S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
358       << "nonnull" << I.getArgNum() << Ex->getSourceRange();
359      return;
360    }
361
362    --x;
363
364    // Is the function argument a pointer type?
365    QualType T = getFunctionOrMethodArgType(d, x);
366    if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
367      // FIXME: Should also highlight argument in decl.
368      S.Diag(Attr.getLoc(), diag::err_nonnull_pointers_only)
369        << "nonnull" << Ex->getSourceRange();
370      continue;
371    }
372
373    NonNullArgs.push_back(x);
374  }
375
376  // If no arguments were specified to __attribute__((nonnull)) then all pointer
377  // arguments have a nonnull attribute.
378  if (NonNullArgs.empty()) {
379    for (unsigned I = 0, E = getFunctionOrMethodNumArgs(d); I != E; ++I) {
380      QualType T = getFunctionOrMethodArgType(d, I);
381      if (T->isAnyPointerType() || T->isBlockPointerType())
382        NonNullArgs.push_back(I);
383    }
384
385    if (NonNullArgs.empty()) {
386      S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
387      return;
388    }
389  }
390
391  unsigned* start = &NonNullArgs[0];
392  unsigned size = NonNullArgs.size();
393  std::sort(start, start + size);
394  d->addAttr(::new (S.Context) NonNullAttr(start, size));
395}
396
397static void HandleAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
398  // check the attribute arguments.
399  if (Attr.getNumArgs() != 1) {
400    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
401    return;
402  }
403
404  Expr *Arg = static_cast<Expr*>(Attr.getArg(0));
405  Arg = Arg->IgnoreParenCasts();
406  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
407
408  if (Str == 0 || Str->isWide()) {
409    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
410      << "alias" << 1;
411    return;
412  }
413
414  // FIXME: check if target symbol exists in current file
415
416  d->addAttr(::new (S.Context) AliasAttr(Str->getString()));
417}
418
419static void HandleAlwaysInlineAttr(Decl *d, const AttributeList &Attr,
420                                   Sema &S) {
421  // check the attribute arguments.
422  if (Attr.getNumArgs() != 0) {
423    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
424    return;
425  }
426
427  if (!isa<FunctionDecl>(d)) {
428    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
429    << Attr.getName() << 0 /*function*/;
430    return;
431  }
432
433  d->addAttr(::new (S.Context) AlwaysInlineAttr());
434}
435
436static void HandleMallocAttr(Decl *d, const AttributeList &Attr, Sema &S) {
437  // check the attribute arguments.
438  if (Attr.getNumArgs() != 0) {
439    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
440    return;
441  }
442
443  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
444    QualType RetTy = FD->getResultType();
445    if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
446      d->addAttr(::new (S.Context) MallocAttr());
447      return;
448    }
449  }
450
451  S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
452}
453
454static bool HandleCommonNoReturnAttr(Decl *d, const AttributeList &Attr,
455                                     Sema &S) {
456  // check the attribute arguments.
457  if (Attr.getNumArgs() != 0) {
458    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
459    return false;
460  }
461
462  if (!isFunctionOrMethod(d) && !isa<BlockDecl>(d)) {
463    ValueDecl *VD = dyn_cast<ValueDecl>(d);
464    if (VD == 0 || !VD->getType()->isBlockPointerType()) {
465      S.Diag(Attr.getLoc(),
466             Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
467                                     : diag::warn_attribute_wrong_decl_type)
468        << Attr.getName() << 0 /*function*/;
469      return false;
470    }
471  }
472
473  return true;
474}
475
476static void HandleNoReturnAttr(Decl *d, const AttributeList &Attr, Sema &S) {
477  if (HandleCommonNoReturnAttr(d, Attr, S))
478    d->addAttr(::new (S.Context) NoReturnAttr());
479}
480
481static void HandleAnalyzerNoReturnAttr(Decl *d, const AttributeList &Attr,
482                                       Sema &S) {
483  if (HandleCommonNoReturnAttr(d, Attr, S))
484    d->addAttr(::new (S.Context) AnalyzerNoReturnAttr());
485}
486
487static void HandleDependencyAttr(Decl *d, const AttributeList &Attr, Sema &S) {
488  if (!isFunctionOrMethod(d) && !isa<ParmVarDecl>(d)) {
489    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
490      << Attr.getName() << 8; /*function, method, or parameter*/
491    return;
492  }
493  // FIXME: Actually store the attribute on the declaration
494}
495
496static void HandleUnusedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
497  // check the attribute arguments.
498  if (Attr.getNumArgs() != 0) {
499    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
500    return;
501  }
502
503  if (!isa<VarDecl>(d) && !isFunctionOrMethod(d)) {
504    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
505      << Attr.getName() << 2 /*variable and function*/;
506    return;
507  }
508
509  d->addAttr(::new (S.Context) UnusedAttr());
510}
511
512static void HandleUsedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
513  // check the attribute arguments.
514  if (Attr.getNumArgs() != 0) {
515    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
516    return;
517  }
518
519  if (const VarDecl *VD = dyn_cast<VarDecl>(d)) {
520    if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
521      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
522      return;
523    }
524  } else if (!isFunctionOrMethod(d)) {
525    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
526      << Attr.getName() << 2 /*variable and function*/;
527    return;
528  }
529
530  d->addAttr(::new (S.Context) UsedAttr());
531}
532
533static void HandleConstructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
534  // check the attribute arguments.
535  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
536    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
537      << "0 or 1";
538    return;
539  }
540
541  int priority = 65535; // FIXME: Do not hardcode such constants.
542  if (Attr.getNumArgs() > 0) {
543    Expr *E = static_cast<Expr *>(Attr.getArg(0));
544    llvm::APSInt Idx(32);
545    if (!E->isIntegerConstantExpr(Idx, S.Context)) {
546      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
547        << "constructor" << 1 << E->getSourceRange();
548      return;
549    }
550    priority = Idx.getZExtValue();
551  }
552
553  if (!isa<FunctionDecl>(d)) {
554    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
555      << Attr.getName() << 0 /*function*/;
556    return;
557  }
558
559  d->addAttr(::new (S.Context) ConstructorAttr(priority));
560}
561
562static void HandleDestructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
563  // check the attribute arguments.
564  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
565    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
566       << "0 or 1";
567    return;
568  }
569
570  int priority = 65535; // FIXME: Do not hardcode such constants.
571  if (Attr.getNumArgs() > 0) {
572    Expr *E = static_cast<Expr *>(Attr.getArg(0));
573    llvm::APSInt Idx(32);
574    if (!E->isIntegerConstantExpr(Idx, S.Context)) {
575      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
576        << "destructor" << 1 << E->getSourceRange();
577      return;
578    }
579    priority = Idx.getZExtValue();
580  }
581
582  if (!isa<FunctionDecl>(d)) {
583    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
584      << Attr.getName() << 0 /*function*/;
585    return;
586  }
587
588  d->addAttr(::new (S.Context) DestructorAttr(priority));
589}
590
591static void HandleDeprecatedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
592  // check the attribute arguments.
593  if (Attr.getNumArgs() != 0) {
594    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
595    return;
596  }
597
598  d->addAttr(::new (S.Context) DeprecatedAttr());
599}
600
601static void HandleUnavailableAttr(Decl *d, const AttributeList &Attr, Sema &S) {
602  // check the attribute arguments.
603  if (Attr.getNumArgs() != 0) {
604    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
605    return;
606  }
607
608  d->addAttr(::new (S.Context) UnavailableAttr());
609}
610
611static void HandleVisibilityAttr(Decl *d, const AttributeList &Attr, Sema &S) {
612  // check the attribute arguments.
613  if (Attr.getNumArgs() != 1) {
614    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
615    return;
616  }
617
618  Expr *Arg = static_cast<Expr*>(Attr.getArg(0));
619  Arg = Arg->IgnoreParenCasts();
620  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
621
622  if (Str == 0 || Str->isWide()) {
623    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
624      << "visibility" << 1;
625    return;
626  }
627
628  const char *TypeStr = Str->getStrData();
629  unsigned TypeLen = Str->getByteLength();
630  VisibilityAttr::VisibilityTypes type;
631
632  if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
633    type = VisibilityAttr::DefaultVisibility;
634  else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
635    type = VisibilityAttr::HiddenVisibility;
636  else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
637    type = VisibilityAttr::HiddenVisibility; // FIXME
638  else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
639    type = VisibilityAttr::ProtectedVisibility;
640  else {
641    S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
642    return;
643  }
644
645  d->addAttr(::new (S.Context) VisibilityAttr(type));
646}
647
648static void HandleObjCExceptionAttr(Decl *D, const AttributeList &Attr,
649                                    Sema &S) {
650  if (Attr.getNumArgs() != 0) {
651    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
652    return;
653  }
654
655  ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
656  if (OCI == 0) {
657    S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
658    return;
659  }
660
661  D->addAttr(::new (S.Context) ObjCExceptionAttr());
662}
663
664static void HandleObjCNSObject(Decl *D, const AttributeList &Attr, Sema &S) {
665  if (Attr.getNumArgs() != 0) {
666    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
667    return;
668  }
669  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
670    QualType T = TD->getUnderlyingType();
671    if (!T->isPointerType() ||
672        !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
673      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
674      return;
675    }
676  }
677  D->addAttr(::new (S.Context) ObjCNSObjectAttr());
678}
679
680static void
681HandleOverloadableAttr(Decl *D, const AttributeList &Attr, Sema &S) {
682  if (Attr.getNumArgs() != 0) {
683    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
684    return;
685  }
686
687  if (!isa<FunctionDecl>(D)) {
688    S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
689    return;
690  }
691
692  D->addAttr(::new (S.Context) OverloadableAttr());
693}
694
695static void HandleBlocksAttr(Decl *d, const AttributeList &Attr, Sema &S) {
696  if (!Attr.getParameterName()) {
697    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
698      << "blocks" << 1;
699    return;
700  }
701
702  if (Attr.getNumArgs() != 0) {
703    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
704    return;
705  }
706
707  BlocksAttr::BlocksAttrTypes type;
708  if (Attr.getParameterName()->isStr("byref"))
709    type = BlocksAttr::ByRef;
710  else {
711    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
712      << "blocks" << Attr.getParameterName();
713    return;
714  }
715
716  d->addAttr(::new (S.Context) BlocksAttr(type));
717}
718
719static void HandleSentinelAttr(Decl *d, const AttributeList &Attr, Sema &S) {
720  // check the attribute arguments.
721  if (Attr.getNumArgs() > 2) {
722    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
723      << "0, 1 or 2";
724    return;
725  }
726
727  int sentinel = 0;
728  if (Attr.getNumArgs() > 0) {
729    Expr *E = static_cast<Expr *>(Attr.getArg(0));
730    llvm::APSInt Idx(32);
731    if (!E->isIntegerConstantExpr(Idx, S.Context)) {
732      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
733       << "sentinel" << 1 << E->getSourceRange();
734      return;
735    }
736    sentinel = Idx.getZExtValue();
737
738    if (sentinel < 0) {
739      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
740        << E->getSourceRange();
741      return;
742    }
743  }
744
745  int nullPos = 0;
746  if (Attr.getNumArgs() > 1) {
747    Expr *E = static_cast<Expr *>(Attr.getArg(1));
748    llvm::APSInt Idx(32);
749    if (!E->isIntegerConstantExpr(Idx, S.Context)) {
750      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
751        << "sentinel" << 2 << E->getSourceRange();
752      return;
753    }
754    nullPos = Idx.getZExtValue();
755
756    if (nullPos > 1 || nullPos < 0) {
757      // FIXME: This error message could be improved, it would be nice
758      // to say what the bounds actually are.
759      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
760        << E->getSourceRange();
761      return;
762    }
763  }
764
765  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
766    const FunctionType *FT = FD->getType()->getAs<FunctionType>();
767    assert(FT && "FunctionDecl has non-function type?");
768
769    if (isa<FunctionNoProtoType>(FT)) {
770      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
771      return;
772    }
773
774    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
775      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
776      return;
777    }
778  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d)) {
779    if (!MD->isVariadic()) {
780      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
781      return;
782    }
783  } else if (isa<BlockDecl>(d)) {
784    // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
785    // caller.
786    ;
787  } else if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
788    QualType Ty = V->getType();
789    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
790      const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(d)
791        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
792      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
793        int m = Ty->isFunctionPointerType() ? 0 : 1;
794        S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
795        return;
796      }
797    } else {
798      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
799      << Attr.getName() << 6 /*function, method or block */;
800      return;
801    }
802  } else {
803    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
804      << Attr.getName() << 6 /*function, method or block */;
805    return;
806  }
807  d->addAttr(::new (S.Context) SentinelAttr(sentinel, nullPos));
808}
809
810static void HandleWarnUnusedResult(Decl *D, const AttributeList &Attr, Sema &S) {
811  // check the attribute arguments.
812  if (Attr.getNumArgs() != 0) {
813    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
814    return;
815  }
816
817  // TODO: could also be applied to methods?
818  FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
819  if (!Fn) {
820    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
821      << Attr.getName() << 0 /*function*/;
822    return;
823  }
824
825  Fn->addAttr(::new (S.Context) WarnUnusedResultAttr());
826}
827
828static void HandleWeakAttr(Decl *D, const AttributeList &Attr, Sema &S) {
829  // check the attribute arguments.
830  if (Attr.getNumArgs() != 0) {
831    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
832    return;
833  }
834
835  /* weak only applies to non-static declarations */
836  bool isStatic = false;
837  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
838    isStatic = VD->getStorageClass() == VarDecl::Static;
839  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
840    isStatic = FD->getStorageClass() == FunctionDecl::Static;
841  }
842  if (isStatic) {
843    S.Diag(Attr.getLoc(), diag::err_attribute_weak_static) <<
844      dyn_cast<NamedDecl>(D)->getNameAsString();
845    return;
846  }
847
848  // TODO: could also be applied to methods?
849  if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
850    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
851      << Attr.getName() << 2 /*variable and function*/;
852    return;
853  }
854
855  D->addAttr(::new (S.Context) WeakAttr());
856}
857
858static void HandleWeakImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
859  // check the attribute arguments.
860  if (Attr.getNumArgs() != 0) {
861    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
862    return;
863  }
864
865  // weak_import only applies to variable & function declarations.
866  bool isDef = false;
867  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
868    isDef = (!VD->hasExternalStorage() || VD->getInit());
869  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
870    isDef = FD->getBody();
871  } else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D)) {
872    // We ignore weak import on properties and methods
873    return;
874  } else if (!(S.LangOpts.ObjCNonFragileABI && isa<ObjCInterfaceDecl>(D))) {
875    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
876    << Attr.getName() << 2 /*variable and function*/;
877    return;
878  }
879
880  // Merge should handle any subsequent violations.
881  if (isDef) {
882    S.Diag(Attr.getLoc(),
883           diag::warn_attribute_weak_import_invalid_on_definition)
884      << "weak_import" << 2 /*variable and function*/;
885    return;
886  }
887
888  D->addAttr(::new (S.Context) WeakImportAttr());
889}
890
891static void HandleDLLImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
892  // check the attribute arguments.
893  if (Attr.getNumArgs() != 0) {
894    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
895    return;
896  }
897
898  // Attribute can be applied only to functions or variables.
899  if (isa<VarDecl>(D)) {
900    D->addAttr(::new (S.Context) DLLImportAttr());
901    return;
902  }
903
904  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
905  if (!FD) {
906    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
907      << Attr.getName() << 2 /*variable and function*/;
908    return;
909  }
910
911  // Currently, the dllimport attribute is ignored for inlined functions.
912  // Warning is emitted.
913  if (FD->isInlineSpecified()) {
914    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "dllimport";
915    return;
916  }
917
918  // The attribute is also overridden by a subsequent declaration as dllexport.
919  // Warning is emitted.
920  for (AttributeList *nextAttr = Attr.getNext(); nextAttr;
921       nextAttr = nextAttr->getNext()) {
922    if (nextAttr->getKind() == AttributeList::AT_dllexport) {
923      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "dllimport";
924      return;
925    }
926  }
927
928  if (D->getAttr<DLLExportAttr>()) {
929    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "dllimport";
930    return;
931  }
932
933  D->addAttr(::new (S.Context) DLLImportAttr());
934}
935
936static void HandleDLLExportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
937  // check the attribute arguments.
938  if (Attr.getNumArgs() != 0) {
939    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
940    return;
941  }
942
943  // Attribute can be applied only to functions or variables.
944  if (isa<VarDecl>(D)) {
945    D->addAttr(::new (S.Context) DLLExportAttr());
946    return;
947  }
948
949  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
950  if (!FD) {
951    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
952      << Attr.getName() << 2 /*variable and function*/;
953    return;
954  }
955
956  // Currently, the dllexport attribute is ignored for inlined functions, unless
957  // the -fkeep-inline-functions flag has been used. Warning is emitted;
958  if (FD->isInlineSpecified()) {
959    // FIXME: ... unless the -fkeep-inline-functions flag has been used.
960    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "dllexport";
961    return;
962  }
963
964  D->addAttr(::new (S.Context) DLLExportAttr());
965}
966
967static void HandleReqdWorkGroupSize(Decl *D, const AttributeList &Attr,
968                                    Sema &S) {
969  // Attribute has 3 arguments.
970  if (Attr.getNumArgs() != 3) {
971    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
972    return;
973  }
974
975  unsigned WGSize[3];
976  for (unsigned i = 0; i < 3; ++i) {
977    Expr *E = static_cast<Expr *>(Attr.getArg(i));
978    llvm::APSInt ArgNum(32);
979    if (!E->isIntegerConstantExpr(ArgNum, S.Context)) {
980      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
981        << "reqd_work_group_size" << E->getSourceRange();
982      return;
983    }
984    WGSize[i] = (unsigned) ArgNum.getZExtValue();
985  }
986  D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(WGSize[0], WGSize[1],
987                                                     WGSize[2]));
988}
989
990static void HandleSectionAttr(Decl *D, const AttributeList &Attr, Sema &S) {
991  // Attribute has no arguments.
992  if (Attr.getNumArgs() != 1) {
993    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
994    return;
995  }
996
997  // Make sure that there is a string literal as the sections's single
998  // argument.
999  Expr *ArgExpr = static_cast<Expr *>(Attr.getArg(0));
1000  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1001  if (!SE) {
1002    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
1003    return;
1004  }
1005
1006  // If the target wants to validate the section specifier, make it happen.
1007  std::string Error = S.Context.Target.isValidSectionSpecifier(SE->getString());
1008  if (Error.empty()) {
1009    D->addAttr(::new (S.Context) SectionAttr(SE->getString()));
1010    return;
1011  }
1012
1013  S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
1014    << Error;
1015
1016}
1017
1018static void HandleCDeclAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1019  // Attribute has no arguments.
1020  if (Attr.getNumArgs() != 0) {
1021    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1022    return;
1023  }
1024
1025  // Attribute can be applied only to functions.
1026  if (!isa<FunctionDecl>(d)) {
1027    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1028      << Attr.getName() << 0 /*function*/;
1029    return;
1030  }
1031
1032  // cdecl and fastcall attributes are mutually incompatible.
1033  if (d->getAttr<FastCallAttr>()) {
1034    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1035      << "cdecl" << "fastcall";
1036    return;
1037  }
1038
1039  // cdecl and stdcall attributes are mutually incompatible.
1040  if (d->getAttr<StdCallAttr>()) {
1041    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1042      << "cdecl" << "stdcall";
1043    return;
1044  }
1045
1046  d->addAttr(::new (S.Context) CDeclAttr());
1047}
1048
1049
1050static void HandleStdCallAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1051  // Attribute has no arguments.
1052  if (Attr.getNumArgs() != 0) {
1053    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1054    return;
1055  }
1056
1057  // Attribute can be applied only to functions.
1058  if (!isa<FunctionDecl>(d)) {
1059    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1060      << Attr.getName() << 0 /*function*/;
1061    return;
1062  }
1063
1064  // stdcall and fastcall attributes are mutually incompatible.
1065  if (d->getAttr<FastCallAttr>()) {
1066    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1067      << "stdcall" << "fastcall";
1068    return;
1069  }
1070
1071  d->addAttr(::new (S.Context) StdCallAttr());
1072}
1073
1074/// Diagnose the use of a non-standard calling convention on the given
1075/// function.
1076static void DiagnoseCConv(FunctionDecl *D, const char *CConv,
1077                          SourceLocation Loc, Sema &S) {
1078  if (!D->hasPrototype()) {
1079    S.Diag(Loc, diag::err_cconv_knr) << CConv;
1080    return;
1081  }
1082
1083  const FunctionProtoType *T = D->getType()->getAs<FunctionProtoType>();
1084  if (T->isVariadic()) {
1085    S.Diag(Loc, diag::err_cconv_varargs) << CConv;
1086    return;
1087  }
1088}
1089
1090static void HandleFastCallAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1091  // Attribute has no arguments.
1092  if (Attr.getNumArgs() != 0) {
1093    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1094    return;
1095  }
1096
1097  if (!isa<FunctionDecl>(d)) {
1098    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1099      << Attr.getName() << 0 /*function*/;
1100    return;
1101  }
1102
1103  DiagnoseCConv(cast<FunctionDecl>(d), "fastcall", Attr.getLoc(), S);
1104
1105  // stdcall and fastcall attributes are mutually incompatible.
1106  if (d->getAttr<StdCallAttr>()) {
1107    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1108      << "fastcall" << "stdcall";
1109    return;
1110  }
1111
1112  d->addAttr(::new (S.Context) FastCallAttr());
1113}
1114
1115static void HandleNothrowAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1116  // check the attribute arguments.
1117  if (Attr.getNumArgs() != 0) {
1118    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1119    return;
1120  }
1121
1122  d->addAttr(::new (S.Context) NoThrowAttr());
1123}
1124
1125static void HandleConstAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1126  // check the attribute arguments.
1127  if (Attr.getNumArgs() != 0) {
1128    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1129    return;
1130  }
1131
1132  d->addAttr(::new (S.Context) ConstAttr());
1133}
1134
1135static void HandlePureAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1136  // check the attribute arguments.
1137  if (Attr.getNumArgs() != 0) {
1138    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1139    return;
1140  }
1141
1142  d->addAttr(::new (S.Context) PureAttr());
1143}
1144
1145static void HandleCleanupAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1146  // Match gcc which ignores cleanup attrs when compiling C++.
1147  if (S.getLangOptions().CPlusPlus)
1148    return;
1149
1150  if (!Attr.getParameterName()) {
1151    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1152    return;
1153  }
1154
1155  if (Attr.getNumArgs() != 0) {
1156    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1157    return;
1158  }
1159
1160  VarDecl *VD = dyn_cast<VarDecl>(d);
1161
1162  if (!VD || !VD->hasLocalStorage()) {
1163    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
1164    return;
1165  }
1166
1167  // Look up the function
1168  NamedDecl *CleanupDecl
1169    = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
1170                         Sema::LookupOrdinaryName);
1171  if (!CleanupDecl) {
1172    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_arg_not_found) <<
1173      Attr.getParameterName();
1174    return;
1175  }
1176
1177  FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
1178  if (!FD) {
1179    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_arg_not_function) <<
1180      Attr.getParameterName();
1181    return;
1182  }
1183
1184  if (FD->getNumParams() != 1) {
1185    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_func_must_take_one_arg) <<
1186      Attr.getParameterName();
1187    return;
1188  }
1189
1190  // We're currently more strict than GCC about what function types we accept.
1191  // If this ever proves to be a problem it should be easy to fix.
1192  QualType Ty = S.Context.getPointerType(VD->getType());
1193  QualType ParamTy = FD->getParamDecl(0)->getType();
1194  if (S.CheckAssignmentConstraints(ParamTy, Ty) != Sema::Compatible) {
1195    S.Diag(Attr.getLoc(),
1196           diag::err_attribute_cleanup_func_arg_incompatible_type) <<
1197      Attr.getParameterName() << ParamTy << Ty;
1198    return;
1199  }
1200
1201  d->addAttr(::new (S.Context) CleanupAttr(FD));
1202}
1203
1204/// Handle __attribute__((format_arg((idx)))) attribute based on
1205/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1206static void HandleFormatArgAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1207  if (Attr.getNumArgs() != 1) {
1208    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1209    return;
1210  }
1211  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
1212    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1213    << Attr.getName() << 0 /*function*/;
1214    return;
1215  }
1216  // FIXME: in C++ the implicit 'this' function parameter also counts.  this is
1217  // needed in order to be compatible with GCC the index must start with 1.
1218  unsigned NumArgs  = getFunctionOrMethodNumArgs(d);
1219  unsigned FirstIdx = 1;
1220  // checks for the 2nd argument
1221  Expr *IdxExpr = static_cast<Expr *>(Attr.getArg(0));
1222  llvm::APSInt Idx(32);
1223  if (!IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1224    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1225    << "format" << 2 << IdxExpr->getSourceRange();
1226    return;
1227  }
1228
1229  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1230    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1231    << "format" << 2 << IdxExpr->getSourceRange();
1232    return;
1233  }
1234
1235  unsigned ArgIdx = Idx.getZExtValue() - 1;
1236
1237  // make sure the format string is really a string
1238  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1239
1240  bool not_nsstring_type = !isNSStringType(Ty, S.Context);
1241  if (not_nsstring_type &&
1242      !isCFStringType(Ty, S.Context) &&
1243      (!Ty->isPointerType() ||
1244       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1245    // FIXME: Should highlight the actual expression that has the wrong type.
1246    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1247    << (not_nsstring_type ? "a string type" : "an NSString")
1248       << IdxExpr->getSourceRange();
1249    return;
1250  }
1251  Ty = getFunctionOrMethodResultType(d);
1252  if (!isNSStringType(Ty, S.Context) &&
1253      !isCFStringType(Ty, S.Context) &&
1254      (!Ty->isPointerType() ||
1255       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1256    // FIXME: Should highlight the actual expression that has the wrong type.
1257    S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
1258    << (not_nsstring_type ? "string type" : "NSString")
1259       << IdxExpr->getSourceRange();
1260    return;
1261  }
1262
1263  d->addAttr(::new (S.Context) FormatArgAttr(Idx.getZExtValue()));
1264}
1265
1266enum FormatAttrKind {
1267  CFStringFormat,
1268  NSStringFormat,
1269  StrftimeFormat,
1270  SupportedFormat,
1271  InvalidFormat
1272};
1273
1274/// getFormatAttrKind - Map from format attribute names to supported format
1275/// types.
1276static FormatAttrKind getFormatAttrKind(llvm::StringRef Format) {
1277  // Check for formats that get handled specially.
1278  if (Format == "NSString")
1279    return NSStringFormat;
1280  if (Format == "CFString")
1281    return CFStringFormat;
1282  if (Format == "strftime")
1283    return StrftimeFormat;
1284
1285  // Otherwise, check for supported formats.
1286  if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
1287      Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
1288      Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
1289      Format == "zcmn_err")
1290    return SupportedFormat;
1291
1292  return InvalidFormat;
1293}
1294
1295/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
1296/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1297static void HandleFormatAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1298
1299  if (!Attr.getParameterName()) {
1300    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1301      << "format" << 1;
1302    return;
1303  }
1304
1305  if (Attr.getNumArgs() != 2) {
1306    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
1307    return;
1308  }
1309
1310  if (!isFunctionOrMethodOrBlock(d) || !hasFunctionProto(d)) {
1311    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1312      << Attr.getName() << 0 /*function*/;
1313    return;
1314  }
1315
1316  unsigned NumArgs  = getFunctionOrMethodNumArgs(d);
1317  unsigned FirstIdx = 1;
1318
1319  llvm::StringRef Format = Attr.getParameterName()->getName();
1320
1321  // Normalize the argument, __foo__ becomes foo.
1322  if (Format.startswith("__") && Format.endswith("__"))
1323    Format = Format.substr(2, Format.size() - 4);
1324
1325  // Check for supported formats.
1326  FormatAttrKind Kind = getFormatAttrKind(Format);
1327  if (Kind == InvalidFormat) {
1328    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1329      << "format" << Attr.getParameterName()->getName();
1330    return;
1331  }
1332
1333  // checks for the 2nd argument
1334  Expr *IdxExpr = static_cast<Expr *>(Attr.getArg(0));
1335  llvm::APSInt Idx(32);
1336  if (!IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1337    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1338      << "format" << 2 << IdxExpr->getSourceRange();
1339    return;
1340  }
1341
1342  // FIXME: We should handle the implicit 'this' parameter in a more generic
1343  // way that can be used for other arguments.
1344  bool HasImplicitThisParam = false;
1345  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(d)) {
1346    if (MD->isInstance()) {
1347      HasImplicitThisParam = true;
1348      NumArgs++;
1349    }
1350  }
1351
1352  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1353    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1354      << "format" << 2 << IdxExpr->getSourceRange();
1355    return;
1356  }
1357
1358  // FIXME: Do we need to bounds check?
1359  unsigned ArgIdx = Idx.getZExtValue() - 1;
1360
1361  if (HasImplicitThisParam) {
1362    if (ArgIdx == 0) {
1363      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1364        << "a string type" << IdxExpr->getSourceRange();
1365      return;
1366    }
1367    ArgIdx--;
1368  }
1369
1370  // make sure the format string is really a string
1371  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1372
1373  if (Kind == CFStringFormat) {
1374    if (!isCFStringType(Ty, S.Context)) {
1375      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1376        << "a CFString" << IdxExpr->getSourceRange();
1377      return;
1378    }
1379  } else if (Kind == NSStringFormat) {
1380    // FIXME: do we need to check if the type is NSString*?  What are the
1381    // semantics?
1382    if (!isNSStringType(Ty, S.Context)) {
1383      // FIXME: Should highlight the actual expression that has the wrong type.
1384      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1385        << "an NSString" << IdxExpr->getSourceRange();
1386      return;
1387    }
1388  } else if (!Ty->isPointerType() ||
1389             !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
1390    // FIXME: Should highlight the actual expression that has the wrong type.
1391    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1392      << "a string type" << IdxExpr->getSourceRange();
1393    return;
1394  }
1395
1396  // check the 3rd argument
1397  Expr *FirstArgExpr = static_cast<Expr *>(Attr.getArg(1));
1398  llvm::APSInt FirstArg(32);
1399  if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
1400    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1401      << "format" << 3 << FirstArgExpr->getSourceRange();
1402    return;
1403  }
1404
1405  // check if the function is variadic if the 3rd argument non-zero
1406  if (FirstArg != 0) {
1407    if (isFunctionOrMethodVariadic(d)) {
1408      ++NumArgs; // +1 for ...
1409    } else {
1410      S.Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
1411      return;
1412    }
1413  }
1414
1415  // strftime requires FirstArg to be 0 because it doesn't read from any
1416  // variable the input is just the current time + the format string.
1417  if (Kind == StrftimeFormat) {
1418    if (FirstArg != 0) {
1419      S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
1420        << FirstArgExpr->getSourceRange();
1421      return;
1422    }
1423  // if 0 it disables parameter checking (to use with e.g. va_list)
1424  } else if (FirstArg != 0 && FirstArg != NumArgs) {
1425    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1426      << "format" << 3 << FirstArgExpr->getSourceRange();
1427    return;
1428  }
1429
1430  d->addAttr(::new (S.Context) FormatAttr(Format, Idx.getZExtValue(),
1431                                          FirstArg.getZExtValue()));
1432}
1433
1434static void HandleTransparentUnionAttr(Decl *d, const AttributeList &Attr,
1435                                       Sema &S) {
1436  // check the attribute arguments.
1437  if (Attr.getNumArgs() != 0) {
1438    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1439    return;
1440  }
1441
1442  // Try to find the underlying union declaration.
1443  RecordDecl *RD = 0;
1444  TypedefDecl *TD = dyn_cast<TypedefDecl>(d);
1445  if (TD && TD->getUnderlyingType()->isUnionType())
1446    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
1447  else
1448    RD = dyn_cast<RecordDecl>(d);
1449
1450  if (!RD || !RD->isUnion()) {
1451    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1452      << Attr.getName() << 1 /*union*/;
1453    return;
1454  }
1455
1456  if (!RD->isDefinition()) {
1457    S.Diag(Attr.getLoc(),
1458        diag::warn_transparent_union_attribute_not_definition);
1459    return;
1460  }
1461
1462  RecordDecl::field_iterator Field = RD->field_begin(),
1463                          FieldEnd = RD->field_end();
1464  if (Field == FieldEnd) {
1465    S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
1466    return;
1467  }
1468
1469  FieldDecl *FirstField = *Field;
1470  QualType FirstType = FirstField->getType();
1471  if (FirstType->isFloatingType() || FirstType->isVectorType()) {
1472    S.Diag(FirstField->getLocation(),
1473           diag::warn_transparent_union_attribute_floating);
1474    return;
1475  }
1476
1477  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
1478  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
1479  for (; Field != FieldEnd; ++Field) {
1480    QualType FieldType = Field->getType();
1481    if (S.Context.getTypeSize(FieldType) != FirstSize ||
1482        S.Context.getTypeAlign(FieldType) != FirstAlign) {
1483      // Warn if we drop the attribute.
1484      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
1485      unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
1486                                 : S.Context.getTypeAlign(FieldType);
1487      S.Diag(Field->getLocation(),
1488          diag::warn_transparent_union_attribute_field_size_align)
1489        << isSize << Field->getDeclName() << FieldBits;
1490      unsigned FirstBits = isSize? FirstSize : FirstAlign;
1491      S.Diag(FirstField->getLocation(),
1492             diag::note_transparent_union_first_field_size_align)
1493        << isSize << FirstBits;
1494      return;
1495    }
1496  }
1497
1498  RD->addAttr(::new (S.Context) TransparentUnionAttr());
1499}
1500
1501static void HandleAnnotateAttr(Decl *d, const AttributeList &Attr, Sema &S) {
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  Expr *ArgExpr = static_cast<Expr *>(Attr.getArg(0));
1508  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1509
1510  // Make sure that there is a string literal as the annotation's single
1511  // argument.
1512  if (!SE) {
1513    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
1514    return;
1515  }
1516  d->addAttr(::new (S.Context) AnnotateAttr(SE->getString()));
1517}
1518
1519static void HandleAlignedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1520  // check the attribute arguments.
1521  if (Attr.getNumArgs() > 1) {
1522    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1523    return;
1524  }
1525
1526  //FIXME: The C++0x version of this attribute has more limited applicabilty
1527  //       than GNU's, and should error out when it is used to specify a
1528  //       weaker alignment, rather than being silently ignored.
1529
1530  unsigned Align = 0;
1531  if (Attr.getNumArgs() == 0) {
1532    // FIXME: This should be the target specific maximum alignment.
1533    // (For now we just use 128 bits which is the maximum on X86).
1534    Align = 128;
1535    d->addAttr(::new (S.Context) AlignedAttr(Align));
1536    return;
1537  }
1538
1539  Expr *alignmentExpr = static_cast<Expr *>(Attr.getArg(0));
1540  llvm::APSInt Alignment(32);
1541  if (!alignmentExpr->isIntegerConstantExpr(Alignment, S.Context)) {
1542    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1543      << "aligned" << alignmentExpr->getSourceRange();
1544    return;
1545  }
1546  if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
1547    S.Diag(Attr.getLoc(), diag::err_attribute_aligned_not_power_of_two)
1548      << alignmentExpr->getSourceRange();
1549    return;
1550  }
1551
1552  d->addAttr(::new (S.Context) AlignedAttr(Alignment.getZExtValue() * 8));
1553}
1554
1555/// HandleModeAttr - This attribute modifies the width of a decl with primitive
1556/// type.
1557///
1558/// Despite what would be logical, the mode attribute is a decl attribute, not a
1559/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
1560/// HImode, not an intermediate pointer.
1561static void HandleModeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1562  // This attribute isn't documented, but glibc uses it.  It changes
1563  // the width of an int or unsigned int to the specified size.
1564
1565  // Check that there aren't any arguments
1566  if (Attr.getNumArgs() != 0) {
1567    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1568    return;
1569  }
1570
1571  IdentifierInfo *Name = Attr.getParameterName();
1572  if (!Name) {
1573    S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
1574    return;
1575  }
1576
1577  llvm::StringRef Str = Attr.getParameterName()->getName();
1578
1579  // Normalize the attribute name, __foo__ becomes foo.
1580  if (Str.startswith("__") && Str.endswith("__"))
1581    Str = Str.substr(2, Str.size() - 4);
1582
1583  unsigned DestWidth = 0;
1584  bool IntegerMode = true;
1585  bool ComplexMode = false;
1586  switch (Str.size()) {
1587  case 2:
1588    switch (Str[0]) {
1589    case 'Q': DestWidth = 8; break;
1590    case 'H': DestWidth = 16; break;
1591    case 'S': DestWidth = 32; break;
1592    case 'D': DestWidth = 64; break;
1593    case 'X': DestWidth = 96; break;
1594    case 'T': DestWidth = 128; break;
1595    }
1596    if (Str[1] == 'F') {
1597      IntegerMode = false;
1598    } else if (Str[1] == 'C') {
1599      IntegerMode = false;
1600      ComplexMode = true;
1601    } else if (Str[1] != 'I') {
1602      DestWidth = 0;
1603    }
1604    break;
1605  case 4:
1606    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
1607    // pointer on PIC16 and other embedded platforms.
1608    if (Str == "word")
1609      DestWidth = S.Context.Target.getPointerWidth(0);
1610    else if (Str == "byte")
1611      DestWidth = S.Context.Target.getCharWidth();
1612    break;
1613  case 7:
1614    if (Str == "pointer")
1615      DestWidth = S.Context.Target.getPointerWidth(0);
1616    break;
1617  }
1618
1619  QualType OldTy;
1620  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D))
1621    OldTy = TD->getUnderlyingType();
1622  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
1623    OldTy = VD->getType();
1624  else {
1625    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
1626      << "mode" << SourceRange(Attr.getLoc(), Attr.getLoc());
1627    return;
1628  }
1629
1630  if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
1631    S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
1632  else if (IntegerMode) {
1633    if (!OldTy->isIntegralType())
1634      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1635  } else if (ComplexMode) {
1636    if (!OldTy->isComplexType())
1637      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1638  } else {
1639    if (!OldTy->isFloatingType())
1640      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1641  }
1642
1643  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
1644  // and friends, at least with glibc.
1645  // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
1646  // width on unusual platforms.
1647  // FIXME: Make sure floating-point mappings are accurate
1648  // FIXME: Support XF and TF types
1649  QualType NewTy;
1650  switch (DestWidth) {
1651  case 0:
1652    S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
1653    return;
1654  default:
1655    S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1656    return;
1657  case 8:
1658    if (!IntegerMode) {
1659      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1660      return;
1661    }
1662    if (OldTy->isSignedIntegerType())
1663      NewTy = S.Context.SignedCharTy;
1664    else
1665      NewTy = S.Context.UnsignedCharTy;
1666    break;
1667  case 16:
1668    if (!IntegerMode) {
1669      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1670      return;
1671    }
1672    if (OldTy->isSignedIntegerType())
1673      NewTy = S.Context.ShortTy;
1674    else
1675      NewTy = S.Context.UnsignedShortTy;
1676    break;
1677  case 32:
1678    if (!IntegerMode)
1679      NewTy = S.Context.FloatTy;
1680    else if (OldTy->isSignedIntegerType())
1681      NewTy = S.Context.IntTy;
1682    else
1683      NewTy = S.Context.UnsignedIntTy;
1684    break;
1685  case 64:
1686    if (!IntegerMode)
1687      NewTy = S.Context.DoubleTy;
1688    else if (OldTy->isSignedIntegerType())
1689      NewTy = S.Context.LongLongTy;
1690    else
1691      NewTy = S.Context.UnsignedLongLongTy;
1692    break;
1693  case 96:
1694    NewTy = S.Context.LongDoubleTy;
1695    break;
1696  case 128:
1697    if (!IntegerMode) {
1698      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1699      return;
1700    }
1701    NewTy = S.Context.getFixedWidthIntType(128, OldTy->isSignedIntegerType());
1702    break;
1703  }
1704
1705  if (ComplexMode) {
1706    NewTy = S.Context.getComplexType(NewTy);
1707  }
1708
1709  // Install the new type.
1710  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1711    // FIXME: preserve existing source info.
1712    TD->setTypeDeclaratorInfo(S.Context.getTrivialDeclaratorInfo(NewTy));
1713  } else
1714    cast<ValueDecl>(D)->setType(NewTy);
1715}
1716
1717static void HandleNoDebugAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1718  // check the attribute arguments.
1719  if (Attr.getNumArgs() > 0) {
1720    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1721    return;
1722  }
1723
1724  if (!isFunctionOrMethod(d)) {
1725    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1726      << Attr.getName() << 0 /*function*/;
1727    return;
1728  }
1729
1730  d->addAttr(::new (S.Context) NoDebugAttr());
1731}
1732
1733static void HandleNoInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1734  // check the attribute arguments.
1735  if (Attr.getNumArgs() != 0) {
1736    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1737    return;
1738  }
1739
1740  if (!isa<FunctionDecl>(d)) {
1741    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1742    << Attr.getName() << 0 /*function*/;
1743    return;
1744  }
1745
1746  d->addAttr(::new (S.Context) NoInlineAttr());
1747}
1748
1749static void HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1750  // check the attribute arguments.
1751  if (Attr.getNumArgs() != 0) {
1752    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1753    return;
1754  }
1755
1756  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
1757  if (Fn == 0) {
1758    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1759      << Attr.getName() << 0 /*function*/;
1760    return;
1761  }
1762
1763  if (!Fn->isInlineSpecified()) {
1764    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
1765    return;
1766  }
1767
1768  d->addAttr(::new (S.Context) GNUInlineAttr());
1769}
1770
1771static void HandleRegparmAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1772  // check the attribute arguments.
1773  if (Attr.getNumArgs() != 1) {
1774    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1775    return;
1776  }
1777
1778  if (!isFunctionOrMethod(d)) {
1779    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1780    << Attr.getName() << 0 /*function*/;
1781    return;
1782  }
1783
1784  Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1785  llvm::APSInt NumParams(32);
1786  if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
1787    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1788      << "regparm" << NumParamsExpr->getSourceRange();
1789    return;
1790  }
1791
1792  if (S.Context.Target.getRegParmMax() == 0) {
1793    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
1794      << NumParamsExpr->getSourceRange();
1795    return;
1796  }
1797
1798  if (NumParams.getLimitedValue(255) > S.Context.Target.getRegParmMax()) {
1799    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
1800      << S.Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
1801    return;
1802  }
1803
1804  d->addAttr(::new (S.Context) RegparmAttr(NumParams.getZExtValue()));
1805}
1806
1807static void HandleFinalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1808  // check the attribute arguments.
1809  if (Attr.getNumArgs() != 0) {
1810    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1811    return;
1812  }
1813
1814  if (!isa<CXXRecordDecl>(d)
1815   && (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual())) {
1816    S.Diag(Attr.getLoc(),
1817           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1818                                   : diag::warn_attribute_wrong_decl_type)
1819      << Attr.getName() << 7 /*virtual method or class*/;
1820    return;
1821  }
1822
1823  // FIXME: Conform to C++0x redeclaration rules.
1824
1825  if (d->getAttr<FinalAttr>()) {
1826    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "final";
1827    return;
1828  }
1829
1830  d->addAttr(::new (S.Context) FinalAttr());
1831}
1832
1833//===----------------------------------------------------------------------===//
1834// C++0x member checking attributes
1835//===----------------------------------------------------------------------===//
1836
1837static void HandleBaseCheckAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1838  if (Attr.getNumArgs() != 0) {
1839    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1840    return;
1841  }
1842
1843  if (!isa<CXXRecordDecl>(d)) {
1844    S.Diag(Attr.getLoc(),
1845           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1846                                   : diag::warn_attribute_wrong_decl_type)
1847      << Attr.getName() << 9 /*class*/;
1848    return;
1849  }
1850
1851  if (d->getAttr<BaseCheckAttr>()) {
1852    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "base_check";
1853    return;
1854  }
1855
1856  d->addAttr(::new (S.Context) BaseCheckAttr());
1857}
1858
1859static void HandleHidingAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1860  if (Attr.getNumArgs() != 0) {
1861    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1862    return;
1863  }
1864
1865  if (!isa<RecordDecl>(d->getDeclContext())) {
1866    // FIXME: It's not the type that's the problem
1867    S.Diag(Attr.getLoc(),
1868           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1869                                   : diag::warn_attribute_wrong_decl_type)
1870      << Attr.getName() << 11 /*member*/;
1871    return;
1872  }
1873
1874  // FIXME: Conform to C++0x redeclaration rules.
1875
1876  if (d->getAttr<HidingAttr>()) {
1877    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "hiding";
1878    return;
1879  }
1880
1881  d->addAttr(::new (S.Context) HidingAttr());
1882}
1883
1884static void HandleOverrideAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1885  if (Attr.getNumArgs() != 0) {
1886    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1887    return;
1888  }
1889
1890  if (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual()) {
1891    // FIXME: It's not the type that's the problem
1892    S.Diag(Attr.getLoc(),
1893           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1894                                   : diag::warn_attribute_wrong_decl_type)
1895      << Attr.getName() << 10 /*virtual method*/;
1896    return;
1897  }
1898
1899  // FIXME: Conform to C++0x redeclaration rules.
1900
1901  if (d->getAttr<OverrideAttr>()) {
1902    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "override";
1903    return;
1904  }
1905
1906  d->addAttr(::new (S.Context) OverrideAttr());
1907}
1908
1909//===----------------------------------------------------------------------===//
1910// Checker-specific attribute handlers.
1911//===----------------------------------------------------------------------===//
1912
1913static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &Attr,
1914                                        Sema &S) {
1915
1916  QualType RetTy;
1917
1918  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
1919    RetTy = MD->getResultType();
1920  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
1921    RetTy = FD->getResultType();
1922  else {
1923    SourceLocation L = Attr.getLoc();
1924    S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
1925        << SourceRange(L, L) << Attr.getName() << 3 /* function or method */;
1926    return;
1927  }
1928
1929  if (!(S.Context.isObjCNSObjectType(RetTy) || RetTy->getAs<PointerType>()
1930        || RetTy->getAs<ObjCObjectPointerType>())) {
1931    SourceLocation L = Attr.getLoc();
1932    S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
1933      << SourceRange(L, L) << Attr.getName();
1934    return;
1935  }
1936
1937  switch (Attr.getKind()) {
1938    default:
1939      assert(0 && "invalid ownership attribute");
1940      return;
1941    case AttributeList::AT_cf_returns_retained:
1942      d->addAttr(::new (S.Context) CFReturnsRetainedAttr());
1943      return;
1944    case AttributeList::AT_ns_returns_retained:
1945      d->addAttr(::new (S.Context) NSReturnsRetainedAttr());
1946      return;
1947  };
1948}
1949
1950//===----------------------------------------------------------------------===//
1951// Top Level Sema Entry Points
1952//===----------------------------------------------------------------------===//
1953
1954/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
1955/// the attribute applies to decls.  If the attribute is a type attribute, just
1956/// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
1957/// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
1958static void ProcessDeclAttribute(Scope *scope, Decl *D,
1959                                 const AttributeList &Attr, Sema &S) {
1960  if (Attr.isDeclspecAttribute())
1961    // FIXME: Try to deal with __declspec attributes!
1962    return;
1963  switch (Attr.getKind()) {
1964  case AttributeList::AT_IBOutlet:    HandleIBOutletAttr  (D, Attr, S); break;
1965  case AttributeList::AT_address_space:
1966  case AttributeList::AT_objc_gc:
1967    // Ignore these, these are type attributes, handled by
1968    // ProcessTypeAttributes.
1969    break;
1970  case AttributeList::AT_alias:       HandleAliasAttr       (D, Attr, S); break;
1971  case AttributeList::AT_aligned:     HandleAlignedAttr     (D, Attr, S); break;
1972  case AttributeList::AT_always_inline:
1973    HandleAlwaysInlineAttr  (D, Attr, S); break;
1974  case AttributeList::AT_analyzer_noreturn:
1975    HandleAnalyzerNoReturnAttr  (D, Attr, S); break;
1976  case AttributeList::AT_annotate:    HandleAnnotateAttr    (D, Attr, S); break;
1977  case AttributeList::AT_base_check:  HandleBaseCheckAttr   (D, Attr, S); break;
1978  case AttributeList::AT_carries_dependency:
1979                                      HandleDependencyAttr  (D, Attr, S); break;
1980  case AttributeList::AT_cdecl:       HandleCDeclAttr       (D, Attr, S); break;
1981  case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
1982  case AttributeList::AT_deprecated:  HandleDeprecatedAttr  (D, Attr, S); break;
1983  case AttributeList::AT_destructor:  HandleDestructorAttr  (D, Attr, S); break;
1984  case AttributeList::AT_dllexport:   HandleDLLExportAttr   (D, Attr, S); break;
1985  case AttributeList::AT_dllimport:   HandleDLLImportAttr   (D, Attr, S); break;
1986  case AttributeList::AT_ext_vector_type:
1987    HandleExtVectorTypeAttr(scope, D, Attr, S);
1988    break;
1989  case AttributeList::AT_fastcall:    HandleFastCallAttr    (D, Attr, S); break;
1990  case AttributeList::AT_final:       HandleFinalAttr       (D, Attr, S); break;
1991  case AttributeList::AT_format:      HandleFormatAttr      (D, Attr, S); break;
1992  case AttributeList::AT_format_arg:  HandleFormatArgAttr   (D, Attr, S); break;
1993  case AttributeList::AT_gnu_inline:  HandleGNUInlineAttr   (D, Attr, S); break;
1994  case AttributeList::AT_hiding:      HandleHidingAttr      (D, Attr, S); break;
1995  case AttributeList::AT_mode:        HandleModeAttr        (D, Attr, S); break;
1996  case AttributeList::AT_malloc:      HandleMallocAttr      (D, Attr, S); break;
1997  case AttributeList::AT_nonnull:     HandleNonNullAttr     (D, Attr, S); break;
1998  case AttributeList::AT_noreturn:    HandleNoReturnAttr    (D, Attr, S); break;
1999  case AttributeList::AT_nothrow:     HandleNothrowAttr     (D, Attr, S); break;
2000  case AttributeList::AT_override:    HandleOverrideAttr    (D, Attr, S); break;
2001
2002  // Checker-specific.
2003  case AttributeList::AT_ns_returns_retained:
2004  case AttributeList::AT_cf_returns_retained:
2005    HandleNSReturnsRetainedAttr(D, Attr, S); break;
2006
2007  case AttributeList::AT_reqd_wg_size:
2008    HandleReqdWorkGroupSize(D, Attr, S); break;
2009
2010  case AttributeList::AT_packed:      HandlePackedAttr      (D, Attr, S); break;
2011  case AttributeList::AT_section:     HandleSectionAttr     (D, Attr, S); break;
2012  case AttributeList::AT_stdcall:     HandleStdCallAttr     (D, Attr, S); break;
2013  case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
2014  case AttributeList::AT_unused:      HandleUnusedAttr      (D, Attr, S); break;
2015  case AttributeList::AT_used:        HandleUsedAttr        (D, Attr, S); break;
2016  case AttributeList::AT_vector_size: HandleVectorSizeAttr  (D, Attr, S); break;
2017  case AttributeList::AT_visibility:  HandleVisibilityAttr  (D, Attr, S); break;
2018  case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
2019    break;
2020  case AttributeList::AT_weak:        HandleWeakAttr        (D, Attr, S); break;
2021  case AttributeList::AT_weak_import: HandleWeakImportAttr  (D, Attr, S); break;
2022  case AttributeList::AT_transparent_union:
2023    HandleTransparentUnionAttr(D, Attr, S);
2024    break;
2025  case AttributeList::AT_objc_exception:
2026    HandleObjCExceptionAttr(D, Attr, S);
2027    break;
2028  case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
2029  case AttributeList::AT_nsobject:    HandleObjCNSObject    (D, Attr, S); break;
2030  case AttributeList::AT_blocks:      HandleBlocksAttr      (D, Attr, S); break;
2031  case AttributeList::AT_sentinel:    HandleSentinelAttr    (D, Attr, S); break;
2032  case AttributeList::AT_const:       HandleConstAttr       (D, Attr, S); break;
2033  case AttributeList::AT_pure:        HandlePureAttr        (D, Attr, S); break;
2034  case AttributeList::AT_cleanup:     HandleCleanupAttr     (D, Attr, S); break;
2035  case AttributeList::AT_nodebug:     HandleNoDebugAttr     (D, Attr, S); break;
2036  case AttributeList::AT_noinline:    HandleNoInlineAttr    (D, Attr, S); break;
2037  case AttributeList::AT_regparm:     HandleRegparmAttr     (D, Attr, S); break;
2038  case AttributeList::IgnoredAttribute:
2039  case AttributeList::AT_no_instrument_function:  // Interacts with -pg.
2040    // Just ignore
2041    break;
2042  default:
2043    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2044    break;
2045  }
2046}
2047
2048/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2049/// attribute list to the specified decl, ignoring any type attributes.
2050void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AttrList) {
2051  while (AttrList) {
2052    ProcessDeclAttribute(S, D, *AttrList, *this);
2053    AttrList = AttrList->getNext();
2054  }
2055}
2056
2057/// DeclClonePragmaWeak - clone existing decl (maybe definition),
2058/// #pragma weak needs a non-definition decl and source may not have one
2059NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
2060  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
2061  NamedDecl *NewD = 0;
2062  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2063    NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
2064                                FD->getLocation(), DeclarationName(II),
2065                                FD->getType(), FD->getDeclaratorInfo());
2066  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
2067    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
2068                           VD->getLocation(), II,
2069                           VD->getType(), VD->getDeclaratorInfo(),
2070                           VD->getStorageClass());
2071  }
2072  return NewD;
2073}
2074
2075/// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
2076/// applied to it, possibly with an alias.
2077void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
2078  if (W.getUsed()) return; // only do this once
2079  W.setUsed(true);
2080  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
2081    IdentifierInfo *NDId = ND->getIdentifier();
2082    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
2083    NewD->addAttr(::new (Context) AliasAttr(NDId->getName()));
2084    NewD->addAttr(::new (Context) WeakAttr());
2085    WeakTopLevelDecl.push_back(NewD);
2086    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
2087    // to insert Decl at TU scope, sorry.
2088    DeclContext *SavedContext = CurContext;
2089    CurContext = Context.getTranslationUnitDecl();
2090    PushOnScopeChains(NewD, S);
2091    CurContext = SavedContext;
2092  } else { // just add weak to existing
2093    ND->addAttr(::new (Context) WeakAttr());
2094  }
2095}
2096
2097/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
2098/// it, apply them to D.  This is a bit tricky because PD can have attributes
2099/// specified in many different places, and we need to find and apply them all.
2100void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
2101  // Handle #pragma weak
2102  if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
2103    if (ND->hasLinkage()) {
2104      WeakInfo W = WeakUndeclaredIdentifiers.lookup(ND->getIdentifier());
2105      if (W != WeakInfo()) {
2106        // Identifier referenced by #pragma weak before it was declared
2107        DeclApplyPragmaWeak(S, ND, W);
2108        WeakUndeclaredIdentifiers[ND->getIdentifier()] = W;
2109      }
2110    }
2111  }
2112
2113  // Apply decl attributes from the DeclSpec if present.
2114  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes())
2115    ProcessDeclAttributeList(S, D, Attrs);
2116
2117  // Walk the declarator structure, applying decl attributes that were in a type
2118  // position to the decl itself.  This handles cases like:
2119  //   int *__attr__(x)** D;
2120  // when X is a decl attribute.
2121  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
2122    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
2123      ProcessDeclAttributeList(S, D, Attrs);
2124
2125  // Finally, apply any attributes on the decl itself.
2126  if (const AttributeList *Attrs = PD.getAttributes())
2127    ProcessDeclAttributeList(S, D, Attrs);
2128}
2129
2130/// PushParsingDeclaration - Enter a new "scope" of deprecation
2131/// warnings.
2132///
2133/// The state token we use is the start index of this scope
2134/// on the warning stack.
2135Action::ParsingDeclStackState Sema::PushParsingDeclaration() {
2136  ParsingDeclDepth++;
2137  return (ParsingDeclStackState) DelayedDeprecationWarnings.size();
2138}
2139
2140static bool isDeclDeprecated(Decl *D) {
2141  do {
2142    if (D->hasAttr<DeprecatedAttr>())
2143      return true;
2144  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
2145  return false;
2146}
2147
2148void Sema::PopParsingDeclaration(ParsingDeclStackState S, DeclPtrTy Ctx) {
2149  assert(ParsingDeclDepth > 0 && "empty ParsingDeclaration stack");
2150  ParsingDeclDepth--;
2151
2152  if (DelayedDeprecationWarnings.empty())
2153    return;
2154
2155  unsigned SavedIndex = (unsigned) S;
2156  assert(SavedIndex <= DelayedDeprecationWarnings.size() &&
2157         "saved index is out of bounds");
2158
2159  if (Ctx && !isDeclDeprecated(Ctx.getAs<Decl>())) {
2160    for (unsigned I = 0, E = DelayedDeprecationWarnings.size(); I != E; ++I) {
2161      SourceLocation Loc = DelayedDeprecationWarnings[I].first;
2162      NamedDecl *&ND = DelayedDeprecationWarnings[I].second;
2163      if (ND) {
2164        Diag(Loc, diag::warn_deprecated) << ND->getDeclName();
2165
2166        // Prevent this from triggering multiple times.
2167        ND = 0;
2168      }
2169    }
2170  }
2171
2172  DelayedDeprecationWarnings.set_size(SavedIndex);
2173}
2174
2175void Sema::EmitDeprecationWarning(NamedDecl *D, SourceLocation Loc) {
2176  // Delay if we're currently parsing a declaration.
2177  if (ParsingDeclDepth) {
2178    DelayedDeprecationWarnings.push_back(std::make_pair(Loc, D));
2179    return;
2180  }
2181
2182  // Otherwise, don't warn if our current context is deprecated.
2183  if (isDeclDeprecated(cast<Decl>(CurContext)))
2184    return;
2185
2186  Diag(Loc, diag::warn_deprecated) << D->getDeclName();
2187}
2188