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