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