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