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