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