SemaDeclAttr.cpp revision 223ae5c26654e5fd7dacdafe43aff28a096ba63b
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/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Sema/DeclSpec.h"
22#include "clang/Sema/DelayedDiagnostic.h"
23#include "llvm/ADT/StringExtras.h"
24using namespace clang;
25using namespace sema;
26
27//===----------------------------------------------------------------------===//
28//  Helper functions
29//===----------------------------------------------------------------------===//
30
31static const FunctionType *getFunctionType(const Decl *d,
32                                           bool blocksToo = true) {
33  QualType Ty;
34  if (const ValueDecl *decl = dyn_cast<ValueDecl>(d))
35    Ty = decl->getType();
36  else if (const FieldDecl *decl = dyn_cast<FieldDecl>(d))
37    Ty = decl->getType();
38  else if (const TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
39    Ty = decl->getUnderlyingType();
40  else
41    return 0;
42
43  if (Ty->isFunctionPointerType())
44    Ty = Ty->getAs<PointerType>()->getPointeeType();
45  else if (blocksToo && Ty->isBlockPointerType())
46    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
47
48  return Ty->getAs<FunctionType>();
49}
50
51// FIXME: We should provide an abstraction around a method or function
52// to provide the following bits of information.
53
54/// isFunction - Return true if the given decl has function
55/// type (function or function-typed variable).
56static bool isFunction(const Decl *d) {
57  return getFunctionType(d, false) != NULL;
58}
59
60/// isFunctionOrMethod - Return true if the given decl has function
61/// type (function or function-typed variable) or an Objective-C
62/// method.
63static bool isFunctionOrMethod(const Decl *d) {
64  return isFunction(d)|| isa<ObjCMethodDecl>(d);
65}
66
67/// isFunctionOrMethodOrBlock - Return true if the given decl has function
68/// type (function or function-typed variable) or an Objective-C
69/// method or a block.
70static bool isFunctionOrMethodOrBlock(const Decl *d) {
71  if (isFunctionOrMethod(d))
72    return true;
73  // check for block is more involved.
74  if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
75    QualType Ty = V->getType();
76    return Ty->isBlockPointerType();
77  }
78  return isa<BlockDecl>(d);
79}
80
81/// hasFunctionProto - Return true if the given decl has a argument
82/// information. This decl should have already passed
83/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
84static bool hasFunctionProto(const Decl *d) {
85  if (const FunctionType *FnTy = getFunctionType(d))
86    return isa<FunctionProtoType>(FnTy);
87  else {
88    assert(isa<ObjCMethodDecl>(d) || isa<BlockDecl>(d));
89    return true;
90  }
91}
92
93/// getFunctionOrMethodNumArgs - Return number of function or method
94/// arguments. It is an error to call this on a K&R function (use
95/// hasFunctionProto first).
96static unsigned getFunctionOrMethodNumArgs(const Decl *d) {
97  if (const FunctionType *FnTy = getFunctionType(d))
98    return cast<FunctionProtoType>(FnTy)->getNumArgs();
99  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
100    return BD->getNumParams();
101  return cast<ObjCMethodDecl>(d)->param_size();
102}
103
104static QualType getFunctionOrMethodArgType(const Decl *d, unsigned Idx) {
105  if (const FunctionType *FnTy = getFunctionType(d))
106    return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
107  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
108    return BD->getParamDecl(Idx)->getType();
109
110  return cast<ObjCMethodDecl>(d)->param_begin()[Idx]->getType();
111}
112
113static QualType getFunctionOrMethodResultType(const Decl *d) {
114  if (const FunctionType *FnTy = getFunctionType(d))
115    return cast<FunctionProtoType>(FnTy)->getResultType();
116  return cast<ObjCMethodDecl>(d)->getResultType();
117}
118
119static bool isFunctionOrMethodVariadic(const Decl *d) {
120  if (const FunctionType *FnTy = getFunctionType(d)) {
121    const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
122    return proto->isVariadic();
123  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
124    return BD->isVariadic();
125  else {
126    return cast<ObjCMethodDecl>(d)->isVariadic();
127  }
128}
129
130static bool isInstanceMethod(const Decl *d) {
131  if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(d))
132    return MethodDecl->isInstance();
133  return false;
134}
135
136static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
137  const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
138  if (!PT)
139    return false;
140
141  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
142  if (!Cls)
143    return false;
144
145  IdentifierInfo* ClsName = Cls->getIdentifier();
146
147  // FIXME: Should we walk the chain of classes?
148  return ClsName == &Ctx.Idents.get("NSString") ||
149         ClsName == &Ctx.Idents.get("NSMutableString");
150}
151
152static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
153  const PointerType *PT = T->getAs<PointerType>();
154  if (!PT)
155    return false;
156
157  const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
158  if (!RT)
159    return false;
160
161  const RecordDecl *RD = RT->getDecl();
162  if (RD->getTagKind() != TTK_Struct)
163    return false;
164
165  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
166}
167
168//===----------------------------------------------------------------------===//
169// Attribute Implementations
170//===----------------------------------------------------------------------===//
171
172// FIXME: All this manual attribute parsing code is gross. At the
173// least add some helper functions to check most argument patterns (#
174// and types of args).
175
176static void HandleExtVectorTypeAttr(Scope *scope, Decl *d,
177                                    const AttributeList &Attr, Sema &S) {
178  TypedefDecl *tDecl = dyn_cast<TypedefDecl>(d);
179  if (tDecl == 0) {
180    S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
181    return;
182  }
183
184  QualType curType = tDecl->getUnderlyingType();
185
186  Expr *sizeExpr;
187
188  // Special case where the argument is a template id.
189  if (Attr.getParameterName()) {
190    CXXScopeSpec SS;
191    UnqualifiedId id;
192    id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
193    sizeExpr = S.ActOnIdExpression(scope, SS, id, false, false).takeAs<Expr>();
194  } else {
195    // check the attribute arguments.
196    if (Attr.getNumArgs() != 1) {
197      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
198      return;
199    }
200    sizeExpr = Attr.getArg(0);
201  }
202
203  // Instantiate/Install the vector type, and let Sema build the type for us.
204  // This will run the reguired checks.
205  QualType T = S.BuildExtVectorType(curType, sizeExpr, Attr.getLoc());
206  if (!T.isNull()) {
207    // FIXME: preserve the old source info.
208    tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
209
210    // Remember this typedef decl, we will need it later for diagnostics.
211    S.ExtVectorDecls.push_back(tDecl);
212  }
213}
214
215static void HandlePackedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
216  // check the attribute arguments.
217  if (Attr.getNumArgs() > 0) {
218    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
219    return;
220  }
221
222  if (TagDecl *TD = dyn_cast<TagDecl>(d))
223    TD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
224  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
225    // If the alignment is less than or equal to 8 bits, the packed attribute
226    // has no effect.
227    if (!FD->getType()->isIncompleteType() &&
228        S.Context.getTypeAlign(FD->getType()) <= 8)
229      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
230        << Attr.getName() << FD->getType();
231    else
232      FD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
233  } else
234    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
235}
236
237static void HandleIBAction(Decl *d, const AttributeList &Attr, Sema &S) {
238  // check the attribute arguments.
239  if (Attr.getNumArgs() > 0) {
240    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
241    return;
242  }
243
244  // The IBAction attributes only apply to instance methods.
245  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
246    if (MD->isInstanceMethod()) {
247      d->addAttr(::new (S.Context) IBActionAttr(Attr.getLoc(), S.Context));
248      return;
249    }
250
251  S.Diag(Attr.getLoc(), diag::err_attribute_ibaction) << Attr.getName();
252}
253
254static void HandleIBOutlet(Decl *d, const AttributeList &Attr, Sema &S) {
255  // check the attribute arguments.
256  if (Attr.getNumArgs() > 0) {
257    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
258    return;
259  }
260
261  // The IBOutlet attributes only apply to instance variables of
262  // Objective-C classes.
263  if (isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d)) {
264    d->addAttr(::new (S.Context) IBOutletAttr(Attr.getLoc(), S.Context));
265    return;
266  }
267
268  S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
269}
270
271static void HandleIBOutletCollection(Decl *d, const AttributeList &Attr,
272                                     Sema &S) {
273
274  // The iboutletcollection attribute can have zero or one arguments.
275  if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
276    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
277    return;
278  }
279
280  // The IBOutletCollection attributes only apply to instance variables of
281  // Objective-C classes.
282  if (!(isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d))) {
283    S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
284    return;
285  }
286  if (const ValueDecl *VD = dyn_cast<ValueDecl>(d))
287    if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
288      S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
289        << VD->getType() << 0;
290      return;
291    }
292  if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(d))
293    if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
294      S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
295        << PD->getType() << 1;
296      return;
297    }
298
299  IdentifierInfo *II = Attr.getParameterName();
300  if (!II)
301    II = &S.Context.Idents.get("id");
302
303  ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
304                        S.getScopeForContext(d->getDeclContext()->getParent()));
305  if (!TypeRep) {
306    S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
307    return;
308  }
309  QualType QT = TypeRep.get();
310  // Diagnose use of non-object type in iboutletcollection attribute.
311  // FIXME. Gnu attribute extension ignores use of builtin types in
312  // attributes. So, __attribute__((iboutletcollection(char))) will be
313  // treated as __attribute__((iboutletcollection())).
314  if (!QT->isObjCIdType() && !QT->isObjCClassType() &&
315      !QT->isObjCObjectType()) {
316    S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
317    return;
318  }
319  d->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getLoc(), S.Context,
320                                                      QT));
321}
322
323static void HandleNonNullAttr(Decl *d, const AttributeList &Attr, Sema &S) {
324  // GCC ignores the nonnull attribute on K&R style function prototypes, so we
325  // ignore it as well
326  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
327    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
328      << Attr.getName() << 0 /*function*/;
329    return;
330  }
331
332  // In C++ the implicit 'this' function parameter also counts, and they are
333  // counted from one.
334  bool HasImplicitThisParam = isInstanceMethod(d);
335  unsigned NumArgs  = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
336
337  // The nonnull attribute only applies to pointers.
338  llvm::SmallVector<unsigned, 10> NonNullArgs;
339
340  for (AttributeList::arg_iterator I=Attr.arg_begin(),
341                                   E=Attr.arg_end(); I!=E; ++I) {
342
343
344    // The argument must be an integer constant expression.
345    Expr *Ex = *I;
346    llvm::APSInt ArgNum(32);
347    if (Ex->isTypeDependent() || Ex->isValueDependent() ||
348        !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    if (HasImplicitThisParam) {
364      if (x == 0) {
365        S.Diag(Attr.getLoc(),
366               diag::err_attribute_invalid_implicit_this_argument)
367          << "nonnull" << Ex->getSourceRange();
368        return;
369      }
370      --x;
371    }
372
373    // Is the function argument a pointer type?
374    QualType T = getFunctionOrMethodArgType(d, x);
375    if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
376      // FIXME: Should also highlight argument in decl.
377      S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
378        << "nonnull" << Ex->getSourceRange();
379      continue;
380    }
381
382    NonNullArgs.push_back(x);
383  }
384
385  // If no arguments were specified to __attribute__((nonnull)) then all pointer
386  // arguments have a nonnull attribute.
387  if (NonNullArgs.empty()) {
388    for (unsigned I = 0, E = getFunctionOrMethodNumArgs(d); I != E; ++I) {
389      QualType T = getFunctionOrMethodArgType(d, I);
390      if (T->isAnyPointerType() || T->isBlockPointerType())
391        NonNullArgs.push_back(I);
392      else if (const RecordType *UT = T->getAsUnionType()) {
393        if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
394          RecordDecl *UD = UT->getDecl();
395          for (RecordDecl::field_iterator it = UD->field_begin(),
396               itend = UD->field_end(); it != itend; ++it) {
397            T = it->getType();
398            if (T->isAnyPointerType() || T->isBlockPointerType()) {
399              NonNullArgs.push_back(I);
400              break;
401            }
402          }
403        }
404      }
405    }
406
407    // No pointer arguments?
408    if (NonNullArgs.empty()) {
409      // Warn the trivial case only if attribute is not coming from a
410      // macro instantiation.
411      if (Attr.getLoc().isFileID())
412        S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
413      return;
414    }
415  }
416
417  unsigned* start = &NonNullArgs[0];
418  unsigned size = NonNullArgs.size();
419  llvm::array_pod_sort(start, start + size);
420  d->addAttr(::new (S.Context) NonNullAttr(Attr.getLoc(), S.Context, start,
421                                           size));
422}
423
424static void HandleOwnershipAttr(Decl *d, const AttributeList &AL, Sema &S) {
425  // This attribute must be applied to a function declaration.
426  // The first argument to the attribute must be a string,
427  // the name of the resource, for example "malloc".
428  // The following arguments must be argument indexes, the arguments must be
429  // of integer type for Returns, otherwise of pointer type.
430  // The difference between Holds and Takes is that a pointer may still be used
431  // after being held.  free() should be __attribute((ownership_takes)), whereas
432  // a list append function may well be __attribute((ownership_holds)).
433
434  if (!AL.getParameterName()) {
435    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
436        << AL.getName()->getName() << 1;
437    return;
438  }
439  // Figure out our Kind, and check arguments while we're at it.
440  OwnershipAttr::OwnershipKind K;
441  switch (AL.getKind()) {
442  case AttributeList::AT_ownership_takes:
443    K = OwnershipAttr::Takes;
444    if (AL.getNumArgs() < 1) {
445      S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
446      return;
447    }
448    break;
449  case AttributeList::AT_ownership_holds:
450    K = OwnershipAttr::Holds;
451    if (AL.getNumArgs() < 1) {
452      S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
453      return;
454    }
455    break;
456  case AttributeList::AT_ownership_returns:
457    K = OwnershipAttr::Returns;
458    if (AL.getNumArgs() > 1) {
459      S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
460          << AL.getNumArgs() + 1;
461      return;
462    }
463    break;
464  default:
465    // This should never happen given how we are called.
466    llvm_unreachable("Unknown ownership attribute");
467  }
468
469  if (!isFunction(d) || !hasFunctionProto(d)) {
470    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL.getName()
471        << 0 /*function*/;
472    return;
473  }
474
475  // In C++ the implicit 'this' function parameter also counts, and they are
476  // counted from one.
477  bool HasImplicitThisParam = isInstanceMethod(d);
478  unsigned NumArgs  = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
479
480  llvm::StringRef Module = AL.getParameterName()->getName();
481
482  // Normalize the argument, __foo__ becomes foo.
483  if (Module.startswith("__") && Module.endswith("__"))
484    Module = Module.substr(2, Module.size() - 4);
485
486  llvm::SmallVector<unsigned, 10> OwnershipArgs;
487
488  for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
489       ++I) {
490
491    Expr *IdxExpr = *I;
492    llvm::APSInt ArgNum(32);
493    if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
494        || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
495      S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
496          << AL.getName()->getName() << IdxExpr->getSourceRange();
497      continue;
498    }
499
500    unsigned x = (unsigned) ArgNum.getZExtValue();
501
502    if (x > NumArgs || x < 1) {
503      S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
504          << AL.getName()->getName() << x << IdxExpr->getSourceRange();
505      continue;
506    }
507    --x;
508    if (HasImplicitThisParam) {
509      if (x == 0) {
510        S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
511          << "ownership" << IdxExpr->getSourceRange();
512        return;
513      }
514      --x;
515    }
516
517    switch (K) {
518    case OwnershipAttr::Takes:
519    case OwnershipAttr::Holds: {
520      // Is the function argument a pointer type?
521      QualType T = getFunctionOrMethodArgType(d, x);
522      if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
523        // FIXME: Should also highlight argument in decl.
524        S.Diag(AL.getLoc(), diag::err_ownership_type)
525            << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
526            << "pointer"
527            << IdxExpr->getSourceRange();
528        continue;
529      }
530      break;
531    }
532    case OwnershipAttr::Returns: {
533      if (AL.getNumArgs() > 1) {
534          // Is the function argument an integer type?
535          Expr *IdxExpr = AL.getArg(0);
536          llvm::APSInt ArgNum(32);
537          if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
538              || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
539            S.Diag(AL.getLoc(), diag::err_ownership_type)
540                << "ownership_returns" << "integer"
541                << IdxExpr->getSourceRange();
542            return;
543          }
544      }
545      break;
546    }
547    default:
548      llvm_unreachable("Unknown ownership attribute");
549    } // switch
550
551    // Check we don't have a conflict with another ownership attribute.
552    for (specific_attr_iterator<OwnershipAttr>
553          i = d->specific_attr_begin<OwnershipAttr>(),
554          e = d->specific_attr_end<OwnershipAttr>();
555        i != e; ++i) {
556      if ((*i)->getOwnKind() != K) {
557        for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
558             I!=E; ++I) {
559          if (x == *I) {
560            S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
561                << AL.getName()->getName() << "ownership_*";
562          }
563        }
564      }
565    }
566    OwnershipArgs.push_back(x);
567  }
568
569  unsigned* start = OwnershipArgs.data();
570  unsigned size = OwnershipArgs.size();
571  llvm::array_pod_sort(start, start + size);
572
573  if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
574    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
575    return;
576  }
577
578  d->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, K, Module,
579                                             start, size));
580}
581
582static bool isStaticVarOrStaticFunciton(Decl *D) {
583  if (VarDecl *VD = dyn_cast<VarDecl>(D))
584    return VD->getStorageClass() == SC_Static;
585  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
586    return FD->getStorageClass() == SC_Static;
587  return false;
588}
589
590static void HandleWeakRefAttr(Decl *d, const AttributeList &Attr, Sema &S) {
591  // Check the attribute arguments.
592  if (Attr.getNumArgs() > 1) {
593    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
594    return;
595  }
596
597  // gcc rejects
598  // class c {
599  //   static int a __attribute__((weakref ("v2")));
600  //   static int b() __attribute__((weakref ("f3")));
601  // };
602  // and ignores the attributes of
603  // void f(void) {
604  //   static int a __attribute__((weakref ("v2")));
605  // }
606  // we reject them
607  const DeclContext *Ctx = d->getDeclContext()->getRedeclContext();
608  if (!Ctx->isFileContext()) {
609    S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
610        dyn_cast<NamedDecl>(d)->getNameAsString();
611    return;
612  }
613
614  // The GCC manual says
615  //
616  // At present, a declaration to which `weakref' is attached can only
617  // be `static'.
618  //
619  // It also says
620  //
621  // Without a TARGET,
622  // given as an argument to `weakref' or to `alias', `weakref' is
623  // equivalent to `weak'.
624  //
625  // gcc 4.4.1 will accept
626  // int a7 __attribute__((weakref));
627  // as
628  // int a7 __attribute__((weak));
629  // This looks like a bug in gcc. We reject that for now. We should revisit
630  // it if this behaviour is actually used.
631
632  if (!isStaticVarOrStaticFunciton(d)) {
633    S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static) <<
634      dyn_cast<NamedDecl>(d)->getNameAsString();
635    return;
636  }
637
638  // GCC rejects
639  // static ((alias ("y"), weakref)).
640  // Should we? How to check that weakref is before or after alias?
641
642  if (Attr.getNumArgs() == 1) {
643    Expr *Arg = Attr.getArg(0);
644    Arg = Arg->IgnoreParenCasts();
645    StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
646
647    if (Str == 0 || Str->isWide()) {
648      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
649          << "weakref" << 1;
650      return;
651    }
652    // GCC will accept anything as the argument of weakref. Should we
653    // check for an existing decl?
654    d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
655                                           Str->getString()));
656  }
657
658  d->addAttr(::new (S.Context) WeakRefAttr(Attr.getLoc(), S.Context));
659}
660
661static void HandleAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
662  // check the attribute arguments.
663  if (Attr.getNumArgs() != 1) {
664    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
665    return;
666  }
667
668  Expr *Arg = Attr.getArg(0);
669  Arg = Arg->IgnoreParenCasts();
670  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
671
672  if (Str == 0 || Str->isWide()) {
673    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
674      << "alias" << 1;
675    return;
676  }
677
678  // FIXME: check if target symbol exists in current file
679
680  d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
681                                         Str->getString()));
682}
683
684static void HandleNakedAttr(Decl *d, const AttributeList &Attr,
685                                   Sema &S) {
686  // Check the attribute arguments.
687  if (Attr.getNumArgs() != 0) {
688    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
689    return;
690  }
691
692  if (!isa<FunctionDecl>(d)) {
693    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
694      << Attr.getName() << 0 /*function*/;
695    return;
696  }
697
698  d->addAttr(::new (S.Context) NakedAttr(Attr.getLoc(), S.Context));
699}
700
701static void HandleAlwaysInlineAttr(Decl *d, const AttributeList &Attr,
702                                   Sema &S) {
703  // Check the attribute arguments.
704  if (Attr.getNumArgs() != 0) {
705    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
706    return;
707  }
708
709  if (!isa<FunctionDecl>(d)) {
710    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
711      << Attr.getName() << 0 /*function*/;
712    return;
713  }
714
715  d->addAttr(::new (S.Context) AlwaysInlineAttr(Attr.getLoc(), S.Context));
716}
717
718static void HandleMallocAttr(Decl *d, const AttributeList &Attr, Sema &S) {
719  // Check the attribute arguments.
720  if (Attr.getNumArgs() != 0) {
721    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
722    return;
723  }
724
725  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
726    QualType RetTy = FD->getResultType();
727    if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
728      d->addAttr(::new (S.Context) MallocAttr(Attr.getLoc(), S.Context));
729      return;
730    }
731  }
732
733  S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
734}
735
736static void HandleMayAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
737  // check the attribute arguments.
738  if (Attr.getNumArgs() != 0) {
739    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
740    return;
741  }
742
743  d->addAttr(::new (S.Context) MayAliasAttr(Attr.getLoc(), S.Context));
744}
745
746static void HandleNoCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
747  assert(Attr.isInvalid() == false);
748  if (isa<VarDecl>(d))
749    d->addAttr(::new (S.Context) NoCommonAttr(Attr.getLoc(), S.Context));
750  else
751    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
752      << Attr.getName() << 12 /* variable */;
753}
754
755static void HandleCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
756  assert(Attr.isInvalid() == false);
757  if (isa<VarDecl>(d))
758    d->addAttr(::new (S.Context) CommonAttr(Attr.getLoc(), S.Context));
759  else
760    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
761      << Attr.getName() << 12 /* variable */;
762}
763
764static void HandleNoReturnAttr(Decl *d, const AttributeList &Attr, Sema &S) {
765  /* Diagnostics (if any) was emitted by Sema::ProcessFnAttr(). */
766  assert(Attr.isInvalid() == false);
767  d->addAttr(::new (S.Context) NoReturnAttr(Attr.getLoc(), S.Context));
768}
769
770static void HandleAnalyzerNoReturnAttr(Decl *d, const AttributeList &Attr,
771                                       Sema &S) {
772
773  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
774  // because 'analyzer_noreturn' does not impact the type.
775
776  if (Attr.getNumArgs() != 0) {
777    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
778    return;
779  }
780
781  if (!isFunctionOrMethod(d) && !isa<BlockDecl>(d)) {
782    ValueDecl *VD = dyn_cast<ValueDecl>(d);
783    if (VD == 0 || (!VD->getType()->isBlockPointerType()
784                    && !VD->getType()->isFunctionPointerType())) {
785      S.Diag(Attr.getLoc(),
786             Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
787             : diag::warn_attribute_wrong_decl_type)
788      << Attr.getName() << 0 /*function*/;
789      return;
790    }
791  }
792
793  d->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getLoc(), S.Context));
794}
795
796// PS3 PPU-specific.
797static void HandleVecReturnAttr(Decl *d, const AttributeList &Attr,
798                                       Sema &S) {
799/*
800  Returning a Vector Class in Registers
801
802  According to the PPU ABI specifications, a class with a single member of
803  vector type is returned in memory when used as the return value of a function.
804  This results in inefficient code when implementing vector classes. To return
805  the value in a single vector register, add the vecreturn attribute to the
806  class definition. This attribute is also applicable to struct types.
807
808  Example:
809
810  struct Vector
811  {
812    __vector float xyzw;
813  } __attribute__((vecreturn));
814
815  Vector Add(Vector lhs, Vector rhs)
816  {
817    Vector result;
818    result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
819    return result; // This will be returned in a register
820  }
821*/
822  if (!isa<RecordDecl>(d)) {
823    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
824      << Attr.getName() << 9 /*class*/;
825    return;
826  }
827
828  if (d->getAttr<VecReturnAttr>()) {
829    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
830    return;
831  }
832
833  RecordDecl *record = cast<RecordDecl>(d);
834  int count = 0;
835
836  if (!isa<CXXRecordDecl>(record)) {
837    S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
838    return;
839  }
840
841  if (!cast<CXXRecordDecl>(record)->isPOD()) {
842    S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
843    return;
844  }
845
846  for (RecordDecl::field_iterator iter = record->field_begin();
847       iter != record->field_end(); iter++) {
848    if ((count == 1) || !iter->getType()->isVectorType()) {
849      S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
850      return;
851    }
852    count++;
853  }
854
855  d->addAttr(::new (S.Context) VecReturnAttr(Attr.getLoc(), S.Context));
856}
857
858static void HandleDependencyAttr(Decl *d, const AttributeList &Attr, Sema &S) {
859  if (!isFunctionOrMethod(d) && !isa<ParmVarDecl>(d)) {
860    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
861      << Attr.getName() << 8 /*function, method, or parameter*/;
862    return;
863  }
864  // FIXME: Actually store the attribute on the declaration
865}
866
867static void HandleUnusedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
868  // check the attribute arguments.
869  if (Attr.getNumArgs() != 0) {
870    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
871    return;
872  }
873
874  if (!isa<VarDecl>(d) && !isa<ObjCIvarDecl>(d) && !isFunctionOrMethod(d) &&
875      !isa<TypeDecl>(d)) {
876    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
877      << Attr.getName() << 2 /*variable and function*/;
878    return;
879  }
880
881  d->addAttr(::new (S.Context) UnusedAttr(Attr.getLoc(), S.Context));
882}
883
884static void HandleUsedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
885  // check the attribute arguments.
886  if (Attr.getNumArgs() != 0) {
887    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
888    return;
889  }
890
891  if (const VarDecl *VD = dyn_cast<VarDecl>(d)) {
892    if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
893      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
894      return;
895    }
896  } else if (!isFunctionOrMethod(d)) {
897    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
898      << Attr.getName() << 2 /*variable and function*/;
899    return;
900  }
901
902  d->addAttr(::new (S.Context) UsedAttr(Attr.getLoc(), S.Context));
903}
904
905static void HandleConstructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
906  // check the attribute arguments.
907  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
908    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
909      << "0 or 1";
910    return;
911  }
912
913  int priority = 65535; // FIXME: Do not hardcode such constants.
914  if (Attr.getNumArgs() > 0) {
915    Expr *E = Attr.getArg(0);
916    llvm::APSInt Idx(32);
917    if (E->isTypeDependent() || E->isValueDependent() ||
918        !E->isIntegerConstantExpr(Idx, S.Context)) {
919      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
920        << "constructor" << 1 << E->getSourceRange();
921      return;
922    }
923    priority = Idx.getZExtValue();
924  }
925
926  if (!isa<FunctionDecl>(d)) {
927    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
928      << Attr.getName() << 0 /*function*/;
929    return;
930  }
931
932  d->addAttr(::new (S.Context) ConstructorAttr(Attr.getLoc(), S.Context,
933                                               priority));
934}
935
936static void HandleDestructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
937  // check the attribute arguments.
938  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
939    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
940       << "0 or 1";
941    return;
942  }
943
944  int priority = 65535; // FIXME: Do not hardcode such constants.
945  if (Attr.getNumArgs() > 0) {
946    Expr *E = Attr.getArg(0);
947    llvm::APSInt Idx(32);
948    if (E->isTypeDependent() || E->isValueDependent() ||
949        !E->isIntegerConstantExpr(Idx, S.Context)) {
950      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
951        << "destructor" << 1 << E->getSourceRange();
952      return;
953    }
954    priority = Idx.getZExtValue();
955  }
956
957  if (!isa<FunctionDecl>(d)) {
958    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
959      << Attr.getName() << 0 /*function*/;
960    return;
961  }
962
963  d->addAttr(::new (S.Context) DestructorAttr(Attr.getLoc(), S.Context,
964                                              priority));
965}
966
967static void HandleDeprecatedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
968  // check the attribute arguments.
969  int noArgs = Attr.getNumArgs();
970  if (noArgs > 1) {
971    S.Diag(Attr.getLoc(),
972           diag::err_attribute_wrong_number_arguments) << "0 or 1";
973    return;
974  }
975  // Handle the case where deprecated attribute has a text message.
976  StringLiteral *SE;
977  if (noArgs == 1) {
978    Expr *ArgExpr = Attr.getArg(0);
979    SE = dyn_cast<StringLiteral>(ArgExpr);
980    if (!SE) {
981      S.Diag(ArgExpr->getLocStart(),
982             diag::err_attribute_not_string) << "deprecated";
983      return;
984    }
985  }
986  else
987    SE = StringLiteral::CreateEmpty(S.Context, 1);
988
989  d->addAttr(::new (S.Context) DeprecatedAttr(Attr.getLoc(), S.Context,
990                                              SE->getString()));
991}
992
993static void HandleUnavailableAttr(Decl *d, const AttributeList &Attr, Sema &S) {
994  // check the attribute arguments.
995  int noArgs = Attr.getNumArgs();
996  if (noArgs > 1) {
997    S.Diag(Attr.getLoc(),
998           diag::err_attribute_wrong_number_arguments) << "0 or 1";
999    return;
1000  }
1001  // Handle the case where unavailable attribute has a text message.
1002  StringLiteral *SE;
1003  if (noArgs == 1) {
1004    Expr *ArgExpr = Attr.getArg(0);
1005    SE = dyn_cast<StringLiteral>(ArgExpr);
1006    if (!SE) {
1007      S.Diag(ArgExpr->getLocStart(),
1008             diag::err_attribute_not_string) << "unavailable";
1009      return;
1010    }
1011  }
1012  else
1013    SE = StringLiteral::CreateEmpty(S.Context, 1);
1014  d->addAttr(::new (S.Context) UnavailableAttr(Attr.getLoc(), S.Context,
1015                                               SE->getString()));
1016}
1017
1018static void HandleVisibilityAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1019  // check the attribute arguments.
1020  if (Attr.getNumArgs() != 1) {
1021    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1022    return;
1023  }
1024
1025  Expr *Arg = Attr.getArg(0);
1026  Arg = Arg->IgnoreParenCasts();
1027  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1028
1029  if (Str == 0 || Str->isWide()) {
1030    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1031      << "visibility" << 1;
1032    return;
1033  }
1034
1035  llvm::StringRef TypeStr = Str->getString();
1036  VisibilityAttr::VisibilityType type;
1037
1038  if (TypeStr == "default")
1039    type = VisibilityAttr::Default;
1040  else if (TypeStr == "hidden")
1041    type = VisibilityAttr::Hidden;
1042  else if (TypeStr == "internal")
1043    type = VisibilityAttr::Hidden; // FIXME
1044  else if (TypeStr == "protected")
1045    type = VisibilityAttr::Protected;
1046  else {
1047    S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
1048    return;
1049  }
1050
1051  d->addAttr(::new (S.Context) VisibilityAttr(Attr.getLoc(), S.Context, type));
1052}
1053
1054static void HandleObjCExceptionAttr(Decl *D, const AttributeList &Attr,
1055                                    Sema &S) {
1056  if (Attr.getNumArgs() != 0) {
1057    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1058    return;
1059  }
1060
1061  ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
1062  if (OCI == 0) {
1063    S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
1064    return;
1065  }
1066
1067  D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getLoc(), S.Context));
1068}
1069
1070static void HandleObjCNSObject(Decl *D, const AttributeList &Attr, Sema &S) {
1071  if (Attr.getNumArgs() != 0) {
1072    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1073    return;
1074  }
1075  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1076    QualType T = TD->getUnderlyingType();
1077    if (!T->isPointerType() ||
1078        !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
1079      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
1080      return;
1081    }
1082  }
1083  D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getLoc(), S.Context));
1084}
1085
1086static void
1087HandleOverloadableAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1088  if (Attr.getNumArgs() != 0) {
1089    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1090    return;
1091  }
1092
1093  if (!isa<FunctionDecl>(D)) {
1094    S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
1095    return;
1096  }
1097
1098  D->addAttr(::new (S.Context) OverloadableAttr(Attr.getLoc(), S.Context));
1099}
1100
1101static void HandleBlocksAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1102  if (!Attr.getParameterName()) {
1103    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1104      << "blocks" << 1;
1105    return;
1106  }
1107
1108  if (Attr.getNumArgs() != 0) {
1109    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1110    return;
1111  }
1112
1113  BlocksAttr::BlockType type;
1114  if (Attr.getParameterName()->isStr("byref"))
1115    type = BlocksAttr::ByRef;
1116  else {
1117    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1118      << "blocks" << Attr.getParameterName();
1119    return;
1120  }
1121
1122  d->addAttr(::new (S.Context) BlocksAttr(Attr.getLoc(), S.Context, type));
1123}
1124
1125static void HandleSentinelAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1126  // check the attribute arguments.
1127  if (Attr.getNumArgs() > 2) {
1128    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1129      << "0, 1 or 2";
1130    return;
1131  }
1132
1133  int sentinel = 0;
1134  if (Attr.getNumArgs() > 0) {
1135    Expr *E = Attr.getArg(0);
1136    llvm::APSInt Idx(32);
1137    if (E->isTypeDependent() || E->isValueDependent() ||
1138        !E->isIntegerConstantExpr(Idx, S.Context)) {
1139      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1140       << "sentinel" << 1 << E->getSourceRange();
1141      return;
1142    }
1143    sentinel = Idx.getZExtValue();
1144
1145    if (sentinel < 0) {
1146      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
1147        << E->getSourceRange();
1148      return;
1149    }
1150  }
1151
1152  int nullPos = 0;
1153  if (Attr.getNumArgs() > 1) {
1154    Expr *E = Attr.getArg(1);
1155    llvm::APSInt Idx(32);
1156    if (E->isTypeDependent() || E->isValueDependent() ||
1157        !E->isIntegerConstantExpr(Idx, S.Context)) {
1158      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1159        << "sentinel" << 2 << E->getSourceRange();
1160      return;
1161    }
1162    nullPos = Idx.getZExtValue();
1163
1164    if (nullPos > 1 || nullPos < 0) {
1165      // FIXME: This error message could be improved, it would be nice
1166      // to say what the bounds actually are.
1167      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
1168        << E->getSourceRange();
1169      return;
1170    }
1171  }
1172
1173  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
1174    const FunctionType *FT = FD->getType()->getAs<FunctionType>();
1175    assert(FT && "FunctionDecl has non-function type?");
1176
1177    if (isa<FunctionNoProtoType>(FT)) {
1178      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
1179      return;
1180    }
1181
1182    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1183      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1184      return;
1185    }
1186  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d)) {
1187    if (!MD->isVariadic()) {
1188      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1189      return;
1190    }
1191  } else if (isa<BlockDecl>(d)) {
1192    // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
1193    // caller.
1194    ;
1195  } else if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
1196    QualType Ty = V->getType();
1197    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
1198      const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(d)
1199       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
1200      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1201        int m = Ty->isFunctionPointerType() ? 0 : 1;
1202        S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
1203        return;
1204      }
1205    } else {
1206      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1207      << Attr.getName() << 6 /*function, method or block */;
1208      return;
1209    }
1210  } else {
1211    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1212      << Attr.getName() << 6 /*function, method or block */;
1213    return;
1214  }
1215  d->addAttr(::new (S.Context) SentinelAttr(Attr.getLoc(), S.Context, sentinel,
1216                                            nullPos));
1217}
1218
1219static void HandleWarnUnusedResult(Decl *D, const AttributeList &Attr, Sema &S) {
1220  // check the attribute arguments.
1221  if (Attr.getNumArgs() != 0) {
1222    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1223    return;
1224  }
1225
1226  if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
1227    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1228      << Attr.getName() << 0 /*function*/;
1229    return;
1230  }
1231
1232  if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
1233    S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1234      << Attr.getName() << 0;
1235    return;
1236  }
1237  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1238    if (MD->getResultType()->isVoidType()) {
1239      S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1240      << Attr.getName() << 1;
1241      return;
1242    }
1243
1244  D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getLoc(), S.Context));
1245}
1246
1247static void HandleWeakAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1248  // check the attribute arguments.
1249  if (Attr.getNumArgs() != 0) {
1250    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1251    return;
1252  }
1253
1254  /* weak only applies to non-static declarations */
1255  if (isStaticVarOrStaticFunciton(D)) {
1256    S.Diag(Attr.getLoc(), diag::err_attribute_weak_static) <<
1257      dyn_cast<NamedDecl>(D)->getNameAsString();
1258    return;
1259  }
1260
1261  // TODO: could also be applied to methods?
1262  if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
1263    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1264      << Attr.getName() << 2 /*variable and function*/;
1265    return;
1266  }
1267
1268  D->addAttr(::new (S.Context) WeakAttr(Attr.getLoc(), S.Context));
1269}
1270
1271static void HandleWeakImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1272  // check the attribute arguments.
1273  if (Attr.getNumArgs() != 0) {
1274    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1275    return;
1276  }
1277
1278  // weak_import only applies to variable & function declarations.
1279  bool isDef = false;
1280  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1281    isDef = (!VD->hasExternalStorage() || VD->getInit());
1282  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1283    isDef = FD->hasBody();
1284  } else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D)) {
1285    // We ignore weak import on properties and methods
1286    return;
1287  } else if (!(S.LangOpts.ObjCNonFragileABI && isa<ObjCInterfaceDecl>(D))) {
1288    // Don't issue the warning for darwin as target; yet, ignore the attribute.
1289    if (S.Context.Target.getTriple().getOS() != llvm::Triple::Darwin ||
1290        !isa<ObjCInterfaceDecl>(D))
1291      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1292        << Attr.getName() << 2 /*variable and function*/;
1293      return;
1294  }
1295
1296  // Merge should handle any subsequent violations.
1297  if (isDef) {
1298    S.Diag(Attr.getLoc(),
1299           diag::warn_attribute_weak_import_invalid_on_definition)
1300      << "weak_import" << 2 /*variable and function*/;
1301    return;
1302  }
1303
1304  D->addAttr(::new (S.Context) WeakImportAttr(Attr.getLoc(), S.Context));
1305}
1306
1307static void HandleReqdWorkGroupSize(Decl *D, const AttributeList &Attr,
1308                                    Sema &S) {
1309  // Attribute has 3 arguments.
1310  if (Attr.getNumArgs() != 3) {
1311    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1312    return;
1313  }
1314
1315  unsigned WGSize[3];
1316  for (unsigned i = 0; i < 3; ++i) {
1317    Expr *E = Attr.getArg(i);
1318    llvm::APSInt ArgNum(32);
1319    if (E->isTypeDependent() || E->isValueDependent() ||
1320        !E->isIntegerConstantExpr(ArgNum, S.Context)) {
1321      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1322        << "reqd_work_group_size" << E->getSourceRange();
1323      return;
1324    }
1325    WGSize[i] = (unsigned) ArgNum.getZExtValue();
1326  }
1327  D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(Attr.getLoc(), S.Context,
1328                                                     WGSize[0], WGSize[1],
1329                                                     WGSize[2]));
1330}
1331
1332static void HandleSectionAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1333  // Attribute has no arguments.
1334  if (Attr.getNumArgs() != 1) {
1335    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1336    return;
1337  }
1338
1339  // Make sure that there is a string literal as the sections's single
1340  // argument.
1341  Expr *ArgExpr = Attr.getArg(0);
1342  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1343  if (!SE) {
1344    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
1345    return;
1346  }
1347
1348  // If the target wants to validate the section specifier, make it happen.
1349  std::string Error = S.Context.Target.isValidSectionSpecifier(SE->getString());
1350  if (!Error.empty()) {
1351    S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
1352    << Error;
1353    return;
1354  }
1355
1356  // This attribute cannot be applied to local variables.
1357  if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
1358    S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
1359    return;
1360  }
1361
1362  D->addAttr(::new (S.Context) SectionAttr(Attr.getLoc(), S.Context,
1363                                           SE->getString()));
1364}
1365
1366
1367static void HandleNothrowAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1368  // check the attribute arguments.
1369  if (Attr.getNumArgs() != 0) {
1370    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1371    return;
1372  }
1373
1374  d->addAttr(::new (S.Context) NoThrowAttr(Attr.getLoc(), S.Context));
1375}
1376
1377static void HandleConstAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1378  // check the attribute arguments.
1379  if (Attr.getNumArgs() != 0) {
1380    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1381    return;
1382  }
1383
1384  d->addAttr(::new (S.Context) ConstAttr(Attr.getLoc(), S.Context));
1385}
1386
1387static void HandlePureAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1388  // check the attribute arguments.
1389  if (Attr.getNumArgs() != 0) {
1390    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1391    return;
1392  }
1393
1394  d->addAttr(::new (S.Context) PureAttr(Attr.getLoc(), S.Context));
1395}
1396
1397static void HandleCleanupAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1398  if (!Attr.getParameterName()) {
1399    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1400    return;
1401  }
1402
1403  if (Attr.getNumArgs() != 0) {
1404    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1405    return;
1406  }
1407
1408  VarDecl *VD = dyn_cast<VarDecl>(d);
1409
1410  if (!VD || !VD->hasLocalStorage()) {
1411    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
1412    return;
1413  }
1414
1415  // Look up the function
1416  // FIXME: Lookup probably isn't looking in the right place
1417  // FIXME: The lookup source location should be in the attribute, not the
1418  // start of the attribute.
1419  NamedDecl *CleanupDecl
1420    = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
1421                         Attr.getParameterLoc(), Sema::LookupOrdinaryName);
1422  if (!CleanupDecl) {
1423    S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
1424      Attr.getParameterName();
1425    return;
1426  }
1427
1428  FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
1429  if (!FD) {
1430    S.Diag(Attr.getParameterLoc(),
1431           diag::err_attribute_cleanup_arg_not_function)
1432      << Attr.getParameterName();
1433    return;
1434  }
1435
1436  if (FD->getNumParams() != 1) {
1437    S.Diag(Attr.getParameterLoc(),
1438           diag::err_attribute_cleanup_func_must_take_one_arg)
1439      << Attr.getParameterName();
1440    return;
1441  }
1442
1443  // We're currently more strict than GCC about what function types we accept.
1444  // If this ever proves to be a problem it should be easy to fix.
1445  QualType Ty = S.Context.getPointerType(VD->getType());
1446  QualType ParamTy = FD->getParamDecl(0)->getType();
1447  if (S.CheckAssignmentConstraints(ParamTy, Ty) != Sema::Compatible) {
1448    S.Diag(Attr.getParameterLoc(),
1449           diag::err_attribute_cleanup_func_arg_incompatible_type) <<
1450      Attr.getParameterName() << ParamTy << Ty;
1451    return;
1452  }
1453
1454  d->addAttr(::new (S.Context) CleanupAttr(Attr.getLoc(), S.Context, FD));
1455  S.MarkDeclarationReferenced(Attr.getParameterLoc(), FD);
1456}
1457
1458/// Handle __attribute__((format_arg((idx)))) attribute based on
1459/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1460static void HandleFormatArgAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1461  if (Attr.getNumArgs() != 1) {
1462    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1463    return;
1464  }
1465  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
1466    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1467    << Attr.getName() << 0 /*function*/;
1468    return;
1469  }
1470
1471  // In C++ the implicit 'this' function parameter also counts, and they are
1472  // counted from one.
1473  bool HasImplicitThisParam = isInstanceMethod(d);
1474  unsigned NumArgs  = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1475  unsigned FirstIdx = 1;
1476
1477  // checks for the 2nd argument
1478  Expr *IdxExpr = Attr.getArg(0);
1479  llvm::APSInt Idx(32);
1480  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1481      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1482    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1483    << "format" << 2 << IdxExpr->getSourceRange();
1484    return;
1485  }
1486
1487  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1488    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1489    << "format" << 2 << IdxExpr->getSourceRange();
1490    return;
1491  }
1492
1493  unsigned ArgIdx = Idx.getZExtValue() - 1;
1494
1495  if (HasImplicitThisParam) {
1496    if (ArgIdx == 0) {
1497      S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1498        << "format_arg" << IdxExpr->getSourceRange();
1499      return;
1500    }
1501    ArgIdx--;
1502  }
1503
1504  // make sure the format string is really a string
1505  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1506
1507  bool not_nsstring_type = !isNSStringType(Ty, S.Context);
1508  if (not_nsstring_type &&
1509      !isCFStringType(Ty, S.Context) &&
1510      (!Ty->isPointerType() ||
1511       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1512    // FIXME: Should highlight the actual expression that has the wrong type.
1513    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1514    << (not_nsstring_type ? "a string type" : "an NSString")
1515       << IdxExpr->getSourceRange();
1516    return;
1517  }
1518  Ty = getFunctionOrMethodResultType(d);
1519  if (!isNSStringType(Ty, S.Context) &&
1520      !isCFStringType(Ty, S.Context) &&
1521      (!Ty->isPointerType() ||
1522       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1523    // FIXME: Should highlight the actual expression that has the wrong type.
1524    S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
1525    << (not_nsstring_type ? "string type" : "NSString")
1526       << IdxExpr->getSourceRange();
1527    return;
1528  }
1529
1530  d->addAttr(::new (S.Context) FormatArgAttr(Attr.getLoc(), S.Context,
1531                                             Idx.getZExtValue()));
1532}
1533
1534enum FormatAttrKind {
1535  CFStringFormat,
1536  NSStringFormat,
1537  StrftimeFormat,
1538  SupportedFormat,
1539  IgnoredFormat,
1540  InvalidFormat
1541};
1542
1543/// getFormatAttrKind - Map from format attribute names to supported format
1544/// types.
1545static FormatAttrKind getFormatAttrKind(llvm::StringRef Format) {
1546  // Check for formats that get handled specially.
1547  if (Format == "NSString")
1548    return NSStringFormat;
1549  if (Format == "CFString")
1550    return CFStringFormat;
1551  if (Format == "strftime")
1552    return StrftimeFormat;
1553
1554  // Otherwise, check for supported formats.
1555  if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
1556      Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
1557      Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
1558      Format == "zcmn_err")
1559    return SupportedFormat;
1560
1561  if (Format == "gcc_diag" || Format == "gcc_cdiag" ||
1562      Format == "gcc_cxxdiag" || Format == "gcc_tdiag")
1563    return IgnoredFormat;
1564
1565  return InvalidFormat;
1566}
1567
1568/// Handle __attribute__((init_priority(priority))) attributes based on
1569/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
1570static void HandleInitPriorityAttr(Decl *d, const AttributeList &Attr,
1571                                   Sema &S) {
1572  if (!S.getLangOptions().CPlusPlus) {
1573    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1574    return;
1575  }
1576
1577  if (!isa<VarDecl>(d) || S.getCurFunctionOrMethodDecl()) {
1578    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1579    Attr.setInvalid();
1580    return;
1581  }
1582  QualType T = dyn_cast<VarDecl>(d)->getType();
1583  if (S.Context.getAsArrayType(T))
1584    T = S.Context.getBaseElementType(T);
1585  if (!T->getAs<RecordType>()) {
1586    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1587    Attr.setInvalid();
1588    return;
1589  }
1590
1591  if (Attr.getNumArgs() != 1) {
1592    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1593    Attr.setInvalid();
1594    return;
1595  }
1596  Expr *priorityExpr = Attr.getArg(0);
1597
1598  llvm::APSInt priority(32);
1599  if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
1600      !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
1601    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1602    << "init_priority" << priorityExpr->getSourceRange();
1603    Attr.setInvalid();
1604    return;
1605  }
1606  unsigned prioritynum = priority.getZExtValue();
1607  if (prioritynum < 101 || prioritynum > 65535) {
1608    S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
1609    <<  priorityExpr->getSourceRange();
1610    Attr.setInvalid();
1611    return;
1612  }
1613  d->addAttr(::new (S.Context) InitPriorityAttr(Attr.getLoc(), S.Context,
1614                                                prioritynum));
1615}
1616
1617/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
1618/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1619static void HandleFormatAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1620
1621  if (!Attr.getParameterName()) {
1622    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1623      << "format" << 1;
1624    return;
1625  }
1626
1627  if (Attr.getNumArgs() != 2) {
1628    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
1629    return;
1630  }
1631
1632  if (!isFunctionOrMethodOrBlock(d) || !hasFunctionProto(d)) {
1633    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1634      << Attr.getName() << 0 /*function*/;
1635    return;
1636  }
1637
1638  // In C++ the implicit 'this' function parameter also counts, and they are
1639  // counted from one.
1640  bool HasImplicitThisParam = isInstanceMethod(d);
1641  unsigned NumArgs  = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1642  unsigned FirstIdx = 1;
1643
1644  llvm::StringRef Format = Attr.getParameterName()->getName();
1645
1646  // Normalize the argument, __foo__ becomes foo.
1647  if (Format.startswith("__") && Format.endswith("__"))
1648    Format = Format.substr(2, Format.size() - 4);
1649
1650  // Check for supported formats.
1651  FormatAttrKind Kind = getFormatAttrKind(Format);
1652
1653  if (Kind == IgnoredFormat)
1654    return;
1655
1656  if (Kind == InvalidFormat) {
1657    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1658      << "format" << Attr.getParameterName()->getName();
1659    return;
1660  }
1661
1662  // checks for the 2nd argument
1663  Expr *IdxExpr = Attr.getArg(0);
1664  llvm::APSInt Idx(32);
1665  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1666      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1667    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1668      << "format" << 2 << IdxExpr->getSourceRange();
1669    return;
1670  }
1671
1672  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1673    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1674      << "format" << 2 << IdxExpr->getSourceRange();
1675    return;
1676  }
1677
1678  // FIXME: Do we need to bounds check?
1679  unsigned ArgIdx = Idx.getZExtValue() - 1;
1680
1681  if (HasImplicitThisParam) {
1682    if (ArgIdx == 0) {
1683      S.Diag(Attr.getLoc(),
1684             diag::err_format_attribute_implicit_this_format_string)
1685        << IdxExpr->getSourceRange();
1686      return;
1687    }
1688    ArgIdx--;
1689  }
1690
1691  // make sure the format string is really a string
1692  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1693
1694  if (Kind == CFStringFormat) {
1695    if (!isCFStringType(Ty, S.Context)) {
1696      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1697        << "a CFString" << IdxExpr->getSourceRange();
1698      return;
1699    }
1700  } else if (Kind == NSStringFormat) {
1701    // FIXME: do we need to check if the type is NSString*?  What are the
1702    // semantics?
1703    if (!isNSStringType(Ty, S.Context)) {
1704      // FIXME: Should highlight the actual expression that has the wrong type.
1705      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1706        << "an NSString" << IdxExpr->getSourceRange();
1707      return;
1708    }
1709  } else if (!Ty->isPointerType() ||
1710             !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
1711    // FIXME: Should highlight the actual expression that has the wrong type.
1712    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1713      << "a string type" << IdxExpr->getSourceRange();
1714    return;
1715  }
1716
1717  // check the 3rd argument
1718  Expr *FirstArgExpr = Attr.getArg(1);
1719  llvm::APSInt FirstArg(32);
1720  if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
1721      !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
1722    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1723      << "format" << 3 << FirstArgExpr->getSourceRange();
1724    return;
1725  }
1726
1727  // check if the function is variadic if the 3rd argument non-zero
1728  if (FirstArg != 0) {
1729    if (isFunctionOrMethodVariadic(d)) {
1730      ++NumArgs; // +1 for ...
1731    } else {
1732      S.Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
1733      return;
1734    }
1735  }
1736
1737  // strftime requires FirstArg to be 0 because it doesn't read from any
1738  // variable the input is just the current time + the format string.
1739  if (Kind == StrftimeFormat) {
1740    if (FirstArg != 0) {
1741      S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
1742        << FirstArgExpr->getSourceRange();
1743      return;
1744    }
1745  // if 0 it disables parameter checking (to use with e.g. va_list)
1746  } else if (FirstArg != 0 && FirstArg != NumArgs) {
1747    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1748      << "format" << 3 << FirstArgExpr->getSourceRange();
1749    return;
1750  }
1751
1752  d->addAttr(::new (S.Context) FormatAttr(Attr.getLoc(), S.Context, Format,
1753                                          Idx.getZExtValue(),
1754                                          FirstArg.getZExtValue()));
1755}
1756
1757static void HandleTransparentUnionAttr(Decl *d, const AttributeList &Attr,
1758                                       Sema &S) {
1759  // check the attribute arguments.
1760  if (Attr.getNumArgs() != 0) {
1761    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1762    return;
1763  }
1764
1765  // Try to find the underlying union declaration.
1766  RecordDecl *RD = 0;
1767  TypedefDecl *TD = dyn_cast<TypedefDecl>(d);
1768  if (TD && TD->getUnderlyingType()->isUnionType())
1769    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
1770  else
1771    RD = dyn_cast<RecordDecl>(d);
1772
1773  if (!RD || !RD->isUnion()) {
1774    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1775      << Attr.getName() << 1 /*union*/;
1776    return;
1777  }
1778
1779  if (!RD->isDefinition()) {
1780    S.Diag(Attr.getLoc(),
1781        diag::warn_transparent_union_attribute_not_definition);
1782    return;
1783  }
1784
1785  RecordDecl::field_iterator Field = RD->field_begin(),
1786                          FieldEnd = RD->field_end();
1787  if (Field == FieldEnd) {
1788    S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
1789    return;
1790  }
1791
1792  FieldDecl *FirstField = *Field;
1793  QualType FirstType = FirstField->getType();
1794  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
1795    S.Diag(FirstField->getLocation(),
1796           diag::warn_transparent_union_attribute_floating)
1797      << FirstType->isVectorType() << FirstType;
1798    return;
1799  }
1800
1801  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
1802  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
1803  for (; Field != FieldEnd; ++Field) {
1804    QualType FieldType = Field->getType();
1805    if (S.Context.getTypeSize(FieldType) != FirstSize ||
1806        S.Context.getTypeAlign(FieldType) != FirstAlign) {
1807      // Warn if we drop the attribute.
1808      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
1809      unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
1810                                 : S.Context.getTypeAlign(FieldType);
1811      S.Diag(Field->getLocation(),
1812          diag::warn_transparent_union_attribute_field_size_align)
1813        << isSize << Field->getDeclName() << FieldBits;
1814      unsigned FirstBits = isSize? FirstSize : FirstAlign;
1815      S.Diag(FirstField->getLocation(),
1816             diag::note_transparent_union_first_field_size_align)
1817        << isSize << FirstBits;
1818      return;
1819    }
1820  }
1821
1822  RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getLoc(), S.Context));
1823}
1824
1825static void HandleAnnotateAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1826  // check the attribute arguments.
1827  if (Attr.getNumArgs() != 1) {
1828    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1829    return;
1830  }
1831  Expr *ArgExpr = Attr.getArg(0);
1832  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1833
1834  // Make sure that there is a string literal as the annotation's single
1835  // argument.
1836  if (!SE) {
1837    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
1838    return;
1839  }
1840  d->addAttr(::new (S.Context) AnnotateAttr(Attr.getLoc(), S.Context,
1841                                            SE->getString()));
1842}
1843
1844static void HandleAlignedAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1845  // check the attribute arguments.
1846  if (Attr.getNumArgs() > 1) {
1847    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1848    return;
1849  }
1850
1851  //FIXME: The C++0x version of this attribute has more limited applicabilty
1852  //       than GNU's, and should error out when it is used to specify a
1853  //       weaker alignment, rather than being silently ignored.
1854
1855  if (Attr.getNumArgs() == 0) {
1856    D->addAttr(::new (S.Context) AlignedAttr(Attr.getLoc(), S.Context, true, 0));
1857    return;
1858  }
1859
1860  S.AddAlignedAttr(Attr.getLoc(), D, Attr.getArg(0));
1861}
1862
1863void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E) {
1864  if (E->isTypeDependent() || E->isValueDependent()) {
1865    // Save dependent expressions in the AST to be instantiated.
1866    D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
1867    return;
1868  }
1869
1870  // FIXME: Cache the number on the Attr object?
1871  llvm::APSInt Alignment(32);
1872  if (!E->isIntegerConstantExpr(Alignment, Context)) {
1873    Diag(AttrLoc, diag::err_attribute_argument_not_int)
1874      << "aligned" << E->getSourceRange();
1875    return;
1876  }
1877  if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
1878    Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
1879      << E->getSourceRange();
1880    return;
1881  }
1882
1883  D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
1884}
1885
1886void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *TS) {
1887  // FIXME: Cache the number on the Attr object if non-dependent?
1888  // FIXME: Perform checking of type validity
1889  D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, false, TS));
1890  return;
1891}
1892
1893/// HandleModeAttr - This attribute modifies the width of a decl with primitive
1894/// type.
1895///
1896/// Despite what would be logical, the mode attribute is a decl attribute, not a
1897/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
1898/// HImode, not an intermediate pointer.
1899static void HandleModeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1900  // This attribute isn't documented, but glibc uses it.  It changes
1901  // the width of an int or unsigned int to the specified size.
1902
1903  // Check that there aren't any arguments
1904  if (Attr.getNumArgs() != 0) {
1905    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1906    return;
1907  }
1908
1909  IdentifierInfo *Name = Attr.getParameterName();
1910  if (!Name) {
1911    S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
1912    return;
1913  }
1914
1915  llvm::StringRef Str = Attr.getParameterName()->getName();
1916
1917  // Normalize the attribute name, __foo__ becomes foo.
1918  if (Str.startswith("__") && Str.endswith("__"))
1919    Str = Str.substr(2, Str.size() - 4);
1920
1921  unsigned DestWidth = 0;
1922  bool IntegerMode = true;
1923  bool ComplexMode = false;
1924  switch (Str.size()) {
1925  case 2:
1926    switch (Str[0]) {
1927    case 'Q': DestWidth = 8; break;
1928    case 'H': DestWidth = 16; break;
1929    case 'S': DestWidth = 32; break;
1930    case 'D': DestWidth = 64; break;
1931    case 'X': DestWidth = 96; break;
1932    case 'T': DestWidth = 128; break;
1933    }
1934    if (Str[1] == 'F') {
1935      IntegerMode = false;
1936    } else if (Str[1] == 'C') {
1937      IntegerMode = false;
1938      ComplexMode = true;
1939    } else if (Str[1] != 'I') {
1940      DestWidth = 0;
1941    }
1942    break;
1943  case 4:
1944    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
1945    // pointer on PIC16 and other embedded platforms.
1946    if (Str == "word")
1947      DestWidth = S.Context.Target.getPointerWidth(0);
1948    else if (Str == "byte")
1949      DestWidth = S.Context.Target.getCharWidth();
1950    break;
1951  case 7:
1952    if (Str == "pointer")
1953      DestWidth = S.Context.Target.getPointerWidth(0);
1954    break;
1955  }
1956
1957  QualType OldTy;
1958  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D))
1959    OldTy = TD->getUnderlyingType();
1960  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
1961    OldTy = VD->getType();
1962  else {
1963    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
1964      << "mode" << SourceRange(Attr.getLoc(), Attr.getLoc());
1965    return;
1966  }
1967
1968  if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
1969    S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
1970  else if (IntegerMode) {
1971    if (!OldTy->isIntegralOrEnumerationType())
1972      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1973  } else if (ComplexMode) {
1974    if (!OldTy->isComplexType())
1975      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1976  } else {
1977    if (!OldTy->isFloatingType())
1978      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1979  }
1980
1981  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
1982  // and friends, at least with glibc.
1983  // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
1984  // width on unusual platforms.
1985  // FIXME: Make sure floating-point mappings are accurate
1986  // FIXME: Support XF and TF types
1987  QualType NewTy;
1988  switch (DestWidth) {
1989  case 0:
1990    S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
1991    return;
1992  default:
1993    S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1994    return;
1995  case 8:
1996    if (!IntegerMode) {
1997      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1998      return;
1999    }
2000    if (OldTy->isSignedIntegerType())
2001      NewTy = S.Context.SignedCharTy;
2002    else
2003      NewTy = S.Context.UnsignedCharTy;
2004    break;
2005  case 16:
2006    if (!IntegerMode) {
2007      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2008      return;
2009    }
2010    if (OldTy->isSignedIntegerType())
2011      NewTy = S.Context.ShortTy;
2012    else
2013      NewTy = S.Context.UnsignedShortTy;
2014    break;
2015  case 32:
2016    if (!IntegerMode)
2017      NewTy = S.Context.FloatTy;
2018    else if (OldTy->isSignedIntegerType())
2019      NewTy = S.Context.IntTy;
2020    else
2021      NewTy = S.Context.UnsignedIntTy;
2022    break;
2023  case 64:
2024    if (!IntegerMode)
2025      NewTy = S.Context.DoubleTy;
2026    else if (OldTy->isSignedIntegerType())
2027      if (S.Context.Target.getLongWidth() == 64)
2028        NewTy = S.Context.LongTy;
2029      else
2030        NewTy = S.Context.LongLongTy;
2031    else
2032      if (S.Context.Target.getLongWidth() == 64)
2033        NewTy = S.Context.UnsignedLongTy;
2034      else
2035        NewTy = S.Context.UnsignedLongLongTy;
2036    break;
2037  case 96:
2038    NewTy = S.Context.LongDoubleTy;
2039    break;
2040  case 128:
2041    if (!IntegerMode) {
2042      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2043      return;
2044    }
2045    if (OldTy->isSignedIntegerType())
2046      NewTy = S.Context.Int128Ty;
2047    else
2048      NewTy = S.Context.UnsignedInt128Ty;
2049    break;
2050  }
2051
2052  if (ComplexMode) {
2053    NewTy = S.Context.getComplexType(NewTy);
2054  }
2055
2056  // Install the new type.
2057  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
2058    // FIXME: preserve existing source info.
2059    TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
2060  } else
2061    cast<ValueDecl>(D)->setType(NewTy);
2062}
2063
2064static void HandleNoDebugAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2065  // check the attribute arguments.
2066  if (Attr.getNumArgs() > 0) {
2067    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2068    return;
2069  }
2070
2071  if (!isFunctionOrMethod(d)) {
2072    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2073      << Attr.getName() << 0 /*function*/;
2074    return;
2075  }
2076
2077  d->addAttr(::new (S.Context) NoDebugAttr(Attr.getLoc(), S.Context));
2078}
2079
2080static void HandleNoInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2081  // check the attribute arguments.
2082  if (Attr.getNumArgs() != 0) {
2083    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2084    return;
2085  }
2086
2087  if (!isa<FunctionDecl>(d)) {
2088    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2089    << Attr.getName() << 0 /*function*/;
2090    return;
2091  }
2092
2093  d->addAttr(::new (S.Context) NoInlineAttr(Attr.getLoc(), S.Context));
2094}
2095
2096static void HandleNoInstrumentFunctionAttr(Decl *d, const AttributeList &Attr,
2097                                           Sema &S) {
2098  // check the attribute arguments.
2099  if (Attr.getNumArgs() != 0) {
2100    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2101    return;
2102  }
2103
2104  if (!isa<FunctionDecl>(d)) {
2105    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2106    << Attr.getName() << 0 /*function*/;
2107    return;
2108  }
2109
2110  d->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getLoc(),
2111                                                        S.Context));
2112}
2113
2114static void HandleConstantAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2115  if (S.LangOpts.CUDA) {
2116    // check the attribute arguments.
2117    if (Attr.getNumArgs() != 0) {
2118      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2119      return;
2120    }
2121
2122    if (!isa<VarDecl>(d)) {
2123      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2124        << Attr.getName() << 12 /*variable*/;
2125      return;
2126    }
2127
2128    d->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getLoc(), S.Context));
2129  } else {
2130    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
2131  }
2132}
2133
2134static void HandleDeviceAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2135  if (S.LangOpts.CUDA) {
2136    // check the attribute arguments.
2137    if (Attr.getNumArgs() != 0) {
2138      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2139      return;
2140    }
2141
2142    if (!isa<FunctionDecl>(d) && !isa<VarDecl>(d)) {
2143      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2144        << Attr.getName() << 2 /*variable and function*/;
2145      return;
2146    }
2147
2148    d->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getLoc(), S.Context));
2149  } else {
2150    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
2151  }
2152}
2153
2154static void HandleGlobalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2155  if (S.LangOpts.CUDA) {
2156    // check the attribute arguments.
2157    if (Attr.getNumArgs() != 0) {
2158      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2159      return;
2160    }
2161
2162    if (!isa<FunctionDecl>(d)) {
2163      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2164        << Attr.getName() << 0 /*function*/;
2165      return;
2166    }
2167
2168    d->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getLoc(), S.Context));
2169  } else {
2170    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
2171  }
2172}
2173
2174static void HandleHostAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2175  if (S.LangOpts.CUDA) {
2176    // check the attribute arguments.
2177    if (Attr.getNumArgs() != 0) {
2178      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2179      return;
2180    }
2181
2182    if (!isa<FunctionDecl>(d)) {
2183      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2184        << Attr.getName() << 0 /*function*/;
2185      return;
2186    }
2187
2188    d->addAttr(::new (S.Context) CUDAHostAttr(Attr.getLoc(), S.Context));
2189  } else {
2190    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
2191  }
2192}
2193
2194static void HandleSharedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2195  if (S.LangOpts.CUDA) {
2196    // check the attribute arguments.
2197    if (Attr.getNumArgs() != 0) {
2198      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2199      return;
2200    }
2201
2202    if (!isa<VarDecl>(d)) {
2203      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2204        << Attr.getName() << 12 /*variable*/;
2205      return;
2206    }
2207
2208    d->addAttr(::new (S.Context) CUDASharedAttr(Attr.getLoc(), S.Context));
2209  } else {
2210    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
2211  }
2212}
2213
2214static void HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2215  // check the attribute arguments.
2216  if (Attr.getNumArgs() != 0) {
2217    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2218    return;
2219  }
2220
2221  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2222  if (Fn == 0) {
2223    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2224      << Attr.getName() << 0 /*function*/;
2225    return;
2226  }
2227
2228  if (!Fn->isInlineSpecified()) {
2229    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
2230    return;
2231  }
2232
2233  d->addAttr(::new (S.Context) GNUInlineAttr(Attr.getLoc(), S.Context));
2234}
2235
2236static void HandleCallConvAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2237  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
2238  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
2239  assert(Attr.isInvalid() == false);
2240
2241  switch (Attr.getKind()) {
2242  case AttributeList::AT_fastcall:
2243    d->addAttr(::new (S.Context) FastCallAttr(Attr.getLoc(), S.Context));
2244    return;
2245  case AttributeList::AT_stdcall:
2246    d->addAttr(::new (S.Context) StdCallAttr(Attr.getLoc(), S.Context));
2247    return;
2248  case AttributeList::AT_thiscall:
2249    d->addAttr(::new (S.Context) ThisCallAttr(Attr.getLoc(), S.Context));
2250    return;
2251  case AttributeList::AT_cdecl:
2252    d->addAttr(::new (S.Context) CDeclAttr(Attr.getLoc(), S.Context));
2253    return;
2254  case AttributeList::AT_pascal:
2255    d->addAttr(::new (S.Context) PascalAttr(Attr.getLoc(), S.Context));
2256    return;
2257  default:
2258    llvm_unreachable("unexpected attribute kind");
2259    return;
2260  }
2261}
2262
2263static void HandleRegparmAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2264  // check the attribute arguments.
2265  if (Attr.getNumArgs() != 1) {
2266    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2267    return;
2268  }
2269
2270  if (!isFunctionOrMethod(d)) {
2271    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2272    << Attr.getName() << 0 /*function*/;
2273    return;
2274  }
2275
2276  Expr *NumParamsExpr = Attr.getArg(0);
2277  llvm::APSInt NumParams(32);
2278  if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
2279      !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
2280    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2281      << "regparm" << NumParamsExpr->getSourceRange();
2282    return;
2283  }
2284
2285  if (S.Context.Target.getRegParmMax() == 0) {
2286    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
2287      << NumParamsExpr->getSourceRange();
2288    return;
2289  }
2290
2291  if (NumParams.getLimitedValue(255) > S.Context.Target.getRegParmMax()) {
2292    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
2293      << S.Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
2294    return;
2295  }
2296
2297  d->addAttr(::new (S.Context) RegparmAttr(Attr.getLoc(), S.Context,
2298                                           NumParams.getZExtValue()));
2299}
2300
2301static void HandleFinalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2302  // check the attribute arguments.
2303  if (Attr.getNumArgs() != 0) {
2304    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2305    return;
2306  }
2307
2308  if (!isa<CXXRecordDecl>(d)
2309   && (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual())) {
2310    S.Diag(Attr.getLoc(),
2311           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2312                                   : diag::warn_attribute_wrong_decl_type)
2313      << Attr.getName() << 7 /*virtual method or class*/;
2314    return;
2315  }
2316
2317  // FIXME: Conform to C++0x redeclaration rules.
2318
2319  if (d->getAttr<FinalAttr>()) {
2320    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "final";
2321    return;
2322  }
2323
2324  d->addAttr(::new (S.Context) FinalAttr(Attr.getLoc(), S.Context));
2325}
2326
2327//===----------------------------------------------------------------------===//
2328// C++0x member checking attributes
2329//===----------------------------------------------------------------------===//
2330
2331static void HandleBaseCheckAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2332  if (Attr.getNumArgs() != 0) {
2333    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2334    return;
2335  }
2336
2337  if (!isa<CXXRecordDecl>(d)) {
2338    S.Diag(Attr.getLoc(),
2339           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2340                                   : diag::warn_attribute_wrong_decl_type)
2341      << Attr.getName() << 9 /*class*/;
2342    return;
2343  }
2344
2345  if (d->getAttr<BaseCheckAttr>()) {
2346    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "base_check";
2347    return;
2348  }
2349
2350  d->addAttr(::new (S.Context) BaseCheckAttr(Attr.getLoc(), S.Context));
2351}
2352
2353static void HandleHidingAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2354  if (Attr.getNumArgs() != 0) {
2355    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2356    return;
2357  }
2358
2359  if (!isa<RecordDecl>(d->getDeclContext())) {
2360    // FIXME: It's not the type that's the problem
2361    S.Diag(Attr.getLoc(),
2362           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2363                                   : diag::warn_attribute_wrong_decl_type)
2364      << Attr.getName() << 11 /*member*/;
2365    return;
2366  }
2367
2368  // FIXME: Conform to C++0x redeclaration rules.
2369
2370  if (d->getAttr<HidingAttr>()) {
2371    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "hiding";
2372    return;
2373  }
2374
2375  d->addAttr(::new (S.Context) HidingAttr(Attr.getLoc(), S.Context));
2376}
2377
2378static void HandleOverrideAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2379  if (Attr.getNumArgs() != 0) {
2380    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2381    return;
2382  }
2383
2384  if (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual()) {
2385    // FIXME: It's not the type that's the problem
2386    S.Diag(Attr.getLoc(),
2387           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2388                                   : diag::warn_attribute_wrong_decl_type)
2389      << Attr.getName() << 10 /*virtual method*/;
2390    return;
2391  }
2392
2393  // FIXME: Conform to C++0x redeclaration rules.
2394
2395  if (d->getAttr<OverrideAttr>()) {
2396    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "override";
2397    return;
2398  }
2399
2400  d->addAttr(::new (S.Context) OverrideAttr(Attr.getLoc(), S.Context));
2401}
2402
2403//===----------------------------------------------------------------------===//
2404// Checker-specific attribute handlers.
2405//===----------------------------------------------------------------------===//
2406
2407static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &Attr,
2408                                        Sema &S) {
2409
2410  QualType RetTy;
2411
2412  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
2413    RetTy = MD->getResultType();
2414  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
2415    RetTy = FD->getResultType();
2416  else {
2417    SourceLocation L = Attr.getLoc();
2418    S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2419        << SourceRange(L, L) << Attr.getName() << 3 /* function or method */;
2420    return;
2421  }
2422
2423  if (!(S.Context.isObjCNSObjectType(RetTy) || RetTy->getAs<PointerType>()
2424        || RetTy->getAs<ObjCObjectPointerType>())) {
2425    SourceLocation L = Attr.getLoc();
2426    S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
2427      << SourceRange(L, L) << Attr.getName();
2428    return;
2429  }
2430
2431  switch (Attr.getKind()) {
2432    default:
2433      assert(0 && "invalid ownership attribute");
2434      return;
2435    case AttributeList::AT_cf_returns_not_retained:
2436      d->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getLoc(),
2437                                                            S.Context));
2438      return;
2439    case AttributeList::AT_ns_returns_not_retained:
2440      d->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getLoc(),
2441                                                            S.Context));
2442      return;
2443    case AttributeList::AT_cf_returns_retained:
2444      d->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getLoc(),
2445                                                         S.Context));
2446      return;
2447    case AttributeList::AT_ns_returns_retained:
2448      d->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getLoc(),
2449                                                         S.Context));
2450      return;
2451  };
2452}
2453
2454static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
2455  return Attr.getKind() == AttributeList::AT_dllimport ||
2456         Attr.getKind() == AttributeList::AT_dllexport;
2457}
2458
2459//===----------------------------------------------------------------------===//
2460// Top Level Sema Entry Points
2461//===----------------------------------------------------------------------===//
2462
2463/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
2464/// the attribute applies to decls.  If the attribute is a type attribute, just
2465/// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
2466/// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
2467static void ProcessDeclAttribute(Scope *scope, Decl *D,
2468                                 const AttributeList &Attr, Sema &S) {
2469  if (Attr.isInvalid())
2470    return;
2471
2472  if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
2473    // FIXME: Try to deal with other __declspec attributes!
2474    return;
2475  switch (Attr.getKind()) {
2476  case AttributeList::AT_IBAction:            HandleIBAction(D, Attr, S); break;
2477    case AttributeList::AT_IBOutlet:          HandleIBOutlet(D, Attr, S); break;
2478  case AttributeList::AT_IBOutletCollection:
2479      HandleIBOutletCollection(D, Attr, S); break;
2480  case AttributeList::AT_address_space:
2481  case AttributeList::AT_objc_gc:
2482  case AttributeList::AT_vector_size:
2483  case AttributeList::AT_neon_vector_type:
2484  case AttributeList::AT_neon_polyvector_type:
2485    // Ignore these, these are type attributes, handled by
2486    // ProcessTypeAttributes.
2487    break;
2488  case AttributeList::AT_alias:       HandleAliasAttr       (D, Attr, S); break;
2489  case AttributeList::AT_aligned:     HandleAlignedAttr     (D, Attr, S); break;
2490  case AttributeList::AT_always_inline:
2491    HandleAlwaysInlineAttr  (D, Attr, S); break;
2492  case AttributeList::AT_analyzer_noreturn:
2493    HandleAnalyzerNoReturnAttr  (D, Attr, S); break;
2494  case AttributeList::AT_annotate:    HandleAnnotateAttr    (D, Attr, S); break;
2495  case AttributeList::AT_base_check:  HandleBaseCheckAttr   (D, Attr, S); break;
2496  case AttributeList::AT_carries_dependency:
2497                                      HandleDependencyAttr  (D, Attr, S); break;
2498  case AttributeList::AT_common:      HandleCommonAttr      (D, Attr, S); break;
2499  case AttributeList::AT_constant:    HandleConstantAttr    (D, Attr, S); break;
2500  case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
2501  case AttributeList::AT_deprecated:  HandleDeprecatedAttr  (D, Attr, S); break;
2502  case AttributeList::AT_destructor:  HandleDestructorAttr  (D, Attr, S); break;
2503  case AttributeList::AT_device:      HandleDeviceAttr      (D, Attr, S); break;
2504  case AttributeList::AT_ext_vector_type:
2505    HandleExtVectorTypeAttr(scope, D, Attr, S);
2506    break;
2507  case AttributeList::AT_final:       HandleFinalAttr       (D, Attr, S); break;
2508  case AttributeList::AT_format:      HandleFormatAttr      (D, Attr, S); break;
2509  case AttributeList::AT_format_arg:  HandleFormatArgAttr   (D, Attr, S); break;
2510  case AttributeList::AT_global:      HandleGlobalAttr      (D, Attr, S); break;
2511  case AttributeList::AT_gnu_inline:  HandleGNUInlineAttr   (D, Attr, S); break;
2512  case AttributeList::AT_hiding:      HandleHidingAttr      (D, Attr, S); break;
2513  case AttributeList::AT_host:        HandleHostAttr        (D, Attr, S); break;
2514  case AttributeList::AT_mode:        HandleModeAttr        (D, Attr, S); break;
2515  case AttributeList::AT_malloc:      HandleMallocAttr      (D, Attr, S); break;
2516  case AttributeList::AT_may_alias:   HandleMayAliasAttr    (D, Attr, S); break;
2517  case AttributeList::AT_nocommon:    HandleNoCommonAttr    (D, Attr, S); break;
2518  case AttributeList::AT_nonnull:     HandleNonNullAttr     (D, Attr, S); break;
2519  case AttributeList::AT_ownership_returns:
2520  case AttributeList::AT_ownership_takes:
2521  case AttributeList::AT_ownership_holds:
2522      HandleOwnershipAttr     (D, Attr, S); break;
2523  case AttributeList::AT_naked:       HandleNakedAttr       (D, Attr, S); break;
2524  case AttributeList::AT_noreturn:    HandleNoReturnAttr    (D, Attr, S); break;
2525  case AttributeList::AT_nothrow:     HandleNothrowAttr     (D, Attr, S); break;
2526  case AttributeList::AT_override:    HandleOverrideAttr    (D, Attr, S); break;
2527  case AttributeList::AT_shared:      HandleSharedAttr      (D, Attr, S); break;
2528  case AttributeList::AT_vecreturn:   HandleVecReturnAttr   (D, Attr, S); break;
2529
2530  // Checker-specific.
2531  case AttributeList::AT_ns_returns_not_retained:
2532  case AttributeList::AT_cf_returns_not_retained:
2533  case AttributeList::AT_ns_returns_retained:
2534  case AttributeList::AT_cf_returns_retained:
2535    HandleNSReturnsRetainedAttr(D, Attr, S); break;
2536
2537  case AttributeList::AT_reqd_wg_size:
2538    HandleReqdWorkGroupSize(D, Attr, S); break;
2539
2540  case AttributeList::AT_init_priority:
2541      HandleInitPriorityAttr(D, Attr, S); break;
2542
2543  case AttributeList::AT_packed:      HandlePackedAttr      (D, Attr, S); break;
2544  case AttributeList::AT_section:     HandleSectionAttr     (D, Attr, S); break;
2545  case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
2546  case AttributeList::AT_unused:      HandleUnusedAttr      (D, Attr, S); break;
2547  case AttributeList::AT_used:        HandleUsedAttr        (D, Attr, S); break;
2548  case AttributeList::AT_visibility:  HandleVisibilityAttr  (D, Attr, S); break;
2549  case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
2550    break;
2551  case AttributeList::AT_weak:        HandleWeakAttr        (D, Attr, S); break;
2552  case AttributeList::AT_weakref:     HandleWeakRefAttr     (D, Attr, S); break;
2553  case AttributeList::AT_weak_import: HandleWeakImportAttr  (D, Attr, S); break;
2554  case AttributeList::AT_transparent_union:
2555    HandleTransparentUnionAttr(D, Attr, S);
2556    break;
2557  case AttributeList::AT_objc_exception:
2558    HandleObjCExceptionAttr(D, Attr, S);
2559    break;
2560  case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
2561  case AttributeList::AT_nsobject:    HandleObjCNSObject    (D, Attr, S); break;
2562  case AttributeList::AT_blocks:      HandleBlocksAttr      (D, Attr, S); break;
2563  case AttributeList::AT_sentinel:    HandleSentinelAttr    (D, Attr, S); break;
2564  case AttributeList::AT_const:       HandleConstAttr       (D, Attr, S); break;
2565  case AttributeList::AT_pure:        HandlePureAttr        (D, Attr, S); break;
2566  case AttributeList::AT_cleanup:     HandleCleanupAttr     (D, Attr, S); break;
2567  case AttributeList::AT_nodebug:     HandleNoDebugAttr     (D, Attr, S); break;
2568  case AttributeList::AT_noinline:    HandleNoInlineAttr    (D, Attr, S); break;
2569  case AttributeList::AT_regparm:     HandleRegparmAttr     (D, Attr, S); break;
2570  case AttributeList::IgnoredAttribute:
2571    // Just ignore
2572    break;
2573  case AttributeList::AT_no_instrument_function:  // Interacts with -pg.
2574    HandleNoInstrumentFunctionAttr(D, Attr, S);
2575    break;
2576  case AttributeList::AT_stdcall:
2577  case AttributeList::AT_cdecl:
2578  case AttributeList::AT_fastcall:
2579  case AttributeList::AT_thiscall:
2580  case AttributeList::AT_pascal:
2581    HandleCallConvAttr(D, Attr, S);
2582    break;
2583  default:
2584    // Ask target about the attribute.
2585    const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
2586    if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
2587      S.Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored)
2588        << Attr.getName();
2589    break;
2590  }
2591}
2592
2593/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2594/// attribute list to the specified decl, ignoring any type attributes.
2595void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
2596                                    const AttributeList *AttrList) {
2597  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
2598    ProcessDeclAttribute(S, D, *l, *this);
2599  }
2600
2601  // GCC accepts
2602  // static int a9 __attribute__((weakref));
2603  // but that looks really pointless. We reject it.
2604  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
2605    Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
2606    dyn_cast<NamedDecl>(D)->getNameAsString();
2607    return;
2608  }
2609}
2610
2611/// DeclClonePragmaWeak - clone existing decl (maybe definition),
2612/// #pragma weak needs a non-definition decl and source may not have one
2613NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
2614  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
2615  NamedDecl *NewD = 0;
2616  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2617    NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
2618                                FD->getLocation(), DeclarationName(II),
2619                                FD->getType(), FD->getTypeSourceInfo());
2620    if (FD->getQualifier()) {
2621      FunctionDecl *NewFD = cast<FunctionDecl>(NewD);
2622      NewFD->setQualifierInfo(FD->getQualifier(), FD->getQualifierRange());
2623    }
2624  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
2625    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
2626                           VD->getLocation(), II,
2627                           VD->getType(), VD->getTypeSourceInfo(),
2628                           VD->getStorageClass(),
2629                           VD->getStorageClassAsWritten());
2630    if (VD->getQualifier()) {
2631      VarDecl *NewVD = cast<VarDecl>(NewD);
2632      NewVD->setQualifierInfo(VD->getQualifier(), VD->getQualifierRange());
2633    }
2634  }
2635  return NewD;
2636}
2637
2638/// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
2639/// applied to it, possibly with an alias.
2640void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
2641  if (W.getUsed()) return; // only do this once
2642  W.setUsed(true);
2643  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
2644    IdentifierInfo *NDId = ND->getIdentifier();
2645    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
2646    NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
2647                                            NDId->getName()));
2648    NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2649    WeakTopLevelDecl.push_back(NewD);
2650    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
2651    // to insert Decl at TU scope, sorry.
2652    DeclContext *SavedContext = CurContext;
2653    CurContext = Context.getTranslationUnitDecl();
2654    PushOnScopeChains(NewD, S);
2655    CurContext = SavedContext;
2656  } else { // just add weak to existing
2657    ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2658  }
2659}
2660
2661/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
2662/// it, apply them to D.  This is a bit tricky because PD can have attributes
2663/// specified in many different places, and we need to find and apply them all.
2664void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
2665  // It's valid to "forward-declare" #pragma weak, in which case we
2666  // have to do this.
2667  if (!WeakUndeclaredIdentifiers.empty()) {
2668    if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
2669      if (IdentifierInfo *Id = ND->getIdentifier()) {
2670        llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
2671          = WeakUndeclaredIdentifiers.find(Id);
2672        if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
2673          WeakInfo W = I->second;
2674          DeclApplyPragmaWeak(S, ND, W);
2675          WeakUndeclaredIdentifiers[Id] = W;
2676        }
2677      }
2678    }
2679  }
2680
2681  // Apply decl attributes from the DeclSpec if present.
2682  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes())
2683    ProcessDeclAttributeList(S, D, Attrs);
2684
2685  // Walk the declarator structure, applying decl attributes that were in a type
2686  // position to the decl itself.  This handles cases like:
2687  //   int *__attr__(x)** D;
2688  // when X is a decl attribute.
2689  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
2690    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
2691      ProcessDeclAttributeList(S, D, Attrs);
2692
2693  // Finally, apply any attributes on the decl itself.
2694  if (const AttributeList *Attrs = PD.getAttributes())
2695    ProcessDeclAttributeList(S, D, Attrs);
2696}
2697
2698/// PushParsingDeclaration - Enter a new "scope" of deprecation
2699/// warnings.
2700///
2701/// The state token we use is the start index of this scope
2702/// on the warning stack.
2703Sema::ParsingDeclStackState Sema::PushParsingDeclaration() {
2704  ParsingDeclDepth++;
2705  return (ParsingDeclStackState) DelayedDiagnostics.size();
2706}
2707
2708void Sema::PopParsingDeclaration(ParsingDeclStackState S, Decl *D) {
2709  assert(ParsingDeclDepth > 0 && "empty ParsingDeclaration stack");
2710  ParsingDeclDepth--;
2711
2712  if (DelayedDiagnostics.empty())
2713    return;
2714
2715  unsigned SavedIndex = (unsigned) S;
2716  assert(SavedIndex <= DelayedDiagnostics.size() &&
2717         "saved index is out of bounds");
2718
2719  unsigned E = DelayedDiagnostics.size();
2720
2721  // We only want to actually emit delayed diagnostics when we
2722  // successfully parsed a decl.
2723  if (D) {
2724    // We really do want to start with 0 here.  We get one push for a
2725    // decl spec and another for each declarator;  in a decl group like:
2726    //   deprecated_typedef foo, *bar, baz();
2727    // only the declarator pops will be passed decls.  This is correct;
2728    // we really do need to consider delayed diagnostics from the decl spec
2729    // for each of the different declarations.
2730    for (unsigned I = 0; I != E; ++I) {
2731      if (DelayedDiagnostics[I].Triggered)
2732        continue;
2733
2734      switch (DelayedDiagnostics[I].Kind) {
2735      case DelayedDiagnostic::Deprecation:
2736        HandleDelayedDeprecationCheck(DelayedDiagnostics[I], D);
2737        break;
2738
2739      case DelayedDiagnostic::Access:
2740        HandleDelayedAccessCheck(DelayedDiagnostics[I], D);
2741        break;
2742      }
2743    }
2744  }
2745
2746  // Destroy all the delayed diagnostics we're about to pop off.
2747  for (unsigned I = SavedIndex; I != E; ++I)
2748    DelayedDiagnostics[I].destroy();
2749
2750  DelayedDiagnostics.set_size(SavedIndex);
2751}
2752
2753static bool isDeclDeprecated(Decl *D) {
2754  do {
2755    if (D->hasAttr<DeprecatedAttr>())
2756      return true;
2757  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
2758  return false;
2759}
2760
2761void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
2762                                         Decl *Ctx) {
2763  if (isDeclDeprecated(Ctx))
2764    return;
2765
2766  DD.Triggered = true;
2767  if (!DD.getDeprecationMessage().empty())
2768    Diag(DD.Loc, diag::warn_deprecated_message)
2769      << DD.getDeprecationDecl()->getDeclName()
2770      << DD.getDeprecationMessage();
2771  else
2772    Diag(DD.Loc, diag::warn_deprecated)
2773      << DD.getDeprecationDecl()->getDeclName();
2774}
2775
2776void Sema::EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
2777                                  SourceLocation Loc) {
2778  // Delay if we're currently parsing a declaration.
2779  if (ParsingDeclDepth) {
2780    DelayedDiagnostics.push_back(DelayedDiagnostic::makeDeprecation(Loc, D,
2781                                                                    Message));
2782    return;
2783  }
2784
2785  // Otherwise, don't warn if our current context is deprecated.
2786  if (isDeclDeprecated(cast<Decl>(CurContext)))
2787    return;
2788  if (!Message.empty())
2789    Diag(Loc, diag::warn_deprecated_message) << D->getDeclName()
2790                                             << Message;
2791  else
2792    Diag(Loc, diag::warn_deprecated) << D->getDeclName();
2793}
2794