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