]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp
Merge ^/head r316992 through r317215.
[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) {
2402     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2403     return;
2404   }
2405
2406   AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2407   AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2408   AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2409   bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2410   bool IsStrict = Attr.getStrictLoc().isValid();
2411   StringRef Str;
2412   if (const StringLiteral *SE =
2413           dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2414     Str = SE->getString();
2415   StringRef Replacement;
2416   if (const StringLiteral *SE =
2417           dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2418     Replacement = SE->getString();
2419
2420   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2421                                                       false/*Implicit*/,
2422                                                       Introduced.Version,
2423                                                       Deprecated.Version,
2424                                                       Obsoleted.Version,
2425                                                       IsUnavailable, Str,
2426                                                       IsStrict, Replacement,
2427                                                       Sema::AMK_None,
2428                                                       Index);
2429   if (NewAttr)
2430     D->addAttr(NewAttr);
2431
2432   // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2433   // matches before the start of the watchOS platform.
2434   if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2435     IdentifierInfo *NewII = nullptr;
2436     if (II->getName() == "ios")
2437       NewII = &S.Context.Idents.get("watchos");
2438     else if (II->getName() == "ios_app_extension")
2439       NewII = &S.Context.Idents.get("watchos_app_extension");
2440
2441     if (NewII) {
2442         auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2443           if (Version.empty())
2444             return Version;
2445           auto Major = Version.getMajor();
2446           auto NewMajor = Major >= 9 ? Major - 7 : 0;
2447           if (NewMajor >= 2) {
2448             if (Version.getMinor().hasValue()) {
2449               if (Version.getSubminor().hasValue())
2450                 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2451                                     Version.getSubminor().getValue());
2452               else
2453                 return VersionTuple(NewMajor, Version.getMinor().getValue());
2454             }
2455           }
2456
2457           return VersionTuple(2, 0);
2458         };
2459
2460         auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2461         auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2462         auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2463
2464         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2465                                                             Attr.getRange(),
2466                                                             NewII,
2467                                                             true/*Implicit*/,
2468                                                             NewIntroduced,
2469                                                             NewDeprecated,
2470                                                             NewObsoleted,
2471                                                             IsUnavailable, Str,
2472                                                             IsStrict,
2473                                                             Replacement,
2474                                                             Sema::AMK_None,
2475                                                             Index);
2476         if (NewAttr)
2477           D->addAttr(NewAttr);
2478       }
2479   } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2480     // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2481     // matches before the start of the tvOS platform.
2482     IdentifierInfo *NewII = nullptr;
2483     if (II->getName() == "ios")
2484       NewII = &S.Context.Idents.get("tvos");
2485     else if (II->getName() == "ios_app_extension")
2486       NewII = &S.Context.Idents.get("tvos_app_extension");
2487
2488     if (NewII) {
2489         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2490                                                             Attr.getRange(),
2491                                                             NewII,
2492                                                             true/*Implicit*/,
2493                                                             Introduced.Version,
2494                                                             Deprecated.Version,
2495                                                             Obsoleted.Version,
2496                                                             IsUnavailable, Str,
2497                                                             IsStrict,
2498                                                             Replacement,
2499                                                             Sema::AMK_None,
2500                                                             Index);
2501         if (NewAttr)
2502           D->addAttr(NewAttr);
2503       }
2504   }
2505 }
2506
2507 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2508                                            const AttributeList &Attr) {
2509   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2510     return;
2511   assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2512          "Invalid number of arguments in an external_source_symbol attribute");
2513
2514   if (!isa<NamedDecl>(D)) {
2515     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2516         << Attr.getName() << ExpectedNamedDecl;
2517     return;
2518   }
2519
2520   StringRef Language;
2521   if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2522     Language = SE->getString();
2523   StringRef DefinedIn;
2524   if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2525     DefinedIn = SE->getString();
2526   bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2527
2528   D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2529       Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2530       Attr.getAttributeSpellingListIndex()));
2531 }
2532
2533 template <class T>
2534 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2535                               typename T::VisibilityType value,
2536                               unsigned attrSpellingListIndex) {
2537   T *existingAttr = D->getAttr<T>();
2538   if (existingAttr) {
2539     typename T::VisibilityType existingValue = existingAttr->getVisibility();
2540     if (existingValue == value)
2541       return nullptr;
2542     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2543     S.Diag(range.getBegin(), diag::note_previous_attribute);
2544     D->dropAttr<T>();
2545   }
2546   return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2547 }
2548
2549 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2550                                           VisibilityAttr::VisibilityType Vis,
2551                                           unsigned AttrSpellingListIndex) {
2552   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2553                                                AttrSpellingListIndex);
2554 }
2555
2556 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2557                                       TypeVisibilityAttr::VisibilityType Vis,
2558                                       unsigned AttrSpellingListIndex) {
2559   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2560                                                    AttrSpellingListIndex);
2561 }
2562
2563 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2564                                  bool isTypeVisibility) {
2565   // Visibility attributes don't mean anything on a typedef.
2566   if (isa<TypedefNameDecl>(D)) {
2567     S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2568       << Attr.getName();
2569     return;
2570   }
2571
2572   // 'type_visibility' can only go on a type or namespace.
2573   if (isTypeVisibility &&
2574       !(isa<TagDecl>(D) ||
2575         isa<ObjCInterfaceDecl>(D) ||
2576         isa<NamespaceDecl>(D))) {
2577     S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2578       << Attr.getName() << ExpectedTypeOrNamespace;
2579     return;
2580   }
2581
2582   // Check that the argument is a string literal.
2583   StringRef TypeStr;
2584   SourceLocation LiteralLoc;
2585   if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2586     return;
2587
2588   VisibilityAttr::VisibilityType type;
2589   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2590     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2591       << Attr.getName() << TypeStr;
2592     return;
2593   }
2594   
2595   // Complain about attempts to use protected visibility on targets
2596   // (like Darwin) that don't support it.
2597   if (type == VisibilityAttr::Protected &&
2598       !S.Context.getTargetInfo().hasProtectedVisibility()) {
2599     S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2600     type = VisibilityAttr::Default;
2601   }
2602
2603   unsigned Index = Attr.getAttributeSpellingListIndex();
2604   clang::Attr *newAttr;
2605   if (isTypeVisibility) {
2606     newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2607                                     (TypeVisibilityAttr::VisibilityType) type,
2608                                         Index);
2609   } else {
2610     newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2611   }
2612   if (newAttr)
2613     D->addAttr(newAttr);
2614 }
2615
2616 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2617                                        const AttributeList &Attr) {
2618   ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2619   if (!Attr.isArgIdent(0)) {
2620     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2621       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2622     return;
2623   }
2624
2625   IdentifierLoc *IL = Attr.getArgAsIdent(0);
2626   ObjCMethodFamilyAttr::FamilyKind F;
2627   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2628     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2629       << IL->Ident;
2630     return;
2631   }
2632
2633   if (F == ObjCMethodFamilyAttr::OMF_init &&
2634       !method->getReturnType()->isObjCObjectPointerType()) {
2635     S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2636         << method->getReturnType();
2637     // Ignore the attribute.
2638     return;
2639   }
2640
2641   method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2642                                                        S.Context, F,
2643                                         Attr.getAttributeSpellingListIndex()));
2644 }
2645
2646 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2647   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2648     QualType T = TD->getUnderlyingType();
2649     if (!T->isCARCBridgableType()) {
2650       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2651       return;
2652     }
2653   }
2654   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2655     QualType T = PD->getType();
2656     if (!T->isCARCBridgableType()) {
2657       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2658       return;
2659     }
2660   }
2661   else {
2662     // It is okay to include this attribute on properties, e.g.:
2663     //
2664     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2665     //
2666     // In this case it follows tradition and suppresses an error in the above
2667     // case.    
2668     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2669   }
2670   D->addAttr(::new (S.Context)
2671              ObjCNSObjectAttr(Attr.getRange(), S.Context,
2672                               Attr.getAttributeSpellingListIndex()));
2673 }
2674
2675 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2676   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2677     QualType T = TD->getUnderlyingType();
2678     if (!T->isObjCObjectPointerType()) {
2679       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2680       return;
2681     }
2682   } else {
2683     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2684     return;
2685   }
2686   D->addAttr(::new (S.Context)
2687              ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2688                               Attr.getAttributeSpellingListIndex()));
2689 }
2690
2691 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2692   if (!Attr.isArgIdent(0)) {
2693     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2694       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2695     return;
2696   }
2697
2698   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2699   BlocksAttr::BlockType type;
2700   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2701     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2702       << Attr.getName() << II;
2703     return;
2704   }
2705
2706   D->addAttr(::new (S.Context)
2707              BlocksAttr(Attr.getRange(), S.Context, type,
2708                         Attr.getAttributeSpellingListIndex()));
2709 }
2710
2711 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2712   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2713   if (Attr.getNumArgs() > 0) {
2714     Expr *E = Attr.getArgAsExpr(0);
2715     llvm::APSInt Idx(32);
2716     if (E->isTypeDependent() || E->isValueDependent() ||
2717         !E->isIntegerConstantExpr(Idx, S.Context)) {
2718       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2719         << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2720         << E->getSourceRange();
2721       return;
2722     }
2723
2724     if (Idx.isSigned() && Idx.isNegative()) {
2725       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2726         << E->getSourceRange();
2727       return;
2728     }
2729
2730     sentinel = Idx.getZExtValue();
2731   }
2732
2733   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2734   if (Attr.getNumArgs() > 1) {
2735     Expr *E = Attr.getArgAsExpr(1);
2736     llvm::APSInt Idx(32);
2737     if (E->isTypeDependent() || E->isValueDependent() ||
2738         !E->isIntegerConstantExpr(Idx, S.Context)) {
2739       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2740         << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2741         << E->getSourceRange();
2742       return;
2743     }
2744     nullPos = Idx.getZExtValue();
2745
2746     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2747       // FIXME: This error message could be improved, it would be nice
2748       // to say what the bounds actually are.
2749       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2750         << E->getSourceRange();
2751       return;
2752     }
2753   }
2754
2755   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2756     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2757     if (isa<FunctionNoProtoType>(FT)) {
2758       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2759       return;
2760     }
2761
2762     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2763       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2764       return;
2765     }
2766   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2767     if (!MD->isVariadic()) {
2768       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2769       return;
2770     }
2771   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2772     if (!BD->isVariadic()) {
2773       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2774       return;
2775     }
2776   } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2777     QualType Ty = V->getType();
2778     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2779       const FunctionType *FT = Ty->isFunctionPointerType()
2780        ? D->getFunctionType()
2781        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2782       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2783         int m = Ty->isFunctionPointerType() ? 0 : 1;
2784         S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2785         return;
2786       }
2787     } else {
2788       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2789         << Attr.getName() << ExpectedFunctionMethodOrBlock;
2790       return;
2791     }
2792   } else {
2793     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2794       << Attr.getName() << ExpectedFunctionMethodOrBlock;
2795     return;
2796   }
2797   D->addAttr(::new (S.Context)
2798              SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2799                           Attr.getAttributeSpellingListIndex()));
2800 }
2801
2802 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2803   if (D->getFunctionType() &&
2804       D->getFunctionType()->getReturnType()->isVoidType()) {
2805     S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2806       << Attr.getName() << 0;
2807     return;
2808   }
2809   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2810     if (MD->getReturnType()->isVoidType()) {
2811       S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2812       << Attr.getName() << 1;
2813       return;
2814     }
2815   
2816   // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2817   // about using it as an extension.
2818   if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2819       !Attr.getScopeName())
2820     S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2821
2822   D->addAttr(::new (S.Context) 
2823              WarnUnusedResultAttr(Attr.getRange(), S.Context,
2824                                   Attr.getAttributeSpellingListIndex()));
2825 }
2826
2827 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2828   // weak_import only applies to variable & function declarations.
2829   bool isDef = false;
2830   if (!D->canBeWeakImported(isDef)) {
2831     if (isDef)
2832       S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2833         << "weak_import";
2834     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2835              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2836               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2837       // Nothing to warn about here.
2838     } else
2839       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2840         << Attr.getName() << ExpectedVariableOrFunction;
2841
2842     return;
2843   }
2844
2845   D->addAttr(::new (S.Context)
2846              WeakImportAttr(Attr.getRange(), S.Context,
2847                             Attr.getAttributeSpellingListIndex()));
2848 }
2849
2850 // Handles reqd_work_group_size and work_group_size_hint.
2851 template <typename WorkGroupAttr>
2852 static void handleWorkGroupSize(Sema &S, Decl *D,
2853                                 const AttributeList &Attr) {
2854   uint32_t WGSize[3];
2855   for (unsigned i = 0; i < 3; ++i) {
2856     const Expr *E = Attr.getArgAsExpr(i);
2857     if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2858       return;
2859     if (WGSize[i] == 0) {
2860       S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2861         << Attr.getName() << E->getSourceRange();
2862       return;
2863     }
2864   }
2865
2866   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2867   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2868                     Existing->getYDim() == WGSize[1] &&
2869                     Existing->getZDim() == WGSize[2]))
2870     S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2871
2872   D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2873                                              WGSize[0], WGSize[1], WGSize[2],
2874                                        Attr.getAttributeSpellingListIndex()));
2875 }
2876
2877 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2878   if (!Attr.hasParsedType()) {
2879     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2880       << Attr.getName() << 1;
2881     return;
2882   }
2883
2884   TypeSourceInfo *ParmTSI = nullptr;
2885   QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2886   assert(ParmTSI && "no type source info for attribute argument");
2887
2888   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2889       (ParmType->isBooleanType() ||
2890        !ParmType->isIntegralType(S.getASTContext()))) {
2891     S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2892         << ParmType;
2893     return;
2894   }
2895
2896   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2897     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2898       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2899       return;
2900     }
2901   }
2902
2903   D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2904                                                ParmTSI,
2905                                         Attr.getAttributeSpellingListIndex()));
2906 }
2907
2908 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2909                                     StringRef Name,
2910                                     unsigned AttrSpellingListIndex) {
2911   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2912     if (ExistingAttr->getName() == Name)
2913       return nullptr;
2914     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2915     Diag(Range.getBegin(), diag::note_previous_attribute);
2916     return nullptr;
2917   }
2918   return ::new (Context) SectionAttr(Range, Context, Name,
2919                                      AttrSpellingListIndex);
2920 }
2921
2922 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2923   std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2924   if (!Error.empty()) {
2925     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2926     return false;
2927   }
2928   return true;
2929 }
2930
2931 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2932   // Make sure that there is a string literal as the sections's single
2933   // argument.
2934   StringRef Str;
2935   SourceLocation LiteralLoc;
2936   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2937     return;
2938
2939   if (!S.checkSectionName(LiteralLoc, Str))
2940     return;
2941
2942   // If the target wants to validate the section specifier, make it happen.
2943   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2944   if (!Error.empty()) {
2945     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2946     << Error;
2947     return;
2948   }
2949
2950   unsigned Index = Attr.getAttributeSpellingListIndex();
2951   SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2952   if (NewAttr)
2953     D->addAttr(NewAttr);
2954 }
2955
2956 // Check for things we'd like to warn about, no errors or validation for now.
2957 // TODO: Validation should use a backend target library that specifies
2958 // the allowable subtarget features and cpus. We could use something like a
2959 // TargetCodeGenInfo hook here to do validation.
2960 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2961   for (auto Str : {"tune=", "fpmath="})
2962     if (AttrStr.find(Str) != StringRef::npos)
2963       Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2964 }
2965
2966 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2967   StringRef Str;
2968   SourceLocation LiteralLoc;
2969   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2970     return;
2971   S.checkTargetAttr(LiteralLoc, Str);
2972   unsigned Index = Attr.getAttributeSpellingListIndex();
2973   TargetAttr *NewAttr =
2974       ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2975   D->addAttr(NewAttr);
2976 }
2977
2978 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2979   VarDecl *VD = cast<VarDecl>(D);
2980   if (!VD->hasLocalStorage()) {
2981     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2982     return;
2983   }
2984
2985   Expr *E = Attr.getArgAsExpr(0);
2986   SourceLocation Loc = E->getExprLoc();
2987   FunctionDecl *FD = nullptr;
2988   DeclarationNameInfo NI;
2989
2990   // gcc only allows for simple identifiers. Since we support more than gcc, we
2991   // will warn the user.
2992   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2993     if (DRE->hasQualifier())
2994       S.Diag(Loc, diag::warn_cleanup_ext);
2995     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2996     NI = DRE->getNameInfo();
2997     if (!FD) {
2998       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2999         << NI.getName();
3000       return;
3001     }
3002   } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3003     if (ULE->hasExplicitTemplateArgs())
3004       S.Diag(Loc, diag::warn_cleanup_ext);
3005     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3006     NI = ULE->getNameInfo();
3007     if (!FD) {
3008       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3009         << NI.getName();
3010       if (ULE->getType() == S.Context.OverloadTy)
3011         S.NoteAllOverloadCandidates(ULE);
3012       return;
3013     }
3014   } else {
3015     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3016     return;
3017   }
3018
3019   if (FD->getNumParams() != 1) {
3020     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3021       << NI.getName();
3022     return;
3023   }
3024
3025   // We're currently more strict than GCC about what function types we accept.
3026   // If this ever proves to be a problem it should be easy to fix.
3027   QualType Ty = S.Context.getPointerType(VD->getType());
3028   QualType ParamTy = FD->getParamDecl(0)->getType();
3029   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3030                                    ParamTy, Ty) != Sema::Compatible) {
3031     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3032       << NI.getName() << ParamTy << Ty;
3033     return;
3034   }
3035
3036   D->addAttr(::new (S.Context)
3037              CleanupAttr(Attr.getRange(), S.Context, FD,
3038                          Attr.getAttributeSpellingListIndex()));
3039 }
3040
3041 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3042                                         const AttributeList &Attr) {
3043   if (!Attr.isArgIdent(0)) {
3044     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3045         << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3046     return;
3047   }
3048
3049   EnumExtensibilityAttr::Kind ExtensibilityKind;
3050   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3051   if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3052                                                ExtensibilityKind)) {
3053     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3054         << Attr.getName() << II;
3055     return;
3056   }
3057
3058   D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3059       Attr.getRange(), S.Context, ExtensibilityKind,
3060       Attr.getAttributeSpellingListIndex()));
3061 }
3062
3063 /// Handle __attribute__((format_arg((idx)))) attribute based on
3064 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3065 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3066   Expr *IdxExpr = Attr.getArgAsExpr(0);
3067   uint64_t Idx;
3068   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3069     return;
3070
3071   // Make sure the format string is really a string.
3072   QualType Ty = getFunctionOrMethodParamType(D, Idx);
3073
3074   bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3075   if (NotNSStringTy &&
3076       !isCFStringType(Ty, S.Context) &&
3077       (!Ty->isPointerType() ||
3078        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3079     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3080         << "a string type" << IdxExpr->getSourceRange()
3081         << getFunctionOrMethodParamRange(D, 0);
3082     return;
3083   }
3084   Ty = getFunctionOrMethodResultType(D);
3085   if (!isNSStringType(Ty, S.Context) &&
3086       !isCFStringType(Ty, S.Context) &&
3087       (!Ty->isPointerType() ||
3088        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3089     S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3090         << (NotNSStringTy ? "string type" : "NSString")
3091         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3092     return;
3093   }
3094
3095   // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3096   // because that has corrected for the implicit this parameter, and is zero-
3097   // based.  The attribute expects what the user wrote explicitly.
3098   llvm::APSInt Val;
3099   IdxExpr->EvaluateAsInt(Val, S.Context);
3100
3101   D->addAttr(::new (S.Context)
3102              FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3103                            Attr.getAttributeSpellingListIndex()));
3104 }
3105
3106 enum FormatAttrKind {
3107   CFStringFormat,
3108   NSStringFormat,
3109   StrftimeFormat,
3110   SupportedFormat,
3111   IgnoredFormat,
3112   InvalidFormat
3113 };
3114
3115 /// getFormatAttrKind - Map from format attribute names to supported format
3116 /// types.
3117 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3118   return llvm::StringSwitch<FormatAttrKind>(Format)
3119       // Check for formats that get handled specially.
3120       .Case("NSString", NSStringFormat)
3121       .Case("CFString", CFStringFormat)
3122       .Case("strftime", StrftimeFormat)
3123
3124       // Otherwise, check for supported formats.
3125       .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3126       .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3127       .Case("kprintf", SupportedFormat)         // OpenBSD.
3128       .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3129       .Case("os_trace", SupportedFormat)
3130       .Case("os_log", SupportedFormat)
3131
3132       .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3133       .Default(InvalidFormat);
3134 }
3135
3136 /// Handle __attribute__((init_priority(priority))) attributes based on
3137 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3138 static void handleInitPriorityAttr(Sema &S, Decl *D,
3139                                    const AttributeList &Attr) {
3140   if (!S.getLangOpts().CPlusPlus) {
3141     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3142     return;
3143   }
3144   
3145   if (S.getCurFunctionOrMethodDecl()) {
3146     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3147     Attr.setInvalid();
3148     return;
3149   }
3150   QualType T = cast<VarDecl>(D)->getType();
3151   if (S.Context.getAsArrayType(T))
3152     T = S.Context.getBaseElementType(T);
3153   if (!T->getAs<RecordType>()) {
3154     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3155     Attr.setInvalid();
3156     return;
3157   }
3158
3159   Expr *E = Attr.getArgAsExpr(0);
3160   uint32_t prioritynum;
3161   if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3162     Attr.setInvalid();
3163     return;
3164   }
3165
3166   if (prioritynum < 101 || prioritynum > 65535) {
3167     S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3168       << E->getSourceRange() << Attr.getName() << 101 << 65535;
3169     Attr.setInvalid();
3170     return;
3171   }
3172   D->addAttr(::new (S.Context)
3173              InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3174                               Attr.getAttributeSpellingListIndex()));
3175 }
3176
3177 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3178                                   IdentifierInfo *Format, int FormatIdx,
3179                                   int FirstArg,
3180                                   unsigned AttrSpellingListIndex) {
3181   // Check whether we already have an equivalent format attribute.
3182   for (auto *F : D->specific_attrs<FormatAttr>()) {
3183     if (F->getType() == Format &&
3184         F->getFormatIdx() == FormatIdx &&
3185         F->getFirstArg() == FirstArg) {
3186       // If we don't have a valid location for this attribute, adopt the
3187       // location.
3188       if (F->getLocation().isInvalid())
3189         F->setRange(Range);
3190       return nullptr;
3191     }
3192   }
3193
3194   return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3195                                     FirstArg, AttrSpellingListIndex);
3196 }
3197
3198 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3199 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3200 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3201   if (!Attr.isArgIdent(0)) {
3202     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3203       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3204     return;
3205   }
3206
3207   // In C++ the implicit 'this' function parameter also counts, and they are
3208   // counted from one.
3209   bool HasImplicitThisParam = isInstanceMethod(D);
3210   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3211
3212   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3213   StringRef Format = II->getName();
3214
3215   if (normalizeName(Format)) {
3216     // If we've modified the string name, we need a new identifier for it.
3217     II = &S.Context.Idents.get(Format);
3218   }
3219
3220   // Check for supported formats.
3221   FormatAttrKind Kind = getFormatAttrKind(Format);
3222   
3223   if (Kind == IgnoredFormat)
3224     return;
3225   
3226   if (Kind == InvalidFormat) {
3227     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3228       << Attr.getName() << II->getName();
3229     return;
3230   }
3231
3232   // checks for the 2nd argument
3233   Expr *IdxExpr = Attr.getArgAsExpr(1);
3234   uint32_t Idx;
3235   if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3236     return;
3237
3238   if (Idx < 1 || Idx > NumArgs) {
3239     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3240       << Attr.getName() << 2 << IdxExpr->getSourceRange();
3241     return;
3242   }
3243
3244   // FIXME: Do we need to bounds check?
3245   unsigned ArgIdx = Idx - 1;
3246
3247   if (HasImplicitThisParam) {
3248     if (ArgIdx == 0) {
3249       S.Diag(Attr.getLoc(),
3250              diag::err_format_attribute_implicit_this_format_string)
3251         << IdxExpr->getSourceRange();
3252       return;
3253     }
3254     ArgIdx--;
3255   }
3256
3257   // make sure the format string is really a string
3258   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3259
3260   if (Kind == CFStringFormat) {
3261     if (!isCFStringType(Ty, S.Context)) {
3262       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3263         << "a CFString" << IdxExpr->getSourceRange()
3264         << getFunctionOrMethodParamRange(D, ArgIdx);
3265       return;
3266     }
3267   } else if (Kind == NSStringFormat) {
3268     // FIXME: do we need to check if the type is NSString*?  What are the
3269     // semantics?
3270     if (!isNSStringType(Ty, S.Context)) {
3271       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3272         << "an NSString" << IdxExpr->getSourceRange()
3273         << getFunctionOrMethodParamRange(D, ArgIdx);
3274       return;
3275     }
3276   } else if (!Ty->isPointerType() ||
3277              !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3278     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3279       << "a string type" << IdxExpr->getSourceRange()
3280       << getFunctionOrMethodParamRange(D, ArgIdx);
3281     return;
3282   }
3283
3284   // check the 3rd argument
3285   Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3286   uint32_t FirstArg;
3287   if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3288     return;
3289
3290   // check if the function is variadic if the 3rd argument non-zero
3291   if (FirstArg != 0) {
3292     if (isFunctionOrMethodVariadic(D)) {
3293       ++NumArgs; // +1 for ...
3294     } else {
3295       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3296       return;
3297     }
3298   }
3299
3300   // strftime requires FirstArg to be 0 because it doesn't read from any
3301   // variable the input is just the current time + the format string.
3302   if (Kind == StrftimeFormat) {
3303     if (FirstArg != 0) {
3304       S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3305         << FirstArgExpr->getSourceRange();
3306       return;
3307     }
3308   // if 0 it disables parameter checking (to use with e.g. va_list)
3309   } else if (FirstArg != 0 && FirstArg != NumArgs) {
3310     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3311       << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3312     return;
3313   }
3314
3315   FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3316                                           Idx, FirstArg,
3317                                           Attr.getAttributeSpellingListIndex());
3318   if (NewAttr)
3319     D->addAttr(NewAttr);
3320 }
3321
3322 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3323                                        const AttributeList &Attr) {
3324   // Try to find the underlying union declaration.
3325   RecordDecl *RD = nullptr;
3326   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3327   if (TD && TD->getUnderlyingType()->isUnionType())
3328     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3329   else
3330     RD = dyn_cast<RecordDecl>(D);
3331
3332   if (!RD || !RD->isUnion()) {
3333     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3334       << Attr.getName() << ExpectedUnion;
3335     return;
3336   }
3337
3338   if (!RD->isCompleteDefinition()) {
3339     if (!RD->isBeingDefined())
3340       S.Diag(Attr.getLoc(),
3341              diag::warn_transparent_union_attribute_not_definition);
3342     return;
3343   }
3344
3345   RecordDecl::field_iterator Field = RD->field_begin(),
3346                           FieldEnd = RD->field_end();
3347   if (Field == FieldEnd) {
3348     S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3349     return;
3350   }
3351
3352   FieldDecl *FirstField = *Field;
3353   QualType FirstType = FirstField->getType();
3354   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3355     S.Diag(FirstField->getLocation(),
3356            diag::warn_transparent_union_attribute_floating)
3357       << FirstType->isVectorType() << FirstType;
3358     return;
3359   }
3360
3361   if (FirstType->isIncompleteType())
3362     return;
3363   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3364   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3365   for (; Field != FieldEnd; ++Field) {
3366     QualType FieldType = Field->getType();
3367     if (FieldType->isIncompleteType())
3368       return;
3369     // FIXME: this isn't fully correct; we also need to test whether the
3370     // members of the union would all have the same calling convention as the
3371     // first member of the union. Checking just the size and alignment isn't
3372     // sufficient (consider structs passed on the stack instead of in registers
3373     // as an example).
3374     if (S.Context.getTypeSize(FieldType) != FirstSize ||
3375         S.Context.getTypeAlign(FieldType) > FirstAlign) {
3376       // Warn if we drop the attribute.
3377       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3378       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3379                                  : S.Context.getTypeAlign(FieldType);
3380       S.Diag(Field->getLocation(),
3381           diag::warn_transparent_union_attribute_field_size_align)
3382         << isSize << Field->getDeclName() << FieldBits;
3383       unsigned FirstBits = isSize? FirstSize : FirstAlign;
3384       S.Diag(FirstField->getLocation(),
3385              diag::note_transparent_union_first_field_size_align)
3386         << isSize << FirstBits;
3387       return;
3388     }
3389   }
3390
3391   RD->addAttr(::new (S.Context)
3392               TransparentUnionAttr(Attr.getRange(), S.Context,
3393                                    Attr.getAttributeSpellingListIndex()));
3394 }
3395
3396 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3397   // Make sure that there is a string literal as the annotation's single
3398   // argument.
3399   StringRef Str;
3400   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3401     return;
3402
3403   // Don't duplicate annotations that are already set.
3404   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3405     if (I->getAnnotation() == Str)
3406       return;
3407   }
3408   
3409   D->addAttr(::new (S.Context)
3410              AnnotateAttr(Attr.getRange(), S.Context, Str,
3411                           Attr.getAttributeSpellingListIndex()));
3412 }
3413
3414 static void handleAlignValueAttr(Sema &S, Decl *D,
3415                                  const AttributeList &Attr) {
3416   S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3417                       Attr.getAttributeSpellingListIndex());
3418 }
3419
3420 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3421                              unsigned SpellingListIndex) {
3422   AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3423   SourceLocation AttrLoc = AttrRange.getBegin();
3424
3425   QualType T;
3426   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3427     T = TD->getUnderlyingType();
3428   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3429     T = VD->getType();
3430   else
3431     llvm_unreachable("Unknown decl type for align_value");
3432
3433   if (!T->isDependentType() && !T->isAnyPointerType() &&
3434       !T->isReferenceType() && !T->isMemberPointerType()) {
3435     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3436       << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3437     return;
3438   }
3439
3440   if (!E->isValueDependent()) {
3441     llvm::APSInt Alignment;
3442     ExprResult ICE
3443       = VerifyIntegerConstantExpression(E, &Alignment,
3444           diag::err_align_value_attribute_argument_not_int,
3445             /*AllowFold*/ false);
3446     if (ICE.isInvalid())
3447       return;
3448
3449     if (!Alignment.isPowerOf2()) {
3450       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3451         << E->getSourceRange();
3452       return;
3453     }
3454
3455     D->addAttr(::new (Context)
3456                AlignValueAttr(AttrRange, Context, ICE.get(),
3457                SpellingListIndex));
3458     return;
3459   }
3460
3461   // Save dependent expressions in the AST to be instantiated.
3462   D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3463 }
3464
3465 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3466   // check the attribute arguments.
3467   if (Attr.getNumArgs() > 1) {
3468     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3469       << Attr.getName() << 1;
3470     return;
3471   }
3472
3473   if (Attr.getNumArgs() == 0) {
3474     D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3475                true, nullptr, Attr.getAttributeSpellingListIndex()));
3476     return;
3477   }
3478
3479   Expr *E = Attr.getArgAsExpr(0);
3480   if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3481     S.Diag(Attr.getEllipsisLoc(),
3482            diag::err_pack_expansion_without_parameter_packs);
3483     return;
3484   }
3485
3486   if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3487     return;
3488
3489   if (E->isValueDependent()) {
3490     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3491       if (!TND->getUnderlyingType()->isDependentType()) {
3492         S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3493             << E->getSourceRange();
3494         return;
3495       }
3496     }
3497   }
3498
3499   S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3500                    Attr.isPackExpansion());
3501 }
3502
3503 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3504                           unsigned SpellingListIndex, bool IsPackExpansion) {
3505   AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3506   SourceLocation AttrLoc = AttrRange.getBegin();
3507
3508   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3509   if (TmpAttr.isAlignas()) {
3510     // C++11 [dcl.align]p1:
3511     //   An alignment-specifier may be applied to a variable or to a class
3512     //   data member, but it shall not be applied to a bit-field, a function
3513     //   parameter, the formal parameter of a catch clause, or a variable
3514     //   declared with the register storage class specifier. An
3515     //   alignment-specifier may also be applied to the declaration of a class
3516     //   or enumeration type.
3517     // C11 6.7.5/2:
3518     //   An alignment attribute shall not be specified in a declaration of
3519     //   a typedef, or a bit-field, or a function, or a parameter, or an
3520     //   object declared with the register storage-class specifier.
3521     int DiagKind = -1;
3522     if (isa<ParmVarDecl>(D)) {
3523       DiagKind = 0;
3524     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3525       if (VD->getStorageClass() == SC_Register)
3526         DiagKind = 1;
3527       if (VD->isExceptionVariable())
3528         DiagKind = 2;
3529     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3530       if (FD->isBitField())
3531         DiagKind = 3;
3532     } else if (!isa<TagDecl>(D)) {
3533       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3534         << (TmpAttr.isC11() ? ExpectedVariableOrField
3535                             : ExpectedVariableFieldOrTag);
3536       return;
3537     }
3538     if (DiagKind != -1) {
3539       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3540         << &TmpAttr << DiagKind;
3541       return;
3542     }
3543   }
3544
3545   if (E->isTypeDependent() || E->isValueDependent()) {
3546     // Save dependent expressions in the AST to be instantiated.
3547     AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3548     AA->setPackExpansion(IsPackExpansion);
3549     D->addAttr(AA);
3550     return;
3551   }
3552
3553   // FIXME: Cache the number on the Attr object?
3554   llvm::APSInt Alignment;
3555   ExprResult ICE
3556     = VerifyIntegerConstantExpression(E, &Alignment,
3557         diag::err_aligned_attribute_argument_not_int,
3558         /*AllowFold*/ false);
3559   if (ICE.isInvalid())
3560     return;
3561
3562   uint64_t AlignVal = Alignment.getZExtValue();
3563
3564   // C++11 [dcl.align]p2:
3565   //   -- if the constant expression evaluates to zero, the alignment
3566   //      specifier shall have no effect
3567   // C11 6.7.5p6:
3568   //   An alignment specification of zero has no effect.
3569   if (!(TmpAttr.isAlignas() && !Alignment)) {
3570     if (!llvm::isPowerOf2_64(AlignVal)) {
3571       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3572         << E->getSourceRange();
3573       return;
3574     }
3575   }
3576
3577   // Alignment calculations can wrap around if it's greater than 2**28.
3578   unsigned MaxValidAlignment =
3579       Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3580                                                               : 268435456;
3581   if (AlignVal > MaxValidAlignment) {
3582     Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3583                                                          << E->getSourceRange();
3584     return;
3585   }
3586
3587   if (Context.getTargetInfo().isTLSSupported()) {
3588     unsigned MaxTLSAlign =
3589         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3590             .getQuantity();
3591     auto *VD = dyn_cast<VarDecl>(D);
3592     if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3593         VD->getTLSKind() != VarDecl::TLS_None) {
3594       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3595           << (unsigned)AlignVal << VD << MaxTLSAlign;
3596       return;
3597     }
3598   }
3599
3600   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3601                                                 ICE.get(), SpellingListIndex);
3602   AA->setPackExpansion(IsPackExpansion);
3603   D->addAttr(AA);
3604 }
3605
3606 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3607                           unsigned SpellingListIndex, bool IsPackExpansion) {
3608   // FIXME: Cache the number on the Attr object if non-dependent?
3609   // FIXME: Perform checking of type validity
3610   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3611                                                 SpellingListIndex);
3612   AA->setPackExpansion(IsPackExpansion);
3613   D->addAttr(AA);
3614 }
3615
3616 void Sema::CheckAlignasUnderalignment(Decl *D) {
3617   assert(D->hasAttrs() && "no attributes on decl");
3618
3619   QualType UnderlyingTy, DiagTy;
3620   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3621     UnderlyingTy = DiagTy = VD->getType();
3622   } else {
3623     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3624     if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3625       UnderlyingTy = ED->getIntegerType();
3626   }
3627   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3628     return;
3629
3630   // C++11 [dcl.align]p5, C11 6.7.5/4:
3631   //   The combined effect of all alignment attributes in a declaration shall
3632   //   not specify an alignment that is less strict than the alignment that
3633   //   would otherwise be required for the entity being declared.
3634   AlignedAttr *AlignasAttr = nullptr;
3635   unsigned Align = 0;
3636   for (auto *I : D->specific_attrs<AlignedAttr>()) {
3637     if (I->isAlignmentDependent())
3638       return;
3639     if (I->isAlignas())
3640       AlignasAttr = I;
3641     Align = std::max(Align, I->getAlignment(Context));
3642   }
3643
3644   if (AlignasAttr && Align) {
3645     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3646     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3647     if (NaturalAlign > RequestedAlign)
3648       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3649         << DiagTy << (unsigned)NaturalAlign.getQuantity();
3650   }
3651 }
3652
3653 bool Sema::checkMSInheritanceAttrOnDefinition(
3654     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3655     MSInheritanceAttr::Spelling SemanticSpelling) {
3656   assert(RD->hasDefinition() && "RD has no definition!");
3657
3658   // We may not have seen base specifiers or any virtual methods yet.  We will
3659   // have to wait until the record is defined to catch any mismatches.
3660   if (!RD->getDefinition()->isCompleteDefinition())
3661     return false;
3662
3663   // The unspecified model never matches what a definition could need.
3664   if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3665     return false;
3666
3667   if (BestCase) {
3668     if (RD->calculateInheritanceModel() == SemanticSpelling)
3669       return false;
3670   } else {
3671     if (RD->calculateInheritanceModel() <= SemanticSpelling)
3672       return false;
3673   }
3674
3675   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3676       << 0 /*definition*/;
3677   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3678       << RD->getNameAsString();
3679   return true;
3680 }
3681
3682 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3683 /// attribute.
3684 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3685                              bool &IntegerMode, bool &ComplexMode) {
3686   IntegerMode = true;
3687   ComplexMode = false;
3688   switch (Str.size()) {
3689   case 2:
3690     switch (Str[0]) {
3691     case 'Q':
3692       DestWidth = 8;
3693       break;
3694     case 'H':
3695       DestWidth = 16;
3696       break;
3697     case 'S':
3698       DestWidth = 32;
3699       break;
3700     case 'D':
3701       DestWidth = 64;
3702       break;
3703     case 'X':
3704       DestWidth = 96;
3705       break;
3706     case 'T':
3707       DestWidth = 128;
3708       break;
3709     }
3710     if (Str[1] == 'F') {
3711       IntegerMode = false;
3712     } else if (Str[1] == 'C') {
3713       IntegerMode = false;
3714       ComplexMode = true;
3715     } else if (Str[1] != 'I') {
3716       DestWidth = 0;
3717     }
3718     break;
3719   case 4:
3720     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3721     // pointer on PIC16 and other embedded platforms.
3722     if (Str == "word")
3723       DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3724     else if (Str == "byte")
3725       DestWidth = S.Context.getTargetInfo().getCharWidth();
3726     break;
3727   case 7:
3728     if (Str == "pointer")
3729       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3730     break;
3731   case 11:
3732     if (Str == "unwind_word")
3733       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3734     break;
3735   }
3736 }
3737
3738 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3739 /// type.
3740 ///
3741 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3742 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3743 /// HImode, not an intermediate pointer.
3744 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3745   // This attribute isn't documented, but glibc uses it.  It changes
3746   // the width of an int or unsigned int to the specified size.
3747   if (!Attr.isArgIdent(0)) {
3748     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3749       << AANT_ArgumentIdentifier;
3750     return;
3751   }
3752
3753   IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3754
3755   S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3756 }
3757
3758 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3759                        unsigned SpellingListIndex, bool InInstantiation) {
3760   StringRef Str = Name->getName();
3761   normalizeName(Str);
3762   SourceLocation AttrLoc = AttrRange.getBegin();
3763
3764   unsigned DestWidth = 0;
3765   bool IntegerMode = true;
3766   bool ComplexMode = false;
3767   llvm::APInt VectorSize(64, 0);
3768   if (Str.size() >= 4 && Str[0] == 'V') {
3769     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3770     size_t StrSize = Str.size();
3771     size_t VectorStringLength = 0;
3772     while ((VectorStringLength + 1) < StrSize &&
3773            isdigit(Str[VectorStringLength + 1]))
3774       ++VectorStringLength;
3775     if (VectorStringLength &&
3776         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3777         VectorSize.isPowerOf2()) {
3778       parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3779                        IntegerMode, ComplexMode);
3780       // Avoid duplicate warning from template instantiation.
3781       if (!InInstantiation)
3782         Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3783     } else {
3784       VectorSize = 0;
3785     }
3786   }
3787
3788   if (!VectorSize)
3789     parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3790
3791   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3792   // and friends, at least with glibc.
3793   // FIXME: Make sure floating-point mappings are accurate
3794   // FIXME: Support XF and TF types
3795   if (!DestWidth) {
3796     Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3797     return;
3798   }
3799
3800   QualType OldTy;
3801   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3802     OldTy = TD->getUnderlyingType();
3803   else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3804     // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3805     // Try to get type from enum declaration, default to int.
3806     OldTy = ED->getIntegerType();
3807     if (OldTy.isNull())
3808       OldTy = Context.IntTy;
3809   } else
3810     OldTy = cast<ValueDecl>(D)->getType();
3811
3812   if (OldTy->isDependentType()) {
3813     D->addAttr(::new (Context)
3814                ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3815     return;
3816   }
3817
3818   // Base type can also be a vector type (see PR17453).
3819   // Distinguish between base type and base element type.
3820   QualType OldElemTy = OldTy;
3821   if (const VectorType *VT = OldTy->getAs<VectorType>())
3822     OldElemTy = VT->getElementType();
3823
3824   // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3825   // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3826   // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3827   if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3828       VectorSize.getBoolValue()) {
3829     Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3830     return;
3831   }
3832   bool IntegralOrAnyEnumType =
3833       OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3834
3835   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3836       !IntegralOrAnyEnumType)
3837     Diag(AttrLoc, diag::err_mode_not_primitive);
3838   else if (IntegerMode) {
3839     if (!IntegralOrAnyEnumType)
3840       Diag(AttrLoc, diag::err_mode_wrong_type);
3841   } else if (ComplexMode) {
3842     if (!OldElemTy->isComplexType())
3843       Diag(AttrLoc, diag::err_mode_wrong_type);
3844   } else {
3845     if (!OldElemTy->isFloatingType())
3846       Diag(AttrLoc, diag::err_mode_wrong_type);
3847   }
3848
3849   QualType NewElemTy;
3850
3851   if (IntegerMode)
3852     NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3853                                               OldElemTy->isSignedIntegerType());
3854   else
3855     NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3856
3857   if (NewElemTy.isNull()) {
3858     Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3859     return;
3860   }
3861
3862   if (ComplexMode) {
3863     NewElemTy = Context.getComplexType(NewElemTy);
3864   }
3865
3866   QualType NewTy = NewElemTy;
3867   if (VectorSize.getBoolValue()) {
3868     NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3869                                   VectorType::GenericVector);
3870   } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3871     // Complex machine mode does not support base vector types.
3872     if (ComplexMode) {
3873       Diag(AttrLoc, diag::err_complex_mode_vector_type);
3874       return;
3875     }
3876     unsigned NumElements = Context.getTypeSize(OldElemTy) *
3877                            OldVT->getNumElements() /
3878                            Context.getTypeSize(NewElemTy);
3879     NewTy =
3880         Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3881   }
3882
3883   if (NewTy.isNull()) {
3884     Diag(AttrLoc, diag::err_mode_wrong_type);
3885     return;
3886   }
3887
3888   // Install the new type.
3889   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3890     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3891   else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3892     ED->setIntegerType(NewTy);
3893   else
3894     cast<ValueDecl>(D)->setType(NewTy);
3895
3896   D->addAttr(::new (Context)
3897              ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3898 }
3899
3900 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3901   D->addAttr(::new (S.Context)
3902              NoDebugAttr(Attr.getRange(), S.Context,
3903                          Attr.getAttributeSpellingListIndex()));
3904 }
3905
3906 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3907                                               IdentifierInfo *Ident,
3908                                               unsigned AttrSpellingListIndex) {
3909   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3910     Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3911     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3912     return nullptr;
3913   }
3914
3915   if (D->hasAttr<AlwaysInlineAttr>())
3916     return nullptr;
3917
3918   return ::new (Context) AlwaysInlineAttr(Range, Context,
3919                                           AttrSpellingListIndex);
3920 }
3921
3922 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3923                                   IdentifierInfo *Ident,
3924                                   unsigned AttrSpellingListIndex) {
3925   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3926     return nullptr;
3927
3928   return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3929 }
3930
3931 InternalLinkageAttr *
3932 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3933                                IdentifierInfo *Ident,
3934                                unsigned AttrSpellingListIndex) {
3935   if (auto VD = dyn_cast<VarDecl>(D)) {
3936     // Attribute applies to Var but not any subclass of it (like ParmVar,
3937     // ImplicitParm or VarTemplateSpecialization).
3938     if (VD->getKind() != Decl::Var) {
3939       Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3940           << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3941                                                : ExpectedVariableOrFunction);
3942       return nullptr;
3943     }
3944     // Attribute does not apply to non-static local variables.
3945     if (VD->hasLocalStorage()) {
3946       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3947       return nullptr;
3948     }
3949   }
3950
3951   if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3952     return nullptr;
3953
3954   return ::new (Context)
3955       InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3956 }
3957
3958 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3959                                     unsigned AttrSpellingListIndex) {
3960   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3961     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3962     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3963     return nullptr;
3964   }
3965
3966   if (D->hasAttr<MinSizeAttr>())
3967     return nullptr;
3968
3969   return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3970 }
3971
3972 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3973                                               unsigned AttrSpellingListIndex) {
3974   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3975     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3976     Diag(Range.getBegin(), diag::note_conflicting_attribute);
3977     D->dropAttr<AlwaysInlineAttr>();
3978   }
3979   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3980     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3981     Diag(Range.getBegin(), diag::note_conflicting_attribute);
3982     D->dropAttr<MinSizeAttr>();
3983   }
3984
3985   if (D->hasAttr<OptimizeNoneAttr>())
3986     return nullptr;
3987
3988   return ::new (Context) OptimizeNoneAttr(Range, Context,
3989                                           AttrSpellingListIndex);
3990 }
3991
3992 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3993                                    const AttributeList &Attr) {
3994   if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3995                                                   Attr.getName()))
3996     return;
3997
3998   if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3999           D, Attr.getRange(), Attr.getName(),
4000           Attr.getAttributeSpellingListIndex()))
4001     D->addAttr(Inline);
4002 }
4003
4004 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4005   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4006           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4007     D->addAttr(MinSize);
4008 }
4009
4010 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4011                                    const AttributeList &Attr) {
4012   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4013           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4014     D->addAttr(Optnone);
4015 }
4016
4017 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4018   if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4019                                                Attr.getName()))
4020     return;
4021   auto *VD = cast<VarDecl>(D);
4022   if (!VD->hasGlobalStorage()) {
4023     S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4024     return;
4025   }
4026   D->addAttr(::new (S.Context) CUDAConstantAttr(
4027       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4028 }
4029
4030 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4031   if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4032                                                  Attr.getName()))
4033     return;
4034   auto *VD = cast<VarDecl>(D);
4035   // extern __shared__ is only allowed on arrays with no length (e.g.
4036   // "int x[]").
4037   if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
4038     S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4039     return;
4040   }
4041   if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4042       S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4043           << S.CurrentCUDATarget())
4044     return;
4045   D->addAttr(::new (S.Context) CUDASharedAttr(
4046       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4047 }
4048
4049 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4050   if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4051                                                Attr.getName()) ||
4052       checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4053                                              Attr.getName())) {
4054     return;
4055   }
4056   FunctionDecl *FD = cast<FunctionDecl>(D);
4057   if (!FD->getReturnType()->isVoidType()) {
4058     SourceRange RTRange = FD->getReturnTypeSourceRange();
4059     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4060         << FD->getType()
4061         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4062                               : FixItHint());
4063     return;
4064   }
4065   if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4066     if (Method->isInstance()) {
4067       S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4068           << Method;
4069       return;
4070     }
4071     S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4072   }
4073   // Only warn for "inline" when compiling for host, to cut down on noise.
4074   if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4075     S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4076
4077   D->addAttr(::new (S.Context)
4078               CUDAGlobalAttr(Attr.getRange(), S.Context,
4079                              Attr.getAttributeSpellingListIndex()));
4080 }
4081
4082 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4083   FunctionDecl *Fn = cast<FunctionDecl>(D);
4084   if (!Fn->isInlineSpecified()) {
4085     S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4086     return;
4087   }
4088
4089   D->addAttr(::new (S.Context)
4090              GNUInlineAttr(Attr.getRange(), S.Context,
4091                            Attr.getAttributeSpellingListIndex()));
4092 }
4093
4094 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4095   if (hasDeclarator(D)) return;
4096
4097   // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4098   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4099   CallingConv CC;
4100   if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4101     return;
4102
4103   if (!isa<ObjCMethodDecl>(D)) {
4104     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4105       << Attr.getName() << ExpectedFunctionOrMethod;
4106     return;
4107   }
4108
4109   switch (Attr.getKind()) {
4110   case AttributeList::AT_FastCall:
4111     D->addAttr(::new (S.Context)
4112                FastCallAttr(Attr.getRange(), S.Context,
4113                             Attr.getAttributeSpellingListIndex()));
4114     return;
4115   case AttributeList::AT_StdCall:
4116     D->addAttr(::new (S.Context)
4117                StdCallAttr(Attr.getRange(), S.Context,
4118                            Attr.getAttributeSpellingListIndex()));
4119     return;
4120   case AttributeList::AT_ThisCall:
4121     D->addAttr(::new (S.Context)
4122                ThisCallAttr(Attr.getRange(), S.Context,
4123                             Attr.getAttributeSpellingListIndex()));
4124     return;
4125   case AttributeList::AT_CDecl:
4126     D->addAttr(::new (S.Context)
4127                CDeclAttr(Attr.getRange(), S.Context,
4128                          Attr.getAttributeSpellingListIndex()));
4129     return;
4130   case AttributeList::AT_Pascal:
4131     D->addAttr(::new (S.Context)
4132                PascalAttr(Attr.getRange(), S.Context,
4133                           Attr.getAttributeSpellingListIndex()));
4134     return;
4135   case AttributeList::AT_SwiftCall:
4136     D->addAttr(::new (S.Context)
4137                SwiftCallAttr(Attr.getRange(), S.Context,
4138                              Attr.getAttributeSpellingListIndex()));
4139     return;
4140   case AttributeList::AT_VectorCall:
4141     D->addAttr(::new (S.Context)
4142                VectorCallAttr(Attr.getRange(), S.Context,
4143                               Attr.getAttributeSpellingListIndex()));
4144     return;
4145   case AttributeList::AT_MSABI:
4146     D->addAttr(::new (S.Context)
4147                MSABIAttr(Attr.getRange(), S.Context,
4148                          Attr.getAttributeSpellingListIndex()));
4149     return;
4150   case AttributeList::AT_SysVABI:
4151     D->addAttr(::new (S.Context)
4152                SysVABIAttr(Attr.getRange(), S.Context,
4153                            Attr.getAttributeSpellingListIndex()));
4154     return;
4155   case AttributeList::AT_RegCall:
4156     D->addAttr(::new (S.Context) RegCallAttr(
4157         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4158     return;
4159   case AttributeList::AT_Pcs: {
4160     PcsAttr::PCSType PCS;
4161     switch (CC) {
4162     case CC_AAPCS:
4163       PCS = PcsAttr::AAPCS;
4164       break;
4165     case CC_AAPCS_VFP:
4166       PCS = PcsAttr::AAPCS_VFP;
4167       break;
4168     default:
4169       llvm_unreachable("unexpected calling convention in pcs attribute");
4170     }
4171
4172     D->addAttr(::new (S.Context)
4173                PcsAttr(Attr.getRange(), S.Context, PCS,
4174                        Attr.getAttributeSpellingListIndex()));
4175     return;
4176   }
4177   case AttributeList::AT_IntelOclBicc:
4178     D->addAttr(::new (S.Context)
4179                IntelOclBiccAttr(Attr.getRange(), S.Context,
4180                                 Attr.getAttributeSpellingListIndex()));
4181     return;
4182   case AttributeList::AT_PreserveMost:
4183     D->addAttr(::new (S.Context) PreserveMostAttr(
4184         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4185     return;
4186   case AttributeList::AT_PreserveAll:
4187     D->addAttr(::new (S.Context) PreserveAllAttr(
4188         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4189     return;
4190   default:
4191     llvm_unreachable("unexpected attribute kind");
4192   }
4193 }
4194
4195 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4196   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4197     return;
4198
4199   std::vector<StringRef> DiagnosticIdentifiers;
4200   for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4201     StringRef RuleName;
4202
4203     if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4204       return;
4205
4206     // FIXME: Warn if the rule name is unknown. This is tricky because only
4207     // clang-tidy knows about available rules.
4208     DiagnosticIdentifiers.push_back(RuleName);
4209   }
4210   D->addAttr(::new (S.Context) SuppressAttr(
4211       Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4212       DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4213 }
4214
4215 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 
4216                                 const FunctionDecl *FD) {
4217   if (attr.isInvalid())
4218     return true;
4219
4220   if (attr.hasProcessingCache()) {
4221     CC = (CallingConv) attr.getProcessingCache();
4222     return false;
4223   }
4224
4225   unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4226   if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
4227     attr.setInvalid();
4228     return true;
4229   }
4230
4231   // TODO: diagnose uses of these conventions on the wrong target.
4232   switch (attr.getKind()) {
4233   case AttributeList::AT_CDecl: CC = CC_C; break;
4234   case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4235   case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4236   case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4237   case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4238   case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4239   case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4240   case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4241   case AttributeList::AT_MSABI:
4242     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4243                                                              CC_X86_64Win64;
4244     break;
4245   case AttributeList::AT_SysVABI:
4246     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4247                                                              CC_C;
4248     break;
4249   case AttributeList::AT_Pcs: {
4250     StringRef StrRef;
4251     if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4252       attr.setInvalid();
4253       return true;
4254     }
4255     if (StrRef == "aapcs") {
4256       CC = CC_AAPCS;
4257       break;
4258     } else if (StrRef == "aapcs-vfp") {
4259       CC = CC_AAPCS_VFP;
4260       break;
4261     }
4262
4263     attr.setInvalid();
4264     Diag(attr.getLoc(), diag::err_invalid_pcs);
4265     return true;
4266   }
4267   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4268   case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4269   case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4270   default: llvm_unreachable("unexpected attribute kind");
4271   }
4272
4273   const TargetInfo &TI = Context.getTargetInfo();
4274   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4275   if (A != TargetInfo::CCCR_OK) {
4276     if (A == TargetInfo::CCCR_Warning)
4277       Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4278
4279     // This convention is not valid for the target. Use the default function or
4280     // method calling convention.
4281     bool IsCXXMethod = false, IsVariadic = false;
4282     if (FD) {
4283       IsCXXMethod = FD->isCXXInstanceMember();
4284       IsVariadic = FD->isVariadic();
4285     }
4286     CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4287   }
4288
4289   attr.setProcessingCache((unsigned) CC);
4290   return false;
4291 }
4292
4293 /// Pointer-like types in the default address space.
4294 static bool isValidSwiftContextType(QualType type) {
4295   if (!type->hasPointerRepresentation())
4296     return type->isDependentType();
4297   return type->getPointeeType().getAddressSpace() == 0;
4298 }
4299
4300 /// Pointers and references in the default address space.
4301 static bool isValidSwiftIndirectResultType(QualType type) {
4302   if (auto ptrType = type->getAs<PointerType>()) {
4303     type = ptrType->getPointeeType();
4304   } else if (auto refType = type->getAs<ReferenceType>()) {
4305     type = refType->getPointeeType();
4306   } else {
4307     return type->isDependentType();
4308   }
4309   return type.getAddressSpace() == 0;
4310 }
4311
4312 /// Pointers and references to pointers in the default address space.
4313 static bool isValidSwiftErrorResultType(QualType type) {
4314   if (auto ptrType = type->getAs<PointerType>()) {
4315     type = ptrType->getPointeeType();
4316   } else if (auto refType = type->getAs<ReferenceType>()) {
4317     type = refType->getPointeeType();
4318   } else {
4319     return type->isDependentType();
4320   }
4321   if (!type.getQualifiers().empty())
4322     return false;
4323   return isValidSwiftContextType(type);
4324 }
4325
4326 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4327                                    ParameterABI abi) {
4328   S.AddParameterABIAttr(attr.getRange(), D, abi,
4329                         attr.getAttributeSpellingListIndex());
4330 }
4331
4332 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4333                                unsigned spellingIndex) {
4334
4335   QualType type = cast<ParmVarDecl>(D)->getType();
4336
4337   if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4338     if (existingAttr->getABI() != abi) {
4339       Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4340         << getParameterABISpelling(abi) << existingAttr;
4341       Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4342       return;
4343     }
4344   }
4345
4346   switch (abi) {
4347   case ParameterABI::Ordinary:
4348     llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4349
4350   case ParameterABI::SwiftContext:
4351     if (!isValidSwiftContextType(type)) {
4352       Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4353         << getParameterABISpelling(abi)
4354         << /*pointer to pointer */ 0 << type;
4355     }
4356     D->addAttr(::new (Context)
4357                SwiftContextAttr(range, Context, spellingIndex));
4358     return;
4359
4360   case ParameterABI::SwiftErrorResult:
4361     if (!isValidSwiftErrorResultType(type)) {
4362       Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4363         << getParameterABISpelling(abi)
4364         << /*pointer to pointer */ 1 << type;
4365     }
4366     D->addAttr(::new (Context)
4367                SwiftErrorResultAttr(range, Context, spellingIndex));
4368     return;
4369
4370   case ParameterABI::SwiftIndirectResult:
4371     if (!isValidSwiftIndirectResultType(type)) {
4372       Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4373         << getParameterABISpelling(abi)
4374         << /*pointer*/ 0 << type;
4375     }
4376     D->addAttr(::new (Context)
4377                SwiftIndirectResultAttr(range, Context, spellingIndex));
4378     return;
4379   }
4380   llvm_unreachable("bad parameter ABI attribute");
4381 }
4382
4383 /// Checks a regparm attribute, returning true if it is ill-formed and
4384 /// otherwise setting numParams to the appropriate value.
4385 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4386   if (Attr.isInvalid())
4387     return true;
4388
4389   if (!checkAttributeNumArgs(*this, Attr, 1)) {
4390     Attr.setInvalid();
4391     return true;
4392   }
4393
4394   uint32_t NP;
4395   Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4396   if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4397     Attr.setInvalid();
4398     return true;
4399   }
4400
4401   if (Context.getTargetInfo().getRegParmMax() == 0) {
4402     Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4403       << NumParamsExpr->getSourceRange();
4404     Attr.setInvalid();
4405     return true;
4406   }
4407
4408   numParams = NP;
4409   if (numParams > Context.getTargetInfo().getRegParmMax()) {
4410     Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4411       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4412     Attr.setInvalid();
4413     return true;
4414   }
4415
4416   return false;
4417 }
4418
4419 // Checks whether an argument of launch_bounds attribute is
4420 // acceptable, performs implicit conversion to Rvalue, and returns
4421 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4422 // and may output an error.
4423 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4424                                      const CUDALaunchBoundsAttr &Attr,
4425                                      const unsigned Idx) {
4426   if (S.DiagnoseUnexpandedParameterPack(E))
4427     return nullptr;
4428
4429   // Accept template arguments for now as they depend on something else.
4430   // We'll get to check them when they eventually get instantiated.
4431   if (E->isValueDependent())
4432     return E;
4433
4434   llvm::APSInt I(64);
4435   if (!E->isIntegerConstantExpr(I, S.Context)) {
4436     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4437         << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4438     return nullptr;
4439   }
4440   // Make sure we can fit it in 32 bits.
4441   if (!I.isIntN(32)) {
4442     S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4443                                                      << 32 << /* Unsigned */ 1;
4444     return nullptr;
4445   }
4446   if (I < 0)
4447     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4448         << &Attr << Idx << E->getSourceRange();
4449
4450   // We may need to perform implicit conversion of the argument.
4451   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4452       S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4453   ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4454   assert(!ValArg.isInvalid() &&
4455          "Unexpected PerformCopyInitialization() failure.");
4456
4457   return ValArg.getAs<Expr>();
4458 }
4459
4460 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4461                                Expr *MinBlocks, unsigned SpellingListIndex) {
4462   CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4463                                SpellingListIndex);
4464   MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4465   if (MaxThreads == nullptr)
4466     return;
4467
4468   if (MinBlocks) {
4469     MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4470     if (MinBlocks == nullptr)
4471       return;
4472   }
4473
4474   D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4475       AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4476 }
4477
4478 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4479                                    const AttributeList &Attr) {
4480   if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4481       !checkAttributeAtMostNumArgs(S, Attr, 2))
4482     return;
4483
4484   S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4485                         Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4486                         Attr.getAttributeSpellingListIndex());
4487 }
4488
4489 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4490                                           const AttributeList &Attr) {
4491   if (!Attr.isArgIdent(0)) {
4492     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4493       << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4494     return;
4495   }
4496   
4497   if (!checkAttributeNumArgs(S, Attr, 3))
4498     return;
4499
4500   IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4501
4502   if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4503     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4504       << Attr.getName() << ExpectedFunctionOrMethod;
4505     return;
4506   }
4507
4508   uint64_t ArgumentIdx;
4509   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4510                                            ArgumentIdx))
4511     return;
4512
4513   uint64_t TypeTagIdx;
4514   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4515                                            TypeTagIdx))
4516     return;
4517
4518   bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4519   if (IsPointer) {
4520     // Ensure that buffer has a pointer type.
4521     QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4522     if (!BufferTy->isPointerType()) {
4523       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4524         << Attr.getName() << 0;
4525     }
4526   }
4527
4528   D->addAttr(::new (S.Context)
4529              ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4530                                      ArgumentIdx, TypeTagIdx, IsPointer,
4531                                      Attr.getAttributeSpellingListIndex()));
4532 }
4533
4534 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4535                                          const AttributeList &Attr) {
4536   if (!Attr.isArgIdent(0)) {
4537     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4538       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4539     return;
4540   }
4541   
4542   if (!checkAttributeNumArgs(S, Attr, 1))
4543     return;
4544
4545   if (!isa<VarDecl>(D)) {
4546     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4547       << Attr.getName() << ExpectedVariable;
4548     return;
4549   }
4550
4551   IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4552   TypeSourceInfo *MatchingCTypeLoc = nullptr;
4553   S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4554   assert(MatchingCTypeLoc && "no type source info for attribute argument");
4555
4556   D->addAttr(::new (S.Context)
4557              TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4558                                     MatchingCTypeLoc,
4559                                     Attr.getLayoutCompatible(),
4560                                     Attr.getMustBeNull(),
4561                                     Attr.getAttributeSpellingListIndex()));
4562 }
4563
4564 static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4565                                   const AttributeList &Attr) {
4566   uint64_t ArgCount;
4567   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4568                                            ArgCount))
4569     return;
4570
4571   // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4572   D->addAttr(::new (S.Context)
4573              XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4574              Attr.getAttributeSpellingListIndex()));
4575 }
4576
4577 //===----------------------------------------------------------------------===//
4578 // Checker-specific attribute handlers.
4579 //===----------------------------------------------------------------------===//
4580
4581 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4582   return type->isDependentType() ||
4583          type->isObjCRetainableType();
4584 }
4585
4586 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4587   return type->isDependentType() || 
4588          type->isObjCObjectPointerType() || 
4589          S.Context.isObjCNSObjectType(type);
4590 }
4591
4592 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4593   return type->isDependentType() || 
4594          type->isPointerType() || 
4595          isValidSubjectOfNSAttribute(S, type);
4596 }
4597
4598 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4599   S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4600                       Attr.getKind() == AttributeList::AT_NSConsumed,
4601                       /*template instantiation*/ false);
4602 }
4603
4604 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4605                              unsigned spellingIndex, bool isNSConsumed,
4606                              bool isTemplateInstantiation) {
4607   ParmVarDecl *param = cast<ParmVarDecl>(D);
4608   bool typeOK;
4609
4610   if (isNSConsumed) {
4611     typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4612   } else {
4613     typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4614   }
4615
4616   if (!typeOK) {
4617     // These attributes are normally just advisory, but in ARC, ns_consumed
4618     // is significant.  Allow non-dependent code to contain inappropriate
4619     // attributes even in ARC, but require template instantiations to be
4620     // set up correctly.
4621     Diag(D->getLocStart(),
4622          (isTemplateInstantiation && isNSConsumed &&
4623             getLangOpts().ObjCAutoRefCount
4624           ? diag::err_ns_attribute_wrong_parameter_type
4625           : diag::warn_ns_attribute_wrong_parameter_type))
4626       << attrRange
4627       << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4628       << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4629     return;
4630   }
4631
4632   if (isNSConsumed)
4633     param->addAttr(::new (Context)
4634                    NSConsumedAttr(attrRange, Context, spellingIndex));
4635   else
4636     param->addAttr(::new (Context)
4637                    CFConsumedAttr(attrRange, Context, spellingIndex));
4638 }
4639
4640 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4641                                         const AttributeList &Attr) {
4642   QualType returnType;
4643
4644   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4645     returnType = MD->getReturnType();
4646   else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4647            (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4648     return; // ignore: was handled as a type attribute
4649   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4650     returnType = PD->getType();
4651   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4652     returnType = FD->getReturnType();
4653   else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4654     returnType = Param->getType()->getPointeeType();
4655     if (returnType.isNull()) {
4656       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4657           << Attr.getName() << /*pointer-to-CF*/2
4658           << Attr.getRange();
4659       return;
4660     }
4661   } else {
4662     AttributeDeclKind ExpectedDeclKind;
4663     switch (Attr.getKind()) {
4664     default: llvm_unreachable("invalid ownership attribute");
4665     case AttributeList::AT_NSReturnsRetained:
4666     case AttributeList::AT_NSReturnsAutoreleased:
4667     case AttributeList::AT_NSReturnsNotRetained:
4668       ExpectedDeclKind = ExpectedFunctionOrMethod;
4669       break;
4670
4671     case AttributeList::AT_CFReturnsRetained:
4672     case AttributeList::AT_CFReturnsNotRetained:
4673       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4674       break;
4675     }
4676     S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4677         << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4678     return;
4679   }
4680
4681   bool typeOK;
4682   bool cf;
4683   switch (Attr.getKind()) {
4684   default: llvm_unreachable("invalid ownership attribute");
4685   case AttributeList::AT_NSReturnsRetained:
4686     typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4687     cf = false;
4688     break;
4689       
4690   case AttributeList::AT_NSReturnsAutoreleased:
4691   case AttributeList::AT_NSReturnsNotRetained:
4692     typeOK = isValidSubjectOfNSAttribute(S, returnType);
4693     cf = false;
4694     break;
4695
4696   case AttributeList::AT_CFReturnsRetained:
4697   case AttributeList::AT_CFReturnsNotRetained:
4698     typeOK = isValidSubjectOfCFAttribute(S, returnType);
4699     cf = true;
4700     break;
4701   }
4702
4703   if (!typeOK) {
4704     if (isa<ParmVarDecl>(D)) {
4705       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4706           << Attr.getName() << /*pointer-to-CF*/2
4707           << Attr.getRange();
4708     } else {
4709       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4710       enum : unsigned {
4711         Function,
4712         Method,
4713         Property
4714       } SubjectKind = Function;
4715       if (isa<ObjCMethodDecl>(D))
4716         SubjectKind = Method;
4717       else if (isa<ObjCPropertyDecl>(D))
4718         SubjectKind = Property;
4719       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4720           << Attr.getName() << SubjectKind << cf
4721           << Attr.getRange();
4722     }
4723     return;
4724   }
4725
4726   switch (Attr.getKind()) {
4727     default:
4728       llvm_unreachable("invalid ownership attribute");
4729     case AttributeList::AT_NSReturnsAutoreleased:
4730       D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4731           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4732       return;
4733     case AttributeList::AT_CFReturnsNotRetained:
4734       D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4735           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4736       return;
4737     case AttributeList::AT_NSReturnsNotRetained:
4738       D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4739           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4740       return;
4741     case AttributeList::AT_CFReturnsRetained:
4742       D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4743           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4744       return;
4745     case AttributeList::AT_NSReturnsRetained:
4746       D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4747           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4748       return;
4749   };
4750 }
4751
4752 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4753                                               const AttributeList &attr) {
4754   const int EP_ObjCMethod = 1;
4755   const int EP_ObjCProperty = 2;
4756   
4757   SourceLocation loc = attr.getLoc();
4758   QualType resultType;
4759   if (isa<ObjCMethodDecl>(D))
4760     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4761   else
4762     resultType = cast<ObjCPropertyDecl>(D)->getType();
4763
4764   if (!resultType->isReferenceType() &&
4765       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4766     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4767       << SourceRange(loc)
4768     << attr.getName()
4769     << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4770     << /*non-retainable pointer*/ 2;
4771
4772     // Drop the attribute.
4773     return;
4774   }
4775
4776   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4777       attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4778 }
4779
4780 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4781                                         const AttributeList &attr) {
4782   ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4783   
4784   DeclContext *DC = method->getDeclContext();
4785   if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4786     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4787     << attr.getName() << 0;
4788     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4789     return;
4790   }
4791   if (method->getMethodFamily() == OMF_dealloc) {
4792     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4793     << attr.getName() << 1;
4794     return;
4795   }
4796   
4797   method->addAttr(::new (S.Context)
4798                   ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4799                                         attr.getAttributeSpellingListIndex()));
4800 }
4801
4802 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4803                                         const AttributeList &Attr) {
4804   if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4805                                                       Attr.getName()))
4806     return;
4807
4808   D->addAttr(::new (S.Context)
4809              CFAuditedTransferAttr(Attr.getRange(), S.Context,
4810                                    Attr.getAttributeSpellingListIndex()));
4811 }
4812
4813 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4814                                         const AttributeList &Attr) {
4815   if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4816                                                       Attr.getName()))
4817     return;
4818
4819   D->addAttr(::new (S.Context)
4820              CFUnknownTransferAttr(Attr.getRange(), S.Context,
4821              Attr.getAttributeSpellingListIndex()));
4822 }
4823
4824 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4825                                 const AttributeList &Attr) {
4826   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4827
4828   if (!Parm) {
4829     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4830     return;
4831   }
4832
4833   // Typedefs only allow objc_bridge(id) and have some additional checking.
4834   if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4835     if (!Parm->Ident->isStr("id")) {
4836       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4837         << Attr.getName();
4838       return;
4839     }
4840
4841     // Only allow 'cv void *'.
4842     QualType T = TD->getUnderlyingType();
4843     if (!T->isVoidPointerType()) {
4844       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4845       return;
4846     }
4847   }
4848   
4849   D->addAttr(::new (S.Context)
4850              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4851                            Attr.getAttributeSpellingListIndex()));
4852 }
4853
4854 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4855                                         const AttributeList &Attr) {
4856   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4857
4858   if (!Parm) {
4859     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4860     return;
4861   }
4862   
4863   D->addAttr(::new (S.Context)
4864              ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4865                             Attr.getAttributeSpellingListIndex()));
4866 }
4867
4868 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4869                                  const AttributeList &Attr) {
4870   IdentifierInfo *RelatedClass =
4871     Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4872   if (!RelatedClass) {
4873     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4874     return;
4875   }
4876   IdentifierInfo *ClassMethod =
4877     Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4878   IdentifierInfo *InstanceMethod =
4879     Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4880   D->addAttr(::new (S.Context)
4881              ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4882                                    ClassMethod, InstanceMethod,
4883                                    Attr.getAttributeSpellingListIndex()));
4884 }
4885
4886 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4887                                             const AttributeList &Attr) {
4888   ObjCInterfaceDecl *IFace;
4889   if (ObjCCategoryDecl *CatDecl =
4890           dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4891     IFace = CatDecl->getClassInterface();
4892   else
4893     IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4894
4895   if (!IFace)
4896     return;
4897
4898   IFace->setHasDesignatedInitializers();
4899   D->addAttr(::new (S.Context)
4900                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4901                                          Attr.getAttributeSpellingListIndex()));
4902 }
4903
4904 static void handleObjCRuntimeName(Sema &S, Decl *D,
4905                                   const AttributeList &Attr) {
4906   StringRef MetaDataName;
4907   if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4908     return;
4909   D->addAttr(::new (S.Context)
4910              ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4911                                  MetaDataName,
4912                                  Attr.getAttributeSpellingListIndex()));
4913 }
4914
4915 // When a user wants to use objc_boxable with a union or struct
4916 // but they don't have access to the declaration (legacy/third-party code)
4917 // then they can 'enable' this feature with a typedef:
4918 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4919 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4920   bool notify = false;
4921
4922   RecordDecl *RD = dyn_cast<RecordDecl>(D);
4923   if (RD && RD->getDefinition()) {
4924     RD = RD->getDefinition();
4925     notify = true;
4926   }
4927
4928   if (RD) {
4929     ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4930                           ObjCBoxableAttr(Attr.getRange(), S.Context,
4931                                           Attr.getAttributeSpellingListIndex());
4932     RD->addAttr(BoxableAttr);
4933     if (notify) {
4934       // we need to notify ASTReader/ASTWriter about
4935       // modification of existing declaration
4936       if (ASTMutationListener *L = S.getASTMutationListener())
4937         L->AddedAttributeToRecord(BoxableAttr, RD);
4938     }
4939   }
4940 }
4941
4942 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4943                                     const AttributeList &Attr) {
4944   if (hasDeclarator(D)) return;
4945
4946   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4947     << Attr.getRange() << Attr.getName() << ExpectedVariable;
4948 }
4949
4950 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4951                                           const AttributeList &Attr) {
4952   ValueDecl *vd = cast<ValueDecl>(D);
4953   QualType type = vd->getType();
4954
4955   if (!type->isDependentType() &&
4956       !type->isObjCLifetimeType()) {
4957     S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4958       << type;
4959     return;
4960   }
4961
4962   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4963
4964   // If we have no lifetime yet, check the lifetime we're presumably
4965   // going to infer.
4966   if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4967     lifetime = type->getObjCARCImplicitLifetime();
4968
4969   switch (lifetime) {
4970   case Qualifiers::OCL_None:
4971     assert(type->isDependentType() &&
4972            "didn't infer lifetime for non-dependent type?");
4973     break;
4974
4975   case Qualifiers::OCL_Weak:   // meaningful
4976   case Qualifiers::OCL_Strong: // meaningful
4977     break;
4978
4979   case Qualifiers::OCL_ExplicitNone:
4980   case Qualifiers::OCL_Autoreleasing:
4981     S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4982       << (lifetime == Qualifiers::OCL_Autoreleasing);
4983     break;
4984   }
4985
4986   D->addAttr(::new (S.Context)
4987              ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4988                                      Attr.getAttributeSpellingListIndex()));
4989 }
4990
4991 //===----------------------------------------------------------------------===//
4992 // Microsoft specific attribute handlers.
4993 //===----------------------------------------------------------------------===//
4994
4995 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4996                               unsigned AttrSpellingListIndex, StringRef Uuid) {
4997   if (const auto *UA = D->getAttr<UuidAttr>()) {
4998     if (UA->getGuid().equals_lower(Uuid))
4999       return nullptr;
5000     Diag(UA->getLocation(), diag::err_mismatched_uuid);
5001     Diag(Range.getBegin(), diag::note_previous_uuid);
5002     D->dropAttr<UuidAttr>();
5003   }
5004
5005   return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5006 }
5007
5008 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5009   if (!S.LangOpts.CPlusPlus) {
5010     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5011       << Attr.getName() << AttributeLangSupport::C;
5012     return;
5013   }
5014
5015   StringRef StrRef;
5016   SourceLocation LiteralLoc;
5017   if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5018     return;
5019
5020   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5021   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5022   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5023     StrRef = StrRef.drop_front().drop_back();
5024
5025   // Validate GUID length.
5026   if (StrRef.size() != 36) {
5027     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5028     return;
5029   }
5030
5031   for (unsigned i = 0; i < 36; ++i) {
5032     if (i == 8 || i == 13 || i == 18 || i == 23) {
5033       if (StrRef[i] != '-') {
5034         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5035         return;
5036       }
5037     } else if (!isHexDigit(StrRef[i])) {
5038       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5039       return;
5040     }
5041   }
5042
5043   UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5044                                  Attr.getAttributeSpellingListIndex(), StrRef);
5045   if (UA)
5046     D->addAttr(UA);
5047 }
5048
5049 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5050   if (!S.LangOpts.CPlusPlus) {
5051     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5052       << Attr.getName() << AttributeLangSupport::C;
5053     return;
5054   }
5055   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5056       D, Attr.getRange(), /*BestCase=*/true,
5057       Attr.getAttributeSpellingListIndex(),
5058       (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5059   if (IA) {
5060     D->addAttr(IA);
5061     S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5062   }
5063 }
5064
5065 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5066                                      const AttributeList &Attr) {
5067   VarDecl *VD = cast<VarDecl>(D);
5068   if (!S.Context.getTargetInfo().isTLSSupported()) {
5069     S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5070     return;
5071   }
5072   if (VD->getTSCSpec() != TSCS_unspecified) {
5073     S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5074     return;
5075   }
5076   if (VD->hasLocalStorage()) {
5077     S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5078     return;
5079   }
5080   VD->addAttr(::new (S.Context) ThreadAttr(
5081       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5082 }
5083
5084 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5085   SmallVector<StringRef, 4> Tags;
5086   for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5087     StringRef Tag;
5088     if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5089       return;
5090     Tags.push_back(Tag);
5091   }
5092
5093   if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5094     if (!NS->isInline()) {
5095       S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5096       return;
5097     }
5098     if (NS->isAnonymousNamespace()) {
5099       S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5100       return;
5101     }
5102     if (Attr.getNumArgs() == 0)
5103       Tags.push_back(NS->getName());
5104   } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5105     return;
5106
5107   // Store tags sorted and without duplicates.
5108   std::sort(Tags.begin(), Tags.end());
5109   Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5110
5111   D->addAttr(::new (S.Context)
5112              AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5113                         Attr.getAttributeSpellingListIndex()));
5114 }
5115
5116 static void handleARMInterruptAttr(Sema &S, Decl *D,
5117                                    const AttributeList &Attr) {
5118   // Check the attribute arguments.
5119   if (Attr.getNumArgs() > 1) {
5120     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5121       << Attr.getName() << 1;
5122     return;
5123   }
5124
5125   StringRef Str;
5126   SourceLocation ArgLoc;
5127
5128   if (Attr.getNumArgs() == 0)
5129     Str = "";
5130   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5131     return;
5132
5133   ARMInterruptAttr::InterruptType Kind;
5134   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5135     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5136       << Attr.getName() << Str << ArgLoc;
5137     return;
5138   }
5139
5140   unsigned Index = Attr.getAttributeSpellingListIndex();
5141   D->addAttr(::new (S.Context)
5142              ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5143 }
5144
5145 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5146                                       const AttributeList &Attr) {
5147   if (!checkAttributeNumArgs(S, Attr, 1))
5148     return;
5149
5150   if (!Attr.isArgExpr(0)) {
5151     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5152       << AANT_ArgumentIntegerConstant;
5153     return;    
5154   }
5155
5156   // FIXME: Check for decl - it should be void ()(void).
5157
5158   Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5159   llvm::APSInt NumParams(32);
5160   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5161     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5162       << Attr.getName() << AANT_ArgumentIntegerConstant
5163       << NumParamsExpr->getSourceRange();
5164     return;
5165   }
5166
5167   unsigned Num = NumParams.getLimitedValue(255);
5168   if ((Num & 1) || Num > 30) {
5169     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5170       << Attr.getName() << (int)NumParams.getSExtValue()
5171       << NumParamsExpr->getSourceRange();
5172     return;
5173   }
5174
5175   D->addAttr(::new (S.Context)
5176               MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5177                                   Attr.getAttributeSpellingListIndex()));
5178   D->addAttr(UsedAttr::CreateImplicit(S.Context));
5179 }
5180
5181 static void handleMipsInterruptAttr(Sema &S, Decl *D,
5182                                     const AttributeList &Attr) {
5183   // Only one optional argument permitted.
5184   if (Attr.getNumArgs() > 1) {
5185     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5186         << Attr.getName() << 1;
5187     return;
5188   }
5189
5190   StringRef Str;
5191   SourceLocation ArgLoc;
5192
5193   if (Attr.getNumArgs() == 0)
5194     Str = "";
5195   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5196     return;
5197
5198   // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5199   // a) Must be a function.
5200   // b) Must have no parameters.
5201   // c) Must have the 'void' return type.
5202   // d) Cannot have the 'mips16' attribute, as that instruction set
5203   //    lacks the 'eret' instruction.
5204   // e) The attribute itself must either have no argument or one of the
5205   //    valid interrupt types, see [MipsInterruptDocs].
5206
5207   if (!isFunctionOrMethod(D)) {
5208     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5209         << "'interrupt'" << ExpectedFunctionOrMethod;
5210     return;
5211   }
5212
5213   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5214     S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5215         << 0;
5216     return;
5217   }
5218
5219   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5220     S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5221         << 1;
5222     return;
5223   }
5224
5225   if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5226                                            Attr.getName()))
5227     return;
5228
5229   MipsInterruptAttr::InterruptType Kind;
5230   if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5231     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5232         << Attr.getName() << "'" + std::string(Str) + "'";
5233     return;
5234   }
5235
5236   D->addAttr(::new (S.Context) MipsInterruptAttr(
5237       Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5238 }
5239
5240 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5241                                       const AttributeList &Attr) {
5242   // Semantic checks for a function with the 'interrupt' attribute.
5243   // a) Must be a function.
5244   // b) Must have the 'void' return type.
5245   // c) Must take 1 or 2 arguments.
5246   // d) The 1st argument must be a pointer.
5247   // e) The 2nd argument (if any) must be an unsigned integer.
5248   if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5249       CXXMethodDecl::isStaticOverloadedOperator(
5250           cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5251     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5252         << Attr.getName() << ExpectedFunctionWithProtoType;
5253     return;
5254   }
5255   // Interrupt handler must have void return type.
5256   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5257     S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5258            diag::err_anyx86_interrupt_attribute)
5259         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5260                 ? 0
5261                 : 1)
5262         << 0;
5263     return;
5264   }
5265   // Interrupt handler must have 1 or 2 parameters.
5266   unsigned NumParams = getFunctionOrMethodNumParams(D);
5267   if (NumParams < 1 || NumParams > 2) {
5268     S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5269         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5270                 ? 0
5271                 : 1)
5272         << 1;
5273     return;
5274   }
5275   // The first argument must be a pointer.
5276   if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5277     S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5278            diag::err_anyx86_interrupt_attribute)
5279         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5280                 ? 0
5281                 : 1)
5282         << 2;
5283     return;
5284   }
5285   // The second argument, if present, must be an unsigned integer.
5286   unsigned TypeSize =
5287       S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5288           ? 64
5289           : 32;
5290   if (NumParams == 2 &&
5291       (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5292        S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5293     S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5294            diag::err_anyx86_interrupt_attribute)
5295         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5296                 ? 0
5297                 : 1)
5298         << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5299     return;
5300   }
5301   D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5302       Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5303   D->addAttr(UsedAttr::CreateImplicit(S.Context));
5304 }
5305
5306 static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5307   if (!isFunctionOrMethod(D)) {
5308     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5309         << "'interrupt'" << ExpectedFunction;
5310     return;
5311   }
5312
5313   if (!checkAttributeNumArgs(S, Attr, 0))
5314     return;
5315
5316   handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5317 }
5318
5319 static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5320   if (!isFunctionOrMethod(D)) {
5321     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5322         << "'signal'" << ExpectedFunction;
5323     return;
5324   }
5325
5326   if (!checkAttributeNumArgs(S, Attr, 0))
5327     return;
5328
5329   handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5330 }
5331
5332 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5333   // Dispatch the interrupt attribute based on the current target.
5334   switch (S.Context.getTargetInfo().getTriple().getArch()) {
5335   case llvm::Triple::msp430:
5336     handleMSP430InterruptAttr(S, D, Attr);
5337     break;
5338   case llvm::Triple::mipsel:
5339   case llvm::Triple::mips:
5340     handleMipsInterruptAttr(S, D, Attr);
5341     break;
5342   case llvm::Triple::x86:
5343   case llvm::Triple::x86_64:
5344     handleAnyX86InterruptAttr(S, D, Attr);
5345     break;
5346   case llvm::Triple::avr:
5347     handleAVRInterruptAttr(S, D, Attr);
5348     break;
5349   default:
5350     handleARMInterruptAttr(S, D, Attr);
5351     break;
5352   }
5353 }
5354
5355 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5356                                               const AttributeList &Attr) {
5357   uint32_t Min = 0;
5358   Expr *MinExpr = Attr.getArgAsExpr(0);
5359   if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5360     return;
5361
5362   uint32_t Max = 0;
5363   Expr *MaxExpr = Attr.getArgAsExpr(1);
5364   if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5365     return;
5366
5367   if (Min == 0 && Max != 0) {
5368     S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5369       << Attr.getName() << 0;
5370     return;
5371   }
5372   if (Min > Max) {
5373     S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5374       << Attr.getName() << 1;
5375     return;
5376   }
5377
5378   D->addAttr(::new (S.Context)
5379              AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5380                                          Attr.getAttributeSpellingListIndex()));
5381 }
5382
5383 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5384                                        const AttributeList &Attr) {
5385   uint32_t Min = 0;
5386   Expr *MinExpr = Attr.getArgAsExpr(0);
5387   if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5388     return;
5389
5390   uint32_t Max = 0;
5391   if (Attr.getNumArgs() == 2) {
5392     Expr *MaxExpr = Attr.getArgAsExpr(1);
5393     if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5394       return;
5395   }
5396
5397   if (Min == 0 && Max != 0) {
5398     S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5399       << Attr.getName() << 0;
5400     return;
5401   }
5402   if (Max != 0 && Min > Max) {
5403     S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5404       << Attr.getName() << 1;
5405     return;
5406   }
5407
5408   D->addAttr(::new (S.Context)
5409              AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5410                                   Attr.getAttributeSpellingListIndex()));
5411 }
5412
5413 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5414                                     const AttributeList &Attr) {
5415   uint32_t NumSGPR = 0;
5416   Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5417   if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5418     return;
5419
5420   D->addAttr(::new (S.Context)
5421              AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5422                                Attr.getAttributeSpellingListIndex()));
5423 }
5424
5425 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5426                                     const AttributeList &Attr) {
5427   uint32_t NumVGPR = 0;
5428   Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5429   if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5430     return;
5431
5432   D->addAttr(::new (S.Context)
5433              AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5434                                Attr.getAttributeSpellingListIndex()));
5435 }
5436
5437 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5438                                               const AttributeList& Attr) {
5439   // If we try to apply it to a function pointer, don't warn, but don't
5440   // do anything, either. It doesn't matter anyway, because there's nothing
5441   // special about calling a force_align_arg_pointer function.
5442   ValueDecl *VD = dyn_cast<ValueDecl>(D);
5443   if (VD && VD->getType()->isFunctionPointerType())
5444     return;
5445   // Also don't warn on function pointer typedefs.
5446   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5447   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5448     TD->getUnderlyingType()->isFunctionType()))
5449     return;
5450   // Attribute can only be applied to function types.
5451   if (!isa<FunctionDecl>(D)) {
5452     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5453       << Attr.getName() << /* function */0;
5454     return;
5455   }
5456
5457   D->addAttr(::new (S.Context)
5458               X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5459                                         Attr.getAttributeSpellingListIndex()));
5460 }
5461
5462 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5463   uint32_t Version;
5464   Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5465   if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5466     return;
5467
5468   // TODO: Investigate what happens with the next major version of MSVC.
5469   if (Version != LangOptions::MSVC2015) {
5470     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5471         << Attr.getName() << Version << VersionExpr->getSourceRange();
5472     return;
5473   }
5474
5475   D->addAttr(::new (S.Context)
5476                  LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5477                                    Attr.getAttributeSpellingListIndex()));
5478 }
5479
5480 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5481                                         unsigned AttrSpellingListIndex) {
5482   if (D->hasAttr<DLLExportAttr>()) {
5483     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5484     return nullptr;
5485   }
5486
5487   if (D->hasAttr<DLLImportAttr>())
5488     return nullptr;
5489
5490   return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5491 }
5492
5493 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5494                                         unsigned AttrSpellingListIndex) {
5495   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5496     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5497     D->dropAttr<DLLImportAttr>();
5498   }
5499
5500   if (D->hasAttr<DLLExportAttr>())
5501     return nullptr;
5502
5503   return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5504 }
5505
5506 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5507   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5508       S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5509     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5510         << A.getName();
5511     return;
5512   }
5513
5514   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5515     if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5516         !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5517       // MinGW doesn't allow dllimport on inline functions.
5518       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5519           << A.getName();
5520       return;
5521     }
5522   }
5523
5524   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5525     if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5526         MD->getParent()->isLambda()) {
5527       S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5528       return;
5529     }
5530   }
5531
5532   unsigned Index = A.getAttributeSpellingListIndex();
5533   Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5534                       ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5535                       : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5536   if (NewAttr)
5537     D->addAttr(NewAttr);
5538 }
5539
5540 MSInheritanceAttr *
5541 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5542                              unsigned AttrSpellingListIndex,
5543                              MSInheritanceAttr::Spelling SemanticSpelling) {
5544   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5545     if (IA->getSemanticSpelling() == SemanticSpelling)
5546       return nullptr;
5547     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5548         << 1 /*previous declaration*/;
5549     Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5550     D->dropAttr<MSInheritanceAttr>();
5551   }
5552
5553   CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5554   if (RD->hasDefinition()) {
5555     if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5556                                            SemanticSpelling)) {
5557       return nullptr;
5558     }
5559   } else {
5560     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5561       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5562           << 1 /*partial specialization*/;
5563       return nullptr;
5564     }
5565     if (RD->getDescribedClassTemplate()) {
5566       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5567           << 0 /*primary template*/;
5568       return nullptr;
5569     }
5570   }
5571
5572   return ::new (Context)
5573       MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5574 }
5575
5576 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5577   // The capability attributes take a single string parameter for the name of
5578   // the capability they represent. The lockable attribute does not take any
5579   // parameters. However, semantically, both attributes represent the same
5580   // concept, and so they use the same semantic attribute. Eventually, the
5581   // lockable attribute will be removed.
5582   //
5583   // For backward compatibility, any capability which has no specified string
5584   // literal will be considered a "mutex."
5585   StringRef N("mutex");
5586   SourceLocation LiteralLoc;
5587   if (Attr.getKind() == AttributeList::AT_Capability &&
5588       !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5589     return;
5590
5591   // Currently, there are only two names allowed for a capability: role and
5592   // mutex (case insensitive). Diagnose other capability names.
5593   if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5594     S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5595
5596   D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5597                                         Attr.getAttributeSpellingListIndex()));
5598 }
5599
5600 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5601                                        const AttributeList &Attr) {
5602   D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5603                                                     Attr.getArgAsExpr(0),
5604                                         Attr.getAttributeSpellingListIndex()));
5605 }
5606
5607 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5608                                         const AttributeList &Attr) {
5609   SmallVector<Expr*, 1> Args;
5610   if (!checkLockFunAttrCommon(S, D, Attr, Args))
5611     return;
5612
5613   D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5614                                                      S.Context,
5615                                                      Args.data(), Args.size(),
5616                                         Attr.getAttributeSpellingListIndex()));
5617 }
5618
5619 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5620                                            const AttributeList &Attr) {
5621   SmallVector<Expr*, 2> Args;
5622   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5623     return;
5624
5625   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5626                                                         S.Context,
5627                                                         Attr.getArgAsExpr(0),
5628                                                         Args.data(),
5629                                                         Args.size(),
5630                                         Attr.getAttributeSpellingListIndex()));
5631 }
5632
5633 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5634                                         const AttributeList &Attr) {
5635   // Check that all arguments are lockable objects.
5636   SmallVector<Expr *, 1> Args;
5637   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5638
5639   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5640       Attr.getRange(), S.Context, Args.data(), Args.size(),
5641       Attr.getAttributeSpellingListIndex()));
5642 }
5643
5644 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5645                                          const AttributeList &Attr) {
5646   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5647     return;
5648
5649   // check that all arguments are lockable objects
5650   SmallVector<Expr*, 1> Args;
5651   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5652   if (Args.empty())
5653     return;
5654
5655   RequiresCapabilityAttr *RCA = ::new (S.Context)
5656     RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5657                            Args.size(), Attr.getAttributeSpellingListIndex());
5658
5659   D->addAttr(RCA);
5660 }
5661
5662 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5663   if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5664     if (NSD->isAnonymousNamespace()) {
5665       S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5666       // Do not want to attach the attribute to the namespace because that will
5667       // cause confusing diagnostic reports for uses of declarations within the
5668       // namespace.
5669       return;
5670     }
5671   }
5672
5673   // Handle the cases where the attribute has a text message.
5674   StringRef Str, Replacement;
5675   if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5676       !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5677     return;
5678
5679   // Only support a single optional message for Declspec and CXX11.
5680   if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5681     checkAttributeAtMostNumArgs(S, Attr, 1);
5682   else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5683            !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5684     return;
5685
5686   if (!S.getLangOpts().CPlusPlus14)
5687     if (Attr.isCXX11Attribute() &&
5688         !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5689       S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5690
5691   D->addAttr(::new (S.Context)
5692                  DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5693                                 Attr.getAttributeSpellingListIndex()));
5694 }
5695
5696 static bool isGlobalVar(const Decl *D) {
5697   if (const auto *S = dyn_cast<VarDecl>(D))
5698     return S->hasGlobalStorage();
5699   return false;
5700 }
5701
5702 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5703   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5704     return;
5705
5706   std::vector<StringRef> Sanitizers;
5707
5708   for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5709     StringRef SanitizerName;
5710     SourceLocation LiteralLoc;
5711
5712     if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5713       return;
5714
5715     if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5716       S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5717     else if (isGlobalVar(D) && SanitizerName != "address")
5718       S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5719           << Attr.getName() << ExpectedFunctionOrMethod;
5720     Sanitizers.push_back(SanitizerName);
5721   }
5722
5723   D->addAttr(::new (S.Context) NoSanitizeAttr(
5724       Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5725       Attr.getAttributeSpellingListIndex()));
5726 }
5727
5728 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5729                                          const AttributeList &Attr) {
5730   StringRef AttrName = Attr.getName()->getName();
5731   normalizeName(AttrName);
5732   StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5733                                 .Case("no_address_safety_analysis", "address")
5734                                 .Case("no_sanitize_address", "address")
5735                                 .Case("no_sanitize_thread", "thread")
5736                                 .Case("no_sanitize_memory", "memory");
5737   if (isGlobalVar(D) && SanitizerName != "address")
5738     S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5739         << Attr.getName() << ExpectedFunction;
5740   D->addAttr(::new (S.Context)
5741                  NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5742                                 Attr.getAttributeSpellingListIndex()));
5743 }
5744
5745 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5746                                       const AttributeList &Attr) {
5747   if (InternalLinkageAttr *Internal =
5748           S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5749                                      Attr.getAttributeSpellingListIndex()))
5750     D->addAttr(Internal);
5751 }
5752
5753 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5754   if (S.LangOpts.OpenCLVersion != 200)
5755     S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5756         << Attr.getName() << "2.0" << 0;
5757   else
5758     S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5759         << Attr.getName() << "2.0";
5760 }
5761
5762 /// Handles semantic checking for features that are common to all attributes,
5763 /// such as checking whether a parameter was properly specified, or the correct
5764 /// number of arguments were passed, etc.
5765 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5766                                           const AttributeList &Attr) {
5767   // Several attributes carry different semantics than the parsing requires, so
5768   // those are opted out of the common handling.
5769   //
5770   // We also bail on unknown and ignored attributes because those are handled
5771   // as part of the target-specific handling logic.
5772   if (Attr.hasCustomParsing() ||
5773       Attr.getKind() == AttributeList::UnknownAttribute)
5774     return false;
5775
5776   // Check whether the attribute requires specific language extensions to be
5777   // enabled.
5778   if (!Attr.diagnoseLangOpts(S))
5779     return true;
5780
5781   if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5782     // If there are no optional arguments, then checking for the argument count
5783     // is trivial.
5784     if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5785       return true;
5786   } else {
5787     // There are optional arguments, so checking is slightly more involved.
5788     if (Attr.getMinArgs() &&
5789         !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5790       return true;
5791     else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5792              !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5793       return true;
5794   }
5795
5796   // Check whether the attribute appertains to the given subject.
5797   if (!Attr.diagnoseAppertainsTo(S, D))
5798     return true;
5799
5800   return false;
5801 }
5802
5803 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5804                                    const AttributeList &Attr) {
5805   if (D->isInvalidDecl())
5806     return;
5807
5808   // Check if there is only one access qualifier.
5809   if (D->hasAttr<OpenCLAccessAttr>()) {
5810     S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5811         << D->getSourceRange();
5812     D->setInvalidDecl(true);
5813     return;
5814   }
5815
5816   // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5817   // image object can be read and written.
5818   // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5819   // object. Using the read_write (or __read_write) qualifier with the pipe
5820   // qualifier is a compilation error.
5821   if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5822     const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5823     if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5824       if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5825         S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5826             << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5827         D->setInvalidDecl(true);
5828         return;
5829       }
5830     }
5831   }
5832
5833   D->addAttr(::new (S.Context) OpenCLAccessAttr(
5834       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5835 }
5836
5837 //===----------------------------------------------------------------------===//
5838 // Top Level Sema Entry Points
5839 //===----------------------------------------------------------------------===//
5840
5841 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5842 /// the attribute applies to decls.  If the attribute is a type attribute, just
5843 /// silently ignore it if a GNU attribute.
5844 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5845                                  const AttributeList &Attr,
5846                                  bool IncludeCXX11Attributes) {
5847   if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5848     return;
5849
5850   // Ignore C++11 attributes on declarator chunks: they appertain to the type
5851   // instead.
5852   if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5853     return;
5854
5855   // Unknown attributes are automatically warned on. Target-specific attributes
5856   // which do not apply to the current target architecture are treated as
5857   // though they were unknown attributes.
5858   if (Attr.getKind() == AttributeList::UnknownAttribute ||
5859       !Attr.existsInTarget(S.Context.getTargetInfo())) {
5860     S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5861                               ? diag::warn_unhandled_ms_attribute_ignored
5862                               : diag::warn_unknown_attribute_ignored)
5863         << Attr.getName();
5864     return;
5865   }
5866
5867   if (handleCommonAttributeFeatures(S, scope, D, Attr))
5868     return;
5869
5870   switch (Attr.getKind()) {
5871   default:
5872     if (!Attr.isStmtAttr()) {
5873       // Type attributes are handled elsewhere; silently move on.
5874       assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5875       break;
5876     }
5877     S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5878         << Attr.getName() << D->getLocation();
5879     break;
5880   case AttributeList::AT_Interrupt:
5881     handleInterruptAttr(S, D, Attr);
5882     break;
5883   case AttributeList::AT_X86ForceAlignArgPointer:
5884     handleX86ForceAlignArgPointerAttr(S, D, Attr);
5885     break;
5886   case AttributeList::AT_DLLExport:
5887   case AttributeList::AT_DLLImport:
5888     handleDLLAttr(S, D, Attr);
5889     break;
5890   case AttributeList::AT_Mips16:
5891     handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5892                                                                        Attr);
5893     break;
5894   case AttributeList::AT_NoMips16:
5895     handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5896     break;
5897   case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5898     handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5899     break;
5900   case AttributeList::AT_AMDGPUWavesPerEU:
5901     handleAMDGPUWavesPerEUAttr(S, D, Attr);
5902     break;
5903   case AttributeList::AT_AMDGPUNumSGPR:
5904     handleAMDGPUNumSGPRAttr(S, D, Attr);
5905     break;
5906   case AttributeList::AT_AMDGPUNumVGPR:
5907     handleAMDGPUNumVGPRAttr(S, D, Attr);
5908     break;
5909   case AttributeList::AT_AVRSignal:
5910     handleAVRSignalAttr(S, D, Attr);
5911     break;
5912   case AttributeList::AT_IBAction:
5913     handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5914     break;
5915   case AttributeList::AT_IBOutlet:
5916     handleIBOutlet(S, D, Attr);
5917     break;
5918   case AttributeList::AT_IBOutletCollection:
5919     handleIBOutletCollection(S, D, Attr);
5920     break;
5921   case AttributeList::AT_IFunc:
5922     handleIFuncAttr(S, D, Attr);
5923     break;
5924   case AttributeList::AT_Alias:
5925     handleAliasAttr(S, D, Attr);
5926     break;
5927   case AttributeList::AT_Aligned:
5928     handleAlignedAttr(S, D, Attr);
5929     break;
5930   case AttributeList::AT_AlignValue:
5931     handleAlignValueAttr(S, D, Attr);
5932     break;
5933   case AttributeList::AT_AllocSize:
5934     handleAllocSizeAttr(S, D, Attr);
5935     break;
5936   case AttributeList::AT_AlwaysInline:
5937     handleAlwaysInlineAttr(S, D, Attr);
5938     break;
5939   case AttributeList::AT_AnalyzerNoReturn:
5940     handleAnalyzerNoReturnAttr(S, D, Attr);
5941     break;
5942   case AttributeList::AT_TLSModel:
5943     handleTLSModelAttr(S, D, Attr);
5944     break;
5945   case AttributeList::AT_Annotate:
5946     handleAnnotateAttr(S, D, Attr);
5947     break;
5948   case AttributeList::AT_Availability:
5949     handleAvailabilityAttr(S, D, Attr);
5950     break;
5951   case AttributeList::AT_CarriesDependency:
5952     handleDependencyAttr(S, scope, D, Attr);
5953     break;
5954   case AttributeList::AT_Common:
5955     handleCommonAttr(S, D, Attr);
5956     break;
5957   case AttributeList::AT_CUDAConstant:
5958     handleConstantAttr(S, D, Attr);
5959     break;
5960   case AttributeList::AT_PassObjectSize:
5961     handlePassObjectSizeAttr(S, D, Attr);
5962     break;
5963   case AttributeList::AT_Constructor:
5964     handleConstructorAttr(S, D, Attr);
5965     break;
5966   case AttributeList::AT_CXX11NoReturn:
5967     handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5968     break;
5969   case AttributeList::AT_Deprecated:
5970     handleDeprecatedAttr(S, D, Attr);
5971     break;
5972   case AttributeList::AT_Destructor:
5973     handleDestructorAttr(S, D, Attr);
5974     break;
5975   case AttributeList::AT_EnableIf:
5976     handleEnableIfAttr(S, D, Attr);
5977     break;
5978   case AttributeList::AT_DiagnoseIf:
5979     handleDiagnoseIfAttr(S, D, Attr);
5980     break;
5981   case AttributeList::AT_ExtVectorType:
5982     handleExtVectorTypeAttr(S, scope, D, Attr);
5983     break;
5984   case AttributeList::AT_ExternalSourceSymbol:
5985     handleExternalSourceSymbolAttr(S, D, Attr);
5986     break;
5987   case AttributeList::AT_MinSize:
5988     handleMinSizeAttr(S, D, Attr);
5989     break;
5990   case AttributeList::AT_OptimizeNone:
5991     handleOptimizeNoneAttr(S, D, Attr);
5992     break;
5993   case AttributeList::AT_FlagEnum:
5994     handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5995     break;
5996   case AttributeList::AT_EnumExtensibility:
5997     handleEnumExtensibilityAttr(S, D, Attr);
5998     break;
5999   case AttributeList::AT_Flatten:
6000     handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6001     break;
6002   case AttributeList::AT_Format:
6003     handleFormatAttr(S, D, Attr);
6004     break;
6005   case AttributeList::AT_FormatArg:
6006     handleFormatArgAttr(S, D, Attr);
6007     break;
6008   case AttributeList::AT_CUDAGlobal:
6009     handleGlobalAttr(S, D, Attr);
6010     break;
6011   case AttributeList::AT_CUDADevice:
6012     handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6013                                                                         Attr);
6014     break;
6015   case AttributeList::AT_CUDAHost:
6016     handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6017                                                                       Attr);
6018     break;
6019   case AttributeList::AT_GNUInline:
6020     handleGNUInlineAttr(S, D, Attr);
6021     break;
6022   case AttributeList::AT_CUDALaunchBounds:
6023     handleLaunchBoundsAttr(S, D, Attr);
6024     break;
6025   case AttributeList::AT_Restrict:
6026     handleRestrictAttr(S, D, Attr);
6027     break;
6028   case AttributeList::AT_MayAlias:
6029     handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6030     break;
6031   case AttributeList::AT_Mode:
6032     handleModeAttr(S, D, Attr);
6033     break;
6034   case AttributeList::AT_NoAlias:
6035     handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6036     break;
6037   case AttributeList::AT_NoCommon:
6038     handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6039     break;
6040   case AttributeList::AT_NoSplitStack:
6041     handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6042     break;
6043   case AttributeList::AT_NonNull:
6044     if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6045       handleNonNullAttrParameter(S, PVD, Attr);
6046     else
6047       handleNonNullAttr(S, D, Attr);
6048     break;
6049   case AttributeList::AT_ReturnsNonNull:
6050     handleReturnsNonNullAttr(S, D, Attr);
6051     break;
6052   case AttributeList::AT_AssumeAligned:
6053     handleAssumeAlignedAttr(S, D, Attr);
6054     break;
6055   case AttributeList::AT_AllocAlign:
6056     handleAllocAlignAttr(S, D, Attr);
6057     break;
6058   case AttributeList::AT_Overloadable:
6059     handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6060     break;
6061   case AttributeList::AT_Ownership:
6062     handleOwnershipAttr(S, D, Attr);
6063     break;
6064   case AttributeList::AT_Cold:
6065     handleColdAttr(S, D, Attr);
6066     break;
6067   case AttributeList::AT_Hot:
6068     handleHotAttr(S, D, Attr);
6069     break;
6070   case AttributeList::AT_Naked:
6071     handleNakedAttr(S, D, Attr);
6072     break;
6073   case AttributeList::AT_NoReturn:
6074     handleNoReturnAttr(S, D, Attr);
6075     break;
6076   case AttributeList::AT_NoThrow:
6077     handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6078     break;
6079   case AttributeList::AT_CUDAShared:
6080     handleSharedAttr(S, D, Attr);
6081     break;
6082   case AttributeList::AT_VecReturn:
6083     handleVecReturnAttr(S, D, Attr);
6084     break;
6085   case AttributeList::AT_ObjCOwnership:
6086     handleObjCOwnershipAttr(S, D, Attr);
6087     break;
6088   case AttributeList::AT_ObjCPreciseLifetime:
6089     handleObjCPreciseLifetimeAttr(S, D, Attr);
6090     break;
6091   case AttributeList::AT_ObjCReturnsInnerPointer:
6092     handleObjCReturnsInnerPointerAttr(S, D, Attr);
6093     break;
6094   case AttributeList::AT_ObjCRequiresSuper:
6095     handleObjCRequiresSuperAttr(S, D, Attr);
6096     break;
6097   case AttributeList::AT_ObjCBridge:
6098     handleObjCBridgeAttr(S, scope, D, Attr);
6099     break;
6100   case AttributeList::AT_ObjCBridgeMutable:
6101     handleObjCBridgeMutableAttr(S, scope, D, Attr);
6102     break;
6103   case AttributeList::AT_ObjCBridgeRelated:
6104     handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6105     break;
6106   case AttributeList::AT_ObjCDesignatedInitializer:
6107     handleObjCDesignatedInitializer(S, D, Attr);
6108     break;
6109   case AttributeList::AT_ObjCRuntimeName:
6110     handleObjCRuntimeName(S, D, Attr);
6111     break;
6112    case AttributeList::AT_ObjCRuntimeVisible:
6113     handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6114     break;
6115   case AttributeList::AT_ObjCBoxable:
6116     handleObjCBoxable(S, D, Attr);
6117     break;
6118   case AttributeList::AT_CFAuditedTransfer:
6119     handleCFAuditedTransferAttr(S, D, Attr);
6120     break;
6121   case AttributeList::AT_CFUnknownTransfer:
6122     handleCFUnknownTransferAttr(S, D, Attr);
6123     break;
6124   case AttributeList::AT_CFConsumed:
6125   case AttributeList::AT_NSConsumed:
6126     handleNSConsumedAttr(S, D, Attr);
6127     break;
6128   case AttributeList::AT_NSConsumesSelf:
6129     handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6130     break;
6131   case AttributeList::AT_NSReturnsAutoreleased:
6132   case AttributeList::AT_NSReturnsNotRetained:
6133   case AttributeList::AT_CFReturnsNotRetained:
6134   case AttributeList::AT_NSReturnsRetained:
6135   case AttributeList::AT_CFReturnsRetained:
6136     handleNSReturnsRetainedAttr(S, D, Attr);
6137     break;
6138   case AttributeList::AT_WorkGroupSizeHint:
6139     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6140     break;
6141   case AttributeList::AT_ReqdWorkGroupSize:
6142     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6143     break;
6144   case AttributeList::AT_VecTypeHint:
6145     handleVecTypeHint(S, D, Attr);
6146     break;
6147   case AttributeList::AT_RequireConstantInit:
6148     handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6149     break;
6150   case AttributeList::AT_InitPriority:
6151     handleInitPriorityAttr(S, D, Attr);
6152     break;
6153   case AttributeList::AT_Packed:
6154     handlePackedAttr(S, D, Attr);
6155     break;
6156   case AttributeList::AT_Section:
6157     handleSectionAttr(S, D, Attr);
6158     break;
6159   case AttributeList::AT_Target:
6160     handleTargetAttr(S, D, Attr);
6161     break;
6162   case AttributeList::AT_Unavailable:
6163     handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
6164     break;
6165   case AttributeList::AT_ArcWeakrefUnavailable:
6166     handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6167     break;
6168   case AttributeList::AT_ObjCRootClass:
6169     handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6170     break;
6171   case AttributeList::AT_ObjCSubclassingRestricted:
6172     handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6173     break;
6174   case AttributeList::AT_ObjCExplicitProtocolImpl:
6175     handleObjCSuppresProtocolAttr(S, D, Attr);
6176     break;
6177   case AttributeList::AT_ObjCRequiresPropertyDefs:
6178     handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6179     break;
6180   case AttributeList::AT_Unused:
6181     handleUnusedAttr(S, D, Attr);
6182     break;
6183   case AttributeList::AT_ReturnsTwice:
6184     handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6185     break;
6186   case AttributeList::AT_NotTailCalled:
6187     handleNotTailCalledAttr(S, D, Attr);
6188     break;
6189   case AttributeList::AT_DisableTailCalls:
6190     handleDisableTailCallsAttr(S, D, Attr);
6191     break;
6192   case AttributeList::AT_Used:
6193     handleUsedAttr(S, D, Attr);
6194     break;
6195   case AttributeList::AT_Visibility:
6196     handleVisibilityAttr(S, D, Attr, false);
6197     break;
6198   case AttributeList::AT_TypeVisibility:
6199     handleVisibilityAttr(S, D, Attr, true);
6200     break;
6201   case AttributeList::AT_WarnUnused:
6202     handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6203     break;
6204   case AttributeList::AT_WarnUnusedResult:
6205     handleWarnUnusedResult(S, D, Attr);
6206     break;
6207   case AttributeList::AT_Weak:
6208     handleSimpleAttribute<WeakAttr>(S, D, Attr);
6209     break;
6210   case AttributeList::AT_WeakRef:
6211     handleWeakRefAttr(S, D, Attr);
6212     break;
6213   case AttributeList::AT_WeakImport:
6214     handleWeakImportAttr(S, D, Attr);
6215     break;
6216   case AttributeList::AT_TransparentUnion:
6217     handleTransparentUnionAttr(S, D, Attr);
6218     break;
6219   case AttributeList::AT_ObjCException:
6220     handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6221     break;
6222   case AttributeList::AT_ObjCMethodFamily:
6223     handleObjCMethodFamilyAttr(S, D, Attr);
6224     break;
6225   case AttributeList::AT_ObjCNSObject:
6226     handleObjCNSObject(S, D, Attr);
6227     break;
6228   case AttributeList::AT_ObjCIndependentClass:
6229     handleObjCIndependentClass(S, D, Attr);
6230     break;
6231   case AttributeList::AT_Blocks:
6232     handleBlocksAttr(S, D, Attr);
6233     break;
6234   case AttributeList::AT_Sentinel:
6235     handleSentinelAttr(S, D, Attr);
6236     break;
6237   case AttributeList::AT_Const:
6238     handleSimpleAttribute<ConstAttr>(S, D, Attr);
6239     break;
6240   case AttributeList::AT_Pure:
6241     handleSimpleAttribute<PureAttr>(S, D, Attr);
6242     break;
6243   case AttributeList::AT_Cleanup:
6244     handleCleanupAttr(S, D, Attr);
6245     break;
6246   case AttributeList::AT_NoDebug:
6247     handleNoDebugAttr(S, D, Attr);
6248     break;
6249   case AttributeList::AT_NoDuplicate:
6250     handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6251     break;
6252   case AttributeList::AT_Convergent:
6253     handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6254     break;
6255   case AttributeList::AT_NoInline:
6256     handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6257     break;
6258   case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6259     handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6260     break;
6261   case AttributeList::AT_StdCall:
6262   case AttributeList::AT_CDecl:
6263   case AttributeList::AT_FastCall:
6264   case AttributeList::AT_ThisCall:
6265   case AttributeList::AT_Pascal:
6266   case AttributeList::AT_RegCall:
6267   case AttributeList::AT_SwiftCall:
6268   case AttributeList::AT_VectorCall:
6269   case AttributeList::AT_MSABI:
6270   case AttributeList::AT_SysVABI:
6271   case AttributeList::AT_Pcs:
6272   case AttributeList::AT_IntelOclBicc:
6273   case AttributeList::AT_PreserveMost:
6274   case AttributeList::AT_PreserveAll:
6275     handleCallConvAttr(S, D, Attr);
6276     break;
6277   case AttributeList::AT_Suppress:
6278     handleSuppressAttr(S, D, Attr);
6279     break;
6280   case AttributeList::AT_OpenCLKernel:
6281     handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6282     break;
6283   case AttributeList::AT_OpenCLAccess:
6284     handleOpenCLAccessAttr(S, D, Attr);
6285     break;
6286   case AttributeList::AT_OpenCLNoSVM:
6287     handleOpenCLNoSVMAttr(S, D, Attr);
6288     break;
6289   case AttributeList::AT_SwiftContext:
6290     handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6291     break;
6292   case AttributeList::AT_SwiftErrorResult:
6293     handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6294     break;
6295   case AttributeList::AT_SwiftIndirectResult:
6296     handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6297     break;
6298   case AttributeList::AT_InternalLinkage:
6299     handleInternalLinkageAttr(S, D, Attr);
6300     break;
6301   case AttributeList::AT_LTOVisibilityPublic:
6302     handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6303     break;
6304
6305   // Microsoft attributes:
6306   case AttributeList::AT_EmptyBases:
6307     handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6308     break;
6309   case AttributeList::AT_LayoutVersion:
6310     handleLayoutVersion(S, D, Attr);
6311     break;
6312   case AttributeList::AT_MSNoVTable:
6313     handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6314     break;
6315   case AttributeList::AT_MSStruct:
6316     handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6317     break;
6318   case AttributeList::AT_Uuid:
6319     handleUuidAttr(S, D, Attr);
6320     break;
6321   case AttributeList::AT_MSInheritance:
6322     handleMSInheritanceAttr(S, D, Attr);
6323     break;
6324   case AttributeList::AT_SelectAny:
6325     handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6326     break;
6327   case AttributeList::AT_Thread:
6328     handleDeclspecThreadAttr(S, D, Attr);
6329     break;
6330
6331   case AttributeList::AT_AbiTag:
6332     handleAbiTagAttr(S, D, Attr);
6333     break;
6334
6335   // Thread safety attributes:
6336   case AttributeList::AT_AssertExclusiveLock:
6337     handleAssertExclusiveLockAttr(S, D, Attr);
6338     break;
6339   case AttributeList::AT_AssertSharedLock:
6340     handleAssertSharedLockAttr(S, D, Attr);
6341     break;
6342   case AttributeList::AT_GuardedVar:
6343     handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6344     break;
6345   case AttributeList::AT_PtGuardedVar:
6346     handlePtGuardedVarAttr(S, D, Attr);
6347     break;
6348   case AttributeList::AT_ScopedLockable:
6349     handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6350     break;
6351   case AttributeList::AT_NoSanitize:
6352     handleNoSanitizeAttr(S, D, Attr);
6353     break;
6354   case AttributeList::AT_NoSanitizeSpecific:
6355     handleNoSanitizeSpecificAttr(S, D, Attr);
6356     break;
6357   case AttributeList::AT_NoThreadSafetyAnalysis:
6358     handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6359     break;
6360   case AttributeList::AT_GuardedBy:
6361     handleGuardedByAttr(S, D, Attr);
6362     break;
6363   case AttributeList::AT_PtGuardedBy:
6364     handlePtGuardedByAttr(S, D, Attr);
6365     break;
6366   case AttributeList::AT_ExclusiveTrylockFunction:
6367     handleExclusiveTrylockFunctionAttr(S, D, Attr);
6368     break;
6369   case AttributeList::AT_LockReturned:
6370     handleLockReturnedAttr(S, D, Attr);
6371     break;
6372   case AttributeList::AT_LocksExcluded:
6373     handleLocksExcludedAttr(S, D, Attr);
6374     break;
6375   case AttributeList::AT_SharedTrylockFunction:
6376     handleSharedTrylockFunctionAttr(S, D, Attr);
6377     break;
6378   case AttributeList::AT_AcquiredBefore:
6379     handleAcquiredBeforeAttr(S, D, Attr);
6380     break;
6381   case AttributeList::AT_AcquiredAfter:
6382     handleAcquiredAfterAttr(S, D, Attr);
6383     break;
6384
6385   // Capability analysis attributes.
6386   case AttributeList::AT_Capability:
6387   case AttributeList::AT_Lockable:
6388     handleCapabilityAttr(S, D, Attr);
6389     break;
6390   case AttributeList::AT_RequiresCapability:
6391     handleRequiresCapabilityAttr(S, D, Attr);
6392     break;
6393
6394   case AttributeList::AT_AssertCapability:
6395     handleAssertCapabilityAttr(S, D, Attr);
6396     break;
6397   case AttributeList::AT_AcquireCapability:
6398     handleAcquireCapabilityAttr(S, D, Attr);
6399     break;
6400   case AttributeList::AT_ReleaseCapability:
6401     handleReleaseCapabilityAttr(S, D, Attr);
6402     break;
6403   case AttributeList::AT_TryAcquireCapability:
6404     handleTryAcquireCapabilityAttr(S, D, Attr);
6405     break;
6406
6407   // Consumed analysis attributes.
6408   case AttributeList::AT_Consumable:
6409     handleConsumableAttr(S, D, Attr);
6410     break;
6411   case AttributeList::AT_ConsumableAutoCast:
6412     handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6413     break;
6414   case AttributeList::AT_ConsumableSetOnRead:
6415     handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6416     break;
6417   case AttributeList::AT_CallableWhen:
6418     handleCallableWhenAttr(S, D, Attr);
6419     break;
6420   case AttributeList::AT_ParamTypestate:
6421     handleParamTypestateAttr(S, D, Attr);
6422     break;
6423   case AttributeList::AT_ReturnTypestate:
6424     handleReturnTypestateAttr(S, D, Attr);
6425     break;
6426   case AttributeList::AT_SetTypestate:
6427     handleSetTypestateAttr(S, D, Attr);
6428     break;
6429   case AttributeList::AT_TestTypestate:
6430     handleTestTypestateAttr(S, D, Attr);
6431     break;
6432
6433   // Type safety attributes.
6434   case AttributeList::AT_ArgumentWithTypeTag:
6435     handleArgumentWithTypeTagAttr(S, D, Attr);
6436     break;
6437   case AttributeList::AT_TypeTagForDatatype:
6438     handleTypeTagForDatatypeAttr(S, D, Attr);
6439     break;
6440   case AttributeList::AT_RenderScriptKernel:
6441     handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6442     break;
6443   // XRay attributes.
6444   case AttributeList::AT_XRayInstrument:
6445     handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6446     break;
6447   case AttributeList::AT_XRayLogArgs:
6448     handleXRayLogArgsAttr(S, D, Attr);
6449     break;
6450   }
6451 }
6452
6453 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6454 /// attribute list to the specified decl, ignoring any type attributes.
6455 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6456                                     const AttributeList *AttrList,
6457                                     bool IncludeCXX11Attributes) {
6458   for (const AttributeList* l = AttrList; l; l = l->getNext())
6459     ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6460
6461   // FIXME: We should be able to handle these cases in TableGen.
6462   // GCC accepts
6463   // static int a9 __attribute__((weakref));
6464   // but that looks really pointless. We reject it.
6465   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6466     Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6467       << cast<NamedDecl>(D);
6468     D->dropAttr<WeakRefAttr>();
6469     return;
6470   }
6471
6472   // FIXME: We should be able to handle this in TableGen as well. It would be
6473   // good to have a way to specify "these attributes must appear as a group",
6474   // for these. Additionally, it would be good to have a way to specify "these
6475   // attribute must never appear as a group" for attributes like cold and hot.
6476   if (!D->hasAttr<OpenCLKernelAttr>()) {
6477     // These attributes cannot be applied to a non-kernel function.
6478     if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6479       // FIXME: This emits a different error message than
6480       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6481       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6482       D->setInvalidDecl();
6483     } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6484       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6485       D->setInvalidDecl();
6486     } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6487       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6488       D->setInvalidDecl();
6489     } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6490       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6491         << A << ExpectedKernelFunction;
6492       D->setInvalidDecl();
6493     } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6494       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6495         << A << ExpectedKernelFunction;
6496       D->setInvalidDecl();
6497     } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6498       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6499         << A << ExpectedKernelFunction;
6500       D->setInvalidDecl();
6501     } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6502       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6503         << A << ExpectedKernelFunction;
6504       D->setInvalidDecl();
6505     }
6506   }
6507 }
6508
6509 // Helper for delayed proccessing TransparentUnion attribute.
6510 void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6511   for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6512     if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6513       handleTransparentUnionAttr(*this, D, *Attr);
6514       break;
6515     }
6516 }
6517
6518 // Annotation attributes are the only attributes allowed after an access
6519 // specifier.
6520 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6521                                           const AttributeList *AttrList) {
6522   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6523     if (l->getKind() == AttributeList::AT_Annotate) {
6524       ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6525     } else {
6526       Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6527       return true;
6528     }
6529   }
6530
6531   return false;
6532 }
6533
6534 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6535 /// contains any decl attributes that we should warn about.
6536 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6537   for ( ; A; A = A->getNext()) {
6538     // Only warn if the attribute is an unignored, non-type attribute.
6539     if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6540     if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6541
6542     if (A->getKind() == AttributeList::UnknownAttribute) {
6543       S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6544         << A->getName() << A->getRange();
6545     } else {
6546       S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6547         << A->getName() << A->getRange();
6548     }
6549   }
6550 }
6551
6552 /// checkUnusedDeclAttributes - Given a declarator which is not being
6553 /// used to build a declaration, complain about any decl attributes
6554 /// which might be lying around on it.
6555 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6556   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6557   ::checkUnusedDeclAttributes(*this, D.getAttributes());
6558   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6559     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6560 }
6561
6562 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6563 /// \#pragma weak needs a non-definition decl and source may not have one.
6564 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6565                                       SourceLocation Loc) {
6566   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6567   NamedDecl *NewD = nullptr;
6568   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6569     FunctionDecl *NewFD;
6570     // FIXME: Missing call to CheckFunctionDeclaration().
6571     // FIXME: Mangling?
6572     // FIXME: Is the qualifier info correct?
6573     // FIXME: Is the DeclContext correct?
6574     NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6575                                  Loc, Loc, DeclarationName(II),
6576                                  FD->getType(), FD->getTypeSourceInfo(),
6577                                  SC_None, false/*isInlineSpecified*/,
6578                                  FD->hasPrototype(),
6579                                  false/*isConstexprSpecified*/);
6580     NewD = NewFD;
6581
6582     if (FD->getQualifier())
6583       NewFD->setQualifierInfo(FD->getQualifierLoc());
6584
6585     // Fake up parameter variables; they are declared as if this were
6586     // a typedef.
6587     QualType FDTy = FD->getType();
6588     if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6589       SmallVector<ParmVarDecl*, 16> Params;
6590       for (const auto &AI : FT->param_types()) {
6591         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6592         Param->setScopeInfo(0, Params.size());
6593         Params.push_back(Param);
6594       }
6595       NewFD->setParams(Params);
6596     }
6597   } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6598     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6599                            VD->getInnerLocStart(), VD->getLocation(), II,
6600                            VD->getType(), VD->getTypeSourceInfo(),
6601                            VD->getStorageClass());
6602     if (VD->getQualifier()) {
6603       VarDecl *NewVD = cast<VarDecl>(NewD);
6604       NewVD->setQualifierInfo(VD->getQualifierLoc());
6605     }
6606   }
6607   return NewD;
6608 }
6609
6610 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6611 /// applied to it, possibly with an alias.
6612 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6613   if (W.getUsed()) return; // only do this once
6614   W.setUsed(true);
6615   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6616     IdentifierInfo *NDId = ND->getIdentifier();
6617     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6618     NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6619                                             W.getLocation()));
6620     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6621     WeakTopLevelDecl.push_back(NewD);
6622     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6623     // to insert Decl at TU scope, sorry.
6624     DeclContext *SavedContext = CurContext;
6625     CurContext = Context.getTranslationUnitDecl();
6626     NewD->setDeclContext(CurContext);
6627     NewD->setLexicalDeclContext(CurContext);
6628     PushOnScopeChains(NewD, S);
6629     CurContext = SavedContext;
6630   } else { // just add weak to existing
6631     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6632   }
6633 }
6634
6635 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6636   // It's valid to "forward-declare" #pragma weak, in which case we
6637   // have to do this.
6638   LoadExternalWeakUndeclaredIdentifiers();
6639   if (!WeakUndeclaredIdentifiers.empty()) {
6640     NamedDecl *ND = nullptr;
6641     if (VarDecl *VD = dyn_cast<VarDecl>(D))
6642       if (VD->isExternC())
6643         ND = VD;
6644     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6645       if (FD->isExternC())
6646         ND = FD;
6647     if (ND) {
6648       if (IdentifierInfo *Id = ND->getIdentifier()) {
6649         auto I = WeakUndeclaredIdentifiers.find(Id);
6650         if (I != WeakUndeclaredIdentifiers.end()) {
6651           WeakInfo W = I->second;
6652           DeclApplyPragmaWeak(S, ND, W);
6653           WeakUndeclaredIdentifiers[Id] = W;
6654         }
6655       }
6656     }
6657   }
6658 }
6659
6660 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6661 /// it, apply them to D.  This is a bit tricky because PD can have attributes
6662 /// specified in many different places, and we need to find and apply them all.
6663 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6664   // Apply decl attributes from the DeclSpec if present.
6665   if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6666     ProcessDeclAttributeList(S, D, Attrs);
6667
6668   // Walk the declarator structure, applying decl attributes that were in a type
6669   // position to the decl itself.  This handles cases like:
6670   //   int *__attr__(x)** D;
6671   // when X is a decl attribute.
6672   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6673     if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6674       ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6675
6676   // Finally, apply any attributes on the decl itself.
6677   if (const AttributeList *Attrs = PD.getAttributes())
6678     ProcessDeclAttributeList(S, D, Attrs);
6679 }
6680
6681 /// Is the given declaration allowed to use a forbidden type?
6682 /// If so, it'll still be annotated with an attribute that makes it
6683 /// illegal to actually use.
6684 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6685                                    const DelayedDiagnostic &diag,
6686                                    UnavailableAttr::ImplicitReason &reason) {
6687   // Private ivars are always okay.  Unfortunately, people don't
6688   // always properly make their ivars private, even in system headers.
6689   // Plus we need to make fields okay, too.
6690   if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6691       !isa<FunctionDecl>(decl))
6692     return false;
6693
6694   // Silently accept unsupported uses of __weak in both user and system
6695   // declarations when it's been disabled, for ease of integration with
6696   // -fno-objc-arc files.  We do have to take some care against attempts
6697   // to define such things;  for now, we've only done that for ivars
6698   // and properties.
6699   if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6700     if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6701         diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6702       reason = UnavailableAttr::IR_ForbiddenWeak;
6703       return true;
6704     }
6705   }
6706
6707   // Allow all sorts of things in system headers.
6708   if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6709     // Currently, all the failures dealt with this way are due to ARC
6710     // restrictions.
6711     reason = UnavailableAttr::IR_ARCForbiddenType;
6712     return true;
6713   }
6714
6715   return false;
6716 }
6717
6718 /// Handle a delayed forbidden-type diagnostic.
6719 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6720                                        Decl *decl) {
6721   auto reason = UnavailableAttr::IR_None;
6722   if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6723     assert(reason && "didn't set reason?");
6724     decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6725                                                   diag.Loc));
6726     return;
6727   }
6728   if (S.getLangOpts().ObjCAutoRefCount)
6729     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6730       // FIXME: we may want to suppress diagnostics for all
6731       // kind of forbidden type messages on unavailable functions. 
6732       if (FD->hasAttr<UnavailableAttr>() &&
6733           diag.getForbiddenTypeDiagnostic() == 
6734           diag::err_arc_array_param_no_ownership) {
6735         diag.Triggered = true;
6736         return;
6737       }
6738     }
6739
6740   S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6741     << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6742   diag.Triggered = true;
6743 }
6744
6745 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6746                                                   const Decl *D) {
6747   // Check each AvailabilityAttr to find the one for this platform.
6748   for (const auto *A : D->attrs()) {
6749     if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6750       // FIXME: this is copied from CheckAvailability. We should try to
6751       // de-duplicate.
6752
6753       // Check if this is an App Extension "platform", and if so chop off
6754       // the suffix for matching with the actual platform.
6755       StringRef ActualPlatform = Avail->getPlatform()->getName();
6756       StringRef RealizedPlatform = ActualPlatform;
6757       if (Context.getLangOpts().AppExt) {
6758         size_t suffix = RealizedPlatform.rfind("_app_extension");
6759         if (suffix != StringRef::npos)
6760           RealizedPlatform = RealizedPlatform.slice(0, suffix);
6761       }
6762
6763       StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6764
6765       // Match the platform name.
6766       if (RealizedPlatform == TargetPlatform)
6767         return Avail;
6768     }
6769   }
6770   return nullptr;
6771 }
6772
6773 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6774 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6775 /// in a deprecated context, but not the other way around.
6776 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6777                                                 VersionTuple DeclVersion,
6778                                                 Decl *Ctx) {
6779   assert(K != AR_Available && "Expected an unavailable declaration here!");
6780
6781   // Checks if we should emit the availability diagnostic in the context of C.
6782   auto CheckContext = [&](const Decl *C) {
6783     if (K == AR_NotYetIntroduced) {
6784       if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6785         if (AA->getIntroduced() >= DeclVersion)
6786           return true;
6787     } else if (K == AR_Deprecated)
6788       if (C->isDeprecated())
6789         return true;
6790
6791     if (C->isUnavailable())
6792       return true;
6793     return false;
6794   };
6795
6796   // FIXME: This is a temporary workaround! Some existing Apple headers depends
6797   // on nested declarations in an @interface having the availability of the
6798   // interface when they really shouldn't: they are members of the enclosing
6799   // context, and can referenced from there.
6800   if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6801     auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6802     if (CheckContext(OrigCtx))
6803       return false;
6804
6805     // An implementation implicitly has the availability of the interface.
6806     if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6807       if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6808         if (CheckContext(Interface))
6809           return false;
6810     }
6811     // A category implicitly has the availability of the interface.
6812     else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6813       if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6814         if (CheckContext(Interface))
6815           return false;
6816   }
6817
6818   do {
6819     if (CheckContext(Ctx))
6820       return false;
6821
6822     // An implementation implicitly has the availability of the interface.
6823     if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6824       if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6825         if (CheckContext(Interface))
6826           return false;
6827     }
6828     // A category implicitly has the availability of the interface.
6829     else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6830       if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6831         if (CheckContext(Interface))
6832           return false;
6833   } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6834
6835   return true;
6836 }
6837
6838 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6839                                       Decl *Ctx, const NamedDecl *D,
6840                                       StringRef Message, SourceLocation Loc,
6841                                       const ObjCInterfaceDecl *UnknownObjCClass,
6842                                       const ObjCPropertyDecl *ObjCProperty,
6843                                       bool ObjCPropertyAccess) {
6844   // Diagnostics for deprecated or unavailable.
6845   unsigned diag, diag_message, diag_fwdclass_message;
6846   unsigned diag_available_here = diag::note_availability_specified_here;
6847   SourceLocation NoteLocation = D->getLocation();
6848
6849   // Matches 'diag::note_property_attribute' options.
6850   unsigned property_note_select;
6851
6852   // Matches diag::note_availability_specified_here.
6853   unsigned available_here_select_kind;
6854
6855   VersionTuple DeclVersion;
6856   if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6857     DeclVersion = AA->getIntroduced();
6858
6859   if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6860     return;
6861
6862   switch (K) {
6863   case AR_Deprecated:
6864     diag = !ObjCPropertyAccess ? diag::warn_deprecated
6865                                : diag::warn_property_method_deprecated;
6866     diag_message = diag::warn_deprecated_message;
6867     diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6868     property_note_select = /* deprecated */ 0;
6869     available_here_select_kind = /* deprecated */ 2;
6870     if (const auto *attr = D->getAttr<DeprecatedAttr>())
6871       NoteLocation = attr->getLocation();
6872     break;
6873
6874   case AR_Unavailable:
6875     diag = !ObjCPropertyAccess ? diag::err_unavailable
6876                                : diag::err_property_method_unavailable;
6877     diag_message = diag::err_unavailable_message;
6878     diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6879     property_note_select = /* unavailable */ 1;
6880     available_here_select_kind = /* unavailable */ 0;
6881
6882     if (auto attr = D->getAttr<UnavailableAttr>()) {
6883       if (attr->isImplicit() && attr->getImplicitReason()) {
6884         // Most of these failures are due to extra restrictions in ARC;
6885         // reflect that in the primary diagnostic when applicable.
6886         auto flagARCError = [&] {
6887           if (S.getLangOpts().ObjCAutoRefCount &&
6888               S.getSourceManager().isInSystemHeader(D->getLocation()))
6889             diag = diag::err_unavailable_in_arc;
6890         };
6891
6892         switch (attr->getImplicitReason()) {
6893         case UnavailableAttr::IR_None: break;
6894
6895         case UnavailableAttr::IR_ARCForbiddenType:
6896           flagARCError();
6897           diag_available_here = diag::note_arc_forbidden_type;
6898           break;
6899
6900         case UnavailableAttr::IR_ForbiddenWeak:
6901           if (S.getLangOpts().ObjCWeakRuntime)
6902             diag_available_here = diag::note_arc_weak_disabled;
6903           else
6904             diag_available_here = diag::note_arc_weak_no_runtime;
6905           break;
6906
6907         case UnavailableAttr::IR_ARCForbiddenConversion:
6908           flagARCError();
6909           diag_available_here = diag::note_performs_forbidden_arc_conversion;
6910           break;
6911
6912         case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6913           flagARCError();
6914           diag_available_here = diag::note_arc_init_returns_unrelated;
6915           break;
6916
6917         case UnavailableAttr::IR_ARCFieldWithOwnership:
6918           flagARCError();
6919           diag_available_here = diag::note_arc_field_with_ownership;
6920           break;
6921         }
6922       }
6923     }
6924     break;
6925
6926   case AR_NotYetIntroduced:
6927     diag = diag::warn_partial_availability;
6928     diag_message = diag::warn_partial_message;
6929     diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6930     property_note_select = /* partial */ 2;
6931     available_here_select_kind = /* partial */ 3;
6932     break;
6933
6934   case AR_Available:
6935     llvm_unreachable("Warning for availability of available declaration?");
6936   }
6937
6938   CharSourceRange UseRange;
6939   StringRef Replacement;
6940   if (K == AR_Deprecated) {
6941     if (auto attr = D->getAttr<DeprecatedAttr>())
6942       Replacement = attr->getReplacement();
6943     if (auto attr = getAttrForPlatform(S.Context, D))
6944       Replacement = attr->getReplacement();
6945
6946     if (!Replacement.empty())
6947       UseRange =
6948           CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6949   }
6950
6951   if (!Message.empty()) {
6952     S.Diag(Loc, diag_message) << D << Message
6953       << (UseRange.isValid() ?
6954           FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6955     if (ObjCProperty)
6956       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6957           << ObjCProperty->getDeclName() << property_note_select;
6958   } else if (!UnknownObjCClass) {
6959     S.Diag(Loc, diag) << D
6960       << (UseRange.isValid() ?
6961           FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6962     if (ObjCProperty)
6963       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6964           << ObjCProperty->getDeclName() << property_note_select;
6965   } else {
6966     S.Diag(Loc, diag_fwdclass_message) << D
6967       << (UseRange.isValid() ?
6968           FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6969     S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6970   }
6971
6972   // The declaration can have multiple availability attributes, we are looking
6973   // at one of them.
6974   const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6975   if (A && A->isInherited()) {
6976     for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6977          Redecl = Redecl->getPreviousDecl()) {
6978       const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6979                                                               Redecl);
6980       if (AForRedecl && !AForRedecl->isInherited()) {
6981         // If D is a declaration with inherited attributes, the note should
6982         // point to the declaration with actual attributes.
6983         S.Diag(Redecl->getLocation(), diag_available_here) << D
6984             << available_here_select_kind;
6985         break;
6986       }
6987     }
6988   }
6989   else
6990     S.Diag(NoteLocation, diag_available_here)
6991         << D << available_here_select_kind;
6992
6993   if (K == AR_NotYetIntroduced)
6994     S.Diag(Loc, diag::note_partial_availability_silence) << D;
6995 }
6996
6997 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6998                                            Decl *Ctx) {
6999   assert(DD.Kind == DelayedDiagnostic::Availability &&
7000          "Expected an availability diagnostic here");
7001
7002   DD.Triggered = true;
7003   DoEmitAvailabilityWarning(
7004       S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
7005       DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
7006       DD.getObjCProperty(), false);
7007 }
7008
7009 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7010   assert(DelayedDiagnostics.getCurrentPool());
7011   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7012   DelayedDiagnostics.popWithoutEmitting(state);
7013
7014   // When delaying diagnostics to run in the context of a parsed
7015   // declaration, we only want to actually emit anything if parsing
7016   // succeeds.
7017   if (!decl) return;
7018
7019   // We emit all the active diagnostics in this pool or any of its
7020   // parents.  In general, we'll get one pool for the decl spec
7021   // and a child pool for each declarator; in a decl group like:
7022   //   deprecated_typedef foo, *bar, baz();
7023   // only the declarator pops will be passed decls.  This is correct;
7024   // we really do need to consider delayed diagnostics from the decl spec
7025   // for each of the different declarations.
7026   const DelayedDiagnosticPool *pool = &poppedPool;
7027   do {
7028     for (DelayedDiagnosticPool::pool_iterator
7029            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7030       // This const_cast is a bit lame.  Really, Triggered should be mutable.
7031       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7032       if (diag.Triggered)
7033         continue;
7034
7035       switch (diag.Kind) {
7036       case DelayedDiagnostic::Availability:
7037         // Don't bother giving deprecation/unavailable diagnostics if
7038         // the decl is invalid.
7039         if (!decl->isInvalidDecl())
7040           handleDelayedAvailabilityCheck(*this, diag, decl);
7041         break;
7042
7043       case DelayedDiagnostic::Access:
7044         HandleDelayedAccessCheck(diag, decl);
7045         break;
7046
7047       case DelayedDiagnostic::ForbiddenType:
7048         handleDelayedForbiddenType(*this, diag, decl);
7049         break;
7050       }
7051     }
7052   } while ((pool = pool->getParent()));
7053 }
7054
7055 /// Given a set of delayed diagnostics, re-emit them as if they had
7056 /// been delayed in the current context instead of in the given pool.
7057 /// Essentially, this just moves them to the current pool.
7058 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7059   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7060   assert(curPool && "re-emitting in undelayed context not supported");
7061   curPool->steal(pool);
7062 }
7063
7064 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
7065                                    NamedDecl *D, StringRef Message,
7066                                    SourceLocation Loc,
7067                                    const ObjCInterfaceDecl *UnknownObjCClass,
7068                                    const ObjCPropertyDecl  *ObjCProperty,
7069                                    bool ObjCPropertyAccess) {
7070   // Delay if we're currently parsing a declaration.
7071   if (DelayedDiagnostics.shouldDelayDiagnostics()) {
7072     DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
7073         AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
7074         ObjCPropertyAccess));
7075     return;
7076   }
7077
7078   Decl *Ctx = cast<Decl>(getCurLexicalContext());
7079   DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
7080                             ObjCProperty, ObjCPropertyAccess);
7081 }
7082
7083 namespace {
7084
7085 /// \brief This class implements -Wunguarded-availability.
7086 ///
7087 /// This is done with a traversal of the AST of a function that makes reference
7088 /// to a partially available declaration. Whenever we encounter an \c if of the
7089 /// form: \c if(@available(...)), we use the version from the condition to visit
7090 /// the then statement.
7091 class DiagnoseUnguardedAvailability
7092     : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7093   typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7094
7095   Sema &SemaRef;
7096   Decl *Ctx;
7097
7098   /// Stack of potentially nested 'if (@available(...))'s.
7099   SmallVector<VersionTuple, 8> AvailabilityStack;
7100
7101   void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7102
7103 public:
7104   DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7105       : SemaRef(SemaRef), Ctx(Ctx) {
7106     AvailabilityStack.push_back(
7107         SemaRef.Context.getTargetInfo().getPlatformMinVersion());
7108   }
7109
7110   void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7111
7112   bool TraverseIfStmt(IfStmt *If);
7113
7114   bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7115     if (ObjCMethodDecl *D = Msg->getMethodDecl())
7116       DiagnoseDeclAvailability(
7117           D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7118     return true;
7119   }
7120
7121   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7122     DiagnoseDeclAvailability(DRE->getDecl(),
7123                              SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7124     return true;
7125   }
7126
7127   bool VisitMemberExpr(MemberExpr *ME) {
7128     DiagnoseDeclAvailability(ME->getMemberDecl(),
7129                              SourceRange(ME->getLocStart(), ME->getLocEnd()));
7130     return true;
7131   }
7132
7133   bool VisitTypeLoc(TypeLoc Ty);
7134 };
7135
7136 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7137     NamedDecl *D, SourceRange Range) {
7138
7139   VersionTuple ContextVersion = AvailabilityStack.back();
7140   if (AvailabilityResult Result =
7141           SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
7142     // All other diagnostic kinds have already been handled in
7143     // DiagnoseAvailabilityOfDecl.
7144     if (Result != AR_NotYetIntroduced)
7145       return;
7146
7147     const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7148     VersionTuple Introduced = AA->getIntroduced();
7149
7150     if (ContextVersion >= Introduced)
7151       return;
7152
7153     // If the context of this function is less available than D, we should not
7154     // emit a diagnostic.
7155     if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7156       return;
7157
7158     SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7159         << Range << D
7160         << AvailabilityAttr::getPrettyPlatformName(
7161                SemaRef.getASTContext().getTargetInfo().getPlatformName())
7162         << Introduced.getAsString();
7163
7164     SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7165         << D << /* partial */ 3;
7166
7167     // FIXME: Replace this with a fixit diagnostic.
7168     SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7169         << Range << D;
7170   }
7171 }
7172
7173 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7174   const Type *TyPtr = Ty.getTypePtr();
7175   SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7176
7177   if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7178     TagDecl *TD = TT->getDecl();
7179     DiagnoseDeclAvailability(TD, Range);
7180
7181   } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7182     TypedefNameDecl *D = TD->getDecl();
7183     DiagnoseDeclAvailability(D, Range);
7184
7185   } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7186     if (NamedDecl *D = ObjCO->getInterface())
7187       DiagnoseDeclAvailability(D, Range);
7188   }
7189
7190   return true;
7191 }
7192
7193 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7194   VersionTuple CondVersion;
7195   if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7196     CondVersion = E->getVersion();
7197
7198     // If we're using the '*' case here or if this check is redundant, then we
7199     // use the enclosing version to check both branches.
7200     if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7201       return Base::TraverseStmt(If->getThen()) &&
7202              Base::TraverseStmt(If->getElse());
7203   } else {
7204     // This isn't an availability checking 'if', we can just continue.
7205     return Base::TraverseIfStmt(If);
7206   }
7207
7208   AvailabilityStack.push_back(CondVersion);
7209   bool ShouldContinue = TraverseStmt(If->getThen());
7210   AvailabilityStack.pop_back();
7211
7212   return ShouldContinue && TraverseStmt(If->getElse());
7213 }
7214
7215 } // end anonymous namespace
7216
7217 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7218   Stmt *Body = nullptr;
7219
7220   if (auto *FD = D->getAsFunction()) {
7221     // FIXME: We only examine the pattern decl for availability violations now,
7222     // but we should also examine instantiated templates.
7223     if (FD->isTemplateInstantiation())
7224       return;
7225
7226     Body = FD->getBody();
7227   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7228     Body = MD->getBody();
7229
7230   assert(Body && "Need a body here!");
7231
7232   DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
7233 }