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