blob: b87c8bfdd8b620d8053a3b10bbc863fbab8712f7 [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}
241const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
242 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(
316 Sema &S, const Decl *D, const AttrInfo& Attr,
317 unsigned AttrArgNum, const Expr *IdxExpr, uint64_t &Idx) {
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.
344 if (HasImplicitThisParam) {
345 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
Aaron Ballman76050722014-04-04 15:13:57 +0000483static bool checkRecordTypeForCapability(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();
Aaron Ballmanefe348e2014-02-18 17:36:50 +0000500 if (RD->hasAttr<CapabilityAttr>())
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>();
508 return Type->getDecl()->hasAttr<CapabilityAttr>();
509 }, 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
Aaron Ballman76050722014-04-04 15:13:57 +0000515static bool checkTypedefTypeForCapability(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
524 return TN->hasAttr<CapabilityAttr>();
525}
526
Aaron Ballman76050722014-04-04 15:13:57 +0000527static bool typeHasCapability(Sema &S, QualType Ty) {
528 if (checkTypedefTypeForCapability(Ty))
529 return true;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000530
Aaron Ballman76050722014-04-04 15:13:57 +0000531 if (checkRecordTypeForCapability(S, Ty))
532 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000533
Aaron Ballman76050722014-04-04 15:13:57 +0000534 return false;
535}
536
537static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
538 // Capability expressions are simple expressions involving the boolean logic
539 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
540 // a DeclRefExpr is found, its type should be checked to determine whether it
541 // is a capability or not.
542
543 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
544 return typeHasCapability(S, E->getType());
545 else if (const auto *E = dyn_cast<CastExpr>(Ex))
546 return isCapabilityExpr(S, E->getSubExpr());
547 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
548 return isCapabilityExpr(S, E->getSubExpr());
549 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
550 if (E->getOpcode() == UO_LNot)
551 return isCapabilityExpr(S, E->getSubExpr());
552 return false;
553 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
554 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
555 return isCapabilityExpr(S, E->getLHS()) &&
556 isCapabilityExpr(S, E->getRHS());
557 return false;
558 }
559
560 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000561}
562
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000563/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
564/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000565/// \param Sidx The attribute argument index to start checking with.
566/// \param ParamIdxOk Whether an argument can be indexing into a function
567/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000568static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
569 const AttributeList &Attr,
570 SmallVectorImpl<Expr *> &Args,
571 int Sidx = 0,
572 bool ParamIdxOk = false) {
573 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000574 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000575
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000576 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000577 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000578 Args.push_back(ArgExp);
579 continue;
580 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000581
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000582 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000583 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000584 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000585 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000586 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000587 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000588 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000589 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000590
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000591 // We allow constant strings to be used as a placeholder for expressions
592 // that are not valid C++ syntax, but warn that they are ignored.
593 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
594 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000595 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000596 continue;
597 }
598
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000599 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000600
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000601 // A pointer to member expression of the form &MyClass::mu is treated
602 // specially -- we need to look at the type of the member.
603 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
604 if (UOp->getOpcode() == UO_AddrOf)
605 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
606 if (DRE->getDecl()->isCXXInstanceMember())
607 ArgTy = DRE->getDecl()->getType();
608
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000609 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000610 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000611
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000612 // Now check if we index into a record type function param.
613 if(!RT && ParamIdxOk) {
614 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000615 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
616 if(FD && IL) {
617 unsigned int NumParams = FD->getNumParams();
618 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000619 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
620 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
621 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000622 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
623 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000624 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000625 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000626 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000627 }
628 }
629
Aaron Ballman76050722014-04-04 15:13:57 +0000630 // If the type does not have a capability, see if the components of the
631 // expression have capabilities. This allows for writing C code where the
632 // capability may be on the type, and the expression is a capability
633 // boolean logic expression. Eg) requires_capability(A || B && !C)
634 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
636 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000637
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000638 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000639 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000640}
641
Chris Lattner58418ff2008-06-29 00:16:31 +0000642//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000643// Attribute Implementations
644//===----------------------------------------------------------------------===//
645
Michael Hana9171bc2012-08-03 17:40:43 +0000646static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000647 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000648 if (!threadSafetyCheckIsPointer(S, D, Attr))
649 return;
650
Michael Han99315932013-01-24 16:46:58 +0000651 D->addAttr(::new (S.Context)
652 PtGuardedVarAttr(Attr.getRange(), S.Context,
653 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000654}
655
Michael Hana9171bc2012-08-03 17:40:43 +0000656static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
657 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000658 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000659 SmallVector<Expr*, 1> Args;
660 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000662 unsigned Size = Args.size();
663 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000664 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000665
Michael Han3be3b442012-07-23 18:48:41 +0000666 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000667
Michael Han3be3b442012-07-23 18:48:41 +0000668 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000669}
670
Michael Han3be3b442012-07-23 18:48:41 +0000671static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000672 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000673 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
674 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000675
Aaron Ballman36a53502014-01-16 13:03:14 +0000676 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
677 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000678}
679
Michael Hana9171bc2012-08-03 17:40:43 +0000680static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000681 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000683 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
684 return;
685
686 if (!threadSafetyCheckIsPointer(S, D, Attr))
687 return;
688
689 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000690 S.Context, Arg,
691 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000692}
693
Michael Hana9171bc2012-08-03 17:40:43 +0000694static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
695 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000696 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000697 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000698 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000699
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000700 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000701 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000702 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
703 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
704 << Attr.getName();
705 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000706 }
707
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000708 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000709 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000710 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000711 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000712
Michael Han3be3b442012-07-23 18:48:41 +0000713 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000714}
715
Michael Hana9171bc2012-08-03 17:40:43 +0000716static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000717 const AttributeList &Attr) {
718 SmallVector<Expr*, 1> Args;
719 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
720 return;
721
722 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000723 D->addAttr(::new (S.Context)
724 AcquiredAfterAttr(Attr.getRange(), S.Context,
725 StartArg, Args.size(),
726 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000727}
728
Michael Hana9171bc2012-08-03 17:40:43 +0000729static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
733 return;
734
735 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000736 D->addAttr(::new (S.Context)
737 AcquiredBeforeAttr(Attr.getRange(), S.Context,
738 StartArg, Args.size(),
739 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000740}
741
Michael Hana9171bc2012-08-03 17:40:43 +0000742static bool checkLockFunAttrCommon(Sema &S, Decl *D,
743 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000744 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000745 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000746 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000747 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000748
Michael Han3be3b442012-07-23 18:48:41 +0000749 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000750}
751
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000752static void handleAssertSharedLockAttr(Sema &S, Decl *D,
753 const AttributeList &Attr) {
754 SmallVector<Expr*, 1> Args;
755 if (!checkLockFunAttrCommon(S, D, Attr, Args))
756 return;
757
758 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000760 D->addAttr(::new (S.Context)
761 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
762 Attr.getAttributeSpellingListIndex()));
763}
764
765static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
766 const AttributeList &Attr) {
767 SmallVector<Expr*, 1> Args;
768 if (!checkLockFunAttrCommon(S, D, Attr, Args))
769 return;
770
771 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000772 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000773 D->addAttr(::new (S.Context)
774 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
775 StartArg, Size,
776 Attr.getAttributeSpellingListIndex()));
777}
778
Erich Keane623efd82017-03-30 21:48:55 +0000779/// \brief Checks to be sure that the given parameter number is in bounds, and is
780/// an integral type. Will emit appropriate diagnostics if this returns
George Burgess IVe3763372016-12-22 02:50:20 +0000781/// false.
782///
783/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
784/// to actually retrieve the argument, so it's base-0.
Erich Keane623efd82017-03-30 21:48:55 +0000785template <typename AttrInfo>
786static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
787 const AttrInfo &Attr, Expr *AttrArg,
788 unsigned FuncParamNo, unsigned AttrArgNo,
789 bool AllowDependentType = false) {
790 uint64_t Idx;
791 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
792 Idx))
793 return false;
794
795 const ParmVarDecl *Param = FD->getParamDecl(Idx);
796 if (AllowDependentType && Param->getType()->isDependentType())
797 return true;
798 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
799 SourceLocation SrcLoc = AttrArg->getLocStart();
800 S.Diag(SrcLoc, diag::err_attribute_integers_only)
801 << getAttrName(Attr) << Param->getSourceRange();
802 return false;
803 }
804 return true;
805}
806
807/// \brief Checks to be sure that the given parameter number is in bounds, and is
808/// an integral type. Will emit appropriate diagnostics if this returns false.
809///
810/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
811/// to actually retrieve the argument, so it's base-0.
George Burgess IVe3763372016-12-22 02:50:20 +0000812static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
813 const AttributeList &Attr,
Erich Keane623efd82017-03-30 21:48:55 +0000814 unsigned FuncParamNo, unsigned AttrArgNo,
815 bool AllowDependentType = false) {
George Burgess IVe3763372016-12-22 02:50:20 +0000816 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
Erich Keane623efd82017-03-30 21:48:55 +0000817 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
818 FuncParamNo, AttrArgNo, AllowDependentType);
George Burgess IVe3763372016-12-22 02:50:20 +0000819}
820
821static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
823 !checkAttributeAtMostNumArgs(S, Attr, 2))
824 return;
825
826 const auto *FD = cast<FunctionDecl>(D);
827 if (!FD->getReturnType()->isPointerType()) {
828 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
829 << Attr.getName();
830 return;
831 }
832
833 const Expr *SizeExpr = Attr.getArgAsExpr(0);
834 int SizeArgNo;
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000835 // Parameter indices are 1-indexed, hence Index=1
George Burgess IVe3763372016-12-22 02:50:20 +0000836 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
837 return;
838
839 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
840 return;
841
842 // Args are 1-indexed, so 0 implies that the arg was not present
843 int NumberArgNo = 0;
844 if (Attr.getNumArgs() == 2) {
845 const Expr *NumberExpr = Attr.getArgAsExpr(1);
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000846 // Parameter indices are 1-based, hence Index=2
George Burgess IVe3763372016-12-22 02:50:20 +0000847 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
848 /*Index=*/2))
849 return;
850
851 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
852 return;
853 }
854
855 D->addAttr(::new (S.Context) AllocSizeAttr(
856 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
857 Attr.getAttributeSpellingListIndex()));
858}
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000859
Michael Hana9171bc2012-08-03 17:40:43 +0000860static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
861 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000862 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000863 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000864 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000865
Aaron Ballman00e99962013-08-31 01:11:41 +0000866 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000867 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000868 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000869 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000870 }
871
872 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000873 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000874
Michael Han3be3b442012-07-23 18:48:41 +0000875 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000876}
877
Michael Hana9171bc2012-08-03 17:40:43 +0000878static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000879 const AttributeList &Attr) {
880 SmallVector<Expr*, 2> Args;
881 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
882 return;
883
Michael Han99315932013-01-24 16:46:58 +0000884 D->addAttr(::new (S.Context)
885 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000886 Attr.getArgAsExpr(0),
887 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000888 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000889}
890
Michael Hana9171bc2012-08-03 17:40:43 +0000891static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000892 const AttributeList &Attr) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
895 return;
896
Nico Weber462fd1e2015-01-07 23:50:05 +0000897 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
898 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
899 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000900}
901
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000902static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000903 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000904 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000905 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000906 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000907 unsigned Size = Args.size();
908 if (Size == 0)
909 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000910
Michael Han99315932013-01-24 16:46:58 +0000911 D->addAttr(::new (S.Context)
912 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
913 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000914}
915
916static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000917 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000918 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000919 return;
920
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000921 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000922 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000923 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000924 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000925 if (Size == 0)
926 return;
927 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000928
Michael Han99315932013-01-24 16:46:58 +0000929 D->addAttr(::new (S.Context)
930 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
931 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000932}
933
George Burgess IV177399e2017-01-09 04:12:14 +0000934static bool checkFunctionConditionAttr(Sema &S, Decl *D,
935 const AttributeList &Attr,
936 Expr *&Cond, StringRef &Msg) {
937 Cond = Attr.getArgAsExpr(0);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 if (!Cond->isTypeDependent()) {
939 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
940 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000941 return false;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000942 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000943 }
944
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000945 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
George Burgess IV177399e2017-01-09 04:12:14 +0000946 return false;
947
948 if (Msg.empty())
949 Msg = "<no message provided>";
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000950
951 SmallVector<PartialDiagnosticAt, 8> Diags;
952 if (!Cond->isValueDependent() &&
953 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
954 Diags)) {
George Burgess IV177399e2017-01-09 04:12:14 +0000955 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
956 << Attr.getName();
George Burgess IV0d546532016-11-10 21:47:12 +0000957 for (const PartialDiagnosticAt &PDiag : Diags)
958 S.Diag(PDiag.first, PDiag.second);
George Burgess IV177399e2017-01-09 04:12:14 +0000959 return false;
960 }
961 return true;
962}
963
964static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
965 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
966
967 Expr *Cond;
968 StringRef Msg;
969 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
970 D->addAttr(::new (S.Context)
971 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
972 Attr.getAttributeSpellingListIndex()));
973}
974
975namespace {
976/// Determines if a given Expr references any of the given function's
977/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
978class ArgumentDependenceChecker
979 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
980#ifndef NDEBUG
981 const CXXRecordDecl *ClassType;
982#endif
983 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
984 bool Result;
985
986public:
987 ArgumentDependenceChecker(const FunctionDecl *FD) {
988#ifndef NDEBUG
989 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
990 ClassType = MD->getParent();
991 else
992 ClassType = nullptr;
993#endif
994 Parms.insert(FD->param_begin(), FD->param_end());
995 }
996
997 bool referencesArgs(Expr *E) {
998 Result = false;
999 TraverseStmt(E);
1000 return Result;
1001 }
1002
1003 bool VisitCXXThisExpr(CXXThisExpr *E) {
1004 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1005 "`this` doesn't refer to the enclosing class?");
1006 Result = true;
1007 return false;
1008 }
1009
1010 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1011 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1012 if (Parms.count(PVD)) {
1013 Result = true;
1014 return false;
1015 }
1016 return true;
1017 }
1018};
1019}
1020
1021static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1022 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1023
1024 Expr *Cond;
1025 StringRef Msg;
1026 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1027 return;
1028
1029 StringRef DiagTypeStr;
1030 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1031 return;
1032
1033 DiagnoseIfAttr::DiagnosticType DiagType;
1034 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1035 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1036 diag::err_diagnose_if_invalid_diagnostic_type);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001037 return;
1038 }
1039
George Burgess IV177399e2017-01-09 04:12:14 +00001040 auto *FD = cast<FunctionDecl>(D);
1041 bool ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1042 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1043 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, FD,
1044 Attr.getAttributeSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001045}
1046
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001047static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1048 const AttributeList &Attr) {
1049 if (D->hasAttr<PassObjectSizeAttr>()) {
1050 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1051 << Attr.getName();
1052 return;
1053 }
1054
1055 Expr *E = Attr.getArgAsExpr(0);
1056 uint32_t Type;
1057 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1058 return;
1059
1060 // pass_object_size's argument is passed in as the second argument of
1061 // __builtin_object_size. So, it has the same constraints as that second
1062 // argument; namely, it must be in the range [0, 3].
1063 if (Type > 3) {
1064 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1065 << Attr.getName() << 0 << 3 << E->getSourceRange();
1066 return;
1067 }
1068
1069 // pass_object_size is only supported on constant pointer parameters; as a
1070 // kindness to users, we allow the parameter to be non-const for declarations.
1071 // At this point, we have no clue if `D` belongs to a function declaration or
1072 // definition, so we defer the constness check until later.
1073 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1074 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1075 << Attr.getName() << 1;
1076 return;
1077 }
1078
1079 D->addAttr(::new (S.Context)
1080 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1081 Attr.getAttributeSpellingListIndex()));
1082}
1083
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001084static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +00001085 ConsumableAttr::ConsumedState DefaultState;
1086
1087 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001088 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1089 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1090 DefaultState)) {
1091 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1092 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +00001093 return;
1094 }
David Blaikie16f76d22013-09-06 01:28:43 +00001095 } else {
1096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1097 << Attr.getName() << AANT_ArgumentIdentifier;
1098 return;
1099 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001100
1101 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +00001102 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001103 Attr.getAttributeSpellingListIndex()));
1104}
1105
1106static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1107 const AttributeList &Attr) {
1108 ASTContext &CurrContext = S.getASTContext();
1109 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1110
1111 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1112 if (!RD->hasAttr<ConsumableAttr>()) {
1113 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1114 RD->getNameAsString();
1115
1116 return false;
1117 }
1118 }
1119
1120 return true;
1121}
1122
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001123static void handleCallableWhenAttr(Sema &S, Decl *D,
1124 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +00001125 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1126 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001127
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001128 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1129 return;
1130
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001131 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1132 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1133 CallableWhenAttr::ConsumedState CallableState;
1134
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001135 StringRef StateString;
1136 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +00001137 if (Attr.isArgIdent(ArgIndex)) {
1138 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1139 StateString = Ident->Ident->getName();
1140 Loc = Ident->Loc;
1141 } else {
1142 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1143 return;
1144 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001145
1146 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +00001147 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001148 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1149 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001150 return;
1151 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001152
1153 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001154 }
1155
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001156 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001157 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1158 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001159}
1160
DeLesley Hutchins69391772013-10-17 23:23:53 +00001161static void handleParamTypestateAttr(Sema &S, Decl *D,
1162 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001163 ParamTypestateAttr::ConsumedState ParamState;
1164
1165 if (Attr.isArgIdent(0)) {
1166 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1167 StringRef StateString = Ident->Ident->getName();
1168
1169 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1170 ParamState)) {
1171 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1172 << Attr.getName() << StateString;
1173 return;
1174 }
1175 } else {
1176 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1177 Attr.getName() << AANT_ArgumentIdentifier;
1178 return;
1179 }
1180
1181 // FIXME: This check is currently being done in the analysis. It can be
1182 // enabled here only after the parser propagates attributes at
1183 // template specialization definition, not declaration.
1184 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1185 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1186 //
1187 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1188 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1189 // ReturnType.getAsString();
1190 // return;
1191 //}
1192
1193 D->addAttr(::new (S.Context)
1194 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1195 Attr.getAttributeSpellingListIndex()));
1196}
1197
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001198static void handleReturnTypestateAttr(Sema &S, Decl *D,
1199 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001200 ReturnTypestateAttr::ConsumedState ReturnState;
1201
1202 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001203 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1204 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1205 ReturnState)) {
1206 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1207 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001208 return;
1209 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001210 } else {
1211 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1212 Attr.getName() << AANT_ArgumentIdentifier;
1213 return;
1214 }
1215
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001216 // FIXME: This check is currently being done in the analysis. It can be
1217 // enabled here only after the parser propagates attributes at
1218 // template specialization definition, not declaration.
1219 //QualType ReturnType;
1220 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001221 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1222 // ReturnType = Param->getType();
1223 //
1224 //} else if (const CXXConstructorDecl *Constructor =
1225 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001226 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1227 //
1228 //} else {
1229 //
1230 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1231 //}
1232 //
1233 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1234 //
1235 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1236 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1237 // ReturnType.getAsString();
1238 // return;
1239 //}
1240
1241 D->addAttr(::new (S.Context)
1242 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1243 Attr.getAttributeSpellingListIndex()));
1244}
1245
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001246static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001247 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1248 return;
1249
1250 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001251 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001252 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1253 StringRef Param = Ident->Ident->getName();
1254 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1255 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1256 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001257 return;
1258 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001259 } else {
1260 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1261 Attr.getName() << AANT_ArgumentIdentifier;
1262 return;
1263 }
1264
1265 D->addAttr(::new (S.Context)
1266 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1267 Attr.getAttributeSpellingListIndex()));
1268}
1269
Chris Wailes9385f9f2013-10-29 20:28:41 +00001270static void handleTestTypestateAttr(Sema &S, Decl *D,
1271 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001272 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1273 return;
1274
Chris Wailes9385f9f2013-10-29 20:28:41 +00001275 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001276 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001277 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1278 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001279 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001280 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1281 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001282 return;
1283 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001284 } else {
1285 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1286 Attr.getName() << AANT_ArgumentIdentifier;
1287 return;
1288 }
1289
1290 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001291 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001292 Attr.getAttributeSpellingListIndex()));
1293}
1294
Chandler Carruthedc2c642011-07-02 00:01:44 +00001295static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1296 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001297 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001298 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001299}
1300
Chandler Carruthedc2c642011-07-02 00:01:44 +00001301static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001302 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001303 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1304 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001305 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001306 // Report warning about changed offset in the newer compiler versions.
Eli Friedmanc087c3f2012-11-07 00:35:20 +00001307 if (!FD->getType()->isDependentType() &&
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001308 !FD->getType()->isIncompleteType() && FD->isBitField() &&
Chris Lattnerb632a6e2008-06-29 00:43:07 +00001309 S.Context.getTypeAlign(FD->getType()) <= 8)
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001310 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1311
1312 FD->addAttr(::new (S.Context) PackedAttr(
1313 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001314 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001315 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001316}
1317
Ted Kremenek7fd17232011-09-29 07:02:25 +00001318static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1319 // The IBOutlet/IBOutletCollection attributes only apply to instance
1320 // variables or properties of Objective-C classes. The outlet must also
1321 // have an object reference type.
1322 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1323 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001324 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001325 << Attr.getName() << VD->getType() << 0;
1326 return false;
1327 }
1328 }
1329 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1330 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001331 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001332 << Attr.getName() << PD->getType() << 1;
1333 return false;
1334 }
1335 }
1336 else {
1337 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1338 return false;
1339 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001340
Ted Kremenek7fd17232011-09-29 07:02:25 +00001341 return true;
1342}
1343
Chandler Carruthedc2c642011-07-02 00:01:44 +00001344static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001345 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001346 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001347
Michael Han99315932013-01-24 16:46:58 +00001348 D->addAttr(::new (S.Context)
1349 IBOutletAttr(Attr.getRange(), S.Context,
1350 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001351}
1352
Chandler Carruthedc2c642011-07-02 00:01:44 +00001353static void handleIBOutletCollection(Sema &S, Decl *D,
1354 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001355
1356 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001357 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001358 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1359 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001360 return;
1361 }
1362
Ted Kremenek7fd17232011-09-29 07:02:25 +00001363 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001364 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001365
Richard Smithb1f9a282013-10-31 01:56:18 +00001366 ParsedType PT;
1367
1368 if (Attr.hasParsedType())
1369 PT = Attr.getTypeArg();
1370 else {
1371 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1372 S.getScopeForContext(D->getDeclContext()->getParent()));
1373 if (!PT) {
1374 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1375 return;
1376 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001377 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001378
Craig Topperc3ec1492014-05-26 06:22:03 +00001379 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001380 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1381 if (!QTLoc)
1382 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001383
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001384 // Diagnose use of non-object type in iboutletcollection attribute.
1385 // FIXME. Gnu attribute extension ignores use of builtin types in
1386 // attributes. So, __attribute__((iboutletcollection(char))) will be
1387 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001388 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001389 S.Diag(Attr.getLoc(),
1390 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1391 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001392 return;
1393 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001394
Michael Han99315932013-01-24 16:46:58 +00001395 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001396 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001397 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001398}
1399
Hal Finkelee90a222014-09-26 05:04:30 +00001400bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1401 if (RefOkay) {
1402 if (T->isReferenceType())
1403 return true;
1404 } else {
1405 T = T.getNonReferenceType();
1406 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001407
Hal Finkelee90a222014-09-26 05:04:30 +00001408 // The nonnull attribute, and other similar attributes, can be applied to a
1409 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001410 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001411 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1412 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001413 for (const auto *I : UD->fields()) {
1414 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001415 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1416 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001417 }
1418 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001419 }
1420
1421 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001422}
1423
Ted Kremenek9aedc152014-01-17 06:24:56 +00001424static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001425 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001426 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001427 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001428 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001429 if (isReturnValue)
1430 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1431 << Attr.getName() << AttrParmRange << TypeRange;
1432 else
1433 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1434 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001435 return false;
1436 }
1437 return true;
1438}
1439
Chandler Carruthedc2c642011-07-02 00:01:44 +00001440static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001441 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001442 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1443 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001444 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001445 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001446 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001447
1448 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001449 if (Idx < getFunctionOrMethodNumParams(D) &&
1450 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001451 Ex->getSourceRange(),
1452 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001453 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001454
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001455 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001456 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001457
1458 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001459 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1460 // check if the attribute came from a macro expansion or a template
1461 // instantiation.
1462 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001463 !S.inTemplateInstantiation()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001464 bool AnyPointers = isFunctionOrMethodVariadic(D);
1465 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1466 I != E && !AnyPointers; ++I) {
1467 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001468 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001469 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001470 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001471
Richard Smith588bd9b2014-08-27 04:59:42 +00001472 if (!AnyPointers)
1473 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001474 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001475
Richard Smith588bd9b2014-08-27 04:59:42 +00001476 unsigned *Start = NonNullArgs.data();
1477 unsigned Size = NonNullArgs.size();
1478 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001479 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001480 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001481 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001482}
1483
Jordan Rosec9399072014-02-11 17:27:59 +00001484static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1485 const AttributeList &Attr) {
1486 if (Attr.getNumArgs() > 0) {
1487 if (D->getFunctionType()) {
1488 handleNonNullAttr(S, D, Attr);
1489 } else {
1490 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1491 << D->getSourceRange();
1492 }
1493 return;
1494 }
1495
1496 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001497 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1498 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001499 return;
1500
1501 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001502 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001503 Attr.getAttributeSpellingListIndex()));
1504}
1505
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001506static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1507 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001508 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001509 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1510 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001511 /* isReturnValue */ true))
1512 return;
1513
1514 D->addAttr(::new (S.Context)
1515 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1516 Attr.getAttributeSpellingListIndex()));
1517}
1518
Hal Finkelee90a222014-09-26 05:04:30 +00001519static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1520 const AttributeList &Attr) {
1521 Expr *E = Attr.getArgAsExpr(0),
1522 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1523 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1524 Attr.getAttributeSpellingListIndex());
1525}
1526
Erich Keane623efd82017-03-30 21:48:55 +00001527static void handleAllocAlignAttr(Sema &S, Decl *D,
1528 const AttributeList &Attr) {
1529 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1530 Attr.getAttributeSpellingListIndex());
1531}
1532
Hal Finkelee90a222014-09-26 05:04:30 +00001533void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1534 Expr *OE, unsigned SpellingListIndex) {
1535 QualType ResultType = getFunctionOrMethodResultType(D);
1536 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1537
1538 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1539 SourceLocation AttrLoc = AttrRange.getBegin();
1540
1541 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1542 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1543 << &TmpAttr << AttrRange << SR;
1544 return;
1545 }
1546
1547 if (!E->isValueDependent()) {
1548 llvm::APSInt I(64);
1549 if (!E->isIntegerConstantExpr(I, Context)) {
1550 if (OE)
1551 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1552 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1553 << E->getSourceRange();
1554 else
1555 Diag(AttrLoc, diag::err_attribute_argument_type)
1556 << &TmpAttr << AANT_ArgumentIntegerConstant
1557 << E->getSourceRange();
1558 return;
1559 }
1560
1561 if (!I.isPowerOf2()) {
1562 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1563 << E->getSourceRange();
1564 return;
1565 }
1566 }
1567
1568 if (OE) {
1569 if (!OE->isValueDependent()) {
1570 llvm::APSInt I(64);
1571 if (!OE->isIntegerConstantExpr(I, Context)) {
1572 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1573 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1574 << OE->getSourceRange();
1575 return;
1576 }
1577 }
1578 }
1579
1580 D->addAttr(::new (Context)
1581 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1582}
1583
Erich Keane623efd82017-03-30 21:48:55 +00001584void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1585 unsigned SpellingListIndex) {
1586 QualType ResultType = getFunctionOrMethodResultType(D);
1587
1588 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1589 SourceLocation AttrLoc = AttrRange.getBegin();
1590
1591 if (!ResultType->isDependentType() &&
1592 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1593 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1594 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1595 return;
1596 }
1597
1598 uint64_t IndexVal;
1599 const auto *FuncDecl = cast<FunctionDecl>(D);
1600 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1601 /*AttrArgNo=*/1, ParamExpr,
1602 IndexVal))
1603 return;
1604
1605 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1606 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1607 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1608 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1609 return;
1610 }
1611
1612 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1613 // because that has corrected for the implicit this parameter, and is zero-
1614 // based. The attribute expects what the user wrote explicitly.
1615 llvm::APSInt Val;
1616 ParamExpr->EvaluateAsInt(Val, Context);
1617
1618 D->addAttr(::new (Context) AllocAlignAttr(
1619 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1620}
1621
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001622/// Normalize the attribute, __foo__ becomes foo.
1623/// Returns true if normalization was applied.
1624static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001625 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1626 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001627 AttrName = AttrName.drop_front(2).drop_back(2);
1628 return true;
1629 }
1630 return false;
1631}
1632
Chandler Carruthedc2c642011-07-02 00:01:44 +00001633static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001634 // This attribute must be applied to a function declaration. The first
1635 // argument to the attribute must be an identifier, the name of the resource,
1636 // for example: malloc. The following arguments must be argument indexes, the
1637 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001638 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001639 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001640 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001641
Aaron Ballman00e99962013-08-31 01:11:41 +00001642 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001643 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001644 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001645 return;
1646 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001647
Richard Smith852e9ce2013-11-27 01:46:48 +00001648 // Figure out our Kind.
1649 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001650 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001651 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001652
Richard Smith852e9ce2013-11-27 01:46:48 +00001653 // Check arguments.
1654 switch (K) {
1655 case OwnershipAttr::Takes:
1656 case OwnershipAttr::Holds:
1657 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001658 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1659 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001660 return;
1661 }
1662 break;
1663 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001664 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001665 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1666 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001667 return;
1668 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001669 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001670 }
1671
Richard Smith852e9ce2013-11-27 01:46:48 +00001672 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001673
Richard Smith852e9ce2013-11-27 01:46:48 +00001674 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001675 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001676 Module = &S.PP.getIdentifierTable().get(ModuleName);
1677 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001678
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001679 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001680 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1681 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001682 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001683 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001684 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001685
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001686 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001687 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001688 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001689 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001690 case OwnershipAttr::Takes:
1691 case OwnershipAttr::Holds:
1692 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1693 Err = 0;
1694 break;
1695 case OwnershipAttr::Returns:
1696 if (!T->isIntegerType())
1697 Err = 1;
1698 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001699 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001700 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001701 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001702 << Ex->getSourceRange();
1703 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001704 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001705
1706 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001707 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001708 // Cannot have two ownership attributes of different kinds for the same
1709 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001710 if (I->getOwnKind() != K && I->args_end() !=
1711 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001712 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001713 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001714 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001715 } else if (K == OwnershipAttr::Returns &&
1716 I->getOwnKind() == OwnershipAttr::Returns) {
1717 // A returns attribute conflicts with any other returns attribute using
1718 // a different index. Note, diagnostic reporting is 1-based, but stored
1719 // argument indexes are 0-based.
1720 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1721 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1722 << *(I->args_begin()) + 1;
1723 if (I->args_size())
1724 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1725 << (unsigned)Idx + 1 << Ex->getSourceRange();
1726 return;
1727 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001728 }
1729 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001730 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001731 }
1732
1733 unsigned* start = OwnershipArgs.data();
1734 unsigned size = OwnershipArgs.size();
1735 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001736
Michael Han99315932013-01-24 16:46:58 +00001737 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001738 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001739 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001740}
1741
Chandler Carruthedc2c642011-07-02 00:01:44 +00001742static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001743 // Check the attribute arguments.
1744 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001745 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1746 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001747 return;
1748 }
1749
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001750 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001751
Rafael Espindolac18086a2010-02-23 22:00:30 +00001752 // gcc rejects
1753 // class c {
1754 // static int a __attribute__((weakref ("v2")));
1755 // static int b() __attribute__((weakref ("f3")));
1756 // };
1757 // and ignores the attributes of
1758 // void f(void) {
1759 // static int a __attribute__((weakref ("v2")));
1760 // }
1761 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001762 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001763 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001764 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1765 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001766 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001767 }
1768
1769 // The GCC manual says
1770 //
1771 // At present, a declaration to which `weakref' is attached can only
1772 // be `static'.
1773 //
1774 // It also says
1775 //
1776 // Without a TARGET,
1777 // given as an argument to `weakref' or to `alias', `weakref' is
1778 // equivalent to `weak'.
1779 //
1780 // gcc 4.4.1 will accept
1781 // int a7 __attribute__((weakref));
1782 // as
1783 // int a7 __attribute__((weak));
1784 // This looks like a bug in gcc. We reject that for now. We should revisit
1785 // it if this behaviour is actually used.
1786
Rafael Espindolac18086a2010-02-23 22:00:30 +00001787 // GCC rejects
1788 // static ((alias ("y"), weakref)).
1789 // Should we? How to check that weakref is before or after alias?
1790
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001791 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1792 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1793 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001794 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001795 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001796 // GCC will accept anything as the argument of weakref. Should we
1797 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001798 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1799 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001800
Michael Han99315932013-01-24 16:46:58 +00001801 D->addAttr(::new (S.Context)
1802 WeakRefAttr(Attr.getRange(), S.Context,
1803 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001804}
1805
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001806static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1807 StringRef Str;
1808 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1809 return;
1810
1811 // Aliases should be on declarations, not definitions.
1812 const auto *FD = cast<FunctionDecl>(D);
1813 if (FD->isThisDeclarationADefinition()) {
1814 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1815 return;
1816 }
1817 // FIXME: it should be handled as a target specific attribute.
1818 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1819 llvm::Triple::ELF) {
1820 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1821 return;
1822 }
1823
1824 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1825 Attr.getAttributeSpellingListIndex()));
1826}
1827
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001828static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1829 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001830 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001831 return;
1832
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001834 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1835 return;
1836 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001837 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1838 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1839 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001840
David Majnemer2dc81462015-01-19 09:00:28 +00001841 // Aliases should be on declarations, not definitions.
1842 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1843 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001844 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001845 return;
1846 }
1847 } else {
1848 const auto *VD = cast<VarDecl>(D);
1849 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001850 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001851 return;
1852 }
1853 }
1854
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001855 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001856
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001857 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001858 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001859}
1860
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001861static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001862 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001863 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001864
Michael Han99315932013-01-24 16:46:58 +00001865 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1866 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001867}
1868
1869static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001870 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001871 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001872
Michael Han99315932013-01-24 16:46:58 +00001873 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1874 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001875}
1876
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001877static void handleTLSModelAttr(Sema &S, Decl *D,
1878 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001879 StringRef Model;
1880 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001881 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001882 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001883 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001884
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001885 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001886 if (Model != "global-dynamic" && Model != "local-dynamic"
1887 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001888 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001889 return;
1890 }
1891
Michael Han99315932013-01-24 16:46:58 +00001892 D->addAttr(::new (S.Context)
1893 TLSModelAttr(Attr.getRange(), S.Context, Model,
1894 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001895}
1896
David Majnemer631a90b2015-02-04 07:23:21 +00001897static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1898 QualType ResultType = getFunctionOrMethodResultType(D);
1899 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1900 D->addAttr(::new (S.Context) RestrictAttr(
1901 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1902 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001903 }
1904
David Majnemer631a90b2015-02-04 07:23:21 +00001905 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1906 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001907}
1908
Chandler Carruthedc2c642011-07-02 00:01:44 +00001909static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001910 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001911 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001912 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001913 return;
1914 }
1915
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001916 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1917 Attr.getAttributeSpellingListIndex()))
1918 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001919}
1920
Charles Davis0e379112016-08-08 21:19:08 +00001921static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1922 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1923 Attr.getName()))
1924 return;
1925
Saleem Abdulrasoolb51bcaf2017-04-07 15:13:47 +00001926 if (Attr.isDeclspecAttribute()) {
1927 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1928 const auto &Arch = Triple.getArch();
1929 if (Arch != llvm::Triple::x86 &&
1930 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1931 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1932 << Attr.getName() << Triple.getArchName();
1933 return;
1934 }
1935 }
1936
Charles Davis0e379112016-08-08 21:19:08 +00001937 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1938 Attr.getAttributeSpellingListIndex()));
1939}
1940
Chandler Carruthedc2c642011-07-02 00:01:44 +00001941static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001942 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001943
1944 if (S.CheckNoReturnAttr(attr)) return;
1945
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001946 if (!isa<ObjCMethodDecl>(D)) {
John McCall3882ace2011-01-05 12:14:39 +00001947 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001948 << attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001949 return;
1950 }
1951
Michael Han99315932013-01-24 16:46:58 +00001952 D->addAttr(::new (S.Context)
1953 NoReturnAttr(attr.getRange(), S.Context,
1954 attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00001955}
1956
1957bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00001958 if (!checkAttributeNumArgs(*this, attr, 0)) {
John McCall3882ace2011-01-05 12:14:39 +00001959 attr.setInvalid();
1960 return true;
1961 }
1962
1963 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00001964}
1965
Chandler Carruthedc2c642011-07-02 00:01:44 +00001966static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1967 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001968
1969 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1970 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00001971 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001972 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00001973 if (!VD || (!VD->getType()->isBlockPointerType() &&
1974 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001975 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00001976 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00001977 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001978 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00001979 return;
1980 }
1981 }
1982
Michael Han99315932013-01-24 16:46:58 +00001983 D->addAttr(::new (S.Context)
1984 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1985 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001986}
1987
John Thompsoncdb847ba2010-08-09 21:53:52 +00001988// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00001989static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00001990/*
1991 Returning a Vector Class in Registers
1992
Eric Christopherbc638a82010-12-01 22:13:54 +00001993 According to the PPU ABI specifications, a class with a single member of
1994 vector type is returned in memory when used as the return value of a function.
1995 This results in inefficient code when implementing vector classes. To return
1996 the value in a single vector register, add the vecreturn attribute to the
1997 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00001998
1999 Example:
2000
2001 struct Vector
2002 {
2003 __vector float xyzw;
2004 } __attribute__((vecreturn));
2005
2006 Vector Add(Vector lhs, Vector rhs)
2007 {
2008 Vector result;
2009 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2010 return result; // This will be returned in a register
2011 }
2012*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00002013 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2014 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00002015 return;
2016 }
2017
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002018 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00002019 int count = 0;
2020
2021 if (!isa<CXXRecordDecl>(record)) {
2022 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2023 return;
2024 }
2025
2026 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2027 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2028 return;
2029 }
2030
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002031 for (const auto *I : record->fields()) {
2032 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00002033 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2034 return;
2035 }
2036 count++;
2037 }
2038
Michael Han99315932013-01-24 16:46:58 +00002039 D->addAttr(::new (S.Context)
2040 VecReturnAttr(Attr.getRange(), S.Context,
2041 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00002042}
2043
Richard Smithe233fbf2013-01-28 22:42:45 +00002044static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2045 const AttributeList &Attr) {
2046 if (isa<ParmVarDecl>(D)) {
2047 // [[carries_dependency]] can only be applied to a parameter if it is a
2048 // parameter of a function declaration or lambda.
2049 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2050 S.Diag(Attr.getLoc(),
2051 diag::err_carries_dependency_param_not_function_decl);
2052 return;
2053 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00002054 }
Richard Smithe233fbf2013-01-28 22:42:45 +00002055
2056 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2057 Attr.getRange(), S.Context,
2058 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002059}
2060
Akira Hatanakac8667622015-11-06 23:56:15 +00002061static void handleNotTailCalledAttr(Sema &S, Decl *D,
2062 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00002063 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2064 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00002065 return;
2066
2067 D->addAttr(::new (S.Context) NotTailCalledAttr(
2068 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2069}
2070
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00002071static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2072 const AttributeList &Attr) {
2073 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2074 Attr.getName()))
2075 return;
2076
2077 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2078 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2079}
2080
Chandler Carruthedc2c642011-07-02 00:01:44 +00002081static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002082 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00002083 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00002084 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002085 return;
2086 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002087 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002088 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002089 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002090 return;
2091 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002092
Michael Han99315932013-01-24 16:46:58 +00002093 D->addAttr(::new (S.Context)
2094 UsedAttr(Attr.getRange(), S.Context,
2095 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002096}
2097
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002098static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2099 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2100
2101 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2102 // The C++1z spelling of this attribute cannot be applied to a static data
2103 // member per [dcl.attr.unused]p2.
2104 if (cast<VarDecl>(D)->isStaticDataMember()) {
2105 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2106 << Attr.getName() << ExpectedForMaybeUnused;
2107 return;
2108 }
2109 }
2110
2111 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2112 // about using it as an extension.
2113 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2114 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2115
2116 D->addAttr(::new (S.Context) UnusedAttr(
2117 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2118}
2119
Chandler Carruthedc2c642011-07-02 00:01:44 +00002120static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002121 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002122 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002123 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2124 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002125
Michael Han99315932013-01-24 16:46:58 +00002126 D->addAttr(::new (S.Context)
2127 ConstructorAttr(Attr.getRange(), S.Context, priority,
2128 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002129}
2130
Chandler Carruthedc2c642011-07-02 00:01:44 +00002131static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00002132 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002133 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002134 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2135 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002136
Michael Han99315932013-01-24 16:46:58 +00002137 D->addAttr(::new (S.Context)
2138 DestructorAttr(Attr.getRange(), S.Context, priority,
2139 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002140}
2141
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002142template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00002143static void handleAttrWithMessage(Sema &S, Decl *D,
2144 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002145 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002146 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002147 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002148 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002149
Michael Han99315932013-01-24 16:46:58 +00002150 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2151 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00002152}
2153
Ted Kremenek438f8db2014-02-22 01:06:05 +00002154static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00002155 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00002156 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00002157 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2158 << Attr.getName() << Attr.getRange();
2159 return;
2160 }
2161
Ted Kremenek28eace62013-11-23 01:01:34 +00002162 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00002163 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2164 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00002165}
2166
Jordy Rose740b0c22012-05-08 03:27:22 +00002167static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2168 IdentifierInfo *Platform,
2169 VersionTuple Introduced,
2170 VersionTuple Deprecated,
2171 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002172 StringRef PlatformName
2173 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2174 if (PlatformName.empty())
2175 PlatformName = Platform->getName();
2176
2177 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2178 // of these steps are needed).
2179 if (!Introduced.empty() && !Deprecated.empty() &&
2180 !(Introduced <= Deprecated)) {
2181 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2182 << 1 << PlatformName << Deprecated.getAsString()
2183 << 0 << Introduced.getAsString();
2184 return true;
2185 }
2186
2187 if (!Introduced.empty() && !Obsoleted.empty() &&
2188 !(Introduced <= Obsoleted)) {
2189 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2190 << 2 << PlatformName << Obsoleted.getAsString()
2191 << 0 << Introduced.getAsString();
2192 return true;
2193 }
2194
2195 if (!Deprecated.empty() && !Obsoleted.empty() &&
2196 !(Deprecated <= Obsoleted)) {
2197 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2198 << 2 << PlatformName << Obsoleted.getAsString()
2199 << 1 << Deprecated.getAsString();
2200 return true;
2201 }
2202
2203 return false;
2204}
2205
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002206/// \brief Check whether the two versions match.
2207///
2208/// If either version tuple is empty, then they are assumed to match. If
2209/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2210static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2211 bool BeforeIsOkay) {
2212 if (X.empty() || Y.empty())
2213 return true;
2214
2215 if (X == Y)
2216 return true;
2217
2218 if (BeforeIsOkay && X < Y)
2219 return true;
2220
2221 return false;
2222}
2223
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002224AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002225 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00002226 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002227 VersionTuple Introduced,
2228 VersionTuple Deprecated,
2229 VersionTuple Obsoleted,
2230 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002231 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00002232 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002233 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002234 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00002235 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002236 VersionTuple MergedIntroduced = Introduced;
2237 VersionTuple MergedDeprecated = Deprecated;
2238 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002239 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002240 bool OverrideOrImpl = false;
2241 switch (AMK) {
2242 case AMK_None:
2243 case AMK_Redeclaration:
2244 OverrideOrImpl = false;
2245 break;
2246
2247 case AMK_Override:
2248 case AMK_ProtocolImplementation:
2249 OverrideOrImpl = true;
2250 break;
2251 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002252
Rafael Espindolac67f2232012-05-10 02:50:16 +00002253 if (D->hasAttrs()) {
2254 AttrVec &Attrs = D->getAttrs();
2255 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2256 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2257 if (!OldAA) {
2258 ++i;
2259 continue;
2260 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002261
Rafael Espindolac67f2232012-05-10 02:50:16 +00002262 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2263 if (OldPlatform != Platform) {
2264 ++i;
2265 continue;
2266 }
2267
Tim Northover7a73cc72015-10-30 16:30:49 +00002268 // If there is an existing availability attribute for this platform that
2269 // is explicit and the new one is implicit use the explicit one and
2270 // discard the new implicit attribute.
Manman Ren719a8642016-05-06 21:04:01 +00002271 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002272 return nullptr;
2273 }
2274
2275 // If there is an existing attribute for this platform that is implicit
2276 // and the new attribute is explicit then erase the old one and
2277 // continue processing the attributes.
Manman Ren719a8642016-05-06 21:04:01 +00002278 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002279 Attrs.erase(Attrs.begin() + i);
2280 --e;
2281 continue;
2282 }
2283
Rafael Espindolac67f2232012-05-10 02:50:16 +00002284 FoundAny = true;
2285 VersionTuple OldIntroduced = OldAA->getIntroduced();
2286 VersionTuple OldDeprecated = OldAA->getDeprecated();
2287 VersionTuple OldObsoleted = OldAA->getObsoleted();
2288 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002289
Douglas Gregord2a713e2015-09-30 21:27:42 +00002290 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2291 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2292 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002293 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002294 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2295 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002296 int Which = -1;
2297 VersionTuple FirstVersion;
2298 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002299 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002300 Which = 0;
2301 FirstVersion = OldIntroduced;
2302 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002303 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002304 Which = 1;
2305 FirstVersion = Deprecated;
2306 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002307 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002308 Which = 2;
2309 FirstVersion = Obsoleted;
2310 SecondVersion = OldObsoleted;
2311 }
2312
2313 if (Which == -1) {
2314 Diag(OldAA->getLocation(),
2315 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002316 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2317 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002318 } else {
2319 Diag(OldAA->getLocation(),
2320 diag::warn_mismatched_availability_override)
2321 << Which
2322 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002323 << FirstVersion.getAsString() << SecondVersion.getAsString()
2324 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002325 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002326 if (AMK == AMK_Override)
2327 Diag(Range.getBegin(), diag::note_overridden_method);
2328 else
2329 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002330 } else {
2331 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2332 Diag(Range.getBegin(), diag::note_previous_attribute);
2333 }
2334
Rafael Espindolac67f2232012-05-10 02:50:16 +00002335 Attrs.erase(Attrs.begin() + i);
2336 --e;
2337 continue;
2338 }
2339
2340 VersionTuple MergedIntroduced2 = MergedIntroduced;
2341 VersionTuple MergedDeprecated2 = MergedDeprecated;
2342 VersionTuple MergedObsoleted2 = MergedObsoleted;
2343
2344 if (MergedIntroduced2.empty())
2345 MergedIntroduced2 = OldIntroduced;
2346 if (MergedDeprecated2.empty())
2347 MergedDeprecated2 = OldDeprecated;
2348 if (MergedObsoleted2.empty())
2349 MergedObsoleted2 = OldObsoleted;
2350
2351 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2352 MergedIntroduced2, MergedDeprecated2,
2353 MergedObsoleted2)) {
2354 Attrs.erase(Attrs.begin() + i);
2355 --e;
2356 continue;
2357 }
2358
2359 MergedIntroduced = MergedIntroduced2;
2360 MergedDeprecated = MergedDeprecated2;
2361 MergedObsoleted = MergedObsoleted2;
2362 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002363 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002364 }
2365
2366 if (FoundAny &&
2367 MergedIntroduced == Introduced &&
2368 MergedDeprecated == Deprecated &&
2369 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002370 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002371
Douglas Gregord2a713e2015-09-30 21:27:42 +00002372 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002373 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002374 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002375 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002376 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002377 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002378 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002379 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002380 IsStrict, Replacement,
2381 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002382 Avail->setImplicit(Implicit);
2383 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002384 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002385 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002386}
2387
Chandler Carruthedc2c642011-07-02 00:01:44 +00002388static void handleAvailabilityAttr(Sema &S, Decl *D,
2389 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002390 if (!checkAttributeNumArgs(S, Attr, 1))
2391 return;
2392 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002393 unsigned Index = Attr.getAttributeSpellingListIndex();
2394
Aaron Ballman00e99962013-08-31 01:11:41 +00002395 IdentifierInfo *II = Platform->Ident;
2396 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2397 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2398 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002399
Rafael Espindolac231fab2013-01-08 21:30:32 +00002400 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2401 if (!ND) {
2402 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2403 return;
2404 }
2405
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002406 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2407 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2408 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002409 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002410 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002411 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002412 if (const StringLiteral *SE =
2413 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002414 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002415 StringRef Replacement;
2416 if (const StringLiteral *SE =
2417 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2418 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002419
Aaron Ballman00e99962013-08-31 01:11:41 +00002420 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002421 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002422 Introduced.Version,
2423 Deprecated.Version,
2424 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002425 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002426 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002427 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002428 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002429 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002430 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002431
2432 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2433 // matches before the start of the watchOS platform.
2434 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2435 IdentifierInfo *NewII = nullptr;
2436 if (II->getName() == "ios")
2437 NewII = &S.Context.Idents.get("watchos");
2438 else if (II->getName() == "ios_app_extension")
2439 NewII = &S.Context.Idents.get("watchos_app_extension");
2440
2441 if (NewII) {
2442 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2443 if (Version.empty())
2444 return Version;
2445 auto Major = Version.getMajor();
2446 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2447 if (NewMajor >= 2) {
2448 if (Version.getMinor().hasValue()) {
2449 if (Version.getSubminor().hasValue())
2450 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2451 Version.getSubminor().getValue());
2452 else
2453 return VersionTuple(NewMajor, Version.getMinor().getValue());
2454 }
2455 }
2456
2457 return VersionTuple(2, 0);
2458 };
2459
2460 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2461 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2462 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2463
2464 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002465 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002466 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002467 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002468 NewIntroduced,
2469 NewDeprecated,
2470 NewObsoleted,
2471 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002472 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002473 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002474 Sema::AMK_None,
2475 Index);
2476 if (NewAttr)
2477 D->addAttr(NewAttr);
2478 }
2479 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2480 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2481 // matches before the start of the tvOS platform.
2482 IdentifierInfo *NewII = nullptr;
2483 if (II->getName() == "ios")
2484 NewII = &S.Context.Idents.get("tvos");
2485 else if (II->getName() == "ios_app_extension")
2486 NewII = &S.Context.Idents.get("tvos_app_extension");
2487
2488 if (NewII) {
2489 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002490 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002491 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002492 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002493 Introduced.Version,
2494 Deprecated.Version,
2495 Obsoleted.Version,
2496 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002497 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002498 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002499 Sema::AMK_None,
2500 Index);
2501 if (NewAttr)
2502 D->addAttr(NewAttr);
2503 }
2504 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002505}
2506
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002507static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2508 const AttributeList &Attr) {
2509 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2510 return;
2511 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2512 "Invalid number of arguments in an external_source_symbol attribute");
2513
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002514 StringRef Language;
2515 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2516 Language = SE->getString();
2517 StringRef DefinedIn;
2518 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2519 DefinedIn = SE->getString();
2520 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2521
2522 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2523 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2524 Attr.getAttributeSpellingListIndex()));
2525}
2526
John McCalld041a9b2013-02-20 01:54:26 +00002527template <class T>
2528static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2529 typename T::VisibilityType value,
2530 unsigned attrSpellingListIndex) {
2531 T *existingAttr = D->getAttr<T>();
2532 if (existingAttr) {
2533 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2534 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002536 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2537 S.Diag(range.getBegin(), diag::note_previous_attribute);
2538 D->dropAttr<T>();
2539 }
2540 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2541}
2542
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002543VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002544 VisibilityAttr::VisibilityType Vis,
2545 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002546 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2547 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002548}
2549
John McCalld041a9b2013-02-20 01:54:26 +00002550TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2551 TypeVisibilityAttr::VisibilityType Vis,
2552 unsigned AttrSpellingListIndex) {
2553 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2554 AttrSpellingListIndex);
2555}
2556
2557static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2558 bool isTypeVisibility) {
2559 // Visibility attributes don't mean anything on a typedef.
2560 if (isa<TypedefNameDecl>(D)) {
2561 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2562 << Attr.getName();
2563 return;
2564 }
2565
2566 // 'type_visibility' can only go on a type or namespace.
2567 if (isTypeVisibility &&
2568 !(isa<TagDecl>(D) ||
2569 isa<ObjCInterfaceDecl>(D) ||
2570 isa<NamespaceDecl>(D))) {
2571 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2572 << Attr.getName() << ExpectedTypeOrNamespace;
2573 return;
2574 }
2575
Benjamin Kramer70370212013-09-09 15:08:57 +00002576 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002577 StringRef TypeStr;
2578 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002579 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002580 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002581
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002582 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002583 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002584 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002585 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002586 return;
2587 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002588
2589 // Complain about attempts to use protected visibility on targets
2590 // (like Darwin) that don't support it.
2591 if (type == VisibilityAttr::Protected &&
2592 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2593 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2594 type = VisibilityAttr::Default;
2595 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002596
Michael Han99315932013-01-24 16:46:58 +00002597 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002598 clang::Attr *newAttr;
2599 if (isTypeVisibility) {
2600 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2601 (TypeVisibilityAttr::VisibilityType) type,
2602 Index);
2603 } else {
2604 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2605 }
2606 if (newAttr)
2607 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002608}
2609
Chandler Carruthedc2c642011-07-02 00:01:44 +00002610static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2611 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002612 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002613 if (!Attr.isArgIdent(0)) {
2614 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2615 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002616 return;
2617 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002618
Aaron Ballman682ee422013-09-11 19:47:58 +00002619 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2620 ObjCMethodFamilyAttr::FamilyKind F;
2621 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2622 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2623 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002624 return;
2625 }
2626
Alp Toker314cc812014-01-25 16:55:45 +00002627 if (F == ObjCMethodFamilyAttr::OMF_init &&
2628 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002629 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002630 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002631 // Ignore the attribute.
2632 return;
2633 }
2634
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002635 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002636 S.Context, F,
2637 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002638}
2639
Chandler Carruthedc2c642011-07-02 00:01:44 +00002640static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002641 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002642 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002643 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002644 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2645 return;
2646 }
2647 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002648 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2649 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002650 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002651 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2652 return;
2653 }
2654 }
2655 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002656 // It is okay to include this attribute on properties, e.g.:
2657 //
2658 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2659 //
2660 // In this case it follows tradition and suppresses an error in the above
2661 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002662 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002663 }
Michael Han99315932013-01-24 16:46:58 +00002664 D->addAttr(::new (S.Context)
2665 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2666 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002667}
2668
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002669static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2670 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2671 QualType T = TD->getUnderlyingType();
2672 if (!T->isObjCObjectPointerType()) {
2673 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2674 return;
2675 }
2676 } else {
2677 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2678 return;
2679 }
2680 D->addAttr(::new (S.Context)
2681 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2682 Attr.getAttributeSpellingListIndex()));
2683}
2684
Chandler Carruthedc2c642011-07-02 00:01:44 +00002685static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002686 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002687 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002688 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002689 return;
2690 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002691
Aaron Ballman00e99962013-08-31 01:11:41 +00002692 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002693 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002694 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2695 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2696 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002697 return;
2698 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002699
Michael Han99315932013-01-24 16:46:58 +00002700 D->addAttr(::new (S.Context)
2701 BlocksAttr(Attr.getRange(), S.Context, type,
2702 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002703}
2704
Chandler Carruthedc2c642011-07-02 00:01:44 +00002705static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002706 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002707 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002708 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002709 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002710 if (E->isTypeDependent() || E->isValueDependent() ||
2711 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002712 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002713 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002714 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002715 return;
2716 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002717
John McCallb46f2872011-09-09 07:56:05 +00002718 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002719 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2720 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002721 return;
2722 }
John McCallb46f2872011-09-09 07:56:05 +00002723
2724 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002725 }
2726
Aaron Ballman18a78382013-11-21 00:28:23 +00002727 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002728 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002729 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002730 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002731 if (E->isTypeDependent() || E->isValueDependent() ||
2732 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002733 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002734 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002735 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002736 return;
2737 }
2738 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002739
John McCallb46f2872011-09-09 07:56:05 +00002740 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002741 // FIXME: This error message could be improved, it would be nice
2742 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002743 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2744 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002745 return;
2746 }
2747 }
2748
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002749 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002750 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002751 if (isa<FunctionNoProtoType>(FT)) {
2752 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2753 return;
2754 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002755
Chris Lattner9363e312009-03-17 23:03:47 +00002756 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002757 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002758 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002759 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002760 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002761 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002762 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002763 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002764 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002765 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2766 if (!BD->isVariadic()) {
2767 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2768 return;
2769 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002770 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002771 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002772 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002773 const FunctionType *FT = Ty->isFunctionPointerType()
2774 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002775 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002776 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002777 int m = Ty->isFunctionPointerType() ? 0 : 1;
2778 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002779 return;
2780 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002781 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002782 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002783 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002784 return;
2785 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002786 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002787 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002788 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002789 return;
2790 }
Michael Han99315932013-01-24 16:46:58 +00002791 D->addAttr(::new (S.Context)
2792 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2793 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002794}
2795
Chandler Carruthedc2c642011-07-02 00:01:44 +00002796static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002797 if (D->getFunctionType() &&
2798 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002799 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2800 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002801 return;
2802 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002803 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002804 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002805 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2806 << Attr.getName() << 1;
2807 return;
2808 }
2809
Aaron Ballmane7964782016-03-07 22:44:55 +00002810 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2811 // about using it as an extension.
2812 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2813 !Attr.getScopeName())
Richard Smith4f902c72016-03-08 00:32:55 +00002814 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002815
Michael Han99315932013-01-24 16:46:58 +00002816 D->addAttr(::new (S.Context)
2817 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2818 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002819}
2820
Chandler Carruthedc2c642011-07-02 00:01:44 +00002821static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002822 // weak_import only applies to variable & function declarations.
2823 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002824 if (!D->canBeWeakImported(isDef)) {
2825 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002826 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2827 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002828 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002829 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002830 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002831 // Nothing to warn about here.
2832 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002833 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002834 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002835
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002836 return;
2837 }
2838
Michael Han99315932013-01-24 16:46:58 +00002839 D->addAttr(::new (S.Context)
2840 WeakImportAttr(Attr.getRange(), S.Context,
2841 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002842}
2843
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002844// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002845template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002846static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002847 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002848 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002849 for (unsigned i = 0; i < 3; ++i) {
2850 const Expr *E = Attr.getArgAsExpr(i);
2851 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002852 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002853 if (WGSize[i] == 0) {
2854 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2855 << Attr.getName() << E->getSourceRange();
2856 return;
2857 }
2858 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002859
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002860 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2861 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2862 Existing->getYDim() == WGSize[1] &&
2863 Existing->getZDim() == WGSize[2]))
2864 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002865
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002866 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2867 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002868 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002869}
2870
Joey Goulyaba589c2013-03-08 09:42:32 +00002871static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002872 if (!Attr.hasParsedType()) {
2873 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2874 << Attr.getName() << 1;
2875 return;
2876 }
2877
Craig Topperc3ec1492014-05-26 06:22:03 +00002878 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002879 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2880 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002881
2882 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2883 (ParmType->isBooleanType() ||
2884 !ParmType->isIntegralType(S.getASTContext()))) {
2885 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2886 << ParmType;
2887 return;
2888 }
2889
Aaron Ballmana9e05402013-12-02 22:16:55 +00002890 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002891 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002892 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2893 return;
2894 }
2895 }
2896
2897 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002898 ParmTSI,
2899 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002900}
2901
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002902SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002903 StringRef Name,
2904 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002905 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2906 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002907 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002908 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2909 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002910 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002911 }
Michael Han99315932013-01-24 16:46:58 +00002912 return ::new (Context) SectionAttr(Range, Context, Name,
2913 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002914}
2915
Reid Kleckner2a133222015-03-04 23:39:17 +00002916bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2917 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2918 if (!Error.empty()) {
2919 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2920 return false;
2921 }
2922 return true;
2923}
2924
Chandler Carruthedc2c642011-07-02 00:01:44 +00002925static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00002926 // Make sure that there is a string literal as the sections's single
2927 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002928 StringRef Str;
2929 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002930 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00002931 return;
Mike Stump11289f42009-09-09 15:08:12 +00002932
Reid Kleckner2a133222015-03-04 23:39:17 +00002933 if (!S.checkSectionName(LiteralLoc, Str))
2934 return;
2935
Chris Lattner30ba6742009-08-10 19:03:04 +00002936 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002937 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00002938 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002939 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00002940 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00002941 return;
2942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Michael Han99315932013-01-24 16:46:58 +00002944 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002945 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002946 if (NewAttr)
2947 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00002948}
2949
Eric Christopher789a7ad2015-06-12 01:36:05 +00002950// Check for things we'd like to warn about, no errors or validation for now.
2951// TODO: Validation should use a backend target library that specifies
2952// the allowable subtarget features and cpus. We could use something like a
2953// TargetCodeGenInfo hook here to do validation.
2954void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2955 for (auto Str : {"tune=", "fpmath="})
2956 if (AttrStr.find(Str) != StringRef::npos)
2957 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2958}
2959
Eric Christopher11acf732015-06-12 01:35:52 +00002960static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00002961 StringRef Str;
2962 SourceLocation LiteralLoc;
2963 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2964 return;
Eric Christopher789a7ad2015-06-12 01:36:05 +00002965 S.checkTargetAttr(LiteralLoc, Str);
Eric Christopher11acf732015-06-12 01:35:52 +00002966 unsigned Index = Attr.getAttributeSpellingListIndex();
2967 TargetAttr *NewAttr =
2968 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2969 D->addAttr(NewAttr);
2970}
2971
Chandler Carruthedc2c642011-07-02 00:01:44 +00002972static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002973 VarDecl *VD = cast<VarDecl>(D);
2974 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002975 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002976 return;
2977 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002978
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002979 Expr *E = Attr.getArgAsExpr(0);
2980 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00002981 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002982 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00002983
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002984 // gcc only allows for simple identifiers. Since we support more than gcc, we
2985 // will warn the user.
2986 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2987 if (DRE->hasQualifier())
2988 S.Diag(Loc, diag::warn_cleanup_ext);
2989 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2990 NI = DRE->getNameInfo();
2991 if (!FD) {
2992 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2993 << NI.getName();
2994 return;
2995 }
2996 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2997 if (ULE->hasExplicitTemplateArgs())
2998 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002999 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3000 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00003001 if (!FD) {
3002 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3003 << NI.getName();
3004 if (ULE->getType() == S.Context.OverloadTy)
3005 S.NoteAllOverloadCandidates(ULE);
3006 return;
3007 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003008 } else {
3009 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00003010 return;
3011 }
3012
Anders Carlssond277d792009-01-31 01:16:18 +00003013 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003014 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3015 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003016 return;
3017 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003018
Anders Carlsson723f55d2009-02-07 23:16:50 +00003019 // We're currently more strict than GCC about what function types we accept.
3020 // If this ever proves to be a problem it should be easy to fix.
3021 QualType Ty = S.Context.getPointerType(VD->getType());
3022 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00003023 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3024 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003025 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3026 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00003027 return;
3028 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003029
Michael Han99315932013-01-24 16:46:58 +00003030 D->addAttr(::new (S.Context)
3031 CleanupAttr(Attr.getRange(), S.Context, FD,
3032 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00003033}
3034
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003035static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3036 const AttributeList &Attr) {
3037 if (!Attr.isArgIdent(0)) {
3038 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3039 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3040 return;
3041 }
3042
3043 EnumExtensibilityAttr::Kind ExtensibilityKind;
3044 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3045 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3046 ExtensibilityKind)) {
3047 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3048 << Attr.getName() << II;
3049 return;
3050 }
3051
3052 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3053 Attr.getRange(), S.Context, ExtensibilityKind,
3054 Attr.getAttributeSpellingListIndex()));
3055}
3056
Mike Stumpd3bb5572009-07-24 19:02:52 +00003057/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00003058/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003059static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003060 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00003061 uint64_t Idx;
3062 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003063 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00003064
Eric Christopherb64963e2015-08-13 21:34:35 +00003065 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00003066 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003067
Eric Christopherb64963e2015-08-13 21:34:35 +00003068 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3069 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003070 !isCFStringType(Ty, S.Context) &&
3071 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003072 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003073 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003074 << "a string type" << IdxExpr->getSourceRange()
3075 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003076 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003077 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003078 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003079 if (!isNSStringType(Ty, S.Context) &&
3080 !isCFStringType(Ty, S.Context) &&
3081 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003082 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003083 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003084 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00003085 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003086 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003087 }
3088
Alp Toker601b22c2014-01-21 23:35:24 +00003089 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003090 // because that has corrected for the implicit this parameter, and is zero-
3091 // based. The attribute expects what the user wrote explicitly.
3092 llvm::APSInt Val;
3093 IdxExpr->EvaluateAsInt(Val, S.Context);
3094
Michael Han99315932013-01-24 16:46:58 +00003095 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003096 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00003097 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003098}
3099
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003100enum FormatAttrKind {
3101 CFStringFormat,
3102 NSStringFormat,
3103 StrftimeFormat,
3104 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00003105 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003106 InvalidFormat
3107};
3108
3109/// getFormatAttrKind - Map from format attribute names to supported format
3110/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003111static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00003112 return llvm::StringSwitch<FormatAttrKind>(Format)
Mehdi Amini06d367c2016-10-24 20:39:34 +00003113 // Check for formats that get handled specially.
3114 .Case("NSString", NSStringFormat)
3115 .Case("CFString", CFStringFormat)
3116 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003117
Mehdi Amini06d367c2016-10-24 20:39:34 +00003118 // Otherwise, check for supported formats.
3119 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3120 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3121 .Case("kprintf", SupportedFormat) // OpenBSD.
3122 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3123 .Case("os_trace", SupportedFormat)
3124 .Case("os_log", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003125
Mehdi Amini06d367c2016-10-24 20:39:34 +00003126 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3127 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003128}
3129
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003130/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003131/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003132static void handleInitPriorityAttr(Sema &S, Decl *D,
3133 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003134 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003135 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3136 return;
3137 }
3138
Aaron Ballman4a611152013-11-27 16:34:09 +00003139 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003140 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3141 Attr.setInvalid();
3142 return;
3143 }
Aaron Ballman4a611152013-11-27 16:34:09 +00003144 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003145 if (S.Context.getAsArrayType(T))
3146 T = S.Context.getBaseElementType(T);
3147 if (!T->getAs<RecordType>()) {
3148 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3149 Attr.setInvalid();
3150 return;
3151 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003152
3153 Expr *E = Attr.getArgAsExpr(0);
3154 uint32_t prioritynum;
3155 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003156 Attr.setInvalid();
3157 return;
3158 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003159
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003160 if (prioritynum < 101 || prioritynum > 65535) {
3161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003162 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003163 Attr.setInvalid();
3164 return;
3165 }
Michael Han99315932013-01-24 16:46:58 +00003166 D->addAttr(::new (S.Context)
3167 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3168 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003169}
3170
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003171FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3172 IdentifierInfo *Format, int FormatIdx,
3173 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003174 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003175 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003176 for (auto *F : D->specific_attrs<FormatAttr>()) {
3177 if (F->getType() == Format &&
3178 F->getFormatIdx() == FormatIdx &&
3179 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003180 // If we don't have a valid location for this attribute, adopt the
3181 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003182 if (F->getLocation().isInvalid())
3183 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00003184 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00003185 }
3186 }
3187
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003188 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3189 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00003190}
3191
Mike Stumpd3bb5572009-07-24 19:02:52 +00003192/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003193/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003194static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003195 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00003196 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00003197 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003198 return;
3199 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003200
Chandler Carruth743682b2010-11-16 08:35:43 +00003201 // In C++ the implicit 'this' function parameter also counts, and they are
3202 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003203 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00003204 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003205
Aaron Ballman00e99962013-08-31 01:11:41 +00003206 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3207 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003208
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00003209 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003210 // If we've modified the string name, we need a new identifier for it.
3211 II = &S.Context.Idents.get(Format);
3212 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003213
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003214 // Check for supported formats.
3215 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00003216
3217 if (Kind == IgnoredFormat)
3218 return;
3219
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003220 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00003221 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00003222 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003223 return;
3224 }
3225
3226 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003227 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003228 uint32_t Idx;
3229 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003230 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003231
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003232 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003233 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003234 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003235 return;
3236 }
3237
3238 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003239 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003240
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003241 if (HasImplicitThisParam) {
3242 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00003243 S.Diag(Attr.getLoc(),
3244 diag::err_format_attribute_implicit_this_format_string)
3245 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003246 return;
3247 }
3248 ArgIdx--;
3249 }
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003251 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00003252 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003253
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003254 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00003255 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003256 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003257 << "a CFString" << IdxExpr->getSourceRange()
3258 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00003259 return;
3260 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003261 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003262 // FIXME: do we need to check if the type is NSString*? What are the
3263 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00003264 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003265 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003266 << "an NSString" << IdxExpr->getSourceRange()
3267 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003268 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003269 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003270 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003271 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003272 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003273 << "a string type" << IdxExpr->getSourceRange()
3274 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003275 return;
3276 }
3277
3278 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003279 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003280 uint32_t FirstArg;
3281 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003282 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003283
3284 // check if the function is variadic if the 3rd argument non-zero
3285 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003286 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003287 ++NumArgs; // +1 for ...
3288 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003289 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003290 return;
3291 }
3292 }
3293
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003294 // strftime requires FirstArg to be 0 because it doesn't read from any
3295 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003296 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003297 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00003298 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3299 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003300 return;
3301 }
3302 // if 0 it disables parameter checking (to use with e.g. va_list)
3303 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003304 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003305 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003306 return;
3307 }
3308
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003309 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003310 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003311 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003312 if (NewAttr)
3313 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003314}
3315
Chandler Carruthedc2c642011-07-02 00:01:44 +00003316static void handleTransparentUnionAttr(Sema &S, Decl *D,
3317 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003318 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003319 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003320 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003321 if (TD && TD->getUnderlyingType()->isUnionType())
3322 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3323 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003324 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003325
3326 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003327 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003328 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003329 return;
3330 }
3331
John McCallf937c022011-10-07 06:10:15 +00003332 if (!RD->isCompleteDefinition()) {
Erich Keane2fe684b2017-02-28 20:44:39 +00003333 if (!RD->isBeingDefined())
3334 S.Diag(Attr.getLoc(),
3335 diag::warn_transparent_union_attribute_not_definition);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003336 return;
3337 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003338
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003339 RecordDecl::field_iterator Field = RD->field_begin(),
3340 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003341 if (Field == FieldEnd) {
3342 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3343 return;
3344 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003345
David Blaikie40ed2972012-06-06 20:45:41 +00003346 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003347 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003348 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003349 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003350 diag::warn_transparent_union_attribute_floating)
3351 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003352 return;
3353 }
3354
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003355 if (FirstType->isIncompleteType())
3356 return;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003357 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3358 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3359 for (; Field != FieldEnd; ++Field) {
3360 QualType FieldType = Field->getType();
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003361 if (FieldType->isIncompleteType())
3362 return;
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003363 // FIXME: this isn't fully correct; we also need to test whether the
3364 // members of the union would all have the same calling convention as the
3365 // first member of the union. Checking just the size and alignment isn't
3366 // sufficient (consider structs passed on the stack instead of in registers
3367 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003368 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003369 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003370 // Warn if we drop the attribute.
3371 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003372 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003373 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003374 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003375 diag::warn_transparent_union_attribute_field_size_align)
3376 << isSize << Field->getDeclName() << FieldBits;
3377 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003378 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003379 diag::note_transparent_union_first_field_size_align)
3380 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003381 return;
3382 }
3383 }
3384
Michael Han99315932013-01-24 16:46:58 +00003385 RD->addAttr(::new (S.Context)
3386 TransparentUnionAttr(Attr.getRange(), S.Context,
3387 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003388}
3389
Chandler Carruthedc2c642011-07-02 00:01:44 +00003390static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003391 // Make sure that there is a string literal as the annotation's single
3392 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003393 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003394 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003395 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003396
3397 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003398 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3399 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003400 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003401 }
Michael Han99315932013-01-24 16:46:58 +00003402
3403 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003404 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003405 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003406}
3407
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003408static void handleAlignValueAttr(Sema &S, Decl *D,
3409 const AttributeList &Attr) {
3410 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3411 Attr.getAttributeSpellingListIndex());
3412}
3413
3414void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3415 unsigned SpellingListIndex) {
3416 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3417 SourceLocation AttrLoc = AttrRange.getBegin();
3418
3419 QualType T;
3420 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3421 T = TD->getUnderlyingType();
3422 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3423 T = VD->getType();
3424 else
3425 llvm_unreachable("Unknown decl type for align_value");
3426
3427 if (!T->isDependentType() && !T->isAnyPointerType() &&
3428 !T->isReferenceType() && !T->isMemberPointerType()) {
3429 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3430 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3431 return;
3432 }
3433
3434 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003435 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003436 ExprResult ICE
3437 = VerifyIntegerConstantExpression(E, &Alignment,
3438 diag::err_align_value_attribute_argument_not_int,
3439 /*AllowFold*/ false);
3440 if (ICE.isInvalid())
3441 return;
3442
3443 if (!Alignment.isPowerOf2()) {
3444 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3445 << E->getSourceRange();
3446 return;
3447 }
3448
3449 D->addAttr(::new (Context)
3450 AlignValueAttr(AttrRange, Context, ICE.get(),
3451 SpellingListIndex));
3452 return;
3453 }
3454
3455 // Save dependent expressions in the AST to be instantiated.
3456 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003457}
3458
Chandler Carruthedc2c642011-07-02 00:01:44 +00003459static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003460 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003461 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003462 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3463 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003464 return;
3465 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003466
Richard Smith848e1f12013-02-01 08:12:08 +00003467 if (Attr.getNumArgs() == 0) {
3468 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003469 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003470 return;
3471 }
3472
Aaron Ballman00e99962013-08-31 01:11:41 +00003473 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003474 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3475 S.Diag(Attr.getEllipsisLoc(),
3476 diag::err_pack_expansion_without_parameter_packs);
3477 return;
3478 }
3479
3480 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3481 return;
3482
David Majnemer26a1e0e2015-04-07 02:37:09 +00003483 if (E->isValueDependent()) {
3484 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3485 if (!TND->getUnderlyingType()->isDependentType()) {
3486 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3487 << E->getSourceRange();
3488 return;
3489 }
3490 }
3491 }
3492
Richard Smith44c247f2013-02-22 08:32:16 +00003493 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3494 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003495}
3496
3497void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003498 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003499 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3500 SourceLocation AttrLoc = AttrRange.getBegin();
3501
Richard Smith1dba27c2013-01-29 09:02:09 +00003502 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003503 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003504 // C++11 [dcl.align]p1:
3505 // An alignment-specifier may be applied to a variable or to a class
3506 // data member, but it shall not be applied to a bit-field, a function
3507 // parameter, the formal parameter of a catch clause, or a variable
3508 // declared with the register storage class specifier. An
3509 // alignment-specifier may also be applied to the declaration of a class
3510 // or enumeration type.
3511 // C11 6.7.5/2:
3512 // An alignment attribute shall not be specified in a declaration of
3513 // a typedef, or a bit-field, or a function, or a parameter, or an
3514 // object declared with the register storage-class specifier.
3515 int DiagKind = -1;
3516 if (isa<ParmVarDecl>(D)) {
3517 DiagKind = 0;
3518 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3519 if (VD->getStorageClass() == SC_Register)
3520 DiagKind = 1;
3521 if (VD->isExceptionVariable())
3522 DiagKind = 2;
3523 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3524 if (FD->isBitField())
3525 DiagKind = 3;
3526 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003527 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003528 << (TmpAttr.isC11() ? ExpectedVariableOrField
3529 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003530 return;
3531 }
3532 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003533 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003534 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003535 return;
3536 }
3537 }
3538
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003539 if (E->isTypeDependent() || E->isValueDependent()) {
3540 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003541 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3542 AA->setPackExpansion(IsPackExpansion);
3543 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003544 return;
3545 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003546
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003547 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003548 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003549 ExprResult ICE
3550 = VerifyIntegerConstantExpression(E, &Alignment,
3551 diag::err_aligned_attribute_argument_not_int,
3552 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003553 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003554 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003555
David Majnemer0be6bd02015-07-26 09:02:21 +00003556 uint64_t AlignVal = Alignment.getZExtValue();
3557
Richard Smith848e1f12013-02-01 08:12:08 +00003558 // C++11 [dcl.align]p2:
3559 // -- if the constant expression evaluates to zero, the alignment
3560 // specifier shall have no effect
3561 // C11 6.7.5p6:
3562 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003563 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003564 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003565 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3566 << E->getSourceRange();
3567 return;
3568 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003569 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003570
David Majnemerabecae72014-02-12 20:36:10 +00003571 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003572 unsigned MaxValidAlignment =
3573 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3574 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003575 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003576 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3577 << E->getSourceRange();
3578 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003579 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003580
David Majnemer0be6bd02015-07-26 09:02:21 +00003581 if (Context.getTargetInfo().isTLSSupported()) {
3582 unsigned MaxTLSAlign =
3583 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3584 .getQuantity();
3585 auto *VD = dyn_cast<VarDecl>(D);
3586 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3587 VD->getTLSKind() != VarDecl::TLS_None) {
3588 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3589 << (unsigned)AlignVal << VD << MaxTLSAlign;
3590 return;
3591 }
3592 }
3593
Richard Smith44c247f2013-02-22 08:32:16 +00003594 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003595 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003596 AA->setPackExpansion(IsPackExpansion);
3597 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003598}
3599
Michael Hanaf02bbe2013-02-01 01:19:17 +00003600void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003601 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003602 // FIXME: Cache the number on the Attr object if non-dependent?
3603 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003604 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3605 SpellingListIndex);
3606 AA->setPackExpansion(IsPackExpansion);
3607 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003608}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003609
Richard Smith848e1f12013-02-01 08:12:08 +00003610void Sema::CheckAlignasUnderalignment(Decl *D) {
3611 assert(D->hasAttrs() && "no attributes on decl");
3612
David Majnemer475b25e2015-01-21 10:54:38 +00003613 QualType UnderlyingTy, DiagTy;
3614 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3615 UnderlyingTy = DiagTy = VD->getType();
3616 } else {
3617 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3618 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3619 UnderlyingTy = ED->getIntegerType();
3620 }
3621 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003622 return;
3623
3624 // C++11 [dcl.align]p5, C11 6.7.5/4:
3625 // The combined effect of all alignment attributes in a declaration shall
3626 // not specify an alignment that is less strict than the alignment that
3627 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003628 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003629 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003630 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003631 if (I->isAlignmentDependent())
3632 return;
3633 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003634 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003635 Align = std::max(Align, I->getAlignment(Context));
3636 }
3637
3638 if (AlignasAttr && Align) {
3639 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003640 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003641 if (NaturalAlign > RequestedAlign)
3642 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003643 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003644 }
3645}
3646
David Majnemer2c4e00a2014-01-29 22:07:36 +00003647bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003648 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003649 MSInheritanceAttr::Spelling SemanticSpelling) {
3650 assert(RD->hasDefinition() && "RD has no definition!");
3651
David Majnemer98c9ee22014-02-07 00:43:07 +00003652 // We may not have seen base specifiers or any virtual methods yet. We will
3653 // have to wait until the record is defined to catch any mismatches.
3654 if (!RD->getDefinition()->isCompleteDefinition())
3655 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003656
David Majnemer98c9ee22014-02-07 00:43:07 +00003657 // The unspecified model never matches what a definition could need.
3658 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3659 return false;
3660
David Majnemer4bb09802014-02-10 19:50:15 +00003661 if (BestCase) {
3662 if (RD->calculateInheritanceModel() == SemanticSpelling)
3663 return false;
3664 } else {
3665 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3666 return false;
3667 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003668
3669 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3670 << 0 /*definition*/;
3671 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3672 << RD->getNameAsString();
3673 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003674}
3675
Alexey Bataevf278eb12015-11-19 10:13:11 +00003676/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3677/// attribute.
3678static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3679 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003680 IntegerMode = true;
3681 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003682 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003683 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003684 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003685 case 'Q':
3686 DestWidth = 8;
3687 break;
3688 case 'H':
3689 DestWidth = 16;
3690 break;
3691 case 'S':
3692 DestWidth = 32;
3693 break;
3694 case 'D':
3695 DestWidth = 64;
3696 break;
3697 case 'X':
3698 DestWidth = 96;
3699 break;
3700 case 'T':
3701 DestWidth = 128;
3702 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003703 }
3704 if (Str[1] == 'F') {
3705 IntegerMode = false;
3706 } else if (Str[1] == 'C') {
3707 IntegerMode = false;
3708 ComplexMode = true;
3709 } else if (Str[1] != 'I') {
3710 DestWidth = 0;
3711 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003712 break;
3713 case 4:
3714 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3715 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003716 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003717 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003718 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003719 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003720 break;
3721 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003722 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003723 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003724 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003725 case 11:
3726 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003727 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003728 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003729 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003730}
3731
3732/// handleModeAttr - This attribute modifies the width of a decl with primitive
3733/// type.
3734///
3735/// Despite what would be logical, the mode attribute is a decl attribute, not a
3736/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3737/// HImode, not an intermediate pointer.
3738static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3739 // This attribute isn't documented, but glibc uses it. It changes
3740 // the width of an int or unsigned int to the specified size.
3741 if (!Attr.isArgIdent(0)) {
3742 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3743 << AANT_ArgumentIdentifier;
3744 return;
3745 }
3746
3747 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003748
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003749 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3750}
3751
3752void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3753 unsigned SpellingListIndex, bool InInstantiation) {
3754 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003755 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003756 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003757
3758 unsigned DestWidth = 0;
3759 bool IntegerMode = true;
3760 bool ComplexMode = false;
3761 llvm::APInt VectorSize(64, 0);
3762 if (Str.size() >= 4 && Str[0] == 'V') {
3763 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3764 size_t StrSize = Str.size();
3765 size_t VectorStringLength = 0;
3766 while ((VectorStringLength + 1) < StrSize &&
3767 isdigit(Str[VectorStringLength + 1]))
3768 ++VectorStringLength;
3769 if (VectorStringLength &&
3770 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3771 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003772 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003773 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003774 // Avoid duplicate warning from template instantiation.
3775 if (!InInstantiation)
3776 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003777 } else {
3778 VectorSize = 0;
3779 }
3780 }
3781
3782 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003783 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3784
3785 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3786 // and friends, at least with glibc.
3787 // FIXME: Make sure floating-point mappings are accurate
3788 // FIXME: Support XF and TF types
3789 if (!DestWidth) {
3790 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3791 return;
3792 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003793
3794 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003795 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003796 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003797 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3798 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3799 // Try to get type from enum declaration, default to int.
3800 OldTy = ED->getIntegerType();
3801 if (OldTy.isNull())
3802 OldTy = Context.IntTy;
3803 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003804 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003805
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003806 if (OldTy->isDependentType()) {
3807 D->addAttr(::new (Context)
3808 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3809 return;
3810 }
3811
Alexey Bataev326057d2015-06-19 07:46:21 +00003812 // Base type can also be a vector type (see PR17453).
3813 // Distinguish between base type and base element type.
3814 QualType OldElemTy = OldTy;
3815 if (const VectorType *VT = OldTy->getAs<VectorType>())
3816 OldElemTy = VT->getElementType();
3817
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003818 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3819 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3820 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3821 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3822 VectorSize.getBoolValue()) {
3823 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3824 return;
3825 }
3826 bool IntegralOrAnyEnumType =
3827 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3828
3829 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3830 !IntegralOrAnyEnumType)
3831 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003832 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003833 if (!IntegralOrAnyEnumType)
3834 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003835 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003836 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003837 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003838 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003839 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003840 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003841 }
3842
Alexey Bataev326057d2015-06-19 07:46:21 +00003843 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003844
3845 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003846 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3847 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003848 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003849 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003850
Alexey Bataev326057d2015-06-19 07:46:21 +00003851 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003852 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003853 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003854 }
3855
Eli Friedman4735374e2009-03-03 06:41:03 +00003856 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003857 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003858 }
3859
3860 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003861 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003862 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3863 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003864 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003865 // Complex machine mode does not support base vector types.
3866 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003867 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003868 return;
3869 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003870 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003871 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003872 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003873 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003874 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003875 }
3876
3877 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003878 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003879 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003880 }
3881
3882 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003883 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3884 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003885 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3886 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003887 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003888 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003889
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003890 D->addAttr(::new (Context)
3891 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003892}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003893
Chandler Carruthedc2c642011-07-02 00:01:44 +00003894static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00003895 D->addAttr(::new (S.Context)
3896 NoDebugAttr(Attr.getRange(), S.Context,
3897 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003898}
3899
Paul Robinson30e41fb2014-12-15 18:57:28 +00003900AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003901 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003902 unsigned AttrSpellingListIndex) {
3903 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003904 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00003905 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3906 return nullptr;
3907 }
3908
3909 if (D->hasAttr<AlwaysInlineAttr>())
3910 return nullptr;
3911
3912 return ::new (Context) AlwaysInlineAttr(Range, Context,
3913 AttrSpellingListIndex);
3914}
3915
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003916CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3917 IdentifierInfo *Ident,
3918 unsigned AttrSpellingListIndex) {
3919 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3920 return nullptr;
3921
3922 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3923}
3924
3925InternalLinkageAttr *
3926Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3927 IdentifierInfo *Ident,
3928 unsigned AttrSpellingListIndex) {
3929 if (auto VD = dyn_cast<VarDecl>(D)) {
3930 // Attribute applies to Var but not any subclass of it (like ParmVar,
3931 // ImplicitParm or VarTemplateSpecialization).
3932 if (VD->getKind() != Decl::Var) {
3933 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3934 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3935 : ExpectedVariableOrFunction);
3936 return nullptr;
3937 }
3938 // Attribute does not apply to non-static local variables.
3939 if (VD->hasLocalStorage()) {
3940 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3941 return nullptr;
3942 }
3943 }
3944
3945 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3946 return nullptr;
3947
3948 return ::new (Context)
3949 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3950}
3951
Paul Robinson30e41fb2014-12-15 18:57:28 +00003952MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3953 unsigned AttrSpellingListIndex) {
3954 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3955 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3956 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3957 return nullptr;
3958 }
3959
3960 if (D->hasAttr<MinSizeAttr>())
3961 return nullptr;
3962
3963 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3964}
3965
3966OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3967 unsigned AttrSpellingListIndex) {
3968 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3969 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3970 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3971 D->dropAttr<AlwaysInlineAttr>();
3972 }
3973 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3974 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3975 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3976 D->dropAttr<MinSizeAttr>();
3977 }
3978
3979 if (D->hasAttr<OptimizeNoneAttr>())
3980 return nullptr;
3981
3982 return ::new (Context) OptimizeNoneAttr(Range, Context,
3983 AttrSpellingListIndex);
3984}
3985
Paul Robinsonf0674352014-03-31 22:29:15 +00003986static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3987 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003988 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00003989 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00003990 return;
3991
Paul Robinson080b1f32015-01-13 18:34:56 +00003992 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3993 D, Attr.getRange(), Attr.getName(),
3994 Attr.getAttributeSpellingListIndex()))
3995 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00003996}
3997
Paul Robinson080b1f32015-01-13 18:34:56 +00003998static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3999 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4000 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4001 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00004002}
4003
Paul Robinsonf0674352014-03-31 22:29:15 +00004004static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4005 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004006 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4007 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4008 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00004009}
4010
Justin Lebare71b2fa2016-09-30 23:57:34 +00004011static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4012 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4013 Attr.getName()))
4014 return;
4015 auto *VD = cast<VarDecl>(D);
4016 if (!VD->hasGlobalStorage()) {
4017 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4018 return;
4019 }
4020 D->addAttr(::new (S.Context) CUDAConstantAttr(
4021 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4022}
4023
Justin Lebar10411012016-09-30 23:57:30 +00004024static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4025 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4026 Attr.getName()))
4027 return;
4028 auto *VD = cast<VarDecl>(D);
Justin Lebar281ce2a2016-10-02 15:24:50 +00004029 // extern __shared__ is only allowed on arrays with no length (e.g.
4030 // "int x[]").
4031 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
Justin Lebar10411012016-09-30 23:57:30 +00004032 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4033 return;
4034 }
Justin Lebaraa370bd2016-10-13 18:45:13 +00004035 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4036 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4037 << S.CurrentCUDATarget())
4038 return;
Justin Lebar10411012016-09-30 23:57:30 +00004039 D->addAttr(::new (S.Context) CUDASharedAttr(
4040 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4041}
4042
Chandler Carruthedc2c642011-07-02 00:01:44 +00004043static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00004044 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4045 Attr.getName()) ||
4046 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4047 Attr.getName())) {
4048 return;
4049 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00004050 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00004051 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00004052 SourceRange RTRange = FD->getReturnTypeSourceRange();
4053 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004054 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00004055 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4056 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00004057 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004058 }
Justin Lebarc66a1062016-01-20 00:26:57 +00004059 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4060 if (Method->isInstance()) {
4061 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4062 << Method;
4063 return;
4064 }
4065 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4066 }
4067 // Only warn for "inline" when compiling for host, to cut down on noise.
4068 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4069 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004070
Aaron Ballman3aff6332013-12-02 19:30:36 +00004071 D->addAttr(::new (S.Context)
4072 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00004073 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004074}
4075
Chandler Carruthedc2c642011-07-02 00:01:44 +00004076static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004077 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00004078 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00004079 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00004080 return;
4081 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004082
Michael Han99315932013-01-24 16:46:58 +00004083 D->addAttr(::new (S.Context)
4084 GNUInlineAttr(Attr.getRange(), S.Context,
4085 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00004086}
4087
Chandler Carruthedc2c642011-07-02 00:01:44 +00004088static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004089 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004090
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004091 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00004092 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4093 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00004094 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00004095 return;
4096
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004097 if (!isa<ObjCMethodDecl>(D)) {
4098 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4099 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00004100 return;
4101 }
4102
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004103 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004104 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00004105 D->addAttr(::new (S.Context)
4106 FastCallAttr(Attr.getRange(), S.Context,
4107 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004108 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004109 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00004110 D->addAttr(::new (S.Context)
4111 StdCallAttr(Attr.getRange(), S.Context,
4112 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004113 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004114 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00004115 D->addAttr(::new (S.Context)
4116 ThisCallAttr(Attr.getRange(), S.Context,
4117 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00004118 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004119 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00004120 D->addAttr(::new (S.Context)
4121 CDeclAttr(Attr.getRange(), S.Context,
4122 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004123 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004124 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00004125 D->addAttr(::new (S.Context)
4126 PascalAttr(Attr.getRange(), S.Context,
4127 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00004128 return;
John McCall477f2bb2016-03-03 06:39:32 +00004129 case AttributeList::AT_SwiftCall:
4130 D->addAttr(::new (S.Context)
4131 SwiftCallAttr(Attr.getRange(), S.Context,
4132 Attr.getAttributeSpellingListIndex()));
4133 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004134 case AttributeList::AT_VectorCall:
4135 D->addAttr(::new (S.Context)
4136 VectorCallAttr(Attr.getRange(), S.Context,
4137 Attr.getAttributeSpellingListIndex()));
4138 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00004139 case AttributeList::AT_MSABI:
4140 D->addAttr(::new (S.Context)
4141 MSABIAttr(Attr.getRange(), S.Context,
4142 Attr.getAttributeSpellingListIndex()));
4143 return;
4144 case AttributeList::AT_SysVABI:
4145 D->addAttr(::new (S.Context)
4146 SysVABIAttr(Attr.getRange(), S.Context,
4147 Attr.getAttributeSpellingListIndex()));
4148 return;
Erich Keane757d3172016-11-02 18:29:35 +00004149 case AttributeList::AT_RegCall:
4150 D->addAttr(::new (S.Context) RegCallAttr(
4151 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4152 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004153 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004154 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004155 switch (CC) {
4156 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004157 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004158 break;
4159 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004160 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004161 break;
4162 default:
4163 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004164 }
4165
Michael Han99315932013-01-24 16:46:58 +00004166 D->addAttr(::new (S.Context)
4167 PcsAttr(Attr.getRange(), S.Context, PCS,
4168 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00004169 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004170 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004171 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00004172 D->addAttr(::new (S.Context)
4173 IntelOclBiccAttr(Attr.getRange(), S.Context,
4174 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00004175 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004176 case AttributeList::AT_PreserveMost:
4177 D->addAttr(::new (S.Context) PreserveMostAttr(
4178 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4179 return;
4180 case AttributeList::AT_PreserveAll:
4181 D->addAttr(::new (S.Context) PreserveAllAttr(
4182 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4183 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004184 default:
4185 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00004186 }
4187}
4188
Matthias Gehre01a63382017-03-27 19:45:24 +00004189static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4190 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4191 return;
4192
4193 std::vector<StringRef> DiagnosticIdentifiers;
4194 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4195 StringRef RuleName;
4196
4197 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4198 return;
4199
4200 // FIXME: Warn if the rule name is unknown. This is tricky because only
4201 // clang-tidy knows about available rules.
4202 DiagnosticIdentifiers.push_back(RuleName);
4203 }
4204 D->addAttr(::new (S.Context) SuppressAttr(
4205 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4206 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4207}
4208
Aaron Ballman02df2e02012-12-09 17:45:41 +00004209bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4210 const FunctionDecl *FD) {
John McCall3882ace2011-01-05 12:14:39 +00004211 if (attr.isInvalid())
4212 return true;
4213
John McCall3b5a8f52016-03-03 00:10:03 +00004214 if (attr.hasProcessingCache()) {
4215 CC = (CallingConv) attr.getProcessingCache();
4216 return false;
4217 }
4218
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004219 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
Aaron Ballman00e99962013-08-31 01:11:41 +00004220 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
John McCall3882ace2011-01-05 12:14:39 +00004221 attr.setInvalid();
4222 return true;
4223 }
4224
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004225 // TODO: diagnose uses of these conventions on the wrong target.
John McCall3882ace2011-01-05 12:14:39 +00004226 switch (attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004227 case AttributeList::AT_CDecl: CC = CC_C; break;
4228 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4229 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4230 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4231 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00004232 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004233 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Erich Keane757d3172016-11-02 18:29:35 +00004234 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00004235 case AttributeList::AT_MSABI:
4236 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4237 CC_X86_64Win64;
4238 break;
4239 case AttributeList::AT_SysVABI:
4240 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4241 CC_C;
4242 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004243 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00004244 StringRef StrRef;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004245 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004246 attr.setInvalid();
4247 return true;
4248 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004249 if (StrRef == "aapcs") {
4250 CC = CC_AAPCS;
4251 break;
4252 } else if (StrRef == "aapcs-vfp") {
4253 CC = CC_AAPCS_VFP;
4254 break;
4255 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004256
4257 attr.setInvalid();
4258 Diag(attr.getLoc(), diag::err_invalid_pcs);
4259 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004260 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004261 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004262 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4263 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00004264 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00004265 }
4266
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004267 const TargetInfo &TI = Context.getTargetInfo();
4268 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004269 if (A != TargetInfo::CCCR_OK) {
4270 if (A == TargetInfo::CCCR_Warning)
4271 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00004272
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004273 // This convention is not valid for the target. Use the default function or
4274 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00004275 bool IsCXXMethod = false, IsVariadic = false;
4276 if (FD) {
4277 IsCXXMethod = FD->isCXXInstanceMember();
4278 IsVariadic = FD->isVariadic();
4279 }
4280 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004281 }
4282
John McCall3b5a8f52016-03-03 00:10:03 +00004283 attr.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00004284 return false;
4285}
4286
John McCall477f2bb2016-03-03 06:39:32 +00004287/// Pointer-like types in the default address space.
4288static bool isValidSwiftContextType(QualType type) {
4289 if (!type->hasPointerRepresentation())
4290 return type->isDependentType();
4291 return type->getPointeeType().getAddressSpace() == 0;
4292}
4293
4294/// Pointers and references in the default address space.
4295static bool isValidSwiftIndirectResultType(QualType type) {
4296 if (auto ptrType = type->getAs<PointerType>()) {
4297 type = ptrType->getPointeeType();
4298 } else if (auto refType = type->getAs<ReferenceType>()) {
4299 type = refType->getPointeeType();
4300 } else {
4301 return type->isDependentType();
4302 }
4303 return type.getAddressSpace() == 0;
4304}
4305
4306/// Pointers and references to pointers in the default address space.
4307static bool isValidSwiftErrorResultType(QualType type) {
4308 if (auto ptrType = type->getAs<PointerType>()) {
4309 type = ptrType->getPointeeType();
4310 } else if (auto refType = type->getAs<ReferenceType>()) {
4311 type = refType->getPointeeType();
4312 } else {
4313 return type->isDependentType();
4314 }
4315 if (!type.getQualifiers().empty())
4316 return false;
4317 return isValidSwiftContextType(type);
4318}
4319
4320static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4321 ParameterABI abi) {
4322 S.AddParameterABIAttr(attr.getRange(), D, abi,
4323 attr.getAttributeSpellingListIndex());
4324}
4325
4326void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4327 unsigned spellingIndex) {
4328
4329 QualType type = cast<ParmVarDecl>(D)->getType();
4330
4331 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4332 if (existingAttr->getABI() != abi) {
4333 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4334 << getParameterABISpelling(abi) << existingAttr;
4335 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4336 return;
4337 }
4338 }
4339
4340 switch (abi) {
4341 case ParameterABI::Ordinary:
4342 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4343
4344 case ParameterABI::SwiftContext:
4345 if (!isValidSwiftContextType(type)) {
4346 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4347 << getParameterABISpelling(abi)
4348 << /*pointer to pointer */ 0 << type;
4349 }
4350 D->addAttr(::new (Context)
4351 SwiftContextAttr(range, Context, spellingIndex));
4352 return;
4353
4354 case ParameterABI::SwiftErrorResult:
4355 if (!isValidSwiftErrorResultType(type)) {
4356 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4357 << getParameterABISpelling(abi)
4358 << /*pointer to pointer */ 1 << type;
4359 }
4360 D->addAttr(::new (Context)
4361 SwiftErrorResultAttr(range, Context, spellingIndex));
4362 return;
4363
4364 case ParameterABI::SwiftIndirectResult:
4365 if (!isValidSwiftIndirectResultType(type)) {
4366 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4367 << getParameterABISpelling(abi)
4368 << /*pointer*/ 0 << type;
4369 }
4370 D->addAttr(::new (Context)
4371 SwiftIndirectResultAttr(range, Context, spellingIndex));
4372 return;
4373 }
4374 llvm_unreachable("bad parameter ABI attribute");
4375}
4376
John McCall3882ace2011-01-05 12:14:39 +00004377/// Checks a regparm attribute, returning true if it is ill-formed and
4378/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004379bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4380 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004381 return true;
4382
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004383 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004384 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004385 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004386 }
Eli Friedman7044b762009-03-27 21:06:47 +00004387
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004388 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004389 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004390 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004391 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004392 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004393 }
4394
Douglas Gregore8bbc122011-09-02 00:18:52 +00004395 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004396 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004397 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004398 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004399 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004400 }
4401
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004402 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004403 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004404 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004405 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004406 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004407 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004408 }
4409
John McCall3882ace2011-01-05 12:14:39 +00004410 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004411}
4412
Artem Belevichbcec9da2016-06-06 22:54:57 +00004413// Checks whether an argument of launch_bounds attribute is
4414// acceptable, performs implicit conversion to Rvalue, and returns
4415// non-nullptr Expr result on success. Otherwise, it returns nullptr
4416// and may output an error.
4417static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4418 const CUDALaunchBoundsAttr &Attr,
4419 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004420 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004421 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004422
4423 // Accept template arguments for now as they depend on something else.
4424 // We'll get to check them when they eventually get instantiated.
4425 if (E->isValueDependent())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004426 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004427
4428 llvm::APSInt I(64);
4429 if (!E->isIntegerConstantExpr(I, S.Context)) {
4430 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4431 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004432 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004433 }
4434 // Make sure we can fit it in 32 bits.
4435 if (!I.isIntN(32)) {
4436 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4437 << 32 << /* Unsigned */ 1;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004438 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004439 }
4440 if (I < 0)
4441 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4442 << &Attr << Idx << E->getSourceRange();
4443
Artem Belevichbcec9da2016-06-06 22:54:57 +00004444 // We may need to perform implicit conversion of the argument.
4445 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4446 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4447 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4448 assert(!ValArg.isInvalid() &&
4449 "Unexpected PerformCopyInitialization() failure.");
4450
4451 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004452}
4453
4454void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4455 Expr *MinBlocks, unsigned SpellingListIndex) {
4456 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4457 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004458 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4459 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004460 return;
4461
Artem Belevichbcec9da2016-06-06 22:54:57 +00004462 if (MinBlocks) {
4463 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4464 if (MinBlocks == nullptr)
4465 return;
4466 }
Artem Belevich7093e402015-04-21 22:55:54 +00004467
4468 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4469 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4470}
4471
4472static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4473 const AttributeList &Attr) {
4474 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4475 !checkAttributeAtMostNumArgs(S, Attr, 2))
4476 return;
4477
4478 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4479 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4480 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004481}
4482
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004483static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4484 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004485 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004486 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004487 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004488 return;
4489 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004490
4491 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004492 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004493
Aaron Ballman00e99962013-08-31 01:11:41 +00004494 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004495
4496 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4497 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4498 << Attr.getName() << ExpectedFunctionOrMethod;
4499 return;
4500 }
4501
4502 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004503 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4504 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004505 return;
4506
4507 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004508 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4509 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004510 return;
4511
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004512 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004513 if (IsPointer) {
4514 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004515 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004516 if (!BufferTy->isPointerType()) {
4517 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004518 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004519 }
4520 }
4521
Michael Han99315932013-01-24 16:46:58 +00004522 D->addAttr(::new (S.Context)
4523 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4524 ArgumentIdx, TypeTagIdx, IsPointer,
4525 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004526}
4527
4528static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4529 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004530 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004531 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004532 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004533 return;
4534 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004535
4536 if (!checkAttributeNumArgs(S, Attr, 1))
4537 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004538
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004539 if (!isa<VarDecl>(D)) {
4540 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4541 << Attr.getName() << ExpectedVariable;
4542 return;
4543 }
4544
Aaron Ballman00e99962013-08-31 01:11:41 +00004545 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004546 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004547 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4548 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004549
Michael Han99315932013-01-24 16:46:58 +00004550 D->addAttr(::new (S.Context)
4551 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004552 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004553 Attr.getLayoutCompatible(),
4554 Attr.getMustBeNull(),
4555 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004556}
4557
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004558static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4559 const AttributeList &Attr) {
4560 uint64_t ArgCount;
4561 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4562 ArgCount))
4563 return;
4564
4565 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4566 D->addAttr(::new (S.Context)
4567 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4568 Attr.getAttributeSpellingListIndex()));
4569}
4570
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004571//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004572// Checker-specific attribute handlers.
4573//===----------------------------------------------------------------------===//
4574
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004575static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004576 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004577 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004578}
4579
John McCalled433932011-01-25 03:31:58 +00004580static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004581 return type->isDependentType() ||
4582 type->isObjCObjectPointerType() ||
4583 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004584}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004585
John McCalled433932011-01-25 03:31:58 +00004586static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004587 return type->isDependentType() ||
4588 type->isPointerType() ||
4589 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004590}
4591
Chandler Carruthedc2c642011-07-02 00:01:44 +00004592static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004593 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4594 Attr.getKind() == AttributeList::AT_NSConsumed,
4595 /*template instantiation*/ false);
4596}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004597
John McCall3b5a8f52016-03-03 00:10:03 +00004598void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4599 unsigned spellingIndex, bool isNSConsumed,
4600 bool isTemplateInstantiation) {
4601 ParmVarDecl *param = cast<ParmVarDecl>(D);
4602 bool typeOK;
4603
4604 if (isNSConsumed) {
4605 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004606 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004607 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004608 }
4609
4610 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004611 // These attributes are normally just advisory, but in ARC, ns_consumed
4612 // is significant. Allow non-dependent code to contain inappropriate
4613 // attributes even in ARC, but require template instantiations to be
4614 // set up correctly.
4615 Diag(D->getLocStart(),
4616 (isTemplateInstantiation && isNSConsumed &&
4617 getLangOpts().ObjCAutoRefCount
4618 ? diag::err_ns_attribute_wrong_parameter_type
4619 : diag::warn_ns_attribute_wrong_parameter_type))
4620 << attrRange
4621 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4622 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004623 return;
4624 }
4625
John McCall3b5a8f52016-03-03 00:10:03 +00004626 if (isNSConsumed)
4627 param->addAttr(::new (Context)
4628 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004629 else
John McCall3b5a8f52016-03-03 00:10:03 +00004630 param->addAttr(::new (Context)
4631 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004632}
4633
Chandler Carruthedc2c642011-07-02 00:01:44 +00004634static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4635 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004636 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004637
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004638 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004639 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004640 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004641 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004642 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004643 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4644 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004645 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004646 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004647 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4648 returnType = Param->getType()->getPointeeType();
4649 if (returnType.isNull()) {
4650 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4651 << Attr.getName() << /*pointer-to-CF*/2
4652 << Attr.getRange();
4653 return;
4654 }
4655 } else {
4656 AttributeDeclKind ExpectedDeclKind;
4657 switch (Attr.getKind()) {
4658 default: llvm_unreachable("invalid ownership attribute");
4659 case AttributeList::AT_NSReturnsRetained:
4660 case AttributeList::AT_NSReturnsAutoreleased:
4661 case AttributeList::AT_NSReturnsNotRetained:
4662 ExpectedDeclKind = ExpectedFunctionOrMethod;
4663 break;
4664
4665 case AttributeList::AT_CFReturnsRetained:
4666 case AttributeList::AT_CFReturnsNotRetained:
4667 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4668 break;
4669 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004670 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004671 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004672 return;
4673 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004674
John McCalled433932011-01-25 03:31:58 +00004675 bool typeOK;
4676 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004677 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004678 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004679 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004680 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004681 cf = false;
4682 break;
4683
4684 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004685 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004686 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4687 cf = false;
4688 break;
4689
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004690 case AttributeList::AT_CFReturnsRetained:
4691 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004692 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4693 cf = true;
4694 break;
4695 }
4696
4697 if (!typeOK) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004698 if (isa<ParmVarDecl>(D)) {
4699 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4700 << Attr.getName() << /*pointer-to-CF*/2
4701 << Attr.getRange();
4702 } else {
4703 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4704 enum : unsigned {
4705 Function,
4706 Method,
4707 Property
4708 } SubjectKind = Function;
4709 if (isa<ObjCMethodDecl>(D))
4710 SubjectKind = Method;
4711 else if (isa<ObjCPropertyDecl>(D))
4712 SubjectKind = Property;
4713 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4714 << Attr.getName() << SubjectKind << cf
4715 << Attr.getRange();
4716 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004717 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004718 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004719
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004720 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004721 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004722 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004723 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004724 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4725 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004726 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004727 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004728 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4729 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004730 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004731 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004732 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4733 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004734 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004735 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004736 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4737 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004738 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004739 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004740 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4741 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004742 return;
4743 };
4744}
4745
John McCallcf166702011-07-22 08:53:00 +00004746static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4747 const AttributeList &attr) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004748 const int EP_ObjCMethod = 1;
4749 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004750
John McCallcf166702011-07-22 08:53:00 +00004751 SourceLocation loc = attr.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004752 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004753 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004754 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004755 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004756 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004757
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004758 if (!resultType->isReferenceType() &&
4759 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004760 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004761 << SourceRange(loc)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004762 << attr.getName()
4763 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004764 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004765
4766 // Drop the attribute.
4767 return;
4768 }
4769
Nico Weber462fd1e2015-01-07 23:50:05 +00004770 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4771 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004772}
4773
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004774static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4775 const AttributeList &attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004776 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004777
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004778 DeclContext *DC = method->getDeclContext();
4779 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4780 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4781 << attr.getName() << 0;
4782 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4783 return;
4784 }
4785 if (method->getMethodFamily() == OMF_dealloc) {
4786 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4787 << attr.getName() << 1;
4788 return;
4789 }
4790
Michael Han99315932013-01-24 16:46:58 +00004791 method->addAttr(::new (S.Context)
4792 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4793 attr.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004794}
4795
Aaron Ballmanfb763042013-12-02 18:05:46 +00004796static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4797 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004798 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4799 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004800 return;
John McCall32f5fe12011-09-30 05:12:12 +00004801
Aaron Ballmanfb763042013-12-02 18:05:46 +00004802 D->addAttr(::new (S.Context)
4803 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4804 Attr.getAttributeSpellingListIndex()));
4805}
4806
4807static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4808 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004809 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4810 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004811 return;
4812
4813 D->addAttr(::new (S.Context)
4814 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4815 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004816}
4817
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004818static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4819 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004820 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004821
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004822 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004823 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004824 return;
4825 }
John McCall28592582015-02-01 22:34:06 +00004826
4827 // Typedefs only allow objc_bridge(id) and have some additional checking.
4828 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4829 if (!Parm->Ident->isStr("id")) {
4830 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4831 << Attr.getName();
4832 return;
4833 }
4834
4835 // Only allow 'cv void *'.
4836 QualType T = TD->getUnderlyingType();
4837 if (!T->isVoidPointerType()) {
4838 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4839 return;
4840 }
4841 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004842
4843 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004844 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004845 Attr.getAttributeSpellingListIndex()));
4846}
4847
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004848static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4849 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004850 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4851
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004852 if (!Parm) {
4853 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4854 return;
4855 }
4856
4857 D->addAttr(::new (S.Context)
4858 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4859 Attr.getAttributeSpellingListIndex()));
4860}
4861
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004862static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4863 const AttributeList &Attr) {
4864 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004865 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004866 if (!RelatedClass) {
4867 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4868 return;
4869 }
4870 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004871 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004872 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004873 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004874 D->addAttr(::new (S.Context)
4875 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4876 ClassMethod, InstanceMethod,
4877 Attr.getAttributeSpellingListIndex()));
4878}
4879
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004880static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4881 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004882 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004883 if (ObjCCategoryDecl *CatDecl =
4884 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004885 IFace = CatDecl->getClassInterface();
4886 else
4887 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00004888
4889 if (!IFace)
4890 return;
4891
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00004892 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00004893 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004894 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4895 Attr.getAttributeSpellingListIndex()));
4896}
4897
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004898static void handleObjCRuntimeName(Sema &S, Decl *D,
4899 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00004900 StringRef MetaDataName;
4901 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4902 return;
4903 D->addAttr(::new (S.Context)
4904 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4905 MetaDataName,
4906 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004907}
4908
Nico Webera6916892016-06-10 18:53:04 +00004909// When a user wants to use objc_boxable with a union or struct
4910// but they don't have access to the declaration (legacy/third-party code)
4911// then they can 'enable' this feature with a typedef:
Alex Denisovfde64952015-06-26 05:28:36 +00004912// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4913static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4914 bool notify = false;
4915
4916 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4917 if (RD && RD->getDefinition()) {
4918 RD = RD->getDefinition();
4919 notify = true;
4920 }
4921
4922 if (RD) {
4923 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4924 ObjCBoxableAttr(Attr.getRange(), S.Context,
4925 Attr.getAttributeSpellingListIndex());
4926 RD->addAttr(BoxableAttr);
4927 if (notify) {
4928 // we need to notify ASTReader/ASTWriter about
4929 // modification of existing declaration
4930 if (ASTMutationListener *L = S.getASTMutationListener())
4931 L->AddedAttributeToRecord(BoxableAttr, RD);
4932 }
4933 }
4934}
4935
Chandler Carruthedc2c642011-07-02 00:01:44 +00004936static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4937 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004938 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00004939
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004940 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00004941 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00004942}
4943
Chandler Carruthedc2c642011-07-02 00:01:44 +00004944static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4945 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004946 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00004947 QualType type = vd->getType();
4948
4949 if (!type->isDependentType() &&
4950 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004951 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00004952 << type;
4953 return;
4954 }
4955
4956 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4957
4958 // If we have no lifetime yet, check the lifetime we're presumably
4959 // going to infer.
4960 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4961 lifetime = type->getObjCARCImplicitLifetime();
4962
4963 switch (lifetime) {
4964 case Qualifiers::OCL_None:
4965 assert(type->isDependentType() &&
4966 "didn't infer lifetime for non-dependent type?");
4967 break;
4968
4969 case Qualifiers::OCL_Weak: // meaningful
4970 case Qualifiers::OCL_Strong: // meaningful
4971 break;
4972
4973 case Qualifiers::OCL_ExplicitNone:
4974 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004975 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00004976 << (lifetime == Qualifiers::OCL_Autoreleasing);
4977 break;
4978 }
4979
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004980 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00004981 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4982 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00004983}
4984
Francois Picheta83957a2010-12-19 06:50:37 +00004985//===----------------------------------------------------------------------===//
4986// Microsoft specific attribute handlers.
4987//===----------------------------------------------------------------------===//
4988
Nico Weber88f5ed92016-09-13 18:55:26 +00004989UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4990 unsigned AttrSpellingListIndex, StringRef Uuid) {
4991 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00004992 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00004993 return nullptr;
4994 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4995 Diag(Range.getBegin(), diag::note_previous_uuid);
4996 D->dropAttr<UuidAttr>();
4997 }
4998
4999 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5000}
5001
Chandler Carruthedc2c642011-07-02 00:01:44 +00005002static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00005003 if (!S.LangOpts.CPlusPlus) {
5004 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5005 << Attr.getName() << AttributeLangSupport::C;
5006 return;
5007 }
5008
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005009 StringRef StrRef;
5010 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00005011 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00005012 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005013
David Majnemer89085342013-08-09 08:56:20 +00005014 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5015 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00005016 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5017 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00005018
Reid Kleckner140c4a72013-05-17 14:04:52 +00005019 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00005020 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005021 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005022 return;
5023 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00005024
David Majnemer89085342013-08-09 08:56:20 +00005025 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00005026 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00005027 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005028 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00005029 return;
5030 }
David Majnemer89085342013-08-09 08:56:20 +00005031 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005032 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005033 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005034 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00005035 }
Francois Picheta83957a2010-12-19 06:50:37 +00005036
Nico Weber88f5ed92016-09-13 18:55:26 +00005037 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5038 Attr.getAttributeSpellingListIndex(), StrRef);
5039 if (UA)
5040 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00005041}
5042
David Majnemer2c4e00a2014-01-29 22:07:36 +00005043static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5044 if (!S.LangOpts.CPlusPlus) {
5045 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5046 << Attr.getName() << AttributeLangSupport::C;
5047 return;
5048 }
5049 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00005050 D, Attr.getRange(), /*BestCase=*/true,
5051 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00005052 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00005053 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00005054 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00005055 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5056 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00005057}
5058
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005059static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5060 const AttributeList &Attr) {
5061 VarDecl *VD = cast<VarDecl>(D);
5062 if (!S.Context.getTargetInfo().isTLSSupported()) {
5063 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5064 return;
5065 }
5066 if (VD->getTSCSpec() != TSCS_unspecified) {
5067 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5068 return;
5069 }
5070 if (VD->hasLocalStorage()) {
5071 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5072 return;
5073 }
5074 VD->addAttr(::new (S.Context) ThreadAttr(
5075 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5076}
5077
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005078static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5079 SmallVector<StringRef, 4> Tags;
5080 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5081 StringRef Tag;
5082 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5083 return;
5084 Tags.push_back(Tag);
5085 }
5086
5087 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5088 if (!NS->isInline()) {
5089 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5090 return;
5091 }
5092 if (NS->isAnonymousNamespace()) {
5093 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5094 return;
5095 }
5096 if (Attr.getNumArgs() == 0)
5097 Tags.push_back(NS->getName());
5098 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5099 return;
5100
5101 // Store tags sorted and without duplicates.
5102 std::sort(Tags.begin(), Tags.end());
5103 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5104
5105 D->addAttr(::new (S.Context)
5106 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5107 Attr.getAttributeSpellingListIndex()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005108}
5109
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005110static void handleARMInterruptAttr(Sema &S, Decl *D,
5111 const AttributeList &Attr) {
5112 // Check the attribute arguments.
5113 if (Attr.getNumArgs() > 1) {
5114 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5115 << Attr.getName() << 1;
5116 return;
5117 }
5118
5119 StringRef Str;
5120 SourceLocation ArgLoc;
5121
5122 if (Attr.getNumArgs() == 0)
5123 Str = "";
5124 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5125 return;
5126
5127 ARMInterruptAttr::InterruptType Kind;
5128 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5129 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5130 << Attr.getName() << Str << ArgLoc;
5131 return;
5132 }
5133
5134 unsigned Index = Attr.getAttributeSpellingListIndex();
5135 D->addAttr(::new (S.Context)
5136 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5137}
5138
5139static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5140 const AttributeList &Attr) {
5141 if (!checkAttributeNumArgs(S, Attr, 1))
5142 return;
5143
5144 if (!Attr.isArgExpr(0)) {
5145 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5146 << AANT_ArgumentIntegerConstant;
5147 return;
5148 }
5149
5150 // FIXME: Check for decl - it should be void ()(void).
5151
5152 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5153 llvm::APSInt NumParams(32);
5154 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5155 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5156 << Attr.getName() << AANT_ArgumentIntegerConstant
5157 << NumParamsExpr->getSourceRange();
5158 return;
5159 }
5160
5161 unsigned Num = NumParams.getLimitedValue(255);
5162 if ((Num & 1) || Num > 30) {
5163 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5164 << Attr.getName() << (int)NumParams.getSExtValue()
5165 << NumParamsExpr->getSourceRange();
5166 return;
5167 }
5168
Aaron Ballman36a53502014-01-16 13:03:14 +00005169 D->addAttr(::new (S.Context)
5170 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5171 Attr.getAttributeSpellingListIndex()));
5172 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005173}
5174
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005175static void handleMipsInterruptAttr(Sema &S, Decl *D,
5176 const AttributeList &Attr) {
5177 // Only one optional argument permitted.
5178 if (Attr.getNumArgs() > 1) {
5179 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5180 << Attr.getName() << 1;
5181 return;
5182 }
5183
5184 StringRef Str;
5185 SourceLocation ArgLoc;
5186
5187 if (Attr.getNumArgs() == 0)
5188 Str = "";
5189 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5190 return;
5191
5192 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5193 // a) Must be a function.
5194 // b) Must have no parameters.
5195 // c) Must have the 'void' return type.
5196 // d) Cannot have the 'mips16' attribute, as that instruction set
5197 // lacks the 'eret' instruction.
5198 // e) The attribute itself must either have no argument or one of the
5199 // valid interrupt types, see [MipsInterruptDocs].
5200
5201 if (!isFunctionOrMethod(D)) {
5202 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5203 << "'interrupt'" << ExpectedFunctionOrMethod;
5204 return;
5205 }
5206
5207 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5208 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5209 << 0;
5210 return;
5211 }
5212
5213 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5214 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5215 << 1;
5216 return;
5217 }
5218
5219 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5220 Attr.getName()))
5221 return;
5222
5223 MipsInterruptAttr::InterruptType Kind;
5224 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5225 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5226 << Attr.getName() << "'" + std::string(Str) + "'";
5227 return;
5228 }
5229
5230 D->addAttr(::new (S.Context) MipsInterruptAttr(
5231 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5232}
5233
Alexey Bataevd51e9932016-01-15 04:06:31 +00005234static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5235 const AttributeList &Attr) {
5236 // Semantic checks for a function with the 'interrupt' attribute.
5237 // a) Must be a function.
5238 // b) Must have the 'void' return type.
5239 // c) Must take 1 or 2 arguments.
5240 // d) The 1st argument must be a pointer.
5241 // e) The 2nd argument (if any) must be an unsigned integer.
5242 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5243 CXXMethodDecl::isStaticOverloadedOperator(
5244 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5245 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5246 << Attr.getName() << ExpectedFunctionWithProtoType;
5247 return;
5248 }
5249 // Interrupt handler must have void return type.
5250 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5251 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5252 diag::err_anyx86_interrupt_attribute)
5253 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5254 ? 0
5255 : 1)
5256 << 0;
5257 return;
5258 }
5259 // Interrupt handler must have 1 or 2 parameters.
5260 unsigned NumParams = getFunctionOrMethodNumParams(D);
5261 if (NumParams < 1 || NumParams > 2) {
5262 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5263 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5264 ? 0
5265 : 1)
5266 << 1;
5267 return;
5268 }
5269 // The first argument must be a pointer.
5270 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5271 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5272 diag::err_anyx86_interrupt_attribute)
5273 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5274 ? 0
5275 : 1)
5276 << 2;
5277 return;
5278 }
5279 // The second argument, if present, must be an unsigned integer.
5280 unsigned TypeSize =
5281 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5282 ? 64
5283 : 32;
5284 if (NumParams == 2 &&
5285 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5286 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5287 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5288 diag::err_anyx86_interrupt_attribute)
5289 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5290 ? 0
5291 : 1)
5292 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5293 return;
5294 }
5295 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5296 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5297 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5298}
5299
Dylan McKaye8232d72017-02-08 05:09:26 +00005300static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5301 if (!isFunctionOrMethod(D)) {
5302 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5303 << "'interrupt'" << ExpectedFunction;
5304 return;
5305 }
5306
5307 if (!checkAttributeNumArgs(S, Attr, 0))
5308 return;
5309
5310 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5311}
5312
5313static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5314 if (!isFunctionOrMethod(D)) {
5315 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5316 << "'signal'" << ExpectedFunction;
5317 return;
5318 }
5319
5320 if (!checkAttributeNumArgs(S, Attr, 0))
5321 return;
5322
5323 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5324}
5325
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005326static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5327 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00005328 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5329 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005330 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005331 break;
5332 case llvm::Triple::mipsel:
5333 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005334 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005335 break;
5336 case llvm::Triple::x86:
5337 case llvm::Triple::x86_64:
5338 handleAnyX86InterruptAttr(S, D, Attr);
5339 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005340 case llvm::Triple::avr:
5341 handleAVRInterruptAttr(S, D, Attr);
5342 break;
Alexey Bataevd51e9932016-01-15 04:06:31 +00005343 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005344 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005345 break;
5346 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005347}
5348
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005349static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5350 const AttributeList &Attr) {
5351 uint32_t Min = 0;
5352 Expr *MinExpr = Attr.getArgAsExpr(0);
5353 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005354 return;
5355
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005356 uint32_t Max = 0;
5357 Expr *MaxExpr = Attr.getArgAsExpr(1);
5358 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5359 return;
5360
5361 if (Min == 0 && Max != 0) {
5362 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5363 << Attr.getName() << 0;
5364 return;
5365 }
5366 if (Min > Max) {
5367 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5368 << Attr.getName() << 1;
5369 return;
5370 }
5371
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005372 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005373 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5374 Attr.getAttributeSpellingListIndex()));
5375}
5376
5377static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5378 const AttributeList &Attr) {
5379 uint32_t Min = 0;
5380 Expr *MinExpr = Attr.getArgAsExpr(0);
5381 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5382 return;
5383
5384 uint32_t Max = 0;
5385 if (Attr.getNumArgs() == 2) {
5386 Expr *MaxExpr = Attr.getArgAsExpr(1);
5387 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5388 return;
5389 }
5390
5391 if (Min == 0 && Max != 0) {
5392 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5393 << Attr.getName() << 0;
5394 return;
5395 }
5396 if (Max != 0 && Min > Max) {
5397 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5398 << Attr.getName() << 1;
5399 return;
5400 }
5401
5402 D->addAttr(::new (S.Context)
5403 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5404 Attr.getAttributeSpellingListIndex()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005405}
5406
5407static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5408 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005409 uint32_t NumSGPR = 0;
5410 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5411 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005412 return;
5413
5414 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005415 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5416 Attr.getAttributeSpellingListIndex()));
5417}
5418
5419static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5420 const AttributeList &Attr) {
5421 uint32_t NumVGPR = 0;
5422 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5423 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5424 return;
5425
5426 D->addAttr(::new (S.Context)
5427 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005428 Attr.getAttributeSpellingListIndex()));
5429}
5430
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005431static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5432 const AttributeList& Attr) {
5433 // If we try to apply it to a function pointer, don't warn, but don't
5434 // do anything, either. It doesn't matter anyway, because there's nothing
5435 // special about calling a force_align_arg_pointer function.
5436 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5437 if (VD && VD->getType()->isFunctionPointerType())
5438 return;
5439 // Also don't warn on function pointer typedefs.
5440 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5441 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5442 TD->getUnderlyingType()->isFunctionType()))
5443 return;
5444 // Attribute can only be applied to function types.
5445 if (!isa<FunctionDecl>(D)) {
5446 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5447 << Attr.getName() << /* function */0;
5448 return;
5449 }
5450
Aaron Ballman36a53502014-01-16 13:03:14 +00005451 D->addAttr(::new (S.Context)
5452 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5453 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005454}
5455
David Majnemercd3ebfe2016-05-23 17:16:12 +00005456static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5457 uint32_t Version;
5458 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5459 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5460 return;
5461
5462 // TODO: Investigate what happens with the next major version of MSVC.
5463 if (Version != LangOptions::MSVC2015) {
5464 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5465 << Attr.getName() << Version << VersionExpr->getSourceRange();
5466 return;
5467 }
5468
5469 D->addAttr(::new (S.Context)
5470 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5471 Attr.getAttributeSpellingListIndex()));
5472}
5473
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005474DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5475 unsigned AttrSpellingListIndex) {
5476 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005477 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005478 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005479 }
5480
5481 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005482 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005483
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005484 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005485}
5486
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005487DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5488 unsigned AttrSpellingListIndex) {
5489 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005490 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005491 D->dropAttr<DLLImportAttr>();
5492 }
5493
5494 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005495 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005496
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005497 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005498}
5499
Hans Wennborge82f19c2014-06-24 23:57:05 +00005500static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005501 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5502 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5503 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5504 << A.getName();
5505 return;
5506 }
5507
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005508 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5509 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5510 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5511 // MinGW doesn't allow dllimport on inline functions.
5512 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5513 << A.getName();
5514 return;
5515 }
5516 }
5517
Hans Wennborg5869ec42015-09-15 21:05:30 +00005518 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5519 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5520 MD->getParent()->isLambda()) {
5521 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5522 return;
5523 }
5524 }
5525
Hans Wennborge82f19c2014-06-24 23:57:05 +00005526 unsigned Index = A.getAttributeSpellingListIndex();
5527 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5528 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5529 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005530 if (NewAttr)
5531 D->addAttr(NewAttr);
5532}
5533
David Majnemer2c4e00a2014-01-29 22:07:36 +00005534MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005535Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005536 unsigned AttrSpellingListIndex,
5537 MSInheritanceAttr::Spelling SemanticSpelling) {
5538 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5539 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005540 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005541 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5542 << 1 /*previous declaration*/;
5543 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5544 D->dropAttr<MSInheritanceAttr>();
5545 }
5546
5547 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5548 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005549 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5550 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005551 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005552 }
5553 } else {
5554 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5555 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5556 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005557 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005558 }
5559 if (RD->getDescribedClassTemplate()) {
5560 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5561 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005562 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005563 }
5564 }
5565
5566 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005567 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005568}
5569
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005570static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5571 // The capability attributes take a single string parameter for the name of
5572 // the capability they represent. The lockable attribute does not take any
5573 // parameters. However, semantically, both attributes represent the same
5574 // concept, and so they use the same semantic attribute. Eventually, the
5575 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005576 //
Alp Toker958027b2014-07-14 19:42:55 +00005577 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005578 // literal will be considered a "mutex."
5579 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005580 SourceLocation LiteralLoc;
5581 if (Attr.getKind() == AttributeList::AT_Capability &&
5582 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5583 return;
5584
Aaron Ballman6c810072014-03-05 21:47:13 +00005585 // Currently, there are only two names allowed for a capability: role and
5586 // mutex (case insensitive). Diagnose other capability names.
5587 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5588 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5589
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005590 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5591 Attr.getAttributeSpellingListIndex()));
5592}
5593
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005594static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5595 const AttributeList &Attr) {
5596 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5597 Attr.getArgAsExpr(0),
5598 Attr.getAttributeSpellingListIndex()));
5599}
5600
5601static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5602 const AttributeList &Attr) {
5603 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005604 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005605 return;
5606
5607 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5608 S.Context,
5609 Args.data(), Args.size(),
5610 Attr.getAttributeSpellingListIndex()));
5611}
5612
5613static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5614 const AttributeList &Attr) {
5615 SmallVector<Expr*, 2> Args;
5616 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5617 return;
5618
5619 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5620 S.Context,
5621 Attr.getArgAsExpr(0),
5622 Args.data(),
5623 Args.size(),
5624 Attr.getAttributeSpellingListIndex()));
5625}
5626
5627static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5628 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005629 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005630 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005631 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005632
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005633 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5634 Attr.getRange(), S.Context, Args.data(), Args.size(),
5635 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005636}
5637
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005638static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5639 const AttributeList &Attr) {
5640 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5641 return;
5642
5643 // check that all arguments are lockable objects
5644 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005645 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005646 if (Args.empty())
5647 return;
5648
5649 RequiresCapabilityAttr *RCA = ::new (S.Context)
5650 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5651 Args.size(), Attr.getAttributeSpellingListIndex());
5652
5653 D->addAttr(RCA);
5654}
5655
Aaron Ballman43f40102014-11-14 22:34:56 +00005656static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5657 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5658 if (NSD->isAnonymousNamespace()) {
5659 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5660 // Do not want to attach the attribute to the namespace because that will
5661 // cause confusing diagnostic reports for uses of declarations within the
5662 // namespace.
5663 return;
5664 }
5665 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005666
Manman Renc7890fe2016-03-16 18:50:49 +00005667 // Handle the cases where the attribute has a text message.
5668 StringRef Str, Replacement;
5669 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5670 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5671 return;
5672
5673 // Only support a single optional message for Declspec and CXX11.
5674 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5675 checkAttributeAtMostNumArgs(S, Attr, 1);
5676 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5677 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5678 return;
5679
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005680 if (!S.getLangOpts().CPlusPlus14)
5681 if (Attr.isCXX11Attribute() &&
5682 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005683 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005684
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005685 D->addAttr(::new (S.Context)
5686 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5687 Attr.getAttributeSpellingListIndex()));
5688}
5689
5690static bool isGlobalVar(const Decl *D) {
5691 if (const auto *S = dyn_cast<VarDecl>(D))
5692 return S->hasGlobalStorage();
5693 return false;
Aaron Ballman43f40102014-11-14 22:34:56 +00005694}
5695
Peter Collingbourne915df992015-05-15 18:33:32 +00005696static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5697 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5698 return;
5699
Benjamin Kramer1b582012016-02-13 18:11:49 +00005700 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005701
5702 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5703 StringRef SanitizerName;
5704 SourceLocation LiteralLoc;
5705
5706 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5707 return;
5708
5709 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5710 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005711 else if (isGlobalVar(D) && SanitizerName != "address")
5712 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5713 << Attr.getName() << ExpectedFunctionOrMethod;
Peter Collingbourne915df992015-05-15 18:33:32 +00005714 Sanitizers.push_back(SanitizerName);
5715 }
5716
5717 D->addAttr(::new (S.Context) NoSanitizeAttr(
5718 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5719 Attr.getAttributeSpellingListIndex()));
5720}
5721
5722static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5723 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005724 StringRef AttrName = Attr.getName()->getName();
5725 normalizeName(AttrName);
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005726 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5727 .Case("no_address_safety_analysis", "address")
5728 .Case("no_sanitize_address", "address")
5729 .Case("no_sanitize_thread", "thread")
5730 .Case("no_sanitize_memory", "memory");
5731 if (isGlobalVar(D) && SanitizerName != "address")
5732 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5733 << Attr.getName() << ExpectedFunction;
Peter Collingbourne915df992015-05-15 18:33:32 +00005734 D->addAttr(::new (S.Context)
5735 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5736 Attr.getAttributeSpellingListIndex()));
5737}
5738
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005739static void handleInternalLinkageAttr(Sema &S, Decl *D,
5740 const AttributeList &Attr) {
5741 if (InternalLinkageAttr *Internal =
5742 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5743 Attr.getAttributeSpellingListIndex()))
5744 D->addAttr(Internal);
5745}
5746
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005747static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5748 if (S.LangOpts.OpenCLVersion != 200)
5749 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5750 << Attr.getName() << "2.0" << 0;
5751 else
5752 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5753 << Attr.getName() << "2.0";
5754}
5755
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005756/// Handles semantic checking for features that are common to all attributes,
5757/// such as checking whether a parameter was properly specified, or the correct
5758/// number of arguments were passed, etc.
5759static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5760 const AttributeList &Attr) {
5761 // Several attributes carry different semantics than the parsing requires, so
Alex Lorenz24952fb2017-04-19 15:52:11 +00005762 // those are opted out of the common argument checks.
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005763 //
5764 // We also bail on unknown and ignored attributes because those are handled
5765 // as part of the target-specific handling logic.
Alex Lorenz24952fb2017-04-19 15:52:11 +00005766 if (Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005767 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005768 // Check whether the attribute requires specific language extensions to be
5769 // enabled.
5770 if (!Attr.diagnoseLangOpts(S))
5771 return true;
Alex Lorenz24952fb2017-04-19 15:52:11 +00005772 // Check whether the attribute appertains to the given subject.
5773 if (!Attr.diagnoseAppertainsTo(S, D))
5774 return true;
5775 if (Attr.hasCustomParsing())
5776 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005777
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005778 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5779 // If there are no optional arguments, then checking for the argument count
5780 // is trivial.
5781 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5782 return true;
5783 } else {
5784 // There are optional arguments, so checking is slightly more involved.
5785 if (Attr.getMinArgs() &&
5786 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5787 return true;
5788 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5789 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5790 return true;
5791 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005792
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005793 return false;
5794}
5795
Xiuli Pan11e13f62016-02-26 03:13:03 +00005796static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5797 const AttributeList &Attr) {
5798 if (D->isInvalidDecl())
5799 return;
5800
5801 // Check if there is only one access qualifier.
5802 if (D->hasAttr<OpenCLAccessAttr>()) {
5803 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5804 << D->getSourceRange();
5805 D->setInvalidDecl(true);
5806 return;
5807 }
5808
5809 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5810 // image object can be read and written.
5811 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5812 // object. Using the read_write (or __read_write) qualifier with the pipe
5813 // qualifier is a compilation error.
5814 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5815 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5816 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5817 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5818 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5819 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5820 D->setInvalidDecl(true);
5821 return;
5822 }
5823 }
5824 }
5825
5826 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5827 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5828}
5829
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005830//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005831// Top Level Sema Entry Points
5832//===----------------------------------------------------------------------===//
5833
Richard Smithf8a75c32013-08-29 00:47:48 +00005834/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5835/// the attribute applies to decls. If the attribute is a type attribute, just
5836/// silently ignore it if a GNU attribute.
5837static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5838 const AttributeList &Attr,
5839 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005840 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005841 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005842
Richard Smithf8a75c32013-08-29 00:47:48 +00005843 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5844 // instead.
5845 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5846 return;
5847
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005848 // Unknown attributes are automatically warned on. Target-specific attributes
5849 // which do not apply to the current target architecture are treated as
5850 // though they were unknown attributes.
5851 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005852 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005853 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5854 ? diag::warn_unhandled_ms_attribute_ignored
5855 : diag::warn_unknown_attribute_ignored)
5856 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005857 return;
5858 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005859
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005860 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5861 return;
5862
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005863 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005864 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005865 if (!Attr.isStmtAttr()) {
5866 // Type attributes are handled elsewhere; silently move on.
5867 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5868 break;
5869 }
5870 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5871 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005872 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005873 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005874 handleInterruptAttr(S, D, Attr);
5875 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005876 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005877 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5878 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005879 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005880 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00005881 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005882 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005883 case AttributeList::AT_Mips16:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005884 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5885 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005886 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005887 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005888 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5889 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005890 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5891 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5892 break;
5893 case AttributeList::AT_AMDGPUWavesPerEU:
5894 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005895 break;
5896 case AttributeList::AT_AMDGPUNumSGPR:
5897 handleAMDGPUNumSGPRAttr(S, D, Attr);
5898 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005899 case AttributeList::AT_AMDGPUNumVGPR:
5900 handleAMDGPUNumVGPRAttr(S, D, Attr);
5901 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005902 case AttributeList::AT_AVRSignal:
5903 handleAVRSignalAttr(S, D, Attr);
5904 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00005905 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005906 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5907 break;
5908 case AttributeList::AT_IBOutlet:
5909 handleIBOutlet(S, D, Attr);
5910 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005911 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005912 handleIBOutletCollection(S, D, Attr);
5913 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00005914 case AttributeList::AT_IFunc:
5915 handleIFuncAttr(S, D, Attr);
5916 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005917 case AttributeList::AT_Alias:
5918 handleAliasAttr(S, D, Attr);
5919 break;
5920 case AttributeList::AT_Aligned:
5921 handleAlignedAttr(S, D, Attr);
5922 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00005923 case AttributeList::AT_AlignValue:
5924 handleAlignValueAttr(S, D, Attr);
5925 break;
George Burgess IVe3763372016-12-22 02:50:20 +00005926 case AttributeList::AT_AllocSize:
5927 handleAllocSizeAttr(S, D, Attr);
5928 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005929 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00005930 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005931 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005932 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005933 handleAnalyzerNoReturnAttr(S, D, Attr);
5934 break;
5935 case AttributeList::AT_TLSModel:
5936 handleTLSModelAttr(S, D, Attr);
5937 break;
5938 case AttributeList::AT_Annotate:
5939 handleAnnotateAttr(S, D, Attr);
5940 break;
5941 case AttributeList::AT_Availability:
5942 handleAvailabilityAttr(S, D, Attr);
5943 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005944 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00005945 handleDependencyAttr(S, scope, D, Attr);
5946 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005947 case AttributeList::AT_Common:
5948 handleCommonAttr(S, D, Attr);
5949 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005950 case AttributeList::AT_CUDAConstant:
Justin Lebare71b2fa2016-09-30 23:57:34 +00005951 handleConstantAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005952 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005953 case AttributeList::AT_PassObjectSize:
5954 handlePassObjectSizeAttr(S, D, Attr);
5955 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005956 case AttributeList::AT_Constructor:
5957 handleConstructorAttr(S, D, Attr);
5958 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005959 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005960 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5961 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005962 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00005963 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005964 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005965 case AttributeList::AT_Destructor:
5966 handleDestructorAttr(S, D, Attr);
5967 break;
5968 case AttributeList::AT_EnableIf:
5969 handleEnableIfAttr(S, D, Attr);
5970 break;
George Burgess IV177399e2017-01-09 04:12:14 +00005971 case AttributeList::AT_DiagnoseIf:
5972 handleDiagnoseIfAttr(S, D, Attr);
5973 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005974 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005975 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005976 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +00005977 case AttributeList::AT_ExternalSourceSymbol:
5978 handleExternalSourceSymbolAttr(S, D, Attr);
5979 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00005980 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00005981 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00005982 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00005983 case AttributeList::AT_OptimizeNone:
5984 handleOptimizeNoneAttr(S, D, Attr);
5985 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00005986 case AttributeList::AT_FlagEnum:
5987 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5988 break;
Akira Hatanaka3c268af2017-03-21 02:23:00 +00005989 case AttributeList::AT_EnumExtensibility:
5990 handleEnumExtensibilityAttr(S, D, Attr);
5991 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00005992 case AttributeList::AT_Flatten:
5993 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5994 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005995 case AttributeList::AT_Format:
5996 handleFormatAttr(S, D, Attr);
5997 break;
5998 case AttributeList::AT_FormatArg:
5999 handleFormatArgAttr(S, D, Attr);
6000 break;
6001 case AttributeList::AT_CUDAGlobal:
6002 handleGlobalAttr(S, D, Attr);
6003 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00006004 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006005 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6006 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006007 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006008 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006009 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6010 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006011 break;
6012 case AttributeList::AT_GNUInline:
6013 handleGNUInlineAttr(S, D, Attr);
6014 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006015 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006016 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00006017 break;
David Majnemer631a90b2015-02-04 07:23:21 +00006018 case AttributeList::AT_Restrict:
6019 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006020 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006021 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006022 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6023 break;
6024 case AttributeList::AT_Mode:
6025 handleModeAttr(S, D, Attr);
6026 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00006027 case AttributeList::AT_NoAlias:
6028 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6029 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006030 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006031 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6032 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00006033 case AttributeList::AT_NoSplitStack:
6034 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6035 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00006036 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006037 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6038 handleNonNullAttrParameter(S, PVD, Attr);
6039 else
6040 handleNonNullAttr(S, D, Attr);
6041 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00006042 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006043 handleReturnsNonNullAttr(S, D, Attr);
6044 break;
Hal Finkelee90a222014-09-26 05:04:30 +00006045 case AttributeList::AT_AssumeAligned:
6046 handleAssumeAlignedAttr(S, D, Attr);
6047 break;
Erich Keane623efd82017-03-30 21:48:55 +00006048 case AttributeList::AT_AllocAlign:
6049 handleAllocAlignAttr(S, D, Attr);
6050 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006051 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006052 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6053 break;
6054 case AttributeList::AT_Ownership:
6055 handleOwnershipAttr(S, D, Attr);
6056 break;
6057 case AttributeList::AT_Cold:
6058 handleColdAttr(S, D, Attr);
6059 break;
6060 case AttributeList::AT_Hot:
6061 handleHotAttr(S, D, Attr);
6062 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006063 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00006064 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006065 break;
6066 case AttributeList::AT_NoReturn:
6067 handleNoReturnAttr(S, D, Attr);
6068 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006069 case AttributeList::AT_NoThrow:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006070 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6071 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006072 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00006073 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006074 break;
6075 case AttributeList::AT_VecReturn:
6076 handleVecReturnAttr(S, D, Attr);
6077 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006078 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006079 handleObjCOwnershipAttr(S, D, Attr);
6080 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006081 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006082 handleObjCPreciseLifetimeAttr(S, D, Attr);
6083 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006084 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006085 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6086 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00006087 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006088 handleObjCRequiresSuperAttr(S, D, Attr);
6089 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00006090 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006091 handleObjCBridgeAttr(S, scope, D, Attr);
6092 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00006093 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006094 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6095 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00006096 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006097 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6098 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00006099 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006100 handleObjCDesignatedInitializer(S, D, Attr);
6101 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006102 case AttributeList::AT_ObjCRuntimeName:
6103 handleObjCRuntimeName(S, D, Attr);
6104 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006105 case AttributeList::AT_ObjCRuntimeVisible:
6106 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6107 break;
Alex Denisovfde64952015-06-26 05:28:36 +00006108 case AttributeList::AT_ObjCBoxable:
6109 handleObjCBoxable(S, D, Attr);
6110 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006111 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006112 handleCFAuditedTransferAttr(S, D, Attr);
6113 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006114 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006115 handleCFUnknownTransferAttr(S, D, Attr);
6116 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006117 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006118 case AttributeList::AT_NSConsumed:
6119 handleNSConsumedAttr(S, D, Attr);
6120 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006121 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006122 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6123 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006124 case AttributeList::AT_NSReturnsAutoreleased:
6125 case AttributeList::AT_NSReturnsNotRetained:
6126 case AttributeList::AT_CFReturnsNotRetained:
6127 case AttributeList::AT_NSReturnsRetained:
6128 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006129 handleNSReturnsRetainedAttr(S, D, Attr);
6130 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00006131 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006132 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6133 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006134 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006135 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6136 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00006137 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006138 handleVecTypeHint(S, D, Attr);
6139 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00006140 case AttributeList::AT_RequireConstantInit:
6141 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6142 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006143 case AttributeList::AT_InitPriority:
6144 handleInitPriorityAttr(S, D, Attr);
6145 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006146 case AttributeList::AT_Packed:
6147 handlePackedAttr(S, D, Attr);
6148 break;
6149 case AttributeList::AT_Section:
6150 handleSectionAttr(S, D, Attr);
6151 break;
Eric Christopher11acf732015-06-12 01:35:52 +00006152 case AttributeList::AT_Target:
6153 handleTargetAttr(S, D, Attr);
6154 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006155 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00006156 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006157 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006158 case AttributeList::AT_ArcWeakrefUnavailable:
6159 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6160 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006161 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006162 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6163 break;
Alex Lorenza8c44ba2016-10-28 10:25:10 +00006164 case AttributeList::AT_ObjCSubclassingRestricted:
6165 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6166 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00006167 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00006168 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00006169 break;
6170 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006171 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6172 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00006173 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00006174 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006175 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006176 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006177 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6178 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00006179 case AttributeList::AT_NotTailCalled:
6180 handleNotTailCalledAttr(S, D, Attr);
6181 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00006182 case AttributeList::AT_DisableTailCalls:
6183 handleDisableTailCallsAttr(S, D, Attr);
6184 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006185 case AttributeList::AT_Used:
6186 handleUsedAttr(S, D, Attr);
6187 break;
John McCalld041a9b2013-02-20 01:54:26 +00006188 case AttributeList::AT_Visibility:
6189 handleVisibilityAttr(S, D, Attr, false);
6190 break;
6191 case AttributeList::AT_TypeVisibility:
6192 handleVisibilityAttr(S, D, Attr, true);
6193 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00006194 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006195 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6196 break;
6197 case AttributeList::AT_WarnUnusedResult:
6198 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00006199 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00006200 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006201 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6202 break;
6203 case AttributeList::AT_WeakRef:
6204 handleWeakRefAttr(S, D, Attr);
6205 break;
6206 case AttributeList::AT_WeakImport:
6207 handleWeakImportAttr(S, D, Attr);
6208 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006209 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006210 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006211 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006212 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006213 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6214 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006215 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006216 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00006217 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006218 case AttributeList::AT_ObjCNSObject:
6219 handleObjCNSObject(S, D, Attr);
6220 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00006221 case AttributeList::AT_ObjCIndependentClass:
6222 handleObjCIndependentClass(S, D, Attr);
6223 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006224 case AttributeList::AT_Blocks:
6225 handleBlocksAttr(S, D, Attr);
6226 break;
6227 case AttributeList::AT_Sentinel:
6228 handleSentinelAttr(S, D, Attr);
6229 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006230 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006231 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6232 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006233 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006234 handleSimpleAttribute<PureAttr>(S, D, Attr);
6235 break;
6236 case AttributeList::AT_Cleanup:
6237 handleCleanupAttr(S, D, Attr);
6238 break;
6239 case AttributeList::AT_NoDebug:
6240 handleNoDebugAttr(S, D, Attr);
6241 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00006242 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006243 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6244 break;
Yaxun Liu7d07ae72016-11-01 18:45:32 +00006245 case AttributeList::AT_Convergent:
6246 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6247 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006248 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006249 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6250 break;
6251 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6252 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6253 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006254 case AttributeList::AT_StdCall:
6255 case AttributeList::AT_CDecl:
6256 case AttributeList::AT_FastCall:
6257 case AttributeList::AT_ThisCall:
6258 case AttributeList::AT_Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00006259 case AttributeList::AT_RegCall:
John McCall477f2bb2016-03-03 06:39:32 +00006260 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00006261 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00006262 case AttributeList::AT_MSABI:
6263 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006264 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00006265 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00006266 case AttributeList::AT_PreserveMost:
6267 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006268 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00006269 break;
Matthias Gehre01a63382017-03-27 19:45:24 +00006270 case AttributeList::AT_Suppress:
6271 handleSuppressAttr(S, D, Attr);
6272 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006273 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006274 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6275 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00006276 case AttributeList::AT_OpenCLAccess:
6277 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006278 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00006279 case AttributeList::AT_OpenCLNoSVM:
6280 handleOpenCLNoSVMAttr(S, D, Attr);
6281 break;
John McCall477f2bb2016-03-03 06:39:32 +00006282 case AttributeList::AT_SwiftContext:
6283 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6284 break;
6285 case AttributeList::AT_SwiftErrorResult:
6286 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6287 break;
6288 case AttributeList::AT_SwiftIndirectResult:
6289 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6290 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00006291 case AttributeList::AT_InternalLinkage:
6292 handleInternalLinkageAttr(S, D, Attr);
6293 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00006294 case AttributeList::AT_LTOVisibilityPublic:
6295 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6296 break;
John McCall8d32c052012-05-22 21:28:12 +00006297
6298 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00006299 case AttributeList::AT_EmptyBases:
6300 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6301 break;
6302 case AttributeList::AT_LayoutVersion:
6303 handleLayoutVersion(S, D, Attr);
6304 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006305 case AttributeList::AT_MSNoVTable:
6306 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00006307 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006308 case AttributeList::AT_MSStruct:
6309 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00006310 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006311 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006312 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00006313 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00006314 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006315 handleMSInheritanceAttr(S, D, Attr);
6316 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00006317 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006318 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6319 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00006320 case AttributeList::AT_Thread:
6321 handleDeclspecThreadAttr(S, D, Attr);
6322 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00006323
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00006324 case AttributeList::AT_AbiTag:
6325 handleAbiTagAttr(S, D, Attr);
6326 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006327
6328 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00006329 case AttributeList::AT_AssertExclusiveLock:
6330 handleAssertExclusiveLockAttr(S, D, Attr);
6331 break;
6332 case AttributeList::AT_AssertSharedLock:
6333 handleAssertSharedLockAttr(S, D, Attr);
6334 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006335 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006336 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6337 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006338 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00006339 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006340 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006341 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006342 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6343 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00006344 case AttributeList::AT_NoSanitize:
6345 handleNoSanitizeAttr(S, D, Attr);
6346 break;
6347 case AttributeList::AT_NoSanitizeSpecific:
6348 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00006349 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006350 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006351 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00006352 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006353 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006354 handleGuardedByAttr(S, D, Attr);
6355 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006356 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00006357 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006358 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006359 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006360 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006361 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006362 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006363 handleLockReturnedAttr(S, D, Attr);
6364 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006365 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006366 handleLocksExcludedAttr(S, D, Attr);
6367 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006368 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006369 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006370 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006371 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00006372 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006373 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006374 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00006375 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006376 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006377
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006378 // Capability analysis attributes.
6379 case AttributeList::AT_Capability:
6380 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006381 handleCapabilityAttr(S, D, Attr);
6382 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006383 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006384 handleRequiresCapabilityAttr(S, D, Attr);
6385 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006386
6387 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006388 handleAssertCapabilityAttr(S, D, Attr);
6389 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006390 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006391 handleAcquireCapabilityAttr(S, D, Attr);
6392 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006393 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006394 handleReleaseCapabilityAttr(S, D, Attr);
6395 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006396 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006397 handleTryAcquireCapabilityAttr(S, D, Attr);
6398 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006399
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00006400 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00006401 case AttributeList::AT_Consumable:
6402 handleConsumableAttr(S, D, Attr);
6403 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006404 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006405 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6406 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006407 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006408 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6409 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00006410 case AttributeList::AT_CallableWhen:
6411 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006412 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00006413 case AttributeList::AT_ParamTypestate:
6414 handleParamTypestateAttr(S, D, Attr);
6415 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00006416 case AttributeList::AT_ReturnTypestate:
6417 handleReturnTypestateAttr(S, D, Attr);
6418 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006419 case AttributeList::AT_SetTypestate:
6420 handleSetTypestateAttr(S, D, Attr);
6421 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00006422 case AttributeList::AT_TestTypestate:
6423 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006424 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006425
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00006426 // Type safety attributes.
6427 case AttributeList::AT_ArgumentWithTypeTag:
6428 handleArgumentWithTypeTagAttr(S, D, Attr);
6429 break;
6430 case AttributeList::AT_TypeTagForDatatype:
6431 handleTypeTagForDatatypeAttr(S, D, Attr);
6432 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006433 case AttributeList::AT_RenderScriptKernel:
6434 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006435 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006436 // XRay attributes.
6437 case AttributeList::AT_XRayInstrument:
6438 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6439 break;
Dean Michael Berris418da3f2017-03-06 07:08:21 +00006440 case AttributeList::AT_XRayLogArgs:
6441 handleXRayLogArgsAttr(S, D, Attr);
6442 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006443 }
6444}
6445
6446/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6447/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006448void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006449 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006450 bool IncludeCXX11Attributes) {
6451 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006452 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006453
Joey Gouly2cd9db12013-12-13 16:15:28 +00006454 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006455 // GCC accepts
6456 // static int a9 __attribute__((weakref));
6457 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006458 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006459 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6460 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006461 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006462 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006463 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006464
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006465 // FIXME: We should be able to handle this in TableGen as well. It would be
6466 // good to have a way to specify "these attributes must appear as a group",
6467 // for these. Additionally, it would be good to have a way to specify "these
6468 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006469 if (!D->hasAttr<OpenCLKernelAttr>()) {
6470 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006471 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006472 // FIXME: This emits a different error message than
6473 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006474 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006475 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006476 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006477 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006478 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006479 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006480 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006481 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006482 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6483 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6484 << A << ExpectedKernelFunction;
6485 D->setInvalidDecl();
6486 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006487 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6488 << A << ExpectedKernelFunction;
6489 D->setInvalidDecl();
6490 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6491 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6492 << A << ExpectedKernelFunction;
6493 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006494 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6495 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6496 << A << ExpectedKernelFunction;
6497 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006498 }
6499 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006500}
6501
Erich Keane2fe684b2017-02-28 20:44:39 +00006502// Helper for delayed proccessing TransparentUnion attribute.
6503void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6504 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6505 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6506 handleTransparentUnionAttr(*this, D, *Attr);
6507 break;
6508 }
6509}
6510
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006511// Annotation attributes are the only attributes allowed after an access
6512// specifier.
6513bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6514 const AttributeList *AttrList) {
6515 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006516 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006517 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006518 } else {
6519 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6520 return true;
6521 }
6522 }
6523
6524 return false;
6525}
6526
John McCall42856de2011-10-01 05:17:03 +00006527/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6528/// contains any decl attributes that we should warn about.
6529static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6530 for ( ; A; A = A->getNext()) {
6531 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00006532 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006533 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6534
6535 if (A->getKind() == AttributeList::UnknownAttribute) {
6536 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6537 << A->getName() << A->getRange();
6538 } else {
6539 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6540 << A->getName() << A->getRange();
6541 }
6542 }
6543}
6544
6545/// checkUnusedDeclAttributes - Given a declarator which is not being
6546/// used to build a declaration, complain about any decl attributes
6547/// which might be lying around on it.
6548void Sema::checkUnusedDeclAttributes(Declarator &D) {
6549 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6550 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6551 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6552 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6553}
6554
Ryan Flynn7d470f32009-07-30 03:15:39 +00006555/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006556/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006557NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6558 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006559 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006560 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006561 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006562 FunctionDecl *NewFD;
6563 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006564 // FIXME: Mangling?
6565 // FIXME: Is the qualifier info correct?
6566 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006567 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6568 Loc, Loc, DeclarationName(II),
6569 FD->getType(), FD->getTypeSourceInfo(),
6570 SC_None, false/*isInlineSpecified*/,
6571 FD->hasPrototype(),
6572 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006573 NewD = NewFD;
6574
6575 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006576 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006577
6578 // Fake up parameter variables; they are declared as if this were
6579 // a typedef.
6580 QualType FDTy = FD->getType();
6581 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6582 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006583 for (const auto &AI : FT->param_types()) {
6584 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006585 Param->setScopeInfo(0, Params.size());
6586 Params.push_back(Param);
6587 }
David Blaikie9c70e042011-09-21 18:16:56 +00006588 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006589 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006590 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6591 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006592 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006593 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006594 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006595 if (VD->getQualifier()) {
6596 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006597 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006598 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006599 }
6600 return NewD;
6601}
6602
James Dennett634962f2012-06-14 21:40:34 +00006603/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006604/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006605void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006606 if (W.getUsed()) return; // only do this once
6607 W.setUsed(true);
6608 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6609 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006610 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006611 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6612 W.getLocation()));
6613 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006614 WeakTopLevelDecl.push_back(NewD);
6615 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6616 // to insert Decl at TU scope, sorry.
6617 DeclContext *SavedContext = CurContext;
6618 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006619 NewD->setDeclContext(CurContext);
6620 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006621 PushOnScopeChains(NewD, S);
6622 CurContext = SavedContext;
6623 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006624 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006625 }
6626}
6627
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006628void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6629 // It's valid to "forward-declare" #pragma weak, in which case we
6630 // have to do this.
6631 LoadExternalWeakUndeclaredIdentifiers();
6632 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006633 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006634 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6635 if (VD->isExternC())
6636 ND = VD;
6637 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6638 if (FD->isExternC())
6639 ND = FD;
6640 if (ND) {
6641 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006642 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006643 if (I != WeakUndeclaredIdentifiers.end()) {
6644 WeakInfo W = I->second;
6645 DeclApplyPragmaWeak(S, ND, W);
6646 WeakUndeclaredIdentifiers[Id] = W;
6647 }
6648 }
6649 }
6650 }
6651}
6652
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006653/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6654/// it, apply them to D. This is a bit tricky because PD can have attributes
6655/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006656void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006657 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006658 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006659 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006660
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006661 // Walk the declarator structure, applying decl attributes that were in a type
6662 // position to the decl itself. This handles cases like:
6663 // int *__attr__(x)** D;
6664 // when X is a decl attribute.
6665 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6666 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006667 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006668
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006669 // Finally, apply any attributes on the decl itself.
6670 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006671 ProcessDeclAttributeList(S, D, Attrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00006672
6673 // Apply additional attributes specified by '#pragma clang attribute'.
6674 AddPragmaAttributes(S, D);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006675}
John McCall28a6aea2009-11-04 02:18:39 +00006676
John McCall31168b02011-06-15 23:02:42 +00006677/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006678/// If so, it'll still be annotated with an attribute that makes it
6679/// illegal to actually use.
6680static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6681 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006682 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006683 // Private ivars are always okay. Unfortunately, people don't
6684 // always properly make their ivars private, even in system headers.
6685 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006686 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6687 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006688 return false;
6689
John McCallc6af8c62015-10-28 05:03:19 +00006690 // Silently accept unsupported uses of __weak in both user and system
6691 // declarations when it's been disabled, for ease of integration with
6692 // -fno-objc-arc files. We do have to take some care against attempts
6693 // to define such things; for now, we've only done that for ivars
6694 // and properties.
6695 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6696 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6697 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6698 reason = UnavailableAttr::IR_ForbiddenWeak;
6699 return true;
6700 }
John McCallb61e14e2015-10-27 04:54:50 +00006701 }
6702
John McCallc6af8c62015-10-28 05:03:19 +00006703 // Allow all sorts of things in system headers.
6704 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6705 // Currently, all the failures dealt with this way are due to ARC
6706 // restrictions.
6707 reason = UnavailableAttr::IR_ARCForbiddenType;
6708 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006709 }
6710
6711 return false;
John McCall31168b02011-06-15 23:02:42 +00006712}
6713
6714/// Handle a delayed forbidden-type diagnostic.
6715static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6716 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006717 auto reason = UnavailableAttr::IR_None;
6718 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6719 assert(reason && "didn't set reason?");
6720 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6721 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006722 return;
6723 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006724 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006725 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006726 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006727 // kind of forbidden type messages on unavailable functions.
6728 if (FD->hasAttr<UnavailableAttr>() &&
6729 diag.getForbiddenTypeDiagnostic() ==
6730 diag::err_arc_array_param_no_ownership) {
6731 diag.Triggered = true;
6732 return;
6733 }
6734 }
John McCall31168b02011-06-15 23:02:42 +00006735
6736 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6737 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6738 diag.Triggered = true;
6739}
6740
Manman Ren45b1ab12016-05-06 19:57:16 +00006741static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6742 const Decl *D) {
6743 // Check each AvailabilityAttr to find the one for this platform.
6744 for (const auto *A : D->attrs()) {
6745 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6746 // FIXME: this is copied from CheckAvailability. We should try to
6747 // de-duplicate.
6748
6749 // Check if this is an App Extension "platform", and if so chop off
6750 // the suffix for matching with the actual platform.
6751 StringRef ActualPlatform = Avail->getPlatform()->getName();
6752 StringRef RealizedPlatform = ActualPlatform;
6753 if (Context.getLangOpts().AppExt) {
6754 size_t suffix = RealizedPlatform.rfind("_app_extension");
6755 if (suffix != StringRef::npos)
6756 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6757 }
6758
6759 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6760
6761 // Match the platform name.
6762 if (RealizedPlatform == TargetPlatform)
6763 return Avail;
6764 }
6765 }
6766 return nullptr;
6767}
6768
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006769/// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6770/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6771/// in a deprecated context, but not the other way around.
6772static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6773 VersionTuple DeclVersion,
6774 Decl *Ctx) {
6775 assert(K != AR_Available && "Expected an unavailable declaration here!");
6776
6777 // Checks if we should emit the availability diagnostic in the context of C.
6778 auto CheckContext = [&](const Decl *C) {
6779 if (K == AR_NotYetIntroduced) {
6780 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6781 if (AA->getIntroduced() >= DeclVersion)
6782 return true;
6783 } else if (K == AR_Deprecated)
6784 if (C->isDeprecated())
6785 return true;
6786
6787 if (C->isUnavailable())
6788 return true;
6789 return false;
6790 };
6791
6792 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6793 // on nested declarations in an @interface having the availability of the
6794 // interface when they really shouldn't: they are members of the enclosing
6795 // context, and can referenced from there.
6796 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6797 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6798 if (CheckContext(OrigCtx))
6799 return false;
6800
6801 // An implementation implicitly has the availability of the interface.
6802 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6803 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6804 if (CheckContext(Interface))
6805 return false;
6806 }
6807 // A category implicitly has the availability of the interface.
6808 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6809 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6810 if (CheckContext(Interface))
6811 return false;
6812 }
6813
6814 do {
6815 if (CheckContext(Ctx))
6816 return false;
6817
6818 // An implementation implicitly has the availability of the interface.
6819 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6820 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6821 if (CheckContext(Interface))
6822 return false;
6823 }
6824 // A category implicitly has the availability of the interface.
6825 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6826 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6827 if (CheckContext(Interface))
6828 return false;
6829 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6830
6831 return true;
6832}
6833
Erik Pilkington796a3e22016-08-05 22:59:03 +00006834static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Aaron Ballmanfb237522014-10-15 15:37:51 +00006835 Decl *Ctx, const NamedDecl *D,
6836 StringRef Message, SourceLocation Loc,
6837 const ObjCInterfaceDecl *UnknownObjCClass,
6838 const ObjCPropertyDecl *ObjCProperty,
6839 bool ObjCPropertyAccess) {
6840 // Diagnostics for deprecated or unavailable.
6841 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00006842 unsigned diag_available_here = diag::note_availability_specified_here;
Erich Keanea32910d2017-03-23 18:51:54 +00006843 SourceLocation NoteLocation = D->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006844
6845 // Matches 'diag::note_property_attribute' options.
6846 unsigned property_note_select;
6847
6848 // Matches diag::note_availability_specified_here.
6849 unsigned available_here_select_kind;
6850
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006851 VersionTuple DeclVersion;
6852 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6853 DeclVersion = AA->getIntroduced();
6854
6855 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6856 return;
6857
Aaron Ballmanfb237522014-10-15 15:37:51 +00006858 switch (K) {
Erik Pilkington796a3e22016-08-05 22:59:03 +00006859 case AR_Deprecated:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006860 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6861 : diag::warn_property_method_deprecated;
6862 diag_message = diag::warn_deprecated_message;
6863 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6864 property_note_select = /* deprecated */ 0;
6865 available_here_select_kind = /* deprecated */ 2;
Erich Keanea32910d2017-03-23 18:51:54 +00006866 if (const auto *attr = D->getAttr<DeprecatedAttr>())
6867 NoteLocation = attr->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006868 break;
6869
Erik Pilkington796a3e22016-08-05 22:59:03 +00006870 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006871 diag = !ObjCPropertyAccess ? diag::err_unavailable
6872 : diag::err_property_method_unavailable;
6873 diag_message = diag::err_unavailable_message;
6874 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6875 property_note_select = /* unavailable */ 1;
6876 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00006877
John McCallc6af8c62015-10-28 05:03:19 +00006878 if (auto attr = D->getAttr<UnavailableAttr>()) {
6879 if (attr->isImplicit() && attr->getImplicitReason()) {
6880 // Most of these failures are due to extra restrictions in ARC;
6881 // reflect that in the primary diagnostic when applicable.
6882 auto flagARCError = [&] {
6883 if (S.getLangOpts().ObjCAutoRefCount &&
6884 S.getSourceManager().isInSystemHeader(D->getLocation()))
6885 diag = diag::err_unavailable_in_arc;
6886 };
6887
6888 switch (attr->getImplicitReason()) {
6889 case UnavailableAttr::IR_None: break;
6890
6891 case UnavailableAttr::IR_ARCForbiddenType:
6892 flagARCError();
6893 diag_available_here = diag::note_arc_forbidden_type;
6894 break;
6895
6896 case UnavailableAttr::IR_ForbiddenWeak:
6897 if (S.getLangOpts().ObjCWeakRuntime)
6898 diag_available_here = diag::note_arc_weak_disabled;
6899 else
6900 diag_available_here = diag::note_arc_weak_no_runtime;
6901 break;
6902
6903 case UnavailableAttr::IR_ARCForbiddenConversion:
6904 flagARCError();
6905 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6906 break;
6907
6908 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6909 flagARCError();
6910 diag_available_here = diag::note_arc_init_returns_unrelated;
6911 break;
6912
6913 case UnavailableAttr::IR_ARCFieldWithOwnership:
6914 flagARCError();
6915 diag_available_here = diag::note_arc_field_with_ownership;
6916 break;
6917 }
6918 }
John McCallb61e14e2015-10-27 04:54:50 +00006919 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00006920 break;
6921
Erik Pilkington796a3e22016-08-05 22:59:03 +00006922 case AR_NotYetIntroduced:
Nico Weber0055a192015-03-19 19:18:22 +00006923 diag = diag::warn_partial_availability;
6924 diag_message = diag::warn_partial_message;
6925 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6926 property_note_select = /* partial */ 2;
6927 available_here_select_kind = /* partial */ 3;
6928 break;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006929
6930 case AR_Available:
6931 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00006932 }
6933
Manman Renc7890fe2016-03-16 18:50:49 +00006934 CharSourceRange UseRange;
6935 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006936 if (K == AR_Deprecated) {
Manman Renc7890fe2016-03-16 18:50:49 +00006937 if (auto attr = D->getAttr<DeprecatedAttr>())
6938 Replacement = attr->getReplacement();
Manman Ren45b1ab12016-05-06 19:57:16 +00006939 if (auto attr = getAttrForPlatform(S.Context, D))
Manman Ren75bc6762016-03-21 17:30:55 +00006940 Replacement = attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00006941
6942 if (!Replacement.empty())
6943 UseRange =
6944 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6945 }
6946
Aaron Ballmanfb237522014-10-15 15:37:51 +00006947 if (!Message.empty()) {
Manman Renc7890fe2016-03-16 18:50:49 +00006948 S.Diag(Loc, diag_message) << D << Message
6949 << (UseRange.isValid() ?
6950 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006951 if (ObjCProperty)
6952 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6953 << ObjCProperty->getDeclName() << property_note_select;
6954 } else if (!UnknownObjCClass) {
Manman Renc7890fe2016-03-16 18:50:49 +00006955 S.Diag(Loc, diag) << D
6956 << (UseRange.isValid() ?
6957 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006958 if (ObjCProperty)
6959 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6960 << ObjCProperty->getDeclName() << property_note_select;
6961 } else {
Manman Renc7890fe2016-03-16 18:50:49 +00006962 S.Diag(Loc, diag_fwdclass_message) << D
6963 << (UseRange.isValid() ?
6964 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006965 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6966 }
6967
Manman Ren45b1ab12016-05-06 19:57:16 +00006968 // The declaration can have multiple availability attributes, we are looking
6969 // at one of them.
6970 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6971 if (A && A->isInherited()) {
6972 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6973 Redecl = Redecl->getPreviousDecl()) {
6974 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6975 Redecl);
6976 if (AForRedecl && !AForRedecl->isInherited()) {
6977 // If D is a declaration with inherited attributes, the note should
6978 // point to the declaration with actual attributes.
6979 S.Diag(Redecl->getLocation(), diag_available_here) << D
6980 << available_here_select_kind;
6981 break;
6982 }
6983 }
6984 }
6985 else
Erich Keanea32910d2017-03-23 18:51:54 +00006986 S.Diag(NoteLocation, diag_available_here)
Manman Ren45b1ab12016-05-06 19:57:16 +00006987 << D << available_here_select_kind;
6988
Erik Pilkington796a3e22016-08-05 22:59:03 +00006989 if (K == AR_NotYetIntroduced)
Nico Weber0055a192015-03-19 19:18:22 +00006990 S.Diag(Loc, diag::note_partial_availability_silence) << D;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006991}
6992
6993static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6994 Decl *Ctx) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00006995 assert(DD.Kind == DelayedDiagnostic::Availability &&
6996 "Expected an availability diagnostic here");
6997
Aaron Ballmanfb237522014-10-15 15:37:51 +00006998 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00006999 DoEmitAvailabilityWarning(
Erik Pilkingtona8003972016-10-28 21:39:27 +00007000 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
7001 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
7002 DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00007003}
7004
John McCall2ec85372012-05-07 06:16:41 +00007005void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7006 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00007007 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00007008 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00007009
John McCall2ec85372012-05-07 06:16:41 +00007010 // When delaying diagnostics to run in the context of a parsed
7011 // declaration, we only want to actually emit anything if parsing
7012 // succeeds.
7013 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00007014
John McCall2ec85372012-05-07 06:16:41 +00007015 // We emit all the active diagnostics in this pool or any of its
7016 // parents. In general, we'll get one pool for the decl spec
7017 // and a child pool for each declarator; in a decl group like:
7018 // deprecated_typedef foo, *bar, baz();
7019 // only the declarator pops will be passed decls. This is correct;
7020 // we really do need to consider delayed diagnostics from the decl spec
7021 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00007022 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00007023 do {
John McCall6347b682012-05-07 06:16:58 +00007024 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00007025 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7026 // This const_cast is a bit lame. Really, Triggered should be mutable.
7027 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00007028 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00007029 continue;
7030
John McCallc1465822011-02-14 07:13:47 +00007031 switch (diag.Kind) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007032 case DelayedDiagnostic::Availability:
Ted Kremenekb79ee572013-12-18 23:30:06 +00007033 // Don't bother giving deprecation/unavailable diagnostics if
7034 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00007035 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00007036 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00007037 break;
7038
7039 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00007040 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00007041 break;
John McCall31168b02011-06-15 23:02:42 +00007042
7043 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00007044 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00007045 break;
John McCall86121512010-01-27 03:50:35 +00007046 }
7047 }
John McCall2ec85372012-05-07 06:16:41 +00007048 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00007049}
7050
John McCall6347b682012-05-07 06:16:58 +00007051/// Given a set of delayed diagnostics, re-emit them as if they had
7052/// been delayed in the current context instead of in the given pool.
7053/// Essentially, this just moves them to the current pool.
7054void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7055 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7056 assert(curPool && "re-emitting in undelayed context not supported");
7057 curPool->steal(pool);
7058}
7059
Erik Pilkington796a3e22016-08-05 22:59:03 +00007060void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
Ted Kremenekb79ee572013-12-18 23:30:06 +00007061 NamedDecl *D, StringRef Message,
7062 SourceLocation Loc,
7063 const ObjCInterfaceDecl *UnknownObjCClass,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +00007064 const ObjCPropertyDecl *ObjCProperty,
7065 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00007066 // Delay if we're currently parsing a declaration.
Erik Pilkingtona8003972016-10-28 21:39:27 +00007067 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
Nico Weber462fd1e2015-01-07 23:50:05 +00007068 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
Erik Pilkington796a3e22016-08-05 22:59:03 +00007069 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
Nico Weber462fd1e2015-01-07 23:50:05 +00007070 ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00007071 return;
7072 }
7073
Ted Kremenekb79ee572013-12-18 23:30:06 +00007074 Decl *Ctx = cast<Decl>(getCurLexicalContext());
Erik Pilkington796a3e22016-08-05 22:59:03 +00007075 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
Nico Weber0055a192015-03-19 19:18:22 +00007076 ObjCProperty, ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00007077}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00007078
Erik Pilkington5cd57172016-08-16 17:44:11 +00007079namespace {
7080
7081/// \brief This class implements -Wunguarded-availability.
7082///
7083/// This is done with a traversal of the AST of a function that makes reference
7084/// to a partially available declaration. Whenever we encounter an \c if of the
7085/// form: \c if(@available(...)), we use the version from the condition to visit
7086/// the then statement.
7087class DiagnoseUnguardedAvailability
7088 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7089 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7090
7091 Sema &SemaRef;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007092 Decl *Ctx;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007093
7094 /// Stack of potentially nested 'if (@available(...))'s.
7095 SmallVector<VersionTuple, 8> AvailabilityStack;
7096
7097 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7098
7099public:
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007100 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7101 : SemaRef(SemaRef), Ctx(Ctx) {
7102 AvailabilityStack.push_back(
7103 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007104 }
7105
7106 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7107
7108 bool TraverseIfStmt(IfStmt *If);
7109
7110 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7111 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7112 DiagnoseDeclAvailability(
7113 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7114 return true;
7115 }
7116
7117 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7118 DiagnoseDeclAvailability(DRE->getDecl(),
7119 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7120 return true;
7121 }
7122
7123 bool VisitMemberExpr(MemberExpr *ME) {
7124 DiagnoseDeclAvailability(ME->getMemberDecl(),
7125 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7126 return true;
7127 }
7128
7129 bool VisitTypeLoc(TypeLoc Ty);
7130};
7131
7132void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7133 NamedDecl *D, SourceRange Range) {
7134
7135 VersionTuple ContextVersion = AvailabilityStack.back();
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007136 if (AvailabilityResult Result =
7137 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
Erik Pilkington5cd57172016-08-16 17:44:11 +00007138 // All other diagnostic kinds have already been handled in
7139 // DiagnoseAvailabilityOfDecl.
7140 if (Result != AR_NotYetIntroduced)
7141 return;
7142
7143 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7144 VersionTuple Introduced = AA->getIntroduced();
7145
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007146 if (ContextVersion >= Introduced)
7147 return;
7148
7149 // If the context of this function is less available than D, we should not
7150 // emit a diagnostic.
7151 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7152 return;
7153
Erik Pilkington5cd57172016-08-16 17:44:11 +00007154 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7155 << Range << D
7156 << AvailabilityAttr::getPrettyPlatformName(
7157 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7158 << Introduced.getAsString();
7159
7160 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7161 << D << /* partial */ 3;
7162
7163 // FIXME: Replace this with a fixit diagnostic.
7164 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7165 << Range << D;
7166 }
7167}
7168
7169bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7170 const Type *TyPtr = Ty.getTypePtr();
7171 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7172
7173 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7174 TagDecl *TD = TT->getDecl();
7175 DiagnoseDeclAvailability(TD, Range);
7176
7177 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7178 TypedefNameDecl *D = TD->getDecl();
7179 DiagnoseDeclAvailability(D, Range);
7180
7181 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7182 if (NamedDecl *D = ObjCO->getInterface())
7183 DiagnoseDeclAvailability(D, Range);
7184 }
7185
7186 return true;
7187}
7188
7189bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7190 VersionTuple CondVersion;
7191 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7192 CondVersion = E->getVersion();
7193
7194 // If we're using the '*' case here or if this check is redundant, then we
7195 // use the enclosing version to check both branches.
7196 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7197 return Base::TraverseStmt(If->getThen()) &&
7198 Base::TraverseStmt(If->getElse());
7199 } else {
7200 // This isn't an availability checking 'if', we can just continue.
7201 return Base::TraverseIfStmt(If);
7202 }
7203
7204 AvailabilityStack.push_back(CondVersion);
7205 bool ShouldContinue = TraverseStmt(If->getThen());
7206 AvailabilityStack.pop_back();
7207
7208 return ShouldContinue && TraverseStmt(If->getElse());
7209}
7210
7211} // end anonymous namespace
7212
7213void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7214 Stmt *Body = nullptr;
7215
7216 if (auto *FD = D->getAsFunction()) {
7217 // FIXME: We only examine the pattern decl for availability violations now,
7218 // but we should also examine instantiated templates.
7219 if (FD->isTemplateInstantiation())
7220 return;
7221
7222 Body = FD->getBody();
7223 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7224 Body = MD->getBody();
7225
7226 assert(Body && "Need a body here!");
7227
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007228 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007229}