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