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