blob: a22e167edf787bfc05ed63211b144d132c77e3a5 [file] [log] [blame]
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001//===--- 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
David Majnemer929025d2016-01-26 19:30:26 +000014#include "clang/AST/ASTConsumer.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000015#include "clang/AST/ASTContext.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "clang/AST/ASTMutationListener.h"
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +000017#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclTemplate.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000021#include "clang/AST/Expr.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000022#include "clang/AST/ExprCXX.h"
Rafael Espindoladb77c4a2013-02-26 19:13:56 +000023#include "clang/AST/Mangle.h"
Erik Pilkington5cd57172016-08-16 17:44:11 +000024#include "clang/AST/RecursiveASTVisitor.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000025#include "clang/Basic/CharInfo.h"
John McCall31168b02011-06-15 23:02:42 +000026#include "clang/Basic/SourceManager.h"
Chris Lattneracbc2d22008-06-27 22:18:37 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramer6ee15622013-09-13 15:35:43 +000028#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
John McCallb45a1e72010-08-26 02:13:20 +000030#include "clang/Sema/DelayedDiagnostic.h"
Artem Belevichbcec9da2016-06-06 22:54:57 +000031#include "clang/Sema/Initialization.h"
John McCallf1e8b342011-09-29 07:17:38 +000032#include "clang/Sema/Lookup.h"
Richard Smithe233fbf2013-01-28 22:42:45 +000033#include "clang/Sema/Scope.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000034#include "clang/Sema/SemaInternal.h"
George Burgess IV177399e2017-01-09 04:12:14 +000035#include "llvm/ADT/STLExtras.h"
Chris Lattner30ba6742009-08-10 19:03:04 +000036#include "llvm/ADT/StringExtras.h"
Hal Finkelee90a222014-09-26 05:04:30 +000037#include "llvm/Support/MathExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000038
Chris Lattner2c6fcf52008-06-26 18:38:35 +000039using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000040using namespace sema;
Chris Lattner2c6fcf52008-06-26 18:38:35 +000041
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000042namespace AttributeLangSupport {
NAKAMURA Takumi01d27f92013-11-25 00:52:29 +000043 enum LANG {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000044 C,
45 Cpp,
46 ObjC
47 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000048} // end namespace AttributeLangSupport
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000049
Chris Lattner58418ff2008-06-29 00:16:31 +000050//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
Ted Kremenek527042b2009-08-14 20:49:40 +000054/// isFunctionOrMethod - Return true if the given decl has function
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000055/// type (function or function-typed variable) or an Objective-C
56/// method.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000057static bool isFunctionOrMethod(const Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
Fariborz Jahanian4447e172009-05-15 23:15:03 +000059}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000060
David Majnemer06864812015-04-07 06:01:53 +000061/// \brief Return true if the given decl has function type (function or
62/// function-typed variable) or an Objective-C method or a block.
63static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65}
Fariborz Jahanian4447e172009-05-15 23:15:03 +000066
John McCall3882ace2011-01-05 12:14:39 +000067/// Return true if the given decl has a declarator that should have
68/// been processed by Sema::GetTypeForDeclarator.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000069static bool hasDeclarator(const Decl *D) {
John McCall31168b02011-06-15 23:02:42 +000070 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000071 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
John McCall3882ace2011-01-05 12:14:39 +000073}
74
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000075/// hasFunctionProto - Return true if the given decl has a argument
76/// information. This decl should have already passed
Fariborz Jahanian4447e172009-05-15 23:15:03 +000077/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000078static bool hasFunctionProto(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000079 if (const FunctionType *FnTy = D->getFunctionType())
Douglas Gregordeaad8c2009-02-26 23:50:07 +000080 return isa<FunctionProtoType>(FnTy);
Aaron Ballman12b9f652014-01-16 13:55:42 +000081 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000082}
83
Alp Toker601b22c2014-01-21 23:35:24 +000084/// getFunctionOrMethodNumParams - Return number of function or method
85/// parameters. It is an error to call this on a K&R function (use
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000086/// hasFunctionProto first).
Alp Toker601b22c2014-01-21 23:35:24 +000087static unsigned getFunctionOrMethodNumParams(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000088 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000089 return cast<FunctionProtoType>(FnTy)->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000090 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000091 return BD->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000092 return cast<ObjCMethodDecl>(D)->param_size();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000093}
94
Alp Toker601b22c2014-01-21 23:35:24 +000095static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000096 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000097 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
Chandler Carruthff4c4f02011-07-01 23:49:12 +000098 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000099 return BD->getParamDecl(Idx)->getType();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000100
Alp Toker03376dc2014-07-07 09:02:20 +0000101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000102}
103
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000104static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000108 return MD->parameters()[Idx]->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000109 if (const auto *BD = dyn_cast<BlockDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
112}
113
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000114static QualType getFunctionOrMethodResultType(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000115 if (const FunctionType *FnTy = D->getFunctionType())
Aaron Ballman6288d062014-07-11 16:31:29 +0000116 return cast<FunctionType>(FnTy)->getReturnType();
Alp Toker314cc812014-01-25 16:55:45 +0000117 return cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanianf1c25022009-05-20 17:41:43 +0000118}
119
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000120static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
126}
127
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000128static bool isFunctionOrMethodVariadic(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000129 if (const FunctionType *FnTy = D->getFunctionType()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000131 return proto->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000132 }
Aaron Ballmane13d0092014-08-01 17:02:34 +0000133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
135
136 return cast<ObjCMethodDecl>(D)->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000137}
138
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000139static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
Chandler Carruth743682b2010-11-16 08:35:43 +0000141 return MethodDecl->isInstance();
142 return false;
143}
144
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000145static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
John McCall9dd450b2009-09-21 23:43:11 +0000146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
Chris Lattner574dee62008-07-26 22:17:49 +0000147 if (!PT)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000148 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000149
John McCall96fa4842010-05-17 21:00:27 +0000150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
151 if (!Cls)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000152 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000153
John McCall96fa4842010-05-17 21:00:27 +0000154 IdentifierInfo* ClsName = Cls->getIdentifier();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000155
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
159}
160
Daniel Dunbar980c6692008-09-26 03:32:58 +0000161static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000162 const PointerType *PT = T->getAs<PointerType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000163 if (!PT)
164 return false;
165
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000167 if (!RT)
168 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000169
Daniel Dunbar980c6692008-09-26 03:32:58 +0000170 const RecordDecl *RD = RT->getDecl();
Abramo Bagnara6150c882010-05-11 21:36:43 +0000171 if (RD->getTagKind() != TTK_Struct)
Daniel Dunbar980c6692008-09-26 03:32:58 +0000172 return false;
173
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
175}
176
Richard Smithb87c4652013-10-31 21:23:20 +0000177static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
180}
181
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000182template <typename Compare>
183static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
185 Compare Comp) {
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
Chandler Carruthfcc48d92011-07-11 23:30:35 +0000188 return false;
189 }
190
191 return true;
192}
193
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000194/// \brief Check if the attribute has exactly as many args as Num. May
195/// output an error.
196static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
197 unsigned Num) {
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
201}
202
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000203/// \brief Check if the attribute has at least as many args as Num. May
204/// output an error.
205static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
Richard Smithb87c4652013-10-31 21:23:20 +0000206 unsigned Num) {
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
210}
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000211
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000212/// \brief Check if the attribute has at most as many args as Num. May
213/// output an error.
214static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
215 unsigned Num) {
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000219}
220
Erich Keane623efd82017-03-30 21:48:55 +0000221/// \brief A helper function to provide Attribute Location for the Attr types
222/// AND the AttributeList.
223template <typename AttrInfo>
224static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
225 SourceLocation>::type
226getAttrLoc(const AttrInfo &Attr) {
227 return Attr.getLocation();
228}
229static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
230 return Attr.getLoc();
231}
232
233/// \brief A helper function to provide Attribute Name for the Attr types
234/// AND the AttributeList.
235template <typename AttrInfo>
236static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
237 const AttrInfo *>::type
238getAttrName(const AttrInfo &Attr) {
239 return &Attr;
240}
Benjamin Kramer674d5792017-05-26 20:08:24 +0000241static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
Erich Keane623efd82017-03-30 21:48:55 +0000242 return Attr.getName();
243}
244
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000245/// \brief If Expr is a valid integer constant, get the value of the integer
246/// expression and return success or failure. May output an error.
Erich Keane623efd82017-03-30 21:48:55 +0000247template<typename AttrInfo>
248static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000250 llvm::APSInt I(32);
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
253 if (Idx != UINT_MAX)
Erich Keane623efd82017-03-30 21:48:55 +0000254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000256 << Expr->getSourceRange();
257 else
Erich Keane623efd82017-03-30 21:48:55 +0000258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000260 << Expr->getSourceRange();
261 return false;
262 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000263
264 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000267 return false;
268 }
269
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000270 Val = (uint32_t)I.getZExtValue();
271 return true;
272}
273
George Burgess IVe3763372016-12-22 02:50:20 +0000274/// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
275/// that the result will fit into a regular (signed) int. All args have the same
276/// purpose as they do in checkUInt32Argument.
Erich Keane623efd82017-03-30 21:48:55 +0000277template<typename AttrInfo>
278static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX) {
George Burgess IVe3763372016-12-22 02:50:20 +0000280 uint32_t UVal;
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
282 return false;
283
George Burgess IVa8049572016-12-22 19:00:31 +0000284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000285 llvm::APSInt I(32); // for toString
286 I = UVal;
287 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
288 << I.toString(10, false) << 32 << /* Unsigned */ 0;
289 return false;
290 }
291
292 Val = UVal;
293 return true;
294}
295
Aaron Ballmanfb763042013-12-02 18:05:46 +0000296/// \brief Diagnose mutually exclusive attributes when present on a given
297/// declaration. Returns true if diagnosed.
298template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000299static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000301 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
303 << A;
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000305 return true;
306 }
307 return false;
308}
309
Alp Toker601b22c2014-01-21 23:35:24 +0000310/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000311/// instance method D. May output an error.
312///
313/// \returns true if IdxExpr is a valid index.
Erich Keane623efd82017-03-30 21:48:55 +0000314template <typename AttrInfo>
315static bool checkFunctionOrMethodParameterIndex(
Dean Michael Berris7456a282017-06-16 03:22:09 +0000316 Sema &S, const Decl *D, const AttrInfo &Attr, unsigned AttrArgNum,
317 const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) {
David Majnemer06864812015-04-07 06:01:53 +0000318 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000319
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000325 unsigned NumParams =
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000327
328 llvm::APSInt IdxInt;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Erich Keane623efd82017-03-30 21:48:55 +0000331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000333 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000334 return false;
335 }
336
337 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000338 if (Idx < 1 || (!IV && Idx > NumParams)) {
Erich Keane623efd82017-03-30 21:48:55 +0000339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000341 return false;
342 }
343 Idx--; // Convert to zero-based.
Dean Michael Berris7456a282017-06-16 03:22:09 +0000344 if (HasImplicitThisParam && !AllowImplicitThis) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000345 if (Idx == 0) {
Erich Keane623efd82017-03-30 21:48:55 +0000346 S.Diag(getAttrLoc(Attr),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000347 diag::err_attribute_invalid_implicit_this_argument)
Erich Keane623efd82017-03-30 21:48:55 +0000348 << getAttrName(Attr) << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000349 return false;
350 }
351 --Idx;
352 }
353
354 return true;
355}
356
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000357/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
358/// If not emit an error and return false. If the argument is an identifier it
359/// will emit an error with a fixit hint and treat it as if it was a string
360/// literal.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000361bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000363 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000364 // Look for identifiers. If we have one emit a hint to fix it to a literal.
365 if (Attr.isArgIdent(ArgNum)) {
366 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000367 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000371 Str = Loc->Ident->getName();
372 if (ArgLocation)
373 *ArgLocation = Loc->Loc;
374 return true;
375 }
376
377 // Now check for an actual string literal.
378 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
379 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
380 if (ArgLocation)
381 *ArgLocation = ArgExpr->getLocStart();
382
383 if (!Literal || !Literal->isAscii()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000385 << Attr.getName() << AANT_ArgumentString;
386 return false;
387 }
388
389 Str = Literal->getString();
390 return true;
391}
392
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000393/// \brief Applies the given attribute to the Decl without performing any
394/// additional semantic checking.
395template <typename AttrType>
396static void handleSimpleAttribute(Sema &S, Decl *D,
397 const AttributeList &Attr) {
398 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
399 Attr.getAttributeSpellingListIndex()));
400}
401
Justin Lebar3eaaf862016-01-13 01:07:35 +0000402template <typename AttrType>
403static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
404 const AttributeList &Attr) {
405 handleSimpleAttribute<AttrType>(S, D, Attr);
406}
407
408/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
409/// already have one of the given incompatible attributes.
410template <typename AttrType, typename IncompatibleAttrType,
411 typename... IncompatibleAttrTypes>
412static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
413 const AttributeList &Attr) {
414 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
415 Attr.getName()))
416 return;
417 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
418 Attr);
419}
420
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000421/// \brief Check if the passed-in expression is of type int or bool.
422static bool isIntOrBool(Expr *Exp) {
423 QualType QT = Exp->getType();
424 return QT->isBooleanType() || QT->isIntegerType();
425}
426
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000427
428// Check to see if the type is a smart pointer of some kind. We assume
429// it's a smart pointer if it defines both operator-> and operator*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000430static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000433 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000434 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000435
Richard Smithcf4bdde2015-02-21 02:45:19 +0000436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000438 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000439 return false;
440
441 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000442}
443
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000444/// \brief Check if passed in Decl is a pointer type.
445/// Note that this function may produce an error message.
446/// \return true if the Decl is a pointer type; false otherwise
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000447static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000449 const ValueDecl *vd = cast<ValueDecl>(D);
450 QualType QT = vd->getType();
451 if (QT->isAnyPointerType())
452 return true;
453
454 if (const RecordType *RT = QT->getAs<RecordType>()) {
455 // If it's an incomplete type, it could be a smart pointer; skip it.
456 // (We don't want to force template instantiation if we can avoid it,
457 // since that would alter the order in which templates are instantiated.)
458 if (RT->isIncompleteType())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000459 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000460
Aaron Ballman553e6812013-12-26 14:54:11 +0000461 if (threadSafetyCheckIsSmartPointer(S, RT))
462 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000463 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000464
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000466 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000467 return false;
468}
469
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000470/// \brief Checks that the passed in QualType either is of RecordType or points
471/// to RecordType. Returns the relevant RecordType, null if it does not exit.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000472static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000474 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000475
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
479
Craig Topperc3ec1492014-05-26 06:22:03 +0000480 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000481}
482
Josh Gaob40c1772017-08-08 19:44:35 +0000483template <typename T> static bool checkRecordTypeForAttr(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000484 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000485
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000486 if (!RT)
487 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000488
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000489 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000490 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000491 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000492
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000493 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000496 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000497
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000498 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000499 RecordDecl *RD = RT->getDecl();
Josh Gaob40c1772017-08-08 19:44:35 +0000500 if (RD->hasAttr<T>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000501 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000502
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000503 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
Josh Gaob40c1772017-08-08 19:44:35 +0000508 return Type->getDecl()->hasAttr<T>();
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000509 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000510 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000511 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000512 return false;
513}
514
Josh Gaob40c1772017-08-08 19:44:35 +0000515template <typename T> static bool checkTypedefTypeForAttr(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000516 const auto *TD = Ty->getAs<TypedefType>();
517 if (!TD)
518 return false;
519
520 TypedefNameDecl *TN = TD->getDecl();
521 if (!TN)
522 return false;
523
Josh Gaob40c1772017-08-08 19:44:35 +0000524 return TN->hasAttr<T>();
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000525}
526
Josh Gaob40c1772017-08-08 19:44:35 +0000527template <typename T> static bool typeHasAttr(Sema &S, QualType Ty) {
528 if (checkTypedefTypeForAttr<T>(Ty))
Aaron Ballman76050722014-04-04 15:13:57 +0000529 return true;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000530
Josh Gaob40c1772017-08-08 19:44:35 +0000531 if (checkRecordTypeForAttr<T>(S, Ty))
Aaron Ballman76050722014-04-04 15:13:57 +0000532 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000533
Aaron Ballman76050722014-04-04 15:13:57 +0000534 return false;
535}
536
Josh Gaob40c1772017-08-08 19:44:35 +0000537static bool typeHasCapability(Sema &S, QualType Ty) {
538 return typeHasAttr<CapabilityAttr>(S, Ty);
539}
540
541static bool typeHasScopedLockable(Sema &S, QualType Ty) {
542 return typeHasAttr<ScopedLockableAttr>(S, Ty);
543}
544
Aaron Ballman76050722014-04-04 15:13:57 +0000545static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
546 // Capability expressions are simple expressions involving the boolean logic
547 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
548 // a DeclRefExpr is found, its type should be checked to determine whether it
549 // is a capability or not.
550
551 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
552 return typeHasCapability(S, E->getType());
553 else if (const auto *E = dyn_cast<CastExpr>(Ex))
554 return isCapabilityExpr(S, E->getSubExpr());
555 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
556 return isCapabilityExpr(S, E->getSubExpr());
557 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
558 if (E->getOpcode() == UO_LNot)
559 return isCapabilityExpr(S, E->getSubExpr());
560 return false;
561 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
562 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
563 return isCapabilityExpr(S, E->getLHS()) &&
564 isCapabilityExpr(S, E->getRHS());
565 return false;
566 }
567
568 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000569}
570
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000571/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
572/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000573/// \param Sidx The attribute argument index to start checking with.
574/// \param ParamIdxOk Whether an argument can be indexing into a function
575/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000576static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
577 const AttributeList &Attr,
578 SmallVectorImpl<Expr *> &Args,
579 int Sidx = 0,
580 bool ParamIdxOk = false) {
Josh Gaob40c1772017-08-08 19:44:35 +0000581 bool TriedParam = false;
582
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000583 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000584 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000585
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000586 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000587 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000588 Args.push_back(ArgExp);
589 continue;
590 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000591
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000592 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000593 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000594 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000595 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000596 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000597 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000598 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000599 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000600
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000601 // We allow constant strings to be used as a placeholder for expressions
602 // that are not valid C++ syntax, but warn that they are ignored.
603 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
604 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000605 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000606 continue;
607 }
608
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000609 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000610
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000611 // A pointer to member expression of the form &MyClass::mu is treated
612 // specially -- we need to look at the type of the member.
613 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
614 if (UOp->getOpcode() == UO_AddrOf)
615 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
616 if (DRE->getDecl()->isCXXInstanceMember())
617 ArgTy = DRE->getDecl()->getType();
618
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000619 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000620 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000621
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000622 // Now check if we index into a record type function param.
Josh Gaob40c1772017-08-08 19:44:35 +0000623 if (!RT && ParamIdxOk) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000624 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000625 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
Josh Gaob40c1772017-08-08 19:44:35 +0000626 if (FD && IL) {
627 // Don't emit free function warnings if an index was given.
628 TriedParam = true;
629
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000630 unsigned int NumParams = FD->getNumParams();
631 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000632 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
633 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
Josh Gaob40c1772017-08-08 19:44:35 +0000634 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000635 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
636 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000637 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000638 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000639 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000640 }
641 }
642
Aaron Ballman76050722014-04-04 15:13:57 +0000643 // If the type does not have a capability, see if the components of the
644 // expression have capabilities. This allows for writing C code where the
645 // capability may be on the type, and the expression is a capability
646 // boolean logic expression. Eg) requires_capability(A || B && !C)
647 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
648 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
649 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000650
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000651 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000652 }
Josh Gaob40c1772017-08-08 19:44:35 +0000653
654 // If we don't have any lockable arguments, verify that we're an instance
655 // method on a lockable type.
656 if (Args.empty() && !TriedParam) {
657 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
658 if (MD->isStatic()) {
659 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_noargs_static_method)
660 << Attr.getName();
661 return;
662 }
663
664 QualType ThisType = MD->getThisType(MD->getASTContext());
665 if (!typeHasCapability(S, ThisType) &&
666 !typeHasScopedLockable(S, ThisType)) {
667 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_noargs_not_lockable)
668 << Attr.getName() << ThisType;
669 }
670 } else {
671 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_noargs_not_method)
672 << Attr.getName();
673 }
674 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000675}
676
Chris Lattner58418ff2008-06-29 00:16:31 +0000677//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000678// Attribute Implementations
679//===----------------------------------------------------------------------===//
680
Michael Hana9171bc2012-08-03 17:40:43 +0000681static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000682 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000683 if (!threadSafetyCheckIsPointer(S, D, Attr))
684 return;
685
Michael Han99315932013-01-24 16:46:58 +0000686 D->addAttr(::new (S.Context)
687 PtGuardedVarAttr(Attr.getRange(), S.Context,
688 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000689}
690
Michael Hana9171bc2012-08-03 17:40:43 +0000691static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
692 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000693 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000694 SmallVector<Expr*, 1> Args;
695 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000696 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000697 unsigned Size = Args.size();
698 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000699 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000700
Michael Han3be3b442012-07-23 18:48:41 +0000701 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000702
Michael Han3be3b442012-07-23 18:48:41 +0000703 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000704}
705
Michael Han3be3b442012-07-23 18:48:41 +0000706static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000707 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000708 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
709 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000710
Aaron Ballman36a53502014-01-16 13:03:14 +0000711 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
712 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000713}
714
Michael Hana9171bc2012-08-03 17:40:43 +0000715static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000716 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000717 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000718 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
719 return;
720
721 if (!threadSafetyCheckIsPointer(S, D, Attr))
722 return;
723
724 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000725 S.Context, Arg,
726 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000727}
728
Michael Hana9171bc2012-08-03 17:40:43 +0000729static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
730 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000731 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000732 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000733 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000734
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000735 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000736 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000737 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
738 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
739 << Attr.getName();
740 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000741 }
742
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000743 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000744 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000745 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000746 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000747
Michael Han3be3b442012-07-23 18:48:41 +0000748 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000749}
750
Michael Hana9171bc2012-08-03 17:40:43 +0000751static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000752 const AttributeList &Attr) {
753 SmallVector<Expr*, 1> Args;
754 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
755 return;
756
757 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000758 D->addAttr(::new (S.Context)
759 AcquiredAfterAttr(Attr.getRange(), S.Context,
760 StartArg, Args.size(),
761 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000762}
763
Michael Hana9171bc2012-08-03 17:40:43 +0000764static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000765 const AttributeList &Attr) {
766 SmallVector<Expr*, 1> Args;
767 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
768 return;
769
770 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000771 D->addAttr(::new (S.Context)
772 AcquiredBeforeAttr(Attr.getRange(), S.Context,
773 StartArg, Args.size(),
774 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000775}
776
Michael Hana9171bc2012-08-03 17:40:43 +0000777static bool checkLockFunAttrCommon(Sema &S, Decl *D,
778 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000779 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000780 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000781 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000782 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000783
Michael Han3be3b442012-07-23 18:48:41 +0000784 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000785}
786
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000787static void handleAssertSharedLockAttr(Sema &S, Decl *D,
788 const AttributeList &Attr) {
789 SmallVector<Expr*, 1> Args;
790 if (!checkLockFunAttrCommon(S, D, Attr, Args))
791 return;
792
793 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000795 D->addAttr(::new (S.Context)
796 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
797 Attr.getAttributeSpellingListIndex()));
798}
799
800static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
801 const AttributeList &Attr) {
802 SmallVector<Expr*, 1> Args;
803 if (!checkLockFunAttrCommon(S, D, Attr, Args))
804 return;
805
806 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000807 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000808 D->addAttr(::new (S.Context)
809 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
810 StartArg, Size,
811 Attr.getAttributeSpellingListIndex()));
812}
813
Erich Keane623efd82017-03-30 21:48:55 +0000814/// \brief Checks to be sure that the given parameter number is in bounds, and is
815/// an integral type. Will emit appropriate diagnostics if this returns
George Burgess IVe3763372016-12-22 02:50:20 +0000816/// false.
817///
818/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
819/// to actually retrieve the argument, so it's base-0.
Erich Keane623efd82017-03-30 21:48:55 +0000820template <typename AttrInfo>
821static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
822 const AttrInfo &Attr, Expr *AttrArg,
823 unsigned FuncParamNo, unsigned AttrArgNo,
824 bool AllowDependentType = false) {
825 uint64_t Idx;
826 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
827 Idx))
828 return false;
829
830 const ParmVarDecl *Param = FD->getParamDecl(Idx);
831 if (AllowDependentType && Param->getType()->isDependentType())
832 return true;
833 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
834 SourceLocation SrcLoc = AttrArg->getLocStart();
835 S.Diag(SrcLoc, diag::err_attribute_integers_only)
836 << getAttrName(Attr) << Param->getSourceRange();
837 return false;
838 }
839 return true;
840}
841
842/// \brief Checks to be sure that the given parameter number is in bounds, and is
843/// an integral type. Will emit appropriate diagnostics if this returns false.
844///
845/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
846/// to actually retrieve the argument, so it's base-0.
George Burgess IVe3763372016-12-22 02:50:20 +0000847static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
848 const AttributeList &Attr,
Erich Keane623efd82017-03-30 21:48:55 +0000849 unsigned FuncParamNo, unsigned AttrArgNo,
850 bool AllowDependentType = false) {
George Burgess IVe3763372016-12-22 02:50:20 +0000851 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
Erich Keane623efd82017-03-30 21:48:55 +0000852 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
853 FuncParamNo, AttrArgNo, AllowDependentType);
George Burgess IVe3763372016-12-22 02:50:20 +0000854}
855
856static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
857 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
858 !checkAttributeAtMostNumArgs(S, Attr, 2))
859 return;
860
861 const auto *FD = cast<FunctionDecl>(D);
862 if (!FD->getReturnType()->isPointerType()) {
863 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
864 << Attr.getName();
865 return;
866 }
867
868 const Expr *SizeExpr = Attr.getArgAsExpr(0);
869 int SizeArgNo;
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000870 // Parameter indices are 1-indexed, hence Index=1
George Burgess IVe3763372016-12-22 02:50:20 +0000871 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
872 return;
873
874 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
875 return;
876
877 // Args are 1-indexed, so 0 implies that the arg was not present
878 int NumberArgNo = 0;
879 if (Attr.getNumArgs() == 2) {
880 const Expr *NumberExpr = Attr.getArgAsExpr(1);
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000881 // Parameter indices are 1-based, hence Index=2
George Burgess IVe3763372016-12-22 02:50:20 +0000882 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
883 /*Index=*/2))
884 return;
885
886 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
887 return;
888 }
889
890 D->addAttr(::new (S.Context) AllocSizeAttr(
891 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
892 Attr.getAttributeSpellingListIndex()));
893}
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000894
Michael Hana9171bc2012-08-03 17:40:43 +0000895static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
896 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000897 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000898 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000899 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000900
Aaron Ballman00e99962013-08-31 01:11:41 +0000901 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000902 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000903 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000904 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000905 }
906
907 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000908 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000909
Michael Han3be3b442012-07-23 18:48:41 +0000910 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000911}
912
Michael Hana9171bc2012-08-03 17:40:43 +0000913static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000914 const AttributeList &Attr) {
915 SmallVector<Expr*, 2> Args;
916 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
917 return;
918
Michael Han99315932013-01-24 16:46:58 +0000919 D->addAttr(::new (S.Context)
920 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000921 Attr.getArgAsExpr(0),
922 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000923 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000924}
925
Michael Hana9171bc2012-08-03 17:40:43 +0000926static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000927 const AttributeList &Attr) {
928 SmallVector<Expr*, 2> Args;
929 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
930 return;
931
Nico Weber462fd1e2015-01-07 23:50:05 +0000932 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
933 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
934 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000935}
936
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000937static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000938 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000939 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000940 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000941 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000942 unsigned Size = Args.size();
943 if (Size == 0)
944 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000945
Michael Han99315932013-01-24 16:46:58 +0000946 D->addAttr(::new (S.Context)
947 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
948 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000949}
950
951static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000952 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000953 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000954 return;
955
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000956 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000957 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000958 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000959 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000960 if (Size == 0)
961 return;
962 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000963
Michael Han99315932013-01-24 16:46:58 +0000964 D->addAttr(::new (S.Context)
965 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
966 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000967}
968
George Burgess IV177399e2017-01-09 04:12:14 +0000969static bool checkFunctionConditionAttr(Sema &S, Decl *D,
970 const AttributeList &Attr,
971 Expr *&Cond, StringRef &Msg) {
972 Cond = Attr.getArgAsExpr(0);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000973 if (!Cond->isTypeDependent()) {
974 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
975 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000976 return false;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000977 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000978 }
979
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000980 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
George Burgess IV177399e2017-01-09 04:12:14 +0000981 return false;
982
983 if (Msg.empty())
984 Msg = "<no message provided>";
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000985
986 SmallVector<PartialDiagnosticAt, 8> Diags;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000987 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000988 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
989 Diags)) {
George Burgess IV177399e2017-01-09 04:12:14 +0000990 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
991 << Attr.getName();
George Burgess IV0d546532016-11-10 21:47:12 +0000992 for (const PartialDiagnosticAt &PDiag : Diags)
993 S.Diag(PDiag.first, PDiag.second);
George Burgess IV177399e2017-01-09 04:12:14 +0000994 return false;
995 }
996 return true;
997}
998
999static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1000 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
1001
1002 Expr *Cond;
1003 StringRef Msg;
1004 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1005 D->addAttr(::new (S.Context)
1006 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
1007 Attr.getAttributeSpellingListIndex()));
1008}
1009
1010namespace {
1011/// Determines if a given Expr references any of the given function's
1012/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1013class ArgumentDependenceChecker
1014 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1015#ifndef NDEBUG
1016 const CXXRecordDecl *ClassType;
1017#endif
1018 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1019 bool Result;
1020
1021public:
1022 ArgumentDependenceChecker(const FunctionDecl *FD) {
1023#ifndef NDEBUG
1024 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1025 ClassType = MD->getParent();
1026 else
1027 ClassType = nullptr;
1028#endif
1029 Parms.insert(FD->param_begin(), FD->param_end());
1030 }
1031
1032 bool referencesArgs(Expr *E) {
1033 Result = false;
1034 TraverseStmt(E);
1035 return Result;
1036 }
1037
1038 bool VisitCXXThisExpr(CXXThisExpr *E) {
1039 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1040 "`this` doesn't refer to the enclosing class?");
1041 Result = true;
1042 return false;
1043 }
1044
1045 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1046 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1047 if (Parms.count(PVD)) {
1048 Result = true;
1049 return false;
1050 }
1051 return true;
1052 }
1053};
1054}
1055
1056static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1057 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1058
1059 Expr *Cond;
1060 StringRef Msg;
1061 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1062 return;
1063
1064 StringRef DiagTypeStr;
1065 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1066 return;
1067
1068 DiagnoseIfAttr::DiagnosticType DiagType;
1069 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1070 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1071 diag::err_diagnose_if_invalid_diagnostic_type);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001072 return;
1073 }
1074
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001075 bool ArgDependent = false;
Argyrios Kyrtzidis5f0c0aa2017-05-24 18:35:01 +00001076 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001077 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
George Burgess IV177399e2017-01-09 04:12:14 +00001078 D->addAttr(::new (S.Context) DiagnoseIfAttr(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001079 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D),
George Burgess IV177399e2017-01-09 04:12:14 +00001080 Attr.getAttributeSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001081}
1082
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001083static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1084 const AttributeList &Attr) {
1085 if (D->hasAttr<PassObjectSizeAttr>()) {
1086 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1087 << Attr.getName();
1088 return;
1089 }
1090
1091 Expr *E = Attr.getArgAsExpr(0);
1092 uint32_t Type;
1093 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1094 return;
1095
1096 // pass_object_size's argument is passed in as the second argument of
1097 // __builtin_object_size. So, it has the same constraints as that second
1098 // argument; namely, it must be in the range [0, 3].
1099 if (Type > 3) {
1100 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1101 << Attr.getName() << 0 << 3 << E->getSourceRange();
1102 return;
1103 }
1104
1105 // pass_object_size is only supported on constant pointer parameters; as a
1106 // kindness to users, we allow the parameter to be non-const for declarations.
1107 // At this point, we have no clue if `D` belongs to a function declaration or
1108 // definition, so we defer the constness check until later.
1109 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1110 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1111 << Attr.getName() << 1;
1112 return;
1113 }
1114
1115 D->addAttr(::new (S.Context)
1116 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1117 Attr.getAttributeSpellingListIndex()));
1118}
1119
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001120static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +00001121 ConsumableAttr::ConsumedState DefaultState;
1122
1123 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001124 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1125 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1126 DefaultState)) {
1127 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1128 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +00001129 return;
1130 }
David Blaikie16f76d22013-09-06 01:28:43 +00001131 } else {
1132 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1133 << Attr.getName() << AANT_ArgumentIdentifier;
1134 return;
1135 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001136
1137 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +00001138 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001139 Attr.getAttributeSpellingListIndex()));
1140}
1141
1142static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1143 const AttributeList &Attr) {
1144 ASTContext &CurrContext = S.getASTContext();
1145 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1146
1147 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1148 if (!RD->hasAttr<ConsumableAttr>()) {
1149 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1150 RD->getNameAsString();
1151
1152 return false;
1153 }
1154 }
1155
1156 return true;
1157}
1158
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001159static void handleCallableWhenAttr(Sema &S, Decl *D,
1160 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +00001161 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1162 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001163
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001164 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1165 return;
1166
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001167 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1168 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1169 CallableWhenAttr::ConsumedState CallableState;
1170
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001171 StringRef StateString;
1172 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +00001173 if (Attr.isArgIdent(ArgIndex)) {
1174 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1175 StateString = Ident->Ident->getName();
1176 Loc = Ident->Loc;
1177 } else {
1178 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1179 return;
1180 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001181
1182 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +00001183 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001184 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1185 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001186 return;
1187 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001188
1189 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001190 }
1191
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001192 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001193 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1194 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001195}
1196
DeLesley Hutchins69391772013-10-17 23:23:53 +00001197static void handleParamTypestateAttr(Sema &S, Decl *D,
1198 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001199 ParamTypestateAttr::ConsumedState ParamState;
1200
1201 if (Attr.isArgIdent(0)) {
1202 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1203 StringRef StateString = Ident->Ident->getName();
1204
1205 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1206 ParamState)) {
1207 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1208 << Attr.getName() << StateString;
1209 return;
1210 }
1211 } else {
1212 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1213 Attr.getName() << AANT_ArgumentIdentifier;
1214 return;
1215 }
1216
1217 // FIXME: This check is currently being done in the analysis. It can be
1218 // enabled here only after the parser propagates attributes at
1219 // template specialization definition, not declaration.
1220 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1221 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1222 //
1223 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1224 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1225 // ReturnType.getAsString();
1226 // return;
1227 //}
1228
1229 D->addAttr(::new (S.Context)
1230 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1231 Attr.getAttributeSpellingListIndex()));
1232}
1233
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001234static void handleReturnTypestateAttr(Sema &S, Decl *D,
1235 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001236 ReturnTypestateAttr::ConsumedState ReturnState;
1237
1238 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001239 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1240 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1241 ReturnState)) {
1242 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1243 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001244 return;
1245 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001246 } else {
1247 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1248 Attr.getName() << AANT_ArgumentIdentifier;
1249 return;
1250 }
1251
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001252 // FIXME: This check is currently being done in the analysis. It can be
1253 // enabled here only after the parser propagates attributes at
1254 // template specialization definition, not declaration.
1255 //QualType ReturnType;
1256 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001257 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1258 // ReturnType = Param->getType();
1259 //
1260 //} else if (const CXXConstructorDecl *Constructor =
1261 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001262 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1263 //
1264 //} else {
1265 //
1266 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1267 //}
1268 //
1269 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1270 //
1271 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1272 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1273 // ReturnType.getAsString();
1274 // return;
1275 //}
1276
1277 D->addAttr(::new (S.Context)
1278 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1279 Attr.getAttributeSpellingListIndex()));
1280}
1281
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001282static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001283 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1284 return;
1285
1286 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001287 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001288 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1289 StringRef Param = Ident->Ident->getName();
1290 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1291 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1292 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001293 return;
1294 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001295 } else {
1296 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1297 Attr.getName() << AANT_ArgumentIdentifier;
1298 return;
1299 }
1300
1301 D->addAttr(::new (S.Context)
1302 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1303 Attr.getAttributeSpellingListIndex()));
1304}
1305
Chris Wailes9385f9f2013-10-29 20:28:41 +00001306static void handleTestTypestateAttr(Sema &S, Decl *D,
1307 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001308 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1309 return;
1310
Chris Wailes9385f9f2013-10-29 20:28:41 +00001311 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001312 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001313 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1314 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001315 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001316 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1317 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001318 return;
1319 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001320 } else {
1321 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1322 Attr.getName() << AANT_ArgumentIdentifier;
1323 return;
1324 }
1325
1326 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001327 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001328 Attr.getAttributeSpellingListIndex()));
1329}
1330
Chandler Carruthedc2c642011-07-02 00:01:44 +00001331static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1332 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001333 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001334 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001335}
1336
Chandler Carruthedc2c642011-07-02 00:01:44 +00001337static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001338 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001339 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1340 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001341 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001342 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1343 !FD->getType()->isIncompleteType() &&
1344 FD->isBitField() &&
1345 S.Context.getTypeAlign(FD->getType()) <= 8);
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001346
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001347 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1348 if (BitfieldByteAligned)
1349 // The PS4 target needs to maintain ABI backwards compatibility.
1350 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1351 << Attr.getName() << FD->getType();
1352 else
1353 FD->addAttr(::new (S.Context) PackedAttr(
1354 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1355 } else {
1356 // Report warning about changed offset in the newer compiler versions.
1357 if (BitfieldByteAligned)
1358 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1359
1360 FD->addAttr(::new (S.Context) PackedAttr(
1361 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1362 }
1363
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001364 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001365 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001366}
1367
Ted Kremenek7fd17232011-09-29 07:02:25 +00001368static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1369 // The IBOutlet/IBOutletCollection attributes only apply to instance
1370 // variables or properties of Objective-C classes. The outlet must also
1371 // have an object reference type.
1372 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1373 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001374 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001375 << Attr.getName() << VD->getType() << 0;
1376 return false;
1377 }
1378 }
1379 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1380 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001381 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001382 << Attr.getName() << PD->getType() << 1;
1383 return false;
1384 }
1385 }
1386 else {
1387 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1388 return false;
1389 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001390
Ted Kremenek7fd17232011-09-29 07:02:25 +00001391 return true;
1392}
1393
Chandler Carruthedc2c642011-07-02 00:01:44 +00001394static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001395 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001396 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001397
Michael Han99315932013-01-24 16:46:58 +00001398 D->addAttr(::new (S.Context)
1399 IBOutletAttr(Attr.getRange(), S.Context,
1400 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001401}
1402
Chandler Carruthedc2c642011-07-02 00:01:44 +00001403static void handleIBOutletCollection(Sema &S, Decl *D,
1404 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001405
1406 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001407 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001408 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1409 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001410 return;
1411 }
1412
Ted Kremenek7fd17232011-09-29 07:02:25 +00001413 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001414 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001415
Richard Smithb1f9a282013-10-31 01:56:18 +00001416 ParsedType PT;
1417
1418 if (Attr.hasParsedType())
1419 PT = Attr.getTypeArg();
1420 else {
1421 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1422 S.getScopeForContext(D->getDeclContext()->getParent()));
1423 if (!PT) {
1424 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1425 return;
1426 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001427 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001428
Craig Topperc3ec1492014-05-26 06:22:03 +00001429 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001430 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1431 if (!QTLoc)
1432 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001433
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001434 // Diagnose use of non-object type in iboutletcollection attribute.
1435 // FIXME. Gnu attribute extension ignores use of builtin types in
1436 // attributes. So, __attribute__((iboutletcollection(char))) will be
1437 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001438 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001439 S.Diag(Attr.getLoc(),
1440 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1441 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001442 return;
1443 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001444
Michael Han99315932013-01-24 16:46:58 +00001445 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001446 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001447 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001448}
1449
Hal Finkelee90a222014-09-26 05:04:30 +00001450bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1451 if (RefOkay) {
1452 if (T->isReferenceType())
1453 return true;
1454 } else {
1455 T = T.getNonReferenceType();
1456 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001457
Hal Finkelee90a222014-09-26 05:04:30 +00001458 // The nonnull attribute, and other similar attributes, can be applied to a
1459 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001460 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001461 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1462 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001463 for (const auto *I : UD->fields()) {
1464 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001465 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1466 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001467 }
1468 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001469 }
1470
1471 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001472}
1473
Ted Kremenek9aedc152014-01-17 06:24:56 +00001474static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001475 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001476 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001477 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001478 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001479 if (isReturnValue)
1480 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1481 << Attr.getName() << AttrParmRange << TypeRange;
1482 else
1483 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1484 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001485 return false;
1486 }
1487 return true;
1488}
1489
Chandler Carruthedc2c642011-07-02 00:01:44 +00001490static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001491 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001492 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1493 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001494 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001495 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001496 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001497
1498 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001499 if (Idx < getFunctionOrMethodNumParams(D) &&
1500 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001501 Ex->getSourceRange(),
1502 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001503 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001504
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001505 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001506 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001507
1508 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001509 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1510 // check if the attribute came from a macro expansion or a template
1511 // instantiation.
1512 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001513 !S.inTemplateInstantiation()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001514 bool AnyPointers = isFunctionOrMethodVariadic(D);
1515 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1516 I != E && !AnyPointers; ++I) {
1517 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001518 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001519 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001520 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001521
Richard Smith588bd9b2014-08-27 04:59:42 +00001522 if (!AnyPointers)
1523 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001524 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001525
Richard Smith588bd9b2014-08-27 04:59:42 +00001526 unsigned *Start = NonNullArgs.data();
1527 unsigned Size = NonNullArgs.size();
1528 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001529 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001530 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001531 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001532}
1533
Jordan Rosec9399072014-02-11 17:27:59 +00001534static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1535 const AttributeList &Attr) {
1536 if (Attr.getNumArgs() > 0) {
1537 if (D->getFunctionType()) {
1538 handleNonNullAttr(S, D, Attr);
1539 } else {
1540 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1541 << D->getSourceRange();
1542 }
1543 return;
1544 }
1545
1546 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001547 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1548 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001549 return;
1550
1551 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001552 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001553 Attr.getAttributeSpellingListIndex()));
1554}
1555
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001556static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1557 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001558 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001559 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1560 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001561 /* isReturnValue */ true))
1562 return;
1563
1564 D->addAttr(::new (S.Context)
1565 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1566 Attr.getAttributeSpellingListIndex()));
1567}
1568
Hal Finkelee90a222014-09-26 05:04:30 +00001569static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1570 const AttributeList &Attr) {
1571 Expr *E = Attr.getArgAsExpr(0),
1572 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1573 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1574 Attr.getAttributeSpellingListIndex());
1575}
1576
Erich Keane623efd82017-03-30 21:48:55 +00001577static void handleAllocAlignAttr(Sema &S, Decl *D,
1578 const AttributeList &Attr) {
1579 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1580 Attr.getAttributeSpellingListIndex());
1581}
1582
Hal Finkelee90a222014-09-26 05:04:30 +00001583void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1584 Expr *OE, unsigned SpellingListIndex) {
1585 QualType ResultType = getFunctionOrMethodResultType(D);
1586 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1587
1588 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1589 SourceLocation AttrLoc = AttrRange.getBegin();
1590
1591 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1592 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1593 << &TmpAttr << AttrRange << SR;
1594 return;
1595 }
1596
1597 if (!E->isValueDependent()) {
1598 llvm::APSInt I(64);
1599 if (!E->isIntegerConstantExpr(I, Context)) {
1600 if (OE)
1601 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1602 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1603 << E->getSourceRange();
1604 else
1605 Diag(AttrLoc, diag::err_attribute_argument_type)
1606 << &TmpAttr << AANT_ArgumentIntegerConstant
1607 << E->getSourceRange();
1608 return;
1609 }
1610
1611 if (!I.isPowerOf2()) {
1612 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1613 << E->getSourceRange();
1614 return;
1615 }
1616 }
1617
1618 if (OE) {
1619 if (!OE->isValueDependent()) {
1620 llvm::APSInt I(64);
1621 if (!OE->isIntegerConstantExpr(I, Context)) {
1622 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1623 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1624 << OE->getSourceRange();
1625 return;
1626 }
1627 }
1628 }
1629
1630 D->addAttr(::new (Context)
1631 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1632}
1633
Erich Keane623efd82017-03-30 21:48:55 +00001634void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1635 unsigned SpellingListIndex) {
1636 QualType ResultType = getFunctionOrMethodResultType(D);
1637
1638 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1639 SourceLocation AttrLoc = AttrRange.getBegin();
1640
1641 if (!ResultType->isDependentType() &&
1642 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1643 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1644 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1645 return;
1646 }
1647
1648 uint64_t IndexVal;
1649 const auto *FuncDecl = cast<FunctionDecl>(D);
1650 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1651 /*AttrArgNo=*/1, ParamExpr,
1652 IndexVal))
1653 return;
1654
1655 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1656 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1657 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1658 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1659 return;
1660 }
1661
1662 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1663 // because that has corrected for the implicit this parameter, and is zero-
1664 // based. The attribute expects what the user wrote explicitly.
1665 llvm::APSInt Val;
1666 ParamExpr->EvaluateAsInt(Val, Context);
1667
1668 D->addAttr(::new (Context) AllocAlignAttr(
1669 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1670}
1671
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001672/// Normalize the attribute, __foo__ becomes foo.
1673/// Returns true if normalization was applied.
1674static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001675 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1676 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001677 AttrName = AttrName.drop_front(2).drop_back(2);
1678 return true;
1679 }
1680 return false;
1681}
1682
Chandler Carruthedc2c642011-07-02 00:01:44 +00001683static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001684 // This attribute must be applied to a function declaration. The first
1685 // argument to the attribute must be an identifier, the name of the resource,
1686 // for example: malloc. The following arguments must be argument indexes, the
1687 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001688 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001689 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001690 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001691
Aaron Ballman00e99962013-08-31 01:11:41 +00001692 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001693 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001694 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001695 return;
1696 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001697
Richard Smith852e9ce2013-11-27 01:46:48 +00001698 // Figure out our Kind.
1699 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001700 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001701 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001702
Richard Smith852e9ce2013-11-27 01:46:48 +00001703 // Check arguments.
1704 switch (K) {
1705 case OwnershipAttr::Takes:
1706 case OwnershipAttr::Holds:
1707 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001708 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1709 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001710 return;
1711 }
1712 break;
1713 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001714 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001715 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1716 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001717 return;
1718 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001719 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001720 }
1721
Richard Smith852e9ce2013-11-27 01:46:48 +00001722 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001723
Richard Smith852e9ce2013-11-27 01:46:48 +00001724 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001725 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001726 Module = &S.PP.getIdentifierTable().get(ModuleName);
1727 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001728
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001729 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001730 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1731 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001732 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001733 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001734 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001735
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001736 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001737 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001738 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001739 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001740 case OwnershipAttr::Takes:
1741 case OwnershipAttr::Holds:
1742 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1743 Err = 0;
1744 break;
1745 case OwnershipAttr::Returns:
1746 if (!T->isIntegerType())
1747 Err = 1;
1748 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001749 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001750 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001751 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001752 << Ex->getSourceRange();
1753 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001754 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001755
1756 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001757 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001758 // Cannot have two ownership attributes of different kinds for the same
1759 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001760 if (I->getOwnKind() != K && I->args_end() !=
1761 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001762 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001763 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001764 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001765 } else if (K == OwnershipAttr::Returns &&
1766 I->getOwnKind() == OwnershipAttr::Returns) {
1767 // A returns attribute conflicts with any other returns attribute using
1768 // a different index. Note, diagnostic reporting is 1-based, but stored
1769 // argument indexes are 0-based.
1770 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1771 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1772 << *(I->args_begin()) + 1;
1773 if (I->args_size())
1774 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1775 << (unsigned)Idx + 1 << Ex->getSourceRange();
1776 return;
1777 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001778 }
1779 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001780 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001781 }
1782
1783 unsigned* start = OwnershipArgs.data();
1784 unsigned size = OwnershipArgs.size();
1785 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001786
Michael Han99315932013-01-24 16:46:58 +00001787 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001788 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001789 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001790}
1791
Chandler Carruthedc2c642011-07-02 00:01:44 +00001792static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001793 // Check the attribute arguments.
1794 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001795 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1796 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001797 return;
1798 }
1799
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001800 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001801
Rafael Espindolac18086a2010-02-23 22:00:30 +00001802 // gcc rejects
1803 // class c {
1804 // static int a __attribute__((weakref ("v2")));
1805 // static int b() __attribute__((weakref ("f3")));
1806 // };
1807 // and ignores the attributes of
1808 // void f(void) {
1809 // static int a __attribute__((weakref ("v2")));
1810 // }
1811 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001812 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001813 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001814 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1815 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001816 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001817 }
1818
1819 // The GCC manual says
1820 //
1821 // At present, a declaration to which `weakref' is attached can only
1822 // be `static'.
1823 //
1824 // It also says
1825 //
1826 // Without a TARGET,
1827 // given as an argument to `weakref' or to `alias', `weakref' is
1828 // equivalent to `weak'.
1829 //
1830 // gcc 4.4.1 will accept
1831 // int a7 __attribute__((weakref));
1832 // as
1833 // int a7 __attribute__((weak));
1834 // This looks like a bug in gcc. We reject that for now. We should revisit
1835 // it if this behaviour is actually used.
1836
Rafael Espindolac18086a2010-02-23 22:00:30 +00001837 // GCC rejects
1838 // static ((alias ("y"), weakref)).
1839 // Should we? How to check that weakref is before or after alias?
1840
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001841 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1842 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1843 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001844 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001845 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001846 // GCC will accept anything as the argument of weakref. Should we
1847 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001848 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1849 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001850
Michael Han99315932013-01-24 16:46:58 +00001851 D->addAttr(::new (S.Context)
1852 WeakRefAttr(Attr.getRange(), S.Context,
1853 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001854}
1855
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001856static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1857 StringRef Str;
1858 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1859 return;
1860
1861 // Aliases should be on declarations, not definitions.
1862 const auto *FD = cast<FunctionDecl>(D);
1863 if (FD->isThisDeclarationADefinition()) {
1864 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1865 return;
1866 }
1867 // FIXME: it should be handled as a target specific attribute.
1868 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1869 llvm::Triple::ELF) {
1870 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1871 return;
1872 }
1873
1874 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1875 Attr.getAttributeSpellingListIndex()));
1876}
1877
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001878static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1879 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001880 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001881 return;
1882
Douglas Gregore8bbc122011-09-02 00:18:52 +00001883 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001884 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1885 return;
1886 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001887 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1888 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1889 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001890
David Majnemer2dc81462015-01-19 09:00:28 +00001891 // Aliases should be on declarations, not definitions.
1892 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1893 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001894 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001895 return;
1896 }
1897 } else {
1898 const auto *VD = cast<VarDecl>(D);
1899 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001900 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001901 return;
1902 }
1903 }
1904
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001905 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001906
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001907 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001908 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001909}
1910
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001911static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001912 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001913 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001914
Michael Han99315932013-01-24 16:46:58 +00001915 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1916 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001917}
1918
1919static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001920 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001921 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001922
Michael Han99315932013-01-24 16:46:58 +00001923 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1924 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001925}
1926
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001927static void handleTLSModelAttr(Sema &S, Decl *D,
1928 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001929 StringRef Model;
1930 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001931 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001932 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001933 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001934
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001935 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001936 if (Model != "global-dynamic" && Model != "local-dynamic"
1937 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001938 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001939 return;
1940 }
1941
Michael Han99315932013-01-24 16:46:58 +00001942 D->addAttr(::new (S.Context)
1943 TLSModelAttr(Attr.getRange(), S.Context, Model,
1944 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001945}
1946
David Majnemer631a90b2015-02-04 07:23:21 +00001947static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1948 QualType ResultType = getFunctionOrMethodResultType(D);
1949 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1950 D->addAttr(::new (S.Context) RestrictAttr(
1951 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1952 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001953 }
1954
David Majnemer631a90b2015-02-04 07:23:21 +00001955 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1956 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001957}
1958
Chandler Carruthedc2c642011-07-02 00:01:44 +00001959static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001960 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001961 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001962 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001963 return;
1964 }
1965
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001966 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1967 Attr.getAttributeSpellingListIndex()))
1968 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001969}
1970
Charles Davis0e379112016-08-08 21:19:08 +00001971static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1972 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1973 Attr.getName()))
1974 return;
1975
Saleem Abdulrasoolb51bcaf2017-04-07 15:13:47 +00001976 if (Attr.isDeclspecAttribute()) {
1977 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1978 const auto &Arch = Triple.getArch();
1979 if (Arch != llvm::Triple::x86 &&
1980 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1981 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1982 << Attr.getName() << Triple.getArchName();
1983 return;
1984 }
1985 }
1986
Charles Davis0e379112016-08-08 21:19:08 +00001987 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1988 Attr.getAttributeSpellingListIndex()));
1989}
1990
Chandler Carruthedc2c642011-07-02 00:01:44 +00001991static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001992 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001993
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001994 if (S.CheckNoReturnAttr(attr))
1995 return;
John McCall3882ace2011-01-05 12:14:39 +00001996
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001997 if (!isa<ObjCMethodDecl>(D)) {
John McCall3882ace2011-01-05 12:14:39 +00001998 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001999 << attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00002000 return;
2001 }
2002
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00002003 D->addAttr(::new (S.Context) NoReturnAttr(
2004 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
2005}
2006
2007static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D,
2008 const AttributeList &Attr) {
2009 if (S.CheckNoCallerSavedRegsAttr(Attr))
2010 return;
2011
2012 D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr(
2013 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00002014}
2015
2016bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002017 if (!checkAttributeNumArgs(*this, attr, 0)) {
John McCall3882ace2011-01-05 12:14:39 +00002018 attr.setInvalid();
2019 return true;
2020 }
2021
2022 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00002023}
2024
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00002025bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &Attr) {
2026 // Check whether the attribute is valid on the current target.
2027 if (!Attr.existsInTarget(Context.getTargetInfo())) {
2028 Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName();
2029 Attr.setInvalid();
2030 return true;
2031 }
2032
2033 if (!checkAttributeNumArgs(*this, Attr, 0)) {
2034 Attr.setInvalid();
2035 return true;
2036 }
2037
2038 return false;
2039}
2040
Chandler Carruthedc2c642011-07-02 00:01:44 +00002041static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
2042 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002043
2044 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2045 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00002046 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002047 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00002048 if (!VD || (!VD->getType()->isBlockPointerType() &&
2049 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002050 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00002051 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002052 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002053 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00002054 return;
2055 }
2056 }
2057
Michael Han99315932013-01-24 16:46:58 +00002058 D->addAttr(::new (S.Context)
2059 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2060 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002061}
2062
John Thompsoncdb847ba2010-08-09 21:53:52 +00002063// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00002064static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00002065/*
2066 Returning a Vector Class in Registers
2067
Eric Christopherbc638a82010-12-01 22:13:54 +00002068 According to the PPU ABI specifications, a class with a single member of
2069 vector type is returned in memory when used as the return value of a function.
2070 This results in inefficient code when implementing vector classes. To return
2071 the value in a single vector register, add the vecreturn attribute to the
2072 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00002073
2074 Example:
2075
2076 struct Vector
2077 {
2078 __vector float xyzw;
2079 } __attribute__((vecreturn));
2080
2081 Vector Add(Vector lhs, Vector rhs)
2082 {
2083 Vector result;
2084 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2085 return result; // This will be returned in a register
2086 }
2087*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00002088 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2089 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00002090 return;
2091 }
2092
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002093 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00002094 int count = 0;
2095
2096 if (!isa<CXXRecordDecl>(record)) {
2097 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2098 return;
2099 }
2100
2101 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2102 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2103 return;
2104 }
2105
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002106 for (const auto *I : record->fields()) {
2107 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00002108 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2109 return;
2110 }
2111 count++;
2112 }
2113
Michael Han99315932013-01-24 16:46:58 +00002114 D->addAttr(::new (S.Context)
2115 VecReturnAttr(Attr.getRange(), S.Context,
2116 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00002117}
2118
Richard Smithe233fbf2013-01-28 22:42:45 +00002119static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2120 const AttributeList &Attr) {
2121 if (isa<ParmVarDecl>(D)) {
2122 // [[carries_dependency]] can only be applied to a parameter if it is a
2123 // parameter of a function declaration or lambda.
2124 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2125 S.Diag(Attr.getLoc(),
2126 diag::err_carries_dependency_param_not_function_decl);
2127 return;
2128 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00002129 }
Richard Smithe233fbf2013-01-28 22:42:45 +00002130
2131 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2132 Attr.getRange(), S.Context,
2133 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002134}
2135
Akira Hatanakac8667622015-11-06 23:56:15 +00002136static void handleNotTailCalledAttr(Sema &S, Decl *D,
2137 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00002138 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2139 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00002140 return;
2141
2142 D->addAttr(::new (S.Context) NotTailCalledAttr(
2143 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2144}
2145
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00002146static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2147 const AttributeList &Attr) {
2148 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2149 Attr.getName()))
2150 return;
2151
2152 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2153 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2154}
2155
Chandler Carruthedc2c642011-07-02 00:01:44 +00002156static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002157 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00002158 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00002159 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002160 return;
2161 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002162 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002163 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002164 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002165 return;
2166 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002167
Michael Han99315932013-01-24 16:46:58 +00002168 D->addAttr(::new (S.Context)
2169 UsedAttr(Attr.getRange(), S.Context,
2170 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002171}
2172
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002173static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2174 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2175
2176 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2177 // The C++1z spelling of this attribute cannot be applied to a static data
2178 // member per [dcl.attr.unused]p2.
2179 if (cast<VarDecl>(D)->isStaticDataMember()) {
2180 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2181 << Attr.getName() << ExpectedForMaybeUnused;
2182 return;
2183 }
2184 }
2185
2186 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2187 // about using it as an extension.
2188 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2189 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2190
2191 D->addAttr(::new (S.Context) UnusedAttr(
2192 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2193}
2194
Chandler Carruthedc2c642011-07-02 00:01:44 +00002195static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002196 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002197 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002198 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2199 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002200
Michael Han99315932013-01-24 16:46:58 +00002201 D->addAttr(::new (S.Context)
2202 ConstructorAttr(Attr.getRange(), S.Context, priority,
2203 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002204}
2205
Chandler Carruthedc2c642011-07-02 00:01:44 +00002206static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00002207 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002208 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002209 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2210 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002211
Michael Han99315932013-01-24 16:46:58 +00002212 D->addAttr(::new (S.Context)
2213 DestructorAttr(Attr.getRange(), S.Context, priority,
2214 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002215}
2216
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002217template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00002218static void handleAttrWithMessage(Sema &S, Decl *D,
2219 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002220 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002221 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002222 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002223 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002224
Michael Han99315932013-01-24 16:46:58 +00002225 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2226 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00002227}
2228
Ted Kremenek438f8db2014-02-22 01:06:05 +00002229static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00002230 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00002231 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00002232 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2233 << Attr.getName() << Attr.getRange();
2234 return;
2235 }
2236
Ted Kremenek28eace62013-11-23 01:01:34 +00002237 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00002238 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2239 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00002240}
2241
Jordy Rose740b0c22012-05-08 03:27:22 +00002242static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2243 IdentifierInfo *Platform,
2244 VersionTuple Introduced,
2245 VersionTuple Deprecated,
2246 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002247 StringRef PlatformName
2248 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2249 if (PlatformName.empty())
2250 PlatformName = Platform->getName();
2251
2252 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2253 // of these steps are needed).
2254 if (!Introduced.empty() && !Deprecated.empty() &&
2255 !(Introduced <= Deprecated)) {
2256 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2257 << 1 << PlatformName << Deprecated.getAsString()
2258 << 0 << Introduced.getAsString();
2259 return true;
2260 }
2261
2262 if (!Introduced.empty() && !Obsoleted.empty() &&
2263 !(Introduced <= Obsoleted)) {
2264 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2265 << 2 << PlatformName << Obsoleted.getAsString()
2266 << 0 << Introduced.getAsString();
2267 return true;
2268 }
2269
2270 if (!Deprecated.empty() && !Obsoleted.empty() &&
2271 !(Deprecated <= Obsoleted)) {
2272 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2273 << 2 << PlatformName << Obsoleted.getAsString()
2274 << 1 << Deprecated.getAsString();
2275 return true;
2276 }
2277
2278 return false;
2279}
2280
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002281/// \brief Check whether the two versions match.
2282///
2283/// If either version tuple is empty, then they are assumed to match. If
2284/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2285static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2286 bool BeforeIsOkay) {
2287 if (X.empty() || Y.empty())
2288 return true;
2289
2290 if (X == Y)
2291 return true;
2292
2293 if (BeforeIsOkay && X < Y)
2294 return true;
2295
2296 return false;
2297}
2298
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002299AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002300 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00002301 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002302 VersionTuple Introduced,
2303 VersionTuple Deprecated,
2304 VersionTuple Obsoleted,
2305 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002306 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00002307 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002308 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002309 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00002310 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002311 VersionTuple MergedIntroduced = Introduced;
2312 VersionTuple MergedDeprecated = Deprecated;
2313 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002314 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002315 bool OverrideOrImpl = false;
2316 switch (AMK) {
2317 case AMK_None:
2318 case AMK_Redeclaration:
2319 OverrideOrImpl = false;
2320 break;
2321
2322 case AMK_Override:
2323 case AMK_ProtocolImplementation:
2324 OverrideOrImpl = true;
2325 break;
2326 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002327
Rafael Espindolac67f2232012-05-10 02:50:16 +00002328 if (D->hasAttrs()) {
2329 AttrVec &Attrs = D->getAttrs();
2330 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2331 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2332 if (!OldAA) {
2333 ++i;
2334 continue;
2335 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002336
Rafael Espindolac67f2232012-05-10 02:50:16 +00002337 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2338 if (OldPlatform != Platform) {
2339 ++i;
2340 continue;
2341 }
2342
Tim Northover7a73cc72015-10-30 16:30:49 +00002343 // If there is an existing availability attribute for this platform that
2344 // is explicit and the new one is implicit use the explicit one and
2345 // discard the new implicit attribute.
Manman Ren719a8642016-05-06 21:04:01 +00002346 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002347 return nullptr;
2348 }
2349
2350 // If there is an existing attribute for this platform that is implicit
2351 // and the new attribute is explicit then erase the old one and
2352 // continue processing the attributes.
Manman Ren719a8642016-05-06 21:04:01 +00002353 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002354 Attrs.erase(Attrs.begin() + i);
2355 --e;
2356 continue;
2357 }
2358
Rafael Espindolac67f2232012-05-10 02:50:16 +00002359 FoundAny = true;
2360 VersionTuple OldIntroduced = OldAA->getIntroduced();
2361 VersionTuple OldDeprecated = OldAA->getDeprecated();
2362 VersionTuple OldObsoleted = OldAA->getObsoleted();
2363 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002364
Douglas Gregord2a713e2015-09-30 21:27:42 +00002365 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2366 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2367 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002368 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002369 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2370 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002371 int Which = -1;
2372 VersionTuple FirstVersion;
2373 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002374 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002375 Which = 0;
2376 FirstVersion = OldIntroduced;
2377 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002378 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002379 Which = 1;
2380 FirstVersion = Deprecated;
2381 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002382 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002383 Which = 2;
2384 FirstVersion = Obsoleted;
2385 SecondVersion = OldObsoleted;
2386 }
2387
2388 if (Which == -1) {
2389 Diag(OldAA->getLocation(),
2390 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002391 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2392 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002393 } else {
2394 Diag(OldAA->getLocation(),
2395 diag::warn_mismatched_availability_override)
2396 << Which
2397 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002398 << FirstVersion.getAsString() << SecondVersion.getAsString()
2399 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002400 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002401 if (AMK == AMK_Override)
2402 Diag(Range.getBegin(), diag::note_overridden_method);
2403 else
2404 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002405 } else {
2406 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2407 Diag(Range.getBegin(), diag::note_previous_attribute);
2408 }
2409
Rafael Espindolac67f2232012-05-10 02:50:16 +00002410 Attrs.erase(Attrs.begin() + i);
2411 --e;
2412 continue;
2413 }
2414
2415 VersionTuple MergedIntroduced2 = MergedIntroduced;
2416 VersionTuple MergedDeprecated2 = MergedDeprecated;
2417 VersionTuple MergedObsoleted2 = MergedObsoleted;
2418
2419 if (MergedIntroduced2.empty())
2420 MergedIntroduced2 = OldIntroduced;
2421 if (MergedDeprecated2.empty())
2422 MergedDeprecated2 = OldDeprecated;
2423 if (MergedObsoleted2.empty())
2424 MergedObsoleted2 = OldObsoleted;
2425
2426 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2427 MergedIntroduced2, MergedDeprecated2,
2428 MergedObsoleted2)) {
2429 Attrs.erase(Attrs.begin() + i);
2430 --e;
2431 continue;
2432 }
2433
2434 MergedIntroduced = MergedIntroduced2;
2435 MergedDeprecated = MergedDeprecated2;
2436 MergedObsoleted = MergedObsoleted2;
2437 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002438 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002439 }
2440
2441 if (FoundAny &&
2442 MergedIntroduced == Introduced &&
2443 MergedDeprecated == Deprecated &&
2444 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002445 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002446
Douglas Gregord2a713e2015-09-30 21:27:42 +00002447 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002448 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002449 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002450 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002451 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002452 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002453 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002454 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002455 IsStrict, Replacement,
2456 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002457 Avail->setImplicit(Implicit);
2458 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002459 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002460 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002461}
2462
Chandler Carruthedc2c642011-07-02 00:01:44 +00002463static void handleAvailabilityAttr(Sema &S, Decl *D,
2464 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002465 if (!checkAttributeNumArgs(S, Attr, 1))
2466 return;
2467 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002468 unsigned Index = Attr.getAttributeSpellingListIndex();
2469
Aaron Ballman00e99962013-08-31 01:11:41 +00002470 IdentifierInfo *II = Platform->Ident;
2471 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2472 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2473 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002474
Rafael Espindolac231fab2013-01-08 21:30:32 +00002475 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Alex Lorenz472cc792017-04-20 09:35:02 +00002476 if (!ND) // We warned about this already, so just return.
Rafael Espindolac231fab2013-01-08 21:30:32 +00002477 return;
Rafael Espindolac231fab2013-01-08 21:30:32 +00002478
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002479 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2480 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2481 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002482 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002483 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002484 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002485 if (const StringLiteral *SE =
2486 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002487 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002488 StringRef Replacement;
2489 if (const StringLiteral *SE =
2490 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2491 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002492
Aaron Ballman00e99962013-08-31 01:11:41 +00002493 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002494 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002495 Introduced.Version,
2496 Deprecated.Version,
2497 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002498 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002499 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002500 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002501 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002502 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002503 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002504
2505 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2506 // matches before the start of the watchOS platform.
2507 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2508 IdentifierInfo *NewII = nullptr;
2509 if (II->getName() == "ios")
2510 NewII = &S.Context.Idents.get("watchos");
2511 else if (II->getName() == "ios_app_extension")
2512 NewII = &S.Context.Idents.get("watchos_app_extension");
2513
2514 if (NewII) {
2515 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2516 if (Version.empty())
2517 return Version;
2518 auto Major = Version.getMajor();
2519 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2520 if (NewMajor >= 2) {
2521 if (Version.getMinor().hasValue()) {
2522 if (Version.getSubminor().hasValue())
2523 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2524 Version.getSubminor().getValue());
2525 else
2526 return VersionTuple(NewMajor, Version.getMinor().getValue());
2527 }
2528 }
2529
2530 return VersionTuple(2, 0);
2531 };
2532
2533 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2534 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2535 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2536
2537 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002538 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002539 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002540 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002541 NewIntroduced,
2542 NewDeprecated,
2543 NewObsoleted,
2544 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002545 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002546 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002547 Sema::AMK_None,
2548 Index);
2549 if (NewAttr)
2550 D->addAttr(NewAttr);
2551 }
2552 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2553 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2554 // matches before the start of the tvOS platform.
2555 IdentifierInfo *NewII = nullptr;
2556 if (II->getName() == "ios")
2557 NewII = &S.Context.Idents.get("tvos");
2558 else if (II->getName() == "ios_app_extension")
2559 NewII = &S.Context.Idents.get("tvos_app_extension");
2560
2561 if (NewII) {
2562 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002563 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002564 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002565 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002566 Introduced.Version,
2567 Deprecated.Version,
2568 Obsoleted.Version,
2569 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002570 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002571 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002572 Sema::AMK_None,
2573 Index);
2574 if (NewAttr)
2575 D->addAttr(NewAttr);
2576 }
2577 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002578}
2579
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002580static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2581 const AttributeList &Attr) {
2582 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2583 return;
2584 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2585 "Invalid number of arguments in an external_source_symbol attribute");
2586
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002587 StringRef Language;
2588 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2589 Language = SE->getString();
2590 StringRef DefinedIn;
2591 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2592 DefinedIn = SE->getString();
2593 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2594
2595 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2596 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2597 Attr.getAttributeSpellingListIndex()));
2598}
2599
John McCalld041a9b2013-02-20 01:54:26 +00002600template <class T>
2601static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2602 typename T::VisibilityType value,
2603 unsigned attrSpellingListIndex) {
2604 T *existingAttr = D->getAttr<T>();
2605 if (existingAttr) {
2606 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2607 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002608 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002609 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2610 S.Diag(range.getBegin(), diag::note_previous_attribute);
2611 D->dropAttr<T>();
2612 }
2613 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2614}
2615
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002616VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002617 VisibilityAttr::VisibilityType Vis,
2618 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002619 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2620 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002621}
2622
John McCalld041a9b2013-02-20 01:54:26 +00002623TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2624 TypeVisibilityAttr::VisibilityType Vis,
2625 unsigned AttrSpellingListIndex) {
2626 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2627 AttrSpellingListIndex);
2628}
2629
2630static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2631 bool isTypeVisibility) {
2632 // Visibility attributes don't mean anything on a typedef.
2633 if (isa<TypedefNameDecl>(D)) {
2634 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2635 << Attr.getName();
2636 return;
2637 }
2638
2639 // 'type_visibility' can only go on a type or namespace.
2640 if (isTypeVisibility &&
2641 !(isa<TagDecl>(D) ||
2642 isa<ObjCInterfaceDecl>(D) ||
2643 isa<NamespaceDecl>(D))) {
2644 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2645 << Attr.getName() << ExpectedTypeOrNamespace;
2646 return;
2647 }
2648
Benjamin Kramer70370212013-09-09 15:08:57 +00002649 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002650 StringRef TypeStr;
2651 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002652 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002653 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002654
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002655 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002656 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002657 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002658 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002659 return;
2660 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002661
2662 // Complain about attempts to use protected visibility on targets
2663 // (like Darwin) that don't support it.
2664 if (type == VisibilityAttr::Protected &&
2665 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2666 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2667 type = VisibilityAttr::Default;
2668 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002669
Michael Han99315932013-01-24 16:46:58 +00002670 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002671 clang::Attr *newAttr;
2672 if (isTypeVisibility) {
2673 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2674 (TypeVisibilityAttr::VisibilityType) type,
2675 Index);
2676 } else {
2677 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2678 }
2679 if (newAttr)
2680 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002681}
2682
Chandler Carruthedc2c642011-07-02 00:01:44 +00002683static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2684 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002685 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002686 if (!Attr.isArgIdent(0)) {
2687 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2688 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002689 return;
2690 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002691
Aaron Ballman682ee422013-09-11 19:47:58 +00002692 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2693 ObjCMethodFamilyAttr::FamilyKind F;
2694 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2695 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2696 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002697 return;
2698 }
2699
Alp Toker314cc812014-01-25 16:55:45 +00002700 if (F == ObjCMethodFamilyAttr::OMF_init &&
2701 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002702 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002703 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002704 // Ignore the attribute.
2705 return;
2706 }
2707
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002708 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002709 S.Context, F,
2710 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002711}
2712
Chandler Carruthedc2c642011-07-02 00:01:44 +00002713static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002714 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002715 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002716 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002717 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2718 return;
2719 }
2720 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002721 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2722 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002723 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002724 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2725 return;
2726 }
2727 }
2728 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002729 // It is okay to include this attribute on properties, e.g.:
2730 //
2731 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2732 //
2733 // In this case it follows tradition and suppresses an error in the above
2734 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002735 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002736 }
Michael Han99315932013-01-24 16:46:58 +00002737 D->addAttr(::new (S.Context)
2738 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2739 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002740}
2741
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002742static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2743 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2744 QualType T = TD->getUnderlyingType();
2745 if (!T->isObjCObjectPointerType()) {
2746 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2747 return;
2748 }
2749 } else {
2750 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2751 return;
2752 }
2753 D->addAttr(::new (S.Context)
2754 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2755 Attr.getAttributeSpellingListIndex()));
2756}
2757
Chandler Carruthedc2c642011-07-02 00:01:44 +00002758static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002759 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002760 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002761 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002762 return;
2763 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002764
Aaron Ballman00e99962013-08-31 01:11:41 +00002765 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002766 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002767 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2768 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2769 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002770 return;
2771 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002772
Michael Han99315932013-01-24 16:46:58 +00002773 D->addAttr(::new (S.Context)
2774 BlocksAttr(Attr.getRange(), S.Context, type,
2775 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002776}
2777
Chandler Carruthedc2c642011-07-02 00:01:44 +00002778static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002779 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002780 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002781 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002782 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002783 if (E->isTypeDependent() || E->isValueDependent() ||
2784 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002785 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002786 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002787 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002788 return;
2789 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002790
John McCallb46f2872011-09-09 07:56:05 +00002791 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002792 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2793 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002794 return;
2795 }
John McCallb46f2872011-09-09 07:56:05 +00002796
2797 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002798 }
2799
Aaron Ballman18a78382013-11-21 00:28:23 +00002800 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002801 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002802 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002803 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002804 if (E->isTypeDependent() || E->isValueDependent() ||
2805 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002806 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002807 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002808 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002809 return;
2810 }
2811 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002812
John McCallb46f2872011-09-09 07:56:05 +00002813 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002814 // FIXME: This error message could be improved, it would be nice
2815 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002816 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2817 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002818 return;
2819 }
2820 }
2821
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002822 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002823 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002824 if (isa<FunctionNoProtoType>(FT)) {
2825 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2826 return;
2827 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002828
Chris Lattner9363e312009-03-17 23:03:47 +00002829 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002830 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002831 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002832 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002833 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002834 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002835 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002836 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002837 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002838 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2839 if (!BD->isVariadic()) {
2840 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2841 return;
2842 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002843 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002844 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002845 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002846 const FunctionType *FT = Ty->isFunctionPointerType()
2847 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002848 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002849 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002850 int m = Ty->isFunctionPointerType() ? 0 : 1;
2851 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002852 return;
2853 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002854 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002855 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002856 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002857 return;
2858 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002859 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002860 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002861 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002862 return;
2863 }
Michael Han99315932013-01-24 16:46:58 +00002864 D->addAttr(::new (S.Context)
2865 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2866 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002867}
2868
Chandler Carruthedc2c642011-07-02 00:01:44 +00002869static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002870 if (D->getFunctionType() &&
2871 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002872 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2873 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002874 return;
2875 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002876 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002877 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002878 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2879 << Attr.getName() << 1;
2880 return;
2881 }
2882
Aaron Ballmane7964782016-03-07 22:44:55 +00002883 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2884 // about using it as an extension.
2885 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2886 !Attr.getScopeName())
Richard Smith4f902c72016-03-08 00:32:55 +00002887 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002888
Michael Han99315932013-01-24 16:46:58 +00002889 D->addAttr(::new (S.Context)
2890 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2891 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002892}
2893
Chandler Carruthedc2c642011-07-02 00:01:44 +00002894static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002895 // weak_import only applies to variable & function declarations.
2896 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002897 if (!D->canBeWeakImported(isDef)) {
2898 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002899 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2900 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002901 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002902 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002903 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002904 // Nothing to warn about here.
2905 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002906 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002907 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002908
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002909 return;
2910 }
2911
Michael Han99315932013-01-24 16:46:58 +00002912 D->addAttr(::new (S.Context)
2913 WeakImportAttr(Attr.getRange(), S.Context,
2914 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002915}
2916
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002917// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002918template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002919static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002920 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002921 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002922 for (unsigned i = 0; i < 3; ++i) {
2923 const Expr *E = Attr.getArgAsExpr(i);
2924 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002925 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002926 if (WGSize[i] == 0) {
2927 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2928 << Attr.getName() << E->getSourceRange();
2929 return;
2930 }
2931 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002932
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002933 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2934 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2935 Existing->getYDim() == WGSize[1] &&
2936 Existing->getZDim() == WGSize[2]))
2937 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002938
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002939 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2940 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002941 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002942}
2943
Xiuli Panbe6da4b2017-05-04 07:31:20 +00002944// Handles intel_reqd_sub_group_size.
2945static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) {
2946 uint32_t SGSize;
2947 const Expr *E = Attr.getArgAsExpr(0);
2948 if (!checkUInt32Argument(S, Attr, E, SGSize))
2949 return;
2950 if (SGSize == 0) {
2951 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2952 << Attr.getName() << E->getSourceRange();
2953 return;
2954 }
2955
2956 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2957 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2958 if (Existing && Existing->getSubGroupSize() != SGSize)
2959 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2960
2961 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2962 Attr.getRange(), S.Context, SGSize,
2963 Attr.getAttributeSpellingListIndex()));
2964}
2965
Joey Goulyaba589c2013-03-08 09:42:32 +00002966static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002967 if (!Attr.hasParsedType()) {
2968 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2969 << Attr.getName() << 1;
2970 return;
2971 }
2972
Craig Topperc3ec1492014-05-26 06:22:03 +00002973 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002974 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2975 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002976
2977 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2978 (ParmType->isBooleanType() ||
2979 !ParmType->isIntegralType(S.getASTContext()))) {
2980 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2981 << ParmType;
2982 return;
2983 }
2984
Aaron Ballmana9e05402013-12-02 22:16:55 +00002985 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002986 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002987 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2988 return;
2989 }
2990 }
2991
2992 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002993 ParmTSI,
2994 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002995}
2996
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002997SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002998 StringRef Name,
2999 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00003000 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3001 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00003002 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00003003 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
3004 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00003005 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00003006 }
Michael Han99315932013-01-24 16:46:58 +00003007 return ::new (Context) SectionAttr(Range, Context, Name,
3008 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00003009}
3010
Reid Kleckner2a133222015-03-04 23:39:17 +00003011bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3012 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
3013 if (!Error.empty()) {
3014 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
3015 return false;
3016 }
3017 return true;
3018}
3019
Chandler Carruthedc2c642011-07-02 00:01:44 +00003020static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00003021 // Make sure that there is a string literal as the sections's single
3022 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003023 StringRef Str;
3024 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003025 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00003026 return;
Mike Stump11289f42009-09-09 15:08:12 +00003027
Reid Kleckner2a133222015-03-04 23:39:17 +00003028 if (!S.checkSectionName(LiteralLoc, Str))
3029 return;
3030
Chris Lattner30ba6742009-08-10 19:03:04 +00003031 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003032 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00003033 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003034 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00003035 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00003036 return;
3037 }
Mike Stump11289f42009-09-09 15:08:12 +00003038
Michael Han99315932013-01-24 16:46:58 +00003039 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003040 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003041 if (NewAttr)
3042 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00003043}
3044
Erich Keane57e15cd2017-07-19 22:06:33 +00003045// Check for things we'd like to warn about. Multiversioning issues are
3046// handled later in the process, once we know how many exist.
3047bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3048 enum FirstParam { Unsupported, Duplicate };
3049 enum SecondParam { None, Architecture };
Eric Christopher789a7ad2015-06-12 01:36:05 +00003050 for (auto Str : {"tune=", "fpmath="})
3051 if (AttrStr.find(Str) != StringRef::npos)
Erich Keane57e15cd2017-07-19 22:06:33 +00003052 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3053 << Unsupported << None << Str;
3054
3055 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3056
3057 if (!ParsedAttrs.Architecture.empty() &&
3058 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3059 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3060 << Unsupported << Architecture << ParsedAttrs.Architecture;
3061
3062 if (ParsedAttrs.DuplicateArchitecture)
3063 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3064 << Duplicate << None << "arch=";
3065
3066 for (const auto &Feature : ParsedAttrs.Features) {
3067 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3068 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3069 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3070 << Unsupported << None << CurFeature;
3071 }
3072
3073 return true;
Eric Christopher789a7ad2015-06-12 01:36:05 +00003074}
3075
Eric Christopher11acf732015-06-12 01:35:52 +00003076static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00003077 StringRef Str;
3078 SourceLocation LiteralLoc;
Erich Keane57e15cd2017-07-19 22:06:33 +00003079 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) ||
3080 !S.checkTargetAttr(LiteralLoc, Str))
Eric Christopher11acf732015-06-12 01:35:52 +00003081 return;
3082 unsigned Index = Attr.getAttributeSpellingListIndex();
3083 TargetAttr *NewAttr =
3084 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
3085 D->addAttr(NewAttr);
3086}
3087
Chandler Carruthedc2c642011-07-02 00:01:44 +00003088static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003089 VarDecl *VD = cast<VarDecl>(D);
3090 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003091 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003092 return;
3093 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003094
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003095 Expr *E = Attr.getArgAsExpr(0);
3096 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00003097 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003098 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00003099
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003100 // gcc only allows for simple identifiers. Since we support more than gcc, we
3101 // will warn the user.
3102 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3103 if (DRE->hasQualifier())
3104 S.Diag(Loc, diag::warn_cleanup_ext);
3105 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3106 NI = DRE->getNameInfo();
3107 if (!FD) {
3108 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3109 << NI.getName();
3110 return;
3111 }
3112 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3113 if (ULE->hasExplicitTemplateArgs())
3114 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003115 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3116 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00003117 if (!FD) {
3118 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3119 << NI.getName();
3120 if (ULE->getType() == S.Context.OverloadTy)
3121 S.NoteAllOverloadCandidates(ULE);
3122 return;
3123 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003124 } else {
3125 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00003126 return;
3127 }
3128
Anders Carlssond277d792009-01-31 01:16:18 +00003129 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003130 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3131 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003132 return;
3133 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003134
Anders Carlsson723f55d2009-02-07 23:16:50 +00003135 // We're currently more strict than GCC about what function types we accept.
3136 // If this ever proves to be a problem it should be easy to fix.
3137 QualType Ty = S.Context.getPointerType(VD->getType());
3138 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00003139 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3140 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003141 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3142 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00003143 return;
3144 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003145
Michael Han99315932013-01-24 16:46:58 +00003146 D->addAttr(::new (S.Context)
3147 CleanupAttr(Attr.getRange(), S.Context, FD,
3148 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00003149}
3150
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003151static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3152 const AttributeList &Attr) {
3153 if (!Attr.isArgIdent(0)) {
3154 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3155 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3156 return;
3157 }
3158
3159 EnumExtensibilityAttr::Kind ExtensibilityKind;
3160 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3161 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3162 ExtensibilityKind)) {
3163 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3164 << Attr.getName() << II;
3165 return;
3166 }
3167
3168 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3169 Attr.getRange(), S.Context, ExtensibilityKind,
3170 Attr.getAttributeSpellingListIndex()));
3171}
3172
Mike Stumpd3bb5572009-07-24 19:02:52 +00003173/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00003174/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003175static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003176 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00003177 uint64_t Idx;
3178 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003179 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00003180
Eric Christopherb64963e2015-08-13 21:34:35 +00003181 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00003182 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003183
Eric Christopherb64963e2015-08-13 21:34:35 +00003184 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3185 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003186 !isCFStringType(Ty, S.Context) &&
3187 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003188 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003189 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003190 << "a string type" << IdxExpr->getSourceRange()
3191 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003192 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003193 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003194 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003195 if (!isNSStringType(Ty, S.Context) &&
3196 !isCFStringType(Ty, S.Context) &&
3197 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003198 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003199 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003200 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00003201 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003202 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003203 }
3204
Alp Toker601b22c2014-01-21 23:35:24 +00003205 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003206 // because that has corrected for the implicit this parameter, and is zero-
3207 // based. The attribute expects what the user wrote explicitly.
3208 llvm::APSInt Val;
3209 IdxExpr->EvaluateAsInt(Val, S.Context);
3210
Michael Han99315932013-01-24 16:46:58 +00003211 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003212 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00003213 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003214}
3215
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003216enum FormatAttrKind {
3217 CFStringFormat,
3218 NSStringFormat,
3219 StrftimeFormat,
3220 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00003221 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003222 InvalidFormat
3223};
3224
3225/// getFormatAttrKind - Map from format attribute names to supported format
3226/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003227static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00003228 return llvm::StringSwitch<FormatAttrKind>(Format)
Mehdi Amini06d367c2016-10-24 20:39:34 +00003229 // Check for formats that get handled specially.
3230 .Case("NSString", NSStringFormat)
3231 .Case("CFString", CFStringFormat)
3232 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003233
Mehdi Amini06d367c2016-10-24 20:39:34 +00003234 // Otherwise, check for supported formats.
3235 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3236 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3237 .Case("kprintf", SupportedFormat) // OpenBSD.
3238 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3239 .Case("os_trace", SupportedFormat)
3240 .Case("os_log", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003241
Mehdi Amini06d367c2016-10-24 20:39:34 +00003242 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3243 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003244}
3245
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003246/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003247/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003248static void handleInitPriorityAttr(Sema &S, Decl *D,
3249 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003250 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003251 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3252 return;
3253 }
3254
Aaron Ballman4a611152013-11-27 16:34:09 +00003255 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003256 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3257 Attr.setInvalid();
3258 return;
3259 }
Aaron Ballman4a611152013-11-27 16:34:09 +00003260 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003261 if (S.Context.getAsArrayType(T))
3262 T = S.Context.getBaseElementType(T);
3263 if (!T->getAs<RecordType>()) {
3264 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3265 Attr.setInvalid();
3266 return;
3267 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003268
3269 Expr *E = Attr.getArgAsExpr(0);
3270 uint32_t prioritynum;
3271 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003272 Attr.setInvalid();
3273 return;
3274 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003275
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003276 if (prioritynum < 101 || prioritynum > 65535) {
3277 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003278 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003279 Attr.setInvalid();
3280 return;
3281 }
Michael Han99315932013-01-24 16:46:58 +00003282 D->addAttr(::new (S.Context)
3283 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3284 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003285}
3286
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003287FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3288 IdentifierInfo *Format, int FormatIdx,
3289 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003290 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003291 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003292 for (auto *F : D->specific_attrs<FormatAttr>()) {
3293 if (F->getType() == Format &&
3294 F->getFormatIdx() == FormatIdx &&
3295 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003296 // If we don't have a valid location for this attribute, adopt the
3297 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003298 if (F->getLocation().isInvalid())
3299 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00003300 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00003301 }
3302 }
3303
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003304 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3305 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00003306}
3307
Mike Stumpd3bb5572009-07-24 19:02:52 +00003308/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003309/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003310static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003311 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00003312 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00003313 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003314 return;
3315 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003316
Chandler Carruth743682b2010-11-16 08:35:43 +00003317 // In C++ the implicit 'this' function parameter also counts, and they are
3318 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003319 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00003320 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003321
Aaron Ballman00e99962013-08-31 01:11:41 +00003322 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3323 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003324
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00003325 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003326 // If we've modified the string name, we need a new identifier for it.
3327 II = &S.Context.Idents.get(Format);
3328 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003329
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003330 // Check for supported formats.
3331 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00003332
3333 if (Kind == IgnoredFormat)
3334 return;
3335
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003336 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00003337 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00003338 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003339 return;
3340 }
3341
3342 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003343 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003344 uint32_t Idx;
3345 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003346 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003347
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003348 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003349 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003350 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003351 return;
3352 }
3353
3354 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003355 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003356
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003357 if (HasImplicitThisParam) {
3358 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00003359 S.Diag(Attr.getLoc(),
3360 diag::err_format_attribute_implicit_this_format_string)
3361 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003362 return;
3363 }
3364 ArgIdx--;
3365 }
Mike Stump11289f42009-09-09 15:08:12 +00003366
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003367 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00003368 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003369
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003370 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00003371 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003372 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003373 << "a CFString" << IdxExpr->getSourceRange()
3374 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00003375 return;
3376 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003377 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003378 // FIXME: do we need to check if the type is NSString*? What are the
3379 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00003380 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003381 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003382 << "an NSString" << IdxExpr->getSourceRange()
3383 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003384 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003385 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003386 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003387 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003388 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003389 << "a string type" << IdxExpr->getSourceRange()
3390 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003391 return;
3392 }
3393
3394 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003395 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003396 uint32_t FirstArg;
3397 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003398 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003399
3400 // check if the function is variadic if the 3rd argument non-zero
3401 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003402 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003403 ++NumArgs; // +1 for ...
3404 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003405 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003406 return;
3407 }
3408 }
3409
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003410 // strftime requires FirstArg to be 0 because it doesn't read from any
3411 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003412 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003413 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00003414 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3415 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003416 return;
3417 }
3418 // if 0 it disables parameter checking (to use with e.g. va_list)
3419 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003420 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003421 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003422 return;
3423 }
3424
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003425 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003426 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003427 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003428 if (NewAttr)
3429 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003430}
3431
Chandler Carruthedc2c642011-07-02 00:01:44 +00003432static void handleTransparentUnionAttr(Sema &S, Decl *D,
3433 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003434 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003435 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003436 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003437 if (TD && TD->getUnderlyingType()->isUnionType())
3438 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3439 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003440 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003441
3442 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003443 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003444 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003445 return;
3446 }
3447
John McCallf937c022011-10-07 06:10:15 +00003448 if (!RD->isCompleteDefinition()) {
Erich Keane2fe684b2017-02-28 20:44:39 +00003449 if (!RD->isBeingDefined())
3450 S.Diag(Attr.getLoc(),
3451 diag::warn_transparent_union_attribute_not_definition);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003452 return;
3453 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003454
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003455 RecordDecl::field_iterator Field = RD->field_begin(),
3456 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003457 if (Field == FieldEnd) {
3458 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3459 return;
3460 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003461
David Blaikie40ed2972012-06-06 20:45:41 +00003462 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003463 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003464 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003465 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003466 diag::warn_transparent_union_attribute_floating)
3467 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003468 return;
3469 }
3470
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003471 if (FirstType->isIncompleteType())
3472 return;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003473 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3474 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3475 for (; Field != FieldEnd; ++Field) {
3476 QualType FieldType = Field->getType();
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003477 if (FieldType->isIncompleteType())
3478 return;
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003479 // FIXME: this isn't fully correct; we also need to test whether the
3480 // members of the union would all have the same calling convention as the
3481 // first member of the union. Checking just the size and alignment isn't
3482 // sufficient (consider structs passed on the stack instead of in registers
3483 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003484 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003485 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003486 // Warn if we drop the attribute.
3487 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003488 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003489 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003490 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003491 diag::warn_transparent_union_attribute_field_size_align)
3492 << isSize << Field->getDeclName() << FieldBits;
3493 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003494 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003495 diag::note_transparent_union_first_field_size_align)
3496 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003497 return;
3498 }
3499 }
3500
Michael Han99315932013-01-24 16:46:58 +00003501 RD->addAttr(::new (S.Context)
3502 TransparentUnionAttr(Attr.getRange(), S.Context,
3503 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003504}
3505
Chandler Carruthedc2c642011-07-02 00:01:44 +00003506static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003507 // Make sure that there is a string literal as the annotation's single
3508 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003509 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003510 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003511 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003512
3513 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003514 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3515 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003516 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003517 }
Michael Han99315932013-01-24 16:46:58 +00003518
3519 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003520 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003521 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003522}
3523
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003524static void handleAlignValueAttr(Sema &S, Decl *D,
3525 const AttributeList &Attr) {
3526 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3527 Attr.getAttributeSpellingListIndex());
3528}
3529
3530void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3531 unsigned SpellingListIndex) {
3532 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3533 SourceLocation AttrLoc = AttrRange.getBegin();
3534
3535 QualType T;
3536 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3537 T = TD->getUnderlyingType();
3538 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3539 T = VD->getType();
3540 else
3541 llvm_unreachable("Unknown decl type for align_value");
3542
3543 if (!T->isDependentType() && !T->isAnyPointerType() &&
3544 !T->isReferenceType() && !T->isMemberPointerType()) {
3545 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3546 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3547 return;
3548 }
3549
3550 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003551 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003552 ExprResult ICE
3553 = VerifyIntegerConstantExpression(E, &Alignment,
3554 diag::err_align_value_attribute_argument_not_int,
3555 /*AllowFold*/ false);
3556 if (ICE.isInvalid())
3557 return;
3558
3559 if (!Alignment.isPowerOf2()) {
3560 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3561 << E->getSourceRange();
3562 return;
3563 }
3564
3565 D->addAttr(::new (Context)
3566 AlignValueAttr(AttrRange, Context, ICE.get(),
3567 SpellingListIndex));
3568 return;
3569 }
3570
3571 // Save dependent expressions in the AST to be instantiated.
3572 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003573}
3574
Chandler Carruthedc2c642011-07-02 00:01:44 +00003575static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003576 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003577 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003578 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3579 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003580 return;
3581 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003582
Richard Smith848e1f12013-02-01 08:12:08 +00003583 if (Attr.getNumArgs() == 0) {
3584 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003585 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003586 return;
3587 }
3588
Aaron Ballman00e99962013-08-31 01:11:41 +00003589 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003590 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3591 S.Diag(Attr.getEllipsisLoc(),
3592 diag::err_pack_expansion_without_parameter_packs);
3593 return;
3594 }
3595
3596 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3597 return;
3598
David Majnemer26a1e0e2015-04-07 02:37:09 +00003599 if (E->isValueDependent()) {
3600 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3601 if (!TND->getUnderlyingType()->isDependentType()) {
3602 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3603 << E->getSourceRange();
3604 return;
3605 }
3606 }
3607 }
3608
Richard Smith44c247f2013-02-22 08:32:16 +00003609 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3610 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003611}
3612
3613void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003614 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003615 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3616 SourceLocation AttrLoc = AttrRange.getBegin();
3617
Richard Smith1dba27c2013-01-29 09:02:09 +00003618 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003619 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003620 // C++11 [dcl.align]p1:
3621 // An alignment-specifier may be applied to a variable or to a class
3622 // data member, but it shall not be applied to a bit-field, a function
3623 // parameter, the formal parameter of a catch clause, or a variable
3624 // declared with the register storage class specifier. An
3625 // alignment-specifier may also be applied to the declaration of a class
3626 // or enumeration type.
3627 // C11 6.7.5/2:
3628 // An alignment attribute shall not be specified in a declaration of
3629 // a typedef, or a bit-field, or a function, or a parameter, or an
3630 // object declared with the register storage-class specifier.
3631 int DiagKind = -1;
3632 if (isa<ParmVarDecl>(D)) {
3633 DiagKind = 0;
3634 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3635 if (VD->getStorageClass() == SC_Register)
3636 DiagKind = 1;
3637 if (VD->isExceptionVariable())
3638 DiagKind = 2;
3639 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3640 if (FD->isBitField())
3641 DiagKind = 3;
3642 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003643 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003644 << (TmpAttr.isC11() ? ExpectedVariableOrField
3645 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003646 return;
3647 }
3648 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003649 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003650 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003651 return;
3652 }
3653 }
3654
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003655 if (E->isTypeDependent() || E->isValueDependent()) {
3656 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003657 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3658 AA->setPackExpansion(IsPackExpansion);
3659 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003660 return;
3661 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003662
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003663 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003664 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003665 ExprResult ICE
3666 = VerifyIntegerConstantExpression(E, &Alignment,
3667 diag::err_aligned_attribute_argument_not_int,
3668 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003669 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003670 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003671
David Majnemer0be6bd02015-07-26 09:02:21 +00003672 uint64_t AlignVal = Alignment.getZExtValue();
3673
Richard Smith848e1f12013-02-01 08:12:08 +00003674 // C++11 [dcl.align]p2:
3675 // -- if the constant expression evaluates to zero, the alignment
3676 // specifier shall have no effect
3677 // C11 6.7.5p6:
3678 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003679 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003680 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003681 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3682 << E->getSourceRange();
3683 return;
3684 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003685 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003686
David Majnemerabecae72014-02-12 20:36:10 +00003687 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003688 unsigned MaxValidAlignment =
3689 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3690 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003691 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003692 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3693 << E->getSourceRange();
3694 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003695 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003696
David Majnemer0be6bd02015-07-26 09:02:21 +00003697 if (Context.getTargetInfo().isTLSSupported()) {
3698 unsigned MaxTLSAlign =
3699 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3700 .getQuantity();
3701 auto *VD = dyn_cast<VarDecl>(D);
3702 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3703 VD->getTLSKind() != VarDecl::TLS_None) {
3704 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3705 << (unsigned)AlignVal << VD << MaxTLSAlign;
3706 return;
3707 }
3708 }
3709
Richard Smith44c247f2013-02-22 08:32:16 +00003710 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003711 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003712 AA->setPackExpansion(IsPackExpansion);
3713 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003714}
3715
Michael Hanaf02bbe2013-02-01 01:19:17 +00003716void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003717 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003718 // FIXME: Cache the number on the Attr object if non-dependent?
3719 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003720 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3721 SpellingListIndex);
3722 AA->setPackExpansion(IsPackExpansion);
3723 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003724}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003725
Richard Smith848e1f12013-02-01 08:12:08 +00003726void Sema::CheckAlignasUnderalignment(Decl *D) {
3727 assert(D->hasAttrs() && "no attributes on decl");
3728
David Majnemer475b25e2015-01-21 10:54:38 +00003729 QualType UnderlyingTy, DiagTy;
3730 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3731 UnderlyingTy = DiagTy = VD->getType();
3732 } else {
3733 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3734 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3735 UnderlyingTy = ED->getIntegerType();
3736 }
3737 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003738 return;
3739
3740 // C++11 [dcl.align]p5, C11 6.7.5/4:
3741 // The combined effect of all alignment attributes in a declaration shall
3742 // not specify an alignment that is less strict than the alignment that
3743 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003744 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003745 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003746 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003747 if (I->isAlignmentDependent())
3748 return;
3749 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003750 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003751 Align = std::max(Align, I->getAlignment(Context));
3752 }
3753
3754 if (AlignasAttr && Align) {
3755 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003756 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003757 if (NaturalAlign > RequestedAlign)
3758 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003759 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003760 }
3761}
3762
David Majnemer2c4e00a2014-01-29 22:07:36 +00003763bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003764 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003765 MSInheritanceAttr::Spelling SemanticSpelling) {
3766 assert(RD->hasDefinition() && "RD has no definition!");
3767
David Majnemer98c9ee22014-02-07 00:43:07 +00003768 // We may not have seen base specifiers or any virtual methods yet. We will
3769 // have to wait until the record is defined to catch any mismatches.
3770 if (!RD->getDefinition()->isCompleteDefinition())
3771 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003772
David Majnemer98c9ee22014-02-07 00:43:07 +00003773 // The unspecified model never matches what a definition could need.
3774 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3775 return false;
3776
David Majnemer4bb09802014-02-10 19:50:15 +00003777 if (BestCase) {
3778 if (RD->calculateInheritanceModel() == SemanticSpelling)
3779 return false;
3780 } else {
3781 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3782 return false;
3783 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003784
3785 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3786 << 0 /*definition*/;
3787 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3788 << RD->getNameAsString();
3789 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003790}
3791
Alexey Bataevf278eb12015-11-19 10:13:11 +00003792/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3793/// attribute.
3794static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3795 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003796 IntegerMode = true;
3797 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003798 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003799 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003800 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003801 case 'Q':
3802 DestWidth = 8;
3803 break;
3804 case 'H':
3805 DestWidth = 16;
3806 break;
3807 case 'S':
3808 DestWidth = 32;
3809 break;
3810 case 'D':
3811 DestWidth = 64;
3812 break;
3813 case 'X':
3814 DestWidth = 96;
3815 break;
3816 case 'T':
3817 DestWidth = 128;
3818 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003819 }
3820 if (Str[1] == 'F') {
3821 IntegerMode = false;
3822 } else if (Str[1] == 'C') {
3823 IntegerMode = false;
3824 ComplexMode = true;
3825 } else if (Str[1] != 'I') {
3826 DestWidth = 0;
3827 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003828 break;
3829 case 4:
3830 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3831 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003832 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003833 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003834 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003835 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003836 break;
3837 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003838 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003839 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003840 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003841 case 11:
3842 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003843 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003844 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003845 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003846}
3847
3848/// handleModeAttr - This attribute modifies the width of a decl with primitive
3849/// type.
3850///
3851/// Despite what would be logical, the mode attribute is a decl attribute, not a
3852/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3853/// HImode, not an intermediate pointer.
3854static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3855 // This attribute isn't documented, but glibc uses it. It changes
3856 // the width of an int or unsigned int to the specified size.
3857 if (!Attr.isArgIdent(0)) {
3858 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3859 << AANT_ArgumentIdentifier;
3860 return;
3861 }
3862
3863 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003864
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003865 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3866}
3867
3868void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3869 unsigned SpellingListIndex, bool InInstantiation) {
3870 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003871 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003872 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003873
3874 unsigned DestWidth = 0;
3875 bool IntegerMode = true;
3876 bool ComplexMode = false;
3877 llvm::APInt VectorSize(64, 0);
3878 if (Str.size() >= 4 && Str[0] == 'V') {
3879 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3880 size_t StrSize = Str.size();
3881 size_t VectorStringLength = 0;
3882 while ((VectorStringLength + 1) < StrSize &&
3883 isdigit(Str[VectorStringLength + 1]))
3884 ++VectorStringLength;
3885 if (VectorStringLength &&
3886 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3887 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003888 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003889 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003890 // Avoid duplicate warning from template instantiation.
3891 if (!InInstantiation)
3892 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003893 } else {
3894 VectorSize = 0;
3895 }
3896 }
3897
3898 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003899 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3900
3901 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3902 // and friends, at least with glibc.
3903 // FIXME: Make sure floating-point mappings are accurate
3904 // FIXME: Support XF and TF types
3905 if (!DestWidth) {
3906 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3907 return;
3908 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003909
3910 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003911 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003912 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003913 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3914 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3915 // Try to get type from enum declaration, default to int.
3916 OldTy = ED->getIntegerType();
3917 if (OldTy.isNull())
3918 OldTy = Context.IntTy;
3919 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003920 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003921
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003922 if (OldTy->isDependentType()) {
3923 D->addAttr(::new (Context)
3924 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3925 return;
3926 }
3927
Alexey Bataev326057d2015-06-19 07:46:21 +00003928 // Base type can also be a vector type (see PR17453).
3929 // Distinguish between base type and base element type.
3930 QualType OldElemTy = OldTy;
3931 if (const VectorType *VT = OldTy->getAs<VectorType>())
3932 OldElemTy = VT->getElementType();
3933
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003934 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3935 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3936 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3937 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3938 VectorSize.getBoolValue()) {
3939 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3940 return;
3941 }
3942 bool IntegralOrAnyEnumType =
3943 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3944
3945 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3946 !IntegralOrAnyEnumType)
3947 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003948 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003949 if (!IntegralOrAnyEnumType)
3950 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003951 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003952 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003953 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003954 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003955 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003956 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003957 }
3958
Alexey Bataev326057d2015-06-19 07:46:21 +00003959 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003960
3961 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003962 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3963 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003964 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003965 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003966
Alexey Bataev326057d2015-06-19 07:46:21 +00003967 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003968 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003969 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003970 }
3971
Eli Friedman4735374e2009-03-03 06:41:03 +00003972 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003973 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003974 }
3975
3976 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003977 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003978 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3979 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003980 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003981 // Complex machine mode does not support base vector types.
3982 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003983 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003984 return;
3985 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003986 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003987 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003988 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003989 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003990 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003991 }
3992
3993 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003994 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003995 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003996 }
3997
3998 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003999 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
4000 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00004001 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
4002 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00004003 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00004004 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00004005
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00004006 D->addAttr(::new (Context)
4007 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00004008}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004009
Chandler Carruthedc2c642011-07-02 00:01:44 +00004010static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00004011 D->addAttr(::new (S.Context)
4012 NoDebugAttr(Attr.getRange(), S.Context,
4013 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00004014}
4015
Paul Robinson30e41fb2014-12-15 18:57:28 +00004016AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00004017 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00004018 unsigned AttrSpellingListIndex) {
4019 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004020 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00004021 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4022 return nullptr;
4023 }
4024
4025 if (D->hasAttr<AlwaysInlineAttr>())
4026 return nullptr;
4027
4028 return ::new (Context) AlwaysInlineAttr(Range, Context,
4029 AttrSpellingListIndex);
4030}
4031
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004032CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
4033 IdentifierInfo *Ident,
4034 unsigned AttrSpellingListIndex) {
4035 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
4036 return nullptr;
4037
4038 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
4039}
4040
4041InternalLinkageAttr *
4042Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
4043 IdentifierInfo *Ident,
4044 unsigned AttrSpellingListIndex) {
4045 if (auto VD = dyn_cast<VarDecl>(D)) {
4046 // Attribute applies to Var but not any subclass of it (like ParmVar,
4047 // ImplicitParm or VarTemplateSpecialization).
4048 if (VD->getKind() != Decl::Var) {
4049 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
4050 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4051 : ExpectedVariableOrFunction);
4052 return nullptr;
4053 }
4054 // Attribute does not apply to non-static local variables.
4055 if (VD->hasLocalStorage()) {
4056 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4057 return nullptr;
4058 }
4059 }
4060
4061 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
4062 return nullptr;
4063
4064 return ::new (Context)
4065 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
4066}
4067
Paul Robinson30e41fb2014-12-15 18:57:28 +00004068MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4069 unsigned AttrSpellingListIndex) {
4070 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4071 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4072 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4073 return nullptr;
4074 }
4075
4076 if (D->hasAttr<MinSizeAttr>())
4077 return nullptr;
4078
4079 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4080}
4081
4082OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4083 unsigned AttrSpellingListIndex) {
4084 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4085 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4086 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4087 D->dropAttr<AlwaysInlineAttr>();
4088 }
4089 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4090 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4091 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4092 D->dropAttr<MinSizeAttr>();
4093 }
4094
4095 if (D->hasAttr<OptimizeNoneAttr>())
4096 return nullptr;
4097
4098 return ::new (Context) OptimizeNoneAttr(Range, Context,
4099 AttrSpellingListIndex);
4100}
4101
Paul Robinsonf0674352014-03-31 22:29:15 +00004102static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4103 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004104 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00004105 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00004106 return;
4107
Paul Robinson080b1f32015-01-13 18:34:56 +00004108 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4109 D, Attr.getRange(), Attr.getName(),
4110 Attr.getAttributeSpellingListIndex()))
4111 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00004112}
4113
Paul Robinson080b1f32015-01-13 18:34:56 +00004114static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4115 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4116 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4117 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00004118}
4119
Paul Robinsonf0674352014-03-31 22:29:15 +00004120static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4121 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004122 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4123 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4124 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00004125}
4126
Justin Lebare71b2fa2016-09-30 23:57:34 +00004127static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4128 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4129 Attr.getName()))
4130 return;
4131 auto *VD = cast<VarDecl>(D);
4132 if (!VD->hasGlobalStorage()) {
4133 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4134 return;
4135 }
4136 D->addAttr(::new (S.Context) CUDAConstantAttr(
4137 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4138}
4139
Justin Lebar10411012016-09-30 23:57:30 +00004140static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4141 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4142 Attr.getName()))
4143 return;
4144 auto *VD = cast<VarDecl>(D);
Justin Lebar281ce2a2016-10-02 15:24:50 +00004145 // extern __shared__ is only allowed on arrays with no length (e.g.
4146 // "int x[]").
4147 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
Justin Lebar10411012016-09-30 23:57:30 +00004148 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4149 return;
4150 }
Justin Lebaraa370bd2016-10-13 18:45:13 +00004151 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4152 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4153 << S.CurrentCUDATarget())
4154 return;
Justin Lebar10411012016-09-30 23:57:30 +00004155 D->addAttr(::new (S.Context) CUDASharedAttr(
4156 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4157}
4158
Chandler Carruthedc2c642011-07-02 00:01:44 +00004159static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00004160 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4161 Attr.getName()) ||
4162 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4163 Attr.getName())) {
4164 return;
4165 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00004166 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00004167 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00004168 SourceRange RTRange = FD->getReturnTypeSourceRange();
4169 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004170 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00004171 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4172 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00004173 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004174 }
Justin Lebarc66a1062016-01-20 00:26:57 +00004175 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4176 if (Method->isInstance()) {
4177 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4178 << Method;
4179 return;
4180 }
4181 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4182 }
4183 // Only warn for "inline" when compiling for host, to cut down on noise.
4184 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4185 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004186
Aaron Ballman3aff6332013-12-02 19:30:36 +00004187 D->addAttr(::new (S.Context)
4188 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00004189 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004190}
4191
Chandler Carruthedc2c642011-07-02 00:01:44 +00004192static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004193 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00004194 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00004195 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00004196 return;
4197 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004198
Michael Han99315932013-01-24 16:46:58 +00004199 D->addAttr(::new (S.Context)
4200 GNUInlineAttr(Attr.getRange(), S.Context,
4201 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00004202}
4203
Chandler Carruthedc2c642011-07-02 00:01:44 +00004204static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004205 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004206
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004207 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00004208 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4209 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00004210 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00004211 return;
4212
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004213 if (!isa<ObjCMethodDecl>(D)) {
4214 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4215 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00004216 return;
4217 }
4218
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004219 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004220 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00004221 D->addAttr(::new (S.Context)
4222 FastCallAttr(Attr.getRange(), S.Context,
4223 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004224 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004225 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00004226 D->addAttr(::new (S.Context)
4227 StdCallAttr(Attr.getRange(), S.Context,
4228 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004229 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004230 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00004231 D->addAttr(::new (S.Context)
4232 ThisCallAttr(Attr.getRange(), S.Context,
4233 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00004234 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004235 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00004236 D->addAttr(::new (S.Context)
4237 CDeclAttr(Attr.getRange(), S.Context,
4238 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004239 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004240 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00004241 D->addAttr(::new (S.Context)
4242 PascalAttr(Attr.getRange(), S.Context,
4243 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00004244 return;
John McCall477f2bb2016-03-03 06:39:32 +00004245 case AttributeList::AT_SwiftCall:
4246 D->addAttr(::new (S.Context)
4247 SwiftCallAttr(Attr.getRange(), S.Context,
4248 Attr.getAttributeSpellingListIndex()));
4249 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004250 case AttributeList::AT_VectorCall:
4251 D->addAttr(::new (S.Context)
4252 VectorCallAttr(Attr.getRange(), S.Context,
4253 Attr.getAttributeSpellingListIndex()));
4254 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00004255 case AttributeList::AT_MSABI:
4256 D->addAttr(::new (S.Context)
4257 MSABIAttr(Attr.getRange(), S.Context,
4258 Attr.getAttributeSpellingListIndex()));
4259 return;
4260 case AttributeList::AT_SysVABI:
4261 D->addAttr(::new (S.Context)
4262 SysVABIAttr(Attr.getRange(), S.Context,
4263 Attr.getAttributeSpellingListIndex()));
4264 return;
Erich Keane757d3172016-11-02 18:29:35 +00004265 case AttributeList::AT_RegCall:
4266 D->addAttr(::new (S.Context) RegCallAttr(
4267 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4268 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004269 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004270 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004271 switch (CC) {
4272 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004273 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004274 break;
4275 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004276 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004277 break;
4278 default:
4279 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004280 }
4281
Michael Han99315932013-01-24 16:46:58 +00004282 D->addAttr(::new (S.Context)
4283 PcsAttr(Attr.getRange(), S.Context, PCS,
4284 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00004285 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004286 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004287 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00004288 D->addAttr(::new (S.Context)
4289 IntelOclBiccAttr(Attr.getRange(), S.Context,
4290 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00004291 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004292 case AttributeList::AT_PreserveMost:
4293 D->addAttr(::new (S.Context) PreserveMostAttr(
4294 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4295 return;
4296 case AttributeList::AT_PreserveAll:
4297 D->addAttr(::new (S.Context) PreserveAllAttr(
4298 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4299 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004300 default:
4301 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00004302 }
4303}
4304
Matthias Gehre01a63382017-03-27 19:45:24 +00004305static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4306 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4307 return;
4308
4309 std::vector<StringRef> DiagnosticIdentifiers;
4310 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4311 StringRef RuleName;
4312
4313 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4314 return;
4315
4316 // FIXME: Warn if the rule name is unknown. This is tricky because only
4317 // clang-tidy knows about available rules.
4318 DiagnosticIdentifiers.push_back(RuleName);
4319 }
4320 D->addAttr(::new (S.Context) SuppressAttr(
4321 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4322 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4323}
4324
Aaron Ballman02df2e02012-12-09 17:45:41 +00004325bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4326 const FunctionDecl *FD) {
John McCall3882ace2011-01-05 12:14:39 +00004327 if (attr.isInvalid())
4328 return true;
4329
John McCall3b5a8f52016-03-03 00:10:03 +00004330 if (attr.hasProcessingCache()) {
4331 CC = (CallingConv) attr.getProcessingCache();
4332 return false;
4333 }
4334
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004335 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
Aaron Ballman00e99962013-08-31 01:11:41 +00004336 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
John McCall3882ace2011-01-05 12:14:39 +00004337 attr.setInvalid();
4338 return true;
4339 }
4340
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004341 // TODO: diagnose uses of these conventions on the wrong target.
John McCall3882ace2011-01-05 12:14:39 +00004342 switch (attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004343 case AttributeList::AT_CDecl: CC = CC_C; break;
4344 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4345 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4346 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4347 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00004348 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004349 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Erich Keane757d3172016-11-02 18:29:35 +00004350 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00004351 case AttributeList::AT_MSABI:
4352 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
Martin Storsjo022e7822017-07-17 20:49:45 +00004353 CC_Win64;
Charles Davisb5a214e2013-08-30 04:39:01 +00004354 break;
4355 case AttributeList::AT_SysVABI:
4356 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4357 CC_C;
4358 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004359 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00004360 StringRef StrRef;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004361 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004362 attr.setInvalid();
4363 return true;
4364 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004365 if (StrRef == "aapcs") {
4366 CC = CC_AAPCS;
4367 break;
4368 } else if (StrRef == "aapcs-vfp") {
4369 CC = CC_AAPCS_VFP;
4370 break;
4371 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004372
4373 attr.setInvalid();
4374 Diag(attr.getLoc(), diag::err_invalid_pcs);
4375 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004376 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004377 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004378 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4379 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00004380 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00004381 }
4382
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004383 const TargetInfo &TI = Context.getTargetInfo();
4384 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004385 if (A != TargetInfo::CCCR_OK) {
4386 if (A == TargetInfo::CCCR_Warning)
4387 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00004388
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004389 // This convention is not valid for the target. Use the default function or
4390 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00004391 bool IsCXXMethod = false, IsVariadic = false;
4392 if (FD) {
4393 IsCXXMethod = FD->isCXXInstanceMember();
4394 IsVariadic = FD->isVariadic();
4395 }
4396 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004397 }
4398
John McCall3b5a8f52016-03-03 00:10:03 +00004399 attr.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00004400 return false;
4401}
4402
John McCall477f2bb2016-03-03 06:39:32 +00004403/// Pointer-like types in the default address space.
4404static bool isValidSwiftContextType(QualType type) {
4405 if (!type->hasPointerRepresentation())
4406 return type->isDependentType();
4407 return type->getPointeeType().getAddressSpace() == 0;
4408}
4409
4410/// Pointers and references in the default address space.
4411static bool isValidSwiftIndirectResultType(QualType type) {
4412 if (auto ptrType = type->getAs<PointerType>()) {
4413 type = ptrType->getPointeeType();
4414 } else if (auto refType = type->getAs<ReferenceType>()) {
4415 type = refType->getPointeeType();
4416 } else {
4417 return type->isDependentType();
4418 }
4419 return type.getAddressSpace() == 0;
4420}
4421
4422/// Pointers and references to pointers in the default address space.
4423static bool isValidSwiftErrorResultType(QualType type) {
4424 if (auto ptrType = type->getAs<PointerType>()) {
4425 type = ptrType->getPointeeType();
4426 } else if (auto refType = type->getAs<ReferenceType>()) {
4427 type = refType->getPointeeType();
4428 } else {
4429 return type->isDependentType();
4430 }
4431 if (!type.getQualifiers().empty())
4432 return false;
4433 return isValidSwiftContextType(type);
4434}
4435
4436static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4437 ParameterABI abi) {
4438 S.AddParameterABIAttr(attr.getRange(), D, abi,
4439 attr.getAttributeSpellingListIndex());
4440}
4441
4442void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4443 unsigned spellingIndex) {
4444
4445 QualType type = cast<ParmVarDecl>(D)->getType();
4446
4447 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4448 if (existingAttr->getABI() != abi) {
4449 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4450 << getParameterABISpelling(abi) << existingAttr;
4451 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4452 return;
4453 }
4454 }
4455
4456 switch (abi) {
4457 case ParameterABI::Ordinary:
4458 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4459
4460 case ParameterABI::SwiftContext:
4461 if (!isValidSwiftContextType(type)) {
4462 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4463 << getParameterABISpelling(abi)
4464 << /*pointer to pointer */ 0 << type;
4465 }
4466 D->addAttr(::new (Context)
4467 SwiftContextAttr(range, Context, spellingIndex));
4468 return;
4469
4470 case ParameterABI::SwiftErrorResult:
4471 if (!isValidSwiftErrorResultType(type)) {
4472 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4473 << getParameterABISpelling(abi)
4474 << /*pointer to pointer */ 1 << type;
4475 }
4476 D->addAttr(::new (Context)
4477 SwiftErrorResultAttr(range, Context, spellingIndex));
4478 return;
4479
4480 case ParameterABI::SwiftIndirectResult:
4481 if (!isValidSwiftIndirectResultType(type)) {
4482 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4483 << getParameterABISpelling(abi)
4484 << /*pointer*/ 0 << type;
4485 }
4486 D->addAttr(::new (Context)
4487 SwiftIndirectResultAttr(range, Context, spellingIndex));
4488 return;
4489 }
4490 llvm_unreachable("bad parameter ABI attribute");
4491}
4492
John McCall3882ace2011-01-05 12:14:39 +00004493/// Checks a regparm attribute, returning true if it is ill-formed and
4494/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004495bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4496 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004497 return true;
4498
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004499 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004500 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004501 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004502 }
Eli Friedman7044b762009-03-27 21:06:47 +00004503
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004504 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004505 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004506 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004507 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004508 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004509 }
4510
Douglas Gregore8bbc122011-09-02 00:18:52 +00004511 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004512 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004513 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004514 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004515 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004516 }
4517
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004518 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004519 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004520 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004521 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004522 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004523 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004524 }
4525
John McCall3882ace2011-01-05 12:14:39 +00004526 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004527}
4528
Artem Belevichbcec9da2016-06-06 22:54:57 +00004529// Checks whether an argument of launch_bounds attribute is
4530// acceptable, performs implicit conversion to Rvalue, and returns
4531// non-nullptr Expr result on success. Otherwise, it returns nullptr
4532// and may output an error.
4533static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4534 const CUDALaunchBoundsAttr &Attr,
4535 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004536 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004537 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004538
4539 // Accept template arguments for now as they depend on something else.
4540 // We'll get to check them when they eventually get instantiated.
4541 if (E->isValueDependent())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004542 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004543
4544 llvm::APSInt I(64);
4545 if (!E->isIntegerConstantExpr(I, S.Context)) {
4546 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4547 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004548 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004549 }
4550 // Make sure we can fit it in 32 bits.
4551 if (!I.isIntN(32)) {
4552 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4553 << 32 << /* Unsigned */ 1;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004554 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004555 }
4556 if (I < 0)
4557 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4558 << &Attr << Idx << E->getSourceRange();
4559
Artem Belevichbcec9da2016-06-06 22:54:57 +00004560 // We may need to perform implicit conversion of the argument.
4561 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4562 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4563 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4564 assert(!ValArg.isInvalid() &&
4565 "Unexpected PerformCopyInitialization() failure.");
4566
4567 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004568}
4569
4570void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4571 Expr *MinBlocks, unsigned SpellingListIndex) {
4572 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4573 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004574 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4575 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004576 return;
4577
Artem Belevichbcec9da2016-06-06 22:54:57 +00004578 if (MinBlocks) {
4579 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4580 if (MinBlocks == nullptr)
4581 return;
4582 }
Artem Belevich7093e402015-04-21 22:55:54 +00004583
4584 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4585 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4586}
4587
4588static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4589 const AttributeList &Attr) {
4590 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4591 !checkAttributeAtMostNumArgs(S, Attr, 2))
4592 return;
4593
4594 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4595 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4596 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004597}
4598
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004599static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4600 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004601 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004602 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004603 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004604 return;
4605 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004606
4607 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004608 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004609
Aaron Ballman00e99962013-08-31 01:11:41 +00004610 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004611
4612 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4613 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4614 << Attr.getName() << ExpectedFunctionOrMethod;
4615 return;
4616 }
4617
4618 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004619 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4620 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004621 return;
4622
4623 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004624 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4625 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004626 return;
4627
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004628 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004629 if (IsPointer) {
4630 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004631 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004632 if (!BufferTy->isPointerType()) {
4633 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004634 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004635 }
4636 }
4637
Michael Han99315932013-01-24 16:46:58 +00004638 D->addAttr(::new (S.Context)
4639 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4640 ArgumentIdx, TypeTagIdx, IsPointer,
4641 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004642}
4643
4644static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4645 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004646 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004647 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004648 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004649 return;
4650 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004651
4652 if (!checkAttributeNumArgs(S, Attr, 1))
4653 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004654
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004655 if (!isa<VarDecl>(D)) {
4656 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4657 << Attr.getName() << ExpectedVariable;
4658 return;
4659 }
4660
Aaron Ballman00e99962013-08-31 01:11:41 +00004661 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004662 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004663 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4664 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004665
Michael Han99315932013-01-24 16:46:58 +00004666 D->addAttr(::new (S.Context)
4667 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004668 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004669 Attr.getLayoutCompatible(),
4670 Attr.getMustBeNull(),
4671 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004672}
4673
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004674static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4675 const AttributeList &Attr) {
4676 uint64_t ArgCount;
Dean Michael Berris7456a282017-06-16 03:22:09 +00004677
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004678 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
Dean Michael Berris7456a282017-06-16 03:22:09 +00004679 ArgCount,
4680 true /* AllowImplicitThis*/))
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004681 return;
4682
4683 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4684 D->addAttr(::new (S.Context)
Dean Michael Berris7456a282017-06-16 03:22:09 +00004685 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4686 Attr.getAttributeSpellingListIndex()));
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004687}
4688
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004689//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004690// Checker-specific attribute handlers.
4691//===----------------------------------------------------------------------===//
4692
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004693static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004694 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004695 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004696}
4697
John McCalled433932011-01-25 03:31:58 +00004698static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004699 return type->isDependentType() ||
4700 type->isObjCObjectPointerType() ||
4701 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004702}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004703
John McCalled433932011-01-25 03:31:58 +00004704static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004705 return type->isDependentType() ||
4706 type->isPointerType() ||
4707 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004708}
4709
Chandler Carruthedc2c642011-07-02 00:01:44 +00004710static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004711 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4712 Attr.getKind() == AttributeList::AT_NSConsumed,
4713 /*template instantiation*/ false);
4714}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004715
John McCall3b5a8f52016-03-03 00:10:03 +00004716void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4717 unsigned spellingIndex, bool isNSConsumed,
4718 bool isTemplateInstantiation) {
4719 ParmVarDecl *param = cast<ParmVarDecl>(D);
4720 bool typeOK;
4721
4722 if (isNSConsumed) {
4723 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004724 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004725 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004726 }
4727
4728 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004729 // These attributes are normally just advisory, but in ARC, ns_consumed
4730 // is significant. Allow non-dependent code to contain inappropriate
4731 // attributes even in ARC, but require template instantiations to be
4732 // set up correctly.
4733 Diag(D->getLocStart(),
4734 (isTemplateInstantiation && isNSConsumed &&
4735 getLangOpts().ObjCAutoRefCount
4736 ? diag::err_ns_attribute_wrong_parameter_type
4737 : diag::warn_ns_attribute_wrong_parameter_type))
4738 << attrRange
4739 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4740 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004741 return;
4742 }
4743
John McCall3b5a8f52016-03-03 00:10:03 +00004744 if (isNSConsumed)
4745 param->addAttr(::new (Context)
4746 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004747 else
John McCall3b5a8f52016-03-03 00:10:03 +00004748 param->addAttr(::new (Context)
4749 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004750}
4751
John McCall12251882017-07-15 11:06:46 +00004752bool Sema::checkNSReturnsRetainedReturnType(SourceLocation loc,
4753 QualType type) {
4754 if (isValidSubjectOfNSReturnsRetainedAttribute(type))
4755 return false;
4756
4757 Diag(loc, diag::warn_ns_attribute_wrong_return_type)
4758 << "'ns_returns_retained'" << 0 << 0;
4759 return true;
4760}
4761
Chandler Carruthedc2c642011-07-02 00:01:44 +00004762static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4763 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004764 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004765
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004766 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004767 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004768 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004769 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004770 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004771 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4772 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004773 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004774 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004775 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4776 returnType = Param->getType()->getPointeeType();
4777 if (returnType.isNull()) {
4778 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4779 << Attr.getName() << /*pointer-to-CF*/2
4780 << Attr.getRange();
4781 return;
4782 }
John McCall12251882017-07-15 11:06:46 +00004783 } else if (Attr.isUsedAsTypeAttr()) {
4784 return;
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004785 } else {
4786 AttributeDeclKind ExpectedDeclKind;
4787 switch (Attr.getKind()) {
4788 default: llvm_unreachable("invalid ownership attribute");
4789 case AttributeList::AT_NSReturnsRetained:
4790 case AttributeList::AT_NSReturnsAutoreleased:
4791 case AttributeList::AT_NSReturnsNotRetained:
4792 ExpectedDeclKind = ExpectedFunctionOrMethod;
4793 break;
4794
4795 case AttributeList::AT_CFReturnsRetained:
4796 case AttributeList::AT_CFReturnsNotRetained:
4797 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4798 break;
4799 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004800 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004801 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004802 return;
4803 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004804
John McCalled433932011-01-25 03:31:58 +00004805 bool typeOK;
4806 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004807 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004808 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004809 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004810 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004811 cf = false;
4812 break;
4813
4814 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004815 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004816 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4817 cf = false;
4818 break;
4819
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004820 case AttributeList::AT_CFReturnsRetained:
4821 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004822 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4823 cf = true;
4824 break;
4825 }
4826
4827 if (!typeOK) {
John McCall12251882017-07-15 11:06:46 +00004828 if (Attr.isUsedAsTypeAttr())
4829 return;
4830
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004831 if (isa<ParmVarDecl>(D)) {
4832 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4833 << Attr.getName() << /*pointer-to-CF*/2
4834 << Attr.getRange();
4835 } else {
4836 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4837 enum : unsigned {
4838 Function,
4839 Method,
4840 Property
4841 } SubjectKind = Function;
4842 if (isa<ObjCMethodDecl>(D))
4843 SubjectKind = Method;
4844 else if (isa<ObjCPropertyDecl>(D))
4845 SubjectKind = Property;
4846 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4847 << Attr.getName() << SubjectKind << cf
4848 << Attr.getRange();
4849 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004850 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004851 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004852
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004853 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004854 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004855 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004856 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004857 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4858 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004859 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004860 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004861 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4862 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004863 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004864 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004865 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4866 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004867 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004868 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004869 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4870 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004871 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004872 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004873 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4874 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004875 return;
4876 };
4877}
4878
John McCallcf166702011-07-22 08:53:00 +00004879static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4880 const AttributeList &attr) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004881 const int EP_ObjCMethod = 1;
4882 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004883
John McCallcf166702011-07-22 08:53:00 +00004884 SourceLocation loc = attr.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004885 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004886 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004887 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004888 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004889 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004890
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004891 if (!resultType->isReferenceType() &&
4892 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004893 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004894 << SourceRange(loc)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004895 << attr.getName()
4896 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004897 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004898
4899 // Drop the attribute.
4900 return;
4901 }
4902
Nico Weber462fd1e2015-01-07 23:50:05 +00004903 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4904 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004905}
4906
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004907static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4908 const AttributeList &attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004909 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004910
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004911 DeclContext *DC = method->getDeclContext();
4912 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4913 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4914 << attr.getName() << 0;
4915 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4916 return;
4917 }
4918 if (method->getMethodFamily() == OMF_dealloc) {
4919 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4920 << attr.getName() << 1;
4921 return;
4922 }
4923
Michael Han99315932013-01-24 16:46:58 +00004924 method->addAttr(::new (S.Context)
4925 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4926 attr.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004927}
4928
Aaron Ballmanfb763042013-12-02 18:05:46 +00004929static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4930 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004931 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4932 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004933 return;
John McCall32f5fe12011-09-30 05:12:12 +00004934
Aaron Ballmanfb763042013-12-02 18:05:46 +00004935 D->addAttr(::new (S.Context)
4936 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4937 Attr.getAttributeSpellingListIndex()));
4938}
4939
4940static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4941 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004942 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4943 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004944 return;
4945
4946 D->addAttr(::new (S.Context)
4947 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4948 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004949}
4950
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004951static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4952 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004953 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004954
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004955 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004956 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004957 return;
4958 }
John McCall28592582015-02-01 22:34:06 +00004959
4960 // Typedefs only allow objc_bridge(id) and have some additional checking.
4961 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4962 if (!Parm->Ident->isStr("id")) {
4963 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4964 << Attr.getName();
4965 return;
4966 }
4967
4968 // Only allow 'cv void *'.
4969 QualType T = TD->getUnderlyingType();
4970 if (!T->isVoidPointerType()) {
4971 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4972 return;
4973 }
4974 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004975
4976 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004977 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004978 Attr.getAttributeSpellingListIndex()));
4979}
4980
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004981static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4982 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004983 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4984
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004985 if (!Parm) {
4986 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4987 return;
4988 }
4989
4990 D->addAttr(::new (S.Context)
4991 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4992 Attr.getAttributeSpellingListIndex()));
4993}
4994
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004995static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4996 const AttributeList &Attr) {
4997 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004998 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004999 if (!RelatedClass) {
5000 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
5001 return;
5002 }
5003 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00005004 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00005005 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00005006 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00005007 D->addAttr(::new (S.Context)
5008 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
5009 ClassMethod, InstanceMethod,
5010 Attr.getAttributeSpellingListIndex()));
5011}
5012
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00005013static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5014 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00005015 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00005016 if (ObjCCategoryDecl *CatDecl =
5017 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00005018 IFace = CatDecl->getClassInterface();
5019 else
5020 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00005021
5022 if (!IFace)
5023 return;
5024
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00005025 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00005026 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00005027 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
5028 Attr.getAttributeSpellingListIndex()));
5029}
5030
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005031static void handleObjCRuntimeName(Sema &S, Decl *D,
5032 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00005033 StringRef MetaDataName;
5034 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
5035 return;
5036 D->addAttr(::new (S.Context)
5037 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
5038 MetaDataName,
5039 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005040}
5041
Nico Webera6916892016-06-10 18:53:04 +00005042// When a user wants to use objc_boxable with a union or struct
5043// but they don't have access to the declaration (legacy/third-party code)
5044// then they can 'enable' this feature with a typedef:
Alex Denisovfde64952015-06-26 05:28:36 +00005045// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5046static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
5047 bool notify = false;
5048
5049 RecordDecl *RD = dyn_cast<RecordDecl>(D);
5050 if (RD && RD->getDefinition()) {
5051 RD = RD->getDefinition();
5052 notify = true;
5053 }
5054
5055 if (RD) {
5056 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5057 ObjCBoxableAttr(Attr.getRange(), S.Context,
5058 Attr.getAttributeSpellingListIndex());
5059 RD->addAttr(BoxableAttr);
5060 if (notify) {
5061 // we need to notify ASTReader/ASTWriter about
5062 // modification of existing declaration
5063 if (ASTMutationListener *L = S.getASTMutationListener())
5064 L->AddedAttributeToRecord(BoxableAttr, RD);
5065 }
5066 }
5067}
5068
Chandler Carruthedc2c642011-07-02 00:01:44 +00005069static void handleObjCOwnershipAttr(Sema &S, Decl *D,
5070 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005071 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00005072
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005073 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00005074 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00005075}
5076
Chandler Carruthedc2c642011-07-02 00:01:44 +00005077static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5078 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005079 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00005080 QualType type = vd->getType();
5081
5082 if (!type->isDependentType() &&
5083 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005084 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00005085 << type;
5086 return;
5087 }
5088
5089 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5090
5091 // If we have no lifetime yet, check the lifetime we're presumably
5092 // going to infer.
5093 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
5094 lifetime = type->getObjCARCImplicitLifetime();
5095
5096 switch (lifetime) {
5097 case Qualifiers::OCL_None:
5098 assert(type->isDependentType() &&
5099 "didn't infer lifetime for non-dependent type?");
5100 break;
5101
5102 case Qualifiers::OCL_Weak: // meaningful
5103 case Qualifiers::OCL_Strong: // meaningful
5104 break;
5105
5106 case Qualifiers::OCL_ExplicitNone:
5107 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005108 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00005109 << (lifetime == Qualifiers::OCL_Autoreleasing);
5110 break;
5111 }
5112
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005113 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00005114 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5115 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00005116}
5117
Francois Picheta83957a2010-12-19 06:50:37 +00005118//===----------------------------------------------------------------------===//
5119// Microsoft specific attribute handlers.
5120//===----------------------------------------------------------------------===//
5121
Nico Weber88f5ed92016-09-13 18:55:26 +00005122UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5123 unsigned AttrSpellingListIndex, StringRef Uuid) {
5124 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00005125 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00005126 return nullptr;
5127 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5128 Diag(Range.getBegin(), diag::note_previous_uuid);
5129 D->dropAttr<UuidAttr>();
5130 }
5131
5132 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5133}
5134
Chandler Carruthedc2c642011-07-02 00:01:44 +00005135static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00005136 if (!S.LangOpts.CPlusPlus) {
5137 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5138 << Attr.getName() << AttributeLangSupport::C;
5139 return;
5140 }
5141
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005142 StringRef StrRef;
5143 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00005144 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00005145 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005146
David Majnemer89085342013-08-09 08:56:20 +00005147 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5148 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00005149 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5150 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00005151
Reid Kleckner140c4a72013-05-17 14:04:52 +00005152 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00005153 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005154 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005155 return;
5156 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00005157
David Majnemer89085342013-08-09 08:56:20 +00005158 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00005159 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00005160 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005161 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00005162 return;
5163 }
David Majnemer89085342013-08-09 08:56:20 +00005164 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005165 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005166 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005167 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00005168 }
Francois Picheta83957a2010-12-19 06:50:37 +00005169
Nico Weber469891e2017-05-05 17:05:56 +00005170 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5171 // the only thing in the [] list, the [] too), and add an insertion of
5172 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5173 // separating attributes nor of the [ and the ] are in the AST.
Nico Weber0a234042017-05-05 17:15:08 +00005174 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
Nico Weber469891e2017-05-05 17:05:56 +00005175 // on cfe-dev.
5176 if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5177 S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5178
Nico Weber88f5ed92016-09-13 18:55:26 +00005179 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5180 Attr.getAttributeSpellingListIndex(), StrRef);
5181 if (UA)
5182 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00005183}
5184
David Majnemer2c4e00a2014-01-29 22:07:36 +00005185static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5186 if (!S.LangOpts.CPlusPlus) {
5187 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5188 << Attr.getName() << AttributeLangSupport::C;
5189 return;
5190 }
5191 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00005192 D, Attr.getRange(), /*BestCase=*/true,
5193 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00005194 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00005195 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00005196 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00005197 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5198 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00005199}
5200
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005201static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5202 const AttributeList &Attr) {
5203 VarDecl *VD = cast<VarDecl>(D);
5204 if (!S.Context.getTargetInfo().isTLSSupported()) {
5205 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5206 return;
5207 }
5208 if (VD->getTSCSpec() != TSCS_unspecified) {
5209 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5210 return;
5211 }
5212 if (VD->hasLocalStorage()) {
5213 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5214 return;
5215 }
5216 VD->addAttr(::new (S.Context) ThreadAttr(
5217 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5218}
5219
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005220static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5221 SmallVector<StringRef, 4> Tags;
5222 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5223 StringRef Tag;
5224 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5225 return;
5226 Tags.push_back(Tag);
5227 }
5228
5229 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5230 if (!NS->isInline()) {
5231 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5232 return;
5233 }
5234 if (NS->isAnonymousNamespace()) {
5235 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5236 return;
5237 }
5238 if (Attr.getNumArgs() == 0)
5239 Tags.push_back(NS->getName());
5240 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5241 return;
5242
5243 // Store tags sorted and without duplicates.
5244 std::sort(Tags.begin(), Tags.end());
5245 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5246
5247 D->addAttr(::new (S.Context)
5248 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5249 Attr.getAttributeSpellingListIndex()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005250}
5251
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005252static void handleARMInterruptAttr(Sema &S, Decl *D,
5253 const AttributeList &Attr) {
5254 // Check the attribute arguments.
5255 if (Attr.getNumArgs() > 1) {
5256 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5257 << Attr.getName() << 1;
5258 return;
5259 }
5260
5261 StringRef Str;
5262 SourceLocation ArgLoc;
5263
5264 if (Attr.getNumArgs() == 0)
5265 Str = "";
5266 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5267 return;
5268
5269 ARMInterruptAttr::InterruptType Kind;
5270 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5271 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5272 << Attr.getName() << Str << ArgLoc;
5273 return;
5274 }
5275
5276 unsigned Index = Attr.getAttributeSpellingListIndex();
5277 D->addAttr(::new (S.Context)
5278 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5279}
5280
5281static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5282 const AttributeList &Attr) {
5283 if (!checkAttributeNumArgs(S, Attr, 1))
5284 return;
5285
5286 if (!Attr.isArgExpr(0)) {
5287 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5288 << AANT_ArgumentIntegerConstant;
5289 return;
5290 }
5291
5292 // FIXME: Check for decl - it should be void ()(void).
5293
5294 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5295 llvm::APSInt NumParams(32);
5296 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5297 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5298 << Attr.getName() << AANT_ArgumentIntegerConstant
5299 << NumParamsExpr->getSourceRange();
5300 return;
5301 }
5302
5303 unsigned Num = NumParams.getLimitedValue(255);
5304 if ((Num & 1) || Num > 30) {
5305 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5306 << Attr.getName() << (int)NumParams.getSExtValue()
5307 << NumParamsExpr->getSourceRange();
5308 return;
5309 }
5310
Aaron Ballman36a53502014-01-16 13:03:14 +00005311 D->addAttr(::new (S.Context)
5312 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5313 Attr.getAttributeSpellingListIndex()));
5314 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005315}
5316
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005317static void handleMipsInterruptAttr(Sema &S, Decl *D,
5318 const AttributeList &Attr) {
5319 // Only one optional argument permitted.
5320 if (Attr.getNumArgs() > 1) {
5321 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5322 << Attr.getName() << 1;
5323 return;
5324 }
5325
5326 StringRef Str;
5327 SourceLocation ArgLoc;
5328
5329 if (Attr.getNumArgs() == 0)
5330 Str = "";
5331 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5332 return;
5333
5334 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5335 // a) Must be a function.
5336 // b) Must have no parameters.
5337 // c) Must have the 'void' return type.
5338 // d) Cannot have the 'mips16' attribute, as that instruction set
5339 // lacks the 'eret' instruction.
5340 // e) The attribute itself must either have no argument or one of the
5341 // valid interrupt types, see [MipsInterruptDocs].
5342
5343 if (!isFunctionOrMethod(D)) {
5344 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5345 << "'interrupt'" << ExpectedFunctionOrMethod;
5346 return;
5347 }
5348
5349 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5350 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5351 << 0;
5352 return;
5353 }
5354
5355 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5356 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5357 << 1;
5358 return;
5359 }
5360
5361 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5362 Attr.getName()))
5363 return;
5364
5365 MipsInterruptAttr::InterruptType Kind;
5366 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5367 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5368 << Attr.getName() << "'" + std::string(Str) + "'";
5369 return;
5370 }
5371
5372 D->addAttr(::new (S.Context) MipsInterruptAttr(
5373 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5374}
5375
Alexey Bataevd51e9932016-01-15 04:06:31 +00005376static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5377 const AttributeList &Attr) {
5378 // Semantic checks for a function with the 'interrupt' attribute.
5379 // a) Must be a function.
5380 // b) Must have the 'void' return type.
5381 // c) Must take 1 or 2 arguments.
5382 // d) The 1st argument must be a pointer.
5383 // e) The 2nd argument (if any) must be an unsigned integer.
5384 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5385 CXXMethodDecl::isStaticOverloadedOperator(
5386 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5387 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5388 << Attr.getName() << ExpectedFunctionWithProtoType;
5389 return;
5390 }
5391 // Interrupt handler must have void return type.
5392 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5393 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5394 diag::err_anyx86_interrupt_attribute)
5395 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5396 ? 0
5397 : 1)
5398 << 0;
5399 return;
5400 }
5401 // Interrupt handler must have 1 or 2 parameters.
5402 unsigned NumParams = getFunctionOrMethodNumParams(D);
5403 if (NumParams < 1 || NumParams > 2) {
5404 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5405 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5406 ? 0
5407 : 1)
5408 << 1;
5409 return;
5410 }
5411 // The first argument must be a pointer.
5412 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5413 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5414 diag::err_anyx86_interrupt_attribute)
5415 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5416 ? 0
5417 : 1)
5418 << 2;
5419 return;
5420 }
5421 // The second argument, if present, must be an unsigned integer.
5422 unsigned TypeSize =
5423 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5424 ? 64
5425 : 32;
5426 if (NumParams == 2 &&
5427 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5428 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5429 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5430 diag::err_anyx86_interrupt_attribute)
5431 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5432 ? 0
5433 : 1)
5434 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5435 return;
5436 }
5437 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5438 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5439 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5440}
5441
Dylan McKaye8232d72017-02-08 05:09:26 +00005442static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5443 if (!isFunctionOrMethod(D)) {
5444 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5445 << "'interrupt'" << ExpectedFunction;
5446 return;
5447 }
5448
5449 if (!checkAttributeNumArgs(S, Attr, 0))
5450 return;
5451
5452 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5453}
5454
5455static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5456 if (!isFunctionOrMethod(D)) {
5457 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5458 << "'signal'" << ExpectedFunction;
5459 return;
5460 }
5461
5462 if (!checkAttributeNumArgs(S, Attr, 0))
5463 return;
5464
5465 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5466}
5467
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005468static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5469 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00005470 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5471 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005472 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005473 break;
5474 case llvm::Triple::mipsel:
5475 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005476 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005477 break;
5478 case llvm::Triple::x86:
5479 case llvm::Triple::x86_64:
5480 handleAnyX86InterruptAttr(S, D, Attr);
5481 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005482 case llvm::Triple::avr:
5483 handleAVRInterruptAttr(S, D, Attr);
5484 break;
Alexey Bataevd51e9932016-01-15 04:06:31 +00005485 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005486 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005487 break;
5488 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005489}
5490
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005491static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5492 const AttributeList &Attr) {
5493 uint32_t Min = 0;
5494 Expr *MinExpr = Attr.getArgAsExpr(0);
5495 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005496 return;
5497
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005498 uint32_t Max = 0;
5499 Expr *MaxExpr = Attr.getArgAsExpr(1);
5500 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5501 return;
5502
5503 if (Min == 0 && Max != 0) {
5504 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5505 << Attr.getName() << 0;
5506 return;
5507 }
5508 if (Min > Max) {
5509 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5510 << Attr.getName() << 1;
5511 return;
5512 }
5513
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005514 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005515 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5516 Attr.getAttributeSpellingListIndex()));
5517}
5518
5519static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5520 const AttributeList &Attr) {
5521 uint32_t Min = 0;
5522 Expr *MinExpr = Attr.getArgAsExpr(0);
5523 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5524 return;
5525
5526 uint32_t Max = 0;
5527 if (Attr.getNumArgs() == 2) {
5528 Expr *MaxExpr = Attr.getArgAsExpr(1);
5529 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5530 return;
5531 }
5532
5533 if (Min == 0 && Max != 0) {
5534 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5535 << Attr.getName() << 0;
5536 return;
5537 }
5538 if (Max != 0 && Min > Max) {
5539 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5540 << Attr.getName() << 1;
5541 return;
5542 }
5543
5544 D->addAttr(::new (S.Context)
5545 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5546 Attr.getAttributeSpellingListIndex()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005547}
5548
5549static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5550 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005551 uint32_t NumSGPR = 0;
5552 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5553 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005554 return;
5555
5556 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005557 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5558 Attr.getAttributeSpellingListIndex()));
5559}
5560
5561static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5562 const AttributeList &Attr) {
5563 uint32_t NumVGPR = 0;
5564 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5565 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5566 return;
5567
5568 D->addAttr(::new (S.Context)
5569 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005570 Attr.getAttributeSpellingListIndex()));
5571}
5572
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005573static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5574 const AttributeList& Attr) {
5575 // If we try to apply it to a function pointer, don't warn, but don't
5576 // do anything, either. It doesn't matter anyway, because there's nothing
5577 // special about calling a force_align_arg_pointer function.
5578 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5579 if (VD && VD->getType()->isFunctionPointerType())
5580 return;
5581 // Also don't warn on function pointer typedefs.
5582 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5583 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5584 TD->getUnderlyingType()->isFunctionType()))
5585 return;
5586 // Attribute can only be applied to function types.
5587 if (!isa<FunctionDecl>(D)) {
5588 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5589 << Attr.getName() << /* function */0;
5590 return;
5591 }
5592
Aaron Ballman36a53502014-01-16 13:03:14 +00005593 D->addAttr(::new (S.Context)
5594 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5595 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005596}
5597
David Majnemercd3ebfe2016-05-23 17:16:12 +00005598static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5599 uint32_t Version;
5600 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5601 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5602 return;
5603
5604 // TODO: Investigate what happens with the next major version of MSVC.
5605 if (Version != LangOptions::MSVC2015) {
5606 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5607 << Attr.getName() << Version << VersionExpr->getSourceRange();
5608 return;
5609 }
5610
5611 D->addAttr(::new (S.Context)
5612 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5613 Attr.getAttributeSpellingListIndex()));
5614}
5615
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005616DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5617 unsigned AttrSpellingListIndex) {
5618 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005619 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005620 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005621 }
5622
5623 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005624 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005625
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005626 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005627}
5628
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005629DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5630 unsigned AttrSpellingListIndex) {
5631 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005632 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005633 D->dropAttr<DLLImportAttr>();
5634 }
5635
5636 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005637 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005638
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005639 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005640}
5641
Hans Wennborge82f19c2014-06-24 23:57:05 +00005642static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005643 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5644 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5645 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5646 << A.getName();
5647 return;
5648 }
5649
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5651 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5652 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5653 // MinGW doesn't allow dllimport on inline functions.
5654 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5655 << A.getName();
5656 return;
5657 }
5658 }
5659
Hans Wennborg5869ec42015-09-15 21:05:30 +00005660 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5661 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5662 MD->getParent()->isLambda()) {
5663 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5664 return;
5665 }
5666 }
5667
Hans Wennborge82f19c2014-06-24 23:57:05 +00005668 unsigned Index = A.getAttributeSpellingListIndex();
5669 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5670 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5671 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005672 if (NewAttr)
5673 D->addAttr(NewAttr);
5674}
5675
David Majnemer2c4e00a2014-01-29 22:07:36 +00005676MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005677Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005678 unsigned AttrSpellingListIndex,
5679 MSInheritanceAttr::Spelling SemanticSpelling) {
5680 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5681 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005682 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005683 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5684 << 1 /*previous declaration*/;
5685 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5686 D->dropAttr<MSInheritanceAttr>();
5687 }
5688
5689 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5690 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005691 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5692 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005693 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005694 }
5695 } else {
5696 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5697 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5698 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005699 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005700 }
5701 if (RD->getDescribedClassTemplate()) {
5702 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5703 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005704 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005705 }
5706 }
5707
5708 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005709 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005710}
5711
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005712static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5713 // The capability attributes take a single string parameter for the name of
5714 // the capability they represent. The lockable attribute does not take any
5715 // parameters. However, semantically, both attributes represent the same
5716 // concept, and so they use the same semantic attribute. Eventually, the
5717 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005718 //
Alp Toker958027b2014-07-14 19:42:55 +00005719 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005720 // literal will be considered a "mutex."
5721 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005722 SourceLocation LiteralLoc;
5723 if (Attr.getKind() == AttributeList::AT_Capability &&
5724 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5725 return;
5726
Aaron Ballman6c810072014-03-05 21:47:13 +00005727 // Currently, there are only two names allowed for a capability: role and
5728 // mutex (case insensitive). Diagnose other capability names.
5729 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5730 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5731
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005732 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5733 Attr.getAttributeSpellingListIndex()));
5734}
5735
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005736static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5737 const AttributeList &Attr) {
Josh Gaoec1369e2017-08-08 19:44:34 +00005738 SmallVector<Expr*, 1> Args;
5739 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5740 return;
5741
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005742 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
Josh Gaoec1369e2017-08-08 19:44:34 +00005743 Args.data(), Args.size(),
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005744 Attr.getAttributeSpellingListIndex()));
5745}
5746
5747static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5748 const AttributeList &Attr) {
5749 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005750 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005751 return;
5752
5753 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5754 S.Context,
5755 Args.data(), Args.size(),
5756 Attr.getAttributeSpellingListIndex()));
5757}
5758
5759static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5760 const AttributeList &Attr) {
5761 SmallVector<Expr*, 2> Args;
5762 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5763 return;
5764
5765 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5766 S.Context,
5767 Attr.getArgAsExpr(0),
5768 Args.data(),
5769 Args.size(),
5770 Attr.getAttributeSpellingListIndex()));
5771}
5772
5773static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5774 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005775 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005776 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005777 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005778
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005779 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5780 Attr.getRange(), S.Context, Args.data(), Args.size(),
5781 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005782}
5783
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005784static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5785 const AttributeList &Attr) {
5786 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5787 return;
5788
5789 // check that all arguments are lockable objects
5790 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005791 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005792 if (Args.empty())
5793 return;
5794
5795 RequiresCapabilityAttr *RCA = ::new (S.Context)
5796 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5797 Args.size(), Attr.getAttributeSpellingListIndex());
5798
5799 D->addAttr(RCA);
5800}
5801
Aaron Ballman43f40102014-11-14 22:34:56 +00005802static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5803 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5804 if (NSD->isAnonymousNamespace()) {
5805 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5806 // Do not want to attach the attribute to the namespace because that will
5807 // cause confusing diagnostic reports for uses of declarations within the
5808 // namespace.
5809 return;
5810 }
5811 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005812
Manman Renc7890fe2016-03-16 18:50:49 +00005813 // Handle the cases where the attribute has a text message.
5814 StringRef Str, Replacement;
5815 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5816 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5817 return;
5818
5819 // Only support a single optional message for Declspec and CXX11.
5820 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5821 checkAttributeAtMostNumArgs(S, Attr, 1);
5822 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5823 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5824 return;
5825
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005826 if (!S.getLangOpts().CPlusPlus14)
5827 if (Attr.isCXX11Attribute() &&
5828 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005829 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005830
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005831 D->addAttr(::new (S.Context)
5832 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5833 Attr.getAttributeSpellingListIndex()));
5834}
5835
5836static bool isGlobalVar(const Decl *D) {
5837 if (const auto *S = dyn_cast<VarDecl>(D))
5838 return S->hasGlobalStorage();
5839 return false;
Aaron Ballman43f40102014-11-14 22:34:56 +00005840}
5841
Peter Collingbourne915df992015-05-15 18:33:32 +00005842static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5843 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5844 return;
5845
Benjamin Kramer1b582012016-02-13 18:11:49 +00005846 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005847
5848 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5849 StringRef SanitizerName;
5850 SourceLocation LiteralLoc;
5851
5852 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5853 return;
5854
5855 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5856 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005857 else if (isGlobalVar(D) && SanitizerName != "address")
5858 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5859 << Attr.getName() << ExpectedFunctionOrMethod;
Peter Collingbourne915df992015-05-15 18:33:32 +00005860 Sanitizers.push_back(SanitizerName);
5861 }
5862
5863 D->addAttr(::new (S.Context) NoSanitizeAttr(
5864 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5865 Attr.getAttributeSpellingListIndex()));
5866}
5867
5868static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5869 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005870 StringRef AttrName = Attr.getName()->getName();
5871 normalizeName(AttrName);
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005872 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5873 .Case("no_address_safety_analysis", "address")
5874 .Case("no_sanitize_address", "address")
5875 .Case("no_sanitize_thread", "thread")
5876 .Case("no_sanitize_memory", "memory");
5877 if (isGlobalVar(D) && SanitizerName != "address")
5878 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5879 << Attr.getName() << ExpectedFunction;
Peter Collingbourne915df992015-05-15 18:33:32 +00005880 D->addAttr(::new (S.Context)
5881 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5882 Attr.getAttributeSpellingListIndex()));
5883}
5884
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005885static void handleInternalLinkageAttr(Sema &S, Decl *D,
5886 const AttributeList &Attr) {
5887 if (InternalLinkageAttr *Internal =
5888 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5889 Attr.getAttributeSpellingListIndex()))
5890 D->addAttr(Internal);
5891}
5892
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005893static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5894 if (S.LangOpts.OpenCLVersion != 200)
5895 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5896 << Attr.getName() << "2.0" << 0;
5897 else
5898 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5899 << Attr.getName() << "2.0";
5900}
5901
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005902/// Handles semantic checking for features that are common to all attributes,
5903/// such as checking whether a parameter was properly specified, or the correct
5904/// number of arguments were passed, etc.
5905static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5906 const AttributeList &Attr) {
5907 // Several attributes carry different semantics than the parsing requires, so
Alex Lorenz24952fb2017-04-19 15:52:11 +00005908 // those are opted out of the common argument checks.
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005909 //
5910 // We also bail on unknown and ignored attributes because those are handled
5911 // as part of the target-specific handling logic.
Alex Lorenz24952fb2017-04-19 15:52:11 +00005912 if (Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005913 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005914 // Check whether the attribute requires specific language extensions to be
5915 // enabled.
5916 if (!Attr.diagnoseLangOpts(S))
5917 return true;
Alex Lorenz24952fb2017-04-19 15:52:11 +00005918 // Check whether the attribute appertains to the given subject.
5919 if (!Attr.diagnoseAppertainsTo(S, D))
5920 return true;
5921 if (Attr.hasCustomParsing())
5922 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005923
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005924 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5925 // If there are no optional arguments, then checking for the argument count
5926 // is trivial.
5927 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5928 return true;
5929 } else {
5930 // There are optional arguments, so checking is slightly more involved.
5931 if (Attr.getMinArgs() &&
5932 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5933 return true;
5934 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5935 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5936 return true;
5937 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005938
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005939 return false;
5940}
5941
Xiuli Pan11e13f62016-02-26 03:13:03 +00005942static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5943 const AttributeList &Attr) {
5944 if (D->isInvalidDecl())
5945 return;
5946
5947 // Check if there is only one access qualifier.
5948 if (D->hasAttr<OpenCLAccessAttr>()) {
5949 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5950 << D->getSourceRange();
5951 D->setInvalidDecl(true);
5952 return;
5953 }
5954
5955 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5956 // image object can be read and written.
5957 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5958 // object. Using the read_write (or __read_write) qualifier with the pipe
5959 // qualifier is a compilation error.
5960 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5961 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5962 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5963 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5964 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5965 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5966 D->setInvalidDecl(true);
5967 return;
5968 }
5969 }
5970 }
5971
5972 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5973 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5974}
5975
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005976//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005977// Top Level Sema Entry Points
5978//===----------------------------------------------------------------------===//
5979
Richard Smithf8a75c32013-08-29 00:47:48 +00005980/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5981/// the attribute applies to decls. If the attribute is a type attribute, just
5982/// silently ignore it if a GNU attribute.
5983static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5984 const AttributeList &Attr,
5985 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005986 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005987 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005988
Richard Smithf8a75c32013-08-29 00:47:48 +00005989 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5990 // instead.
5991 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5992 return;
5993
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005994 // Unknown attributes are automatically warned on. Target-specific attributes
5995 // which do not apply to the current target architecture are treated as
5996 // though they were unknown attributes.
5997 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005998 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005999 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
6000 ? diag::warn_unhandled_ms_attribute_ignored
6001 : diag::warn_unknown_attribute_ignored)
6002 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006003 return;
6004 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006005
Aaron Ballman8ee40b72013-09-09 23:33:17 +00006006 if (handleCommonAttributeFeatures(S, scope, D, Attr))
6007 return;
6008
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006009 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006010 default:
Richard Smith4f902c72016-03-08 00:32:55 +00006011 if (!Attr.isStmtAttr()) {
6012 // Type attributes are handled elsewhere; silently move on.
6013 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
6014 break;
6015 }
6016 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6017 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006018 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006019 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006020 handleInterruptAttr(S, D, Attr);
6021 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006022 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006023 handleX86ForceAlignArgPointerAttr(S, D, Attr);
6024 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006025 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006026 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00006027 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006028 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006029 case AttributeList::AT_Mips16:
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006030 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6031 MipsInterruptAttr>(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006032 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006033 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006034 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
6035 break;
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006036 case AttributeList::AT_MicroMips:
6037 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, Attr);
6038 break;
6039 case AttributeList::AT_NoMicroMips:
6040 handleSimpleAttribute<NoMicroMipsAttr>(S, D, Attr);
6041 break;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006042 case AttributeList::AT_MipsLongCall:
6043 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6044 S, D, Attr);
6045 break;
6046 case AttributeList::AT_MipsShortCall:
6047 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6048 S, D, Attr);
6049 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006050 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
6051 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
6052 break;
6053 case AttributeList::AT_AMDGPUWavesPerEU:
6054 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006055 break;
6056 case AttributeList::AT_AMDGPUNumSGPR:
6057 handleAMDGPUNumSGPRAttr(S, D, Attr);
6058 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006059 case AttributeList::AT_AMDGPUNumVGPR:
6060 handleAMDGPUNumVGPRAttr(S, D, Attr);
6061 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00006062 case AttributeList::AT_AVRSignal:
6063 handleAVRSignalAttr(S, D, Attr);
6064 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00006065 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006066 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
6067 break;
6068 case AttributeList::AT_IBOutlet:
6069 handleIBOutlet(S, D, Attr);
6070 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006071 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006072 handleIBOutletCollection(S, D, Attr);
6073 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00006074 case AttributeList::AT_IFunc:
6075 handleIFuncAttr(S, D, Attr);
6076 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006077 case AttributeList::AT_Alias:
6078 handleAliasAttr(S, D, Attr);
6079 break;
6080 case AttributeList::AT_Aligned:
6081 handleAlignedAttr(S, D, Attr);
6082 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00006083 case AttributeList::AT_AlignValue:
6084 handleAlignValueAttr(S, D, Attr);
6085 break;
George Burgess IVe3763372016-12-22 02:50:20 +00006086 case AttributeList::AT_AllocSize:
6087 handleAllocSizeAttr(S, D, Attr);
6088 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006089 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00006090 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006091 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006092 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006093 handleAnalyzerNoReturnAttr(S, D, Attr);
6094 break;
6095 case AttributeList::AT_TLSModel:
6096 handleTLSModelAttr(S, D, Attr);
6097 break;
6098 case AttributeList::AT_Annotate:
6099 handleAnnotateAttr(S, D, Attr);
6100 break;
6101 case AttributeList::AT_Availability:
6102 handleAvailabilityAttr(S, D, Attr);
6103 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006104 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00006105 handleDependencyAttr(S, scope, D, Attr);
6106 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006107 case AttributeList::AT_Common:
6108 handleCommonAttr(S, D, Attr);
6109 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006110 case AttributeList::AT_CUDAConstant:
Justin Lebare71b2fa2016-09-30 23:57:34 +00006111 handleConstantAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006112 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006113 case AttributeList::AT_PassObjectSize:
6114 handlePassObjectSizeAttr(S, D, Attr);
6115 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006116 case AttributeList::AT_Constructor:
6117 handleConstructorAttr(S, D, Attr);
6118 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006119 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006120 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
6121 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006122 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00006123 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006124 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006125 case AttributeList::AT_Destructor:
6126 handleDestructorAttr(S, D, Attr);
6127 break;
6128 case AttributeList::AT_EnableIf:
6129 handleEnableIfAttr(S, D, Attr);
6130 break;
George Burgess IV177399e2017-01-09 04:12:14 +00006131 case AttributeList::AT_DiagnoseIf:
6132 handleDiagnoseIfAttr(S, D, Attr);
6133 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006134 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006135 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006136 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +00006137 case AttributeList::AT_ExternalSourceSymbol:
6138 handleExternalSourceSymbolAttr(S, D, Attr);
6139 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00006140 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00006141 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00006142 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00006143 case AttributeList::AT_OptimizeNone:
6144 handleOptimizeNoneAttr(S, D, Attr);
6145 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00006146 case AttributeList::AT_FlagEnum:
6147 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
6148 break;
Akira Hatanaka3c268af2017-03-21 02:23:00 +00006149 case AttributeList::AT_EnumExtensibility:
6150 handleEnumExtensibilityAttr(S, D, Attr);
6151 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00006152 case AttributeList::AT_Flatten:
6153 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6154 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006155 case AttributeList::AT_Format:
6156 handleFormatAttr(S, D, Attr);
6157 break;
6158 case AttributeList::AT_FormatArg:
6159 handleFormatArgAttr(S, D, Attr);
6160 break;
6161 case AttributeList::AT_CUDAGlobal:
6162 handleGlobalAttr(S, D, Attr);
6163 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00006164 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006165 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6166 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006167 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006168 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006169 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6170 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006171 break;
6172 case AttributeList::AT_GNUInline:
6173 handleGNUInlineAttr(S, D, Attr);
6174 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006175 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006176 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00006177 break;
David Majnemer631a90b2015-02-04 07:23:21 +00006178 case AttributeList::AT_Restrict:
6179 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006180 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006181 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006182 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6183 break;
6184 case AttributeList::AT_Mode:
6185 handleModeAttr(S, D, Attr);
6186 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00006187 case AttributeList::AT_NoAlias:
6188 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6189 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006190 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006191 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6192 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00006193 case AttributeList::AT_NoSplitStack:
6194 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6195 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00006196 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006197 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6198 handleNonNullAttrParameter(S, PVD, Attr);
6199 else
6200 handleNonNullAttr(S, D, Attr);
6201 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00006202 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006203 handleReturnsNonNullAttr(S, D, Attr);
6204 break;
Hal Finkelee90a222014-09-26 05:04:30 +00006205 case AttributeList::AT_AssumeAligned:
6206 handleAssumeAlignedAttr(S, D, Attr);
6207 break;
Erich Keane623efd82017-03-30 21:48:55 +00006208 case AttributeList::AT_AllocAlign:
6209 handleAllocAlignAttr(S, D, Attr);
6210 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006211 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006212 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6213 break;
6214 case AttributeList::AT_Ownership:
6215 handleOwnershipAttr(S, D, Attr);
6216 break;
6217 case AttributeList::AT_Cold:
6218 handleColdAttr(S, D, Attr);
6219 break;
6220 case AttributeList::AT_Hot:
6221 handleHotAttr(S, D, Attr);
6222 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006223 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00006224 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006225 break;
6226 case AttributeList::AT_NoReturn:
6227 handleNoReturnAttr(S, D, Attr);
6228 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006229 case AttributeList::AT_NoThrow:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006230 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6231 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006232 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00006233 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006234 break;
6235 case AttributeList::AT_VecReturn:
6236 handleVecReturnAttr(S, D, Attr);
6237 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006238 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006239 handleObjCOwnershipAttr(S, D, Attr);
6240 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006241 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006242 handleObjCPreciseLifetimeAttr(S, D, Attr);
6243 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006244 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006245 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6246 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00006247 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006248 handleObjCRequiresSuperAttr(S, D, Attr);
6249 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00006250 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006251 handleObjCBridgeAttr(S, scope, D, Attr);
6252 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00006253 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006254 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6255 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00006256 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006257 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6258 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00006259 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006260 handleObjCDesignatedInitializer(S, D, Attr);
6261 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006262 case AttributeList::AT_ObjCRuntimeName:
6263 handleObjCRuntimeName(S, D, Attr);
6264 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006265 case AttributeList::AT_ObjCRuntimeVisible:
6266 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6267 break;
Alex Denisovfde64952015-06-26 05:28:36 +00006268 case AttributeList::AT_ObjCBoxable:
6269 handleObjCBoxable(S, D, Attr);
6270 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006271 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006272 handleCFAuditedTransferAttr(S, D, Attr);
6273 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006274 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006275 handleCFUnknownTransferAttr(S, D, Attr);
6276 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006277 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006278 case AttributeList::AT_NSConsumed:
6279 handleNSConsumedAttr(S, D, Attr);
6280 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006281 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006282 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6283 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006284 case AttributeList::AT_NSReturnsAutoreleased:
6285 case AttributeList::AT_NSReturnsNotRetained:
6286 case AttributeList::AT_CFReturnsNotRetained:
6287 case AttributeList::AT_NSReturnsRetained:
6288 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006289 handleNSReturnsRetainedAttr(S, D, Attr);
6290 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00006291 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006292 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6293 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006294 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006295 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6296 break;
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006297 case AttributeList::AT_OpenCLIntelReqdSubGroupSize:
6298 handleSubGroupSize(S, D, Attr);
6299 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00006300 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006301 handleVecTypeHint(S, D, Attr);
6302 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00006303 case AttributeList::AT_RequireConstantInit:
6304 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6305 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006306 case AttributeList::AT_InitPriority:
6307 handleInitPriorityAttr(S, D, Attr);
6308 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006309 case AttributeList::AT_Packed:
6310 handlePackedAttr(S, D, Attr);
6311 break;
6312 case AttributeList::AT_Section:
6313 handleSectionAttr(S, D, Attr);
6314 break;
Eric Christopher11acf732015-06-12 01:35:52 +00006315 case AttributeList::AT_Target:
6316 handleTargetAttr(S, D, Attr);
6317 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006318 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00006319 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006320 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006321 case AttributeList::AT_ArcWeakrefUnavailable:
6322 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6323 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006324 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006325 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6326 break;
Alex Lorenza8c44ba2016-10-28 10:25:10 +00006327 case AttributeList::AT_ObjCSubclassingRestricted:
6328 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6329 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00006330 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00006331 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00006332 break;
6333 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006334 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6335 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00006336 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00006337 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006338 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006339 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006340 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6341 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00006342 case AttributeList::AT_NotTailCalled:
6343 handleNotTailCalledAttr(S, D, Attr);
6344 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00006345 case AttributeList::AT_DisableTailCalls:
6346 handleDisableTailCallsAttr(S, D, Attr);
6347 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006348 case AttributeList::AT_Used:
6349 handleUsedAttr(S, D, Attr);
6350 break;
John McCalld041a9b2013-02-20 01:54:26 +00006351 case AttributeList::AT_Visibility:
6352 handleVisibilityAttr(S, D, Attr, false);
6353 break;
6354 case AttributeList::AT_TypeVisibility:
6355 handleVisibilityAttr(S, D, Attr, true);
6356 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00006357 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006358 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6359 break;
6360 case AttributeList::AT_WarnUnusedResult:
6361 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00006362 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00006363 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006364 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6365 break;
6366 case AttributeList::AT_WeakRef:
6367 handleWeakRefAttr(S, D, Attr);
6368 break;
6369 case AttributeList::AT_WeakImport:
6370 handleWeakImportAttr(S, D, Attr);
6371 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006372 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006373 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006374 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006375 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006376 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6377 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006378 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006379 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00006380 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006381 case AttributeList::AT_ObjCNSObject:
6382 handleObjCNSObject(S, D, Attr);
6383 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00006384 case AttributeList::AT_ObjCIndependentClass:
6385 handleObjCIndependentClass(S, D, Attr);
6386 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006387 case AttributeList::AT_Blocks:
6388 handleBlocksAttr(S, D, Attr);
6389 break;
6390 case AttributeList::AT_Sentinel:
6391 handleSentinelAttr(S, D, Attr);
6392 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006393 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006394 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6395 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006396 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006397 handleSimpleAttribute<PureAttr>(S, D, Attr);
6398 break;
6399 case AttributeList::AT_Cleanup:
6400 handleCleanupAttr(S, D, Attr);
6401 break;
6402 case AttributeList::AT_NoDebug:
6403 handleNoDebugAttr(S, D, Attr);
6404 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00006405 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006406 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6407 break;
Yaxun Liu7d07ae72016-11-01 18:45:32 +00006408 case AttributeList::AT_Convergent:
6409 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6410 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006411 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006412 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6413 break;
6414 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6415 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6416 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006417 case AttributeList::AT_StdCall:
6418 case AttributeList::AT_CDecl:
6419 case AttributeList::AT_FastCall:
6420 case AttributeList::AT_ThisCall:
6421 case AttributeList::AT_Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00006422 case AttributeList::AT_RegCall:
John McCall477f2bb2016-03-03 06:39:32 +00006423 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00006424 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00006425 case AttributeList::AT_MSABI:
6426 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006427 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00006428 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00006429 case AttributeList::AT_PreserveMost:
6430 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006431 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00006432 break;
Matthias Gehre01a63382017-03-27 19:45:24 +00006433 case AttributeList::AT_Suppress:
6434 handleSuppressAttr(S, D, Attr);
6435 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006436 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006437 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6438 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00006439 case AttributeList::AT_OpenCLAccess:
6440 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006441 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00006442 case AttributeList::AT_OpenCLNoSVM:
6443 handleOpenCLNoSVMAttr(S, D, Attr);
6444 break;
John McCall477f2bb2016-03-03 06:39:32 +00006445 case AttributeList::AT_SwiftContext:
6446 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6447 break;
6448 case AttributeList::AT_SwiftErrorResult:
6449 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6450 break;
6451 case AttributeList::AT_SwiftIndirectResult:
6452 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6453 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00006454 case AttributeList::AT_InternalLinkage:
6455 handleInternalLinkageAttr(S, D, Attr);
6456 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00006457 case AttributeList::AT_LTOVisibilityPublic:
6458 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6459 break;
John McCall8d32c052012-05-22 21:28:12 +00006460
6461 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00006462 case AttributeList::AT_EmptyBases:
6463 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6464 break;
6465 case AttributeList::AT_LayoutVersion:
6466 handleLayoutVersion(S, D, Attr);
6467 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006468 case AttributeList::AT_MSNoVTable:
6469 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00006470 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006471 case AttributeList::AT_MSStruct:
6472 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00006473 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006474 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006475 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00006476 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00006477 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006478 handleMSInheritanceAttr(S, D, Attr);
6479 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00006480 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006481 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6482 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00006483 case AttributeList::AT_Thread:
6484 handleDeclspecThreadAttr(S, D, Attr);
6485 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00006486
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00006487 case AttributeList::AT_AbiTag:
6488 handleAbiTagAttr(S, D, Attr);
6489 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006490
6491 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00006492 case AttributeList::AT_AssertExclusiveLock:
6493 handleAssertExclusiveLockAttr(S, D, Attr);
6494 break;
6495 case AttributeList::AT_AssertSharedLock:
6496 handleAssertSharedLockAttr(S, D, Attr);
6497 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006498 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006499 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6500 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006501 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00006502 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006503 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006504 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006505 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6506 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00006507 case AttributeList::AT_NoSanitize:
6508 handleNoSanitizeAttr(S, D, Attr);
6509 break;
6510 case AttributeList::AT_NoSanitizeSpecific:
6511 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00006512 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006513 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006514 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00006515 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006516 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006517 handleGuardedByAttr(S, D, Attr);
6518 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006519 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00006520 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006521 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006522 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006523 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006524 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006525 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006526 handleLockReturnedAttr(S, D, Attr);
6527 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006528 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006529 handleLocksExcludedAttr(S, D, Attr);
6530 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006531 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006532 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006533 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006534 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00006535 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006536 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006537 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00006538 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006539 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006540
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006541 // Capability analysis attributes.
6542 case AttributeList::AT_Capability:
6543 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006544 handleCapabilityAttr(S, D, Attr);
6545 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006546 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006547 handleRequiresCapabilityAttr(S, D, Attr);
6548 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006549
6550 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006551 handleAssertCapabilityAttr(S, D, Attr);
6552 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006553 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006554 handleAcquireCapabilityAttr(S, D, Attr);
6555 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006556 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006557 handleReleaseCapabilityAttr(S, D, Attr);
6558 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006559 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006560 handleTryAcquireCapabilityAttr(S, D, Attr);
6561 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006562
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00006563 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00006564 case AttributeList::AT_Consumable:
6565 handleConsumableAttr(S, D, Attr);
6566 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006567 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006568 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6569 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006570 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006571 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6572 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00006573 case AttributeList::AT_CallableWhen:
6574 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006575 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00006576 case AttributeList::AT_ParamTypestate:
6577 handleParamTypestateAttr(S, D, Attr);
6578 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00006579 case AttributeList::AT_ReturnTypestate:
6580 handleReturnTypestateAttr(S, D, Attr);
6581 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006582 case AttributeList::AT_SetTypestate:
6583 handleSetTypestateAttr(S, D, Attr);
6584 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00006585 case AttributeList::AT_TestTypestate:
6586 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006587 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006588
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00006589 // Type safety attributes.
6590 case AttributeList::AT_ArgumentWithTypeTag:
6591 handleArgumentWithTypeTagAttr(S, D, Attr);
6592 break;
6593 case AttributeList::AT_TypeTagForDatatype:
6594 handleTypeTagForDatatypeAttr(S, D, Attr);
6595 break;
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006596 case AttributeList::AT_AnyX86NoCallerSavedRegisters:
6597 handleNoCallerSavedRegsAttr(S, D, Attr);
6598 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006599 case AttributeList::AT_RenderScriptKernel:
6600 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006601 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006602 // XRay attributes.
6603 case AttributeList::AT_XRayInstrument:
6604 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6605 break;
Dean Michael Berris418da3f2017-03-06 07:08:21 +00006606 case AttributeList::AT_XRayLogArgs:
6607 handleXRayLogArgsAttr(S, D, Attr);
6608 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006609 }
6610}
6611
6612/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6613/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006614void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006615 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006616 bool IncludeCXX11Attributes) {
6617 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006618 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006619
Joey Gouly2cd9db12013-12-13 16:15:28 +00006620 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006621 // GCC accepts
6622 // static int a9 __attribute__((weakref));
6623 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006624 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006625 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6626 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006627 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006628 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006629 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006630
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006631 // FIXME: We should be able to handle this in TableGen as well. It would be
6632 // good to have a way to specify "these attributes must appear as a group",
6633 // for these. Additionally, it would be good to have a way to specify "these
6634 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006635 if (!D->hasAttr<OpenCLKernelAttr>()) {
6636 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006637 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006638 // FIXME: This emits a different error message than
6639 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006640 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006641 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006642 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006643 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006644 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006645 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006646 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006647 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006648 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6649 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6650 << A << ExpectedKernelFunction;
6651 D->setInvalidDecl();
6652 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006653 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6654 << A << ExpectedKernelFunction;
6655 D->setInvalidDecl();
6656 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6657 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6658 << A << ExpectedKernelFunction;
6659 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006660 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6661 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6662 << A << ExpectedKernelFunction;
6663 D->setInvalidDecl();
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006664 } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6665 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6666 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006667 }
6668 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006669}
6670
Hiroshi Inoue939d9322017-06-30 05:40:31 +00006671// Helper for delayed processing TransparentUnion attribute.
Erich Keane2fe684b2017-02-28 20:44:39 +00006672void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6673 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6674 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6675 handleTransparentUnionAttr(*this, D, *Attr);
6676 break;
6677 }
6678}
6679
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006680// Annotation attributes are the only attributes allowed after an access
6681// specifier.
6682bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6683 const AttributeList *AttrList) {
6684 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006685 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006686 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006687 } else {
6688 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6689 return true;
6690 }
6691 }
6692
6693 return false;
6694}
6695
John McCall42856de2011-10-01 05:17:03 +00006696/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6697/// contains any decl attributes that we should warn about.
6698static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6699 for ( ; A; A = A->getNext()) {
6700 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00006701 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006702 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6703
6704 if (A->getKind() == AttributeList::UnknownAttribute) {
6705 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6706 << A->getName() << A->getRange();
6707 } else {
6708 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6709 << A->getName() << A->getRange();
6710 }
6711 }
6712}
6713
6714/// checkUnusedDeclAttributes - Given a declarator which is not being
6715/// used to build a declaration, complain about any decl attributes
6716/// which might be lying around on it.
6717void Sema::checkUnusedDeclAttributes(Declarator &D) {
6718 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6719 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6720 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6721 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6722}
6723
Ryan Flynn7d470f32009-07-30 03:15:39 +00006724/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006725/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006726NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6727 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006728 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006729 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006731 FunctionDecl *NewFD;
6732 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006733 // FIXME: Mangling?
6734 // FIXME: Is the qualifier info correct?
6735 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006736 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6737 Loc, Loc, DeclarationName(II),
6738 FD->getType(), FD->getTypeSourceInfo(),
6739 SC_None, false/*isInlineSpecified*/,
6740 FD->hasPrototype(),
6741 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006742 NewD = NewFD;
6743
6744 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006745 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006746
6747 // Fake up parameter variables; they are declared as if this were
6748 // a typedef.
6749 QualType FDTy = FD->getType();
6750 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6751 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006752 for (const auto &AI : FT->param_types()) {
6753 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006754 Param->setScopeInfo(0, Params.size());
6755 Params.push_back(Param);
6756 }
David Blaikie9c70e042011-09-21 18:16:56 +00006757 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006758 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006759 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6760 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006761 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006762 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006763 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006764 if (VD->getQualifier()) {
6765 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006766 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006767 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006768 }
6769 return NewD;
6770}
6771
James Dennett634962f2012-06-14 21:40:34 +00006772/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006773/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006774void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006775 if (W.getUsed()) return; // only do this once
6776 W.setUsed(true);
6777 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6778 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006779 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006780 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6781 W.getLocation()));
6782 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006783 WeakTopLevelDecl.push_back(NewD);
6784 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6785 // to insert Decl at TU scope, sorry.
6786 DeclContext *SavedContext = CurContext;
6787 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006788 NewD->setDeclContext(CurContext);
6789 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006790 PushOnScopeChains(NewD, S);
6791 CurContext = SavedContext;
6792 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006793 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006794 }
6795}
6796
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006797void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6798 // It's valid to "forward-declare" #pragma weak, in which case we
6799 // have to do this.
6800 LoadExternalWeakUndeclaredIdentifiers();
6801 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006802 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006803 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6804 if (VD->isExternC())
6805 ND = VD;
6806 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6807 if (FD->isExternC())
6808 ND = FD;
6809 if (ND) {
6810 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006811 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006812 if (I != WeakUndeclaredIdentifiers.end()) {
6813 WeakInfo W = I->second;
6814 DeclApplyPragmaWeak(S, ND, W);
6815 WeakUndeclaredIdentifiers[Id] = W;
6816 }
6817 }
6818 }
6819 }
6820}
6821
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006822/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6823/// it, apply them to D. This is a bit tricky because PD can have attributes
6824/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006825void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006826 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006827 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006828 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006829
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006830 // Walk the declarator structure, applying decl attributes that were in a type
6831 // position to the decl itself. This handles cases like:
6832 // int *__attr__(x)** D;
6833 // when X is a decl attribute.
6834 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6835 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006836 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006837
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006838 // Finally, apply any attributes on the decl itself.
6839 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006840 ProcessDeclAttributeList(S, D, Attrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00006841
6842 // Apply additional attributes specified by '#pragma clang attribute'.
6843 AddPragmaAttributes(S, D);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006844}
John McCall28a6aea2009-11-04 02:18:39 +00006845
John McCall31168b02011-06-15 23:02:42 +00006846/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006847/// If so, it'll still be annotated with an attribute that makes it
6848/// illegal to actually use.
6849static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6850 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006851 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006852 // Private ivars are always okay. Unfortunately, people don't
6853 // always properly make their ivars private, even in system headers.
6854 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006855 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6856 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006857 return false;
6858
John McCallc6af8c62015-10-28 05:03:19 +00006859 // Silently accept unsupported uses of __weak in both user and system
6860 // declarations when it's been disabled, for ease of integration with
6861 // -fno-objc-arc files. We do have to take some care against attempts
6862 // to define such things; for now, we've only done that for ivars
6863 // and properties.
6864 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6865 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6866 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6867 reason = UnavailableAttr::IR_ForbiddenWeak;
6868 return true;
6869 }
John McCallb61e14e2015-10-27 04:54:50 +00006870 }
6871
John McCallc6af8c62015-10-28 05:03:19 +00006872 // Allow all sorts of things in system headers.
6873 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6874 // Currently, all the failures dealt with this way are due to ARC
6875 // restrictions.
6876 reason = UnavailableAttr::IR_ARCForbiddenType;
6877 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006878 }
6879
6880 return false;
John McCall31168b02011-06-15 23:02:42 +00006881}
6882
6883/// Handle a delayed forbidden-type diagnostic.
6884static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6885 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006886 auto reason = UnavailableAttr::IR_None;
6887 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6888 assert(reason && "didn't set reason?");
6889 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6890 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006891 return;
6892 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006893 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006895 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006896 // kind of forbidden type messages on unavailable functions.
6897 if (FD->hasAttr<UnavailableAttr>() &&
6898 diag.getForbiddenTypeDiagnostic() ==
6899 diag::err_arc_array_param_no_ownership) {
6900 diag.Triggered = true;
6901 return;
6902 }
6903 }
John McCall31168b02011-06-15 23:02:42 +00006904
6905 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6906 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6907 diag.Triggered = true;
6908}
6909
Manman Ren45b1ab12016-05-06 19:57:16 +00006910static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6911 const Decl *D) {
6912 // Check each AvailabilityAttr to find the one for this platform.
6913 for (const auto *A : D->attrs()) {
6914 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6915 // FIXME: this is copied from CheckAvailability. We should try to
6916 // de-duplicate.
6917
6918 // Check if this is an App Extension "platform", and if so chop off
6919 // the suffix for matching with the actual platform.
6920 StringRef ActualPlatform = Avail->getPlatform()->getName();
6921 StringRef RealizedPlatform = ActualPlatform;
6922 if (Context.getLangOpts().AppExt) {
6923 size_t suffix = RealizedPlatform.rfind("_app_extension");
6924 if (suffix != StringRef::npos)
6925 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6926 }
6927
6928 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6929
6930 // Match the platform name.
6931 if (RealizedPlatform == TargetPlatform)
6932 return Avail;
6933 }
6934 }
6935 return nullptr;
6936}
6937
Erik Pilkington9f866a72017-07-18 20:32:07 +00006938/// The diagnostic we should emit for \c D, and the declaration that
6939/// originated it, or \c AR_Available.
6940///
6941/// \param D The declaration to check.
6942/// \param Message If non-null, this will be populated with the message from
6943/// the availability attribute that is selected.
6944static std::pair<AvailabilityResult, const NamedDecl *>
6945ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message) {
6946 AvailabilityResult Result = D->getAvailability(Message);
6947
6948 // For typedefs, if the typedef declaration appears available look
6949 // to the underlying type to see if it is more restrictive.
6950 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6951 if (Result == AR_Available) {
6952 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6953 D = TT->getDecl();
6954 Result = D->getAvailability(Message);
6955 continue;
6956 }
6957 }
6958 break;
6959 }
6960
6961 // Forward class declarations get their attributes from their definition.
6962 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
6963 if (IDecl->getDefinition()) {
6964 D = IDecl->getDefinition();
6965 Result = D->getAvailability(Message);
6966 }
6967 }
6968
6969 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
6970 if (Result == AR_Available) {
6971 const DeclContext *DC = ECD->getDeclContext();
6972 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
6973 Result = TheEnumDecl->getAvailability(Message);
6974 D = TheEnumDecl;
6975 }
6976 }
6977
6978 return {Result, D};
6979}
6980
6981
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006982/// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6983/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6984/// in a deprecated context, but not the other way around.
6985static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6986 VersionTuple DeclVersion,
6987 Decl *Ctx) {
6988 assert(K != AR_Available && "Expected an unavailable declaration here!");
6989
6990 // Checks if we should emit the availability diagnostic in the context of C.
6991 auto CheckContext = [&](const Decl *C) {
6992 if (K == AR_NotYetIntroduced) {
6993 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6994 if (AA->getIntroduced() >= DeclVersion)
6995 return true;
6996 } else if (K == AR_Deprecated)
6997 if (C->isDeprecated())
6998 return true;
6999
7000 if (C->isUnavailable())
7001 return true;
7002 return false;
7003 };
7004
7005 // FIXME: This is a temporary workaround! Some existing Apple headers depends
7006 // on nested declarations in an @interface having the availability of the
7007 // interface when they really shouldn't: they are members of the enclosing
7008 // context, and can referenced from there.
7009 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
7010 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
7011 if (CheckContext(OrigCtx))
7012 return false;
7013
7014 // An implementation implicitly has the availability of the interface.
7015 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
7016 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7017 if (CheckContext(Interface))
7018 return false;
7019 }
7020 // A category implicitly has the availability of the interface.
7021 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
7022 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7023 if (CheckContext(Interface))
7024 return false;
7025 }
7026
7027 do {
7028 if (CheckContext(Ctx))
7029 return false;
7030
7031 // An implementation implicitly has the availability of the interface.
7032 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7033 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7034 if (CheckContext(Interface))
7035 return false;
7036 }
7037 // A category implicitly has the availability of the interface.
7038 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7039 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7040 if (CheckContext(Interface))
7041 return false;
7042 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7043
7044 return true;
7045}
7046
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007047static bool
7048shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7049 const VersionTuple &DeploymentVersion,
7050 const VersionTuple &DeclVersion) {
7051 const auto &Triple = Context.getTargetInfo().getTriple();
7052 VersionTuple ForceAvailabilityFromVersion;
7053 switch (Triple.getOS()) {
7054 case llvm::Triple::IOS:
7055 case llvm::Triple::TvOS:
7056 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7057 break;
7058 case llvm::Triple::WatchOS:
7059 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7060 break;
7061 case llvm::Triple::Darwin:
7062 case llvm::Triple::MacOSX:
7063 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7064 break;
7065 default:
7066 // New targets should always warn about availability.
7067 return Triple.getVendor() == llvm::Triple::Apple;
7068 }
7069 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7070 DeclVersion >= ForceAvailabilityFromVersion;
7071}
7072
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007073static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7074 for (Decl *Ctx = OrigCtx; Ctx;
7075 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7076 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7077 return cast<NamedDecl>(Ctx);
7078 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7079 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7080 return Imp->getClassInterface();
7081 return CD;
7082 }
7083 }
7084
7085 return dyn_cast<NamedDecl>(OrigCtx);
7086}
7087
Alex Lorenz727c21e2017-07-26 13:58:02 +00007088namespace {
7089
7090struct AttributeInsertion {
7091 StringRef Prefix;
7092 SourceLocation Loc;
7093 StringRef Suffix;
7094
7095 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7096 return {" ", D->getLocEnd(), ""};
7097 }
7098 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7099 return {" ", Loc, ""};
7100 }
7101 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7102 return {"", D->getLocStart(), "\n"};
7103 }
7104};
7105
7106} // end anonymous namespace
7107
7108/// Returns a source location in which it's appropriate to insert a new
7109/// attribute for the given declaration \D.
7110static Optional<AttributeInsertion>
7111createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7112 const LangOptions &LangOpts) {
7113 if (isa<ObjCPropertyDecl>(D))
7114 return AttributeInsertion::createInsertionAfter(D);
7115 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7116 if (MD->hasBody())
7117 return None;
7118 return AttributeInsertion::createInsertionAfter(D);
7119 }
7120 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7121 SourceLocation Loc =
7122 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7123 if (Loc.isInvalid())
7124 return None;
7125 // Insert after the 'struct'/whatever keyword.
7126 return AttributeInsertion::createInsertionAfter(Loc);
7127 }
7128 return AttributeInsertion::createInsertionBefore(D);
7129}
7130
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007131/// Actually emit an availability diagnostic for a reference to an unavailable
7132/// decl.
7133///
7134/// \param Ctx The context that the reference occurred in
7135/// \param ReferringDecl The exact declaration that was referenced.
7136/// \param OffendingDecl A related decl to \c ReferringDecl that has an
7137/// availability attribute corrisponding to \c K attached to it. Note that this
7138/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7139/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7140/// and OffendingDecl is the EnumDecl.
Erik Pilkington796a3e22016-08-05 22:59:03 +00007141static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007142 Decl *Ctx, const NamedDecl *ReferringDecl,
7143 const NamedDecl *OffendingDecl,
Aaron Ballmanfb237522014-10-15 15:37:51 +00007144 StringRef Message, SourceLocation Loc,
7145 const ObjCInterfaceDecl *UnknownObjCClass,
7146 const ObjCPropertyDecl *ObjCProperty,
7147 bool ObjCPropertyAccess) {
7148 // Diagnostics for deprecated or unavailable.
7149 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00007150 unsigned diag_available_here = diag::note_availability_specified_here;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007151 SourceLocation NoteLocation = OffendingDecl->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007152
7153 // Matches 'diag::note_property_attribute' options.
7154 unsigned property_note_select;
7155
7156 // Matches diag::note_availability_specified_here.
7157 unsigned available_here_select_kind;
7158
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007159 VersionTuple DeclVersion;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007160 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007161 DeclVersion = AA->getIntroduced();
7162
7163 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
7164 return;
7165
Aaron Ballmanfb237522014-10-15 15:37:51 +00007166 switch (K) {
Erik Pilkington796a3e22016-08-05 22:59:03 +00007167 case AR_Deprecated:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007168 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7169 : diag::warn_property_method_deprecated;
7170 diag_message = diag::warn_deprecated_message;
7171 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7172 property_note_select = /* deprecated */ 0;
7173 available_here_select_kind = /* deprecated */ 2;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007174 if (const auto *attr = OffendingDecl->getAttr<DeprecatedAttr>())
Erich Keanea32910d2017-03-23 18:51:54 +00007175 NoteLocation = attr->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007176 break;
7177
Erik Pilkington796a3e22016-08-05 22:59:03 +00007178 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007179 diag = !ObjCPropertyAccess ? diag::err_unavailable
7180 : diag::err_property_method_unavailable;
7181 diag_message = diag::err_unavailable_message;
7182 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7183 property_note_select = /* unavailable */ 1;
7184 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00007185
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007186 if (auto attr = OffendingDecl->getAttr<UnavailableAttr>()) {
John McCallc6af8c62015-10-28 05:03:19 +00007187 if (attr->isImplicit() && attr->getImplicitReason()) {
7188 // Most of these failures are due to extra restrictions in ARC;
7189 // reflect that in the primary diagnostic when applicable.
7190 auto flagARCError = [&] {
7191 if (S.getLangOpts().ObjCAutoRefCount &&
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007192 S.getSourceManager().isInSystemHeader(
7193 OffendingDecl->getLocation()))
John McCallc6af8c62015-10-28 05:03:19 +00007194 diag = diag::err_unavailable_in_arc;
7195 };
7196
7197 switch (attr->getImplicitReason()) {
7198 case UnavailableAttr::IR_None: break;
7199
7200 case UnavailableAttr::IR_ARCForbiddenType:
7201 flagARCError();
7202 diag_available_here = diag::note_arc_forbidden_type;
7203 break;
7204
7205 case UnavailableAttr::IR_ForbiddenWeak:
7206 if (S.getLangOpts().ObjCWeakRuntime)
7207 diag_available_here = diag::note_arc_weak_disabled;
7208 else
7209 diag_available_here = diag::note_arc_weak_no_runtime;
7210 break;
7211
7212 case UnavailableAttr::IR_ARCForbiddenConversion:
7213 flagARCError();
7214 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7215 break;
7216
7217 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7218 flagARCError();
7219 diag_available_here = diag::note_arc_init_returns_unrelated;
7220 break;
7221
7222 case UnavailableAttr::IR_ARCFieldWithOwnership:
7223 flagARCError();
7224 diag_available_here = diag::note_arc_field_with_ownership;
7225 break;
7226 }
7227 }
John McCallb61e14e2015-10-27 04:54:50 +00007228 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00007229 break;
7230
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007231 case AR_NotYetIntroduced: {
7232 // We would like to emit the diagnostic even if -Wunguarded-availability is
7233 // not specified for deployment targets >= to iOS 11 or equivalent or
7234 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7235 // later.
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007236 const AvailabilityAttr *AA =
7237 getAttrForPlatform(S.getASTContext(), OffendingDecl);
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007238 VersionTuple Introduced = AA->getIntroduced();
7239 bool NewWarning = shouldDiagnoseAvailabilityByDefault(
7240 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7241 Introduced);
7242 diag = NewWarning ? diag::warn_partial_availability_new
7243 : diag::warn_partial_availability;
7244 diag_message = NewWarning ? diag::warn_partial_message_new
7245 : diag::warn_partial_message;
7246 diag_fwdclass_message = NewWarning ? diag::warn_partial_fwdclass_message_new
7247 : diag::warn_partial_fwdclass_message;
Nico Weber0055a192015-03-19 19:18:22 +00007248 property_note_select = /* partial */ 2;
7249 available_here_select_kind = /* partial */ 3;
7250 break;
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007251 }
Erik Pilkington796a3e22016-08-05 22:59:03 +00007252
7253 case AR_Available:
7254 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00007255 }
7256
Manman Renc7890fe2016-03-16 18:50:49 +00007257 CharSourceRange UseRange;
7258 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00007259 if (K == AR_Deprecated) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007260 if (auto attr = OffendingDecl->getAttr<DeprecatedAttr>())
Manman Renc7890fe2016-03-16 18:50:49 +00007261 Replacement = attr->getReplacement();
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007262 if (auto attr = getAttrForPlatform(S.Context, OffendingDecl))
Manman Ren75bc6762016-03-21 17:30:55 +00007263 Replacement = attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00007264
7265 if (!Replacement.empty())
7266 UseRange =
7267 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7268 }
7269
Aaron Ballmanfb237522014-10-15 15:37:51 +00007270 if (!Message.empty()) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007271 S.Diag(Loc, diag_message) << ReferringDecl << Message
Manman Renc7890fe2016-03-16 18:50:49 +00007272 << (UseRange.isValid() ?
7273 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007274 if (ObjCProperty)
7275 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7276 << ObjCProperty->getDeclName() << property_note_select;
7277 } else if (!UnknownObjCClass) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007278 S.Diag(Loc, diag) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007279 << (UseRange.isValid() ?
7280 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007281 if (ObjCProperty)
7282 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7283 << ObjCProperty->getDeclName() << property_note_select;
7284 } else {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007285 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007286 << (UseRange.isValid() ?
7287 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007288 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7289 }
7290
Manman Ren45b1ab12016-05-06 19:57:16 +00007291 // The declaration can have multiple availability attributes, we are looking
7292 // at one of them.
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007293 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
Manman Ren45b1ab12016-05-06 19:57:16 +00007294 if (A && A->isInherited()) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007295 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
Manman Ren45b1ab12016-05-06 19:57:16 +00007296 Redecl = Redecl->getPreviousDecl()) {
7297 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
7298 Redecl);
7299 if (AForRedecl && !AForRedecl->isInherited()) {
7300 // If D is a declaration with inherited attributes, the note should
7301 // point to the declaration with actual attributes.
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007302 S.Diag(Redecl->getLocation(), diag_available_here) << OffendingDecl
Manman Ren45b1ab12016-05-06 19:57:16 +00007303 << available_here_select_kind;
7304 break;
7305 }
7306 }
7307 }
7308 else
Erich Keanea32910d2017-03-23 18:51:54 +00007309 S.Diag(NoteLocation, diag_available_here)
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007310 << OffendingDecl << available_here_select_kind;
Manman Ren45b1ab12016-05-06 19:57:16 +00007311
Erik Pilkington796a3e22016-08-05 22:59:03 +00007312 if (K == AR_NotYetIntroduced)
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007313 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7314 if (auto *TD = dyn_cast<TagDecl>(Enclosing))
7315 if (TD->getDeclName().isEmpty()) {
7316 S.Diag(TD->getLocation(), diag::note_partial_availability_silence)
7317 << /*Anonymous*/1 << TD->getKindName();
7318 return;
7319 }
Alex Lorenz727c21e2017-07-26 13:58:02 +00007320 auto FixitNoteDiag = S.Diag(Enclosing->getLocation(),
7321 diag::note_partial_availability_silence)
7322 << /*Named*/ 0 << Enclosing;
7323 // Don't offer a fixit for declarations with availability attributes.
7324 if (Enclosing->hasAttr<AvailabilityAttr>())
7325 return;
7326 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7327 return;
7328 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7329 Enclosing, S.getSourceManager(), S.getLangOpts());
7330 if (!Insertion)
7331 return;
7332 std::string PlatformName =
7333 AvailabilityAttr::getPlatformNameSourceSpelling(
7334 S.getASTContext().getTargetInfo().getPlatformName())
7335 .lower();
7336 std::string Introduced =
7337 OffendingDecl->getVersionIntroduced().getAsString();
7338 FixitNoteDiag << FixItHint::CreateInsertion(
7339 Insertion->Loc,
7340 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7341 "(" + Introduced + "))" + Insertion->Suffix)
7342 .str());
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007343 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00007344}
7345
7346static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7347 Decl *Ctx) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007348 assert(DD.Kind == DelayedDiagnostic::Availability &&
7349 "Expected an availability diagnostic here");
7350
Aaron Ballmanfb237522014-10-15 15:37:51 +00007351 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00007352 DoEmitAvailabilityWarning(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007353 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7354 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc,
7355 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00007356}
7357
John McCall2ec85372012-05-07 06:16:41 +00007358void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7359 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00007360 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00007361 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00007362
John McCall2ec85372012-05-07 06:16:41 +00007363 // When delaying diagnostics to run in the context of a parsed
7364 // declaration, we only want to actually emit anything if parsing
7365 // succeeds.
7366 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00007367
John McCall2ec85372012-05-07 06:16:41 +00007368 // We emit all the active diagnostics in this pool or any of its
7369 // parents. In general, we'll get one pool for the decl spec
7370 // and a child pool for each declarator; in a decl group like:
7371 // deprecated_typedef foo, *bar, baz();
7372 // only the declarator pops will be passed decls. This is correct;
7373 // we really do need to consider delayed diagnostics from the decl spec
7374 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00007375 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00007376 do {
John McCall6347b682012-05-07 06:16:58 +00007377 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00007378 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7379 // This const_cast is a bit lame. Really, Triggered should be mutable.
7380 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00007381 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00007382 continue;
7383
John McCallc1465822011-02-14 07:13:47 +00007384 switch (diag.Kind) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007385 case DelayedDiagnostic::Availability:
Ted Kremenekb79ee572013-12-18 23:30:06 +00007386 // Don't bother giving deprecation/unavailable diagnostics if
7387 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00007388 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00007389 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00007390 break;
7391
7392 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00007393 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00007394 break;
John McCall31168b02011-06-15 23:02:42 +00007395
7396 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00007397 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00007398 break;
John McCall86121512010-01-27 03:50:35 +00007399 }
7400 }
John McCall2ec85372012-05-07 06:16:41 +00007401 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00007402}
7403
John McCall6347b682012-05-07 06:16:58 +00007404/// Given a set of delayed diagnostics, re-emit them as if they had
7405/// been delayed in the current context instead of in the given pool.
7406/// Essentially, this just moves them to the current pool.
7407void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7408 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7409 assert(curPool && "re-emitting in undelayed context not supported");
7410 curPool->steal(pool);
7411}
7412
Erik Pilkington9f866a72017-07-18 20:32:07 +00007413static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7414 const NamedDecl *ReferringDecl,
7415 const NamedDecl *OffendingDecl,
7416 StringRef Message, SourceLocation Loc,
7417 const ObjCInterfaceDecl *UnknownObjCClass,
7418 const ObjCPropertyDecl *ObjCProperty,
7419 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00007420 // Delay if we're currently parsing a declaration.
Erik Pilkington9f866a72017-07-18 20:32:07 +00007421 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7422 S.DelayedDiagnostics.add(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007423 DelayedDiagnostic::makeAvailability(
7424 AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass,
7425 ObjCProperty, Message, ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00007426 return;
7427 }
7428
Erik Pilkington9f866a72017-07-18 20:32:07 +00007429 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7430 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007431 Message, Loc, UnknownObjCClass, ObjCProperty,
7432 ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00007433}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00007434
Erik Pilkington5cd57172016-08-16 17:44:11 +00007435namespace {
7436
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007437/// Returns true if the given statement can be a body-like child of \p Parent.
7438bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7439 switch (Parent->getStmtClass()) {
7440 case Stmt::IfStmtClass:
7441 return cast<IfStmt>(Parent)->getThen() == S ||
7442 cast<IfStmt>(Parent)->getElse() == S;
7443 case Stmt::WhileStmtClass:
7444 return cast<WhileStmt>(Parent)->getBody() == S;
7445 case Stmt::DoStmtClass:
7446 return cast<DoStmt>(Parent)->getBody() == S;
7447 case Stmt::ForStmtClass:
7448 return cast<ForStmt>(Parent)->getBody() == S;
7449 case Stmt::CXXForRangeStmtClass:
7450 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7451 case Stmt::ObjCForCollectionStmtClass:
7452 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7453 case Stmt::CaseStmtClass:
7454 case Stmt::DefaultStmtClass:
7455 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7456 default:
7457 return false;
7458 }
7459}
7460
7461class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7462 const Stmt *Target;
7463
7464public:
7465 bool VisitStmt(Stmt *S) { return S != Target; }
7466
7467 /// Returns true if the given statement is present in the given declaration.
7468 static bool isContained(const Stmt *Target, const Decl *D) {
7469 StmtUSEFinder Visitor;
7470 Visitor.Target = Target;
7471 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7472 }
7473};
7474
7475/// Traverses the AST and finds the last statement that used a given
7476/// declaration.
7477class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7478 const Decl *D;
7479
7480public:
7481 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7482 if (DRE->getDecl() == D)
7483 return false;
7484 return true;
7485 }
7486
7487 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7488 const CompoundStmt *Scope) {
7489 LastDeclUSEFinder Visitor;
7490 Visitor.D = D;
7491 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
7492 const Stmt *S = *I;
7493 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
7494 return S;
7495 }
7496 return nullptr;
7497 }
7498};
7499
Erik Pilkington5cd57172016-08-16 17:44:11 +00007500/// \brief This class implements -Wunguarded-availability.
7501///
7502/// This is done with a traversal of the AST of a function that makes reference
7503/// to a partially available declaration. Whenever we encounter an \c if of the
7504/// form: \c if(@available(...)), we use the version from the condition to visit
7505/// the then statement.
7506class DiagnoseUnguardedAvailability
7507 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7508 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7509
7510 Sema &SemaRef;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007511 Decl *Ctx;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007512
7513 /// Stack of potentially nested 'if (@available(...))'s.
7514 SmallVector<VersionTuple, 8> AvailabilityStack;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007515 SmallVector<const Stmt *, 16> StmtStack;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007516
7517 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7518
7519public:
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007520 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7521 : SemaRef(SemaRef), Ctx(Ctx) {
7522 AvailabilityStack.push_back(
7523 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007524 }
7525
Alex Lorenz6f911122017-05-16 13:58:53 +00007526 bool TraverseDecl(Decl *D) {
7527 // Avoid visiting nested functions to prevent duplicate warnings.
7528 if (!D || isa<FunctionDecl>(D))
7529 return true;
7530 return Base::TraverseDecl(D);
7531 }
7532
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007533 bool TraverseStmt(Stmt *S) {
7534 if (!S)
7535 return true;
7536 StmtStack.push_back(S);
7537 bool Result = Base::TraverseStmt(S);
7538 StmtStack.pop_back();
7539 return Result;
7540 }
7541
Erik Pilkington5cd57172016-08-16 17:44:11 +00007542 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7543
7544 bool TraverseIfStmt(IfStmt *If);
7545
Alex Lorenz6f911122017-05-16 13:58:53 +00007546 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
7547
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007548 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
7549 if (PRE->isClassReceiver())
7550 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
7551 return true;
7552 }
7553
Erik Pilkington5cd57172016-08-16 17:44:11 +00007554 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7555 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7556 DiagnoseDeclAvailability(
7557 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7558 return true;
7559 }
7560
7561 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7562 DiagnoseDeclAvailability(DRE->getDecl(),
7563 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7564 return true;
7565 }
7566
7567 bool VisitMemberExpr(MemberExpr *ME) {
7568 DiagnoseDeclAvailability(ME->getMemberDecl(),
7569 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7570 return true;
7571 }
7572
Alex Lorenz0a484ba2017-05-24 15:15:29 +00007573 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
7574 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use)
7575 << (!SemaRef.getLangOpts().ObjC1);
7576 return true;
7577 }
7578
Erik Pilkington5cd57172016-08-16 17:44:11 +00007579 bool VisitTypeLoc(TypeLoc Ty);
7580};
7581
7582void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7583 NamedDecl *D, SourceRange Range) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007584 AvailabilityResult Result;
7585 const NamedDecl *OffendingDecl;
7586 std::tie(Result, OffendingDecl) =
Erik Pilkington9f866a72017-07-18 20:32:07 +00007587 ShouldDiagnoseAvailabilityOfDecl(D, nullptr);
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007588 if (Result != AR_Available) {
Erik Pilkington5cd57172016-08-16 17:44:11 +00007589 // All other diagnostic kinds have already been handled in
7590 // DiagnoseAvailabilityOfDecl.
7591 if (Result != AR_NotYetIntroduced)
7592 return;
7593
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007594 const AvailabilityAttr *AA =
7595 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007596 VersionTuple Introduced = AA->getIntroduced();
7597
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007598 if (AvailabilityStack.back() >= Introduced)
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007599 return;
7600
7601 // If the context of this function is less available than D, we should not
7602 // emit a diagnostic.
7603 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7604 return;
7605
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007606 // We would like to emit the diagnostic even if -Wunguarded-availability is
7607 // not specified for deployment targets >= to iOS 11 or equivalent or
7608 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7609 // later.
7610 unsigned DiagKind =
7611 shouldDiagnoseAvailabilityByDefault(
7612 SemaRef.Context,
7613 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
7614 ? diag::warn_unguarded_availability_new
7615 : diag::warn_unguarded_availability;
7616
7617 SemaRef.Diag(Range.getBegin(), DiagKind)
Erik Pilkington5cd57172016-08-16 17:44:11 +00007618 << Range << D
7619 << AvailabilityAttr::getPrettyPlatformName(
7620 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7621 << Introduced.getAsString();
7622
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007623 SemaRef.Diag(OffendingDecl->getLocation(),
7624 diag::note_availability_specified_here)
7625 << OffendingDecl << /* partial */ 3;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007626
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007627 auto FixitDiag =
7628 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7629 << Range << D
7630 << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0
7631 : /*__builtin_available*/ 1);
7632
7633 // Find the statement which should be enclosed in the if @available check.
7634 if (StmtStack.empty())
7635 return;
7636 const Stmt *StmtOfUse = StmtStack.back();
7637 const CompoundStmt *Scope = nullptr;
7638 for (const Stmt *S : llvm::reverse(StmtStack)) {
7639 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7640 Scope = CS;
7641 break;
7642 }
7643 if (isBodyLikeChildStmt(StmtOfUse, S)) {
7644 // The declaration won't be seen outside of the statement, so we don't
7645 // have to wrap the uses of any declared variables in if (@available).
7646 // Therefore we can avoid setting Scope here.
7647 break;
7648 }
7649 StmtOfUse = S;
7650 }
7651 const Stmt *LastStmtOfUse = nullptr;
7652 if (isa<DeclStmt>(StmtOfUse) && Scope) {
7653 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
7654 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
7655 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
7656 break;
7657 }
7658 }
7659 }
7660
7661 const SourceManager &SM = SemaRef.getSourceManager();
7662 SourceLocation IfInsertionLoc =
7663 SM.getExpansionLoc(StmtOfUse->getLocStart());
7664 SourceLocation StmtEndLoc =
7665 SM.getExpansionRange(
7666 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd())
7667 .second;
7668 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
7669 return;
7670
7671 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
7672 const char *ExtraIndentation = " ";
7673 std::string FixItString;
7674 llvm::raw_string_ostream FixItOS(FixItString);
7675 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available"
7676 : "__builtin_available")
Alex Lorenze1fb64e2017-05-09 15:34:46 +00007677 << "("
7678 << AvailabilityAttr::getPlatformNameSourceSpelling(
7679 SemaRef.getASTContext().getTargetInfo().getPlatformName())
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007680 << " " << Introduced.getAsString() << ", *)) {\n"
7681 << Indentation << ExtraIndentation;
7682 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
7683 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
7684 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
7685 /*SkipTrailingWhitespaceAndNewLine=*/false);
7686 if (ElseInsertionLoc.isInvalid())
7687 ElseInsertionLoc =
7688 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
7689 FixItOS.str().clear();
7690 FixItOS << "\n"
7691 << Indentation << "} else {\n"
7692 << Indentation << ExtraIndentation
7693 << "// Fallback on earlier versions\n"
7694 << Indentation << "}";
7695 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007696 }
7697}
7698
7699bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7700 const Type *TyPtr = Ty.getTypePtr();
7701 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7702
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007703 if (Range.isInvalid())
7704 return true;
7705
Erik Pilkington5cd57172016-08-16 17:44:11 +00007706 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7707 TagDecl *TD = TT->getDecl();
7708 DiagnoseDeclAvailability(TD, Range);
7709
7710 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7711 TypedefNameDecl *D = TD->getDecl();
7712 DiagnoseDeclAvailability(D, Range);
7713
7714 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7715 if (NamedDecl *D = ObjCO->getInterface())
7716 DiagnoseDeclAvailability(D, Range);
7717 }
7718
7719 return true;
7720}
7721
7722bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7723 VersionTuple CondVersion;
7724 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7725 CondVersion = E->getVersion();
7726
7727 // If we're using the '*' case here or if this check is redundant, then we
7728 // use the enclosing version to check both branches.
7729 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7730 return Base::TraverseStmt(If->getThen()) &&
7731 Base::TraverseStmt(If->getElse());
7732 } else {
7733 // This isn't an availability checking 'if', we can just continue.
7734 return Base::TraverseIfStmt(If);
7735 }
7736
7737 AvailabilityStack.push_back(CondVersion);
7738 bool ShouldContinue = TraverseStmt(If->getThen());
7739 AvailabilityStack.pop_back();
7740
7741 return ShouldContinue && TraverseStmt(If->getElse());
7742}
7743
7744} // end anonymous namespace
7745
7746void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7747 Stmt *Body = nullptr;
7748
7749 if (auto *FD = D->getAsFunction()) {
7750 // FIXME: We only examine the pattern decl for availability violations now,
7751 // but we should also examine instantiated templates.
7752 if (FD->isTemplateInstantiation())
7753 return;
7754
7755 Body = FD->getBody();
7756 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7757 Body = MD->getBody();
Alex Lorenz28559ce2017-04-26 14:20:02 +00007758 else if (auto *BD = dyn_cast<BlockDecl>(D))
7759 Body = BD->getBody();
Erik Pilkington5cd57172016-08-16 17:44:11 +00007760
7761 assert(Body && "Need a body here!");
7762
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007763 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007764}
Erik Pilkington9f866a72017-07-18 20:32:07 +00007765
7766void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
7767 const ObjCInterfaceDecl *UnknownObjCClass,
7768 bool ObjCPropertyAccess,
7769 bool AvoidPartialAvailabilityChecks) {
7770 std::string Message;
7771 AvailabilityResult Result;
7772 const NamedDecl* OffendingDecl;
7773 // See if this declaration is unavailable, deprecated, or partial.
7774 std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, &Message);
7775 if (Result == AR_Available)
7776 return;
7777
7778 if (Result == AR_NotYetIntroduced) {
7779 if (AvoidPartialAvailabilityChecks)
7780 return;
7781
7782 // We need to know the @available context in the current function to
7783 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
7784 // when we're done parsing the current function.
7785 if (getCurFunctionOrMethodDecl()) {
7786 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
7787 return;
7788 } else if (getCurBlock() || getCurLambda()) {
7789 getCurFunction()->HasPotentialAvailabilityViolations = true;
7790 return;
7791 }
7792 }
7793
7794 const ObjCPropertyDecl *ObjCPDecl = nullptr;
7795 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
7796 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
7797 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
7798 if (PDeclResult == Result)
7799 ObjCPDecl = PD;
7800 }
7801 }
7802
7803 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Loc,
7804 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
7805}