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