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